Changeset 10795
- Timestamp:
- 01/04/11 16:17:36 (2 years ago)
- Files:
-
- modules/branches/bootstrap-2.9/directory/agi-bin/directory.agi (modified) (10 diffs)
- modules/branches/bootstrap-2.9/directory/agi-bin/directory.lib.php (modified) (10 diffs)
- modules/branches/bootstrap-2.9/directory/functions.inc.php (modified) (26 diffs)
- modules/branches/bootstrap-2.9/directory/install.php (modified) (5 diffs)
- modules/branches/bootstrap-2.9/directory/page.directory.php (modified) (6 diffs)
- modules/branches/bootstrap-2.9/directory/uninstall.php (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
modules/branches/bootstrap-2.9/directory/agi-bin/directory.agi
r10753 r10795 2 2 <?php 3 3 error_reporting(1); 4 set_error_handler("error_handler");5 6 verbose('entered dir!',6);7 4 require_once(dirname(__FILE__).'/directory.lib.php'); 8 $loopcounter1 = 0; 9 $loopcounter2 = 0; 10 $matches = false; 11 $matches = false; 12 $needs_welcome = true; 13 $search = array(); 14 $dir = new Dir(); 15 16 while ($loopcounter1 <= $dir->dir['repeat_loops']) { 5 $loopcounter1=$loopcounter2=0; 6 $matches=false; 7 $search=array(); 8 $dir=new Dir(); 9 $matches = false; 10 $needs_welcome = true; 11 12 if ($dir->agivar['keypress']) { 13 $needs_welcome = false; 14 $search = $dir->agivar['keypress']; 15 $matches = true; 16 } 17 18 while($loopcounter1 <= $dir->dir['repeat_loops']){ 17 19 //get inital search term 18 while ($loopcounter2 <= $dir->dir['repeat_loops'] && !$matches ){20 while($loopcounter2 <= $dir->dir['repeat_loops'] && !$matches ){ 19 21 //get any number of digits, terminated by timeout or # 20 $buffer = '';21 if ($needs_welcome) {22 $needs_welcome = false;23 $search = $dir->agi->fastpass_get_data($buffer, 'cdir-welcome',100,3);24 if ((strlen($buffer) < 3) && (strstr($search['result'],'0') === false)) {25 $search = $dir->agi->fastpass_get_data($buffer, $dir->dir['announcement'], 3000,3);26 }27 } else {28 $search = $dir->agi->fastpass_get_data($buffer, $dir->dir['announcement'],3000,3);22 $buffer = ''; 23 if ($needs_welcome) { 24 $needs_welcome = false; 25 $search = $dir->agi->fastpass_get_data($buffer, 'cdir-welcome',100,3); 26 if ((strlen($buffer) < 3) && (strstr($search['result'],'0') === false)) { 27 $search = $dir->agi->fastpass_get_data($buffer, $dir->dir['announcement'],3000,3); 28 } 29 } else { 30 $search = $dir->agi->fastpass_get_data($buffer, $dir->dir['announcement'], 3000, 3); 29 31 } 30 32 $search = $search['result'];//being set so we can use it later … … 33 35 } 34 36 //hangup if we failed to receive anything meanigfull 35 if ($loopcounter2 == 3){//seem like we ran out of tries...37 if($loopcounter2 == 3){//seem like we ran out of tries... 36 38 $dir->agi->stream_file('sorry-youre-having-problems'); 37 $dir->bail();39 $dir->bail(); 38 40 break; 39 41 } … … 42 44 //prompt the caller for more info if there are too many results (and he didnt terminate with #) 43 45 44 while($matches > 1 && $matchesloop < $dir->dir['repeat_loops'] && substr($search,-1)!='#'){ 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++; 46 while ($matches > 1 && $matchesloop < $dir->dir['repeat_loops'] && substr($search,-1)!='#') { 47 if ($matches < 10) { 48 $compound = array('silence/1','cdir-there-are',(integer)$matches,'cdir-matching-entries-or-pound'); 49 $validdigits = '1234567890#'; 50 } else { 51 // don't allow #, get new recording that indicates such 52 $compound = array('silence/1','cdir-there-are',(integer)$matches,'cdir-matching-entries-continue'); 53 $validdigits = '1234567890'; 54 } 55 $press=$dir->getKeypress($compound, $validdigits, 3000); 56 if(!empty($press['result']) || $press==0){ 57 $search.=$press['result']; 58 $matches=$dir->search($search,1); 59 if ($matches > 9) { 60 $search = rtrim($search,'#'); 61 dbug("Too many found: $matches, remove # if set and try again"); 63 62 } 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 } 63 }else{ 64 $matchesloop++; 65 } 66 // if they timeout and there are 3 or fewer matches then just play them 67 if (empty($press['result']) && $matches <=3) { 68 break; 69 } 68 70 } 69 71 70 72 //act based on the amount of matches 71 if ($matches > 1 && $matches <= 9){73 if($matches > 1 && $matches <= 9){ 72 74 //draw up variable of valid key presses 73 $validkeys ='';74 for ($i=1; $i < $matches+1; $i++) {75 $validkeys=''; 76 for ($i=1; $i<$matches+1; $i++) { 75 77 $validkeys .= $i; 76 78 } 77 verbose("valid keys for entries are: $validkeys",6);79 dbug("valid keys for entries are: $validkeys"); 78 80 79 81 //playback entries 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'])) { 82 $matches=$dir->search($search); 83 foreach($matches as $idx => $match){ 84 $ret=$dir->getKeypress('for',$validkeys,0);if(trim($ret['result'])){break;} 85 $ret=$dir->readContact($matches[$idx],$validkeys,0);if(trim($ret['result'])){break;} 86 $ret=$dir->getKeypress('press',$validkeys,0);if(trim($ret['result'])){;break;} 87 $ret=$dir->agi->say_digits($idx+1,$validkeys);if(trim($ret['result'])){$ret['result']=chr($ret['result']);break;} 88 } 89 dbug("got result: ".$ret['result']); 90 if(trim($ret['result'])){ 108 91 call($matches[$ret['result']-1]); 109 92 } 110 } elseif ($matches==1) { 93 $dir->agi->wait_for_digit(10000); 94 } elseif($matches == 1) { 111 95 //call person $macthes[0]; 112 $matches =$dir->search($search);96 $matches=$dir->search($search); 113 97 call($matches[0]); 114 98 } else { … … 119 103 } 120 104 121 if ($loopcounter1){105 if ($loopcounter1) { 122 106 $dir->bail(); 123 107 } … … 126 110 global $dir; 127 111 $dir->readContact($contact,$validkeys,0); 128 if ($dir->dir['alert_info'] != ''){112 if($dir->dir['alert_info'] != ''){ 129 113 $dir->agi->set_alertinfo($dir->dir['alert_info']); 130 114 } 131 if ($dir->dir['callid_prefix'] != ''){115 if($dir->dir['callid_prefix'] != ''){ 132 116 $dir->agi->set_variable('CALLERID(name)',$dir->dir['callid_prefix'].$dir->dir['calleridname']); 133 117 } … … 136 120 } 137 121 138 //send debug to asterisk cli 139 function verbose($string, $level=3){ 140 global $dir; 141 $dir->agi->verbose($string, $level); 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 */ 122 /* 123 * FreePBX dbuging function 124 * This function can be called as follows: 125 * dbug() - will just print a time stamp to the dbug log file ($amp_conf['FPBXDBUGFILE']) 126 * dbug('string') - same as above + will print the string 127 * dbug('string',$array) - same as above + will print_r the array after the message 128 * dbug($array) - will print_r the array with no message (just a time stamp) 129 * dbug('string',$array,1) - same as above + will var_dump the array 130 * dbug($array,1) - will var_dump the array with no message (just a time stamp) 131 * 132 */ 133 158 134 function dbug(){ 159 135 $opts = func_get_args(); … … 181 157 } 182 158 183 if ( isset($disc) &&$disc) {159 if ($disc) { 184 160 $disc = ' \'' . $disc . '\':'; 185 161 } … … 189 165 . "\t" . $bt[0]['file'] . ':' . $bt[0]['line'] 190 166 . "\n\n" 191 . (isset($disc) ? $disc : '' )167 . $disc 192 168 . "\n"; //add timestamp + file info 193 169 dbug_write($txt); … … 206 182 207 183 function dbug_write($txt,$check=''){ 184 global $amp_conf; 208 185 $append=false; 209 186 //optionaly ensure that dbug file is smaller than $max_size … … 224 201 if ($errno == 2048){return;} //keeps out erros related to pear::db 225 202 $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"; 203 $error .= date("Y-M-d H:i:s").$disc."\n"; //add timestamp 204 $error .= 'Error Number '.$errno.": ".$errstr."\n"; 205 $error .= 'In file: '.$errfile."\n"; 206 $error .= 'At line number: '.$errline."\n"; 229 207 //$error .= print_r($errcontext)."\n"; 230 dbug_write($error); 231 } 208 file_put_contents('/tmp/freepbx_debug.log',$error, FILE_APPEND); 209 } 210 set_error_handler("error_handler"); 232 211 ?> modules/branches/bootstrap-2.9/directory/agi-bin/directory.lib.php
r10753 r10795 3 3 //agi class handler 4 4 var $agi; 5 6 5 //inital agi pased variables 7 6 var $agivar; 8 9 7 //asterisk manager class handler 10 8 var $ami; 11 12 9 //pear::db database object handel 13 10 var $db; 14 15 11 //options of the directory that we are currently working with 16 12 var $dir; 17 18 13 //the current directory that we are working with 19 14 var $directory; 20 21 15 //string we are searching for 22 16 var $searchstring; 23 24 17 //TODO: what is this var for? 25 18 var $vmbasedir=''; 26 19 27 20 //PHP4 comaptibility constructor 28 function Dir(){29 $this->__construct();30 }21 function Dir(){ 22 $this->__construct(); 23 } 31 24 32 25 //this function is run by php automaticly when the class is initalized … … 43 36 function __construct_agi(){ 44 37 require_once('phpagi.php'); 45 $agi =new AGI();46 foreach ($agi->request as $key => $value){//strip agi_ prefix from keys47 if (substr($key,0,4)=='agi_'){38 $agi=new AGI(); 39 foreach($agi->request as $key => $value){//strip agi_ prefix from keys 40 if(substr($key,0,4)=='agi_'){ 48 41 $opts[substr($key,4)]=$value; 49 42 } 50 43 } 51 44 52 foreach ($opts as $key => $value){//get passed in vars53 if (substr($key,0,4)=='arg_'){54 $expld =explode('=',$value);55 $opts[$expld[0]] =$expld[1];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]; 56 49 unset($opts[$key]); 57 50 } … … 59 52 60 53 array_shift($_SERVER['argv']); 61 foreach ($_SERVER['argv'] as $arg){62 $arg =explode('=',$arg);54 foreach($_SERVER['argv'] as $arg){ 55 $arg=explode('=',$arg); 63 56 //remove leading '--' 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; 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; 70 61 return $agi; 71 62 } … … 74 65 function __construct_ami(){ 75 66 require_once('phpagi-asmanager.php'); 76 $ami =new AGI_AsteriskManager();67 $ami=new AGI_AsteriskManager(); 77 68 return $ami; 78 69 } … … 83 74 function __construct_db(){ 84 75 require_once("DB.php"); 85 $dsn =array(76 $dsn=array( 86 77 'phptype' => $this->agi_get_var('AMPDBENGINE'), 87 78 'hostspec' => $this->agi_get_var('AMPDBHOST'), … … 90 81 'password' => $this->agi_get_var('AMPDBPASS'), 91 82 ); 92 $db =DB::connect($dsn);83 $db=DB::connect($dsn); 93 84 return $db; 94 85 } … … 97 88 // TODO: handle getRow failures 98 89 function __construct_dir_opts(){ 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 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 // 104 96 if ($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'].')';97 $sql='SELECT id, filename from recordings where id in ('.$row['announcement'].','.$row['repeat_recording'].','.$row['invalid_recording'].')'; 106 98 $res=$this->db->getAll($sql,DB_FETCHMODE_ASSOC); 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 all114 $rec_file[$entry['id']] = $entry['filename'];115 }116 unset($res);117 }99 if(DB::IsError($res)) { 100 dbug("FATAL: got error from getAll query",1); 101 dbug($res->getdbugInfo()); 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 } 118 110 $row['announcement'] = $row['announcement']&&isset($rec_file[$row['announcement']])?$rec_file[$row['announcement']]:'cdir-please-enter-first-three'; 119 111 $row['repeat_recording'] = $row['repeat_recording']&&isset($rec_file[$row['repeat_recording']])?$rec_file[$row['repeat_recording']]:'cdir-sorry-no-entries'; … … 138 130 } 139 131 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 } 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 } 163 154 } 164 155 … … 166 157 switch($con['audio']){ 167 158 case 'vm': 168 $vm_dir = $this->agi->database_get('AMPUSER',$con['dial'].'/voicemail'); 159 160 $vm_dir = $this->agi->database_get('AMPUSER',$con['dial'].'/voicemail'); 169 161 $vm_dir = $vm_dir['data']; 170 verbose("got directory $vm_dir for user {$con['dial']}",6); 162 dbug("got directory $vm_dir for user {$con['dial']}",6); 163 171 164 //check to see if we have a greet.* and play it. otherwise, fallback to spelling the name 172 if ($vm_dir && $vm_dir != 'novm') { 165 166 if ($vm_dir && $vm_dir != 'novm') { 173 167 if (!$this->vmbasedir) { 174 168 $this->vmbasedir = $this->agi_get_var('ASTSPOOLDIR').'/voicemail/'; 175 169 } 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 } 170 $dir=scandir($this->vmbasedir.$vm_dir.'/'.$con['dial']); 171 foreach($dir as $file){ 172 dbug("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 } 188 180 //fallthough if not successfull 189 181 case 'spell': … … 191 183 switch(true){ 192 184 case ctype_alpha($char): 193 $ret =$this->agi->evaluate('SAY ALPHA '.$char.' '.$keys);194 //dbug("returned from SAY ALPHA with code/result {$ret['code']}/{$ret['result']}",6);185 $ret=$this->agi->evaluate('SAY ALPHA '.$char.' '.$keys); 186 dbug("returned from SAY ALPHA with code/result {$ret['code']}/{$ret['result']}",6); 195 187 break; 196 188 case ctype_digit($char): 197 $ret =$this->agi->say_digits($char, $keys);189 $ret=$this->agi->say_digits($char, $keys); 198 190 break; 199 191 case ctype_space($char)://pause 200 $ret =$this->agi->wait_for_digit(750);192 $ret=$this->agi->wait_for_digit(750); 201 193 break; 202 194 } 203 if(trim($ret['result'])){ 204 $ret['result'] = chr($ret['result']); 205 break; 206 } 195 if(trim($ret['result'])){$ret['result']=chr($ret['result']);break;} 207 196 } 208 197 break; 209 //TODO: BUG: hardcoded to Flite, needs to either check what is there or be configurable198 //TODO: BUG: hardcoded to Flite, needs to either check what is there or be configurable 210 199 case 'tts': 211 200 $ret=$this->agi->exec('Flite "'.$con['name'].'"|'.$keys); 212 if ($ret['result']){$ret['result']=chr($ret['result']);}213 break;201 if ($ret['result']){$ret['result']=chr($ret['result']);} 202 break; 214 203 default: 215 204 if(is_numeric($con['audio'])){ 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"); 205 $sql='SELECT filename from recordings where id = ?'; 206 $rec=$this->db->getOne($sql, array($con['audio'])); 207 dbug("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 dbug("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 dbug("user pressed 0 - bailing out"); 245 229 $this->bail(); 246 230 } 247 231 248 //the regex in the query will match the searchstring at the beging of the string or after a space249 $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);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 dbug("search string for regex: {$this->searchstring}",6); 253 237 254 238 //TODO: check db results for errors and fail gracefully 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; 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 dbug("FATAL: got error from COUNT(*) query"); 246 dbug($res->getdbugInfo()); 247 } 248 dbug("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 dbug("FATAL: got error from getAll query"); 254 dbug($res->getdbugInfo()); 255 } else { 256 dbug("Found the following matches:"); 257 foreach ($res as $ent) { 258 dbug("name: {$ent['name']}, audio: {$ent['audio']}, dial: {$ent['dial']}"); 259 } 260 } 261 } 262 return $res; 278 263 } 279 264 280 265 function bail() { 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 } 266 //do something if we are exiting due to to many tries 267 // 268 dbug("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 } 293 279 $this->agi->set_priority('1'); 294 280 exit; 295 }281 } 296 282 297 283 } 298 // PHP 4 does not have file_put_contents so create an aproximation of what the real function does 299 // TODO: get rid of extinc php4 stuff as we dont support it anymore 300 // 301 if (!function_exists('file_put_contents')) { 302 function file_put_contents($filename, $data, $flags='', $context=null) { 303 $option = $flags == FILE_APPEND ? 'a' : 'w'; 304 if ($context !== null) { 305 $fd = @fopen($filename, $option); 306 } else { 307 $fd = @fopen($filename, $option, false, $context); 308 } 309 if (!$fd) { 310 return false; 311 } 312 if (is_array($data)) { 313 $data = implode('',$data); 314 } else if (is_object($data)) { 315 $data = print_r($data,true); 316 } 317 $bytes = fwrite($fd,$data); 318 fclose($fd); 319 320 return $bytes; 321 } 322 } 323 if (!function_exists('scandir')) { 324 function scandir($path,$sort=0) { 325 $fh = opendir($path); 326 $list = array(); 327 while(false !== ($filename = readdir($fh))) { 328 $list[] = $filename; 329 } 330 closedir($fh); 331 /* Not really needed here 332 if ($sort) { 333 sort($list); 334 } else { 335 rsort($list); 336 } 337 */ 338 return $list; 339 } 340 } 341 342 // non-utf8 version for php4 343 if(!function_exists('str_split')) { 344 function str_split($string, $split_length = 1) { 345 $array = explode("\r\n", chunk_split($string, $split_length)); 346 array_pop($array); 347 return $array; 348 } 349 } 284 350 285 ?> modules/branches/bootstrap-2.9/directory/functions.inc.php
r10637 r10795 1 1 <?php 2 2 3 function directory_configpageload() { 3 4 global $currentcomponent,$display; … … 5 6 $currentcomponent->addguielem('_top', new gui_pageheading('title', _('Directory')), 0); 6 7 7 if ($_REQUEST['action'] == 'add') {8 $deet = array('dirname', 'description', 'repeat_loops', 'announcement',9 'repeat_recording', 'invalid_recording',10 'callid_prefix', 'alert_info', 'invalid_destination', 'retivr',11 'default_directory','say_extension', 'id');8 if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'add') { 9 $deet = array('dirname', 'description', 'repeat_loops', 'announcement', 10 'repeat_recording', 'invalid_recording', 11 'callid_prefix', 'alert_info', 'invalid_destination', 'retivr', 12 'say_extension', 'id'); 12 13 13 14 foreach ($deet as $d) { … … 22 23 break; 23 24 default: 24 $dir[$d] = '';25 $dir[$d] = ''; 25 26 break; 26 27 } 27 28 } 28 } else {29 $dir=directory_get_dir_details($_REQUEST['id']);29 } else { 30 $dir = directory_get_dir_details($_REQUEST['id']); 30 31 //display usage 31 $usage_list = framework_display_destination_usage(directory_getdest($dir['id'])); 32 $currentcomponent->addguielem('_top', new gui_link_label('usage', $usage_list['text'], $usage_list['tooltip']), 0); 32 $usage_list = framework_display_destination_usage(directory_getdest($dir['id'])); 33 $usage_list_text = isset($usage_list['text']) ? $usage_list['text'] : ''; 34 $usage_list_tooltip = isset($usage_list['tooltip']) ? $usage_list['tooltip'] : ''; 35 $currentcomponent->addguielem('_top', new gui_link_label('usage', $usage_list_text, $usage_list_tooltip), 0); 33 36 //display delete link 34 $label=sprintf(_("Delete Directory %s"),$dir['dirname']?$dir['dirname']:$dir['id']); 35 $label='<span><img width="16" height="16" border="0" title="'.$label.'" alt="" src="images/core_delete.png"/> '.$label.'</span>'; 36 $currentcomponent->addguielem('_top', new gui_link('del', $label, $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].'&action=delete', true, false), 0); 37 $label = sprintf(_("Delete Directory %s"), $dir['dirname'] ? $dir['dirname'] : $dir['id']); 38 $label = '<span><img width="16" height="16" border="0" title="' 39 . $label . '" alt="" src="images/core_delete.png"/> ' . $label . '</span>'; 40 $currentcomponent->addguielem('_top', new gui_link('del', $label, $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'] . '&action=delete', true, false), 0); 37 41 } 38 42 //delete link, dont show if we dont have an id (i.e. directory wasnt created yet) 39 $currentcomponent->addguielem('', new gui_textbox('dirname', $dir['dirname'], _('Directory Name'), _('Name of this directory.'))); 40 $currentcomponent->addguielem('', new gui_textbox('description', $dir['description'], _('Directory Description'), _('Description of this directory.'))); 41 $section = _('Directory Options'); 43 $gen_section = _('Directory General Options'); 44 $currentcomponent->addguielem($gen_section, new gui_textbox('dirname', $dir['dirname'], _('Directory Name'), _('Name of this directory.'))); 45 $currentcomponent->addguielem($gen_section, new gui_textbox('description', $dir['description'], _('Directory Description'), _('Description of this directory.'))); 46 $currentcomponent->addguielem($gen_section, new gui_textbox('callid_prefix', $dir['callid_prefix'], _('CallerID Name Prefix'), _('Prefix to be appended to current CallerID Name.'))); 47 $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.'))); 48 49 $section = _('Directory Options (DTMF)'); 42 50 43 51 //build recordings select list … … 46 54 $currentcomponent->addoptlistitem('recordings', $r['id'], $r['displayname']); 47 55 } 48 $currentcomponent->setoptlistopts('recordings', 'sort', false);56 $currentcomponent->setoptlistopts('recordings', 'sort', false); 49 57 //build repeat_loops select list and defualt it to 3 50 58 for($i=0; $i <11; $i++){ … … 53 61 54 62 //generate page 55 $currentcomponent->addguielem($section, new gui_selectbox('announcement', $currentcomponent->getoptlist('recordings'), $dir['announcement'], _('Announcement'), _('Greeting to be played on entry to the directory'), false)); 56 $currentcomponent->addguielem($section, new gui_textbox('callid_prefix', $dir['callid_prefix'], _('CallerID Name Prefix'), _('Prefix to be appended to current CallerID Name.'))); 57 $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.'))); 63 $currentcomponent->addguielem($section, new gui_selectbox('announcement', $currentcomponent->getoptlist('recordings'), $dir['announcement'], _('Announcement'), _('Greeting to be played on entry to the directory.'), false)); 58 64 $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)); 59 65 $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 68 $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)); 63 69 $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)); 64 $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));65 70 $currentcomponent->addguielem($section, new gui_hidden('id', $dir['id'])); 66 71 $currentcomponent->addguielem($section, new gui_hidden('action', 'edit')); … … 75 80 function directory_configpageinit($pagename) { 76 81 global $currentcomponent; 77 if($pagename =='directory'){82 if($pagename == 'directory'){ 78 83 $currentcomponent->addprocessfunc('directory_configprocess'); 79 84 $currentcomponent->addguifunc('directory_configpageload'); … … 86 91 } 87 92 88 $action = isset($_REQUEST['action'])?$_REQUEST['action']:null;89 $extdisplay = isset($_REQUEST['extdisplay'])?$_REQUEST['extdisplay']:null;90 $extension = isset($_REQUEST['extension'])?$_REQUEST['extension']:null;91 $tech_hardware = isset($_REQUEST['tech_hardware'])?$_REQUEST['tech_hardware']:null;93 $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null; 94 $extdisplay = isset($_REQUEST['extdisplay']) ? $_REQUEST['extdisplay'] : null; 95 $extension = isset($_REQUEST['extension']) ? $_REQUEST['extension'] : null; 96 $tech_hardware = isset($_REQUEST['tech_hardware']) ? $_REQUEST['tech_hardware'] : null; 92 97 93 98 if ($tech_hardware != null || $pagename == 'users') { 94 99 directory_applyhooks(); 95 100 $currentcomponent->addprocessfunc('directory_configprocess_exten', 8); 96 } elseif ($action =="add") {101 } elseif ($action == "add") { 97 102 // We don't need to display anything on an 'add', but we do need to handle returned data. 98 103 $currentcomponent->addprocessfunc('directory_configprocess_exten', 8); … … 106 111 //prosses received arguments 107 112 function directory_configprocess(){ 108 if($_REQUEST['display'] =='directory'){113 if($_REQUEST['display'] == 'directory'){ 109 114 global $db,$amp_conf; 110 115 //get variables for directory_details 111 $requestvars=array('id','dirname','description','announcement', 112 'callid_prefix','alert_info','repeat_loops','repeat_recording', 113 'invalid_recording','invalid_destination','retivr','say_extension','default_directory'); 116 $requestvars = array('id','dirname','description','announcement', 117 'callid_prefix','alert_info','repeat_loops', 118 'repeat_recording','invalid_recording', 119 'invalid_destination','retivr','say_extension'); 114 120 foreach($requestvars as $var){ 115 $vars[$var] =isset($_REQUEST[$var])?$_REQUEST[$var]:'';116 } 117 118 $action =isset($_REQUEST['action'])?$_REQUEST['action']:'';119 $entries =isset($_REQUEST['entries'])?$_REQUEST['entries']:'';120 $entries=(($entries)?array_values($entries):'');//reset keys121 $vars[$var] = isset($_REQUEST[$var]) ? $_REQUEST[$var] : ''; 122 } 123 124 $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : ''; 125 $entries = isset($_REQUEST['entries']) ? $_REQUEST['entries'] : ''; 126 //$entries=(($entries)?array_values($entries):'');//reset keys 121 127 122 128 switch($action){ 123 129 case 'edit': 124 130 //get real dest 125 $vars['invalid_destination'] =$_REQUEST[$_REQUEST[$_REQUEST['invalid_destination']].str_replace('goto','',$_REQUEST['invalid_destination'])];126 $vars['id'] =directory_save_dir_details($vars);131 $vars['invalid_destination'] = $_REQUEST[$_REQUEST[$_REQUEST['invalid_destination']].str_replace('goto','',$_REQUEST['invalid_destination'])]; 132 $vars['id'] = directory_save_dir_details($vars); 127 133 directory_save_dir_entries($vars['id'],$entries); 128 134 needreload(); 129 redirect_standard ('id');135 redirect_standard_continue('id'); 130 136 break; 131 137 case 'delete': 132 138 directory_delete($vars['id']); 133 139 needreload(); 134 redirect_standard ();140 redirect_standard_continue(); 135 141 break; 136 142 } … … 142 148 switch ($engine) { 143 149 case 'asterisk': 144 $sql ='SELECT id,dirname,say_extension FROM directory_details ORDER BY dirname';150 $sql = 'SELECT id,dirname,say_extension FROM directory_details ORDER BY dirname'; 145 151 $results=sql($sql,'getAll',DB_FETCHMODE_ASSOC); 146 152 if($results){ 147 $context= 'directory';148 // Note create a dial-id label for each directory to allow other modules to hook on a per149 // directory basis. (Otherwise we could have consolidated this into a call extension)153 $c = 'directory'; 154 // Note create a dial-id label for each directory to allow other modules to hook on a per 155 // directory basis. (Otherwise we could have consolidated this into a call extension) 150 156 foreach ($results as $row) { 151 $ext->add($context,$row['id'], '', new ext_answer(''));152 $ext->add($context,$row['id'], '', new ext_wait('1'));153 $ext->add($c ontext,$row['id'], '', new ext_agi('directory.agi,dir='.$row['id']));154 if ($row['say_extension']) {155 $ext->add($context,$row['id'], '', new ext_playback('pls-hold-while-try&to-extension'));156 $ext->add($context,$row['id'], '', new ext_saydigits('${DIR_DIAL}'));157 }158 $ext->add($context,$row['id'], 'dial-'.$row['id'], new ext_ringing());159 $ext->add($context,$row['id'], '', new ext_goto('1','${DIR_DIAL}','from-internal'));157 $ext->add($c, $row['id'], '', new ext_answer('')); 158 $ext->add($c, $row['id'], '', new ext_wait('1')); 159 $ext->add($c, $row['id'], '', new ext_agi('directory.agi,dir=' . $row['id'] . ',keypress=${keypress}')); 160 if ($row['say_extension']) { 161 $ext->add($c, $row['id'], '', new ext_playback('pls-hold-while-try&to-extension')); 162 $ext->add($c, $row['id'], '', new ext_saydigits('${DIR_DIAL}')); 163 } 164 $ext->add($c, $row['id'], 'dial-'.$row['id'], new ext_ringing()); 165 $ext->add($c, $row['id'], '', new ext_goto('1','${DIR_DIAL}','from-internal')); 160 166 } 161 $ext->add($context,'invalid', 'invalid', new ext_playback('${DIR_INVALID_RECORDING}')); 162 $ext->add($context,'invalid', '', new ext_ringing()); 163 $ext->add($context,'invalid', '', new ext_goto('${DIR_INVALID_PRI}','${DIR_INVALID_EXTEN}','${DIR_INVALID_CONTEXT}')); 164 $ext->add($context,'retivr', 'retivr', new ext_playback('${DIR_INVALID_RECORDING}')); 165 $ext->add($context,'retivr', '', new ext_goto('1','return','${IVR_CONTEXT}')); 166 $ext->add($context,'h', '', new ext_macro('hangupcall')); 167 168 } 169 break; 167 $ext->add($c, 'invalid', 'invalid', new ext_playback('${DIR_INVALID_RECORDING}')); 168 $ext->add($c, 'invalid', '', new ext_ringing()); 169 $ext->add($c, 'invalid', '', new ext_goto('${DIR_INVALID_PRI}','${DIR_INVALID_EXTEN}','${DIR_INVALID_CONTEXT}')); 170 $ext->add($c, 'retivr', 'retivr', new ext_playback('${DIR_INVALID_RECORDING}')); 171 $ext->add($c, 'retivr', '', new ext_goto('1','return','${IVR_CONTEXT}')); 172 $ext->add($c, 'h', '', new ext_macro('hangupcall')); 173 } 174 break; 170 175 } 171 176 } … … 173 178 function directory_list() { 174 179 $sql='SELECT id,dirname FROM directory_details ORDER BY dirname'; 175 $results=sql($sql, 'getAll',DB_FETCHMODE_ASSOC);176 return $results;180 $results=sql($sql, 'getAll', DB_FETCHMODE_ASSOC); 181 return $results; 177 182 } 178 183 179 184 function directory_get_dir_entries($id){ 180 185 global $db; 181 if ($id == '') {182 return array();183 }184 $id = $db->escapeSimple($id);185 $sql = "SELECT a.name, a.type, a.audio, a.dial, a.foreign_id, b.name foreign_name, IF(a.name != \"\",a.name,b.name) realname186 if ($id == '') { 187 return array(); 188 } 189 $id = $db->escapeSimple($id); 190 $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 186 191 FROM directory_entries a LEFT JOIN users b ON a.foreign_id = b.extension WHERE id = $id ORDER BY realname"; 187 192 $results = sql($sql,'getAll',DB_FETCHMODE_ASSOC); … … 191 196 function directory_get_dir_details($id){ 192 197 global $db; 193 $clean_id = $db->escapeSimple($id); 194 $sql="SELECT * FROM directory_details WHERE ID = $clean_id"; 195 $row=sql($sql,'getRow',DB_FETCHMODE_ASSOC); 196 $default_directory_id = sql("SELECT value FROM `admin` WHERE variable = 'default_directory' limit 1", "getOne"); 197 $row['default_directory'] = $default_directory_id == $id ? '1' : ''; 198 $clean_id = $db->escapeSimple($id); 199 $sql = "SELECT * FROM directory_details WHERE ID = $clean_id"; 200 $row = sql($sql,'getRow',DB_FETCHMODE_ASSOC); 198 201 return $row; 199 202 } … … 201 204 function directory_delete($id){ 202 205 global $db; 203 $id = $db->escapeSimple($id);206 $id = $db->escapeSimple($id); 204 207 sql("DELETE FROM directory_details WHERE id = $id"); 205 208 sql("DELETE FROM directory_entries WHERE id = $id"); 206 sql("DELETE FROM `admin` WHERE variable = 'default_directory' AND value = '$id'"); 209 if (directory_get_default_dir() == $id) { 210 directory_save_default_dir(''); 211 } 207 212 } 208 213 209 214 function directory_destinations(){ 210 215 global $db; 211 $sql ='SELECT id,dirname FROM directory_details ORDER BY dirname';212 $results =sql($sql,'getAll',DB_FETCHMODE_ASSOC);216 $sql = 'SELECT id,dirname FROM directory_details ORDER BY dirname'; 217 $results = sql($sql,'getAll',DB_FETCHMODE_ASSOC); 213 218 214 219 foreach($results as $row){ 215 $row['dirname'] =($row['dirname'])?$row['dirname']:'Directory '.$row['id'] ;220 $row['dirname'] = ($row['dirname'])?$row['dirname']:'Directory '.$row['id'] ; 216 221 $extens[] = array('destination' => 'directory,' . $row['id'] . ',1', 'description' => $row['dirname'], 'category' => _('Directory')); 217 222 } 218 223 return isset($extens)?$extens:null; 224 } 225 226 function directory_draw_entries_table_header_directory() { 227 return array(_('Name'), _('Name Announcement'), _('Dial')); 219 228 } 220 229 221 230 function directory_draw_entries($id){ 222 231 $sql='SELECT id,name FROM directory_entries ORDER BY name'; 223 $results=sql($sql,'getAll',DB_FETCHMODE_ASSOC); 224 $html=''; 225 $html.='<table id="dir_entries_tbl">'; 226 //$html.='<th>User</th><th>Name</th><th>Name Announcement</th><th>Dial</th>'; 227 $html.='<thead><th>Name</th><th>Name Announcement</th><th>Dial</th></thead>'; 228 $newuser='<select id="addusersel">'; 229 $newuser.='<option value="none" selected> == '._('Choose One').' == </option>'; 230 $newuser.='<option value="all">'._('All Users').'</option>'; 231 $newuser.='<option value="|">'._('Custom').'</option>'; 232 $results = sql($sql,'getAll',DB_FETCHMODE_ASSOC); 233 $html = ''; 234 $html .= '<table id="dir_entries_tbl">'; 235 $headers = mod_func_iterator('draw_entries_table_header_directory'); 236 237 $html .= '<thead><tr>'; 238 foreach ($headers as $mod => $header) { 239 foreach ($header as $h) { 240 if(is_array($h)) { 241 $html .= '<th ' . $h['attr'] . '/>'; 242 $html .= $h['val']; 243 $html .= '</th>'; 244 } else { 245 $html .= '<th>' . $h . '</th>'; 246 247 } 248 } 249 250 } 251 $html .= '</tr></thead>'; 252 253 $newuser = '<select id="addusersel">'; 254 $newuser .= '<option value="none" selected> == '._('Choose One').' == </option>'; 255 $newuser .= '<option value="all">'._('All Users').'</option>'; 256 $newuser .= '<option value="|">'._('Custom').'</option>'; 232 257 233 258 //TODO: could this cause a problem with the '|' separator if a name has a '|' in it? (probably not check for comment where parsed 234 259 // 235 260 foreach(core_users_list() as $user){ 236 $newuser.='<option value="'.$user[0].'|'.$user[1].'">('.$user[0].') '.$user[1]."</option>\n"; 237 } 238 $newuser.='</select>'; 239 $html.='<tfoot><tr><td id="addbut"><a href="#" class="info"><img src="images/core_add.png" name="image" style="border:none;cursor:pointer;" /><span>'._('Add new entry.').'</span></a></td><td colspan="3"id="addrow">'.$newuser.'</td></tr></tfoot>'; 240 $html.='<tbody>'; 241 $entries=directory_get_dir_entries($id); 242 $arraynum=1; 261 $newuser .= '<option value="'.$user[0].'|'.$user[1].'">('.$user[0].') '.$user[1]."</option>\n"; 262 } 263 $newuser .= '</select>'; 264 $html .= '<tfoot><tr><td id="addbut"><a href="#" class="info"><img src="images/core_add.png" name="image" style="border:none;cursor:pointer;" /><span>'._('Add new entry.').'</span></a></td><td colspan="3"id="addrow">'.$newuser.'</td></tr></tfoot>'; 265 $html .= '<tbody>'; 266 $entries = directory_get_dir_entries($id); 243 267 foreach($entries as $e){ 244 268 $realid = $e['type'] == 'custom' ? 'custom' : $e['foreign_id']; 245 269 $foreign_name = $e['foreign_name'] == '' ? 'Custom Entry' : $e['foreign_name']; 246 $html .=directory_draw_entries_tr($realid, $e['name'],$foreign_name, $e['audio'],$e['dial'],$arraynum++);247 } 248 $html .='</tbody></table>';270 $html .= directory_draw_entries_tr($id, $realid, $e['name'], $foreign_name, $e['audio'], $e['dial'], $e['e_id']); 271 } 272 $html .= '</tbody></table>'; 249 273 return $html; 250 274 } 251 275 252 276 //used to add row's the entry table 253 function directory_draw_entries_tr($realid, $name='',$foreign_name, $audio='',$num='',$id, $reuse_audio=false){ 254 global $amp_conf; 255 global $directory_draw_recordings_list;//make global, so its only drawn once 256 if(!$directory_draw_recordings_list){$directory_draw_recordings_list=recordings_list();} 257 258 // if reuse_audio is true create once, used by all_users to avoid recreating each time 259 global $audio_select; 260 if (!$audio_select || !$reuse_audio) { 261 unset($audio_select); 262 $audio_select='<select name="entries['.$id.'][audio]">'; 263 $audio_select.='<option value="vm" '.(($audio=='vm')?'SELECTED':'').'>'._('Voicemail Greeting').'</option>'; 264 $audio_select.='<option value="tts" '.(($audio=='tts')?'SELECTED':'').'>'._('Text to Speech').'</option>'; 265 $audio_select.='<option value="spell" '.(($audio=='spell')?'SELECTED':'').'>'._('Spell Name').'</option>'; 266 $audio_select.='<optgroup label="'._('System Recordings:').'">'; 267 foreach($directory_draw_recordings_list as $r){ 268 $audio_select.='<option value="'.$r['id'].'" '.(($audio==$r['id'])?'SELECTED':'').'>'.$r['displayname'].'</option>'; 269 } 270 $audio_select.='</select>'; 271 } 272 273 if ($realid != 'custom') { 274 $user_type = $amp_conf['AMPEXTENSION'] == 'deviceanduser' ? 'user' : 'extension'; 275 $tlabel = sprintf(_("Edit %s: %s"),$user_type,$realid); 276 $label = '<span><img width="16" height="16" border="0" title="'.$tlabel.'" alt="" src="images/user_edit.png"/> </span>'; 277 $user = ' <a href="/admin/config.php?type=setup&display='.$user_type.'s&skip=0&extdisplay='.$realid.'">'.$label.'</a> '; 278 } else { 279 $user = ''; 280 } 281 $delete='<img src="images/trash.png" style="cursor:pointer;" alt="'._('remove').'" title="'._('Click here to remove this entry').'" class="trash-tr">'; 282 $t1_class = $name == '' ? ' class = "dpt-title" ' : ''; 283 $t2_class = $realid == 'custom' ? ' title="Custom Dialstring" ' : ' title="'.$realid.'" '; 277 function directory_draw_entries_tr($id, $realid, $name = '',$foreign_name, $audio = '',$num = '',$e_id = '', $reuse_audio = false){ 278 global $amp_conf, $directory_draw_recordings_list, $audio_select; 279 if (!$directory_draw_recordings_list) { 280 $directory_draw_recordings_list = recordings_list(); 281 } 282 $e_id = $e_id ? $e_id : directory_get_next_id($realid); 283 if (!$audio_select || !$reuse_audio) { 284 unset($audio_select); 285 $audio_select = '<select name="entries['.$e_id.'][audio]">'; 286 $audio_select .= '<option value="vm" '.(($audio=='vm')?'SELECTED':'').'>'._('Voicemail Greeting').'</option>'; 287 $audio_select .= '<option value="tts" '.(($audio=='tts')?'SELECTED':'').'>'._('Text to Speech').'</option>'; 288 $audio_select .= '<option value="spell" '.(($audio=='spell')?'SELECTED':'').'>'._('Spell Name').'</option>'; 289 $audio_select .= '<optgroup label="'._('System Recordings:').'">'; 290 foreach($directory_draw_recordings_list as $r){ 291 $audio_select .= '<option value="' . $r['id'] . '" ' . (($audio == $r['id']) ? 'SELECTED' : '') . '>' . $r['displayname'] . '</option>'; 292 } 293 $audio_select .= '</select>'; 294 } 295 296 if ($realid != 'custom') { 297 $user_type = (isset($amp_conf['AMPEXTENSION']) && $amp_conf['AMPEXTENSION']) == 'deviceanduser' ? 'user' : 'extension'; 298 $tlabel = sprintf(_("Edit %s: %s"), $user_type ,$realid); 299 $label = '<span><img width="16" height="16" border="0" title="'.$tlabel.'" alt="" src="images/user_edit.png"/> </span>'; 300 $user = ' <a href="/admin/config.php?type=setup&display='.$user_type.'s&skip=0&extdisplay='.$realid.'">'.$label.'</a> '; 301 } else { 302 $user = ''; 303 } 304 $delete = '<img src="images/trash.png" style="cursor:pointer;" alt="'._('remove').'" title="'._('Click here to remove this entry').'" class="trash-tr">'; 305 $t1_class = $name == '' ? ' class = "dpt-title" ' : ''; 306 $t2_class = $realid == 'custom' ? ' title="Custom Dialstring" ' : ' title="' . $realid . '" '; 284 307 if (trim($num) == '') { 285 $t2_class .= '" class = "dpt-title" '; 286 } 287 $html='<tr class="entrie'.$id.'"><td><input type="hidden" readonly="readonly" name="entries['.$id.'][foreign_id]" value="'.$realid.'" /><input type="text" name="entries['.$id.'][name]" title="'.$foreign_name.'"'.$t1_class.' value="'.$name.'" /></td><td>'.$audio_select.'</td><td><input type="text" name="entries['.$id.'][num]" '.$t2_class.' value="'.$num.'" /></td><td>'.$delete.$user.'</td></tr>'; 308 $t2_class .= '" class = "dpt-title" '; 309 } 310 311 $td[] = '<input type="hidden" readonly="readonly" name="entries['.$e_id.'][foreign_id]" value="'.$realid.'" /><input type="text" name="entries['.$e_id.'][name]" title="'.$foreign_name.'"'.$t1_class.' value="'.$name.'" />'; 312 $td[] = $audio_select; 313 $td[] = '<input type="text" name="entries['.$e_id.'][num]" '.$t2_class.' value="'.$num.'" />'; 314 $opts = array('id' => $id, 'e_id' => $e_id, 'realid' => $realid, 'name' => $name, 'audio' => $audio, 'num' => $num); 315 316 $more_td = mod_func_iterator('draw_entries_tr_directory', $opts); 317 foreach ($more_td as $mod) { 318 foreach ($mod as $m){ 319 $td[] = $m; 320 } 321 } 322 323 $td[] = $delete.$user; 324 325 //build html 326 $html = '<tr class="entrie'.$e_id.'">'; 327 foreach ($td as $t) { 328 if (is_array($t)) { 329 $html .= '<td ' . $t['attr'] . '/>'; 330 $html .= $t['val']; 331 $html .= '</td>'; 332 } else { 333 $html .= '<td>' . $t . '</td>'; 334 } 335 } 336 $html .= '</tr>'; 288 337 return $html; 289 338 } … … 293 342 $html=''; 294 343 foreach(core_users_list() as $user){ 295 $html .= directory_draw_entries_tr($user[0], '', $user[1], 'vm', '',$id++, true);344 $html .= directory_draw_entries_tr($id, $user[0], '', $user[1], 'vm', '',$id++, true); 296 345 } 297 346 return $html; 347 } 348 349 350 function directory_save_default_dir($default_directory) { 351 global $db; 352 353 if ($default_directory) { 354 sql("REPLACE INTO `directory` (`key`, value) VALUES ('default_directory', '$default_directory')"); 355 } else { 356 sql("DELETE FROM `directory` WHERE `key` = 'default_directory'"); 357 } 358 } 359 360 function directory_get_default_dir() { 361 global $db; 362 363 $ret = sql("SELECT value FROM `directory` WHERE `key` = 'default_directory'", 'getOne'); 364 return $ret ? $ret : ''; 365 298 366 } 299 367 … … 301 369 // 302 370 function directory_save_dir_details($vals){ 303 global $db; 304 global $amp_conf; 305 306 foreach($vals as $key => $value) { 307 $vals[$key] = $db->escapeSimple($value); 308 } 309 if (isset($vals['default_directory'])) { 310 $default_directory = $vals['default_directory']; 311 unset($vals['default_directory']); 312 } else { 313 $default_directory = false; 314 } 315 316 if ($vals['id']) { 317 $sql='REPLACE INTO directory_details (id,dirname,description,announcement, 371 global $db, $amp_conf; 372 373 foreach($vals as $key => $value) { 374 $vals[$key] = $db->escapeSimple($value); 375 } 376 377 if ($vals['id']) { 378 $sql = 'REPLACE INTO directory_details (id,dirname,description,announcement, 318 379 callid_prefix,alert_info,repeat_loops,repeat_recording, 319 380 invalid_recording,invalid_destination,retivr,say_extension) 320 381 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; 321 $foo=$db->query($sql,$vals);322 if(DB::IsError($foo)) {323 die_freepbx(print_r($vals,true).' '.$foo->getDebugInfo());324 }325 } else {326 unset($vals['id']);327 $sql='INSERT INTO directory_details (dirname,description,announcement,382 $foo = $db->query($sql,$vals); 383 if(DB::IsError($foo)) { 384 die_freepbx(print_r($vals,true).' '.$foo->getDebugInfo()); 385 } 386 } else { 387 unset($vals['id']); 388 $sql = 'INSERT INTO directory_details (dirname,description,announcement, 328 389 callid_prefix,alert_info,repeat_loops,repeat_recording, 329 390 invalid_recording,invalid_destination,retivr,say_extension) 330 391 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; 331 $foo=$db->query($sql,$vals); 332 if(DB::IsError($foo)) { 333 die_freepbx(print_r($vals,true).' '.$foo->getDebugInfo()); 334 } 335 $sql=(($amp_conf["AMPDBENGINE"]=="sqlite3")?'SELECT last_insert_rowid()':'SELECT LAST_INSERT_ID()'); 336 $vals['id']=$db->getOne($sql); 337 if (DB::IsError($foo)){ 338 die_freepbx($foo->getDebugInfo()); 339 } 340 } 341 342 if ($default_directory) { 343 sql("REPLACE INTO `admin` (variable, value) VALUES ('default_directory', '{$vals['id']}')"); 344 } else { 345 sql("DELETE FROM `admin` WHERE variable = 'default_directory' AND value = '{$vals['id']}'"); 392 $foo = $db->query($sql,$vals); 393 if(DB::IsError($foo)) { 394 die_freepbx(print_r($vals,true).' '.$foo->getDebugInfo()); 395 } 396 $sql = ( ($amp_conf["AMPDBENGINE"]=="sqlite3") ? 'SELECT last_insert_rowid()' : 'SELECT LAST_INSERT_ID()'); 397 $vals['id'] = $db->getOne($sql); 398 if (DB::IsError($foo)){ 399 die_freepbx($foo->getDebugInfo()); 400 } 346 401 } 347 402 … … 351 406 function directory_save_dir_entries($id,$entries){ 352 407 global $db; 353 $id = $db->escapeSimple($id); 354 408 $id = $db->escapeSimple($id); 355 409 sql("DELETE FROM directory_entries WHERE id = $id"); 356 410 357 //TODO = prepare the data:358 // if 'dial' is the same as type_id, then delete the 'dial,' leave as default359 // if 'name' is same as default_name, then delete the 'name,' leave as default411 //TODO = prepare the data: 412 // if 'dial' is the same as type_id, then delete the 'dial,' leave as default 413 // if 'name' is same as default_name, then delete the 'name,' leave as default 360 414 if($entries){ 361 415 $insert=''; 362 // TODO: should we change to perpare/execute ?416 // TODO: should we change to perpare/execute ? 363 417 foreach($entries as $idx => $row){ 364 418 if($row['foreign_id'] == 'custom' && trim($row['name']) == '' || $row['foreign_id']==''){ … … 372 426 $foreign_id = $db->escapeSimple($row['foreign_id']); 373 427 } 374 $audio = $row['audio'] != '' ? $db->escapeSimple($row['audio']) : ($row['foreign_id'] == 'custom' ? 'tts' : 'vm');375 if (!empty($insert)) {376 $insert .= ',';377 } 378 $insert.='("'.$id.'","'.$db->escapeSimple(trim($row['name'])).'","'.$type.'","'.$foreign_id.'","'.$audio.'","'.$db->escapeSimple(trim($row['num'])).'")';428 $audio = $row['audio'] != '' ? $db->escapeSimple($row['audio']) : ($row['foreign_id'] == 'custom' ? 'tts' : 'vm'); 429 if (!empty($insert)) { 430 $insert .= ','; 431 } 432 $insert.='("'.$id.'","'.$idx.'","'.$db->escapeSimple(trim($row['name'])).'","'.$type.'","'.$foreign_id.'","'.$audio.'","'.$db->escapeSimple(trim($row['num'])).'")'; 379 433 } 380 sql('INSERT INTO directory_entries (id, name,type,foreign_id,audio,dial) VALUES '.$insert);434 sql('INSERT INTO directory_entries (id, e_id, name,type,foreign_id,audio,dial) VALUES '.$insert); 381 435 } 382 436 } … … 386 440 387 441 function directory_check_default($extension) { 388 $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"; 442 $def_dir = directory_get_default_dir(); 443 $sql = "SELECT foreign_id FROM directory_entries WHERE foreign_id = '$extension' AND id = '$def_dir' LIMIT 1"; 389 444 $results = sql($sql,"getAll"); 390 445 return count($results); … … 392 447 393 448 function directory_set_default($extension, $value) { 394 $default_directory_id = sql("SELECT value FROM `admin` WHERE variable = 'default_directory' limit 1", "getOne");449 $default_directory_id = directory_get_default_dir(); 395 450 if ($default_directory_id == '') { 396 451 return false; 397 452 } 398 if ($value) {399 sql("REPLACE INTO directory_entries (id, foreign_id) VALUES ($default_directory_id, '$extension')");400 } else {401 sql("DELETE FROM directory_entries WHERE id = $default_directory_id AND foreign_id = '$extension'");402 }453 if ($value) { 454 sql("REPLACE INTO directory_entries (id, foreign_id) VALUES ($default_directory_id, '$extension')"); 455 } else { 456 sql("DELETE FROM directory_entries WHERE id = $default_directory_id AND foreign_id = '$extension'"); 457 } 403 458 } 404 459 … … 426 481 if ($action != 'del') { 427 482 428 $default_directory_id = sql("SELECT value FROM `admin` WHERE variable = 'default_directory'", "getOne");483 $default_directory_id = directory_get_default_dir(); 429 484 $section = _("Default Group Inclusion"); 430 485 if ($default_directory_id != "") { … … 440 495 //create vars from the request 441 496 // 442 $action = isset($_REQUEST['action'])?$_REQUEST['action']:null;443 $ext = isset($_REQUEST['extdisplay'])?$_REQUEST['extdisplay']:null;444 $extn = isset($_REQUEST['extension'])?$_REQUEST['extension']:null;445 $in_default_directory = isset($_REQUEST['in_default_directory'])?$_REQUEST['in_default_directory']:false;446 447 $extdisplay = ($ext==='') ? $extn : $ext;497 $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null; 498 $ext = isset($_REQUEST['extdisplay']) ? $_REQUEST['extdisplay'] : null; 499 $extn = isset($_REQUEST['extension']) ? $_REQUEST['extension'] : null; 500 $in_default_directory = isset($_REQUEST['in_default_directory']) ? $_REQUEST['in_default_directory'] : false; 501 502 $extdisplay = ($ext === '') ? $extn : $ext; 448 503 449 504 if (($action == "add" || $action == "edit")) { … … 473 528 $sql .= "WHERE invalid_destination in ('".implode("','",$dest)."')"; 474 529 } 475 $results = sql($sql, "getAll",DB_FETCHMODE_ASSOC);530 $results = sql($sql, "getAll", DB_FETCHMODE_ASSOC); 476 531 477 532 foreach ($results as $result) { 478 $thisdest = $result['invalid_destination'];479 $thisid = $result['id'];480 $destlist[] = array(533 $thisdest = $result['invalid_destination']; 534 $thisid = $result['id']; 535 $destlist[] = array( 481 536 'dest' => $thisdest, 482 'description' => sprintf(_("Directory: %s "), ($result['dirname']?$result['dirname']:$result['id'])),483 'edit_url' => 'config.php?display=directory&id=' .urlencode($result['id']),537 'description' => sprintf(_("Directory: %s "), ($result['dirname'] ? $result['dirname'] : $result['id'])), 538 'edit_url' => 'config.php?display=directory&id=' . urlencode($result['id']), 484 539 ); 485 540 } … … 500 555 return array(); 501 556 } else { 502 return array('description' => sprintf(_("Directory %s: "), ($thisdir['dirname']?$thisdir['dirname']:$id)),503 'edit_url' => 'config.php?display=directory&id=' .urlencode($id),504 );557 return array('description' => sprintf(_("Directory %s: "), ($thisdir['dirname'] ? $thisdir['dirname'] : $id)), 558 'edit_url' => 'config.php?display=directory&id=' . urlencode($id), 559 ); 505 560 } 506 561 } else { … … 509 564 } 510 565 566 function directory_get_next_id($realid) { 567 global $db; 568 $res = sql('SELECT MAX(e_id) FROM directory_entries WHERE id = "' . $realid . '"', 'getOne'); 569 return $res ? $res : 1; 570 } 571 511 572 function directory_recordings_usage($recording_id) { 512 573 global $active_modules; 513 574 514 575 $results = sql("SELECT `id`, `dirname` FROM `directory_details` 515 WHERE `announcement` = '$recording_id'516 OR `repeat_recording` = '$recording_id'517 OR `invalid_recording` = '$recording_id'",518 "getAll",DB_FETCHMODE_ASSOC);576 WHERE `announcement` = '$recording_id' 577 OR `repeat_recording` = '$recording_id' 578 OR `invalid_recording` = '$recording_id'", 579 "getAll",DB_FETCHMODE_ASSOC); 519 580 if (empty($results)) { 520 581 return array(); … … 523 584 foreach ($results as $result) { 524 585 $usage_arr[] = array( 525 'url_query' => 'config.php?display=directory&id=' .urlencode($result['id']),526 'description' => sprintf(_("Directory: %s"), ($result['dirname']?$result['dirname']:$result['id'])),586 'url_query' => 'config.php?display=directory&id=' . urlencode($result['id']), 587 'description' => sprintf(_("Directory: %s"), ($result['dirname'] ? $result['dirname'] : $result['id'])), 527 588 ); 528 589 } … … 531 592 } 532 593 533 function directory_change_destination($old_dest, $new_dest) {534 $sql = 'UPDATE directory_details SET invalid_destination = "' . $new_dest . '" WHERE invalid_destination = "' . $old_dest . '"';535 sql($sql, "query");536 }537 594 ?> modules/branches/bootstrap-2.9/directory/install.php
r9882 r10795 19 19 outn(_('Adding directory_details table if needed...')); 20 20 21 $sql = "CREATE TABLE IF NOT EXISTS directory_details (21 $sql[] = "CREATE TABLE IF NOT EXISTS directory_details ( 22 22 id INT NOT NULL PRIMARY KEY $autoincrement, 23 23 dirname varchar(50), … … 34 34 )"; 35 35 36 $check = $db->query($sql); 37 if (DB::IsError($check)) { 38 out(_('failed')); 39 out(_('Can not create `directory_details` table: ') . $check->getMessage()); 40 return false; 41 } 42 out(_('ok')); 43 outn(_('Adding directory_entries table if needed...')); 44 45 $sql = "CREATE TABLE IF NOT EXISTS directory_entries ( 36 37 $sql[] = "CREATE TABLE IF NOT EXISTS directory_entries ( 46 38 id INT NOT NULL, 47 39 name varchar(50), … … 50 42 audio varchar(50), 51 43 dial varchar(50) default '' 52 );"; 53 54 $check = $db->query($sql); 55 if (DB::IsError($check)) { 56 out(_('failed')); 57 out(_('Can not create `directory_entries` table: ') . $check->getMessage()); 58 } 59 out(_('ok')); 44 )"; 45 46 $sql[] = "CREATE TABLE IF NOT EXISTS directory ( 47 `key` varchar(50) UNIQUE key, 48 `value` varchar(150) 49 )"; 50 51 foreach ($sql as $s) { 52 $do = $db->query($s); 53 if (DB::IsError($do)) { 54 out(_('Can not create table: ') . $check->getMessage()); 55 return false; 56 } 57 } 60 58 61 59 $sql = "SELECT say_extension FROM directory_details"; … … 77 75 $check = $db->getRow($sql, DB_FETCHMODE_ASSOC); 78 76 if(!DB::IsError($check)) { 79 outn(_("dropping valid_details field.."));77 outn(_("dropping valid_details field..")); 80 78 $sql = "ALTER TABLE `directory_details` DROP `valid_recording`"; 81 79 $result = $db->query($sql); … … 86 84 } 87 85 } 86 87 // 88 //add e_id field if it doesnt already exists 89 // 90 $sql = 'SHOW COLUMNS FROM directory_entries LIKE "e_id"'; 91 $res = $db->getAll($sql); 92 //check to see if the field already exists 93 if (count($res) == 0) { 94 //if not add it 95 $sql = 'ALTER TABLE directory_entries ADD COLUMN e_id INT AFTER id'; 96 $do = $db->query($sql); 97 if(DB::IsError($do)) { 98 out(_("cannot add field e_id to table directory_entries \n" . $do->getDebugInfo())); 99 } else { 100 out(_("e_id added to table directory_entries")); 101 } 102 //get ALL directory entires 103 $sql = 'SELECT * FROM directory_entries'; 104 $de = $db->getAll($sql, DB_FETCHMODE_ASSOC); 105 $count = array(); 106 foreach($de as $d => $e) { 107 if (!isset($count[$e['id']]) || $count[$e['id']] == '') { 108 //set id and delete all entires for this ivr. This only gets run once per ivr 109 $count[$e['id']] = 1; 110 sql('DELETE FROM directory_entries WHERE id = "' . $e['id'] . '"'); 111 } else { 112 $count[$e['id']]++; 113 } 114 $de[$d]['e_id'] = $count[$e['id']]; 115 //update entire 116 $sql = 'INSERT INTO directory_entries (id, e_id, name, type, foreign_id, audio, dial) VALUES (?, ?, ?, ?, ?, ?, ?)'; 117 $do = $db->query($sql, $de[$d]); 118 if(DB::IsError($do)) { 119 out(_('cannot set e_id for directory_id = ' . $e['id'] . '. Please resubmit this directory manually to correct this issue.')); 120 } 121 } 122 } 123 124 //move defualt dir info in to directory table 125 $defdir = $db->getOne("SELECT value FROM `admin` WHERE `key` = 'default_directory'"); 126 if (isset($defdir) && $defdir) { 127 $q = $db->query("REPLACE INTO `directory` (`key`, value) VALUES ('default_directory', '$defdir')"); 128 if(DB::IsError($q)) { 129 die_freepbx(_('Error migrating to new directory! ERROR: Unable to migrate. The default directory setting. You may need to reset this manually. ' . $q->getDebugInfo())); 130 } 131 $db->query("DELETE FROM `admin` WHERE variable = 'default_directory"); 132 } 133 134 //check to see if there is a need to migrate from legacy directory 135 $migrated = $db->getOne("SELECT value FROM `directory` WHERE `key` = 'directory28_migrated'"); 136 137 138 if (!$migrated) { 139 //migrate legacy directories to new directory 140 //get a list of vm users 141 $vmconf = null; 142 $section = null; 143 $vmusers = array(); 144 parse_voicemailconf_directory_migration(rtrim($amp_conf["ASTETCDIR"],"/")."/voicemail.conf", $vmconf, $section); 145 if (isset($vmconf) && $vmconf) { 146 foreach ($vmconf['default'] as $ext => $vm) { 147 $vmusers[$ext] = $vm['name']; 148 } 149 } 150 151 152 //create a new directory if we have voicemail users 153 if (isset($vmusers) && $vmusers) { 154 out(_("Migrating Directory")); 155 //TODO: make this the default directory 156 $vals = array('Migrated Directory', '', '0', '', '', '2', 157 '0', '0', 'app-blackhole,hangup,1', '', '1'); 158 $sql = 'INSERT INTO directory_details (dirname, description, announcement, 159 callid_prefix, alert_info, repeat_loops, repeat_recording, 160 invalid_recording, invalid_destination, retivr, say_extension) 161 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; 162 $new = $db->query($sql, $vals); 163 if(DB::IsError($new)) { 164 die_freepbx(_('Error migrating to new directory! ERROR: Could not create new Directory.' . $new->getDebugInfo())); 165 } 166 //get the id of the new directory 167 $sql = ( ($amp_conf["AMPDBENGINE"] == "sqlite3") ? 'SELECT last_insert_rowid()' : 'SELECT LAST_INSERT_ID()'); 168 $newdir = $db->getOne($sql); 169 $dirdest = 'directory,' . $newdir . ',1'; 170 171 //insert all system users to the new directory, 172 //Just insert their ext. number, everythign else will be handeled automatically by directory 173 $e_id = 0; 174 foreach ($vmusers as $ext => $user) { 175 $vals = array($newdir, $e_id++, 'user', $ext, 'vm'); 176 $sql = 'INSERT INTO directory_entries (id, e_id, type, foreign_id, audio) 177 VALUES (?, ?, ?, ?, ?)'; 178 $q = $db->query($sql, $vals); 179 if(DB::IsError($q)) { 180 die_freepbx(_('Error migrating to new directory! ERROR: Could not populate new Directory ' . $q->getDebugInfo())); 181 } 182 } 183 184 //set as defualt directory 185 if (!isset($def_dir) || !$def_dir) { 186 out(_("Setting migrated directory as defualt")); 187 $sql = 'REPLACE INTO `directory` (`key`, value) VALUES ("default_directory", ?)'; 188 $db->query($sql, $newdir); 189 } 190 } 191 192 193 //check to see if were using the directory in ivr's 194 $count = $db->getOne('SELECT count(*) FROM ivr WHERE displayname != "__install_done"'); 195 if(DB::IsError($count)) { 196 die_freepbx(_('Error migrating to new directory! ERROR: Could not get count of Ivr\'s using the legacy Directory ' . $q->getDebugInfo())); 197 } 198 199 //Migrate ivr's if we have ivr's using directory 200 if ($count > 0) { 201 out(_("Migrating Ivr's to new Directory")); 202 //if we were able to set a new directory 203 if (isset($newdir) && $newdir){ 204 //get al ivr's 205 $ivrs = $db->getAll('SELECT * FROM ivr WHERE displayname != "__install_done"', DB_FETCHMODE_ASSOC); 206 if(DB::IsError($ivrs)) { 207 die_freepbx(_('Error migrating to new directory! ERROR: Could not get all Ivr\'s')); 208 } 209 210 //get misc destinations that might be referencing legacy directory 211 $miscdests = $db->getAll('SELECT id FROM miscdests WHERE destdial = "{infoservices:directory}"'); 212 foreach ($miscdests as $m) { 213 $miscdest[] = 'ext-miscdests,' . $m[0] . ',1'; 214 } 215 //iterate over ivr's and their entries, looking for a misc apps that might be legacy directory or a # dest 216 foreach ($ivrs as $ivr) { 217 out(_("Migrating Ivr " . $ivr['displayname'] . "'s entires to new Directory")); 218 219 //is this ivr set to use directory? 220 $true_opts = array('1', 'on', 'ON', 'CHECKED', 'checked', 'TRUE', 'true'); 221 if (in_array($ivr['enable_directory'], $true_opts)) { 222 out(_("Removing legacy Directory from Ivr " . $ivr['displayname'] . "'s destinations")); 223 224 //update ivr dests 225 $sql = 'UPDATE ivr_dests SET dest = ? WHERE ivr_id = ? AND '; 226 //add misc diests if we have any 227 if (isset($miscdest) && $miscdest) { 228 $sql .= ' (selection = "#" '; 229 $m = array(); 230 foreach ($miscdest as $md) { 231 $m[] = '"' . $md . '"'; 232 } 233 $sql .= ' OR dest IN(' . implode(',', $m) . ') )'; 234 } else { 235 $sql .= ' selection = "#" '; 236 } 237 $q = $db->query($sql, array($dirdest, $ivr['ivr_id'])); 238 if(DB::IsError($q)) { 239 die_freepbx(_('Error migrating to new directory! ERROR: Failed to update ivr destinations ' . $q->getDebugInfo())); 240 } 241 242 243 //check to ensure that we have a # destination 244 $sql = 'SELECT COUNT(*) FROM ivr_dests WHERE ivr_id = ? AND selection = "#"'; 245 $pound_count = $db->getOne($sql, array($ivr['ivr_id'])); 246 247 if ($pound_count < 1) { 248 $sql = 'INSERT INTO ivr_dests (ivr_id, selection, dest) VALUES (?, ?, ?)'; 249 $q = $db->query($sql, array($ivr['ivr_id'], '#', $dirdest)); 250 if(DB::IsError($q)) { 251 die_freepbx(_('Error migrating to new directory! ERROR: Failed to add ivr destination # ' . $q->getDebugInfo())); 252 } 253 } 254 255 //remove the legacy directroy option from this ivr 256 $sql = 'UPDATE ivr SET enable_directory = "" WHERE ivr_id = ?'; 257 $q = $db->query($sql, array($ivr['ivr_id'])); 258 if(DB::IsError($q)) { 259 die_freepbx(_('Error migrating to new directory! ERROR: Failed to unset enable_directory from ivr ' . $q->getDebugInfo())); 260 } 261 } else {//even if it wasnt set to use the legace directory, ensure that we dont have mics dests pointing at it 262 if (isset($miscdest) && $miscdest) { 263 $sql = 'UPDATE ivr_dests SET dest = ? WHERE ivr_id = ? AND dest'; 264 $m = array(); 265 foreach ($miscdest as $md) { 266 $m[] = '"' . $md . '"'; 267 } 268 $sql .= ' IN(' . implode(',', $m) . ')'; 269 $q = $db->query($sql, array($dirdest, $ivr['ivr_id'])); 270 if(DB::IsError($q)) { 271 die_freepbx(_('Error migrating to new directory! ERROR: Failed to update ivr destinations (2) ' . $q->getDebugInfo())); 272 } 273 } 274 } 275 }//<--- end ivr foreach loop 276 } else { //if we dont have/couldnt create a new directory, assume there are no vm users and disable the option from ivr's 277 out(_("Removing legacy Directory from Ivr " . $ivr['displayname'])); 278 $q = $db->query('UPDATE ivr SET enable_directory = ""'); 279 if(DB::IsError($q)) { 280 die_freepbx(_('Error migrating to new directory! ERROR: Failed to unset enable_directory from ivr (2) ' . $q->getDebugInfo())); 281 } 282 } 283 }//<--- end ivr if case 284 285 //TODO: migrate misc dests if any are using legacy directory 286 287 //Seem where done with migration - mark that in the database 288 $migrated_dir = (isset($newdir) && $newdir) ? $newdir : 'true'; 289 $q = $db->query("REPLACE INTO `directory` (`key`, value) VALUES ('directory28_migrated', '$migrated_dir')"); 290 if(DB::IsError($q)) { 291 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())); 292 } 293 out(_('Migration Complete!')); 294 } 295 296 /** Recursively read voicemail.conf (and any included files) 297 * This function coppied from functions.inc.php 298 */ 299 function parse_voicemailconf_directory_migration($filename, &$vmconf, &$section) { 300 if (is_null($vmconf)) { 301 $vmconf = array(); 302 } 303 if (is_null($section)) { 304 $section = "general"; 305 } 306 307 if (file_exists($filename)) { 308 $fd = fopen($filename, "r"); 309 while ($line = fgets($fd, 1024)) { 310 if (preg_match("/^\s*(\d+)\s*=>\s*(\d*),(.*),(.*),(.*),(.*)\s*([;#].*)?/",$line,$matches)) { 311 // "mailbox=>password,name,email,pager,options" 312 // this is a voicemail line 313 $vmconf[$section][ $matches[1] ] = array("mailbox"=>$matches[1], 314 "pwd"=>$matches[2], 315 "name"=>$matches[3], 316 "email"=>$matches[4], 317 "pager"=>$matches[5], 318 "options"=>array(), 319 ); 320 321 // parse options 322 //output($matches); 323 foreach (explode("|",$matches[6]) as $opt) { 324 $temp = explode("=",$opt); 325 //output($temp); 326 if (isset($temp[1])) { 327 list($key,$value) = $temp; 328 $vmconf[$section][ $matches[1] ]["options"][$key] = $value; 329 } 330 } 331 } else if (preg_match('/^(?:\s*)#include(?:\s+)["\']{0,1}([^"\']*)["\']{0,1}(\s*[;#].*)?$/',$line,$matches)) { 332 // include another file 333 334 if ($matches[1][0] == "/") { 335 // absolute path 336 $filename = trim($matches[1]); 337 } else { 338 // relative path 339 $filename = dirname($filename)."/".trim($matches[1]); 340 } 341 342 parse_voicemailconf_directory_migration($filename, $vmconf, $section); 343 344 } else if (preg_match("/^\s*\[(.+)\]/",$line,$matches)) { 345 // section name 346 $section = strtolower($matches[1]); 347 } else if (preg_match("/^\s*([a-zA-Z0-9-_]+)\s*=\s*(.*?)\s*([;#].*)?$/",$line,$matches)) { 348 // name = value 349 // option line 350 $vmconf[$section][ $matches[1] ] = $matches[2]; 351 } 352 } 353 fclose($fd); 354 } 355 } 88 356 ?> modules/branches/bootstrap-2.9/directory/page.directory.php
r10758 r10795 8 8 //check for ajax request and process that immediately 9 9 if(isset($_REQUEST['ajaxgettr'])){//got ajax request 10 $opts = $opts=explode('|', urldecode($_REQUEST['ajaxgettr']));10 $opts = $opts=explode('|', urldecode($_REQUEST['ajaxgettr'])); 11 11 if($opts[0] == 'all') { 12 12 echo directory_draw_entries_all_users($opts[1]); … … 23 23 $audio = 'tts'; 24 24 } 25 echo directory_draw_entries_tr($ real_id, $name, $realname, $audio,'',$opts[2]);25 echo directory_draw_entries_tr($opts[0], $real_id, $name, $realname, $audio,'',$opts[2]); 26 26 } 27 27 exit; … … 29 29 30 30 //get vars 31 $requestvars =array('id','action','entries','newentries');32 foreach ($requestvars as $var){33 $$var =isset($_REQUEST[$var])?$_REQUEST[$var]:'';31 $requestvars = array('id', 'action', 'entries', 'newentries', 'def_dir', 'Submit'); 32 foreach ($requestvars as $var){ 33 $$var = isset($_REQUEST[$var])?$_REQUEST[$var]:''; 34 34 } 35 36 if (isset($Submit) && $Submit == 'Submit' && isset($def_dir)) { 37 directory_save_default_dir($def_dir); 38 } 39 35 40 //draw right nav bar 36 41 directory_drawListMenu(); 37 42 38 if($action=='' && $id==''){ 43 ?> 44 <script type="text/javascript"> 45 $(document).ready(function() { 46 $('#new_dir').click(function(){ 47 window.location.href = 'config.php?type=<?php echo $type ?>&display=directory&action=add'; 48 }) 49 }); 50 </script> 51 <?php 52 if($action == '' && $id == ''){ 53 $dirlist = directory_list(); 54 array_unshift($dirlist, array('id' => '', 'dirname' => _('none'))); 55 $def_dir = directory_get_default_dir(); 39 56 echo '<h2 id="title">Directory</h2>'; 40 echo '<br /><br /><input type="button" value="'._('Add a new Directory').'" onclick="window.location.href=\'config.php?type='.$type.'&display=directory&action=add\';"/>'; 41 echo '<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />'; 57 echo '<br /><br /><input type="button" value="' . _('Add a new Directory') . '" id="new_dir"/>'; 58 echo '<form action="' . $_SERVER['REQUEST_URI'] . '" method="post">'; 59 echo '<br /><br /><h5>' . _('Directory Options') . '</h5><hr class="dirhr">'; 60 echo '<a href="javascript:void(null)" class="info">Default Directory <span style="left: -18px; display: none; ">'; 61 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'); 62 echo '</span></a>'; 63 echo '  <select name="def_dir">'; 64 if (isset($dirlist) && $dirlist) { 65 foreach ($dirlist as $dir) { 66 echo '<option value="' . $dir['id'] . '"'; 67 echo (($dir['id'] == $def_dir) ? ' SELECTED ' : '') . '>'; 68 echo $dir['dirname'] ? $dir['dirname'] : _('Directory') . ' ' . $dir['id']; 69 echo '</option>'; 70 } 71 } 72 echo '</select>'; 73 echo '<br /><br /><input type="submit" name="Submit">'; 74 echo '</form><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />'; 42 75 } 43 76 44 77 function directory_drawListMenu(){ 45 78 global $id,$type; 46 $results=directory_list(); 79 $results = directory_list(); 80 $def_dir = directory_get_default_dir(); 47 81 echo '<div class="rnav"><ul>'."\n"; 48 echo " \t<li><a href=\"config.php?type=$type&display=directory&action=add\">"._('Add Directory')."</a></li>\n";82 echo "<li><a href=\"config.php?type=$type&display=directory&action=add\">"._('Add Directory')."</a></li>"; 49 83 if($results){ 50 84 foreach ($results as $key=>$result){ 51 if(!$result['dirname']){$result['dirname']='Directory '.$result['id'];} 52 echo "\t<li><a".($id==$result['id'] ? ' class="current"':''). ' href="config.php?type='.$type.'&display=directory&id='.$result['id'].'">'.$result['dirname']."</a></li>\n"; 85 if (!$result['dirname']) { 86 $result['dirname'] = 'Directory '.$result['id']; 87 } 88 if ($result['id'] == $def_dir) { 89 $result['dirname'] = '<span id="defdir" >' . $result['dirname'] . '</span>'; 90 } 91 echo "<li><a".($id==$result['id'] ? ' class="current"':''). ' href="config.php?type='.$type.'&display=directory&id='.$result['id'].'">'.$result['dirname']."</a></li>"; 53 92 } 54 93 } 55 echo "</ul> \n<br /></div>";94 echo "</ul><br /></div>"; 56 95 } 57 96 … … 76 115 $('#addbut').not("span").fadeIn(250).find("span").hide(); 77 116 }); 78 if($('#addusersel').val() !='none'){117 if($('#addusersel').val() != 'none'){ 79 118 var rownum=$('[class^=entrie]').length+1; 80 119 //increment id untill we find one that isnt being used 81 while($('.entrie' +rownum).length==1){120 while($('.entrie' + rownum).length == 1){ 82 121 rownum++; 83 122 } 84 addrow($('#addusersel').val() +'|'+rownum);123 addrow($('#addusersel').val() + '|' + rownum); 85 124 } 86 125 return false; … … 118 157 type: 'POST', 119 158 url: location.href, 120 data: 'ajaxgettr='+encodeURIComponent(user)+'&quietmode=1&skip_astman=1 &restrictmods=directory/core/recordings',159 data: 'ajaxgettr='+encodeURIComponent(user)+'&quietmode=1&skip_astman=1', 121 160 success: function(data) { 122 161 $('#dir_entries_tbl > tbody:last').append(data); … … 141 180 .dpt-title {color: #CCCCCC;} 142 181 .text-normal {color: inherit;} 182 .dirhr{width: 50%; margin-left: 0px;} 183 #defdir{font-weight:bold;} 143 184 </style> modules/branches/bootstrap-2.9/directory/uninstall.php
r9585 r10795 11 11 } 12 12 } 13 outn(_('dropping directory_details, directory_entries ..'));14 sql('DROP TABLE IF EXISTS directory_details, directory_entries ');13 outn(_('dropping directory_details, directory_entries, directory...')); 14 sql('DROP TABLE IF EXISTS directory_details, directory_entries, directory'); 15 15 out(_('ok')); 16 16 ?>
