Changeset 10755

Show
Ignore:
Timestamp:
12/29/10 17:03:53 (2 years ago)
Author:
p_lindheimer
Message:

Merged revisions 10680,10753 via svnmerge from
http://www.freepbx.org/v2/svn/modules/branches/bootstrap-2.9

........

r10680 | mbrevda | 2010-12-09 14:13:11 -0800 (Thu, 09 Dec 2010) | 1 line


re #4566 - should have been checked in here

........

r10753 | p_lindheimer | 2010-12-29 13:15:57 -0800 (Wed, 29 Dec 2010) | 1 line


put back CLI debug() function as verbose, change several dbug back to verbose, have verbose write to dbug log, put back php4 comp functions until bootstrap is enabled, fix some errors with db debug method

........

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • modules/branches/2.9

    • Property svnmerge-integrated changed from /modules/branches/bootstrap-2.9:1-10625,10637,10647 /modules/branches/2.8:1-10750 to /modules/branches/bootstrap-2.9:1-10625,10637,10647,10680-10753 /modules/branches/2.8:1-10750
  • modules/branches/2.9/blacklist/functions.inc.php

    r10373 r10755  
    1919// 
    2020 
    21 if( !class_exists('extension') ) { 
    22   require('libraries/extensions.class.php'); 
    23 
     21 
    2422function blacklist_get_config($engine) { 
    2523  global $ext; 
  • modules/branches/2.9/dashboard/page.index.php

    r10528 r10755  
    503503include APP_ROOT."/common_functions.php"; 
    504504include APP_ROOT."/class.".PHP_OS.".inc.php"; 
    505 include_once "common/json.inc.php"; 
    506505include dirname(__FILE__)."/class.astinfo.php"; 
    507506include dirname(__FILE__)."/class.average_rate_calculator.php"; 
     
    658657   
    659658  echo '</div><div id="sysinfo-right">'; 
    660   ?>     
    661     <script type="text/javascript">      
    662     // If we detect 67 show cpu info       
    663     $(document).ready(function()       
    664     {  
    665         $(document).keydown(function detectEvent(e)      
    666         {      
    667             var evt = e || window.event;       
    668             var code = evt.keyCode || evt.charCode;      
    669  
    670             if (code == 67)      
    671             {      
    672                 document.getElementById('sysstats').style.display = 'block';       
    673             }      
    674         })       
    675     });      
    676     </script>      
    677  
    678   <?php 
     659   
    679660  echo '<div id="sysstats" class="infobox">'; 
    680661  echo show_sysstats(); 
     
    724705     
    725706    case 'info': 
    726       $json = new Services_JSON(); 
    727707      header("Content-type: application/json");  
    728       echo $json->encode( 
     708      echo json_encode( 
    729709        array( 
    730710          'procinfo'=>show_procinfo(), 
     
    736716    break; 
    737717    case 'stats': 
    738       $json = new Services_JSON(); 
    739718      header("Content-type: application/json");  
    740       echo $json->encode( 
     719      echo json_encode( 
    741720        array( 
    742721          'sysstats'=>show_sysstats(), 
     
    746725    break; 
    747726    case 'all': 
    748       $json = new Services_JSON(); 
    749727      header("Content-type: application/json");  
    750       echo $json->encode( 
     728      echo json_encode( 
    751729        array( 
    752730          'sysstats'=>show_sysstats(), 
  • modules/branches/2.9/dashboard/phpsysinfo/common_functions.php

    r9635 r10755  
    2424}  
    2525// usefull during development 
    26 error_reporting(E_ALL | E_NOTICE); 
     26//error_reporting(E_ALL | E_NOTICE); 
    2727 
    2828// print out the bar graph 
  • modules/branches/2.9/directory/agi-bin/directory.agi

    r10283 r10755  
    11#!/usr/bin/php -q 
    22<?php 
     3error_reporting(1); 
     4set_error_handler("error_handler"); 
     5 
     6verbose('entered dir!',6); 
    37require_once(dirname(__FILE__).'/directory.lib.php'); 
    4 $loopcounter1=$loopcounter2=0; 
    5 $matches=false; 
    6 $search=array(); 
    7 $dir=new Dir(); 
    8  
    9 $matches = false; 
    10 $needs_welcome = true; 
    11 while($loopcounter1 <= $dir->dir['repeat_loops']){ 
     8$loopcounter1 = 0; 
     9$loopcounter2   = 0; 
     10$matches    = false; 
     11$matches    = false; 
     12$needs_welcome  = true; 
     13$search     = array(); 
     14$dir      = new Dir(); 
     15 
     16while ($loopcounter1 <= $dir->dir['repeat_loops']) { 
    1217  //get inital search term 
    13   while($loopcounter2 <= $dir->dir['repeat_loops'] && !$matches )
     18  while ($loopcounter2 <= $dir->dir['repeat_loops'] && !$matches )
    1419    //get any number of digits, terminated by timeout or # 
    1520    $buffer = ''; 
    16     if ($needs_welcome) { 
    17       $needs_welcome = false; 
    18       $search=$dir->agi->fastpass_get_data($buffer, 'cdir-welcome',100,3); 
     21 if ($needs_welcome) { 
     22   $needs_welcome = false; 
     23    $search = $dir->agi->fastpass_get_data($buffer, 'cdir-welcome',100,3); 
    1924      if ((strlen($buffer) < 3) && (strstr($search['result'],'0') === false)) { 
    20        $search=$dir->agi->fastpass_get_data($buffer, $dir->dir['announcement'],3000,3); 
     25     $search = $dir->agi->fastpass_get_data($buffer, $dir->dir['announcement'], 3000, 3); 
    2126      } 
    2227    } else { 
    23       $search=$dir->agi->fastpass_get_data($buffer, $dir->dir['announcement'],3000,3); 
     28    $search = $dir->agi->fastpass_get_data($buffer, $dir->dir['announcement'],3000,3); 
    2429    } 
    25     $search=$search['result'];//being set so we can use it later 
    26     $matches=$dir->search($search,1); 
     30    $search = $search['result'];//being set so we can use it later 
     31    $matches = $dir->search($search,1); 
    2732    $loopcounter2++; 
    2833  } 
    2934  //hangup if we failed to receive anything meanigfull 
    30   if($loopcounter2 == 3){//seem like we ran out of tries...  
     35  if ($loopcounter2 == 3) {//seem like we ran out of tries...  
    3136    $dir->agi->stream_file('sorry-youre-having-problems'); 
    3237    $dir->bail(); 
    3338    break; 
    3439  } 
    35   $matchesloop=0; 
    36   $matches=$dir->search($search,1); 
     40  $matchesloop = 0; 
     41  $matches = $dir->search($search,1); 
    3742  //prompt the caller for more info if there are too many results (and he didnt terminate with #) 
    3843 
    3944  while($matches > 1 && $matchesloop < $dir->dir['repeat_loops'] && substr($search,-1)!='#'){ 
    40     if ($matches < 10) { 
    41       $compound = array('silence/1','cdir-there-are',(integer)$matches,'cdir-matching-entries-or-pound'); 
    42       $validdigits = '1234567890#'; 
    43     } else { 
    44       // don't allow #, get new recording that indicates such 
    45       $compound = array('silence/1','cdir-there-are',(integer)$matches,'cdir-matching-entries-continue'); 
    46       $validdigits = '1234567890'; 
    47     } 
    48     $press=$dir->getKeypress($compound, $validdigits, 3000); 
    49     if(!empty($press['result']) || $press==0)
    50       $search.=$press['result']; 
    51       $matches=$dir->search($search,1); 
    52       if ($matches > 9) { 
    53         $search = rtrim($search,'#'); 
    54         debug("Too many found: $matches, remove # if set and try again"); 
    55       } 
    56     }else
    57       $matchesloop++; 
    58    
    59     // if they timeout and there are 3 or fewer matches then just play them 
    60     if (empty($press['result']) && $matches <=3) { 
    61       break; 
    62     } 
     45     if ($matches < 10) { 
     46       $compound = array('silence/1','cdir-there-are',(integer)$matches,'cdir-matching-entries-or-pound'); 
     47       $validdigits = '1234567890#'; 
     48     } else { 
     49       // don't allow #, get new recording that indicates such 
     50       $compound = array('silence/1','cdir-there-are',(integer)$matches,'cdir-matching-entries-continue'); 
     51       $validdigits = '1234567890'; 
     52     } 
     53     $press = $dir->getKeypress($compound, $validdigits, 3000); 
     54    if (!empty($press['result']) || $press==0)
     55      $search .= $press['result']; 
     56      $matches = $dir->search($search,1); 
     57       if ($matches > 9) { 
     58         $search = rtrim($search,'#'); 
     59         verbose("Too many found: $matches, remove # if set and try again",6); 
     60       } 
     61    } else
     62      $matchesloop++; 
     63   
     64     // if they timeout and there are 3 or fewer matches then just play them 
     65     if (empty($press['result']) && $matches <=3) { 
     66       break; 
     67     } 
    6368  } 
    6469 
    6570  //act based on the amount of matches 
    66   if($matches > 1 && $matches <= 9)
     71  if ($matches > 1 && $matches <= 9)
    6772    //draw up variable of valid key presses 
    68     $validkeys=''; 
    69     for($i=1;$i<$matches+1;$i++){$validkeys.=$i;} 
    70     debug("valid keys for entries are: $validkeys"); 
     73    $validkeys = ''; 
     74    for ($i=1; $i < $matches+1; $i++) { 
     75      $validkeys .= $i; 
     76    } 
     77      verbose("valid keys for entries are: $validkeys",6); 
    7178     
    7279    //playback entries 
    73     $matches=$dir->search($search); 
    74     foreach($matches as $idx => $match){ 
    75       $ret=$dir->getKeypress('for',$validkeys,0);if(trim($ret['result'])){break;} 
    76       $ret=$dir->readContact($matches[$idx],$validkeys,0);if(trim($ret['result'])){break;} 
    77       $ret=$dir->getKeypress('press',$validkeys,0);if(trim($ret['result'])){;break;} 
    78       $ret=$dir->agi->say_digits($idx+1,$validkeys);if(trim($ret['result'])){$ret['result']=chr($ret['result']);break;} 
    79     } 
    80     debug("got result: ".$ret['result']); 
    81     if(trim($ret['result'])){ 
     80    $matches = $dir->search($search); 
     81    foreach ($matches as $idx => $match) { 
     82      $ret = $dir->getKeypress('for',$validkeys,0); 
     83      if (trim($ret['result'])) { 
     84        break; 
     85      } 
     86      $ret = $dir->readContact($matches[$idx],$validkeys,0); 
     87      if (trim($ret['result'])) { 
     88        break; 
     89      } 
     90      $ret = $dir->getKeypress('press',$validkeys,0); 
     91      if (trim($ret['result'])) { 
     92        break; 
     93      } 
     94      $ret = $dir->agi->say_digits($idx+1,$validkeys); 
     95      if (trim($ret['result'])) { 
     96        $ret['result'] = chr($ret['result']); 
     97        break; 
     98      } 
     99    } 
     100    //wait for a responce before restarting loop 
     101      $ret = $dir->agi->wait_for_digit(10000); 
     102    if (trim($ret['result'])) { 
     103      $ret['result'] = chr($ret['result']); 
     104    } 
     105     
     106    verbose("got result: ".$ret['result'],6); 
     107    if (trim($ret['result'])) { 
    82108      call($matches[$ret['result']-1]); 
    83109    } 
    84     $dir->agi->wait_for_digit(10000); 
    85   }elseif($matches==1){ 
     110  } elseif ($matches==1) { 
    86111    //call person $macthes[0]; 
    87     $matches=$dir->search($search); 
     112    $matches = $dir->search($search); 
    88113    call($matches[0]); 
    89   }else
     114  } else
    90115    $dir->agi->stream_file($dir->dir['repeat_recording']); 
    91116    $loopcounter1++; 
    92     $search=$matches=$loopcounter2=0; 
     117    $search = $matches = $loopcounter2 = 0; 
    93118  } 
    94119} 
     
    101126  global $dir; 
    102127  $dir->readContact($contact,$validkeys,0); 
    103   if($dir->dir['alert_info'] != '')
     128  if ($dir->dir['alert_info'] != '')
    104129    $dir->agi->set_alertinfo($dir->dir['alert_info']); 
    105130  } 
    106   if($dir->dir['callid_prefix'] != '')
     131  if ($dir->dir['callid_prefix'] != '')
    107132    $dir->agi->set_variable('CALLERID(name)',$dir->dir['callid_prefix'].$dir->dir['calleridname']); 
    108133  } 
     
    112137 
    113138//send debug to asterisk cli 
    114 function debug($string, $level=3){ 
     139function verbose($string, $level=3){ 
    115140  global $dir; 
    116141  $dir->agi->verbose($string, $level); 
    117 
    118  
    119 //pointer function so that we dont have to write '$dir->' every time we want to call dbug from here 
    120 function dbug(){global $dir;$a=func_get_args();switch(func_num_args()){case 1:$dir->dbug($a[0]);break;case 2:$dir->dbug($a[0],$a[1]);break;case 3:$dir->dbug($a[0],$a[1],$a[2]);break;}} 
     142 
     143  // send same message to debug log if enabled 
     144  dbug($string); 
     145
     146 
     147 /*  
     148  * FreePBX Debugging function 
     149  * This function can be called as follows: 
     150  * dbug() - will just print a time stamp to the debug log file ($amp_conf['FPBXDBUGFILE']) 
     151  * dbug('string') - same as above + will print the string 
     152  * dbug('string',$array) - same as above + will print_r the array after the message 
     153  * dbug($array) - will print_r the array with no message (just a time stamp)   
     154  * dbug('string',$array,1) - same as above + will var_dump the array 
     155  * dbug($array,1) - will var_dump the array with no message  (just a time stamp) 
     156  *     
     157  */   
     158function dbug(){ 
     159  $opts = func_get_args(); 
     160 
     161  $dump = 0; 
     162  //sort arguments 
     163  switch (count($opts)) { 
     164    case 1: 
     165      $msg    = $opts[0]; 
     166      break; 
     167    case 2: 
     168      if ( is_array($opts[0]) || is_object($opts[0]) ) { 
     169        $msg  = $opts[0]; 
     170        $dump = $opts[1]; 
     171      } else { 
     172        $disc = $opts[0]; 
     173        $msg  = $opts[1]; 
     174      } 
     175      break; 
     176    case 3: 
     177      $disc   = $opts[0]; 
     178      $msg    = $opts[1]; 
     179      $dump   = $opts[2]; 
     180      break;   
     181  } 
     182   
     183  if (isset($disc) && $disc) { 
     184    $disc = ' \'' . $disc . '\':'; 
     185  } 
     186   
     187  $bt = debug_backtrace(); 
     188  $txt = date("Y-M-d H:i:s")  
     189    . "\t" . $bt[0]['file'] . ':' . $bt[0]['line']  
     190    . "\n\n" 
     191    . (isset($disc) ? $disc : '' ) 
     192    . "\n"; //add timestamp + file info 
     193  dbug_write($txt); 
     194  if ($dump==1) {//force output via var_dump 
     195    ob_start(); 
     196    var_dump($msg); 
     197    $msg=ob_get_contents(); 
     198    ob_end_clean(); 
     199    dbug_write($msg."\n\n\n"); 
     200  } elseif(is_array($msg)||is_object($msg)) { 
     201    dbug_write(print_r($msg,true)."\n\n\n"); 
     202  } else { 
     203    dbug_write($msg."\n\n\n"); 
     204  } 
     205
     206 
     207function dbug_write($txt,$check=''){ 
     208  $append=false; 
     209  //optionaly ensure that dbug file is smaller than $max_size 
     210  if($check){ 
     211    $max_size = 52428800;//hardcoded to 50MB. is that bad? not enough? 
     212    $size = filesize('/tmp/freepbx_debug.log'); 
     213    $append = (($size > $max_size) ? false : true ); 
     214  } 
     215  if ($append) { 
     216    file_put_contents('/tmp/freepbx_debug.log',$txt); 
     217  } else { 
     218    file_put_contents('/tmp/freepbx_debug.log',$txt, FILE_APPEND); 
     219  } 
     220   
     221
     222 
     223function error_handler($errno, $errstr, $errfile, $errline, $errcontext){ 
     224  if ($errno == 2048){return;} //keeps out erros related to pear::db 
     225  $error = "\n\n"; 
     226  $error .= date("Y-M-d H:i:s").$disc."\t"; //add timestamp 
     227  $error .= $errfile."[".$errline."]\n"; 
     228  $error .= 'Error ['.$errno."]: ".$errstr."\n"; 
     229  //$error .=  print_r($errcontext)."\n"; 
     230  dbug_write($error); 
     231
    121232?> 
  • modules/branches/2.9/directory/agi-bin/directory.lib.php

    r9923 r10755  
    33  //agi class handler 
    44  var $agi; 
     5   
    56  //inital agi pased variables 
    67  var $agivar;   
     8   
    79  //asterisk manager class handler 
    810  var $ami; 
     11   
    912  //pear::db database object handel 
    1013  var $db; 
     14   
    1115  //options of the directory that we are currently working with 
    1216  var $dir; 
     17   
    1318  //the current directory that we are working with 
    1419  var $directory; 
     20   
    1521  //string we are searching for 
    1622  var $searchstring; 
     23   
    1724  //TODO: what is this var for? 
    1825  var $vmbasedir=''; 
    1926   
    2027  //PHP4 comaptibility constructor 
    21   function Dir(){ 
    22     $this->__construct(); 
    23  
     28   function Dir(){ 
     29    $this->__construct(); 
     30  
    2431 
    2532  //this function is run by php automaticly when the class is initalized 
     
    3643  function __construct_agi(){ 
    3744    require_once('phpagi.php'); 
    38     $agi=new AGI(); 
    39     foreach($agi->request as $key => $value){//strip agi_ prefix from keys 
    40       if(substr($key,0,4)=='agi_')
     45    $agi = new AGI(); 
     46    foreach ($agi->request as $key => $value) {//strip agi_ prefix from keys 
     47      if (substr($key,0,4)=='agi_')
    4148        $opts[substr($key,4)]=$value; 
    4249      } 
    4350    } 
    4451 
    45     foreach($opts as $key => $value){//get passed in vars 
    46       if(substr($key,0,4)=='arg_')
    47         $expld=explode('=',$value); 
    48         $opts[$expld[0]]=$expld[1]; 
     52    foreach ($opts as $key => $value) {//get passed in vars 
     53      if (substr($key,0,4)=='arg_')
     54        $expld = explode('=',$value); 
     55        $opts[$expld[0]] = $expld[1]; 
    4956        unset($opts[$key]); 
    5057      } 
     
    5259     
    5360    array_shift($_SERVER['argv']); 
    54     foreach($_SERVER['argv'] as $arg)
    55       $arg=explode('=',$arg); 
     61    foreach ($_SERVER['argv'] as $arg)
     62      $arg = explode('=',$arg); 
    5663      //remove leading '--' 
    57       if(substr($arg['0'],0,2) == '--'){$arg['0']=substr($arg['0'],2);} 
    58       $opts[$arg['0']]=isset($arg['1'])?$arg['1']:null; 
    59     } 
    60     $this->agivar=$opts; 
     64      if (substr($arg['0'],0,2) == '--') { 
     65        $arg['0']=substr($arg['0'],2); 
     66      } 
     67      $opts[$arg['0']] = isset($arg['1']) ? $arg['1'] : null; 
     68    } 
     69    $this->agivar = $opts; 
    6170    return $agi; 
    6271  } 
     
    6574  function __construct_ami(){ 
    6675    require_once('phpagi-asmanager.php'); 
    67     $ami=new AGI_AsteriskManager(); 
     76    $ami = new AGI_AsteriskManager(); 
    6877    return $ami; 
    6978  }  
     
    7483  function __construct_db(){ 
    7584    require_once("DB.php"); 
    76     $dsn=array( 
     85    $dsn = array( 
    7786      'phptype'  => $this->agi_get_var('AMPDBENGINE'), 
    7887      'hostspec' => $this->agi_get_var('AMPDBHOST'), 
     
    8190      'password' => $this->agi_get_var('AMPDBPASS'), 
    8291    ); 
    83     $db=DB::connect($dsn); 
     92    $db = DB::connect($dsn); 
    8493    return $db; 
    8594  } 
     
    8897  // TODO: handle getRow failures 
    8998  function __construct_dir_opts(){ 
    90     $sql='SELECT * FROM directory_details WHERE ID = ?'; 
    91     $row=$this->db->getRow($sql,array($this->directory),DB_FETCHMODE_ASSOC); 
    92     //TODO: Error Checking 
    93  
    94     //If any non-defaults (non-zero id) then lookup files 
    95     // 
     99    $sql = 'SELECT * FROM directory_details WHERE ID = ?'; 
     100    $row = $this->db->getRow($sql, array($this->directory), DB_FETCHMODE_ASSOC); 
     101      //TODO: Error Checking 
     102 
     103      //If any non-defaults (non-zero id) then lookup files 
    96104    if ($row['announcement'] || $row['repeat_recording'] || $row['invalid_recording']) { 
    97       $sql='SELECT id, filename from recordings where id in ('.$row['announcement'].','.$row['repeat_recording'].','.$row['invalid_recording'].')'; 
     105     $sql='SELECT id, filename from recordings where id in ('.$row['announcement'].','.$row['repeat_recording'].','.$row['invalid_recording'].')'; 
    98106      $res=$this->db->getAll($sql,DB_FETCHMODE_ASSOC); 
    99       if(DB::IsError($res)) { 
    100         debug("FATAL: got error from getAll query",1); 
    101         debug($res->getDebugInfo()); 
    102      
    103       $rec_file = array(); 
    104       foreach ($res as $entry) { 
    105         //TODO: check if file exists, which means splitting on & and checkking all 
    106         $rec_file[$entry['id']] = $entry['filename']; 
    107      
    108       unset($res); 
    109    
     107      if(DB::IsError($res)) { 
     108           verbose("FATAL: got error from getAll query",1); 
     109           dbug($res->getDebugInfo()); 
     110         
     111         $rec_file = array(); 
     112         foreach ($res as $entry) { 
     113           //TODO: check if file exists, which means splitting on & and checkking all 
     114           $rec_file[$entry['id']] = $entry['filename']; 
     115         
     116         unset($res); 
     117   
    110118    $row['announcement'] = $row['announcement']&&isset($rec_file[$row['announcement']])?$rec_file[$row['announcement']]:'cdir-please-enter-first-three'; 
    111119    $row['repeat_recording'] = $row['repeat_recording']&&isset($rec_file[$row['repeat_recording']])?$rec_file[$row['repeat_recording']]:'cdir-sorry-no-entries'; 
     
    130138  } 
    131139 
    132   // Return null on nothing pressed, false on error, otherwise the key 
    133   // TODO: make it so you can pass in an array: 
    134   // 
    135   function getKeypress($filename, $pressables='', $timeout=2000){ 
    136     if (!is_array($filename)) { 
    137       $filename = array($filename); 
    138     } 
    139     foreach ($filename as $chunk) { 
    140       $ret=is_int($chunk)?$this->agi->say_number($chunk,$pressables):$this->agi->stream_file($chunk,$pressables); 
    141       if(!empty($ret['result'])) {break;} 
    142     } 
    143     if(empty($ret['result'])){ 
    144       $ret=$this->agi->wait_for_digit($timeout); 
    145     } 
    146     switch ($ret['result']) { 
    147       case 0: 
    148         return null; 
    149       case -1: 
    150         return false; 
    151       default: 
    152         return chr($ret['result']); 
    153     } 
     140  // Return null on nothing pressed, false on error, otherwise the key 
     141  // TODO: make it so you can pass in an array: 
     142  function getKeypress($filename, $pressables='', $timeout=2000) { 
     143      if (!is_array($filename)) { 
     144        $filename = array($filename); 
     145      } 
     146      foreach ($filename as $chunk) { 
     147        $ret = is_int($chunk) ? $this->agi->say_number($chunk,$pressables) : $this->agi->stream_file($chunk,$pressables); 
     148        if (!empty($ret['result'])) { 
     149        break; 
     150      } 
     151      } 
     152      if(empty($ret['result'])) { 
     153        $ret = $this->agi->wait_for_digit($timeout); 
     154      } 
     155      switch ($ret['result']) {//TODO: are we mising break statements here? 
     156        case 0: 
     157          return null; 
     158        case -1: 
     159          return false; 
     160        default: 
     161          return chr($ret['result']); 
     162      } 
    154163  } 
    155164   
     
    157166    switch($con['audio']){ 
    158167      case 'vm': 
    159  
    160         $vm_dir = $this->agi->database_get('AMPUSER',$con['dial'].'/voicemail'); 
     168        $vm_dir = $this->agi->database_get('AMPUSER',$con['dial'].'/voicemail'); 
    161169        $vm_dir = $vm_dir['data']; 
    162         debug("got directory $vm_dir for user {$con['dial']}",6); 
    163  
     170        verbose("got directory $vm_dir for user {$con['dial']}",6); 
    164171        //check to see if we have a greet.* and play it. otherwise, fallback to spelling the name 
    165  
    166         if ($vm_dir && $vm_dir != 'novm') { 
     172            if ($vm_dir && $vm_dir != 'novm') { 
    167173          if (!$this->vmbasedir) { 
    168174            $this->vmbasedir = $this->agi_get_var('ASTSPOOLDIR').'/voicemail/'; 
    169175          } 
    170           $dir=scandir($this->vmbasedir.$vm_dir.'/'.$con['dial']); 
    171           foreach($dir as $file){ 
    172             debug("looking for vm file $file using: ".basename($file),6); 
    173             if(substr($file,0,5) == 'greet' && is_file($this->vmbasedir.$vm_dir.'/'.$con['dial'].'/'.$file)){ 
    174               $ret=$this->agi->stream_file($this->vmbasedir.$vm_dir.'/'.$con['dial'].'/greet',$keys); 
    175               if ($ret['result']){$ret['result']=chr($ret['result']);} 
    176               break 2;   
    177             }  
    178           } 
    179         } 
     176          $dir = scandir($this->vmbasedir.$vm_dir.'/'.$con['dial']); 
     177          foreach ($dir as $file) { 
     178          verbose("looking for vm file $file using: ".basename($file),6); 
     179          if (substr($file,0,5) == 'greet' && is_file($this->vmbasedir.$vm_dir.'/'.$con['dial'].'/'.$file)) { 
     180            $ret = $this->agi->stream_file($this->vmbasedir . $vm_dir . '/' . $con['dial'] . '/greet',$ keys); 
     181            if ($ret['result']){ 
     182              $ret['result']=chr($ret['result']); 
     183            } 
     184            break 2;   
     185          }  
     186        } 
     187      } 
    180188        //fallthough if not successfull 
    181189      case 'spell': 
     
    183191          switch(true){ 
    184192            case ctype_alpha($char): 
    185               $ret=$this->agi->evaluate('SAY ALPHA '.$char.' '.$keys); 
    186               debug("returned from SAY ALPHA with code/result {$ret['code']}/{$ret['result']}",6); 
     193              $ret = $this->agi->evaluate('SAY ALPHA '.$char.' '.$keys); 
     194                     //dbug("returned from SAY ALPHA with code/result {$ret['code']}/{$ret['result']}",6); 
    187195            break; 
    188196            case ctype_digit($char): 
    189               $ret=$this->agi->say_digits($char, $keys); 
     197              $ret = $this->agi->say_digits($char, $keys); 
    190198            break; 
    191199            case ctype_space($char)://pause 
    192               $ret=$this->agi->wait_for_digit(750); 
     200              $ret = $this->agi->wait_for_digit(750); 
    193201            break;           
    194202          } 
    195           if(trim($ret['result'])){$ret['result']=chr($ret['result']);break;} 
     203          if(trim($ret['result'])){ 
     204            $ret['result'] = chr($ret['result']); 
     205            break; 
     206          } 
    196207        } 
    197208      break; 
    198       //TODO: BUG: hardcoded to Flite, needs to either check what is there or be configurable 
     209         //TODO: BUG: hardcoded to Flite, needs to either check what is there or be configurable 
    199210      case 'tts': 
    200211        $ret=$this->agi->exec('Flite "'.$con['name'].'"|'.$keys); 
    201         if ($ret['result']){$ret['result']=chr($ret['result']);} 
    202       break; 
     212         if ($ret['result']){$ret['result']=chr($ret['result']);} 
     213      break; 
    203214      default: 
    204215        if(is_numeric($con['audio'])){ 
    205           $sql='SELECT filename from recordings where id = ?'; 
    206           $rec=$this->db->getOne($sql, array($con['audio'])); 
    207           debug("got record id: {$con['audio']} file(s): $rec"); 
    208           if($rec){ 
    209             $rec=explode('&',$rec); 
    210             foreach($rec as $r){ 
    211               $ret=$this->agi->stream_file($r,$keys); 
    212               if(trim($ret['result'])){$ret['result']=chr($ret['result']);break;} 
    213             } 
    214           } else { 
    215             //TODO: handle error 
    216             debug("ERROR: unknown/undefined sound file"); 
    217           } 
    218         } 
    219       break;  
    220     } 
    221     return $ret; 
    222   } 
    223    
    224   function search($key,$count=0){ 
    225     if($key == ''){return false;}//requre search term 
    226  
    227     if(strstr($key,'0') !== false) { 
    228       debug("user pressed 0 - bailing out"); 
     216          $sql = 'SELECT filename from recordings where id = ?'; 
     217          $rec = $this->db->getOne($sql, array($con['audio'])); 
     218          verbose("got record id: {$con['audio']} file(s): $rec"); 
     219          if ($rec) { 
     220            $rec = explode('&',$rec); 
     221            foreach ($rec as $r) { 
     222              $ret = $this->agi->stream_file($r,$keys); 
     223              if (trim($ret['result'])) { 
     224                $ret['result'] = chr($ret['result']); 
     225                break; 
     226              } 
     227            } 
     228          } else { 
     229            //TODO: handle error 
     230            verbose("ERROR: unknown/undefined sound file"); 
     231          } 
     232        } 
     233        break;  
     234      } 
     235      return $ret; 
     236    } 
     237   
     238  function search ($key,$count=0) { 
     239    if($key == ''){ 
     240      return false; 
     241    }//requre search term 
     242 
     243    if (strstr($key,'0') !== false) { 
     244      verbose("user pressed 0 - bailing out"); 
    229245      $this->bail(); 
    230246    } 
    231247 
    232   //the regex in the query will match the searchstring at the beging of the string or after a space 
    233   $num= array('1','2','3','4','5','6','7','8','9','0','#'); 
    234   $alph=array("[ \s@,-\!/+=\.']",'[abcABC]','[defDEF]','[ghiGHI]','[jklJKL]','[mnoMNO]','[pqrsPQRS]','[tuvTUV]','[wxyzWXYZ]','',''); 
    235     $this->searchstring=$this->db->escapeSimple(str_replace($num,$alph,$key)); 
    236     debug("search string for regex: {$this->searchstring}",6); 
     248  //the regex in the query will match the searchstring at the beging of the string or after a space 
     249  $num = array('1','2','3','4','5','6','7','8','9','0','#'); 
     250  $alph = array("[ \s@,-\!/+=\.']",'[abcABC]','[defDEF]','[ghiGHI]','[jklJKL]','[mnoMNO]','[pqrsPQRS]','[tuvTUV]','[wxyzWXYZ]','',''); 
     251    $this->searchstring = $this->db->escapeSimple(str_replace($num,$alph,$key)); 
     252    verbose("search string for regex: {$this->searchstring}",6); 
    237253 
    238254    //TODO: check db results for errors and fail gracefully 
    239  
    240     $vtable = '(SELECT DISTINCT a.audio, IF(a.name != "",a.name,b.name) name, IF(a.dial != "",a.dial,b.extension) dial FROM directory_entries a LEFT JOIN users b ON a.foreign_id = b.extension WHERE id = "'.$this->directory.'") v'; 
    241     if($count==1){ 
    242       $sql="SELECT COUNT(*) FROM $vtable WHERE name REGEXP \"(^| ){$this->searchstring}\""; 
    243       $res=$this->db->getOne($sql); 
    244       if(DB::IsError($res)) { 
    245         debug("FATAL: got error from COUNT(*) query"); 
    246         debug($res->getDebugInfo()); 
    247       } 
    248       debug("Found $res possible matches from $key"); 
    249     }else{ 
    250       $sql="SELECT * FROM $vtable WHERE name REGEXP \"(^| ){$this->searchstring}\""; 
    251       $res=$this->db->getAll($sql,DB_FETCHMODE_ASSOC); 
    252       if(DB::IsError($res)) { 
    253         debug("FATAL: got error from getAll query"); 
    254         debug($res->getDebugInfo()); 
    255       } else { 
    256         debug("Found the following matches:"); 
    257         foreach ($res as $ent) { 
    258           debug("name: {$ent['name']}, audio: {$ent['audio']}, dial: {$ent['dial']}"); 
    259         } 
    260       } 
    261     } 
    262     return $res; 
     255    $vtable = '(SELECT DISTINCT a.audio, IF(a.name != "", a.name, b.name) name, IF(a.dial != "",a.dial,b.extension) dial FROM directory_entries a LEFT JOIN users b ON a.foreign_id = b.extension WHERE id = "'.$this->directory.'") v'; 
     256  if ($count==1) { 
     257    $sql="SELECT COUNT(*) FROM $vtable WHERE name REGEXP \"(^| ){$this->searchstring}\""; 
     258    $res=$this->db->getOne($sql); 
     259      if (DB::IsError($res)) { 
     260      verbose("FATAL: got error from COUNT(*) query"); 
     261      dbug($res->getDebugInfo()); 
     262    } 
     263    verbose("Found $res possible matches from $key"); 
     264  } else { 
     265    $sql = "SELECT * FROM $vtable WHERE name REGEXP \"(^| ){$this->searchstring}\""; 
     266    $res = $this->db->getAll($sql,DB_FETCHMODE_ASSOC); 
     267    if (DB::IsError($res)) { 
     268      verbose("FATAL: got error from getAll query"); 
     269      dbug($res->getDebugInfo()); 
     270    } else { 
     271      verbose("Found the following matches:",6); 
     272      foreach ($res as $ent) { 
     273        verbose("name: {$ent['name']}, audio: {$ent['audio']}, dial: {$ent['dial']}",6); 
     274      } 
     275    } 
     276  } 
     277  return $res; 
    263278  } 
    264279 
    265280  function bail() { 
    266     //do something if we are exiting due to to many tries 
    267     // 
    268     debug("User pressed zero, passing back recording of {$this->dir['invalid_recording']}"); 
    269     $this->agi->set_variable('DIR_INVALID_RECORDING',$this->dir['invalid_recording']); 
    270     if($this->agi_get_var('IVR_CONTEXT')){ 
    271       $this->agi->set_extension('retivr'); 
    272     }else{ 
    273       $dest = explode(',',$this->dir['invalid_destination']); 
    274       $this->agi->set_variable('DIR_INVALID_CONTEXT',$dest['0']); 
    275       $this->agi->set_variable('DIR_INVALID_EXTEN',$dest['1']); 
    276       $this->agi->set_variable('DIR_INVALID_PRI',$dest['2']); 
    277       $this->agi->set_extension('invalid'); 
    278     } 
     281  //do something if we are exiting due to to many tries 
     282    verbose("User pressed zero, passing back recording of {$this->dir['invalid_recording']}"); 
     283  $this->agi->set_variable('DIR_INVALID_RECORDING',$this->dir['invalid_recording']); 
     284  if ($this->agi_get_var('IVR_CONTEXT')) { 
     285    $this->agi->set_extension('retivr'); 
     286  }else{ 
     287    $dest = explode(',',$this->dir['invalid_destination']); 
     288    $this->agi->set_variable('DIR_INVALID_CONTEXT',$dest['0']); 
     289    $this->agi->set_variable('DIR_INVALID_EXTEN',$dest['1']); 
     290    $this->agi->set_variable('DIR_INVALID_PRI',$dest['2']); 
     291    $this->agi->set_extension('invalid'); 
     292  } 
    279293    $this->agi->set_priority('1'); 
    280294    exit; 
    281   } 
    282  
    283  /*  
    284   * FreePBX Debuging function 
    285   * This function can be called as follows: 
    286   * dbug() - will just print a time stamp to the debug log file ($amp_conf['FPBXDBUGFILE']) 
    287   * dbug('string') - same as above + will print the string 
    288   * dbug('string',$array) - same as above + will print_r the array after the message 
    289   * dbug($array) - will print_r the array with no message (just a time stamp)   
    290   * dbug('string',$array,1) - same as above + will var_dump the array 
    291   * dbug($array,1) - will var_dump the array with no message  (just a time stamp) 
    292   *     
    293   */   
    294   function dbug(){ 
    295     $opts=func_get_args(); 
    296     //call_user_func_array('freepbx_debug',$opts); 
    297     $disc=$msg=$dump=''; 
    298     //sort arguments 
    299     switch(count($opts)){ 
    300       case 1: 
    301         $msg=$opts[0]; 
    302       break; 
    303       case 2: 
    304         if(is_array($opts[0])||is_object($opts[0])){ 
    305           $msg=$opts[0]; 
    306           $dump=$opts[1]; 
    307         }else{ 
    308           $disc=$opts[0]; 
    309           $msg=$opts[1]; 
    310         } 
    311       break; 
    312       case 3: 
    313         $disc=$opts[0]; 
    314         $msg=$opts[1]; 
    315         $dump=$opts[2]; 
    316       break;   
    317     } 
    318     if($disc){$disc=' \''.$disc.'\':';} 
    319     $txt=date("Y-M-d H:i:s").$disc."\n"; //add timestamp 
    320     $this->dbug_write($txt,1); 
    321     if($dump==1){//force output via var_dump 
    322       ob_start(); 
    323       var_dump($msg); 
    324       $msg=ob_get_contents(); 
    325       ob_end_clean(); 
    326       $this->dbug_write($msg."\n"); 
    327     }elseif(is_array($msg)||is_object($msg)){ 
    328       $this->dbug_write(print_r($msg,true)."\n"); 
    329     }else{ 
    330       $this->dbug_write($msg."\n"); 
    331     } 
    332   } 
    333   function dbug_write($txt,$check=''){ 
    334     $append=FILE_APPEND; 
    335     //optionaly ensure that dbug file is smaller than $max_size 
    336     if($check){ 
    337       $max_size=52428800;//hardcoded to 50MB. is that bad? not enough? 
    338       $size=filesize('/tmp/freepbx_debug.log'); 
    339       $append=(($size > $max_size)?'':FILE_APPEND); 
    340     } 
    341     file_put_contents('/tmp/freepbx_debug.log',$txt, $append); 
    342   } 
     295  } 
     296 
    343297} 
    344298// PHP 4 does not have file_put_contents so create an aproximation of what the real function does