root/modules/branches/bootstrap-2.9/queues/functions.inc.php

Revision 10684, 43.8 kB (checked in by mbrevda, 2 years ago)

re #4566 - merge forward

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1 <?php /* $id:$ */
2
3 class queues_conf {
4
5     var $_queues_general    = array();
6
7     // return an array of filenames to write
8     // files named like pinset_N
9     function get_filename() {
10         $files = array(
11             'queues_additional.conf',
12             'queues_general_additional.conf',
13             );
14         return $files;
15     }
16     
17     // return the output that goes in each of the files
18     function generateConf($file) {
19         global $version;
20
21         switch ($file) {
22             case 'queues_additional.conf':
23                 return $this->generate_queues_additional($version);
24                 break;
25             case 'queues_general_additional.conf':
26                 return $this->generate_queues_general_additional($version);
27                 break;
28         }
29     }
30
31     function addQueuesGeneral($key, $value) {
32         $this->_queues_general[] = array('key' => $key, 'value' => $value);
33     }
34
35     function generate_queues_additional($ast_version) {
36
37         global $db;
38         global $amp_conf;
39
40         $additional = "";
41         $output = "";
42         // Asterisk 1.4 does not like blank assignments so just don't put them there
43         //
44         $ver12 = version_compare($ast_version, '1.4', 'lt');
45         $ver16 = version_compare($ast_version, '1.6', 'ge');
46     $ast_ge_14_25 = version_compare($ast_version,'1.4.25','ge');
47         
48         // legacy but in case someone was using this we will leave it
49         //
50         $sql = "SELECT keyword,data FROM queues_details WHERE id='-1' AND keyword <> 'account'";
51         $results = $db->getAll($sql, DB_FETCHMODE_ASSOC);
52         if(DB::IsError($results)) {
53            die($results->getMessage());
54         }
55         foreach ($results as $result) {
56             if (!$ver12 && trim($result['data']) == '') {
57                 continue;
58             }
59             $additional .= $result['keyword']."=".$result['data']."\n";
60         }
61
62     if ($ast_ge_14_25) {
63           $devices = array();
64           $device_results = core_devices_list('all','full',true);
65           if (is_array($device_results)) {
66               foreach ($device_results as $device) {
67           if (!isset($devices[$device['user']]) && $device['devicetype'] == 'fixed') {
68                     $devices[$device['user']] = $device['dial'];
69           }
70               }
71               unset($device_results);
72           }
73     }
74     if ($amp_conf['USEQUEUESTATE'] || $ast_ge_14_25) {
75           $users = array();
76           $user_results = core_users_list();
77           if (is_array($user_results)) {
78               foreach ($user_results as $user) {
79                   $users[$user[0]] = $user[1];
80               }
81               unset($user_results);
82           }
83     }
84         $results = queues_list(true);
85         foreach ($results as $result) {
86             $output .= "[".$result[0]."]\n";
87
88             // passing 2nd param 'true' tells queues_get to send back only queue_conf required params
89             // and nothing else
90             //
91             $results2 = queues_get($result[0], true);
92
93             // memebers is an array of members so we set it asside and remove it
94             // and then generate each later
95             //
96             $members = $results2['member'];
97             unset($results2['member']);
98
99             foreach ($results2 as $keyword => $data) {
100                 if ($ver12){
101                     switch($keyword){
102                         case 'ringinuse':
103                         case 'autofill':
104                             break;
105                         case 'retry':
106                             if ($data == 'none') {
107                                 $data = 0;
108                             }
109                             // no break, fallthrough to default
110                         default:
111                             $output .= $keyword."=".$data."\n";
112                             break;
113                     }
114                 }else{
115                     switch($keyword){
116                         case (trim($data) == ''):
117                         case 'monitor-join':
118                             break;
119                         case 'monitor-format':
120                             if (strtolower($data) != 'no'){
121                                 $output .= "monitor-type=mixmonitor\n";
122                                 $output .= $keyword."=".$data."\n";
123                             }
124                             break;
125                         case 'announce-position':
126                             if ($ver16) {
127                                 $output .= $keyword."=".$data."\n";
128                             }
129                             break;
130                         case 'retry':
131                             if ($data == 'none') {
132                                 $data = 0;
133                             }
134                             // no break, fallthrough to default
135                         default:
136                             $output .= $keyword."=".$data."\n";
137                             break;
138                     }
139                 }
140             }
141
142             // Now pull out all the memebers, one line for each
143             //
144       if ($amp_conf['USEQUEUESTATE']) {
145               foreach ($members as $member) {
146                   preg_match("/^Local\/([\d]+)\@*/",$member,$matches);
147                   if (isset($matches[1]) && isset($users[$matches[1]])) {
148                       $name = $users[$matches[1]];
149                       str_replace(',','\,',$name);
150                       $output .= "member=$member,$name,hint:".$matches[1]."@ext-local\n";
151                   } else {
152                       $output .= "member=".$member."\n";
153                   }
154               }
155       } else if ($ast_ge_14_25) {
156               foreach ($members as $member) {
157                   preg_match("/^Local\/([\d]+)\@*/",$member,$matches);
158                   if (isset($matches[1]) && isset($devices[$matches[1]])) {
159                       $name = $users[$matches[1]];
160                       str_replace(',','\,',$name);
161                       $output .= "member=$member,$name,".$devices[$matches[1]]."\n";
162                   } else {
163                       $output .= "member=".$member."\n";
164                   }
165               }
166       } else {
167         foreach ($members as $member) {
168           $output .= "member=".$member."\n";
169         }
170       }
171             $output .= $additional."\n";
172         }
173
174         // Before returning the results, do an integrity check to see
175         // if there are any truncated compound recrodings and if so
176         // crate a noticication.
177         //
178         $nt = notifications::create($db);
179
180         $compound_recordings = queues_check_compoundrecordings();
181         if (empty($compound_recordings)) {
182             $nt->delete('queues', 'COMPOUNDREC');
183         } else {
184             $str = _("Warning, there are compound recordings configured in one or more Queue configurations. Queues can not play these so they have been truncated to the first sound file. You should correct this problem.<br />Details:<br /><br />");
185             foreach ($compound_recordings as $item) {
186                 $str .= sprintf(_("Queue - %s (%s): %s<br />"), $item['extension'], $item['descr'], $item['error']);
187             }
188             $nt->add_error('queues', 'COMPOUNDREC', _("Compound Recordings in Queues Detected"), $str);
189         }
190         return $output;
191     }
192
193     function generate_queues_general_additional($ast_version) {
194         $output = '';
195
196         if (isset($this->_queues_general) && is_array($this->_queues_general)) {
197             foreach ($this->_queues_general as $values) {
198                 $output .= $values['key']."=".$values['value']."\n";
199             }
200         }
201         return $output;
202     }
203 }
204
205 // The destinations this module provides
206 // returns a associative arrays with keys 'destination' and 'description'
207 function queues_destinations() {
208     //get the list of all exisiting
209     $results = queues_list(true);
210     
211     //return an associative array with destination and description
212     if (isset($results)) {
213         foreach($results as $result){
214                 $extens[] = array('destination' => 'ext-queues,'.$result['0'].',1', 'description' => $result['1'].' <'.$result['0'].'>');
215         }
216     }
217     
218     if (isset($extens))
219         return $extens;
220     else
221         return null;
222 }
223
224 function queues_getdest($exten) {
225     return array('ext-queues,'.$exten.',1');
226 }
227
228 function queues_getdestinfo($dest) {
229     global $active_modules;
230
231     if (substr(trim($dest),0,11) == 'ext-queues,') {
232         $exten = explode(',',$dest);
233         $exten = $exten[1];
234         $thisexten = queues_get($exten);
235         if (empty($thisexten)) {
236             return array();
237         } else {
238             //$type = isset($active_modules['announcement']['type'])?$active_modules['announcement']['type']:'setup';
239             return array('description' => sprintf(_("Queue %s : %s"),$exten,$thisexten['name']),
240                          'edit_url' => 'config.php?display=queues&extdisplay='.urlencode($exten),
241                                   );
242         }
243     } else {
244         return false;
245     }
246 }
247
248 function queues_recordings_usage($recording_id) {
249     global $active_modules;
250
251     $results = sql("SELECT `extension`, `descr` FROM `queues_config` WHERE `agentannounce_id` = '$recording_id' OR `joinannounce_id` = '$recording_id'","getAll",DB_FETCHMODE_ASSOC);
252     if (empty($results)) {
253         return array();
254     } else {
255         //$type = isset($active_modules['queues']['type'])?$active_modules['queues']['type']:'setup';
256         foreach ($results as $result) {
257             $usage_arr[] = array(
258               'url_query' => 'config.php?display=queues&extdisplay='.urlencode($result['extension']),
259                 'description' => sprintf(_("Queue: %s"),$result['descr']),
260             );
261         }
262         return $usage_arr;
263     }
264 }
265
266 function queues_ivr_usage($ivr_id) {
267     global $active_modules;
268
269     $results = sql("SELECT `extension`, `descr` FROM `queues_config` WHERE `ivr_id` = '$ivr_id'","getAll",DB_FETCHMODE_ASSOC);
270     if (empty($results)) {
271         return array();
272     } else {
273         foreach ($results as $result) {
274             $usage_arr[] = array(
275               'url_query' => 'config.php?display=queues&extdisplay='.urlencode($result['extension']),
276                 'description' => sprintf(_("Queue: %s"),$result['descr']),
277             );
278         }
279         return $usage_arr;
280     }
281 }
282
283 /*     Generates dialplan for "queues" components (extensions & inbound routing)
284     We call this with retrieve_conf
285 */
286 function queues_get_config($engine) {
287     global $ext// is this the best way to pass this?
288     global $queues_conf;
289     global $amp_conf;
290     global $version;
291
292     switch($engine) {
293         case "asterisk":
294             global $astman;
295
296       $ast_ge_14 = version_compare($version,'1.4','ge');
297       $ast_ge_16 = version_compare($version,'1.6','ge');
298       $ast_ge_14_25 = version_compare($version,'1.4.25','ge');
299
300       $has_extension_state = $ast_ge_16;
301             if ($ast_ge_14 && !$ast_ge_16) {
302                 $response = $astman->send_request('Command', array('Command' => 'module show like func_extstate'));
303                 if (preg_match('/1 modules loaded/', $response['data'])) {
304           $has_extension_state = true;
305         }
306             }
307
308             if (isset($queues_conf) && is_a($queues_conf, "queues_conf")) {
309                 $queues_conf->addQueuesGeneral('persistentmembers','yes');
310             }
311
312             /* queue extensions */
313             $ext->addInclude('from-internal-additional','ext-queues');
314             /* Trial DEVSTATE */
315             if ($amp_conf['USEDEVSTATE']) {
316                 $ext->addGlobal('QUEDEVSTATE','TRUE');
317             }
318             // $que_code = '*45';
319             $fcc = new featurecode('queues', 'que_toggle');
320             $que_code = $fcc->getCodeActive();
321             unset($fcc);
322             if ($que_code != '') {
323                 queue_app_toggle($que_code);
324                 queue_agent_del_toggle();
325                 queue_agent_add_toggle();
326             }
327             $qlist = queues_list(true);
328
329             $from_queue_exten_only = 'from-queue-exten-only';
330             $from_queue_exten_internal = 'from-queue-exten-internal';
331
332             if (is_array($qlist)) {
333                 foreach($qlist as $item) {
334                     
335                     $exten = $item[0];
336                     $q = queues_get($exten);
337
338                     $grppre = (isset($q['prefix'])?$q['prefix']:'');
339                     $alertinfo = (isset($q['alertinfo'])?$q['alertinfo']:'');
340
341                     // Not sure why someone would ever have a ; in the regex, but since Asterisk has problems with them
342                     // it would need to be escaped
343                     //
344                     $qregex = (isset($q['qregex'])?$q['qregex']:'');
345                     str_replace(';','\;',$qregex);
346                     
347                     $ext->add('ext-queues', $exten, '', new ext_macro('user-callerid'));
348                     $ext->add('ext-queues', $exten, '', new ext_answer(''));
349
350                     // block voicemail until phone is answered at which point a macro should be called on the answering
351                     // line to clear this flag so that subsequent transfers can occur.
352                     //
353                     if ($q['queuewait']) {
354                         $ext->add('ext-queues', $exten, '', new ext_execif('$["${QUEUEWAIT}" = ""]', 'Set', '__QUEUEWAIT=${EPOCH}'));
355                     }
356           // If extension_only don't do this and CFIGNORE
357           if($q['use_queue_context'] != '2') {
358                       $ext->add('ext-queues', $exten, '', new ext_setvar('__BLKVM_OVERRIDE', 'BLKVM/${EXTEN}/${CHANNEL}'));
359                       $ext->add('ext-queues', $exten, '', new ext_setvar('__BLKVM_BASE', '${EXTEN}'));
360                       $ext->add('ext-queues', $exten, '', new ext_setvar('DB(${BLKVM_OVERRIDE})', 'TRUE'));
361                       $ext->add('ext-queues', $exten, '', new ext_execif('$["${REGEX("(M[(]auto-blkvm[)])" ${DIAL_OPTIONS})}" != "1"]', 'Set', '_DIAL_OPTIONS=${DIAL_OPTIONS}M(auto-blkvm)'));
362           }
363
364                     // Inform all the children NOT to send calls to destinations or voicemail
365                     //
366                     $ext->add('ext-queues', $exten, '', new ext_setvar('__NODEST', '${EXTEN}'));
367
368                     // deal with group CID prefix
369                     // Use the same variable as ringgroups/followme so that we can manage chaines of calls
370                     // but strip only if you plan on setting a new one
371                     //
372                     if ($grppre != '') {
373                         $ext->add('ext-queues', $exten, '', new ext_gotoif('$["foo${RGPREFIX}" = "foo"]', 'REPCID'));
374                         $ext->add('ext-queues', $exten, '', new ext_gotoif('$["${RGPREFIX}" != "${CALLERID(name):0:${LEN(${RGPREFIX})}}"]', 'REPCID'));
375                         $ext->add('ext-queues', $exten, '', new ext_noop('Current RGPREFIX is ${RGPREFIX}....stripping from Caller ID'));
376                         $ext->add('ext-queues', $exten, '', new ext_setvar('CALLERID(name)', '${CALLERID(name):${LEN(${RGPREFIX})}}'));
377                         $ext->add('ext-queues', $exten, '', new ext_setvar('_RGPREFIX', ''));
378                         $ext->add('ext-queues', $exten, 'REPCID', new ext_noop('CALLERID(name) is ${CALLERID(name)}'));
379                         $ext->add('ext-queues', $exten, '', new ext_setvar('_RGPREFIX', $grppre));
380                         $ext->add('ext-queues', $exten, '', new ext_setvar('CALLERID(name)','${RGPREFIX}${CALLERID(name)}'));
381                     }
382
383                     // Set Alert_Info
384                     if ($alertinfo != '') {
385                         $ext->add('ext-queues', $exten, '', new ext_setvar('__ALERT_INFO', str_replace(';', '\;', $alertinfo)));
386                     }
387
388                     $ext->add('ext-queues', $exten, '', new ext_setvar('MONITOR_FILENAME','/var/spool/asterisk/monitor/q${EXTEN}-${STRFTIME(${EPOCH},,%Y%m%d-%H%M%S)}-${UNIQUEID}'));
389                     $joinannounce_id = (isset($q['joinannounce_id'])?$q['joinannounce_id']:'');
390                     if($joinannounce_id) {
391                         $joinannounce = recordings_get_file($joinannounce_id);
392                         $ext->add('ext-queues', $exten, '', new ext_playback($joinannounce));
393                     }
394                     $options = 't';
395                     if ($q['rtone'] == 1) {
396                         $options .= 'r';
397                     }
398                     if ($q['retry'] == 'none'){
399                         $options .= 'n';
400                     }
401                     if (isset($q['music'])) {
402                          $ext->add('ext-queues', $exten, '', new ext_setvar('__MOHCLASS', $q['music']));
403                     }
404                     // Set CWIGNORE  if enabled so that busy agents don't have another line key ringing and
405                     // stalling the ACD.
406                     if ($q['cwignore'] == 1 || $q['cwignore'] == 2 ) {
407                          $ext->add('ext-queues', $exten, '', new ext_setvar('__CWIGNORE', 'TRUE'));
408                     }
409                     if ($q['use_queue_context']) {
410                          $ext->add('ext-queues', $exten, '', new ext_setvar('__CFIGNORE', 'TRUE'));
411                          $ext->add('ext-queues', $exten, '', new ext_setvar('__FORWARD_CONTEXT', 'block-cf'));
412                     }
413                     $agentannounce_id = (isset($q['agentannounce_id'])?$q['agentannounce_id']:'');
414                     if ($agentannounce_id) {
415                         $agentannounce = recordings_get_file($agentannounce_id);
416                     } else {
417                         $agentannounce = '';
418                     }
419                     $ext->add('ext-queues', $exten, '', new ext_queue($exten,$options,'',$agentannounce,$q['maxwait']));
420  
421           if($q['use_queue_context'] != '2') {
422                       $ext->add('ext-queues', $exten, '', new ext_dbdel('${BLKVM_OVERRIDE}'));
423           }
424                      // If we are here, disable the NODEST as we want things to resume as normal
425                      //
426                      $ext->add('ext-queues', $exten, '', new ext_setvar('__NODEST', ''));
427                     if ($q['cwignore'] == 1 || $q['cwignore'] == 2 ) {
428                         $ext->add('ext-queues', $exten, '', new ext_setvar('__CWIGNORE', ''));
429                     }
430                     if ($q['use_queue_context']) {
431                          $ext->add('ext-queues', $exten, '', new ext_setvar('__CFIGNORE', ''));
432                          $ext->add('ext-queues', $exten, '', new ext_setvar('__FORWARD_CONTEXT', 'from-internal'));
433                     }
434     
435                     // destination field in 'incoming' database is backwards from what ext_goto expects
436                     $goto_context = strtok($q['goto'],',');
437                     $goto_exten = strtok(',');
438                     $goto_pri = strtok(',');
439                     
440                     $ext->add('ext-queues', $exten, '', new ext_goto($goto_pri,$goto_exten,$goto_context));
441                     
442                     //dynamic agent login/logout
443                     if (trim($qregex) != '') {
444                          $ext->add('ext-queues', $exten."*", '', new ext_setvar('QREGEX', $qregex));
445                     }
446           if($q['use_queue_context'] == '2') {
447                       $ext->add('ext-queues', $exten."*", '', new ext_macro('agent-add',$exten.",".$q['password'].",EXTEN"));
448           } else {
449                       $ext->add('ext-queues', $exten."*", '', new ext_macro('agent-add',$exten.",".$q['password']));
450           }
451                     $ext->add('ext-queues', $exten."**", '', new ext_macro('agent-del',"$exten"));
452                     if ($que_code != '') {
453             $ext->add('ext-queues', $que_code.$exten, '', new ext_setvar('QUEUENO',$exten));
454             $ext->add('ext-queues', $que_code.$exten, '', new ext_goto('start','s','app-queue-toggle'));
455           }
456                     /* Trial Devstate */
457                     // Create Hints for Devices and Add Astentries for Users
458                     // Clean up the Members array
459                     if ($q['togglehint'] && $amp_conf['USEDEVSTATE'] && $que_code != '') {
460             if (!isset($device_list)) {
461                           $device_list = core_devices_list("all", 'full', true);
462             }
463             if ($astman) {
464               if (($dynmemberonly = strtolower($astman->database_get('QPENALTY/'.$exten,'dynmemberonly')) == 'yes') == true) {
465                 $get=$astman->database_show('QPENALTY/'.$exten.'/agents');
466                 if($get){
467                   $mem = array();
468                   foreach($get as $key => $value){
469                     $key=explode('/',$key);
470                     $mem[$key[4]]=$value;
471                   }
472                 }
473               }
474             } else {
475               fatal("Cannot connect to Asterisk Manager with ".$amp_conf["AMPMGRUSER"]."/".$amp_conf["AMPMGRPASS"]);
476             }
477                         foreach ($device_list as $device) {
478               if ((!$dynmemberonly||$device['devicetype']=='adhoc'||isset($mem[$device['user']]))&&($device['tech']=='sip'||$device['tech']=='iax2')) {
479                               $ext->add('ext-queues', $que_code.$device['id'].'*'.$exten, '', new ext_setvar('QUEUENO',$exten));
480                               $ext->add('ext-queues', $que_code.$device['id'].'*'.$exten, '', new ext_goto('start','s','app-queue-toggle'));
481                               $ext->addHint('ext-queues', $que_code.$device['id'].'*'.$exten, "Custom:QUEUE".$device['id'].'*'.$exten);
482               }
483                         }
484                     }
485
486                     // Add routing vector to direct which context call should go
487                     //
488                     $agent_context = $q['use_queue_context'] ? $queue_context : 'from-internal';
489                     switch ($q['use_queue_context']) {
490                         case 1:
491                             $agent_context = $from_queue_exten_internal;
492                             break;
493                         case 2:
494                             $agent_context = $from_queue_exten_only;
495                             break;
496                         case 0:
497                         default:
498                             $agent_context = 'from-internal';
499                             break;
500                     }
501                     $ext->add('from-queue', $exten, '', new ext_goto('1','${QAGENT}',$agent_context));
502                 }
503             }
504             // We need to have a hangup here, if call is ended by the caller during Playback it will end in the
505             // h context and do a proper hangup and clean the BLKVM, see #4671
506             $ext->add('ext-queues', 'h', '', new ext_macro('hangupcall'));           
507             // NODEST will be the queue that this came from, so we will vector though an entry to determine the context the
508             // agent should be delivered to. All queue calls come here, this decides if the should go direct to from-internal
509             // or indirectly through from-queue-exten-only to trap extension calls and avoid their follow-me, etc.
510             //
511             $ext->add('from-queue', '_.', '', new ext_setvar('QAGENT','${EXTEN}'));
512             $ext->add('from-queue', '_.', '', new ext_goto('1','${NODEST}'));
513
514             $ext->addInclude($from_queue_exten_internal,$from_queue_exten_only);
515             $ext->addInclude($from_queue_exten_internal,'from-internal');
516             $ext->add($from_queue_exten_internal, 'foo', '', new ext_noop('bar'));
517
518             /* create a context, from-queue-exten-only, that can be used for queues that want behavir similar to
519              * ringgroup where only the agent's phone will be rung, no follow-me will be pursued.
520              */
521             $userlist = core_users_list();
522             if (is_array($userlist)) {
523                 foreach($userlist as $item) {
524                      $ext->add($from_queue_exten_only, $item[0], '', new ext_setvar('RingGroupMethod', 'none'));
525                     $ext->add($from_queue_exten_only, $item[0], '', new ext_macro('record-enable',$item[0].",IN"));
526           if ($has_extension_state) {
527                       $ext->add($from_queue_exten_only, $item[0], '', new ext_macro('dial-one',',${DIAL_OPTIONS},'.$item[0]));
528           } else {
529                       $ext->add($from_queue_exten_only, $item[0], '', new ext_macro('dial',',${DIAL_OPTIONS},'.$item[0]));
530           }
531                      $ext->add($from_queue_exten_only, $item[0], '', new ext_hangup());
532                 }
533                  $ext->add($from_queue_exten_only, 'h', '', new ext_macro('hangupcall'));
534             }
535
536             /*
537              * Adds a dynamic agent/member to a Queue
538              * Prompts for call-back number - in not entered, uses CIDNum
539              */
540
541             $context = 'macro-agent-add';
542             $exten = 's';
543             
544             $ext->add($context, $exten, '', new ext_wait(1));
545             $ext->add($context, $exten, '', new ext_macro('user-callerid', 'SKIPTTL'));
546             $ext->add($context, $exten, 'a3', new ext_read('CALLBACKNUM', 'agent-login'));  // get callback number from user
547             $ext->add($context, $exten, '', new ext_gotoif('$[${LEN(${CALLBACKNUM})}=0]','a5','a7'));  // if user just pressed # or timed out, use cidnum
548             $ext->add($context, $exten, 'a5', new ext_set('CALLBACKNUM', '${IF($[${LEN(${AMPUSER})}=0]?${CALLERID(number)}:${AMPUSER})}'));
549
550       if ($ast_ge_14_25) {
551               $ext->add($context, $exten, '', new ext_set('THISDEVICE', '${DB(DEVICE/${REALCALLERIDNUM}/dial)}'));
552       }
553             $ext->add($context, $exten, '', new ext_gotoif('$["${CALLBACKNUM}" = ""]', 'a3'));  // if still no number, start over
554             $ext->add($context, $exten, 'a7', new ext_gotoif('$["${CALLBACKNUM}" = "${ARG1}"]', 'invalid'));  // Error, they put in the queue number
555
556       // If this is an extension only queue then EXTEN is passed as ARG3 and we make sure this is a valid extension being entered
557       //
558             $ext->add($context, $exten, '', new ext_gotoif('$["${ARG3}" = "EXTEN" & ${DB_EXISTS(AMPUSER/${CALLBACKNUM}/cidname)} = 0]', 'invalid'));
559
560       // If this is a restricted dynamic agent queue then check to make sure they are allowed
561       //
562       $ext->add($context, $exten, '', new ext_gotoif('$["${DB(QPENALTY/${ARG1}/dynmemberonly)}" = "yes" & ${DB_EXISTS(QPENALTY/${ARG1}/agents/${CALLBACKNUM})} != 1]', 'invalid'));
563
564             $ext->add($context, $exten, '', new ext_execif('$["${QREGEX}" != ""]', 'GotoIf', '$["${REGEX("${QREGEX}" ${CALLBACKNUM})}" = "0"]?invalid'));
565             $ext->add($context, $exten, '', new ext_execif('$["${ARG2}" != ""]', 'Authenticate', '${ARG2}'));
566
567
568       if ($amp_conf['USEQUEUESTATE']) {
569               $ext->add($context, $exten, '', new ext_execif('$[${DB_EXISTS(AMPUSER/${CALLBACKNUM}/cidname)} = 1]', 'AddQueueMember', '${ARG1},Local/${CALLBACKNUM}@from-queue/n,${DB(QPENALTY/${ARG1}/agents/${CALLBACKNUM})},,${DB(AMPUSER/${CALLBACKNUM}/cidname)},hint:${CALLBACKNUM}@ext-local'));
570               $ext->add($context, $exten, '', new ext_execif('$[${DB_EXISTS(AMPUSER/${CALLBACKNUM}/cidname)} = 0]', 'AddQueueMember', '${ARG1},Local/${CALLBACKNUM}@from-queue/n,${DB(QPENALTY/${ARG1}/agents/${CALLBACKNUM})}'));
571       } else if ($ast_ge_14_25) {
572               $ext->add($context, $exten, '', new ext_set('THISDEVICE', '${IF($[${LEN(${THISDEVICE})}=0]?${DB(DEVICE/${CUT(DB(AMPUSER/${CALLBACKNUM}/device),&,1)}/dial)}:${THISDEVICE})}'));
573               $ext->add($context, $exten, '', new ext_execif('$[${LEN(${THISDEVICE})}!=0]', 'AddQueueMember', '${ARG1},Local/${CALLBACKNUM}@from-queue/n,${DB(QPENALTY/${ARG1}/agents/${CALLBACKNUM})},,${DB(AMPUSER/${CALLBACKNUM}/cidname)},${THISDEVICE}'));
574               $ext->add($context, $exten, '', new ext_execif('$[${LEN(${THISDEVICE})}=0]', 'AddQueueMember', '${ARG1},Local/${CALLBACKNUM}@from-queue/n,${DB(QPENALTY/${ARG1}/agents/${CALLBACKNUM})}'));
575       } else {
576         $ext->add($context, $exten, 'a9', new ext_addqueuemember('${ARG1}', 'Local/${CALLBACKNUM}@from-queue/n,${DB(QPENALTY/${ARG1}/agents/${CALLBACKNUM})}'));
577       }
578           $ext->add($context, $exten, '', new ext_userevent('Agentlogin', 'Agent: ${CALLBACKNUM}'));
579           $ext->add($context, $exten, '', new ext_wait(1));
580           $ext->add($context, $exten, '', new ext_playback('agent-loginok&with&extension'));
581           $ext->add($context, $exten, '', new ext_saydigits('${CALLBACKNUM}'));
582           $ext->add($context, $exten, '', new ext_hangup());
583           $ext->add($context, $exten, '', new ext_macroexit());
584           $ext->add($context, $exten, 'invalid', new ext_playback('pbx-invalid'));
585           $ext->add($context, $exten, '', new ext_goto('a3'));
586
587             /*
588              * Removes a dynamic agent/member from a Queue
589              * Prompts for call-back number - in not entered, uses CIDNum
590              */
591
592             $context = 'macro-agent-del';
593             
594             $ext->add($context, $exten, '', new ext_wait(1));
595             $ext->add($context, $exten, '', new ext_macro('user-callerid', 'SKIPTTL'));
596             $ext->add($context, $exten, 'a3', new ext_read('CALLBACKNUM', 'agent-logoff'));  // get callback number from user
597             $ext->add($context, $exten, '', new ext_gotoif('$[${LEN(${CALLBACKNUM})}=0]','a5','a7'));  // if user just pressed # or timed out, use cidnum
598             $ext->add($context, $exten, 'a5', new ext_set('CALLBACKNUM', '${IF($[${LEN(${AMPUSER})}=0]?${CALLERID(number)}:${AMPUSER})}'));
599             $ext->add($context, $exten, '', new ext_gotoif('$["${CALLBACKNUM}" = ""]', 'a3'));  // if still no number, start over
600
601             // remove from both contexts in case left over dynamic agents after an upgrade
602             $ext->add($context, $exten, 'a7', new ext_removequeuemember('${ARG1}', 'Local/${CALLBACKNUM}@from-queue/n'));
603             $ext->add($context, $exten, '', new ext_removequeuemember('${ARG1}', 'Local/${CALLBACKNUM}@from-internal/n'));
604             $ext->add($context, $exten, '', new ext_userevent('RefreshQueue'));
605             $ext->add($context, $exten, '', new ext_wait(1));
606             $ext->add($context, $exten, '', new ext_playback('agent-loggedoff'));
607             $ext->add($context, $exten, '', new ext_hangup());
608         break;
609     }
610 }
611
612 function queues_timeString($seconds, $full = false) {
613     if ($seconds == 0) {
614         return "0 ".($full ? _("seconds") : "s");
615     }
616
617     $minutes = floor($seconds / 60);
618     $seconds = $seconds % 60;
619
620     $hours = floor($minutes / 60);
621     $minutes = $minutes % 60;
622
623     $days = floor($hours / 24);
624     $hours = $hours % 24;
625
626     if ($full) {
627          return substr(
628                       ($days ? $days." "._("day").(($days == 1) ? "" : "s").", " : "").
629                       ($hours ? $hours." ".(($hours == 1) ? _("hour") : _("hours")).", " : "").
630                       ($minutes ? $minutes." ".(($minutes == 1) ? _("minute") : _("minutes")).", " : "").
631                       ($seconds ? $seconds." ".(($seconds == 1) ? _("second") : _("seconds")).", " : ""),
632                       0, -2);
633     } else {
634         return substr(($days ? $days."d, " : "").($hours ? $hours."h, " : "").($minutes ? $minutes."m, " : "").($seconds ? $seconds."s, " : ""), 0, -2);
635     }
636 }
637
638 function queues_add($account,$name,$password,$prefix,$goto,$agentannounce_id,$members,$joinannounce_id,$maxwait,$alertinfo='',$cwignore='0',$qregex='',$queuewait='0', $use_queue_context='0', $dynmembers = '', $dynmemberonly = 'no', $togglehint = '0') {
639   global $db,$astman,$amp_conf;
640
641     if (trim($account) == '') {
642         echo "<script>javascript:alert('"._("Bad Queue Number, can not be blank")."');</script>";
643         return false;
644     }
645
646     //add to extensions table
647     if (empty($agentannounce_id)) {
648         $agentannounce_id="";
649     }
650
651 $fields = array(
652     array($account,'maxlen',($_REQUEST['maxlen'])?$_REQUEST['maxlen']:'0',0),
653     array($account,'joinempty',($_REQUEST['joinempty'])?$_REQUEST['joinempty']:'yes',0),
654     array($account,'leavewhenempty',($_REQUEST['leavewhenempty'])?$_REQUEST['leavewhenempty']:'no',0),
655     array($account,'strategy',($_REQUEST['strategy'])?$_REQUEST['strategy']:'ringall',0),
656     array($account,'timeout',(isset($_REQUEST['timeout']))?$_REQUEST['timeout']:'15',0),
657     array($account,'retry',(isset($_REQUEST['retry']) && $_REQUEST['retry'] != '')?$_REQUEST['retry']:'5',0),
658     array($account,'wrapuptime',($_REQUEST['wrapuptime'])?$_REQUEST['wrapuptime']:'0',0),
659     array($account,'announce-frequency',($_REQUEST['announcefreq'])?$_REQUEST['announcefreq']:'0',0),
660     array($account,'announce-holdtime',($_REQUEST['announceholdtime'])?$_REQUEST['announceholdtime']:'no',0),
661     array($account,'announce-position',($_REQUEST['announceposition'])?$_REQUEST['announceposition']:'no',0),
662     array($account,'queue-youarenext',($_REQUEST['announceposition']=='no')?'silence/1':'queue-youarenext',0),  //if no, play no sound
663     array($account,'queue-thereare',($_REQUEST['announceposition']=='no')?'silence/1':'queue-thereare',0),  //if no, play no sound
664     array($account,'queue-callswaiting',($_REQUEST['announceposition']=='no')?'silence/1':'queue-callswaiting',0),  //if no, play no sound
665     array($account,'queue-thankyou',($_REQUEST['announceposition']=='no')?'':'queue-thankyou',0),  //if no, play no sound
666     array($account,'periodic-announce-frequency',($_REQUEST['pannouncefreq'])?$_REQUEST['pannouncefreq']:'0',0),
667     array($account,'monitor-format',($_REQUEST['monitor-format'])?$_REQUEST['monitor-format']:'',0),
668     array($account,'monitor-join','yes',0),
669     array($account,'eventwhencalled',($_REQUEST['eventwhencalled'])?$_REQUEST['eventwhencalled']:'no',0),
670     array($account,'eventmemberstatus',($_REQUEST['eventmemberstatus'])?$_REQUEST['eventmemberstatus']:'no',0),
671     array($account,'weight',(isset($_REQUEST['weight']))?$_REQUEST['weight']:'0',0),
672     array($account,'autofill',(isset($_REQUEST['autofill']))?'yes':'no',0),
673     array($account,'ringinuse',($cwignore == 2 || $cwignore == 3)?'no':'yes',0),
674     array($account,'reportholdtime',(isset($_REQUEST['reportholdtime']))?$_REQUEST['reportholdtime']:'no',0),
675     array($account,'servicelevel',(isset($_REQUEST['servicelevel']))?$_REQUEST['servicelevel']:60,0),
676 );
677
678     if ($_REQUEST['music'] != 'inherit') {
679         $fields[] = array($account,'music',($_REQUEST['music'])?$_REQUEST['music']:'default',0);
680     }
681
682     //there can be multiple members
683     if (isset($members)) {
684         $count = 0;
685         $members = array_unique($members);
686         foreach ($members as $member) {
687             $fields[] = array($account,'member',$member,$count);
688             $count++;
689         }
690     }
691
692     $compiled = $db->prepare('INSERT INTO queues_details (id, keyword, data, flags) values (?,?,?,?)');
693     $result = $db->executeMultiple($compiled,$fields);
694     if(DB::IsError($result)) {
695         die_freepbx($result->getMessage()."<br><br>error adding to queues_details table");   
696     }
697     $extension        = $account;
698     $descr         = isset($name) ? $db->escapeSimple($name):'';
699     $grppre        = isset($prefix) ? $db->escapeSimple($prefix):'';
700     $alertinfo     = isset($alertinfo) ? $db->escapeSimple($alertinfo):'';
701     //$joinannounce_id  = $joinannounce_id;
702     $ringing       = isset($_REQUEST['rtone']) ? $_REQUEST['rtone']:'';
703     //$agentannounce_id = $agentannounce_id;
704     $maxwait       = isset($maxwait) ? $maxwait:'';
705     $password      = isset($password) ? $password:'';
706     $ivr_id        = isset($_REQUEST['announcemenu']) ? $_REQUEST['announcemenu']:'none';
707     $dest          = isset($goto) ? $goto:'';
708     $cwignore      = isset($cwignore) ? $cwignore:'0';
709     $queuewait     = isset($queuewait) ? $queuewait:'0';
710     $qregex        = isset($qregex) ? $db->escapeSimple($qregex):'';
711     $use_queue_context = isset($use_queue_context) ? $use_queue_context:'0';
712     $togglehint    = isset($togglehint) ? $togglehint:'0';
713
714     // Assumes it has just been deleted
715     $sql = "INSERT INTO queues_config (extension, descr, grppre, alertinfo, joinannounce_id, ringing, agentannounce_id, maxwait, password, ivr_id, dest, cwignore, qregex, queuewait, use_queue_context, togglehint)
716              VALUES ('$extension', '$descr', '$grppre', '$alertinfo', '$joinannounce_id', '$ringing', '$agentannounce_id', '$maxwait', '$password', '$ivr_id', '$dest', '$cwignore', '$qregex', '$queuewait', '$use_queue_context', '$togglehint')    ";
717     $results = sql($sql);
718
719   // store dynamic member data in astDB
720     if ($astman) {
721     $dynmembers = array_unique($dynmembers);
722       foreach($dynmembers as $member){
723         $mem=explode(',',$member);
724       if (isset($mem[0]) && trim($mem[0]) != '') {
725         $penalty = isset($mem[1]) && ctype_digit(trim($mem[1])) ? $mem[1] : 0;
726           $astman->database_put('QPENALTY/'.$account.'/agents',trim($mem[0]),trim($penalty));
727       }
728     }
729        $astman->database_put('QPENALTY/'.$account,'dynmemberonly',$dynmemberonly);
730     } else {
731         fatal("Cannot connect to Asterisk Manager with ".$amp_conf["AMPMGRUSER"]."/".$amp_conf["AMPMGRPASS"]);
732     }
733
734     return true;
735 }
736
737 function queues_del($account) {
738     global $db,$astman,$amp_conf;
739     
740     $sql = "DELETE FROM queues_details WHERE id = '$account'";
741     $result = $db->query($sql);
742     if(DB::IsError($result)) {
743         die_freepbx($result->getMessage().$sql);
744     }
745     $sql = "DELETE FROM queues_config WHERE extension = '$account'";
746     $result = $db->query($sql);
747     if(DB::IsError($result)) {
748         die_freepbx($result->getMessage().$sql);
749     }
750     
751     //remove dynamic memebers from astDB
752     if ($astman) {
753       $astman->database_deltree('QPENALTY/'.$account);
754     } else {
755         fatal("Cannot connect to Asterisk Manager with ".$amp_conf["AMPMGRUSER"]."/".$amp_conf["AMPMGRPASS"]);
756     }
757 }
758
759 //get the existing queue extensions
760 //
761 function queues_list($listall=false) {
762     global $db;
763     $sql = "SELECT extension, descr FROM queues_config ORDER BY extension";
764     $results = $db->getAll($sql);
765     if(DB::IsError($results)) {
766         $results = array();
767     }
768
769     foreach($results as $result){
770         if ($listall || checkRange($result[0])){
771             $extens[] = array($result[0],$result[1]);
772         }
773     }
774     if (isset($extens)) {
775         return $extens;
776     } else {
777         return array();
778     }
779 }
780
781 function queues_check_extensions($exten=true) {
782     global $active_modules;
783
784     $extenlist = array();
785     if (is_array($exten) && empty($exten)) {
786         return $extenlist;
787     }
788     $sql = "SELECT extension, descr FROM queues_config ";
789     if (is_array($exten)) {
790         $sql .= "WHERE extension in ('".implode("','",$exten)."')";
791     }
792     $sql .= " ORDER BY extension";
793     $results = sql($sql,"getAll",DB_FETCHMODE_ASSOC);
794
795     //$type = isset($active_modules['queues']['type'])?$active_modules['queues']['type']:'setup';
796     foreach ($results as $result) {
797         $thisexten = $result['extension'];
798         $extenlist[$thisexten]['description'] = sprintf(_("Queue: %s"),$result['descr']);
799         $extenlist[$thisexten]['status'] = _('INUSE');
800         $extenlist[$thisexten]['edit_url'] = 'config.php?display=queues&extdisplay='.urlencode($thisexten);
801     }
802     return $extenlist;
803 }
804
805 function queues_check_destinations($dest=true) {
806     global $active_modules;
807
808     $destlist = array();
809     if (is_array($dest) && empty($dest)) {
810         return $destlist;
811     }
812     $sql = "SELECT extension, descr, dest FROM queues_config";
813     if ($dest !== true) {
814         $sql .= " WHERE dest in ('".implode("','",$dest)."')";
815     }
816     $sql .= " ORDER BY extension";
817
818     $results = sql($sql,"getAll",DB_FETCHMODE_ASSOC);
819
820     //$type = isset($active_modules['announcement']['type'])?$active_modules['announcement']['type']:'setup';
821
822     foreach ($results as $result) {
823         $thisdest = $result['dest'];
824         $thisid   = $result['extension'];
825         $destlist[] = array(
826             'dest' => $thisdest,
827             'description' => sprintf(_("Queue: %s (%s)"),$result['descr'],$thisid),
828             'edit_url' => 'config.php?display=queues&extdisplay='.urlencode($thisid),
829         );
830     }
831     return $destlist;
832 }
833
834 function queues_check_compoundrecordings() {
835     global $db;
836
837     $compound_recordings = array();
838     $sql = "SELECT extension, descr, agentannounce_id, ivr_id FROM queues_config WHERE (ivr_id != 'none' AND ivr_id != '') OR agentannounce_id != ''";
839     $results = sql($sql, "getAll",DB_FETCHMODE_ASSOC);
840
841     if (function_exists('ivr_list')) {
842         $ivr_details = ivr_list();
843         foreach ($ivr_details as $item) {
844             $ivr_hash[$item['ivr_id']] = $item;
845         }
846         $check_ivr = true;
847     } else {
848         $check_ivr = false;
849     }
850
851     foreach ($results as $result) {
852         $agentannounce = $result['agentannounce_id'] ? recordings_get_file($result['agentannounce_id']):'';
853         if (strpos($agentannounce,"&") !== false) {
854             $compound_recordings[] = array(
855                                            'extension' => $result['extension'],
856                                                                  'descr' => $result['descr'],
857                                                                  'error' => _("Agent Announce Msg"),
858                                                              );
859         }
860         if ($result['ivr_id'] != 'none' && $result['ivr_id'] != '' && $check_ivr) {
861             $id = $ivr_hash[$result['ivr_id']]['announcement_id'];
862             $announce = $id ? recordings_get_file($id) : '';
863             if (strpos($announce,"&") !== false) {
864                 $compound_recordings[] = array(
865                                                'extension' => $result['extension'],
866                                                                      'descr' => $result['descr'],
867                                                                      'error' => sprintf(_("IVR Announce: %s"),$ivr_hash[$result['ivr_id']]['displayname']),
868                                                                  );
869             }
870         }
871     }
872     return $compound_recordings;
873 }
874
875
876 function queues_get($account, $queues_conf_only=false) {
877     global $db,$astman,$amp_conf;
878     
879     if ($account == "")
880     {
881         return array();
882     }
883
884     $account = q($account);
885     //get all the variables for the queue
886     $sql = "SELECT keyword,data FROM queues_details WHERE id = $account";
887     $results = $db->getAssoc($sql);
888     if (empty($results)) {
889         return array();
890     }
891
892     //okay, but there can be multiple member variables ... do another select for them
893     $sql = "SELECT data FROM queues_details WHERE id = $account AND keyword = 'member' order by flags";
894     $results['member'] = $db->getCol($sql);
895     
896     //if 'queue-youarenext=queue-youarenext', then assume we want to announce position
897     if (!$queues_conf_only) {
898         if(isset($results['queue-youarenext']) && $results['queue-youarenext'] == 'queue-youarenext') {
899             $results['announce-position'] = 'yes';
900         } else {
901             $results['announce-position'] = 'no';
902         }
903     }
904     
905     //if 'eventmemberstatusoff=Yes', then assume we want to 'eventmemberstatus=no'
906     if(isset($results['eventmemberstatusoff'])) {
907         if (strtolower($results['eventmemberstatusoff']) == 'yes') {
908             $results['eventmemberstatus'] = 'no';
909         } else {
910             $results['eventmemberstatus'] = 'yes';
911         }
912     } elseif (!isset($results['eventmemberstatus'])){
913         $results['eventmemberstatus'] = 'no';
914     }
915
916     if ($queues_conf_only) {
917         $sql = "SELECT ivr_id FROM queues_config WHERE extension = $account";
918         $config = sql($sql, "getRow",DB_FETCHMODE_ASSOC);
919
920         // We need to strip off all but the first sound file of any compound sound files
921         //
922         $results['agentannounce_id'] = $agentannounce_id_arr[0];
923     } else {
924         $sql = "SELECT * FROM queues_config WHERE extension = $account";
925         $config = sql($sql, "getRow",DB_FETCHMODE_ASSOC);
926
927         $results['prefix']        = $config['grppre'];
928         $results['alertinfo']     = $config['alertinfo'];
929         $results['agentannounce_id'] = $config['agentannounce_id'];
930         $results['maxwait']       = $config['maxwait'];
931         $results['name']          = $config['descr'];
932         $results['joinannounce_id']  = $config['joinannounce_id'];
933         $results['password']      = $config['password'];
934         $results['goto']          = $config['dest'];
935         $results['announcemenu']  = $config['ivr_id'];
936         $results['rtone']         = $config['ringing'];
937         $results['cwignore']      = $config['cwignore'];
938         $results['qregex']        = $config['qregex'];
939         $results['queuewait']     = $config['queuewait'];
940         $results['use_queue_context'] = $config['use_queue_context'];
941         $results['togglehint']    = $config['togglehint'];
942
943     // TODO: why the str_replace?
944     //
945       if ($astman) {
946         $account=str_replace("'",'',$account);
947         //get dynamic members priority from astDB
948         $get=$astman->database_show('QPENALTY/'.$account.'/agents');
949         if($get){
950             foreach($get as $key => $value){
951                 $key=explode('/',$key);
952                 $mem[$key[4]]=$value;
953             }
954             foreach($mem as $mem => $pnlty){
955                 $dynmem[]=$mem.','.$pnlty;
956             }
957           $results['dynmembers']=implode("\n",$dynmem);
958         } else {
959           $results['dynmembers']='';
960       }
961         $results['dynmemberonly'] = $astman->database_get('QPENALTY/'.$account,'dynmemberonly');
962       } else {
963           fatal("Cannot connect to Asterisk Manager with ".$amp_conf["AMPMGRUSER"]."/".$amp_conf["AMPMGRPASS"]);
964       }
965     }
966
967     $results['context'] = '';
968     $results['periodic-announce'] = '';
969
970     if ($config['ivr_id'] != 'none' && $config['ivr_id'] != '') {
971         if (function_exists('ivr_get_details')) {
972             $results['context'] = "ivr-".$config['ivr_id'];
973             $arr = ivr_get_details($config['ivr_id']);
974             if( isset($arr['announcement_id']) && $arr['announcement_id'] != '') {
975                 $periodic = recordings_get_file($arr['announcement_id']);
976                 // We need to strip off all but the first sound file of any compound sound files
977                 //
978                 $periodic_arr = explode("&", $periodic);
979                 $results['periodic-announce'] = $periodic_arr[0];
980             }
981         }
982     }
983     return $results;
984 }
985 /* Trial DEVSTATE */
986 function queue_app_toggle($c) {
987     global $ext;
988     global $amp_conf;
989     global $version;
990
991   $DEVSTATE = version_compare($version, "1.6", "ge") ? "DEVICE_STATE" : "DEVSTATE";
992
993     $id = "app-queue-toggle"; // The context to be included
994     $ext->addInclude('from-internal-additional', $id); // Add the include from from-internal
995
996     $c = 's';
997
998     $ext->add($id, $c, 'start', new ext_answer(''));
999     $ext->add($id, $c, '', new ext_wait('1'));
1000     $ext->add($id, $c, '', new ext_macro('user-callerid'));
1001     $ext->add($id, $c, '', new ext_setvar('QUEUESTAT', 'LOGGEDOUT'));
1002     $ext->add($id, $c, '', new ext_agi('queue_devstate.agi,getqueues,${AMPUSER}'));
1003
1004     $ext->add($id, $c, '', new ext_gotoif('$["${QUEUESTAT}" = "LOGGEDOUT"]', 'activate'));
1005     $ext->add($id, $c, '', new ext_gotoif('$["${QUEUESTAT}" = "LOGGEDIN"]', 'deactivate'));
1006     $ext->add($id, $c, '', new ext_gotoif('$["${QUEUESTAT}" = "STATIC"]', 'static','end'));
1007     $ext->add($id, $c, 'deactivate', new ext_noop('Agent Logged out'));
1008     $ext->add($id, $c, '', new ext_macro('toggle-del-agent'));
1009     if ($amp_conf['USEDEVSTATE']) {
1010         $ext->add($id, $c, '', new ext_setvar('STATE', 'NOT_INUSE'));
1011         $ext->add($id, $c, '', new ext_gosub('1', 'sstate'));
1012         }
1013     $ext->add($id, $c, '', new ext_playback('agent-loggedoff'));
1014     $ext->add($id, $c, '', new ext_macro('hangupcall'));
1015
1016     $ext->add($id, $c, 'activate', new ext_noop('Agent Logged In'));
1017     $ext->add($id, $c, '', new ext_macro('toggle-add-agent'));
1018     if ($amp_conf['USEDEVSTATE']) {
1019         $ext->add($id, $c, '', new ext_setvar('STATE', 'INUSE'));
1020         $ext->add($id, $c, '', new ext_gosub('1', 'sstate'));
1021     }
1022     $ext->add($id, $c, '', new ext_playback('agent-loginok'));
1023     $ext->add($id, $c, '', new ext_saydigits('${CALLBACKNUM}'));
1024     $ext->add($id, $c, '', new ext_macro('hangupcall'));
1025
1026     $ext->add($id, $c, 'static', new ext_noop('User is a Static Agent'));
1027     if ($amp_conf['USEDEVSTATE']) {
1028         $ext->add($id, $c, '', new ext_setvar('STATE', 'INUSE'));
1029         $ext->add($id, $c, '', new ext_gosub('1', 'sstate'));
1030     }
1031     $ext->add($id, $c, '', new ext_playback('agent-loginok'));
1032     $ext->add($id, $c, '', new ext_macro('hangupcall'));
1033
1034     if ($amp_conf['USEDEVSTATE']) {
1035         $c = 'sstate';
1036         $ext->add($id, $c, '', new ext_dbget('DEVICES','AMPUSER/${AMPUSER}/device'));
1037         $ext->add($id, $c, '', new ext_gotoif('$["${DEVICES}" = "" ]', 'return'));
1038         $ext->add($id, $c, '', new ext_setvar('LOOPCNT', '${FIELDQTY(DEVICES,&)}'));
1039         $ext->add($id, $c, '', new ext_setvar('ITER', '1'));
1040         $ext->add($id, $c, 'begin', new ext_setvar($DEVSTATE.'(Custom:QUEUE${CUT(DEVICES,&,${ITER})}*${QUEUENO})','${STATE}'));
1041         $ext->add($id, $c, '', new ext_setvar('ITER', '$[${ITER} + 1]'));
1042         $ext->add($id, $c, '', new ext_gotoif('$[${ITER} <= ${LOOPCNT}]', 'begin'));
1043         $ext->add($id, $c, 'return', new ext_return());
1044         }
1045 }
1046 function queue_agent_add_toggle() {
1047     global $ext;
1048     global $amp_conf;
1049     global $version;
1050
1051   $ast_ge_14_25 = version_compare($version,'1.4.25','ge');
1052     $id = "macro-toggle-add-agent"; // The context to be included
1053
1054     $c = 's';
1055
1056     $ext->add($id, $c, '', new ext_wait('1'));
1057     $ext->add($id, $c, '', new ext_macro('user-callerid,SKIPTTL'));
1058     $ext->add($id, $c, '', new ext_setvar('CALLBACKNUM','${AMPUSER}'));
1059   //TODO: check if it's not a user for some reason and abort?
1060   $ext->add($id, $c, '', new ext_gotoif('$["${DB(QPENALTY/${QUEUENO}/dynmemberonly)}" = "yes" & ${DB_EXISTS(QPENALTY/${QUEUENO}/agents/${CALLBACKNUM})} != 1]', 'invalid'));
1061   if ($amp_conf['USEQUEUESTATE']) {
1062       $ext->add($id, $c, '', new ext_addqueuemember('${QUEUENO}','Local/${CALLBACKNUM}@from-queue/n,${DB(QPENALTY/${QUEUENO}/agents/${CALLBACKNUM})},,${DB(AMPUSER/${CALLBACKNUM}/cidname)},hint:${CALLBACKNUM}@ext-local'));
1063   } else if ($ast_ge_14_25) {
1064       $ext->add($id, $c, '', new ext_addqueuemember('${QUEUENO}','Local/${CALLBACKNUM}@from-queue/n,${DB(QPENALTY/${QUEUENO}/agents/${CALLBACKNUM})},,${DB(AMPUSER/${CALLBACKNUM}/cidname)},${DB(DEVICE/${REALCALLERIDNUM}/dial)}'));
1065   } else {
1066       $ext->add($id, $c, '', new ext_addqueuemember('${QUEUENO}','Local/${CALLBACKNUM}@from-queue/n,${DB(QPENALTY/${QUEUENO}/agents/${CALLBACKNUM})}'));
1067   }
1068
1069     $ext->add($id, $c, '', new ext_userevent('AgentLogin','Agent: ${CALLBACKNUM}'));
1070     $ext->add($id, $c, '', new ext_macroexit());
1071   $ext->add($id, $c, 'invalid', new ext_playback('pbx-invalid'));
1072     $ext->add($id, $c, '', new ext_macroexit());
1073 }
1074
1075 function queue_agent_del_toggle() {
1076     global $ext;
1077     global $amp_conf;
1078
1079     $id = "macro-toggle-del-agent"; // The context to be included
1080
1081     $c = 's';
1082
1083     $ext->add($id, $c, '', new ext_wait('1'));
1084     $ext->add($id, $c, '', new ext_macro('user-callerid,SKIPTTL'));
1085     $ext->add($id, $c, '', new ext_setvar('CALLBACKNUM','${AMPUSER}'));
1086     $ext->add($id, $c, '', new ext_removequeuemember('${QUEUENO}','Local/${CALLBACKNUM}@from-queue/n'));
1087     $ext->add($id, $c, '', new ext_removequeuemember('${QUEUENO}','Local/${CALLBACKNUM}@from-internal/n'));
1088     $ext->add($id, $c, '', new ext_userevent('RefreshQueue'));
1089     $ext->add($id, $c, '', new ext_macroexit());
1090 }
1091
1092 function queue_change_destination($old_dest, $new_dest) {
1093     $sql = 'UPDATE queues_config SET dest = "' . $new_dest . '" WHERE dest = "' . $old_dest . '"';
1094     sql($sql, "query");
1095 }
1096 ?>
Note: See TracBrowser for help on using the browser.