tinymon.php

Go to the documentation of this file.
00001 <?php
00002 session_start() ;
00003 
00004 /** \mainpage Tinymon Real-Time monitoring application for Asterisk
00005  * \version v0.21 2006
00006  */
00007  
00008 /* Written by Frederic LE FOLL (frederic       @     fr) __    /  \__
00009  * ___________________________          .lefoll free.      \__/      \_________ !
00010  *
00011  * This software is distributed under GPL 2 License (http://www.gnu.org/copyleft/gpl.html)
00012  */
00013 
00014 /** \file
00015  * Tiny real-time monitoring board for Asterisk.
00016  */
00017 
00018 include_once ('defines.php') ;
00019 
00020 
00021 /** Protect HTML code : add escape chars.
00022  *
00023  * @param $text Input String
00024  * @returns Converted String
00025  */
00026 function my_htmlentities($text)
00027         {
00028         return (htmlentities($text, ENT_COMPAT, 'UTF-8')) ;
00029         }
00030 
00031 
00032 /** Clean device status information : delete (obsolete) call information.
00033  *
00034  * In debug mode, "now", i.e. reference for tickets obsolescence, is the time
00035  * of last ticket extracted from DB.
00036  * Otherwise, "now" is current server time.
00037  *
00038  * @param $type Channel type (SIP, ...)
00039  * @param $dev Device
00040  * @param $forced Set to TRUE to delete ALL call information, FALSE to delete obolete call information only
00041  * @returns Number of calls remaining
00042  */
00043 function clean_dev_calls($type, $dev, $forced)
00044         {
00045         $calls = 0 ;
00046         if (isset($_SESSION['st'][$type][$dev]['_chan']))
00047                 {
00048                 if ($forced)
00049                         {
00050                         $_SESSION['st'][$type][$dev]['_chan'] = array () ;
00051                         }
00052                 else
00053                         {
00054                         $now = DEBUG ? $_SESSION['last_ticket']['timestamp'] : time() ;
00055                         foreach (array_keys($_SESSION['st'][$type][$dev]['_chan']) as $chanid)
00056                                 {
00057                                 if ($now - $_SESSION['st'][$type][$dev]['_chan'][$chanid]['_ts'] > CALL_TIMEOUT)
00058                                         {
00059                                         unset ($_SESSION['st'][$type][$dev]['_chan'][$chanid]) ;
00060                                         }
00061                                 else
00062                                         {
00063                                         $calls++ ;
00064                                         }
00065                                 }
00066                         }
00067                 }
00068         return ($calls) ;
00069         }
00070 
00071 
00072 /** Update device status information : update device information.
00073  *
00074  * @param $mode Mode : UPDATE or DELETE
00075  * @param $type Channel type (SIP, ...)
00076  * @param $dev Device
00077  * @param $ticket_a AMI ticket contents, stored in an associative array
00078  */
00079 function update_dev($mode, $type, $dev, $ticket_a)
00080         {
00081         switch ($mode)
00082                 {
00083         case UPDATE :
00084                 if (!isset($_SESSION['st'][$type][$dev]))
00085                         {
00086                         $_SESSION['st'][$type][$dev] = array() ;
00087                         }
00088                 $_SESSION['st'][$type][$dev] = array_merge($_SESSION['st'][$type][$dev], $ticket_a) ;
00089                 break ;
00090 
00091         case DELETE :
00092                 unset ($_SESSION['st'][$type][$dev]) ;
00093                 break ;
00094 
00095         default :
00096                 }
00097         }
00098 
00099 
00100 /** Parse "chantype/dev-chanid" string and extract fields.
00101  *
00102  * This function analyses the input string and extracts the fields.
00103  * It tries to make its best with < Z O M B I E > and suffixes alike,
00104  * as well as with AsyncGoto/ and possibly other prefixes.
00105  * Obviously, this simplification may involve a loss of information, or
00106  * even worse, may generate incorrect information !
00107  *
00108  * @param $cnxid String, supposedly looking like "chantype/dev-chanid"
00109  * @returns array (chantype, dev, chanid)
00110  */
00111 function parse_cnxid($cnxid)
00112         {
00113         /* Remove any <xxx> suffix */
00114         $cnxid = preg_replace('/<\w+>$/', '', $cnxid) ;
00115          /* Remove any xxx/ prefix ahead of "chantype/" - be even prepared to a cascade of A/B/C/... - */
00116         $cnxid = preg_replace('/^([\w\/]+\/)(\w+\/)/', '$2', $cnxid) ;
00117         list ($channel, $chanid) = explode('-', $cnxid) ;
00118         list($type, $dev) = explode("/", $channel) ;
00119         return (array ($type, $dev, $chanid)) ;
00120         }
00121 
00122 
00123 /** Update device status information : update call information.
00124  *
00125  * @param $mode Mode : UPDATE or DELETE
00126  * @param $cnxid Connection id with syntax "channeltype/device-channelid"
00127  * @param $ticket_a AMI ticket contents, stored in an associative array
00128  */
00129 function update_dev_call($mode, $cnxid, $ticket_a)
00130         {
00131         list($type, $dev, $chanid) = parse_cnxid($cnxid) ;
00132 
00133         switch ($mode)
00134                 {
00135         case UPDATE :
00136                 if (!isset($_SESSION['st'][$type][$dev]['_chan'][$chanid]))
00137                         {
00138                         $_SESSION['st'][$type][$dev]['_chan'][$chanid] = array() ;
00139                         }
00140                 $_SESSION['st'][$type][$dev]['_chan'][$chanid] = array_merge($_SESSION['st'][$type][$dev]['_chan'][$chanid], $ticket_a) ;
00141                 break ;
00142 
00143         case DELETE :
00144                 if (!isset($_SESSION['st'][$type][$dev]['_chan']))
00145                         {
00146                         $_SESSION['st'][$type][$dev]['_chan'] = array() ;
00147                         }
00148                 if (isset($_SESSION['st'][$type][$dev]['_chan'][$chanid]))
00149                         {
00150                         unset ($_SESSION['st'][$type][$dev]['_chan'][$chanid]) ;
00151                         }
00152                 break ;
00153 
00154         default :
00155                 }
00156         }
00157 
00158 /** Elaborate TinyMON display
00159  */
00160 function run_session()
00161         {
00162         global $ui, $status, $db ;
00163 
00164         /* Connect to DB */
00165 
00166         $db = mysql_pconnect(DB_HOST, DB_USERNAME, DB_PASSWORD) ;
00167         if (!$db)
00168                 {
00169                 trigger_error(mysql_error() . ' after mysql_pconnect()', E_USER_ERROR) ;
00170                 }
00171         else
00172                 {
00173                 $query = "set NAMES utf8" ;
00174                 $result = $db ? mysql_query($query) : FALSE ; if (!$result && $db) trigger_error(mysql_error() . ' after : ' . $query, E_USER_ERROR) ;
00175 
00176                 /* Add next two lines only if necessary */
00177                 /* $query = "set CHARACTER_SET utf8" ; */
00178                 /* $result = mysql_query($query) or error_log($query) and error_log(mysql_error()) ; */
00179 
00180                 $res = mysql_select_db(DB_DATABASE) ;
00181                 if (!$res)
00182                         {
00183                         trigger_error(mysql_error() . ' after mysql_select_db()', E_USER_ERROR) ;
00184                         mysql_close($db) ;
00185                         $db = NULL ;
00186                         }
00187                 }
00188 
00189         /* This code is called periodically, either because of refresh timeout, or because of user request.
00190          * Check whether there is a user request pending (Post or Get method). */
00191 
00192         $userrequest = 0 ;
00193         if (isset($_REQUEST['submit']['freeze']))
00194                 {
00195                 $_SESSION['freeze'] = 1 ;
00196                 $userrequest = 1 ;
00197                 }
00198         if (isset($_REQUEST['submit']['refresh']))
00199                 {
00200                 $_SESSION['freeze'] = 0 ;
00201                 $userrequest = 1 ;
00202                 }
00203         if (isset($_REQUEST['submit']['view']))
00204                 {
00205                 foreach (array_keys($_REQUEST['submit']['view']) as $type)
00206                         {
00207                         $_SESSION['view'][$type] = !$_SESSION['view'][$type] ;
00208                         }
00209                 $userrequest = 1 ;
00210                 }
00211         if (isset($_REQUEST['itemsperrow']))
00212                 {
00213                 $_SESSION['itemsperrow'] = $_REQUEST['itemsperrow'] ;
00214                 $userrequest = 1 ;
00215                 }
00216         if (isset($_REQUEST['zoom']))
00217                 {
00218                 $_SESSION['zoom'] = $_REQUEST['zoom'] ;
00219                 $userrequest = 1 ;
00220                 }
00221         if (isset($_REQUEST['id']))
00222                 {
00223                 $_SESSION['last_ticket']['id'] = $_REQUEST['id'] ;
00224                 $_SESSION['last_ticket']['datetime'] = NULL ;
00225                 $_SESSION['last_ticket']['timestamp'] = NULL ;
00226                 $_SESSION['last_ticket']['ticket'] = NULL ;
00227                 $_SESSION['last_ticket']['handled'] = 1 ;
00228                 $userrequest = 1 ;
00229                 }
00230 
00231         /* Assign default value to any non initialized variable */
00232 
00233         if (!isset($_SESSION['counter']))
00234                 {
00235                 $_SESSION['counter'] = 0 ;
00236                 }
00237         else
00238                 {
00239                 $_SESSION['counter']++ ;
00240                 }
00241         if (!isset($_SESSION['freeze']))
00242                 {
00243                 $_SESSION['freeze'] = 0 ;
00244                 }
00245         if (!isset($_SESSION['online']))
00246                 {
00247                 $_SESSION['online'] = 0 ;
00248                 }
00249         if (!isset($_SESSION['refresh_min']))
00250                 {
00251                 $_SESSION['refresh_min'] = REFRESH_MIN ;
00252                 }
00253         if (!isset($_SESSION['refresh_max']))
00254                 {
00255                 $_SESSION['refresh_max'] = REFRESH_MAX ;
00256                 }
00257         if (!isset($_SESSION['last_ticket']))
00258                 {
00259                 $_SESSION['last_ticket']['id'] = 0 ;
00260                 $_SESSION['last_ticket']['datetime'] = 0 ;
00261                 $_SESSION['last_ticket']['timestamp'] = 0 ;
00262                 $_SESSION['last_ticket']['ticket'] = '' ;
00263                 $_SESSION['last_ticket']['handled'] = 1 ;
00264                 }
00265         if (!isset($_SESSION['st']))
00266                 {
00267                 $_SESSION['st'] = array () ;
00268                 $_SESSION['st']['Asterisk']['status'] = 'unknown' ;
00269                 }
00270         if (!isset($_SESSION['view']))
00271                 {
00272                 $_SESSION['view']['Asterisk'] = 1 ;
00273                 $_SESSION['view']['SIP'] = 1 ;
00274                 }
00275         if (!isset($_SESSION['itemsperrow']))
00276                 {
00277                 $_SESSION['itemsperrow'] = 6 ;
00278                 }
00279 
00280         /* Run background monitoring application */
00281 
00282         if (!$_SESSION['online'])
00283                 {
00284                 if (DEMO)
00285                         {
00286                         $_SESSION['online'] = 1 ;
00287                         }
00288                 else
00289                         {
00290                         $check = exec(MON_APP . ' ping') ;
00291                         if ($check == 'pong')
00292                                 {
00293                                 $args = AST_USERNAME . ' ' . AST_PASSWORD .
00294                                        ' -h=' . AST_HOST .
00295                                        ' -p=' . AST_PORT .
00296                                        ' -a' . /* Auto-reconnect to Asterisk */
00297                                        ' -u' . /* Unique instance */
00298                                        ' -dbh=' . DB_HOST .
00299                                        ' -dbp=' . DB_PORT .
00300                                        ' -dbu=' . DB_USERNAME .
00301                                        ' -dbw=' . DB_PASSWORD .
00302                                        ' -dbd=' . DB_DATABASE .
00303                                        ' -dbt=' . DB_TABLE .
00304                                        ' -dbe=' . TICKETS_PURGE . /* Erase tickets older than ... */
00305                                        ' -dbc' . /* Create table if not exists */
00306                                        ' -c="loop ' . (POLLING_PERIOD - 1) . ' / action: sippeers / . / ! 1 / Action: status / . /"' ;
00307                                 /* And now, a little Black Magic to start a process in background.
00308                                  * This pclose(popen(... solution seems better than exec("... &") when the called process uses forks. */
00309                                 pclose(popen(MON_APP . " $args &", 'r')) ;
00310                                 $_SESSION['online'] = 1 ;
00311                                 }
00312                         else
00313                                 {
00314                                 trigger_error(MON_APP . ' is not available', E_USER_ERROR) ;
00315                                 }
00316                         }
00317                 }
00318 
00319         $sid = SID ? "?" . strip_tags(SID) : "" ;
00320         $url = $_SERVER['PHP_SELF'] . $sid ;
00321         $now = time() ;
00322         $_SESSION['scanstart'] = $now ;
00323 
00324         /*********************************************************************************
00325          * HTML Header. Include refresh information.
00326          *********************************************************************************/
00327 
00328         header("Cache-Control: no-cache, must-revalidate") ;
00329         header("Expires: Mon, 26 Jul 1997 05:00:00 GMT") ;
00330         header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT") ;
00331         if ($_SESSION['online'] && !$_SESSION['freeze'])
00332                 {
00333                 $refresh_min = $_SESSION['refresh_min'] ;
00334                 header("Refresh: $refresh_min; URL=$url");
00335                 }
00336 
00337         print "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" ;
00338         print "<html>\n" ;
00339         print "<head>\n" ;
00340         print "  <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" ;
00341         print "  <title>tinymon</title>\n" ;
00342         print "  <link type=\"text/css\" href=\"css/tinymon.css\" rel=\"stylesheet\">\n" ;
00343         print "</head>\n" ;
00344         print "<body>\n" ;
00345 
00346         /* Handle tickets available in DB.
00347          * We may wait for new tickets within the time limit of $_SESSION['refresh_max'] */
00348 
00349         $maxtime = $now + $_SESSION['refresh_max'] - $_SESSION['refresh_min'] ;
00350         $newtickets = 0 ;                           /* Count the number of tickets during current page execution */
00351         $maxnewtickets = TICKETS_PER_REFRESH_MAX ;  /* Maximum number of ticket we want to read during current page execution */
00352         $nomoretickets = FALSE ;                    /* Flag : last DB query returned no ticket */
00353         $wanttodisplay = FALSE ;                    /* Flag : stop reading tickets, and display current state */
00354         while (!$_SESSION['freeze'] &&              /* If display is user-frozen, don't update data */
00355                !$userrequest &&                     /* If this is a page refresh because of user request, don't update data this time */
00356                !($newtickets && $nomoretickets) &&  /* Flag : last DB query did not bring any ticket back */
00357                $newtickets < $maxnewtickets &&      /* We dont' want to query indefinitely, even if there are MANY tickets ahead in DB */
00358                time() < $maxtime &&                 /* Timeout */
00359                !$wanttodisplay)                     /* Flag : stop reading tickets, and display current state */ 
00360                 {
00361                 if ($nomoretickets)
00362                         {
00363                         /* If previous query was in vain, wait just a second before retrying a query */
00364                         sleep (1) ;
00365                         }
00366 
00367                 $ticketsavail = -1 ;
00368                 $query = "select count(*) from `" . DB_TABLE . "` where `id`>" . $_SESSION['last_ticket']['id'] ;
00369                 $result = $db ? mysql_query($query) : FALSE ; if (!$result && $db) trigger_error(mysql_error() . ' in : ' . $query, E_USER_ERROR) ;
00370                 if ($result)
00371                         {
00372                         $num_rows = mysql_num_rows($result) ;
00373                         if ($num_rows > 0)
00374                                 {
00375                                 $row = mysql_fetch_row($result) ;
00376                                 $ticketsavail = $row[0] ;
00377                                 }
00378                         mysql_free_result($result) ;
00379                         }
00380                 else
00381                         {
00382                         $wanttodisplay = 1 ;
00383                         }
00384 
00385                 if ($ticketsavail > 0)
00386                         {
00387                         $nomoretickets = FALSE ;
00388                         $newtickets++ ;
00389                         $query = "select `id`, `datetime`, time_to_sec(timediff(`datetime`, now())), `ticket`from `" . DB_TABLE . "` where `id`>" . $_SESSION['last_ticket']['id'] . " limit 0, 1" ;
00390                         $result = $db ? mysql_query($query) : FALSE ; if (!$result && $db) trigger_error(mysql_error() . ' in : ' . $query, E_USER_ERROR) ;
00391                         if ($result)
00392                                 {
00393                                 $num_rows = mysql_num_rows($result) ;
00394                                 if ($num_rows > 0)
00395                                         {
00396                                         $row = mysql_fetch_row($result) ;
00397                                         $_SESSION['last_ticket']['id'] = $row[0] ;
00398                                         $_SESSION['last_ticket']['datetime'] = $row[1] ;
00399                                         $_SESSION['last_ticket']['timestamp'] = time() + $row[2] ;
00400                                         $_SESSION['last_ticket']['ticket'] = $row[3] ;
00401                                         $_SESSION['last_ticket']['handled'] = 0 ;
00402                                         }
00403                                 mysql_free_result($result) ;
00404                                 }
00405                         else
00406                                 {
00407                                 $wanttodisplay = 1 ;
00408                                 }
00409 
00410                         $ticket_l = explode("\n", $_SESSION['last_ticket']['ticket']) ;
00411                         if (preg_match("/^Asterisk Call Manager\//", $ticket_l[0]))
00412                                 {
00413                                 array_shift($ticket_l) ;
00414                                 }
00415                         $msg = trim($ticket_l[0]) ;
00416                         if (strstr($msg, ': '))
00417                                 {
00418                                 list($msg, $indication) = explode(': ', $msg) ;
00419                                 }
00420                         else
00421                                 {
00422                                 $indication = '' ;
00423                                 }
00424 
00425                         /* Analyze ticket */
00426 
00427                         switch ($msg)
00428                                 {
00429 
00430                         case 'Response' :
00431 
00432                                 switch ($indication)
00433                                         {
00434                                 case 'Success' :
00435                                         $_SESSION['st']['Asterisk']['status'] = 'online' ;
00436                                         $_SESSION['last_ticket']['handled'] = 1 ;
00437                                         break ;
00438 
00439                                 case 'Goodbye' :
00440                                         $_SESSION['st']['Asterisk']['status'] = 'unknown' ;
00441                                         $_SESSION['last_ticket']['handled'] = 1 ;
00442                                         break ;
00443 
00444                                 default :
00445 
00446                                         }
00447                                 break ;
00448 
00449                         case 'Event' :
00450 
00451                                 /* Asterisk is considered online by default as soon as we receive an event */
00452                                 $_SESSION['st']['Asterisk']['status'] = 'online' ;
00453 
00454                                 /* Make an associative array from ticket information */
00455                                 $ticket_a = array('_ts' => $_SESSION['last_ticket']['timestamp']) ; /* Store timestamp with ticket */
00456                                 foreach ($ticket_l as $line)
00457                                         {
00458                                         if (strstr($line, ': '))
00459                                                 {
00460                                                 $split = explode(": ", trim($line), 2) ;
00461                                                 $item = $split[0] ;
00462                                                 $value = count($split) > 1 ? $split[1] : '' ;
00463                                                 $ticket_a[$item] = $value ;
00464                                                 }
00465                                         }
00466 
00467                                 $_SESSION['last_ticket']['handled'] = TRUE ; /* switch 'default' entry will deny when required */
00468                                 switch ($indication)
00469                                         {
00470                                 case 'Shutdown' :
00471                                         $_SESSION['st'] = array () ;
00472                                         $_SESSION['st']['Asterisk']['status'] = 'offline' ;
00473                                         $wanttodisplay = DEMO ;
00474                                         break ;
00475 
00476                                 case 'PeerEntry' :
00477                                         if (isset($ticket_a['Channeltype']) && isset($ticket_a['ObjectName']))
00478                                                 {
00479                                                 update_dev(UPDATE, $ticket_a['Channeltype'], $ticket_a['ObjectName'], $ticket_a) ;
00480                                                 $type = $ticket_a['Channeltype'] ;
00481                                                 $dev = $ticket_a['ObjectName'] ;
00482                                                 if (isset($_SESSION['st'][$type][$dev]['IPaddress']) &&
00483                                                     $_SESSION['st'][$type][$dev]['IPaddress'] == '-none-')
00484                                                         {
00485                                                         clean_dev_calls($type, $dev, 1) ;
00486                                                         }
00487                                                 }
00488                                         break ;
00489 
00490                                 case 'PeerStatus' :
00491                                         if (isset($ticket_a['Peer']))
00492                                                 {
00493                                                 list($type, $dev) = explode("/", $ticket_a['Peer']) ;
00494                                                 update_dev(UPDATE, $type, $dev, $ticket_a) ;
00495                                                 }
00496                                         break ;
00497 
00498                                 case 'Newchannel' :
00499                                 case 'Newcallerid' :
00500                                 case 'Newstate' :
00501                                 case 'Status' :
00502                                         if (isset($ticket_a['Channel']))
00503                                                 {
00504                                                 update_dev_call(UPDATE, $ticket_a['Channel'], $ticket_a) ;
00505                                                 }
00506                                         $wanttodisplay = DEMO ;
00507                                         break ;
00508 
00509                         case 'Dial' :
00510                                         if (isset($ticket_a['Source']))
00511                                                 {
00512                                                 update_dev_call(UPDATE, $ticket_a['Source'], $ticket_a) ;
00513                                                 }
00514                                         if (isset($ticket_a['Destination']))
00515                                                 {
00516                                                 update_dev_call(UPDATE, $ticket_a['Destination'], $ticket_a) ;
00517                                                 }
00518                                         $wanttodisplay = DEMO ;
00519                                         break ;
00520 
00521                                 case 'Hangup' :
00522                                         if (isset($ticket_a['Channel']))
00523                                                 {
00524                                                 update_dev_call(DELETE, $ticket_a['Channel'], $ticket_a) ;
00525                                                 }
00526                                         $wanttodisplay = DEMO ;
00527                                         break ;
00528 
00529                                 case 'MeetmeJoin' :
00530                                 case 'MeetmeLeave' :
00531                                         if (!isset($ticket_a['Meetme']) || !isset($ticket_a['Channel']))
00532                                                 break ; /* Should not happen. Don't care. */
00533                                         $meetme = $ticket_a['Meetme'] ;
00534                                         $cnxid = $ticket_a['Channel'] ;
00535                                         list ($channel, $chanid) = explode('-', $cnxid) ;
00536                                         /* Update Meetme status. Let's mimic the usual "channeltype/device-channelid" identifier */
00537                                         if ($indication == 'MeetmeJoin')
00538                                                 {
00539                                                 update_dev_call(UPDATE, "Meetme/$meetme-$chanid", $ticket_a) ; 
00540                                                 }
00541                                         else
00542                                                 {
00543                                                 update_dev_call(DELETE, "Meetme/$meetme-$chanid", $ticket_a) ;
00544                                                 }
00545                                         /* Update also Participant device status */
00546                                         if (isset($ticket_a['Channel']))
00547                                                 {
00548                                                 update_dev_call(UPDATE, $ticket_a['Channel'], $ticket_a) ;
00549                                                 }
00550                                         $wanttodisplay = DEMO ;
00551                                         break ;
00552 
00553                                 case 'ZapShowChannels' :
00554                                         if (isset($ticket_a['Channel']))
00555                                                 {
00556                                                 update_dev(UPDATE, 'Zap', $ticket_a['Channel'], $ticket_a) ;
00557                                                 }
00558                                         break ;
00559 
00560                                 case 'Rename' : /* This one is used for dark indicible reasons ... */
00561                                         if (!isset($ticket_a['Oldname']) || !isset($ticket_a['Newname']))
00562                                                 break ; /* Should not happen. Don't care. */
00563                                         $o_cnxid = preg_replace('/<\w+>/', '', $ticket_a['Oldname']) ; /* Remove any <xxx> sequence */
00564                                         $n_cnxid = preg_replace('/<\w+>/', '', $ticket_a['Newname']) ; /* Remove any <xxx> sequence */
00565                                         if ($n_cnxid != $o_cnxid)
00566                                                 {
00567                                                 list($o_type, $o_dev, $o_chanid) = parse_cnxid($o_cnxid) ;
00568                                                 list($n_type, $n_dev, $n_chanid) = parse_cnxid($n_cnxid) ;
00569                                                 update_dev_call(UPDATE, $o_cnxid, array ()) ; /* Just to be sure that an entry exists */
00570                                                 $_SESSION['st'][$n_type][$n_dev]['_chan'][$n_chanid] = $_SESSION['st'][$o_type][$o_dev]['_chan'][$o_chanid] ;
00571                                                 $_SESSION['st'][$n_type][$n_dev]['_chan'][$n_chanid][$msg] = $indication ;
00572                                                 unset ($_SESSION['st'][$o_type][$o_dev]['_chan'][$o_chanid]) ;
00573                                                 }
00574                                         $wanttodisplay = DEMO ;
00575                                         break ;
00576 
00577                                 case 'Alarm' :
00578                                         if (isset($ticket_a['Channel']))
00579                                                 {
00580                                                 update_dev(UPDATE, 'Zap', $ticket_a['Channel'], $ticket_a) ;
00581                                                 }
00582                                         break ;
00583 
00584                                 case 'AlarmClear' :
00585                                         if (isset($ticket_a['Channel']))
00586                                                 {
00587                                                 $ticket_a['Alarm'] = 'No Alarm' ;
00588                                                 update_dev(UPDATE, 'Zap', $ticket_a['Channel'], $ticket_a) ;
00589                                                 }
00590                                         break ;
00591 
00592                                 case 'PeerlistComplete' :          /* End of an Events list, after a SipPeers query, ... */
00593                                 case 'PeerlistComplete' :          /* End of an Events list, after a SipPeers query, ... */
00594                                 case 'StatusComplete' :            /* End of an Events list, after a Status query */
00595                                 case 'ZapShowChannelsComplete' :   /* End of an Events list, after a ZapShowChannels query */
00596                                 case 'Newexten' :                  /* Call routing progress information */
00597                                 case 'Link' :                      /* Communication established */
00598                                 case 'Unlink' :                    /* Communication discontinued */
00599                                 case 'Reload' :                    /* Asterisk configuration reloaded */
00600                                         /* TinyMON just ignores these events. */
00601                                         break ;
00602 
00603                                 default :
00604                                         $_SESSION['last_ticket']['handled'] = FALSE ;
00605                                         }
00606                                 break ;
00607 
00608                         default :
00609 
00610                                 }
00611                         }
00612                 else
00613                         {
00614                         $nomoretickets = TRUE ;
00615                         }
00616                 if (FREEZE_IF_NOT_HANDLED)
00617                         {
00618                         /* Auto-freeze if ticket not handled */
00619                         $_SESSION['freeze'] = $_SESSION['freeze'] || !$_SESSION['last_ticket']['handled'] ;
00620                         }
00621                 }
00622 
00623         /*********************************************************************************
00624          * TinyMON page structure : simple table with two cells aside
00625          *********************************************************************************/
00626 
00627         print "<table style=\"width: 100%;\">\n" ;
00628         print " <tbody>\n" ;
00629         print "  <tr>\n" ;
00630 
00631         /*********************************************************************************
00632          * Left side : information, commands, snapshots/zooms
00633          *********************************************************************************/
00634 
00635         print "   <td style=\"vertical-align: top; width: 200px;\">\n" ;
00636 
00637         /* Information */
00638 
00639         print "<span class=title>TinyMON</span>" ;
00640         if ($_SESSION['freeze'])
00641                 {
00642                 print " <img src=\"" . $ui['frozen'][0] . "\" title=\"" . $ui['frozen'][1] . "\"/>" ;
00643                 }
00644         else
00645                 {
00646                 print " <img src=\"" . $ui['running'][0] . "\" title=\"" . $ui['running'][1] . "\"/>" ;
00647                 }
00648         print "<br/> <span class=nota>Software under GPL license</span><br/>\n" ;
00649 
00650         print "Asterisk : " . AST_HOST . "<br/><span class=\"info\">" . date("Y-m-d H:i:s", $now) . "</span><br/>\n" ;
00651 
00652         /* Commands */
00653 
00654         print "<form action=\"$url\" method=\"post\">\n" ;
00655         foreach (array_keys($_SESSION['view']) as $type)
00656                 {
00657                 print "<input type=\"image\" name=\"submit[view][$type]\" src=\"" .
00658                   ($_SESSION['view'][$type] ? IMG_SELECTED : IMG_NOT_SELECTED) .
00659                       "\"> $type<br/>\n" ;
00660                 }
00661 
00662         if ($_SESSION['freeze'])
00663                 {
00664                 $rule_args_list = array(2, 4, 6, 8, 16) ;
00665                 $preset = $_SESSION['itemsperrow'] ;
00666                 print "<select name=\"itemsperrow\">" ;
00667                 foreach ($rule_args_list as $arg)
00668                         {
00669                         $selected_status = ($arg == $preset) ? 'selected' : '' ;
00670                         print "<option value=\"$arg\" $selected_status>$arg " ;
00671                         }
00672                 print "</select>" ;
00673                 }
00674         else
00675                 {
00676                 print $_SESSION['itemsperrow'] ;
00677                 }
00678         print " items/row<br/>" ;
00679 
00680         print "<br/>\n" ;
00681         print "<input type=\"image\" name=\"submit[freeze]\" src=\"" . $ui['freeze'][0] . "\" title=\"" . $ui['freeze'][1] . "\"/>\n" ;
00682         print "<img src=\"" . IMG_BLANK . "\">\n" ;
00683         print "<input type=\"image\" name=\"submit[refresh]\" src=\"" . $ui['refresh'][0] . "\" title=\"" . $ui['refresh'][1] . "\"/>\n" ;
00684         print "<br/><br/>\n" ;
00685 
00686         /* Snapshots/zooms */
00687 
00688         if (isset($_SESSION['zoom']) && strstr($_SESSION['zoom'], '/'))
00689                 {
00690                 list($type, $dev) = explode ('/', $_SESSION['zoom']) ;
00691                 print "<input type=\"submit\" name=\"zoom\" value=\"Close\"/> \n" ;
00692                 print "<span class=\"info\">Zoom $type/$dev<br/>\n" ;
00693                 print "<textarea name=\"ticket\" rows=\"10\" cols=\"32\" readonly>" ;
00694                 if (is_array($_SESSION['st'][$type][$dev]))
00695                         {
00696                         foreach (array_keys($_SESSION['st'][$type][$dev]) as $attr)
00697                                 {
00698                                 if ($attr == '_chan' || $attr == '_ts')
00699                                         {
00700                                         continue ;
00701                                         }
00702                                 $value = $_SESSION['st'][$type][$dev][$attr] ;
00703                                 print my_htmlentities("$attr: $value\n") ;
00704                                 }
00705                         }
00706                 if (is_array($_SESSION['st'][$type][$dev]['_chan']))
00707                         {
00708                         foreach (array_keys($_SESSION['st'][$type][$dev]['_chan']) as $chan)
00709                                 {
00710                                 print "* Channel $chan\n" ;
00711                                 foreach (array_keys($_SESSION['st'][$type][$dev]['_chan'][$chan]) as $chanattr)
00712                                         {
00713                                         if ($chanattr == '_ts')
00714                                                 {
00715                                                 continue ;
00716                                                 }
00717                                         $value = $_SESSION['st'][$type][$dev]['_chan'][$chan][$chanattr] ;
00718                                         print my_htmlentities("$chanattr: $value\n") ;
00719                                         }
00720                                 }
00721                         }
00722                 print "</textarea></span>" ;
00723                 }
00724 
00725         else if (isset($_SESSION['last_ticket']))
00726                 {
00727                 print "<span class=\"info\">Last Ticket - ID " . $_SESSION['last_ticket']['id'] . (!$_SESSION['last_ticket']['handled'] ? " <span class=\"msg\"> Not handled </span>" : "") . "<br/>\n" ;
00728                 print $_SESSION['last_ticket']['datetime'] . "<br/>\n" ;
00729                 print "<textarea name=\"ticket\" rows=\"10\" cols=\"32\" readonly>" . my_htmlentities($_SESSION['last_ticket']['ticket']) . "</textarea></span>" ;
00730                 }
00731 
00732         print "</form>" ;
00733 
00734         print "   </td>\n" ;
00735 
00736         /***********************************************************************
00737          * Right side : real-time view
00738          ***********************************************************************/
00739 
00740         print "   <td style=\"vertical-align: top;\">\n" ;
00741 
00742         $topofpage = TRUE ;
00743         $urlsnap = (strstr ($url, '?') ? $url . '&' : '?') . 'zoom=' ;
00744 
00745         foreach (array_keys($_SESSION['st']) as $type)
00746                 {
00747                 if(!isset($_SESSION['view'][$type]))
00748                         {
00749                         /* Auto-create new items in the 'view' list according to new channels */
00750                         $_SESSION['view'][$type] = VIEW_BY_DEFAULT ;
00751                         }
00752 
00753                 if (!$_SESSION['view'][$type])
00754                         {
00755                         continue ;
00756                         }
00757 
00758                 if (!$topofpage)
00759                         {
00760                         print "<hr style=\"width: 100%; height: 2px;\">\n" ;
00761                         }
00762                 $topofpage = FALSE ;
00763 
00764                 print "<div class=subtitle>$type</div>\n" ;
00765                 switch ($type)
00766                         {
00767                 case 'Asterisk' :
00768                         $sta = $_SESSION['st']['Asterisk']['status'] ;
00769                         print "<img src=\"" . $status[$sta][0] . "\" alt=\"" . $status[$sta][1] . "\" title=\"" . $status[$sta][1] . "\">Asterisk \n" ;
00770                         break ;
00771 
00772                 default :
00773                         if (!isset($_SESSION['st'][$type]))
00774                                 {
00775                                 continue ;
00776                                 }
00777 
00778                         $devs = array_keys($_SESSION['st'][$type]) ;
00779                         sort($devs) ;
00780                         print "<table style=\"width: 100%;\"><tbody>\n<tr>" ;
00781                         $count = 0 ;
00782                         $width = 100 / $_SESSION['itemsperrow'] ;
00783                         foreach ($devs as $dev)
00784                                 {
00785                                 if ($count != 0 && $count % $_SESSION['itemsperrow'] == 0)
00786                                         {
00787                                         print "</tr>\n<tr>" ;
00788                                         }
00789                                 $channels   = clean_dev_calls($type, $dev, 0) ;
00790                                 $registered = (isset($_SESSION['st'][$type][$dev]['IPaddress']) &&
00791                                                $_SESSION['st'][$type][$dev]['IPaddress'] != '-none-') &&
00792                                                (!isset($_SESSION['st'][$type][$dev]['PeerStatus']) ||
00793                                                $_SESSION['st'][$type][$dev]['PeerStatus'] != 'Unregistered') ;
00794                                 if ($channels)
00795                                         {
00796                                         if ($type == 'SIP')
00797                                                 {
00798                                                 $sta = 'ringing' ;
00799                                                 foreach (array_keys($_SESSION['st'][$type][$dev]['_chan']) as $chanid)
00800                                                         {
00801                                                         if (isset($_SESSION['st'][$type][$dev]['_chan'][$chanid]['State']) &&
00802                                                             $_SESSION['st'][$type][$dev]['_chan'][$chanid]['State'] != 'Ringing')
00803                                                                 {
00804                                                                 $sta = 'active' ;
00805                                                                 }
00806                                                         }
00807                                                 }
00808                                         else
00809                                                 {
00810                                                 $sta = 'active' ;
00811                                                 }
00812                                         }
00813                                 else if ($registered)
00814                                         {
00815                                         $sta = 'online' ;
00816                                         }
00817                                 else
00818                                         {
00819                                         $sta = 'offline' ;
00820                                         }
00821                                 if (isset($_SESSION['st'][$type][$dev]['Alarm']) &&
00822                                     $_SESSION['st'][$type][$dev]['Alarm'] != 'No Alarm')
00823                                         {
00824                                         $sta = 'alarm' ; /* Alarm state overrides any other state */
00825                                         }
00826                                 print "<td style=\"width: $width%;\" vertical-align: top;>" ;
00827                                 print "<img src=\"" . $status[$sta][0] . "\" alt=\"" . $status[$sta][1] . "\" title=\"" . $status[$sta][1] . "\">" ;
00828                                 print "<a href=\"$urlsnap$type/$dev\">$dev</a>" ;
00829                                 print "</td>\n" ;
00830                                 $count++ ;
00831                                 }
00832                         print "</tr>\n" ;
00833                         print "</tbody></table>\n" ;
00834                         }
00835                 }
00836 
00837         /* Intense debug information */
00838         /* print "<class=\"info\"><pre>" ;
00839         foreach (array_keys($_SESSION) as $var)
00840                 {
00841                 print "$var = " ;
00842                 if (!is_array($_SESSION[$var]))
00843                         print $_SESSION[$var] ;
00844                 elseif (in_array($var, array ('st')))
00845                         print 'array ()' ;
00846                 else
00847                         print_r($_SESSION[$var]) ;
00848                 print "\n" ;
00849                 } */
00850         /* print_r($_SESSION) ; */
00851 
00852         print "</pre></class>\n" ;
00853 
00854         print "   </td>\n" ;
00855 
00856         print "  </tr>\n" ;
00857         print " </tbody>\n" ;
00858         print "</table>\n" ;
00859 
00860         if (isset($_SESSION['errorlist']))
00861                 {
00862                 display_errors() ;
00863                 }
00864 
00865         print "</body>\n" ;
00866         print "</html>\n" ;
00867         }
00868 
00869 
00870 /** Store errors and syslog them. We'll display them alltogether later.
00871  */
00872 function store_error($err_type, $err_msg, $err_file, $err_line)
00873         {
00874         /* PHP error type => syslog severity */
00875         $severity = array (
00876                 E_ERROR =>           LOG_ERR,
00877                 E_WARNING =>         LOG_WARNING,
00878                 E_PARSE =>           LOG_ERR,
00879                 E_NOTICE =>          LOG_NOTICE,
00880                 E_CORE_ERROR =>      LOG_ERR,
00881                 E_CORE_WARNING =>    LOG_WARNING,
00882                 E_COMPILE_ERROR =>   LOG_ERR,
00883                 E_COMPILE_WARNING => LOG_WARNING,
00884                 E_USER_ERROR =>      LOG_ERR,
00885                 E_USER_WARNING =>    LOG_WARNING,
00886                 E_USER_NOTICE =>     LOG_NOTICE,
00887                 E_STRICT =>          LOG_ERR
00888                 ) ;
00889 
00890         if (in_array($err_type, array (E_NOTICE, E_STRICT)))
00891                 {
00892                 return (1) ;
00893                 }
00894         $_SESSION['errorlist'][] = array ($err_type, $err_msg, $err_file, $err_line) ;
00895         $priority = isset($severity[$err_type]) ? $severity[$err_type] : LOG_ERR ;
00896         syslog($priority, "TinyMON ($err_file:$err_line) $err_msg") ;
00897         return (1) ;
00898         }
00899 
00900 
00901 /** Display errors that have been stored.
00902  */
00903 function display_errors()
00904         {
00905         /* PHP error typ => text */
00906         $type = array (
00907                 E_ERROR =>           'ERROR',
00908                 E_WARNING =>         'WARNING',
00909                 E_PARSE =>           'PARSE',
00910                 E_NOTICE =>          'NOTICE',
00911                 E_CORE_ERROR =>      'CORE_ERROR',
00912                 E_CORE_WARNING =>    'CORE_WARNING',
00913                 E_COMPILE_ERROR =>   'COMPILE_ERROR',
00914                 E_COMPILE_WARNING => 'COMPILE_WARNING',
00915                 E_USER_ERROR =>      'USER_ERROR',
00916                 E_USER_WARNING =>    'USER_WARNING',
00917                 E_USER_NOTICE =>     'USER_NOTICE',
00918                 E_STRICT =>          'STRICT'
00919                 ) ;
00920         $sid = SID ? "?" . strip_tags(SID) : '' ;
00921         $url = $_SERVER['PHP_SELF'] . $sid ;
00922 
00923         print "<div class=\"alertbox\">\n" ;
00924         foreach ($_SESSION['errorlist'] as $error)
00925                 {
00926                 list ($err_type, $err_msg, $err_file, $err_line) = $error ;
00927                 $texttype = isset($type[$err_type]) ? $type[$err_type] : "Err $err_type" ;
00928                 $file = preg_replace ('/.*\//', '', $err_file) ;
00929                 print "$texttype ($file:$err_line) ". my_htmlentities($err_msg) . "<br/>\n" ;
00930                 }
00931         /* Submit button */
00932         print "<br/><form action=\"$url\" method=\"post\">\n" ;
00933         print "<input type=\"submit\" name=\"close_errorlist\" value=\"close\"> " ;
00934         print "</form>\n" ;     
00935         print "</div>\n" ;
00936         
00937         $_SESSION['freeze'] = 1 ;
00938         }
00939 
00940 set_error_handler('store_error') ;
00941 $db = NULL ;
00942 if (isset($_REQUEST['close_errorlist']))
00943         {
00944         unset ($_SESSION['errorlist']) ;
00945         }
00946 run_session() ;
00947 
00948 ?>

Generated on Sat Apr 1 18:43:45 2006 for TinyMON by  doxygen 1.4.6