Index: /modules/branches/bootstrap-2.9/directory/uninstall.php =================================================================== --- /modules/branches/bootstrap-2.9/directory/uninstall.php (revision 9585) +++ /modules/branches/bootstrap-2.9/directory/uninstall.php (revision 10795) @@ -11,6 +11,6 @@ } } -outn(_('dropping directory_details, directory_entries..')); -sql('DROP TABLE IF EXISTS directory_details, directory_entries'); +outn(_('dropping directory_details, directory_entries, directory...')); +sql('DROP TABLE IF EXISTS directory_details, directory_entries, directory'); out(_('ok')); ?> Index: /modules/branches/bootstrap-2.9/directory/page.directory.php =================================================================== --- /modules/branches/bootstrap-2.9/directory/page.directory.php (revision 10758) +++ /modules/branches/bootstrap-2.9/directory/page.directory.php (revision 10795) @@ -8,5 +8,5 @@ //check for ajax request and process that immediately if(isset($_REQUEST['ajaxgettr'])){//got ajax request - $opts = $opts=explode('|',urldecode($_REQUEST['ajaxgettr'])); + $opts = $opts=explode('|', urldecode($_REQUEST['ajaxgettr'])); if($opts[0] == 'all') { echo directory_draw_entries_all_users($opts[1]); @@ -23,5 +23,5 @@ $audio = 'tts'; } - echo directory_draw_entries_tr($real_id, $name, $realname, $audio,'',$opts[2]); + echo directory_draw_entries_tr($opts[0], $real_id, $name, $realname, $audio,'',$opts[2]); } exit; @@ -29,29 +29,68 @@ //get vars -$requestvars=array('id','action','entries','newentries'); -foreach($requestvars as $var){ - $$var=isset($_REQUEST[$var])?$_REQUEST[$var]:''; +$requestvars = array('id', 'action', 'entries', 'newentries', 'def_dir', 'Submit'); +foreach ($requestvars as $var){ + $$var = isset($_REQUEST[$var])?$_REQUEST[$var]:''; } + +if (isset($Submit) && $Submit == 'Submit' && isset($def_dir)) { + directory_save_default_dir($def_dir); +} + //draw right nav bar directory_drawListMenu(); -if($action=='' && $id==''){ +?> + + '', 'dirname' => _('none'))); + $def_dir = directory_get_default_dir(); echo '

Directory

'; - echo '

'; - echo '















'; + echo '

'; + echo '
'; + echo '

' . _('Directory Options') . '

'; + echo 'Default Directory '; + echo _('When checked, this becomes the default directory and replaces any other directory as the default directory. This has the effect of exposing entries for this directory into the Extension/User page'); + echo ''; + echo '  '; + echo '

'; + echo '














'; } function directory_drawListMenu(){ global $id,$type; - $results=directory_list(); + $results = directory_list(); + $def_dir = directory_get_default_dir(); echo '
\n
"; + echo "
"; } @@ -76,11 +115,11 @@ $('#addbut').not("span").fadeIn(250).find("span").hide(); }); - if($('#addusersel').val()!='none'){ + if($('#addusersel').val() != 'none'){ var rownum=$('[class^=entrie]').length+1; //increment id untill we find one that isnt being used - while($('.entrie'+rownum).length==1){ + while($('.entrie' + rownum).length == 1){ rownum++; } - addrow($('#addusersel').val()+'|'+rownum); + addrow($('#addusersel').val() + '|' + rownum); } return false; @@ -118,5 +157,5 @@ type: 'POST', url: location.href, - data: 'ajaxgettr='+encodeURIComponent(user)+'&quietmode=1&skip_astman=1&restrictmods=directory/core/recordings', + data: 'ajaxgettr='+encodeURIComponent(user)+'&quietmode=1&skip_astman=1', success: function(data) { $('#dir_entries_tbl > tbody:last').append(data); @@ -141,3 +180,5 @@ .dpt-title {color: #CCCCCC;} .text-normal {color: inherit;} +.dirhr{width: 50%; margin-left: 0px;} +#defdir{font-weight:bold;} Index: /modules/branches/bootstrap-2.9/directory/agi-bin/directory.lib.php =================================================================== --- /modules/branches/bootstrap-2.9/directory/agi-bin/directory.lib.php (revision 10753) +++ /modules/branches/bootstrap-2.9/directory/agi-bin/directory.lib.php (revision 10795) @@ -3,30 +3,23 @@ //agi class handler var $agi; - //inital agi pased variables var $agivar; - //asterisk manager class handler var $ami; - //pear::db database object handel var $db; - //options of the directory that we are currently working with var $dir; - //the current directory that we are working with var $directory; - //string we are searching for var $searchstring; - //TODO: what is this var for? var $vmbasedir=''; //PHP4 comaptibility constructor - function Dir(){ - $this->__construct(); - } + function Dir(){ + $this->__construct(); + } //this function is run by php automaticly when the class is initalized @@ -43,15 +36,15 @@ function __construct_agi(){ require_once('phpagi.php'); - $agi = new AGI(); - foreach ($agi->request as $key => $value) {//strip agi_ prefix from keys - if (substr($key,0,4)=='agi_') { + $agi=new AGI(); + foreach($agi->request as $key => $value){//strip agi_ prefix from keys + if(substr($key,0,4)=='agi_'){ $opts[substr($key,4)]=$value; } } - foreach ($opts as $key => $value) {//get passed in vars - if (substr($key,0,4)=='arg_') { - $expld = explode('=',$value); - $opts[$expld[0]] = $expld[1]; + foreach($opts as $key => $value){//get passed in vars + if(substr($key,0,4)=='arg_'){ + $expld=explode('=',$value); + $opts[$expld[0]]=$expld[1]; unset($opts[$key]); } @@ -59,13 +52,11 @@ array_shift($_SERVER['argv']); - foreach ($_SERVER['argv'] as $arg) { - $arg = explode('=',$arg); + foreach($_SERVER['argv'] as $arg){ + $arg=explode('=',$arg); //remove leading '--' - if (substr($arg['0'],0,2) == '--') { - $arg['0']=substr($arg['0'],2); - } - $opts[$arg['0']] = isset($arg['1']) ? $arg['1'] : null; - } - $this->agivar = $opts; + if(substr($arg['0'],0,2) == '--'){$arg['0']=substr($arg['0'],2);} + $opts[$arg['0']]=isset($arg['1'])?$arg['1']:null; + } + $this->agivar=$opts; return $agi; } @@ -74,5 +65,5 @@ function __construct_ami(){ require_once('phpagi-asmanager.php'); - $ami = new AGI_AsteriskManager(); + $ami=new AGI_AsteriskManager(); return $ami; } @@ -83,5 +74,5 @@ function __construct_db(){ require_once("DB.php"); - $dsn = array( + $dsn=array( 'phptype' => $this->agi_get_var('AMPDBENGINE'), 'hostspec' => $this->agi_get_var('AMPDBHOST'), @@ -90,5 +81,5 @@ 'password' => $this->agi_get_var('AMPDBPASS'), ); - $db = DB::connect($dsn); + $db=DB::connect($dsn); return $db; } @@ -97,23 +88,24 @@ // TODO: handle getRow failures function __construct_dir_opts(){ - $sql = 'SELECT * FROM directory_details WHERE ID = ?'; - $row = $this->db->getRow($sql, array($this->directory), DB_FETCHMODE_ASSOC); - //TODO: Error Checking - - //If any non-defaults (non-zero id) then lookup files + $sql='SELECT * FROM directory_details WHERE ID = ?'; + $row=$this->db->getRow($sql,array($this->directory),DB_FETCHMODE_ASSOC); + //TODO: Error Checking + + //If any non-defaults (non-zero id) then lookup files + // if ($row['announcement'] || $row['repeat_recording'] || $row['invalid_recording']) { - $sql='SELECT id, filename from recordings where id in ('.$row['announcement'].','.$row['repeat_recording'].','.$row['invalid_recording'].')'; + $sql='SELECT id, filename from recordings where id in ('.$row['announcement'].','.$row['repeat_recording'].','.$row['invalid_recording'].')'; $res=$this->db->getAll($sql,DB_FETCHMODE_ASSOC); - if(DB::IsError($res)) { - verbose("FATAL: got error from getAll query",1); - dbug($res->getDebugInfo()); - } - $rec_file = array(); - foreach ($res as $entry) { - //TODO: check if file exists, which means splitting on & and checkking all - $rec_file[$entry['id']] = $entry['filename']; - } - unset($res); - } + if(DB::IsError($res)) { + dbug("FATAL: got error from getAll query",1); + dbug($res->getdbugInfo()); + } + $rec_file = array(); + foreach ($res as $entry) { + //TODO: check if file exists, which means splitting on & and checkking all + $rec_file[$entry['id']] = $entry['filename']; + } + unset($res); + } $row['announcement'] = $row['announcement']&&isset($rec_file[$row['announcement']])?$rec_file[$row['announcement']]:'cdir-please-enter-first-three'; $row['repeat_recording'] = $row['repeat_recording']&&isset($rec_file[$row['repeat_recording']])?$rec_file[$row['repeat_recording']]:'cdir-sorry-no-entries'; @@ -138,27 +130,26 @@ } - // Return null on nothing pressed, false on error, otherwise the key - // TODO: make it so you can pass in an array: - function getKeypress($filename, $pressables='', $timeout=2000) { - if (!is_array($filename)) { - $filename = array($filename); - } - foreach ($filename as $chunk) { - $ret = is_int($chunk) ? $this->agi->say_number($chunk,$pressables) : $this->agi->stream_file($chunk,$pressables); - if (!empty($ret['result'])) { - break; - } - } - if(empty($ret['result'])) { - $ret = $this->agi->wait_for_digit($timeout); - } - switch ($ret['result']) {//TODO: are we mising break statements here? - case 0: - return null; - case -1: - return false; - default: - return chr($ret['result']); - } + // Return null on nothing pressed, false on error, otherwise the key + // TODO: make it so you can pass in an array: + // + function getKeypress($filename, $pressables='', $timeout=2000){ + if (!is_array($filename)) { + $filename = array($filename); + } + foreach ($filename as $chunk) { + $ret=is_int($chunk)?$this->agi->say_number($chunk,$pressables):$this->agi->stream_file($chunk,$pressables); + if(!empty($ret['result'])) {break;} + } + if(empty($ret['result'])){ + $ret=$this->agi->wait_for_digit($timeout); + } + switch ($ret['result']) { + case 0: + return null; + case -1: + return false; + default: + return chr($ret['result']); + } } @@ -166,24 +157,25 @@ switch($con['audio']){ case 'vm': - $vm_dir = $this->agi->database_get('AMPUSER',$con['dial'].'/voicemail'); + + $vm_dir = $this->agi->database_get('AMPUSER',$con['dial'].'/voicemail'); $vm_dir = $vm_dir['data']; - verbose("got directory $vm_dir for user {$con['dial']}",6); + dbug("got directory $vm_dir for user {$con['dial']}",6); + //check to see if we have a greet.* and play it. otherwise, fallback to spelling the name - if ($vm_dir && $vm_dir != 'novm') { + + if ($vm_dir && $vm_dir != 'novm') { if (!$this->vmbasedir) { $this->vmbasedir = $this->agi_get_var('ASTSPOOLDIR').'/voicemail/'; } - $dir = scandir($this->vmbasedir.$vm_dir.'/'.$con['dial']); - foreach ($dir as $file) { - verbose("looking for vm file $file using: ".basename($file),6); - if (substr($file,0,5) == 'greet' && is_file($this->vmbasedir.$vm_dir.'/'.$con['dial'].'/'.$file)) { - $ret = $this->agi->stream_file($this->vmbasedir . $vm_dir . '/' . $con['dial'] . '/greet',$ keys); - if ($ret['result']){ - $ret['result']=chr($ret['result']); - } - break 2; - } - } - } + $dir=scandir($this->vmbasedir.$vm_dir.'/'.$con['dial']); + foreach($dir as $file){ + dbug("looking for vm file $file using: ".basename($file),6); + if(substr($file,0,5) == 'greet' && is_file($this->vmbasedir.$vm_dir.'/'.$con['dial'].'/'.$file)){ + $ret=$this->agi->stream_file($this->vmbasedir.$vm_dir.'/'.$con['dial'].'/greet',$keys); + if ($ret['result']){$ret['result']=chr($ret['result']);} + break 2; + } + } + } //fallthough if not successfull case 'spell': @@ -191,160 +183,103 @@ switch(true){ case ctype_alpha($char): - $ret = $this->agi->evaluate('SAY ALPHA '.$char.' '.$keys); - //dbug("returned from SAY ALPHA with code/result {$ret['code']}/{$ret['result']}",6); + $ret=$this->agi->evaluate('SAY ALPHA '.$char.' '.$keys); + dbug("returned from SAY ALPHA with code/result {$ret['code']}/{$ret['result']}",6); break; case ctype_digit($char): - $ret = $this->agi->say_digits($char, $keys); + $ret=$this->agi->say_digits($char, $keys); break; case ctype_space($char)://pause - $ret = $this->agi->wait_for_digit(750); + $ret=$this->agi->wait_for_digit(750); break; } - if(trim($ret['result'])){ - $ret['result'] = chr($ret['result']); - break; - } + if(trim($ret['result'])){$ret['result']=chr($ret['result']);break;} } break; - //TODO: BUG: hardcoded to Flite, needs to either check what is there or be configurable + //TODO: BUG: hardcoded to Flite, needs to either check what is there or be configurable case 'tts': $ret=$this->agi->exec('Flite "'.$con['name'].'"|'.$keys); - if ($ret['result']){$ret['result']=chr($ret['result']);} - break; + if ($ret['result']){$ret['result']=chr($ret['result']);} + break; default: if(is_numeric($con['audio'])){ - $sql = 'SELECT filename from recordings where id = ?'; - $rec = $this->db->getOne($sql, array($con['audio'])); - verbose("got record id: {$con['audio']} file(s): $rec"); - if ($rec) { - $rec = explode('&',$rec); - foreach ($rec as $r) { - $ret = $this->agi->stream_file($r,$keys); - if (trim($ret['result'])) { - $ret['result'] = chr($ret['result']); - break; - } - } - } else { - //TODO: handle error - verbose("ERROR: unknown/undefined sound file"); - } - } - break; - } - return $ret; - } - - function search ($key,$count=0) { - if($key == ''){ - return false; - }//requre search term - - if (strstr($key,'0') !== false) { - verbose("user pressed 0 - bailing out"); + $sql='SELECT filename from recordings where id = ?'; + $rec=$this->db->getOne($sql, array($con['audio'])); + dbug("got record id: {$con['audio']} file(s): $rec"); + if($rec){ + $rec=explode('&',$rec); + foreach($rec as $r){ + $ret=$this->agi->stream_file($r,$keys); + if(trim($ret['result'])){$ret['result']=chr($ret['result']);break;} + } + } else { + //TODO: handle error + dbug("ERROR: unknown/undefined sound file"); + } + } + break; + } + return $ret; + } + + function search($key,$count=0){ + if($key == ''){return false;}//requre search term + + if(strstr($key,'0') !== false) { + dbug("user pressed 0 - bailing out"); $this->bail(); } - //the regex in the query will match the searchstring at the beging of the string or after a space - $num = array('1','2','3','4','5','6','7','8','9','0','#'); - $alph = array("[ \s@,-\!/+=\.']",'[abcABC]','[defDEF]','[ghiGHI]','[jklJKL]','[mnoMNO]','[pqrsPQRS]','[tuvTUV]','[wxyzWXYZ]','',''); - $this->searchstring = $this->db->escapeSimple(str_replace($num,$alph,$key)); - verbose("search string for regex: {$this->searchstring}",6); + //the regex in the query will match the searchstring at the beging of the string or after a space + $num= array('1','2','3','4','5','6','7','8','9','0','#'); + $alph=array("[ \s@,-\!/+=\.']",'[abcABC]','[defDEF]','[ghiGHI]','[jklJKL]','[mnoMNO]','[pqrsPQRS]','[tuvTUV]','[wxyzWXYZ]','',''); + $this->searchstring=$this->db->escapeSimple(str_replace($num,$alph,$key)); + dbug("search string for regex: {$this->searchstring}",6); //TODO: check db results for errors and fail gracefully - $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'; - if ($count==1) { - $sql="SELECT COUNT(*) FROM $vtable WHERE name REGEXP \"(^| ){$this->searchstring}\""; - $res=$this->db->getOne($sql); - if (DB::IsError($res)) { - verbose("FATAL: got error from COUNT(*) query"); - dbug($res->getDebugInfo()); - } - verbose("Found $res possible matches from $key"); - } else { - $sql = "SELECT * FROM $vtable WHERE name REGEXP \"(^| ){$this->searchstring}\""; - $res = $this->db->getAll($sql,DB_FETCHMODE_ASSOC); - if (DB::IsError($res)) { - verbose("FATAL: got error from getAll query"); - dbug($res->getDebugInfo()); - } else { - verbose("Found the following matches:",6); - foreach ($res as $ent) { - verbose("name: {$ent['name']}, audio: {$ent['audio']}, dial: {$ent['dial']}",6); - } - } - } - return $res; + + $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'; + if($count==1){ + $sql="SELECT COUNT(*) FROM $vtable WHERE name REGEXP \"(^| ){$this->searchstring}\""; + $res=$this->db->getOne($sql); + if(DB::IsError($res)) { + dbug("FATAL: got error from COUNT(*) query"); + dbug($res->getdbugInfo()); + } + dbug("Found $res possible matches from $key"); + }else{ + $sql="SELECT * FROM $vtable WHERE name REGEXP \"(^| ){$this->searchstring}\""; + $res=$this->db->getAll($sql,DB_FETCHMODE_ASSOC); + if(DB::IsError($res)) { + dbug("FATAL: got error from getAll query"); + dbug($res->getdbugInfo()); + } else { + dbug("Found the following matches:"); + foreach ($res as $ent) { + dbug("name: {$ent['name']}, audio: {$ent['audio']}, dial: {$ent['dial']}"); + } + } + } + return $res; } function bail() { - //do something if we are exiting due to to many tries - verbose("User pressed zero, passing back recording of {$this->dir['invalid_recording']}"); - $this->agi->set_variable('DIR_INVALID_RECORDING',$this->dir['invalid_recording']); - if ($this->agi_get_var('IVR_CONTEXT')) { - $this->agi->set_extension('retivr'); - }else{ - $dest = explode(',',$this->dir['invalid_destination']); - $this->agi->set_variable('DIR_INVALID_CONTEXT',$dest['0']); - $this->agi->set_variable('DIR_INVALID_EXTEN',$dest['1']); - $this->agi->set_variable('DIR_INVALID_PRI',$dest['2']); - $this->agi->set_extension('invalid'); - } + //do something if we are exiting due to to many tries + // + dbug("User pressed zero, passing back recording of {$this->dir['invalid_recording']}"); + $this->agi->set_variable('DIR_INVALID_RECORDING',$this->dir['invalid_recording']); + if($this->agi_get_var('IVR_CONTEXT')){ + $this->agi->set_extension('retivr'); + }else{ + $dest = explode(',',$this->dir['invalid_destination']); + $this->agi->set_variable('DIR_INVALID_CONTEXT',$dest['0']); + $this->agi->set_variable('DIR_INVALID_EXTEN',$dest['1']); + $this->agi->set_variable('DIR_INVALID_PRI',$dest['2']); + $this->agi->set_extension('invalid'); + } $this->agi->set_priority('1'); exit; - } + } } -// PHP 4 does not have file_put_contents so create an aproximation of what the real function does -// TODO: get rid of extinc php4 stuff as we dont support it anymore -// -if (!function_exists('file_put_contents')) { - function file_put_contents($filename, $data, $flags='', $context=null) { - $option = $flags == FILE_APPEND ? 'a' : 'w'; - if ($context !== null) { - $fd = @fopen($filename, $option); - } else { - $fd = @fopen($filename, $option, false, $context); - } - if (!$fd) { - return false; - } - if (is_array($data)) { - $data = implode('',$data); - } else if (is_object($data)) { - $data = print_r($data,true); - } - $bytes = fwrite($fd,$data); - fclose($fd); - - return $bytes; - } -} -if (!function_exists('scandir')) { - function scandir($path,$sort=0) { - $fh = opendir($path); - $list = array(); - while(false !== ($filename = readdir($fh))) { - $list[] = $filename; - } - closedir($fh); - /* Not really needed here - if ($sort) { - sort($list); - } else { - rsort($list); - } - */ - return $list; - } -} - -// non-utf8 version for php4 -if(!function_exists('str_split')) { - function str_split($string, $split_length = 1) { - $array = explode("\r\n", chunk_split($string, $split_length)); - array_pop($array); - return $array; - } -} + ?> Index: /modules/branches/bootstrap-2.9/directory/agi-bin/directory.agi =================================================================== --- /modules/branches/bootstrap-2.9/directory/agi-bin/directory.agi (revision 10753) +++ /modules/branches/bootstrap-2.9/directory/agi-bin/directory.agi (revision 10795) @@ -2,29 +2,31 @@ dir['repeat_loops']) { +$loopcounter1=$loopcounter2=0; +$matches=false; +$search=array(); +$dir=new Dir(); +$matches = false; +$needs_welcome = true; + +if ($dir->agivar['keypress']) { + $needs_welcome = false; + $search = $dir->agivar['keypress']; + $matches = true; +} + +while($loopcounter1 <= $dir->dir['repeat_loops']){ //get inital search term - while ($loopcounter2 <= $dir->dir['repeat_loops'] && !$matches ) { + while($loopcounter2 <= $dir->dir['repeat_loops'] && !$matches ){ //get any number of digits, terminated by timeout or # - $buffer = ''; - if ($needs_welcome) { - $needs_welcome = false; - $search = $dir->agi->fastpass_get_data($buffer, 'cdir-welcome',100,3); - if ((strlen($buffer) < 3) && (strstr($search['result'],'0') === false)) { - $search = $dir->agi->fastpass_get_data($buffer, $dir->dir['announcement'], 3000, 3); - } - } else { - $search = $dir->agi->fastpass_get_data($buffer, $dir->dir['announcement'],3000,3); + $buffer = ''; + if ($needs_welcome) { + $needs_welcome = false; + $search = $dir->agi->fastpass_get_data($buffer, 'cdir-welcome',100,3); + if ((strlen($buffer) < 3) && (strstr($search['result'],'0') === false)) { + $search = $dir->agi->fastpass_get_data($buffer, $dir->dir['announcement'],3000,3); + } + } else { + $search = $dir->agi->fastpass_get_data($buffer, $dir->dir['announcement'], 3000, 3); } $search = $search['result'];//being set so we can use it later @@ -33,7 +35,7 @@ } //hangup if we failed to receive anything meanigfull - if ($loopcounter2 == 3) {//seem like we ran out of tries... + if($loopcounter2 == 3){//seem like we ran out of tries... $dir->agi->stream_file('sorry-youre-having-problems'); - $dir->bail(); + $dir->bail(); break; } @@ -42,73 +44,55 @@ //prompt the caller for more info if there are too many results (and he didnt terminate with #) - while($matches > 1 && $matchesloop < $dir->dir['repeat_loops'] && substr($search,-1)!='#'){ - if ($matches < 10) { - $compound = array('silence/1','cdir-there-are',(integer)$matches,'cdir-matching-entries-or-pound'); - $validdigits = '1234567890#'; - } else { - // don't allow #, get new recording that indicates such - $compound = array('silence/1','cdir-there-are',(integer)$matches,'cdir-matching-entries-continue'); - $validdigits = '1234567890'; - } - $press = $dir->getKeypress($compound, $validdigits, 3000); - if (!empty($press['result']) || $press==0) { - $search .= $press['result']; - $matches = $dir->search($search,1); - if ($matches > 9) { - $search = rtrim($search,'#'); - verbose("Too many found: $matches, remove # if set and try again",6); - } - } else { - $matchesloop++; + while ($matches > 1 && $matchesloop < $dir->dir['repeat_loops'] && substr($search,-1)!='#') { + if ($matches < 10) { + $compound = array('silence/1','cdir-there-are',(integer)$matches,'cdir-matching-entries-or-pound'); + $validdigits = '1234567890#'; + } else { + // don't allow #, get new recording that indicates such + $compound = array('silence/1','cdir-there-are',(integer)$matches,'cdir-matching-entries-continue'); + $validdigits = '1234567890'; + } + $press=$dir->getKeypress($compound, $validdigits, 3000); + if(!empty($press['result']) || $press==0){ + $search.=$press['result']; + $matches=$dir->search($search,1); + if ($matches > 9) { + $search = rtrim($search,'#'); + dbug("Too many found: $matches, remove # if set and try again"); } - // if they timeout and there are 3 or fewer matches then just play them - if (empty($press['result']) && $matches <=3) { - break; - } + }else{ + $matchesloop++; + } + // if they timeout and there are 3 or fewer matches then just play them + if (empty($press['result']) && $matches <=3) { + break; + } } //act based on the amount of matches - if ($matches > 1 && $matches <= 9) { + if($matches > 1 && $matches <= 9){ //draw up variable of valid key presses - $validkeys = ''; - for ($i=1; $i < $matches+1; $i++) { + $validkeys=''; + for ($i=1; $i<$matches+1; $i++) { $validkeys .= $i; } - verbose("valid keys for entries are: $validkeys",6); + dbug("valid keys for entries are: $validkeys"); //playback entries - $matches = $dir->search($search); - foreach ($matches as $idx => $match) { - $ret = $dir->getKeypress('for',$validkeys,0); - if (trim($ret['result'])) { - break; - } - $ret = $dir->readContact($matches[$idx],$validkeys,0); - if (trim($ret['result'])) { - break; - } - $ret = $dir->getKeypress('press',$validkeys,0); - if (trim($ret['result'])) { - break; - } - $ret = $dir->agi->say_digits($idx+1,$validkeys); - if (trim($ret['result'])) { - $ret['result'] = chr($ret['result']); - break; - } - } - //wait for a responce before restarting loop - $ret = $dir->agi->wait_for_digit(10000); - if (trim($ret['result'])) { - $ret['result'] = chr($ret['result']); - } - - verbose("got result: ".$ret['result'],6); - if (trim($ret['result'])) { + $matches=$dir->search($search); + foreach($matches as $idx => $match){ + $ret=$dir->getKeypress('for',$validkeys,0);if(trim($ret['result'])){break;} + $ret=$dir->readContact($matches[$idx],$validkeys,0);if(trim($ret['result'])){break;} + $ret=$dir->getKeypress('press',$validkeys,0);if(trim($ret['result'])){;break;} + $ret=$dir->agi->say_digits($idx+1,$validkeys);if(trim($ret['result'])){$ret['result']=chr($ret['result']);break;} + } + dbug("got result: ".$ret['result']); + if(trim($ret['result'])){ call($matches[$ret['result']-1]); } - } elseif ($matches==1) { + $dir->agi->wait_for_digit(10000); + } elseif($matches == 1) { //call person $macthes[0]; - $matches = $dir->search($search); + $matches=$dir->search($search); call($matches[0]); } else { @@ -119,5 +103,5 @@ } -if($loopcounter1){ +if ($loopcounter1) { $dir->bail(); } @@ -126,8 +110,8 @@ global $dir; $dir->readContact($contact,$validkeys,0); - if ($dir->dir['alert_info'] != '') { + if($dir->dir['alert_info'] != ''){ $dir->agi->set_alertinfo($dir->dir['alert_info']); } - if ($dir->dir['callid_prefix'] != '') { + if($dir->dir['callid_prefix'] != ''){ $dir->agi->set_variable('CALLERID(name)',$dir->dir['callid_prefix'].$dir->dir['calleridname']); } @@ -136,24 +120,16 @@ } -//send debug to asterisk cli -function verbose($string, $level=3){ - global $dir; - $dir->agi->verbose($string, $level); - - // send same message to debug log if enabled - dbug($string); -} - - /* - * FreePBX Debugging function - * This function can be called as follows: - * dbug() - will just print a time stamp to the debug log file ($amp_conf['FPBXDBUGFILE']) - * dbug('string') - same as above + will print the string - * dbug('string',$array) - same as above + will print_r the array after the message - * dbug($array) - will print_r the array with no message (just a time stamp) - * dbug('string',$array,1) - same as above + will var_dump the array - * dbug($array,1) - will var_dump the array with no message (just a time stamp) - * - */ +/* + * FreePBX dbuging function + * This function can be called as follows: + * dbug() - will just print a time stamp to the dbug log file ($amp_conf['FPBXDBUGFILE']) + * dbug('string') - same as above + will print the string + * dbug('string',$array) - same as above + will print_r the array after the message + * dbug($array) - will print_r the array with no message (just a time stamp) + * dbug('string',$array,1) - same as above + will var_dump the array + * dbug($array,1) - will var_dump the array with no message (just a time stamp) + * +*/ + function dbug(){ $opts = func_get_args(); @@ -181,5 +157,5 @@ } - if (isset($disc) && $disc) { + if ($disc) { $disc = ' \'' . $disc . '\':'; } @@ -189,5 +165,5 @@ . "\t" . $bt[0]['file'] . ':' . $bt[0]['line'] . "\n\n" - . (isset($disc) ? $disc : '' ) + . $disc . "\n"; //add timestamp + file info dbug_write($txt); @@ -206,4 +182,5 @@ function dbug_write($txt,$check=''){ + global $amp_conf; $append=false; //optionaly ensure that dbug file is smaller than $max_size @@ -224,9 +201,11 @@ if ($errno == 2048){return;} //keeps out erros related to pear::db $error = "\n\n"; - $error .= date("Y-M-d H:i:s").$disc."\t"; //add timestamp - $error .= $errfile."[".$errline."]\n"; - $error .= 'Error ['.$errno."]: ".$errstr."\n"; + $error .= date("Y-M-d H:i:s").$disc."\n"; //add timestamp + $error .= 'Error Number '.$errno.": ".$errstr."\n"; + $error .= 'In file: '.$errfile."\n"; + $error .= 'At line number: '.$errline."\n"; //$error .= print_r($errcontext)."\n"; - dbug_write($error); -} + file_put_contents('/tmp/freepbx_debug.log',$error, FILE_APPEND); +} +set_error_handler("error_handler"); ?> Index: /modules/branches/bootstrap-2.9/directory/functions.inc.php =================================================================== --- /modules/branches/bootstrap-2.9/directory/functions.inc.php (revision 10637) +++ /modules/branches/bootstrap-2.9/directory/functions.inc.php (revision 10795) @@ -1,3 +1,4 @@ addguielem('_top', new gui_pageheading('title', _('Directory')), 0); - if ($_REQUEST['action'] == 'add') { - $deet = array('dirname', 'description', 'repeat_loops', 'announcement', - 'repeat_recording', 'invalid_recording', - 'callid_prefix', 'alert_info', 'invalid_destination', 'retivr', - 'default_directory', 'say_extension', 'id'); + if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'add') { + $deet = array('dirname', 'description', 'repeat_loops', 'announcement', + 'repeat_recording', 'invalid_recording', + 'callid_prefix', 'alert_info', 'invalid_destination', 'retivr', + 'say_extension', 'id'); foreach ($deet as $d) { @@ -22,22 +23,29 @@ break; default: - $dir[$d] = ''; + $dir[$d] = ''; break; } } - } else { - $dir=directory_get_dir_details($_REQUEST['id']); + } else { + $dir = directory_get_dir_details($_REQUEST['id']); //display usage - $usage_list = framework_display_destination_usage(directory_getdest($dir['id'])); - $currentcomponent->addguielem('_top', new gui_link_label('usage', $usage_list['text'], $usage_list['tooltip']), 0); + $usage_list = framework_display_destination_usage(directory_getdest($dir['id'])); + $usage_list_text = isset($usage_list['text']) ? $usage_list['text'] : ''; + $usage_list_tooltip = isset($usage_list['tooltip']) ? $usage_list['tooltip'] : ''; + $currentcomponent->addguielem('_top', new gui_link_label('usage', $usage_list_text, $usage_list_tooltip), 0); //display delete link - $label=sprintf(_("Delete Directory %s"),$dir['dirname']?$dir['dirname']:$dir['id']); - $label=' '.$label.''; - $currentcomponent->addguielem('_top', new gui_link('del', $label, $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].'&action=delete', true, false), 0); + $label = sprintf(_("Delete Directory %s"), $dir['dirname'] ? $dir['dirname'] : $dir['id']); + $label = ' ' . $label . ''; + $currentcomponent->addguielem('_top', new gui_link('del', $label, $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'] . '&action=delete', true, false), 0); } //delete link, dont show if we dont have an id (i.e. directory wasnt created yet) - $currentcomponent->addguielem('', new gui_textbox('dirname', $dir['dirname'], _('Directory Name'), _('Name of this directory.'))); - $currentcomponent->addguielem('', new gui_textbox('description', $dir['description'], _('Directory Description'), _('Description of this directory.'))); - $section = _('Directory Options'); + $gen_section = _('Directory General Options'); + $currentcomponent->addguielem($gen_section, new gui_textbox('dirname', $dir['dirname'], _('Directory Name'), _('Name of this directory.'))); + $currentcomponent->addguielem($gen_section, new gui_textbox('description', $dir['description'], _('Directory Description'), _('Description of this directory.'))); + $currentcomponent->addguielem($gen_section, new gui_textbox('callid_prefix', $dir['callid_prefix'], _('CallerID Name Prefix'), _('Prefix to be appended to current CallerID Name.'))); + $currentcomponent->addguielem($gen_section, new gui_textbox('alert_info', $dir['alert_info'], _('Alert Info'), _('ALERT_INFO to be sent when called from this Directory. Can be used for ditinctive ring for SIP devices.'))); + + $section = _('Directory Options (DTMF)'); //build recordings select list @@ -46,5 +54,5 @@ $currentcomponent->addoptlistitem('recordings', $r['id'], $r['displayname']); } - $currentcomponent->setoptlistopts('recordings', 'sort', false); + $currentcomponent->setoptlistopts('recordings', 'sort', false); //build repeat_loops select list and defualt it to 3 for($i=0; $i <11; $i++){ @@ -53,7 +61,5 @@ //generate page - $currentcomponent->addguielem($section, new gui_selectbox('announcement', $currentcomponent->getoptlist('recordings'), $dir['announcement'], _('Announcement'), _('Greeting to be played on entry to the directory'), false)); - $currentcomponent->addguielem($section, new gui_textbox('callid_prefix', $dir['callid_prefix'], _('CallerID Name Prefix'), _('Prefix to be appended to current CallerID Name.'))); - $currentcomponent->addguielem($section, new gui_textbox('alert_info', $dir['alert_info'], _('Alert Info'), _('ALERT_INFO to be sent when called from this Directory. Can be used for ditinctive ring for SIP devices.'))); + $currentcomponent->addguielem($section, new gui_selectbox('announcement', $currentcomponent->getoptlist('recordings'), $dir['announcement'], _('Announcement'), _('Greeting to be played on entry to the directory.'), false)); $currentcomponent->addguielem($section, new gui_selectbox('repeat_loops', $currentcomponent->getoptlist('repeat_loops'), $dir['repeat_loops'], _('Invalid Retries'), _('Number of times to retry when receiving an invalid/unmatched response from the caller'), false)); $currentcomponent->addguielem($section, new gui_selectbox('repeat_recording', $currentcomponent->getoptlist('recordings'), $dir['repeat_recording'], _('Invalid Retry Recording'), _('Prompt to be played when an invalid/unmatched response is received, before prompting the caller to try again'), false)); @@ -62,5 +68,4 @@ $currentcomponent->addguielem($section, new gui_checkbox('retivr', $dir['retivr'], _('Return to IVR'), _('When selected, if the call passed through an IVR that had "Return to IVR" selected, the call will be returned there instead of the Invalid destination.'),true)); $currentcomponent->addguielem($section, new gui_checkbox('say_extension', $dir['say_extension'], _('Announce Extension'), _('When checked, the extension number being transfered to will be announced prior to the transfer'),true)); - $currentcomponent->addguielem($section, new gui_checkbox('default_directory', $dir['default_directory'], _('Default Directory'), _('When checked, this becomes the default directory and replaces any other directory as the default directory. This has the effect of exposing entries for this directory into the Extension/User page'),true)); $currentcomponent->addguielem($section, new gui_hidden('id', $dir['id'])); $currentcomponent->addguielem($section, new gui_hidden('action', 'edit')); @@ -75,5 +80,5 @@ function directory_configpageinit($pagename) { global $currentcomponent; - if($pagename=='directory'){ + if($pagename == 'directory'){ $currentcomponent->addprocessfunc('directory_configprocess'); $currentcomponent->addguifunc('directory_configpageload'); @@ -86,13 +91,13 @@ } - $action = isset($_REQUEST['action'])?$_REQUEST['action']:null; - $extdisplay = isset($_REQUEST['extdisplay'])?$_REQUEST['extdisplay']:null; - $extension = isset($_REQUEST['extension'])?$_REQUEST['extension']:null; - $tech_hardware = isset($_REQUEST['tech_hardware'])?$_REQUEST['tech_hardware']:null; + $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null; + $extdisplay = isset($_REQUEST['extdisplay']) ? $_REQUEST['extdisplay'] : null; + $extension = isset($_REQUEST['extension']) ? $_REQUEST['extension'] : null; + $tech_hardware = isset($_REQUEST['tech_hardware']) ? $_REQUEST['tech_hardware'] : null; if ($tech_hardware != null || $pagename == 'users') { directory_applyhooks(); $currentcomponent->addprocessfunc('directory_configprocess_exten', 8); - } elseif ($action=="add") { + } elseif ($action == "add") { // We don't need to display anything on an 'add', but we do need to handle returned data. $currentcomponent->addprocessfunc('directory_configprocess_exten', 8); @@ -106,31 +111,32 @@ //prosses received arguments function directory_configprocess(){ - if($_REQUEST['display']=='directory'){ + if($_REQUEST['display'] == 'directory'){ global $db,$amp_conf; //get variables for directory_details - $requestvars=array('id','dirname','description','announcement', - 'callid_prefix','alert_info','repeat_loops','repeat_recording', - 'invalid_recording','invalid_destination','retivr','say_extension','default_directory'); + $requestvars = array('id','dirname','description','announcement', + 'callid_prefix','alert_info','repeat_loops', + 'repeat_recording','invalid_recording', + 'invalid_destination','retivr','say_extension'); foreach($requestvars as $var){ - $vars[$var]=isset($_REQUEST[$var])?$_REQUEST[$var]:''; - } - - $action=isset($_REQUEST['action'])?$_REQUEST['action']:''; - $entries=isset($_REQUEST['entries'])?$_REQUEST['entries']:''; - $entries=(($entries)?array_values($entries):'');//reset keys + $vars[$var] = isset($_REQUEST[$var]) ? $_REQUEST[$var] : ''; + } + + $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : ''; + $entries = isset($_REQUEST['entries']) ? $_REQUEST['entries'] : ''; + //$entries=(($entries)?array_values($entries):'');//reset keys switch($action){ case 'edit': //get real dest - $vars['invalid_destination']=$_REQUEST[$_REQUEST[$_REQUEST['invalid_destination']].str_replace('goto','',$_REQUEST['invalid_destination'])]; - $vars['id']=directory_save_dir_details($vars); + $vars['invalid_destination'] = $_REQUEST[$_REQUEST[$_REQUEST['invalid_destination']].str_replace('goto','',$_REQUEST['invalid_destination'])]; + $vars['id'] = directory_save_dir_details($vars); directory_save_dir_entries($vars['id'],$entries); needreload(); - redirect_standard('id'); + redirect_standard_continue('id'); break; case 'delete': directory_delete($vars['id']); needreload(); - redirect_standard(); + redirect_standard_continue(); break; } @@ -142,30 +148,29 @@ switch ($engine) { case 'asterisk': - $sql='SELECT id,dirname,say_extension FROM directory_details ORDER BY dirname'; + $sql = 'SELECT id,dirname,say_extension FROM directory_details ORDER BY dirname'; $results=sql($sql,'getAll',DB_FETCHMODE_ASSOC); if($results){ - $context = 'directory'; - // Note create a dial-id label for each directory to allow other modules to hook on a per - // directory basis. (Otherwise we could have consolidated this into a call extension) + $c = 'directory'; + // Note create a dial-id label for each directory to allow other modules to hook on a per + // directory basis. (Otherwise we could have consolidated this into a call extension) foreach ($results as $row) { - $ext->add($context,$row['id'], '', new ext_answer('')); - $ext->add($context,$row['id'], '', new ext_wait('1')); - $ext->add($context,$row['id'], '', new ext_agi('directory.agi,dir='.$row['id'])); - if ($row['say_extension']) { - $ext->add($context,$row['id'], '', new ext_playback('pls-hold-while-try&to-extension')); - $ext->add($context,$row['id'], '', new ext_saydigits('${DIR_DIAL}')); - } - $ext->add($context,$row['id'], 'dial-'.$row['id'], new ext_ringing()); - $ext->add($context,$row['id'], '', new ext_goto('1','${DIR_DIAL}','from-internal')); + $ext->add($c, $row['id'], '', new ext_answer('')); + $ext->add($c, $row['id'], '', new ext_wait('1')); + $ext->add($c, $row['id'], '', new ext_agi('directory.agi,dir=' . $row['id'] . ',keypress=${keypress}')); + if ($row['say_extension']) { + $ext->add($c, $row['id'], '', new ext_playback('pls-hold-while-try&to-extension')); + $ext->add($c, $row['id'], '', new ext_saydigits('${DIR_DIAL}')); + } + $ext->add($c, $row['id'], 'dial-'.$row['id'], new ext_ringing()); + $ext->add($c, $row['id'], '', new ext_goto('1','${DIR_DIAL}','from-internal')); } - $ext->add($context,'invalid', 'invalid', new ext_playback('${DIR_INVALID_RECORDING}')); - $ext->add($context,'invalid', '', new ext_ringing()); - $ext->add($context,'invalid', '', new ext_goto('${DIR_INVALID_PRI}','${DIR_INVALID_EXTEN}','${DIR_INVALID_CONTEXT}')); - $ext->add($context,'retivr', 'retivr', new ext_playback('${DIR_INVALID_RECORDING}')); - $ext->add($context,'retivr', '', new ext_goto('1','return','${IVR_CONTEXT}')); - $ext->add($context,'h', '', new ext_macro('hangupcall')); - - } - break; + $ext->add($c, 'invalid', 'invalid', new ext_playback('${DIR_INVALID_RECORDING}')); + $ext->add($c, 'invalid', '', new ext_ringing()); + $ext->add($c, 'invalid', '', new ext_goto('${DIR_INVALID_PRI}','${DIR_INVALID_EXTEN}','${DIR_INVALID_CONTEXT}')); + $ext->add($c, 'retivr', 'retivr', new ext_playback('${DIR_INVALID_RECORDING}')); + $ext->add($c, 'retivr', '', new ext_goto('1','return','${IVR_CONTEXT}')); + $ext->add($c, 'h', '', new ext_macro('hangupcall')); + } + break; } } @@ -173,15 +178,15 @@ function directory_list() { $sql='SELECT id,dirname FROM directory_details ORDER BY dirname'; - $results=sql($sql,'getAll',DB_FETCHMODE_ASSOC); - return $results; + $results=sql($sql, 'getAll', DB_FETCHMODE_ASSOC); + return $results; } function directory_get_dir_entries($id){ global $db; - if ($id == '') { - return array(); - } - $id = $db->escapeSimple($id); - $sql = "SELECT a.name, a.type, a.audio, a.dial, a.foreign_id, b.name foreign_name, IF(a.name != \"\",a.name,b.name) realname + if ($id == '') { + return array(); + } + $id = $db->escapeSimple($id); + $sql = "SELECT a.name, a.type, a.audio, a.dial, a.foreign_id, a.e_id, b.name foreign_name, IF(a.name != \"\",a.name,b.name) realname FROM directory_entries a LEFT JOIN users b ON a.foreign_id = b.extension WHERE id = $id ORDER BY realname"; $results = sql($sql,'getAll',DB_FETCHMODE_ASSOC); @@ -191,9 +196,7 @@ function directory_get_dir_details($id){ global $db; - $clean_id = $db->escapeSimple($id); - $sql="SELECT * FROM directory_details WHERE ID = $clean_id"; - $row=sql($sql,'getRow',DB_FETCHMODE_ASSOC); - $default_directory_id = sql("SELECT value FROM `admin` WHERE variable = 'default_directory' limit 1", "getOne"); - $row['default_directory'] = $default_directory_id == $id ? '1' : ''; + $clean_id = $db->escapeSimple($id); + $sql = "SELECT * FROM directory_details WHERE ID = $clean_id"; + $row = sql($sql,'getRow',DB_FETCHMODE_ASSOC); return $row; } @@ -201,89 +204,135 @@ function directory_delete($id){ global $db; - $id = $db->escapeSimple($id); + $id = $db->escapeSimple($id); sql("DELETE FROM directory_details WHERE id = $id"); sql("DELETE FROM directory_entries WHERE id = $id"); - sql("DELETE FROM `admin` WHERE variable = 'default_directory' AND value = '$id'"); + if (directory_get_default_dir() == $id) { + directory_save_default_dir(''); + } } function directory_destinations(){ global $db; - $sql='SELECT id,dirname FROM directory_details ORDER BY dirname'; - $results=sql($sql,'getAll',DB_FETCHMODE_ASSOC); + $sql = 'SELECT id,dirname FROM directory_details ORDER BY dirname'; + $results = sql($sql,'getAll',DB_FETCHMODE_ASSOC); foreach($results as $row){ - $row['dirname']=($row['dirname'])?$row['dirname']:'Directory '.$row['id'] ; + $row['dirname'] = ($row['dirname'])?$row['dirname']:'Directory '.$row['id'] ; $extens[] = array('destination' => 'directory,' . $row['id'] . ',1', 'description' => $row['dirname'], 'category' => _('Directory')); } return isset($extens)?$extens:null; +} + +function directory_draw_entries_table_header_directory() { + return array(_('Name'), _('Name Announcement'), _('Dial')); } function directory_draw_entries($id){ $sql='SELECT id,name FROM directory_entries ORDER BY name'; - $results=sql($sql,'getAll',DB_FETCHMODE_ASSOC); - $html=''; - $html.=''; - //$html.=''; - $html.=''; - $newuser='
UserNameName AnnouncementDial
NameName AnnouncementDial
'; + $headers = mod_func_iterator('draw_entries_table_header_directory'); + + $html .= ''; + foreach ($headers as $mod => $header) { + foreach ($header as $h) { + if(is_array($h)) { + $html .= ''; + } else { + $html .= ''; + + } + } + + } + $html .= ''; + + $newuser = ''; - $html.=''; - $html.=''; - $entries=directory_get_dir_entries($id); - $arraynum=1; + $newuser .= '\n"; + } + $newuser .= ''; + $html .= ''; + $html .= ''; + $entries = directory_get_dir_entries($id); foreach($entries as $e){ $realid = $e['type'] == 'custom' ? 'custom' : $e['foreign_id']; $foreign_name = $e['foreign_name'] == '' ? 'Custom Entry' : $e['foreign_name']; - $html.=directory_draw_entries_tr($realid, $e['name'],$foreign_name, $e['audio'],$e['dial'],$arraynum++); - } - $html.='
'; + $html .= $h['val']; + $html .= '' . $h . '
'._('Add new entry.').''.$newuser.'
'._('Add new entry.').''.$newuser.'
'; + $html .= directory_draw_entries_tr($id, $realid, $e['name'], $foreign_name, $e['audio'], $e['dial'], $e['e_id']); + } + $html .= ''; return $html; } //used to add row's the entry table -function directory_draw_entries_tr($realid, $name='',$foreign_name, $audio='',$num='',$id, $reuse_audio=false){ - global $amp_conf; - global $directory_draw_recordings_list;//make global, so its only drawn once - if(!$directory_draw_recordings_list){$directory_draw_recordings_list=recordings_list();} - - // if reuse_audio is true create once, used by all_users to avoid recreating each time - global $audio_select; - if (!$audio_select || !$reuse_audio) { - unset($audio_select); - $audio_select=''; - } - - if ($realid != 'custom') { - $user_type = $amp_conf['AMPEXTENSION'] == 'deviceanduser' ? 'user' : 'extension'; - $tlabel = sprintf(_("Edit %s: %s"),$user_type,$realid); - $label = ' '; - $user = ' '.$label.' '; - } else { - $user = ''; - } - $delete=''._('remove').''; - $t1_class = $name == '' ? ' class = "dpt-title" ' : ''; - $t2_class = $realid == 'custom' ? ' title="Custom Dialstring" ' : ' title="'.$realid.'" '; +function directory_draw_entries_tr($id, $realid, $name = '',$foreign_name, $audio = '',$num = '',$e_id = '', $reuse_audio = false){ + global $amp_conf, $directory_draw_recordings_list, $audio_select; + if (!$directory_draw_recordings_list) { + $directory_draw_recordings_list = recordings_list(); + } + $e_id = $e_id ? $e_id : directory_get_next_id($realid); + if (!$audio_select || !$reuse_audio) { + unset($audio_select); + $audio_select = ''; + } + + if ($realid != 'custom') { + $user_type = (isset($amp_conf['AMPEXTENSION']) && $amp_conf['AMPEXTENSION']) == 'deviceanduser' ? 'user' : 'extension'; + $tlabel = sprintf(_("Edit %s: %s"), $user_type ,$realid); + $label = ' '; + $user = ' '.$label.' '; + } else { + $user = ''; + } + $delete = ''._('remove').''; + $t1_class = $name == '' ? ' class = "dpt-title" ' : ''; + $t2_class = $realid == 'custom' ? ' title="Custom Dialstring" ' : ' title="' . $realid . '" '; if (trim($num) == '') { - $t2_class .= '" class = "dpt-title" '; - } - $html=''.$audio_select.''.$delete.$user.''; + $t2_class .= '" class = "dpt-title" '; + } + + $td[] = ''; + $td[] = $audio_select; + $td[] = ''; + $opts = array('id' => $id, 'e_id' => $e_id, 'realid' => $realid, 'name' => $name, 'audio' => $audio, 'num' => $num); + + $more_td = mod_func_iterator('draw_entries_tr_directory', $opts); + foreach ($more_td as $mod) { + foreach ($mod as $m){ + $td[] = $m; + } + } + + $td[] = $delete.$user; + + //build html + $html = ''; + foreach ($td as $t) { + if (is_array($t)) { + $html .= ''; + $html .= $t['val']; + $html .= ''; + } else { + $html .= '' . $t . ''; + } + } + $html .= ''; return $html; } @@ -293,7 +342,26 @@ $html=''; foreach(core_users_list() as $user){ - $html .= directory_draw_entries_tr($user[0], '', $user[1], 'vm', '',$id++, true); + $html .= directory_draw_entries_tr($id, $user[0], '', $user[1], 'vm', '',$id++, true); } return $html; +} + + +function directory_save_default_dir($default_directory) { + global $db; + + if ($default_directory) { + sql("REPLACE INTO `directory` (`key`, value) VALUES ('default_directory', '$default_directory')"); + } else { + sql("DELETE FROM `directory` WHERE `key` = 'default_directory'"); + } +} + +function directory_get_default_dir() { + global $db; + + $ret = sql("SELECT value FROM `directory` WHERE `key` = 'default_directory'", 'getOne'); + return $ret ? $ret : ''; + } @@ -301,47 +369,34 @@ // function directory_save_dir_details($vals){ - global $db; - global $amp_conf; - - foreach($vals as $key => $value) { - $vals[$key] = $db->escapeSimple($value); - } - if (isset($vals['default_directory'])) { - $default_directory = $vals['default_directory']; - unset($vals['default_directory']); - } else { - $default_directory = false; - } - - if ($vals['id']) { - $sql='REPLACE INTO directory_details (id,dirname,description,announcement, + global $db, $amp_conf; + + foreach($vals as $key => $value) { + $vals[$key] = $db->escapeSimple($value); + } + + if ($vals['id']) { + $sql = 'REPLACE INTO directory_details (id,dirname,description,announcement, callid_prefix,alert_info,repeat_loops,repeat_recording, invalid_recording,invalid_destination,retivr,say_extension) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; - $foo=$db->query($sql,$vals); - if(DB::IsError($foo)) { - die_freepbx(print_r($vals,true).' '.$foo->getDebugInfo()); - } - } else { - unset($vals['id']); - $sql='INSERT INTO directory_details (dirname,description,announcement, + $foo = $db->query($sql,$vals); + if(DB::IsError($foo)) { + die_freepbx(print_r($vals,true).' '.$foo->getDebugInfo()); + } + } else { + unset($vals['id']); + $sql = 'INSERT INTO directory_details (dirname,description,announcement, callid_prefix,alert_info,repeat_loops,repeat_recording, invalid_recording,invalid_destination,retivr,say_extension) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; - $foo=$db->query($sql,$vals); - if(DB::IsError($foo)) { - die_freepbx(print_r($vals,true).' '.$foo->getDebugInfo()); - } - $sql=(($amp_conf["AMPDBENGINE"]=="sqlite3")?'SELECT last_insert_rowid()':'SELECT LAST_INSERT_ID()'); - $vals['id']=$db->getOne($sql); - if (DB::IsError($foo)){ - die_freepbx($foo->getDebugInfo()); - } - } - - if ($default_directory) { - sql("REPLACE INTO `admin` (variable, value) VALUES ('default_directory', '{$vals['id']}')"); - } else { - sql("DELETE FROM `admin` WHERE variable = 'default_directory' AND value = '{$vals['id']}'"); + $foo = $db->query($sql,$vals); + if(DB::IsError($foo)) { + die_freepbx(print_r($vals,true).' '.$foo->getDebugInfo()); + } + $sql = ( ($amp_conf["AMPDBENGINE"]=="sqlite3") ? 'SELECT last_insert_rowid()' : 'SELECT LAST_INSERT_ID()'); + $vals['id'] = $db->getOne($sql); + if (DB::IsError($foo)){ + die_freepbx($foo->getDebugInfo()); + } } @@ -351,14 +406,13 @@ function directory_save_dir_entries($id,$entries){ global $db; - $id = $db->escapeSimple($id); - + $id = $db->escapeSimple($id); sql("DELETE FROM directory_entries WHERE id = $id"); - //TODO = prepare the data: - // if 'dial' is the same as type_id, then delete the 'dial,' leave as default - // if 'name' is same as default_name, then delete the 'name,' leave as default + //TODO = prepare the data: + // if 'dial' is the same as type_id, then delete the 'dial,' leave as default + // if 'name' is same as default_name, then delete the 'name,' leave as default if($entries){ $insert=''; - // TODO: should we change to perpare/execute ? + // TODO: should we change to perpare/execute ? foreach($entries as $idx => $row){ if($row['foreign_id'] == 'custom' && trim($row['name']) == '' || $row['foreign_id']==''){ @@ -372,11 +426,11 @@ $foreign_id = $db->escapeSimple($row['foreign_id']); } - $audio = $row['audio'] != '' ? $db->escapeSimple($row['audio']) : ($row['foreign_id'] == 'custom' ? 'tts' : 'vm'); - if (!empty($insert)) { - $insert .= ','; - } - $insert.='("'.$id.'","'.$db->escapeSimple(trim($row['name'])).'","'.$type.'","'.$foreign_id.'","'.$audio.'","'.$db->escapeSimple(trim($row['num'])).'")'; + $audio = $row['audio'] != '' ? $db->escapeSimple($row['audio']) : ($row['foreign_id'] == 'custom' ? 'tts' : 'vm'); + if (!empty($insert)) { + $insert .= ','; + } + $insert.='("'.$id.'","'.$idx.'","'.$db->escapeSimple(trim($row['name'])).'","'.$type.'","'.$foreign_id.'","'.$audio.'","'.$db->escapeSimple(trim($row['num'])).'")'; } - sql('INSERT INTO directory_entries (id,name,type,foreign_id,audio,dial) VALUES '.$insert); + sql('INSERT INTO directory_entries (id, e_id, name,type,foreign_id,audio,dial) VALUES '.$insert); } } @@ -386,5 +440,6 @@ function directory_check_default($extension) { - $sql = "SELECT foreign_id FROM directory_entries WHERE foreign_id = '$extension' AND id = (SELECT value FROM admin WHERE variable = 'default_directory' LIMIT 1) LIMIT 1"; + $def_dir = directory_get_default_dir(); + $sql = "SELECT foreign_id FROM directory_entries WHERE foreign_id = '$extension' AND id = '$def_dir' LIMIT 1"; $results = sql($sql,"getAll"); return count($results); @@ -392,13 +447,13 @@ function directory_set_default($extension, $value) { - $default_directory_id = sql("SELECT value FROM `admin` WHERE variable = 'default_directory' limit 1", "getOne"); + $default_directory_id = directory_get_default_dir(); if ($default_directory_id == '') { return false; } - if ($value) { - sql("REPLACE INTO directory_entries (id, foreign_id) VALUES ($default_directory_id, '$extension')"); - } else { - sql("DELETE FROM directory_entries WHERE id = $default_directory_id AND foreign_id = '$extension'"); - } + if ($value) { + sql("REPLACE INTO directory_entries (id, foreign_id) VALUES ($default_directory_id, '$extension')"); + } else { + sql("DELETE FROM directory_entries WHERE id = $default_directory_id AND foreign_id = '$extension'"); + } } @@ -426,5 +481,5 @@ if ($action != 'del') { - $default_directory_id = sql("SELECT value FROM `admin` WHERE variable = 'default_directory'", "getOne"); + $default_directory_id = directory_get_default_dir(); $section = _("Default Group Inclusion"); if ($default_directory_id != "") { @@ -440,10 +495,10 @@ //create vars from the request // - $action = isset($_REQUEST['action'])?$_REQUEST['action']:null; - $ext = isset($_REQUEST['extdisplay'])?$_REQUEST['extdisplay']:null; - $extn = isset($_REQUEST['extension'])?$_REQUEST['extension']:null; - $in_default_directory = isset($_REQUEST['in_default_directory'])?$_REQUEST['in_default_directory']:false; - - $extdisplay = ($ext==='') ? $extn : $ext; + $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null; + $ext = isset($_REQUEST['extdisplay']) ? $_REQUEST['extdisplay'] : null; + $extn = isset($_REQUEST['extension']) ? $_REQUEST['extension'] : null; + $in_default_directory = isset($_REQUEST['in_default_directory']) ? $_REQUEST['in_default_directory'] : false; + + $extdisplay = ($ext === '') ? $extn : $ext; if (($action == "add" || $action == "edit")) { @@ -473,13 +528,13 @@ $sql .= "WHERE invalid_destination in ('".implode("','",$dest)."')"; } - $results = sql($sql,"getAll",DB_FETCHMODE_ASSOC); + $results = sql($sql, "getAll", DB_FETCHMODE_ASSOC); foreach ($results as $result) { - $thisdest = $result['invalid_destination']; - $thisid = $result['id']; - $destlist[] = array( + $thisdest = $result['invalid_destination']; + $thisid = $result['id']; + $destlist[] = array( 'dest' => $thisdest, - 'description' => sprintf(_("Directory: %s "),($result['dirname']?$result['dirname']:$result['id'])), - 'edit_url' => 'config.php?display=directory&id='.urlencode($result['id']), + 'description' => sprintf(_("Directory: %s "), ($result['dirname'] ? $result['dirname'] : $result['id'])), + 'edit_url' => 'config.php?display=directory&id=' . urlencode($result['id']), ); } @@ -500,7 +555,7 @@ return array(); } else { - return array('description' => sprintf(_("Directory %s: "),($thisdir['dirname']?$thisdir['dirname']:$id)), - 'edit_url' => 'config.php?display=directory&id='.urlencode($id), - ); + return array('description' => sprintf(_("Directory %s: "), ($thisdir['dirname'] ? $thisdir['dirname'] : $id)), + 'edit_url' => 'config.php?display=directory&id=' . urlencode($id), + ); } } else { @@ -509,12 +564,18 @@ } +function directory_get_next_id($realid) { + global $db; + $res = sql('SELECT MAX(e_id) FROM directory_entries WHERE id = "' . $realid . '"', 'getOne'); + return $res ? $res : 1; +} + function directory_recordings_usage($recording_id) { global $active_modules; $results = sql("SELECT `id`, `dirname` FROM `directory_details` - WHERE `announcement` = '$recording_id' - OR `repeat_recording` = '$recording_id' - OR `invalid_recording` = '$recording_id'", - "getAll",DB_FETCHMODE_ASSOC); + WHERE `announcement` = '$recording_id' + OR `repeat_recording` = '$recording_id' + OR `invalid_recording` = '$recording_id'", + "getAll",DB_FETCHMODE_ASSOC); if (empty($results)) { return array(); @@ -523,6 +584,6 @@ foreach ($results as $result) { $usage_arr[] = array( - 'url_query' => 'config.php?display=directory&id='.urlencode($result['id']), - 'description' => sprintf(_("Directory: %s"),($result['dirname']?$result['dirname']:$result['id'])), + 'url_query' => 'config.php?display=directory&id=' . urlencode($result['id']), + 'description' => sprintf(_("Directory: %s"), ($result['dirname'] ? $result['dirname'] : $result['id'])), ); } @@ -531,7 +592,3 @@ } -function directory_change_destination($old_dest, $new_dest) { - $sql = 'UPDATE directory_details SET invalid_destination = "' . $new_dest . '" WHERE invalid_destination = "' . $old_dest . '"'; - sql($sql, "query"); -} ?> Index: /modules/branches/bootstrap-2.9/directory/install.php =================================================================== --- /modules/branches/bootstrap-2.9/directory/install.php (revision 9882) +++ /modules/branches/bootstrap-2.9/directory/install.php (revision 10795) @@ -19,5 +19,5 @@ outn(_('Adding directory_details table if needed...')); -$sql = "CREATE TABLE IF NOT EXISTS directory_details ( +$sql[] = "CREATE TABLE IF NOT EXISTS directory_details ( id INT NOT NULL PRIMARY KEY $autoincrement, dirname varchar(50), @@ -34,14 +34,6 @@ )"; -$check = $db->query($sql); -if (DB::IsError($check)) { - out(_('failed')); - out(_('Can not create `directory_details` table: ') . $check->getMessage()); - return false; -} -out(_('ok')); -outn(_('Adding directory_entries table if needed...')); - -$sql = "CREATE TABLE IF NOT EXISTS directory_entries ( + +$sql[] = "CREATE TABLE IF NOT EXISTS directory_entries ( id INT NOT NULL, name varchar(50), @@ -50,12 +42,18 @@ audio varchar(50), dial varchar(50) default '' -);"; - -$check = $db->query($sql); -if (DB::IsError($check)) { - out(_('failed')); - out(_('Can not create `directory_entries` table: ') . $check->getMessage()); -} -out(_('ok')); + )"; + +$sql[] = "CREATE TABLE IF NOT EXISTS directory ( + `key` varchar(50) UNIQUE key, + `value` varchar(150) + )"; + +foreach ($sql as $s) { + $do = $db->query($s); + if (DB::IsError($do)) { + out(_('Can not create table: ') . $check->getMessage()); + return false; + } +} $sql = "SELECT say_extension FROM directory_details"; @@ -77,5 +75,5 @@ $check = $db->getRow($sql, DB_FETCHMODE_ASSOC); if(!DB::IsError($check)) { -outn(_("dropping valid_details field..")); + outn(_("dropping valid_details field..")); $sql = "ALTER TABLE `directory_details` DROP `valid_recording`"; $result = $db->query($sql); @@ -86,3 +84,273 @@ } } + +// +//add e_id field if it doesnt already exists +// +$sql = 'SHOW COLUMNS FROM directory_entries LIKE "e_id"'; +$res = $db->getAll($sql); +//check to see if the field already exists +if (count($res) == 0) { + //if not add it + $sql = 'ALTER TABLE directory_entries ADD COLUMN e_id INT AFTER id'; + $do = $db->query($sql); + if(DB::IsError($do)) { + out(_("cannot add field e_id to table directory_entries \n" . $do->getDebugInfo())); + } else { + out(_("e_id added to table directory_entries")); + } + //get ALL directory entires + $sql = 'SELECT * FROM directory_entries'; + $de = $db->getAll($sql, DB_FETCHMODE_ASSOC); + $count = array(); + foreach($de as $d => $e) { + if (!isset($count[$e['id']]) || $count[$e['id']] == '') { + //set id and delete all entires for this ivr. This only gets run once per ivr + $count[$e['id']] = 1; + sql('DELETE FROM directory_entries WHERE id = "' . $e['id'] . '"'); + } else { + $count[$e['id']]++; + } + $de[$d]['e_id'] = $count[$e['id']]; + //update entire + $sql = 'INSERT INTO directory_entries (id, e_id, name, type, foreign_id, audio, dial) VALUES (?, ?, ?, ?, ?, ?, ?)'; + $do = $db->query($sql, $de[$d]); + if(DB::IsError($do)) { + out(_('cannot set e_id for directory_id = ' . $e['id'] . '. Please resubmit this directory manually to correct this issue.')); + } + } +} + +//move defualt dir info in to directory table +$defdir = $db->getOne("SELECT value FROM `admin` WHERE `key` = 'default_directory'"); +if (isset($defdir) && $defdir) { + $q = $db->query("REPLACE INTO `directory` (`key`, value) VALUES ('default_directory', '$defdir')"); + if(DB::IsError($q)) { + die_freepbx(_('Error migrating to new directory! ERROR: Unable to migrate. The default directory setting. You may need to reset this manually. ' . $q->getDebugInfo())); + } + $db->query("DELETE FROM `admin` WHERE variable = 'default_directory"); +} + +//check to see if there is a need to migrate from legacy directory +$migrated = $db->getOne("SELECT value FROM `directory` WHERE `key` = 'directory28_migrated'"); + + +if (!$migrated) { + //migrate legacy directories to new directory + //get a list of vm users + $vmconf = null; + $section = null; + $vmusers = array(); + parse_voicemailconf_directory_migration(rtrim($amp_conf["ASTETCDIR"],"/")."/voicemail.conf", $vmconf, $section); + if (isset($vmconf) && $vmconf) { + foreach ($vmconf['default'] as $ext => $vm) { + $vmusers[$ext] = $vm['name']; + } + } + + + //create a new directory if we have voicemail users + if (isset($vmusers) && $vmusers) { + out(_("Migrating Directory")); + //TODO: make this the default directory + $vals = array('Migrated Directory', '', '0', '', '', '2', + '0', '0', 'app-blackhole,hangup,1', '', '1'); + $sql = 'INSERT INTO directory_details (dirname, description, announcement, + callid_prefix, alert_info, repeat_loops, repeat_recording, + invalid_recording, invalid_destination, retivr, say_extension) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; + $new = $db->query($sql, $vals); + if(DB::IsError($new)) { + die_freepbx(_('Error migrating to new directory! ERROR: Could not create new Directory.' . $new->getDebugInfo())); + } + //get the id of the new directory + $sql = ( ($amp_conf["AMPDBENGINE"] == "sqlite3") ? 'SELECT last_insert_rowid()' : 'SELECT LAST_INSERT_ID()'); + $newdir = $db->getOne($sql); + $dirdest = 'directory,' . $newdir . ',1'; + + //insert all system users to the new directory, + //Just insert their ext. number, everythign else will be handeled automatically by directory + $e_id = 0; + foreach ($vmusers as $ext => $user) { + $vals = array($newdir, $e_id++, 'user', $ext, 'vm'); + $sql = 'INSERT INTO directory_entries (id, e_id, type, foreign_id, audio) + VALUES (?, ?, ?, ?, ?)'; + $q = $db->query($sql, $vals); + if(DB::IsError($q)) { + die_freepbx(_('Error migrating to new directory! ERROR: Could not populate new Directory ' . $q->getDebugInfo())); + } + } + + //set as defualt directory + if (!isset($def_dir) || !$def_dir) { + out(_("Setting migrated directory as defualt")); + $sql = 'REPLACE INTO `directory` (`key`, value) VALUES ("default_directory", ?)'; + $db->query($sql, $newdir); + } + } + + + //check to see if were using the directory in ivr's + $count = $db->getOne('SELECT count(*) FROM ivr WHERE displayname != "__install_done"'); + if(DB::IsError($count)) { + die_freepbx(_('Error migrating to new directory! ERROR: Could not get count of Ivr\'s using the legacy Directory ' . $q->getDebugInfo())); + } + + //Migrate ivr's if we have ivr's using directory + if ($count > 0) { + out(_("Migrating Ivr's to new Directory")); + //if we were able to set a new directory + if (isset($newdir) && $newdir){ + //get al ivr's + $ivrs = $db->getAll('SELECT * FROM ivr WHERE displayname != "__install_done"', DB_FETCHMODE_ASSOC); + if(DB::IsError($ivrs)) { + die_freepbx(_('Error migrating to new directory! ERROR: Could not get all Ivr\'s')); + } + + //get misc destinations that might be referencing legacy directory + $miscdests = $db->getAll('SELECT id FROM miscdests WHERE destdial = "{infoservices:directory}"'); + foreach ($miscdests as $m) { + $miscdest[] = 'ext-miscdests,' . $m[0] . ',1'; + } + //iterate over ivr's and their entries, looking for a misc apps that might be legacy directory or a # dest + foreach ($ivrs as $ivr) { + out(_("Migrating Ivr " . $ivr['displayname'] . "'s entires to new Directory")); + + //is this ivr set to use directory? + $true_opts = array('1', 'on', 'ON', 'CHECKED', 'checked', 'TRUE', 'true'); + if (in_array($ivr['enable_directory'], $true_opts)) { + out(_("Removing legacy Directory from Ivr " . $ivr['displayname'] . "'s destinations")); + + //update ivr dests + $sql = 'UPDATE ivr_dests SET dest = ? WHERE ivr_id = ? AND '; + //add misc diests if we have any + if (isset($miscdest) && $miscdest) { + $sql .= ' (selection = "#" '; + $m = array(); + foreach ($miscdest as $md) { + $m[] = '"' . $md . '"'; + } + $sql .= ' OR dest IN(' . implode(',', $m) . ') )'; + } else { + $sql .= ' selection = "#" '; + } + $q = $db->query($sql, array($dirdest, $ivr['ivr_id'])); + if(DB::IsError($q)) { + die_freepbx(_('Error migrating to new directory! ERROR: Failed to update ivr destinations ' . $q->getDebugInfo())); + } + + + //check to ensure that we have a # destination + $sql = 'SELECT COUNT(*) FROM ivr_dests WHERE ivr_id = ? AND selection = "#"'; + $pound_count = $db->getOne($sql, array($ivr['ivr_id'])); + + if ($pound_count < 1) { + $sql = 'INSERT INTO ivr_dests (ivr_id, selection, dest) VALUES (?, ?, ?)'; + $q = $db->query($sql, array($ivr['ivr_id'], '#', $dirdest)); + if(DB::IsError($q)) { + die_freepbx(_('Error migrating to new directory! ERROR: Failed to add ivr destination # ' . $q->getDebugInfo())); + } + } + + //remove the legacy directroy option from this ivr + $sql = 'UPDATE ivr SET enable_directory = "" WHERE ivr_id = ?'; + $q = $db->query($sql, array($ivr['ivr_id'])); + if(DB::IsError($q)) { + die_freepbx(_('Error migrating to new directory! ERROR: Failed to unset enable_directory from ivr ' . $q->getDebugInfo())); + } + } else {//even if it wasnt set to use the legace directory, ensure that we dont have mics dests pointing at it + if (isset($miscdest) && $miscdest) { + $sql = 'UPDATE ivr_dests SET dest = ? WHERE ivr_id = ? AND dest'; + $m = array(); + foreach ($miscdest as $md) { + $m[] = '"' . $md . '"'; + } + $sql .= ' IN(' . implode(',', $m) . ')'; + $q = $db->query($sql, array($dirdest, $ivr['ivr_id'])); + if(DB::IsError($q)) { + die_freepbx(_('Error migrating to new directory! ERROR: Failed to update ivr destinations (2) ' . $q->getDebugInfo())); + } + } + } + }//<--- end ivr foreach loop + } else { //if we dont have/couldnt create a new directory, assume there are no vm users and disable the option from ivr's + out(_("Removing legacy Directory from Ivr " . $ivr['displayname'])); + $q = $db->query('UPDATE ivr SET enable_directory = ""'); + if(DB::IsError($q)) { + die_freepbx(_('Error migrating to new directory! ERROR: Failed to unset enable_directory from ivr (2) ' . $q->getDebugInfo())); + } + } + }//<--- end ivr if case + + //TODO: migrate misc dests if any are using legacy directory + + //Seem where done with migration - mark that in the database + $migrated_dir = (isset($newdir) && $newdir) ? $newdir : 'true'; + $q = $db->query("REPLACE INTO `directory` (`key`, value) VALUES ('directory28_migrated', '$migrated_dir')"); + if(DB::IsError($q)) { + die_freepbx(_('Error migrating to new directory! ERROR: Unable to mark Directory as migrated. Migration will probobly be run again at next install/upgrade of this module. ' . $q->getDebugInfo())); + } + out(_('Migration Complete!')); +} + +/** Recursively read voicemail.conf (and any included files) + * This function coppied from functions.inc.php + */ +function parse_voicemailconf_directory_migration($filename, &$vmconf, &$section) { + if (is_null($vmconf)) { + $vmconf = array(); + } + if (is_null($section)) { + $section = "general"; + } + + if (file_exists($filename)) { + $fd = fopen($filename, "r"); + while ($line = fgets($fd, 1024)) { + if (preg_match("/^\s*(\d+)\s*=>\s*(\d*),(.*),(.*),(.*),(.*)\s*([;#].*)?/",$line,$matches)) { + // "mailbox=>password,name,email,pager,options" + // this is a voicemail line + $vmconf[$section][ $matches[1] ] = array("mailbox"=>$matches[1], + "pwd"=>$matches[2], + "name"=>$matches[3], + "email"=>$matches[4], + "pager"=>$matches[5], + "options"=>array(), + ); + + // parse options + //output($matches); + foreach (explode("|",$matches[6]) as $opt) { + $temp = explode("=",$opt); + //output($temp); + if (isset($temp[1])) { + list($key,$value) = $temp; + $vmconf[$section][ $matches[1] ]["options"][$key] = $value; + } + } + } else if (preg_match('/^(?:\s*)#include(?:\s+)["\']{0,1}([^"\']*)["\']{0,1}(\s*[;#].*)?$/',$line,$matches)) { + // include another file + + if ($matches[1][0] == "/") { + // absolute path + $filename = trim($matches[1]); + } else { + // relative path + $filename = dirname($filename)."/".trim($matches[1]); + } + + parse_voicemailconf_directory_migration($filename, $vmconf, $section); + + } else if (preg_match("/^\s*\[(.+)\]/",$line,$matches)) { + // section name + $section = strtolower($matches[1]); + } else if (preg_match("/^\s*([a-zA-Z0-9-_]+)\s*=\s*(.*?)\s*([;#].*)?$/",$line,$matches)) { + // name = value + // option line + $vmconf[$section][ $matches[1] ] = $matches[2]; + } + } + fclose($fd); + } +} ?>