Source for file webfuncs.inc

Documentation is available at webfuncs.inc

  1. <?php
  2. /**
  3.  * /opt/nac/bin/funcs.inc
  4.  *
  5.  * Long description for file:
  6.  * common PHP functions used by several scripts
  7.  *
  8.  * PHP version 5
  9.  *
  10.  * LICENSE: This program is free software; you can redistribute it and/or
  11.  * modify it under the terms of the GNU General Public License as published
  12.  * by the Free Software Foundation.
  13.  *
  14.  * @package            FreeNAC
  15.  * @author            Sean Boran (FreeNAC Core Team)
  16.  * @copyright        2007 FreeNAC
  17.  * @license            http://www.gnu.org/copyleft/gpl.html   GNU Public License Version 2
  18.  * @version            SVN: $Id$
  19.  * @link                http://www.freenac.net
  20.  *
  21.  */
  22.  
  23. chdir(dirname(__FILE__));
  24. require_once "../../etc/config.inc";
  25. require_once "../../bin/funcs.inc.php";
  26. /* funcs.inc
  27. function db_connect($username,$password)
  28. {
  29.   global $connect, $dbhost, $dbname;
  30.  
  31.   $connect=mysql_connect($dbhost, $username, $password)
  32.      or die("Could not connect to mysql: " . mysql_error());
  33.   mysql_select_db($dbname, $connect) or die("Could not select database")
  34.      or die("Could not select DB: " . mysql_error());;
  35. }
  36. */
  37.  
  38. function vlans_for($username)
  39. {
  40.    global $ad_auth;
  41.    if $ad_auth )
  42.    {
  43.       if $username )
  44.       {
  45.          $restriction[0]='';
  46.          return $restriction;
  47.       }
  48.       $user mysql_escape_string($username);
  49.       $query "select GuiVlanRights from users where username='$user';";
  50.       $res mysql_query($query);
  51.       if $res )
  52.       {
  53.          $restriction[0]='';
  54.          return $restriction;
  55.       }
  56.       if (mysql_num_rows($res)>0)
  57.       {
  58.          $restriction mysql_fetch_row($res);
  59.          $restriction $restriction[0];
  60.          if empty($restriction) )
  61.             return false;
  62.          else
  63.          {
  64.             $restriction .= ',';
  65.             $restriction explode(',',$restriction);
  66.             return $restriction;
  67.          }
  68.       }
  69.       else
  70.          return false;
  71.    }
  72.    else
  73.    {
  74.       return false;
  75.    }
  76. }
  77.  
  78. function ismemberof($username,$group)
  79. {
  80.    ## This function says whether a username in the form user@domain.com is belongs to the AD group specified
  81.    global $ad_server,$ad_user,$ad_password,$ad_port,$ad_base;
  82.    $counter=0;
  83.    $ad=ldap_connect($ad_server,$ad_port);
  84.    if ($ad)
  85.    {
  86.       if (ldap_bind($ad,$ad_user,$ad_password))
  87.       {
  88.          if ($ad_port==3268)         ## Global catalog is more flexible. 
  89.                                      ## In the event that we have more than one domain, 
  90.                                      ## the username gives us the domain name 
  91.                                      ## where we should look at.
  92.          {
  93.             ## Build the DN out of the username
  94.             $dn=explode('@',$username);
  95.             if (empty($dn))
  96.                return false;
  97.             $temp_dn=str_replace('.',',DC=',$dn[1]);
  98.             $dn='DC='.$temp_dn;
  99.          }
  100.          else
  101.             ## We are using a domain-level lookup, so in this case we need to know where the user information is 
  102.             $dn=$ad_base;
  103.          $attributes=array('memberOf');  ## We are interested only in the memberOf attribute
  104.          $filter='(&(userPrincipalName='.$username.')(objectClass=person))'## Retrieve info only for this specific username
  105.          $result=ldap_search($ad,$dn,$filter,$attributes);   ## Do the search
  106.          if ($result)
  107.          {
  108.             $entries=ldap_get_entries($ad,$result);
  109.             if ($entries['count']==1)    ## We should have only one result
  110.             {
  111.                $groups=$entries[0]['memberof']['count'];
  112.                if ($groups>0)
  113.                {
  114.                   for ($i=0;$i<$groups;$i++)
  115.                   {
  116.                      if (strcasecmp($entries[0]['memberof'][$i],$group== 0)
  117.                         $counter++;      ## Username is a member of the group
  118.                   }
  119.                }
  120.             }
  121.          }
  122.       }
  123.       else
  124.       {
  125.          echo 'Unable to bind to LDAP server with given credentials';
  126.       }
  127.       ldap_close($ad);
  128.    }
  129.    else
  130.    {
  131.       echo 'Unable to connect to LDAP server';
  132.    }
  133.    if ($counter>0)
  134.       return true;
  135.    else
  136.       return false;
  137. }
  138.  
  139. function user_rights($username)
  140. #This function outputs the rights associated to the username
  141. {
  142.    
  143.    global $dbuser,$dbpass;
  144.    db_connect($dbuser,$dbpass);
  145.    if (empty($username))
  146.    {
  147.       echo "<html>\n";
  148.       echo "<head>\n";
  149.       echo "\t<title>Oops, we have an empty username</title>\n";
  150.       echo "</head>\n";
  151.       echo "<body>\n";
  152.       echo "\tCan't authenticate an <strong>empty username</strong>.<br /><br />\n";
  153.       echo "\tIt seems as if you were trying to perform AD auth but you forgot to enable the required <strong>mod_authnz_ldap</strong> module in Apache<br />\n";
  154.       echo "</body>\n";
  155.       echo "</html>\n";
  156.       die();
  157.    }
  158.    $query='select * from guirights order by code desc;';
  159.    $res=mysql_query($query);
  160.    $rights=-1;
  161.    /*while ($result=mysql_fetch_array($res,MYSQL_ASSOC))
  162.    {
  163.       if ( ! empty($result['ad_group']))
  164.          if (ismemberof($username,$result['ad_group']))
  165.          {
  166.             $rights<$result['code'] ? $rights=$result['code'] : $result['code']=$rights;
  167.             break;
  168.          }
  169.    }*/
  170.    $user explode('@',$username);
  171.    $user $user[0];
  172.    $user mysql_escape_string($user);
  173.    $query "select nac_rights from users where username='$user'";
  174.    $res mysql_query($query);
  175.    if ($res)
  176.    {
  177.       if (mysql_num_rows($res)>0)
  178.       {
  179.          $rights mysql_fetch_row($res);
  180.          $rights $rights[0];
  181.       }
  182.       else
  183.       {
  184.          $rights = -1;
  185.       }
  186.    }
  187.    else
  188.    {
  189.       die ()
  190.    }
  191.    return $rights;
  192. }
  193.  
  194. function print_header(){
  195.    global $conf;    
  196.    if (!defined(HEADER)){
  197.         $ret='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  198.         <html xmlns="http://www.w3.org/1999/xhtml">
  199.         <head>
  200.         <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  201.         <title>FreeNAC @'.$conf->entityname.'</title>
  202.         <link href="bw.css" rel="stylesheet" type="text/css" />
  203.         </head>
  204.  
  205.         <body>
  206.         <table class="bw" width="1000" border="0">
  207.           <tr>
  208.             <td><a href="./index.html"><img src="./images/logo_small.png" border="0" /></a></td>
  209.                         <td align="right">
  210.                            <a href="http://www.freenac.net">FreeNAC website</a><br />
  211.                            <a href="http://www.freenac.net/en/installguide">Documentation</a><br />
  212.                            <a href="http://www.freenac.net/phpBB2">Support</a>
  213.                         </td>
  214.           </tr>
  215.           <tr>
  216.             <td class="center" colspan="2"><a href="'.$_SERVER['PHP_SELF'].'">List Unknowns</a> | <a href="'.$_SERVER['PHP_SELF'].'?action=search">Search</a>';
  217.         if ($conf->web_xls_output){
  218.             $ret.=' | <a href="'.$_SERVER['PHP_SELF'].'?action=export">Export</a>';
  219.         }
  220.         $ret.='</td>
  221.           </tr>
  222.         </table>
  223.         ';
  224.         define('HEADER',true)// The header is out
  225.         return $ret;
  226.     }
  227.  
  228. }
  229.  
  230. //
  231. // Print page footer (if not already done)
  232. //
  233. function print_footer(){
  234.     if(!defined(FOOTER)){
  235.         $ret='</table></body></html>';
  236.         define('FOOTER',true);
  237.         return $ret;
  238.     }
  239. }
  240.  
  241. function header_read()
  242. {
  243.    global $conf;
  244.    if (!defined(HEADER))
  245.    {
  246.       $ret='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  247.             <html xmlns="http://www.w3.org/1999/xhtml">
  248.             <head>
  249.                <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  250.                <title>FreeNAC @'.$conf->entityname.'</title>
  251.                <link href="bw.css" rel="stylesheet" type="text/css" />
  252.             </head>
  253.             <body>';
  254.       define('HEADER',true);
  255.       return $ret;
  256.    }
  257. }
  258.  
  259. function main_stuff()
  260. {
  261.    $text=<<<EOF
  262.    <table class="bw" border="0" align="center" width="500">
  263.    <tr height="80">
  264.       <td valign="center"><a href="./index.html"><img src="../images/logo_small.png" border="0" /></a></td>
  265.       <td align="right">
  266.          <a href="http://www.freenac.net">FreeNAC website</a><br />
  267.          <a href="http://www.freenac.net/en/usersguide">Users Guide</a><br />
  268.          <a href="http://www.freenac.net/phpBB2">Community Forum</a>
  269.       </td>
  270.    </tr>
  271.    <tr valign="top">
  272.       <td colspan="2">
  273.  
  274. EOF;
  275.    return $text;
  276. }
  277.  
  278. function read_footer()
  279. {
  280.    $text=<<<EOF
  281.       <p ALIGN=CENTER><a href="./index.php">NAC Menu</a></p>
  282.       </td>
  283.    </tr>
  284.    </table>
  285.    </body>
  286.    </html>
  287. EOF;
  288.    return $text;
  289. }
  290.  
  291. function user_tooltip($username{
  292.   global $dbuser,$dbpass;
  293.   db_connect($dbuser,$dbpass);
  294.   $query "SELECT * FROM users WHERE username = '$username'; ";
  295.   $res mysql_query($query)  or die ("Unable to query MySQL");
  296.  
  297.   $user mysql_fetch_array($res);
  298.  
  299.   //$text = $user['GivenName'].' '.$user['Surname'].', '.$user['Department']." (";
  300.   $text .= $user['HouseIdentifier'].' '.$user['PhysicalDeliveryOfficeName']." / ";
  301.  
  302.   // Shorter tel number for INO
  303.   if (stristr($user['TelephoneNumber'],'31-342')) {
  304.     $user['TelephoneNumber'str_replace(' ','',substr($user['TelephoneNumber'],strlen($user['TelephoneNumber'])-7,7));
  305.   };
  306.  
  307.   $text .= $user['TelephoneNumber']" / ";
  308.   $text .= $user['Mobile'];
  309.   //."\n";
  310.  
  311.   return($text);
  312. };
  313.  
  314. //
  315. // Get the proper icon
  316. //
  317. function get_icon($os,$os1,$os2,$os3){
  318.     $os strtolower($os);
  319.         $os1 strtolower($os1);
  320.         $os2 strtolower($os2);
  321.         $os3 strtolower($os3);
  322.     $prefix 'images';
  323.     
  324.     if (is_readable($prefix.'/'.$os.'.'.$os1.'.'.$os2.'.'.$os3.'.gif')) {
  325.         return($prefix.'/'.$os.'.'.$os1.'.'.$os2.'.'.$os3.'.gif');
  326.     else {
  327.         if (is_readable($prefix.'/'.$os.'.'.$os1.'.'.$os2.'.gif')) {
  328.             return($prefix.'/'.$os.'.'.$os1.'.'.$os2.'.gif');
  329.         else {
  330.             if (is_readable($prefix.'/'.$os.'.gif')) {
  331.                 return($prefix.'/'.$os.'.gif');
  332.             else {
  333.                 return($prefix.'/unknown.gif');
  334.             };
  335.         };
  336.     };
  337. };
  338.  
  339. //
  340. // Print the lookup results
  341. //
  342. function print_resultset($res,$server){
  343.         $ret='';
  344.         while ($row=mysql_fetch_array($res)){
  345.                 $ret.=($i%2==0)?'<tr class="light">':'<tr class="dark">';
  346.                 $ret.='<td><a href="'.$server['PHP_SELF'].'?action=edit&id='.$row['id'].'">';
  347.                 // if we have a name, echo the name, else just the id
  348.                 $ret.=($row['name']!=''?stripslashes($row['name']):$row['id']);
  349.                 $ret.='</a></td>'."\n";
  350.                 $ret.='<td class="center">'.$row['mac'].'</td>'."\n";
  351.                 $ret.='<td class="center">'.ucfirst($row['status']).'</td>'."\n";
  352.                 $ret.='<td class="center" title="VLAN '.$row['vlan'].'">'.$row['vlanname'].'</td>'."\n";
  353.                 $ret.='<td class="center">'.($row['lastvlan']!=''?$row['lastvlan']:'&nbsp;').'</td>'."\n";
  354.                 $ret.='<td class="center" title="'.$row['surname'].' '.$row['givenname'].'">'.$row['user'].'</td>'."\n";
  355.                 $ret.='<td class="center">'.$row['port'].'</td>'."\n";
  356.                 $ret.='<td class="center">'.$row['lastseen'].'</td>'."\n";
  357.                 $ret.='<td class="center" title="'.$row['switchip'].'">'.$row['switch'].'</td>'."\n";
  358.                 $ret.='<td class="center">'.($row['lastip']!=''?$row['lastip']:'&nbsp;').'</td>'."\n";
  359.         $ret.='<td class="center">'.($row['scan']!=''?$row['scan']:'&nbsp;').'</td>'."\n";
  360.                 $ret.='<td class="center">'.($row['epo']!=''?$row['epo']:'&nbsp;').'</td>'."\n";
  361.                 $ret.='<td class="center">'.($row['wsus']!=''?$row['wsus']:'&nbsp;').'</td>'."\n";
  362.         $ret.='<td class="center"><img width=20 height=20 src="'.get_icon($row['os'],$row['os1'],$row['os2'],$row['os3']).'"></td>'."\n";
  363.                 $ret.='</tr>'."\n";
  364.                 $i++;
  365.         }
  366.         return $ret;
  367. }
  368.  
  369. //
  370. // validates webinput
  371. // if the variable is an array recursevly call the
  372. // function for each value
  373. //
  374. function validate_webinput($value){
  375.         if (is_array($value)){
  376.                 array_map('validate_webinput',$value);
  377.         }
  378.         else {
  379.                 if (get_magic_quotes_gpc()) {
  380.                         $value @stripslashes($value);
  381.                 }
  382.                 if (!is_numeric($value)){
  383.                         $value @mysql_real_escape_string($value);
  384.                 }
  385.         }
  386.         return trim($value);
  387. }
  388.  
  389.  
  390.  
  391. //
  392. // retrieves all users from the databases and returns them as a hmtl dropdownlist
  393. //
  394. function get_userdropdown($selected_user{
  395.         global $rights;
  396.         if ($rights>=2)
  397.         {
  398.            $ret='<select name="username">';
  399.            $sql='SELECT id, username, CONCAT(surname,\' \',givenname,\', \',department) as displayname FROM users ORDER BY surname'// Get details for all users
  400.            $res=mysql_query($sqlor die('Query failed: ' mysql_error());
  401.            if (mysql_num_rows($res)>0){
  402.                 while ($r=mysql_fetch_array($res)){
  403.                         $ret.='<option value="'.$r['id'].'" '.($r['id']==$selected_user?'selected="selected"':'').'>'.$r['displayname'].'</option>'."\n";
  404.                 }
  405.            }
  406.            $ret.='</select>'."\n";
  407.         }
  408.         else
  409.         {
  410.            $sql="select username from users where id='$selected_user';";
  411.            $res=mysql_query($sqlor die('Query failed: ' mysql_error());
  412.            if (mysql_num_rows($res)>0)
  413.                 while ($r=mysql_fetch_array($res))
  414.                    $ret=$r['username'];
  415.         }
  416.         return $ret;
  417. }
  418.  
  419. //
  420. // retrieves all offices from the database and returns them as a html dropdownlist
  421. //
  422. function get_officedropdown($oid){
  423.         $ret='<select name="office">';
  424.         $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
  425.         $res=mysql_query($sqlor die('Query failed: ' mysql_error());
  426.         if (mysql_num_rows($res)>0){
  427.                 while ($r=mysql_fetch_array($res)){
  428.                         $ret.='<option value="'.$r['id'].'" '.($r['id']==$oid?'selected="selected"':'').'>'.$r['building'].' -  '.$r['office'].'</option>'."\n";
  429.              }
  430.         }
  431.         $ret.='</select>'."\n";
  432.         return $ret;
  433. }
  434.  
  435. //
  436. // retrieves the different status and returns them as a html dropdownlist
  437. //
  438. function get_status($s)
  439. {
  440.         global $rights;
  441.         if ($rights>=2)
  442.         {
  443.            $ret='<select name="status">';
  444.            $sql='SELECT id, value FROM vstatus ORDER BY value ASC;';
  445.            $res=mysql_query($sqlor die('Query failed: ' mysql_error());
  446.            if (mysql_num_rows($res)>0){
  447.                 while ($r=mysql_fetch_array($res)){
  448.                         $ret.='<option value="'.$r['id'].'" '.($s==$r['id']?'selected="selected"':'').'>'.$r['value'].'</option>'."\n";
  449.                 }
  450.            }
  451.            $ret.='</select>'."\n";
  452.         }
  453.         else
  454.         {
  455.           $sql="select value from vstatus where id='$s';";
  456.           $res=mysql_query($sqlor die('Query failed: ' mysql_error());
  457.           if (mysql_num_rows($res)>0)
  458.                 while ($r=mysql_fetch_array($res))
  459.                    $ret=$r['value'];
  460.         }
  461.         return $ret;
  462. }
  463.  
  464.  
  465. //
  466. // creates an excel sheet and sends it to the browser
  467. // input: $result (must be a mysql query result)
  468. //
  469. function create_xls($result){
  470.         $fields mysql_num_fields($result);
  471.         // create a new workbook
  472.         $xls new Spreadsheet_Excel_Writer();
  473.  
  474.         // format head row
  475.         $head =$xls->addFormat();
  476.         $head->setBold();
  477.         $head->setAlign('center');
  478.  
  479.         // send HTTP headers
  480.         $xls->send('freenac.xls');
  481.  
  482.         // create a worksheet
  483.         $sheet =$xls->addWorksheet('FreeNAC');
  484.  
  485.         // iterate trough the result set
  486.         $r=0// row
  487.         $c=0// column
  488.         for ($c=0$c $fields$c++{
  489.                 $sheet->writeString(0$cucfirst(mysql_field_name($result$c))$head);
  490.         }
  491.         while ($row=mysql_fetch_row($result)){
  492.                 $r++;
  493.                 for ($c=0$c $fields$c++{
  494.                         $sheet->write($r$c$row[$c]);
  495.                 }
  496.         }
  497.         // send the file
  498.         $xls->close();
  499. }
  500.  
  501.  
  502. $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,
  503.     s.name as ComputerName, u.username as user, s.comment, s.ChangeDate, LastSeen, LastPort, sysbd.name as building, 
  504.     CONCAT(sysbd.name,' ',sysloc.name) as officeSoll, patchloc.name as officeIst,
  505.     pat.outlet as PatchSocket, patchloc.name as PatchCable,
  506.     p.name as port, sw.name as switch,
  507.     s.class as class, c1.value as classname,
  508.     s.class2 as class2, c2.value as class2name,
  509.     os.value as os, os.value as osname, os1.value as os1, os2.value as os2, os3.value as os3
  510. FROM systems s
  511. LEFT JOIN vstatus ON vstatus.id = s.status
  512. LEFT JOIN vlan v ON v.id = s.LastVlan
  513. LEFT JOIN port p ON p.id = s.LastPort
  514. LEFT JOIN switch sw ON sw.id = p.switch
  515. LEFT JOIN patchcable pat ON pat.port = p.id
  516.     LEFT JOIN location as patchloc ON patchloc.id = pat.office
  517. LEFT JOIN users u ON u.id = s.uid
  518. LEFT JOIN sys_class c1 ON c1.id = s.class
  519. LEFT JOIN sys_class2 c2 ON c2.id = s.class2
  520. LEFT JOIN sys_os os ON os.id = s.os
  521. LEFT JOIN sys_os1 os1 ON os1.id = s.os1
  522. LEFT JOIN sys_os2 os2 ON os2.id = s.os2
  523. LEFT JOIN sys_os3 os3 ON os3.id = s.os3
  524. LEFT JOIN location sysloc ON sysloc.id = s.office
  525.     LEFT JOIN building sysbd ON sysbd.id = sysloc.building_id";
  526.  
  527.  
  528. function vmps_header()
  529. {
  530.   echo '<p ALIGN=CENTER><a href="./index.html">NAC Menu</a></p>';
  531. }
  532.  
  533. function vmps_footer()
  534. {
  535.   echo '<p ALIGN=CENTER><a href="./index.html">NAC Menu</a></p>';
  536. }
  537.  
  538. /*
  539. function debug1($msg) {
  540.   g