Source for file WebCommon.php

Documentation is available at WebCommon.php

  1. <?php
  2. /**
  3.  *
  4.  * WebCommon.php
  5.  *
  6.  * Long description for file:
  7.  * Class of common objects/functions for the WebGUI
  8.  * see also the 'Common' Class which this extends
  9.  *
  10.  * @package     FreeNAC
  11.  * @author      FreeNAC Core Team
  12.  * @copyright   2008 FreeNAC
  13.  * @license     http://www.gnu.org/copyleft/gpl.html   GNU Public License Version 3
  14.  * @version     SVN: $Id
  15.  * @link        http://freenac.net
  16.  *
  17.  */
  18. class WebCommon extends Common 
  19. {
  20.   // see also Variables inherited from Common
  21.   protected $calling_script$calling_href$module$table;   
  22.  
  23.   function __construct($show_header=true$debuglevel=1)
  24.   {
  25.     parent::__construct();
  26.     $this->calling_script=basename($_SERVER['SCRIPT_FILENAME']);   // TBD: clean unneeded, trust apache?
  27.     if (isset($_SESSION['caller'])) {
  28.       $this->calling_href=$_SESSION['caller'];    // TBD: needed? same as calling_script?
  29.     }
  30.     $this->module='WebCommon';
  31.     $this->logger->setDebugLevel($debuglevel);  // 3 for max debugging
  32.     $this->remote_host=validate_webinput($_SERVER['REMOTE_ADDR']);
  33.  
  34.     if (function_exists('mysqli_connect')) {
  35.       throw new DatabaseErrorException("PHP has not been compiled with mysqli support");
  36.     }
  37.  
  38.     if ($show_header===true// Show Webpage start, is the constructor the right place?
  39.       echo $this->print_header();  
  40.   }
  41.  
  42.   /**
  43.    * Add the class name and uid to debug messages
  44.    */
  45.   public function debug($msg$level=1
  46.   {
  47.     if (isset($_SESSION['uid'])) {
  48.        $this->logger->debug("uid={$_SESSION['uid']} "  .get_class($this." " .$msg$level);
  49.     else {
  50.        $this->logger->debug(get_class($this." " .$msg$level);
  51.     }
  52.   }
  53.  
  54.   public function logit($msg
  55.   {
  56.     if (isset($_SESSION['uid'])) {
  57.        $this->logger->logit("uid={$_SESSION['uid']} "  .get_class($this." " .$msg);
  58.     else {
  59.        $this->logger->logit(get_class($this." " .$msg);
  60.     }
  61.   }
  62.  
  63.  
  64.  
  65.   public function loggui($msg$who=0$priority='info')
  66.   {
  67.     $conn=$this->getConnection();     //  make sure we have a DB connection
  68.  
  69.     if ( (isset($_SESSION['uid'])) && ($who===0) ) {
  70.       $who=$_SESSION['uid'];
  71.     }
  72.     $q="insert into guilog (who, host, datetime, priority, what)
  73.          values ('$who', '$this->remote_host', NOW(), '$priority', 'Web: $msg')";
  74.       $this->debug($q3);
  75.       $res $conn->query($q);
  76.       if ($res === FALSE)
  77.         throw new DatabaseInsertException("Unable to insert guilog entry:: " .$conn->error);
  78.   }
  79.  
  80.  
  81.   public function print_logo()
  82.   {
  83.     global $head_left1;
  84.     return $head_left1 "\n";
  85.   }
  86.   public function print_headerSmall($print_links=true)
  87.   {
  88.     $this->print_header($print_links);
  89.   }
  90.  
  91.   public function print_header($print_links=true)
  92.   {
  93.     global $header1;
  94.     $ret='';
  95.  
  96.     if (defined('HEADER')){   // already displayed?
  97.       $this->debug('print_header: HEADER already true'3);
  98.  
  99.     else {
  100.       if (isset($_SESSION['nac_rights']|| ($_SESSION['nac_rights']=='')) {
  101.         $this->debug("print_header() nac_rights not set: ignore, do not show menu/headers"2);
  102.         return;
  103.       }
  104.  
  105.       define('HEADER',true)// The header is out
  106.       $ret.= $header1 ."\n";
  107.       #$ret.= $_SESSION['nac_rights'];
  108.       $ret.= $this->print_logo(."\n";
  109.       $ret.= main_menu();     // webfuncs.inc
  110.       $this->debug('print_header: done'3);
  111.     }
  112.     return $ret;
  113.   }
  114.  
  115.  
  116.   public function print_headerMin()
  117.   {
  118.     global $header1;
  119.  
  120.     if (defined('HEADER')){   // already displayed?
  121.       $this->debug('print_headerMin: HEADER already true',2);
  122.     #} 
  123.     #else {
  124.       return $header1;
  125.     }
  126.   }
  127.  
  128.   public function print_header1()
  129.   {
  130.     global $header1;
  131.     $ret$header1 ."\n";
  132.     $ret.= $this->print_logo(."\n";
  133.     return $ret;
  134.   }
  135.  
  136.  
  137.   public function print_footer($print_links=true)
  138.   {
  139.     global $sql_auth$drupal_auth;
  140.     $text='';
  141.  
  142.     if (defined('FOOTER')){   // already displayed?
  143.       $this->debug('print_footer: FOOTER already true',2);
  144.     
  145.     else {
  146.       if (!isset ($_SESSION['login_data'])) {
  147.         $userdata=">> Not logged in <<";
  148.         $text=<<<EOF
  149.   </tr> </table> 
  150.   </body> </html>
  151. EOF;
  152.       }
  153.       else {
  154.         $userdata="<br>Logged in as: " .$_SESSION['login_data']
  155.           ." (" .$_SESSION['nac_rights_text'.")";
  156.  
  157.         if (($sql_auth===true|| ($drupal_auth===true)) {
  158.           $logout_button="<li><a href='./logout.php'>Log out</a></li>";
  159.         }
  160.         else {
  161.           $logout_button='';
  162.         }
  163.  
  164.         $text=<<<EOF
  165.   <div id='user_footer'><p>$userdata</p></div>
  166.   <a href='./logout.php'>Log out</a>
  167. EOF;
  168.         if ($print_links===true{
  169. // Stop for now, not needed with the new menus?
  170. #          $text.=<<<EOF
  171. #  <div id="headermenue">
  172. #  <ul>
  173. #     <li><A HREF='javascript:javascript:history.go(-1)'< Back</A></li>
  174. #     <li><a href="./index.php">Main Menu</a></li>
  175. #     $logout_button
  176. #  </ul> </div>
  177. #EOF;
  178.         }
  179.         $text.=<<<EOF
  180.   </tr> </table> </body> </html>
  181. EOF;
  182.  
  183.       }
  184.       return $text;
  185.  
  186.     }
  187.   }
  188.  
  189.  
  190.   /* no menu on the botton */
  191.   public function print_footer_empty()
  192.   {
  193.     if (defined('FOOTER')){   // already displayed?
  194.       $this->debug('print_footer: FOOTER already true',2);
  195.     
  196.     else {
  197.       $ret="</table></body></html>";
  198.       define('FOOTER',true);
  199.       return $ret;
  200.     }
  201.   }
  202.  
  203.  
  204.  
  205.   public function print_title($title)
  206.   {
  207.     $ret$this->print_header();
  208.     $ret.= "<div id='GuiList1Title'>{$title}</div>";
  209.     $this->debug("print_title($title)3);
  210.     return $ret;
  211.   }
  212.  
  213.  
  214.   /**
  215.    * Delete a record from the WebGUI
  216.    */
  217.   public function Delete($table$id)
  218.   {
  219.     global $_SESSION$_REQUEST;
  220.  
  221.     if ($_SESSION['nac_rights']<2)
  222.       throw new InsufficientRightsException($_SESSION['nac_rights']);
  223.     if $id===)
  224.       throw new InvalidWebInputException("Delete() invalid index: zero");
  225.     if strlen($table)===)
  226.       throw new InvalidWebInputException("Delete() no table name.");
  227.     
  228.     $ret $this->print_title("Delete {$this->module} record");
  229.  
  230.     #var_dump($_REQUEST);
  231.     $conn=$this->getConnection();     //  make sure we have a DB connection
  232.     $this->debug("Delete() index {$id}", 3);
  233.  
  234.     $q="DELETE FROM {$table} WHERE id='{$id}' LIMIT 1";     // only this record
  235.       $this->debug($q3);
  236.       $res $conn->query($q);
  237.       if ($res === FALSE)
  238.         throw new DatabaseErrorException($q ." :: " .$conn->error);
  239.  
  240.     // Inform the user that is was OK
  241.       $txt=<<<TXT
  242. <p class='UpdateMsgOK'>Delete of entry with index=$id Successful</p>
  243.  <br><p>Go back to the <a href="{$this->calling_href}">{$this->module} list</a></p>
  244. </div>
  245. TXT;
  246.     $ret.= $txt;
  247.     $this->logit("Deleted {$this->module}: table=$table, Id={$id}");
  248.     $this->loggui("Deleted {$this->module}: table=$table, Id={$id}");
  249.     return $ret;
  250.   }
  251.  
  252.  
  253. // ------------ functions common to the FreeNAC DB scheam, to be reused where possible in the
  254. // ------------ Web GUI
  255. /**
  256.  * Get a Vlan name, given its index number
  257.  */
  258. public function get_vlan($s)
  259. {
  260.    $conn=$this->getConnection();     //  make sure we have a DB connection
  261.    $ret='';
  262.    $q="select default_name from vlan where id='$s'";
  263.      $res = $conn->query($q);
  264.      if ($res === FALSE)
  265.        throw new DatabaseErrorException($q .'; ' .$conn->error);
  266.  
  267.      while (($row $res->fetch_assoc()) !== NULL{
  268.          $ret=$row['default_name'];
  269.      }
  270.    return($ret);
  271. }
  272.  
  273.  
  274. /**
  275.  * Look up what systems were seen on a port in the last $conf->web_lastdays days
  276.  */
  277. public function get_hosts($port) 
  278. {
  279.   $conn=$this->getConnection();     //  make sure we have a DB connection
  280.   $ret='';
  281. $q=<<<TXT
  282. SELECT s.name, 
  283.   s.LastSeen, CONCAT(users.Surname, ' ',users.GivenName, ', ',users.Department) as owner 
  284.   FROM systems as s 
  285.   LEFT JOIN users ON users.id = s.uid 
  286.   WHERE LastPort='$port'  AND (TO_DAYS(LastSeen)>=TO_DAYS(CURDATE())-{$this->conf->web_lastdays}
  287. TXT;
  288.      //$this->debug($q ,3);
  289.      $res = $conn->query($q);
  290.      if ($res === FALSE)
  291.        throw new DatabaseErrorException($q .'; ' .$conn->error);
  292.  
  293.      while (($row $res->fetch_assoc()) !== NULL{
  294.          $ret.=$row['name'] .' (' .$row['owner'] .'), ' .$row['LastSeen'] .'<br>';
  295.      }
  296.    //$this->debug($ret ,3);
  297.    return($ret);
  298. }
  299.  
  300.  
  301. /**
  302.  * Look up the first switch or patch location ID for a port
  303.  */
  304. public function get_locationid($port) 
  305. {
  306.   $conn=$this->getConnection();     //  make sure we have a DB connection
  307.   $query "SELECT patchloc.id as patchlocid, switchloc.id as switchlocid FROM port
  308.                   LEFT JOIN patchcable ON patchcable.port = port.id
  309.                    LEFT JOIN location patchloc ON patchloc.id = patchcable.office
  310.                   LEFT JOIN switch ON switch.id = port.switch
  311.                    LEFT JOIN location switchloc ON switchloc.id = switch.location WHERE port.id = '$port';";
  312.   $res = $conn->query($q);
  313.   if ($res === FALSE)
  314.        throw new DatabaseErrorException($q .'; ' .$conn->error);
  315.  
  316.   while (($row $res->fetch_assoc()) !== NULL{
  317.  
  318.        if (($row['patchlocid'] = '') || (!$row['patchlocid'])) {
  319.          return($row['switchlocid']);
  320.        } 
  321.        else {
  322.          return($row['patchlocid']);
  323.        }
  324.   }
  325. }
  326.  
  327.  
  328. /**
  329.  * Lookup the patch outlet name
  330.  */
  331. public function get_patch($port)
  332. {
  333.   $conn=$this->getConnection()
  334.   $q "SELECT outlet,location.name as location FROM patchcable LEFT JOIN location ON location.id = patchcable.office WHERE port='$port'";
  335.   $res = $conn->query($q);
  336.   if ($res === FALSE)
  337.        throw new DatabaseErrorException($q .'; ' .$conn->error);
  338.  
  339.   while (($row $res->fetch_assoc()) !== NULL{
  340.     return($row['outlet'] ." (" .$row['location'] .")");
  341.   } 
  342.   return(FALSE);
  343. }
  344.  
  345.  
  346. /**
  347.  * Lookup the patch outlet name
  348.  */
  349. public function get_dose($port)
  350. {
  351.   $conn=$this->getConnection()
  352.   $q "SELECT outlet FROM patchcable WHERE port='$port'";
  353.   $res = $conn->query($q);
  354.   if ($res === FALSE)
  355.        throw new DatabaseErrorException($q .'; ' .$conn->error);
  356.  
  357.   while (($row $res->fetch_assoc()) !== NULL{
  358.     return($row['outlet']);
  359.   } 
  360.   return(FALSE);
  361. }
  362.  
  363.  
  364. /**
  365.  * Print a HTML lookup list of switches
  366.  */
  367. public function print_switch_sel($sw)
  368. {
  369.   $conn=$this->getConnection()
  370.   $q "SELECT DISTINCT(switch.id) as id, switch.name as name, switch.ip as ip, CONCAT(building.name,' ',location.name) as location
  371.  FROM systems
  372.  LEFT JOIN port ON port.id = systems.LastPort
  373.  LEFT JOIN switch ON port.switch = switch.id
  374.  LEFT JOIN location ON location.id = switch.location
  375.   LEFT JOIN building ON building.id = location.building_id
  376. WHERE  (TO_DAYS(LastSeen)>=TO_DAYS(CURDATE())-" .$this->conf->web_lastdays .") AND port.switch != ''
  377. ORDER BY switch.name;";
  378.  
  379.   $this->debug($q3);
  380.   $res $conn->query($q);
  381.   $html="<select name=sw>\n";
  382.   if ($res === FALSE)
  383.        throw new DatabaseErrorException($q .'; ' .$conn->error);
  384.  
  385.   while (($row $res->fetch_assoc()) !== NULL{
  386.     $html .= '<option value="' .$row['id'] .'"';
  387.     if ($sw == $row['id']) {
  388.       $html .= ' selected ';
  389.     };
  390.     $html .='>'.$row['name'].' ('.$row['location'].")</option>\n";
  391.   };
  392.   $html .= "</select>\n";
  393.   return($html);
  394. }
  395.  
  396. /* not used? */
  397. function print_dot_sel() 
  398. {
  399.   $types = array('dot','neato','fdp','twopi','circo');
  400.   $html = "<select name=\"dottype\">\n";
  401.  
  402.   foreach ($types as $mytype) {
  403.     $html .= '<option value="'.$mytype.'"';
  404.     if ($this->conf->web_dotcmd == $mytype{
  405.       $html .= ' selected ';
  406.     };
  407.     $html .= ">$mytype</option>\n";
  408.   };
  409.   $html .= "</select>\n";
  410.   return($html);
  411. }
  412.  
  413.  
  414.  
  415.  
  416. /**
  417.  * Get port comment
  418.  */
  419. public function get_port_comment($port) 
  420. {
  421.   $conn=$this->getConnection();     //  make sure we have a DB connection
  422.   // TBD: could really look up the port/switch name for nicer logging?
  423.   if (isset($port&& is_numeric($port&& $port>{
  424.  
  425.     $this->debug("get_port_comment $port", 1);
  426.     $q="SELECT comment from port WHERE id=$port LIMIT 1";
  427.       $this->debug($q3);
  428.       $res $conn->query($q);
  429.     if ($res === FALSE)
  430.       throw new DatabaseErrorException($conn->error);
  431.     while (($row $res->fetch_assoc()) !== NULL{
  432.       return ($row['comment']);
  433.     }
  434.  
  435.   } else {
  436.     $this->logit("get_port_comment invalid port index=<$port>");
  437.     // return nothing
  438.   }
  439. }
  440.  
  441.  
  442. /**
  443.  * Set the restart flag for a port
  444.  */
  445. public function port_restart_request($port) 
  446. {
  447.   $conn=$this->getConnection();     //  make sure we have a DB connection
  448.  
  449.   // TBD: could really look up the port/switch name for nicer logging?
  450.  
  451.   if (isset($port&& is_numeric($port&& $port>{
  452.  
  453.     $this->debug("port_restart_request $port", 1);
  454.     $this->loggui("Port index $port restart requested");
  455.     $q="UPDATE port set restart_now=1 WHERE id=$port LIMIT 1";
  456.       $this->debug($q3);
  457.       $res $conn->query($q);
  458.     if ($res === FALSE)
  459.       throw new DatabaseErrorException($conn->error);
  460.     return true;
  461.  
  462.   } else {
  463.     $this->logit("port_restart_request invalid port index=<$port>");
  464.     return false;
  465.   }
  466. }
  467.  
  468. /**
  469.  * Delete a port
  470.  */
  471. public function port_delete($port)
  472. {
  473.   $conn=$this->getConnection();     //  make sure we have a DB connection
  474.  
  475.   // TBD: could really look up the port/switch name for nicer logging?
  476.   if (isset($port&& is_numeric($port&& $port>{
  477.  
  478.     $this->debug("port_delete $port", 1);
  479.     $q="DELETE from port WHERE id=$port LIMIT 1";
  480.       $this->debug($q3);
  481.       $res $conn->query($q);
  482.     if ($res === FALSE)
  483.       throw new DatabaseErrorException($conn->error);
  484.  
  485.     $this->loggui("Port $port deleted ");
  486.     $this->logit("Port $port deleted ");
  487.   } else {
  488.     $this->logit("port_delete invalid port=$port");
  489.   }
  490. }
  491.  
  492.  
  493. /**
  494.  * Look up the first switch or patch location for a port
  495.  */
  496. public function get_location($port) 
  497. {
  498.   $conn=$this->getConnection();     //  make sure we have a DB connection
  499. $q=<<<TXT
  500. SELECT patchloc.id as patchlocid, CONCAT(patchbd.name,' ',patchloc.name) as patchloc,
  501.    switchloc.id as switchlocid, CONCAT(switchbd.name,' ',switchloc.name) as switchloc
  502.    FROM port
  503.    LEFT JOIN patchcable ON patchcable.port = port.id
  504.    LEFT JOIN location patchloc ON patchloc.id = patchcable.office
  505.    LEFT JOIN building as patchbd ON patchbd.id = patchloc.building_id
  506.    LEFT JOIN switch ON switch.id = port.switch
  507.    LEFT JOIN location switchloc ON switchloc.id = switch.location
  508.    LEFT JOIN building as switchbd ON switchbd.id = switchloc.building_id
  509.    WHERE port.id = '$port'
  510. TXT;
  511.  
  512.   $res $conn->query($q);
  513.   if ($res === FALSE)
  514.        throw new DatabaseErrorException($q .'; ' .$conn->error);
  515.  
  516.   while (($row $res->fetch_assoc()) !== NULL{
  517.  
  518.        if (($row['patchloc'] = '') || (!$row['patchloc'])) {
  519.          return($row['switchloc']);
  520.        } 
  521.        else {
  522.          return($row['patchloc']);
  523.        }
  524.   }
  525. }
  526.  
  527. public function strip_datversion($long_version) 
  528. {
  529.      $list=explode('.',$long_version);
  530.      $short_version = $list[2];
  531.      return($short_version);
  532. }
  533.  
  534.  
  535. public function print_dat_stats($q) 
  536. {
  537.   $conn=$this->getConnection();     //  make sure we have a DB connection
  538.   $readme_url='http://vil.nai.com/vil/DATReadme.aspx';
  539.   $ret='';
  540.   $unknown='';
  541.   $total=0;
  542.   $res $conn->query($q);
  543.   if ($res === FALSE)
  544.        throw new DatabaseErrorException($q .'; ' .$conn->error);
  545.  
  546.   $ret.= "<table cellspacing=0 cellpadding=5 border=1>\n";
  547.   $ret.= "<tr><th><a href=\"$readme_url\">DAT Version</a><th>count";
  548.  
  549.      while (($row&