Source for file webfuncs.inc

Documentation is available at webfuncs.inc

  1. <?php
  2. /**
  3.  * webfuncs.inc
  4.  *
  5.  * Long description for file:
  6.  * common PHP functions used by several web GUI scripts
  7.  *
  8.  * @package     FreeNAC
  9.  * @author      Sean Boran (FreeNAC Core Team)
  10.  * @copyright   2008 FreeNAC
  11.  * @license     http://www.gnu.org/copyleft/gpl.html   GNU Public License Version 3
  12.  * @version     SVN: $Id: webfuncs.inc,v 1.1 2008/02/22 13:04:57 root Exp root $
  13.  * @link        http://freenac.net
  14.  *
  15.  */
  16.  
  17. chdir(dirname(__FILE__));
  18.  
  19. require_once('../bin/funcs.inc.php');   // include pat set here too
  20. require_once('../etc/config.inc');
  21. require_once "Logger.php";    // in the nac lib
  22. $logger=Logger::getInstance();
  23.   #$logger->setDebugLevel(3);
  24.   #$logger->debug("webfuncs.inc: $dbhost, $dbuser, $dbname.", 3); //TBD
  25.   #print_r($dbhost);
  26.  
  27. require_once "web1.config.inc";     // TBD: move to /opt/nac/config.inc . note the absolute path!
  28. require_once "exceptions.inc";
  29.  
  30. define('UA_SALT''web1.376654seed');
  31.  
  32.  
  33. #### Functions ####
  34. ##################
  35.  
  36. function ismemberof($username,$group)
  37. {
  38.    ## This function says whether a username in the form user@domain.com is belongs to the AD group specified
  39.    global $ad_server,$ad_user,$ad_password,$ad_port,$ad_base;
  40.    $counter=0;
  41.    $ad=ldap_connect($ad_server,$ad_port);
  42.    if ($ad)
  43.    {
  44.       if (ldap_bind($ad,$ad_user,$ad_password))
  45.       {
  46.          if ($ad_port==3268)         ## Global catalog is more flexible. 
  47.                                      ## In the event that we have more than one domain, 
  48.                                      ## the username gives us the domain name 
  49.                                      ## where we should look at.
  50.          {
  51.             ## Build the DN out of the username
  52.             $dn=explode('@',$username);
  53.             if (empty($dn))
  54.                return false;
  55.             $temp_dn=str_replace('.',',DC=',$dn[1]);
  56.             $dn='DC='.$temp_dn;
  57.          }
  58.          else
  59.             ## We are using a domain-level lookup, so in this case we need to know where the user information is 
  60.             $dn=$ad_base;
  61.          $attributes=array('memberOf');  ## We are interested only in the memberOf attribute
  62.          $filter='(&(userPrincipalName='.$username.')(objectClass=person))'## Retrieve info only for this specific username
  63.          $result=ldap_search($ad,$dn,$filter,$attributes);   ## Do the search
  64.          if ($result)
  65.          {
  66.             $entries=ldap_get_entries($ad,$result);
  67.             if ($entries['count']==1)    ## We should have only one result
  68.             {
  69.                $groups=$entries[0]['memberof']['count'];
  70.                if ($groups>0)
  71.                {
  72.                   for ($i=0;$i<$groups;$i++)
  73.                   {
  74.                      if (strcasecmp($entries[0]['memberof'][$i],$group== 0)
  75.                         $counter++;      ## Username is a member of the group
  76.                   }
  77.                }
  78.             }
  79.          }
  80.       }
  81.       else
  82.       {
  83.          echo 'Unable to bind to LDAP server with given credentials';
  84.       }
  85.       ldap_close($ad);
  86.    }
  87.    else
  88.    {
  89.       echo 'Unable to connect to LDAP server';
  90.    }
  91.    if ($counter>0)
  92.       return true;
  93.    else
  94.       return false;
  95. }
  96.  
  97. function user_rights($username)
  98. #This function outputs the rights associated to the username
  99. {
  100.    global $dbuser,$dbpass;
  101.    db_connect($dbuser,$dbpass);
  102.    $query='select * from guirights order by code desc;';
  103.    $res=mysql_query($query);
  104.    $rights=-1;
  105.    while ($result=mysql_fetch_array($res,MYSQL_ASSOC))
  106.    {
  107.       if empty($result['ad_group']))
  108.          if (ismemberof($username,$result['ad_group']))
  109.          {
  110.             $rights<$result['code'$rights=$result['code'$result['code']=$rights;
  111.             break;
  112.          }
  113.    }
  114.    return $rights;
  115. }
  116.  
  117. /**
  118.  * Header for each page
  119.  *
  120.  */
  121. global $head_title$head_right1$head_right2$js1;
  122. $header1=<<<TEXT
  123. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  124.      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  125.     <html xmlns="http://www.w3.org/1999/xhtml">
  126.     <head>
  127.       <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  128.       <title>{$head_title}</title>
  129.       <link href="bw.css" rel="stylesheet" type="text/css" />
  130.     </head>
  131. TEXT;
  132.  
  133. //  if (trim(document.getElementById('name').value)== \'\') {
  134. $js1=<<<TEXT
  135. <script type="text/javascript"> 
  136. // TBD: Both of these are still early prototypes,,,,
  137. //
  138. // Alert if field n on form f is less than l chars
  139. function checkLen(f,len)
  140. {
  141.   //alert(document.formadd.name.value.trim());
  142.   var myform="formadd";  // hard coded to formadd for now; f.form does not work
  143.   if (eval("document." +myform +"." +f.name +".value.trim().length") <len) {
  144.     alert('The value must contain at least ' +len +' characters');
  145.   }
  146. }
  147. function checkForm()
  148. {
  149.         var cname, cmac;
  150.         with(document.formadd) {
  151.                 cname  = name;
  152.                 cmac   = mac;
  153.         }
  154.  
  155.         if(trim(cname.value).length == 0) {
  156.                 alert('Please enter a name');
  157.                 cname.focus();
  158.                 return false;
  159.         } else if(trim(cmac.value).length == 0) {
  160.                 alert('Please enter a mac');
  161.                 cmac.focus();
  162.                 return false;
  163.         } else {
  164.                 cname.value    = trim(cname.value);
  165.                 cmac.value   = trim(cemail.value);
  166.                 return true;
  167.         }
  168. }
  169. /* Strip whitespace from the beginning and end of a string
  170. Input : a string
  171. */
  172. //function trim(str)
  173. String.prototype.trim = function()
  174. {
  175.   return this.replace(/^\s+|\s+$/g, '');
  176. }
  177. </script>
  178. TEXT;
  179.  
  180.  
  181. $header2=<<<TEXT
  182. <table class="header2" width="1000" border="0">
  183.   <tr height="80"> 
  184.     <td valign="center">{$head_left1}</td>
  185.     <td align="right">{$head_right1}<p>{$head_right2}</p> </td>
  186.   </tr>
  187.   </table>
  188.   <p/>
  189. TEXT;
  190. // TBD: why will it not take the width from table#header2_small in bw.css?
  191. $header2_small=<<<TEXT
  192. <table id="header2_small" width="500">
  193.   <tr height="80"> 
  194.     <td valign="center">{$head_left1}</td>
  195.     <td align="right">{$head_right1}<p>{$head_right2}</p> </td>
  196.   </tr>
  197. </table>
  198. TEXT;
  199.         
  200. /*
  201.  * Popup a JavaScript alert window 
  202.  */
  203. function jalert($str=''
  204. {
  205.   return "<script type='text/javascript'>alert('" .$str ."')</script>";
  206. }
  207.  
  208. // Obsolete: use WebCommon class
  209. function print_header($print_links=true){
  210.    global $header1$header2$head_right1$head_right2;    
  211.    $logger=Logger::getInstance();
  212.  
  213.    if (defined('HEADER')){   // already displayed?
  214.      $logger->debug('print_header: HEADER already true',2);
  215.  
  216.    else {
  217.      if ($print_links===false{
  218.        $logger->debug('print_header: do not print right links'3);
  219.        $head_right1='';
  220.        $head_right2='';       
  221.      }
  222.      $ret$header1 $header2;
  223.      define('HEADER',true)// The header is out
  224.      $logger->debug('print_header: done'3);
  225.      return $ret;
  226.    }
  227. }
  228.  
  229. // Obsolete: use WebCommon class
  230. function print_headerSmall(){
  231.    global $header1$header2_small;    
  232.    $logger=Logger::getInstance();
  233.  
  234.    if (defined('HEADER')){   // already displayed?
  235.      $logger->debug('print_header: HEADER already true'3);
  236.  
  237.    else {
  238.      $logger->debug('print_headerSmall() '3);
  239.      $ret$header1 $header2_small;
  240.      define('HEADER',true)// The header is out
  241.      return $ret;
  242.    }
  243. }
  244.  
  245. //
  246. // Print page footer (if not already done)
  247. // Obsolete: use WebCommon class
  248. function print_footer(){
  249.     if(!defined(FOOTER)){
  250.         $ret="</table></body></html>";
  251.         define('FOOTER',true);
  252.         return $ret;
  253.     }
  254. }
  255.  
  256. // test only, not used
  257. function report_menu()
  258. {
  259. /*
  260.      <li>Sort order: <input type="text" name="sortby" size='30' maxlength="30" /></li>
  261. */
  262.   $text=<<<EOF
  263.   <div id="reportmenu">
  264.   <ul >
  265.      <li>Max. records: <input type="text" name="sortlimit" size='10' maxlength="20" /></li>
  266.      <li>Sort order: <SELECT NAME=sortby>
  267.       <OPTION LABEL="1.5.x">Order date</OPTION>
  268.       <OPTION LABEL="1.0.x">status</OPTION>
  269.      </SELECT> </li>
  270.   </ul> </div>
  271. EOF;
  272.    return $text;
  273. }
  274.  
  275. // Obsolete, use WebCommon class
  276. function read_footer()
  277. {
  278.   if (!isset ($_SESSION['login_data'])) {
  279.     $userdata=">> Not logged in <<";
  280.     $text=<<<EOF
  281.   <div align='center'>
  282.   <font class=user_footer>$userdata</font></p>
  283.   </div>
  284.   </tr> </table> </body> </html>
  285. EOF;
  286.   
  287.   else {
  288.     $userdata="Logged in as: " .$_SESSION['login_data']
  289.       ." (" .$_SESSION['nac_rights_text'.")";
  290.  
  291.     #if (($_SESSION['sql_auth']===true) || ($_SESSION['drupal_auth']===true)) {
  292.     #  $logout_button="<li><a href='./logout.php'>Log out</a></li>";
  293.     #}
  294.     #else {
  295.       $logout_button='';
  296.     #}
  297.  
  298.     $text=<<<EOF
  299.   <div align='center'>
  300.   <font class=user_footer>$userdata</font></p>
  301.   </div>
  302.   <div id="headermenue">
  303.   <ul>
  304.      <li><a href="./index.php">Main Menu</a></li>    
  305.      $logout_button
  306.   </ul> </div>
  307.   </tr> </table> </body> </html>
  308. EOF;
  309.      #<li><a href="./ChooseAccount.php">Change Account</a></li>
  310.   }
  311.   return $text;
  312. }
  313.  
  314. // Obsolete, use WebCommon class
  315. function read_footer2()
  316. {
  317.   if (!isset ($_SESSION['login_data'])) {
  318.     $userdata=">> Not logged in <<";
  319.     $text=<<<EOF
  320.   <p>  </p>
  321.   <hr size='500'><p>  </p>
  322.   <p ALIGN=CENTER class=text16> 
  323.   <font class=user_footer>$userdata</font></p>
  324.   </td>
  325.    </tr> </table> </body> </html>
  326. EOF;
  327.   else {
  328.     $userdata="Welcome " .$_SESSION['login_data'];
  329.     $text=<<<EOF
  330.   <p>  </p>
  331.   <hr size='500'><p>  </p>
  332.   <p ALIGN=CENTER class=text16> 
  333.   <a href="./index.php">Main Menu</a> &nbsp&nbsp|&nbsp&nbsp 
  334.   <a href='./logout.php'>Log out</a>  &nbsp&nbsp|&nbsp&nbsp
  335.   <font class=user_footer>$userdata</font></p>
  336.   </td>
  337.    </tr> </table> </body> </html>
  338. EOF;
  339.   #<a href="./ChooseAccount.php">Change Account</a> &nbsp&nbsp|&nbsp&nbsp 
  340.   }
  341.   return $text;
  342. }
  343.  
  344. function user_tooltip($username{
  345.   global $readuser,$readpass;
  346.   db_connect($readuser,$readpass);
  347.   $query "SELECT * FROM users WHERE username = '$username'; ";
  348.   $res mysql_query($query)  or die ("Unable to query MySQL");
  349.  
  350.   $user mysql_fetch_array($res);
  351.  
  352.   //$text = $user['GivenName'].' '.$user['Surname'].', '.$user['Department']." (";
  353.   $text .= $user['HouseIdentifier'].' '.$user['PhysicalDeliveryOfficeName']." / ";
  354.  
  355.   // Shorter tel number for INO
  356.   if (stristr($user['TelephoneNumber'],'31-342')) {
  357.     $user['TelephoneNumber'str_replace(' ','',substr($user['TelephoneNumber'],strlen($user['TelephoneNumber'])-7,7));
  358.   };
  359.  
  360.   $text .= $user['TelephoneNumber']" / ";
  361.   $text .= $user['Mobile'];
  362.   //."\n";
  363.  
  364.   return($text);
  365. };
  366.  
  367. //
  368. // Print the lookup results
  369. //
  370. function print_resultset($res,$server){
  371.         $ret='';
  372.         while ($row=mysql_fetch_array($res)){
  373.                 $ret.=($i%2==0)?'<tr class="light">':'<tr class="dark">';
  374.                 
  375.                 $ret.='<td><a href="'.$server['PHP_SELF'].'?action=edit&id='.$row['id'].'">';
  376.                 // if we have a name, echo the name, else just the id
  377.                 $ret.=($row['name']!=''?stripslashes($row['name']):$row['Jcard_no']);
  378.                 $ret.='</a></td>'."\n";
  379.                 $ret.='<td class="center">'.$row['Cust_part'].'</td>'."\n";                
  380.                 $ret.='<td class="center">'.$row['Print_ref'].'</td>'."\n";                
  381.                 $ret.='<td class="center">'.$row['Film_or_bags'].'</td>'."\n";
  382.                 $ret.='<td class="center">'.$row['Film_col'].'</td>'."\n";  
  383.                 $ret.='<td class="center">'.$row['Quantity'].'</td>'."\n";                                                                
  384.                 $ret.='<td class="center">'.$row['Ord_contact'].'</td>'."\n";                                                                
  385.                 $ret.='</tr>'."\n";
  386.                 $i++;
  387.         }
  388.         return $ret;
  389. }
  390.  
  391. //
  392. // validates webinput: carefully remove 'dangerous'  input
  393. // if the variable is an array recursevly call the
  394. // function for each value
  395. //
  396. function validate_webinput($value){
  397.         if (is_array($value)){
  398.                 array_map('validate_webinput',$value);
  399.         }
  400.         else {
  401.                 if (get_magic_quotes_gpc()) {  // are quotes escaped already?
  402.                         #$value = @stripslashes($value);
  403.                         $value stripslashes($value);
  404.                 }
  405.                 if (!is_numeric($value)){
  406.             // prepends backslashes to: \x00, \n, \r, \, ', " and \x1a
  407.                         #$value = @mysql_real_escape_string($value);
  408.                         #$value = mysqli_real_escape_string($value);
  409.                        $value ereg_replace('(\'|;)''\\\1'$value);  // escape ',;
  410.                 }
  411.         }
  412.         return trim($value);
  413. }
  414.  
  415. /* 
  416.  * not yet tested 
  417.  * This method takes three parameters
  418.  * 1. the string to escape, 
  419.  * 2. (optional) indicating whether any markup element characters such as < or > 
  420.  * should be escaped
  421.  * 3. (optional) indicating whether percent symbols (%) should be stripped out.
  422.  */
  423. function mega_escape_string ($in_string$in_markup FALSE$in_removePct FALSE)
  424. {
  425.   $str ereg_replace('(\')''\\\1'$in_string);  // escape '
  426.   if ($in_removePct)
  427.     $str ereg_replace('(%)''\\\1'$str);       // escape %
  428.   if ($in_markup == TRUE{
  429.     #$str = htmlspecialchars($str, ENT_NOQUOTES, 'UTF-8');
  430.     $str htmlspecialchars($strENT_NOQUOTES'ISO-8859-1');
  431.   }
  432.  
  433.   return $str;
  434. }
  435.  
  436.  
  437.  
  438.  
  439. //
  440. // retrieves all users from the databases and returns them as a hmtl dropdownlist
  441. //
  442. function get_userdropdown($selected_user{
  443.         global $rights;
  444.         if ($rights>=2)
  445.         {
  446.            $ret='<select name="username">';
  447.            $sql='SELECT id, username, surname, givenname FROM users ORDER BY surname'// Get details for all users
  448.            $res=mysql_query($sqlor die('Query failed: ' mysql_error());
  449.            if (mysql_num_rows($res)>0){
  450.                 while ($r=mysql_fetch_array($res)){
  451.                         $ret.='<option value="'.$r['id'].'" '.($r['id']==$selected_user?'selected="selected"':'').'>'.$r['surname'].' '.$r['givenname'].'</option>'."\n";
  452.                 }
  453.            }
  454.            $ret.='</select>'."\n";
  455.         }
  456.         else
  457.         {
  458.            $sql="select username from users where id='$selected_user';";
  459.            $res=mysql_query($sqlor die('Query failed: ' mysql_error());
  460.            if (mysql_num_rows($res)>0)
  461.                 while ($r=mysql_fetch_array($res))
  462.                    $ret=$r['username'];
  463.         }
  464.         return $ret;
  465. }
  466.  
  467. //
  468. // retrieves all offices from the database and returns them as a html dropdownlist
  469. //
  470. function get_officedropdown($oid){
  471.         $ret='<select name="office">';
  472.         $sql='SELECT loc.id, loc.name as office, b.name as building FROM location as loc LEFT JOIN building as b on loc.building_id=b.id ORDER BY building, office'// Get details for all offices
  473.         $res=mysql_query($sqlor die('Query failed: ' mysql_error());
  474.         if (mysql_num_rows($res)>0){
  475.                 while ($r=mysql_fetch_array($res)){
  476.                         $ret.='<option value="'.$r['id'].'" '.($r['id']==$oid?'selected="selected"':'').'>'.$r['building'].' -  '.$r['office'].'</option>'."\n";
  477.              }
  478.         }
  479.         $ret.='</select>'."\n";
  480.         return $ret;
  481. }
  482.  
  483. //
  484. // retrieves the different status and returns them as a html dropdownlist
  485. //
  486. function get_status($s)
  487. {
  488.         global $rights;
  489.         if ($rights>=2)
  490.         {
  491.            $ret='<select name="status">';
  492.            $sql='SELECT id, value FROM vstatus ORDER BY value ASC;';
  493.            $res=mysql_query($sqlor die('Query failed: ' mysql_error());
  494.            if (mysql_num_rows($res)>0){
  495.                 while ($r=mysql_fetch_array($res)){
  496.                         $ret.='<option value="'.$r['id'].'" '.($s==$r['id']?'selected="selected"':'').'>'.$r['value'].'</option>'."\n";
  497.                 }
  498.            }
  499.            $ret.='</select>'."\n";
  500.         }
  501.         else
  502.         {
  503.           $sql="select value from vstatus where id='$s';";
  504.           $res=mysql_query($sqlor die('Query failed: ' mysql_error());
  505.           if (mysql_num_rows($res)>0)
  506.                 while ($r=mysql_fetch_array($res))
  507.                    $ret=$r['value'];
  508.         }
  509.         return $ret;
  510. }
  511.  
  512.  
  513. //
  514. // creates an excel sheet and sends it to the browser
  515. // input: $result (must be a mysql query result)
  516. //
  517. function create_xls($result){
  518.         $fields mysql_num_fields($result);
  519.         // create a new workbook
  520.         $xls new Spreadsheet_Excel_Writer();
  521.  
  522.         // format head row
  523.         $head =$xls->addFormat();
  524.         $head->setBold();
  525.         $head->setAlign('center');
  526.  
  527.         // send HTTP headers
  528.         $xls->send('freenac.xls');
  529.  
  530.         // create a worksheet
  531.         $sheet =$xls->addWorksheet('FreeNAC');
  532.  
  533.         // iterate trough the result set
  534.         $r=0// row
  535.         $c=0// column
  536.         for ($c=0$c $fields$c++{
  537.                 $sheet->writeString(0$cucfirst(mysql_field_name($result$c))$head);
  538.         }
  539.         while ($row=mysql_fetch_row($result)){
  540.                 $r++;
  541.                 for ($c=0$c $fields$c++{
  542.                         $sheet->write($r$c$row[$c]);
  543.                 }
  544.         }
  545.         // send the file
  546.         $xls->close();
  547. }
  548.  
  549.  
  550.  
  551. #---------------------------------
  552. $big_sel "SELECT s.id as sid, inventory as inventory, s.mac as mac, v.default_id as vlan, v.default_name as vlanname, vstatus.value as status,
  553.     s.name as ComputerName, u.username as user, s.comment, s.ChangeDate, LastSeen, LastPort, sysbd.name as building, 
  554.     CONCAT(sysbd.name,' ',sysloc.name) as officeSoll, patchloc.name as officeIst,
  555.     pat.outlet as PatchSocket, patchloc.name as PatchCable,
  556.     p.name as port, sw.name as switch,
  557.     s.class as class, c1.value as classname,
  558.     s.class2 as class2, c2.value as class2name,
  559.     os.value as os, os.value as osname, os1.value as os1, os2.value as os2, os3.value as os3
  560. FROM systems s
  561. LEFT JOIN vstatus ON vstatus.id = s.status
  562. LEFT JOIN vlan v ON v.id = s.LastVlan
  563. LEFT JOIN port p ON p.id = s.LastPort
  564. LEFT JOIN switch sw ON sw.id = p.switch
  565. LEFT JOIN patchcable pat ON pat.port = p.id
  566.     LEFT JOIN location as patchloc ON patchloc.id = pat.office
  567. LEFT JOIN users u ON u.id = s.uid
  568. LEFT JOIN sys_class c1 ON c1.id = s.class
  569. LEFT JOIN sys_class2 c2 ON c2.id = s.class2
  570. LEFT JOIN sys_os os ON os.id = s.os
  571. LEFT JOIN sys_os1 os1 ON os1.id = s.os1
  572. LEFT JOIN sys_os2 os2 ON os2.id = s.os2
  573. LEFT JOIN sys_os3 os3 ON os3.id = s.os3
  574. LEFT JOIN location sysloc ON sysloc.id = s.office
  575.     LEFT JOIN building sysbd ON sysbd.id = sysloc.building_id";
  576.  
  577.  
  578. function debug_dump()
  579. {
  580.   if (DEBUG_OUTPUT === TRUE{
  581.     $args func_get_args();
  582.     $output '';
  583.     foreach ($args as $arg{
  584.       if (is_array($arg))
  585.         $output .=  print_r($argTRUE);
  586.       else
  587.         $output .= $arg;
  588.     }
  589.   }
  590. }
  591. /*
  592.   function dump_array($in_array)
  593.   {
  594.     echo "<table width='100%' border='0'>\n";
  595.  
  596.     foreach ($in_array as $key => $val)
  597.     {
  598.       echo "<tr><td>$key</td><td>$val</td></tr>\n";
  599.     }
  600.     echo "</table>\n";
  601.   }
  602.  
  603. dump_array($_REQUEST);
  604. dump_array($_POST);
  605. dump_array($_GET);