atinymon.php

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

Generated on Sat Jul 8 09:39:14 2006 for TinyMON by  doxygen 1.4.6