Code

udpated queue attributes.
[gosa.git] / plugins / admin / ogroups / class_phonequeue.inc
1 <?php
3 class phonequeue extends plugin
4 {
5   /* plugin specific values */
6   var $mail= "";
7   var $cn= "";
8   var $old_cn ="";
10   var $goFonTimeOut             ="20"; 
11   var $goFonMaxLen              ="20"; // 
12   var $goFonAnnounceFrequency   ="60"; // Annouce Frequency in seconds
13   var $goFonDialOption_t        ="";
14   var $goFonDialOption_T        ="";
15   var $goFonDialOption_h        ="";
16   var $goFonDialOption_r        ="";
17   var $goFonQueueAnnounce       ="gonicus-berlin-welcome";
18   var $goFonDialOption_H        ="";
19   var $goFonMusiconHold         ="default";
20   var $goFonWelcomeMusic        ="gonicus-berlin-welcome";
21   var $goFonQueueReportHold     ="yes";
22   var $goFonQueueYouAreNext     ="queue-youarenext";
23   var $goFonQueueThereAre       ="queue-thereare";
24   var $goFonQueueCallsWaiting   ="queue-callswaiting";
25   var $goFonQueueThankYou       ="queue-thankyou";
26   var $goFonQueueMinutes        ="queue-minutes"; 
27   var $goFonQueueSeconds        ="queue-seconds";
28   var $goFonQueueLessThan       ="queue-lessthan";
29   var $goFonQueueLanguage       ="queue-holdtime";
30   var $goFonQueueStrategy       ="ringall";
31   var $goFonQueueAnnounceHoldtime="yes";
32   var $telephoneNumber          =array();
33   var $goFonQueueMember         =array(); 
34   var $goFonDialOption          ="";
35   var $goFonQueueRetry          =5;
37   var $goFonQueueStrategyOptions=array();
38   var $goFonQueueStrategyOptionsR=array();
39   
40   var $old_phone_numbers        =array();
42   var $goFonHomeServer  = "0";
43   var $init_HomeServer  = "0";
44   var $goFonHomeServers = array();
46   /* attribute list for save action */
47   var $attributes= array( "goFonTimeOut","goFonMaxLen","goFonAnnounceFrequency","goFonDialOption_t","goFonDialOption_T",
48       "goFonDialOption_h","goFonDialOption_r","cn","goFonHomeServer",
49       "goFonDialOption_H","goFonMusiconHold","goFonWelcomeMusic","goFonQueueReportHold","goFonQueueYouAreNext",
50       "goFonQueueThereAre","goFonQueueCallsWaiting","goFonQueueThankYou","goFonQueueMinutes","goFonQueueSeconds","goFonQueueLessThan",
51       "telephoneNumber","goFonQueueLanguage","goFonQueueStrategy","goFonQueueAnnounceHoldtime","goFonQueueAnnounce","goFonDialOption","goFonQueueRetry");
53   /* ObjectClass */
54   var $objectclasses= array("goFonQueue");
58   /* Pluigin initialization 
59    * - Check currently selected and available home server.
60    * - Set default home server if necessary
61    * - Parse phone options flags
62    * - Get phone numbers 
63    */
64   function phonequeue ($config, $dn= NULL)
65   {
66     plugin::plugin($config, $dn);
68     /* Check server configurations
69      * Load all server configuration in $this->goFonHomeServers if available
70      *  and use first server as default if necessary.
71      */
72     if(array_key_exists('config',$_SESSION) &&
73         array_key_exists('SERVERS',$_SESSION['config']->data) &&
74         array_key_exists('FON',$_SESSION['config']->data['SERVERS']) &&
75         count($_SESSION['config']->data['SERVERS']['FON']) &&
76         is_callable("mysql_connect")
77       ) {
79       /* Set available server */
80       $this->goFonHomeServers = $_SESSION['config']->data['SERVERS']['FON'];
82       /* Set default server */
83       if($this->dn == "new"){
84         $this->goFonHomeServer = $this->goFonHomeServers[0]['DN'];
85       }
87       /* Remember inital home server, to be able to remove old entries */
88       $this->init_HomeServer = $this->goFonHomeServer;
90       /* get config */
91       if(!isset($this->goFonHomeServers[$this->goFonHomeServer])){
92         print_red(sprintf(_("The specified home server '%s' is not available in GOsa server configuration. Saving this account will create a new entry on the server '%s'. Use cancel if you do not want to create a new entry while ignoring old accounts."), preg_replace("/,/",", ",$this->goFonHomeServer), preg_replace("/,/",", ",$this->goFonHomeServers[0]['DN'])));
93         $this->goFonHomeServer = $this->goFonHomeServers[0]['DN'];
94         $this->init_HomeServer = $this->goFonHomeServers[0]['DN'];
95       }
96       $cur_cfg = $this->goFonHomeServers[$this->goFonHomeServer];
97     }
100     /* Variable init  
101      *  Load phone nubmers and parse dial options 
102      */
103     if($this->is_account){
104       if(isset($this->attrs['telephoneNumber'])){
105         $this->telephoneNumber=$this->attrs['telephoneNumber'];
106         unset($this->telephoneNumber['count']); 
107       }
108       for($i = 0; $i < strlen($this->goFonDialOption); $i++){
109         $name = "goFonDialOption_".$this->goFonDialOption[$i];
110         $this->$name=$this->goFonDialOption[$i];
111       }
112     }
114     /* Set Queue announce hold time to true/false */
115     if(preg_match("/no/i",$this->goFonQueueAnnounceHoldtime)){
116       $this->goFonQueueAnnounceHoldtime=false;
117     }else{
118       $this->goFonQueueAnnounceHoldtime=true;
119     }
121     /* Define all available ringdown types */
122     $types= array('ringall'    =>_("ring all"),
123         'roundrobin' =>_("round robin"),
124         'leastrecent'=>_("least recently called"),
125         'fewestcalls'=>_("fewest completed calls"),
126         'random'     =>_("random"),
127         'rrmemory'   =>_("round robin with memory"));
128     $i = 0;
129     foreach($types as $type => $name){
130       $i++;
131       $this->goFonQueueStrategyOptions[$i]    =$name;
132       $this->goFonQueueStrategyOptionsR[$i]   =$type;
133       $tmp[$type] = $i; 
134     }
135     $this->goFonQueueStrategy= $tmp[$this->goFonQueueStrategy];
136     $this->old_cn = $this->cn;
137     $this->old_phone_numbers = $this->telephoneNumber;
138   }
141   /* This function ensures that the selected home server 
142    * and the initially selected home server are reachable and accessible  
143    */
144   function check_database_accessibility()
145   {
146     /* Check if mysql extension is available */
147     if(!is_callable("mysql_pconnect")){
148       return(_("Can't save any changes to asterisk database, there is currently no mysql extension available in your php setup."));
149     }
151     /********************
152      * Check currently selected home server
153      ********************/
155     $cfg_Current  = $this->goFonHomeServers[$this->goFonHomeServer];
156     $r_current    =  @mysql_pconnect($cfg_Current['SERVER'],$cfg_Current['LOGIN'],$cfg_Current['PASSWORD']);
157     if(!$r_current){
158       gosa_log(@mysql_error($r_current));
159       return(sprintf(_("The MySQL home server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
160             $cfg_Current['SERVER'],$cfg_Current['LOGIN']));
161     }
162     $db_current  =  @mysql_select_db($cfg_Current['DB'],$r_current);
163     if(!$db_current){
164       gosa_log(@mysql_error($r_current));
165       mysql_close($r_current);
166       return( sprintf(_("Can't select database '%s' on home server '%s'."),$cfg_Current['DB'],$cfg_Current['SERVER']));
167     }
169     /********************
170      * Check init home server
171      ********************/
173     if($this->initially_was_account){
174       $cfg_Init  = $this->goFonHomeServers[$this->init_HomeServer] ;
175       $r_init    =  @mysql_pconnect($cfg_Init['SERVER'],$cfg_Init['LOGIN'],$cfg_Init['PASSWORD']);
176       if(!$r_init){
177         gosa_log(@mysql_error($r_init));
178         return(sprintf(_("The MySQL initial home server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
179               $cfg_Init['SERVER'],$cfg_Init['LOGIN']));
180       }
181       $db_init  =  @mysql_select_db($cfg_Init['DB'],$r_init);
182       if(!$db_init){
183         gosa_log(@mysql_error($r_init));
184         mysql_close($r_init);
185         return( sprintf(_("Can't select database '%s' on initial home server '%s'."),$cfg_Init['DB'],$cfg_Init['SERVER']));
186       }
187     }
188   }
190   
191   /* Display plugin ui */
192   function execute()
193   {
194     /* Call parent execute */
195     plugin::execute();
197     /* Do we need to flip is_account state? */
198     if (isset($_POST['modify_state'])){
199       $this->is_account= !$this->is_account;
200     }
202     /* Show tab dialog headers */
203     if ($this->parent != NULL){
204       if ($this->is_account){
205         $display= $this->show_header(_("Remove the phone queue from this Account"),
206             _("Phone queue is enabled for this group. You can disable it by clicking below."));
207       } else {
208         $display= $this->show_header(_("Create phone queue"), 
209                   _("For this group the phone queues are disabled. You can enable them by clicking below."));
210         return ($display);
211       }
212     }
214     /* Add queue number */ 
215     if(isset($_POST['add_phonenumber'])&&(isset($_POST['phonenumber']))&&(!empty($_POST['phonenumber']))){
216       if((!in_array($_POST['phonenumber'],$this->telephoneNumber))&&(is_numeric($_POST['phonenumber']))){
217         $this->telephoneNumber[]=$_POST['phonenumber'];
218       }
219     }
221     /* Delete queue number */ 
222     if(isset($_POST['delete_phonenumber'])&&(isset($_POST['goFonQueueNumber_List']))){
223       unset($this->telephoneNumber[$_POST['goFonQueueNumber_List']]);
224     }
225   
226     $tmp = array();
227     foreach($this->telephoneNumber as $val){
228       if(!empty($val)){
229         $tmp[]= $val;
230       }
231     }  
232     $this->telephoneNumber=$tmp;
234     /* queue number up */ 
235     if(isset($_POST['up_phonenumber'])&&(isset($_POST['goFonQueueNumber_List']))){
236       if($_POST['goFonQueueNumber_List']>0){
237         $up   = $this->telephoneNumber[$_POST['goFonQueueNumber_List']];
238         $down = $this->telephoneNumber[$_POST['goFonQueueNumber_List']-1];
239         $this->telephoneNumber[$_POST['goFonQueueNumber_List']]    = $down; 
240         $this->telephoneNumber[$_POST['goFonQueueNumber_List']-1]  = $up;
241       }
242     }
244     /* Queuenumber down */ 
245     if(isset($_POST['down_phonenumber'])&&(isset($_POST['goFonQueueNumber_List']))){
246       if(isset($this->telephoneNumber[($_POST['goFonQueueNumber_List']+1)])){
247         $up   = $this->telephoneNumber[$_POST['goFonQueueNumber_List']+1];
248         $down = $this->telephoneNumber[$_POST['goFonQueueNumber_List']];
249         $this->telephoneNumber[$_POST['goFonQueueNumber_List']+1]    = $down; 
250         $this->telephoneNumber[$_POST['goFonQueueNumber_List']]  = $up;
251       }
252     }
254     /* Assign samrty variables */
255     $smarty= get_smarty();
256     $smarty->assign("goFonQueueLanguageOptions",array('de'=>_('German')));
257     $smarty->assign("goFonQueueStrategyOptions", $this->goFonQueueStrategyOptions);
259     foreach($this->attributes as $key => $val){
260       $smarty->assign($val,$this->$val);  
261       if($this->$val == false){
262         $smarty->assign($val."CHK","");
263       }else{
264         $smarty->assign($val."CHK"," checked ");
265       }
266       if(chkacl($this->acl,$key)==""){
267         $smarty->assign($val."ACL","");
268       }else{
269         $smarty->assign($val."ACL"," disabled ");
270       }
271     }
272     
273     /* Create array with goFonHomeServer */
274     $tmp = array();
275     foreach($this->goFonHomeServers as $dn => $val){
276       if(!is_numeric($dn)){
277         $tmp[$dn]  = $val['SERVER'];
278       }
279     }
280     $smarty->assign("goFonHomeServers",$tmp);
282     return ($display.$smarty->fetch (get_template_path('phonequeue.tpl', TRUE)));
283   }
286   /* Check formular input */
287   function check()
288   {
289     /* Call common method to give check the hook */
290     $message= plugin::check();
291     if(!count($this->goFonHomeServers)){
292       $message[] = _("There must be at least one server with an asterisk database to create a phone queue.");
293     }
294     if(empty($this->goFonHomeServer)){
295       $message[] = _("Please select a valid goFonHomeServer.");
296     }
297     if($this->is_number_used()){
298       $message[] = $this->is_number_used();
299     }
300     if(!((is_numeric($this->goFonTimeOut))||(empty($this->goFonTimeOut)))){
301       $message[] = _("Timeout must be numeric");
302     }
303     if(!((is_numeric($this->goFonQueueRetry))||(empty($this->goFonQueueRetry)))){
304       $message[] = _("Retry must be numeric");
305     }
306     if(!((is_numeric($this->goFonMaxLen))||(empty($this->goFonMaxLen)))){
307       $message[] = _("Max queue length must be numeric");
308     }
309     if(!((is_numeric($this->goFonAnnounceFrequency))||(empty($this->goFonAnnounceFrequency)))){
310       $message[] = _("Announce frequency must be numeric");
311     }
312     if(count($this->telephoneNumber)==0){
313       $message[] = _("There must be least one queue number defined.");
314     }
316     /* check if add to database could be successfull  */
317     $str = $this->add_to_database();
318     if(!empty($str)){
319       $message[] = $str;
320     }
321     return $message;
322   }
325   /* This function removes the old database entries. 
326    * If this entry should be removed or the home server has changed
327    *  this function is called to ensure that all old entries will be deleted.
328    */
329   function remove_from_database($save = false)
330   {
331     /* Check if we must remove old entries */
332     if($this->initially_was_account){
334       /* Check if there is at least on server configuration */
335       if(!count($this->goFonHomeServers)){
336         return( _("There is currently no asterisk server defined. Possibly you are missing a server that handles the asterisk management (goFonServer). Your settings can't be saved to asterisk database."));
337       }
339       /********************
340        * Get configuration and check it
341        ********************/
343       /* Check if databases are reachable, returns an error string if anything fails  */
344       $error_str = $this->check_database_accessibility();
345       if($error_str){
346         return($error_str);
347       }
349       /* Connect to current database to be able to add new entries */
350       $cfg_Current  = $this->goFonHomeServers[$this->init_HomeServer] ;
351       $res_cur      =  @mysql_pconnect($cfg_Current['SERVER'],$cfg_Current['LOGIN'],$cfg_Current['PASSWORD']);
352       $db_cur       =  @mysql_select_db($cfg_Current['DB'],$res_cur);
354       /* Create sql entries */
355       $delete[]=    "DELETE FROM ".$cfg_Current['EXT_TABLE']."    WHERE exten='".$this->old_cn."';\n";
356       $delete[]=    "DELETE FROM ".$cfg_Current['QUEUE_TABLE']."  WHERE name='".$this->old_cn."'; \n";
357       $delete[]=    "DELETE FROM ".$cfg_Current['QUEUE_MEMBER_TABLE']." WHERE queue_name='".$this->old_cn."';\n";
358       foreach($this->old_phone_numbers as $number){
359         $delete[]=    "DELETE FROM ".$cfg_Current['EXT_TABLE']."    WHERE exten='".$number."';\n";
360       }
362       /* Execute the queries */  
363       if($save){
364         foreach($delete as $sql){
365           $res = @mysql_query($sql,$res_cur);
366           if(!$res){
367             gosa_log(@mysql_error($res_cur));
368             return(_("Error while removing old queue entries from database.").
369                 "&nbsp;"._("Please have a look a the gosa logfiles."));
370           }
371         }
372       }
373     }
374   }
377   /* This function handles the database entries for this 
378    *  queue. 
379    * Existing entries will be updated if possible.
380    */
381   function add_to_database($save = false)
382   {
383     /* Check if there is at least on server configuration */
384     if(!count($this->goFonHomeServers)){
385       return( _("There is currently no asterisk server defined. Possibly you are missing a server that handles the asterisk management (goFonServer). Your settings can't be saved to asterisk database."));
386     }
388     /********************
389      * Get configuration and check it
390      ********************/
392     /* Check if databases are reachable, returns an error string if anything fails  */
393     $error_str = $this->check_database_accessibility();
394     if($error_str){
395       return($error_str);
396     }
398     /* Connect to current database to be able to add new entries */
399     $cfg_Current  = $this->goFonHomeServers[$this->goFonHomeServer] ;
400     $res_cur      =  @mysql_pconnect($cfg_Current['SERVER'],$cfg_Current['LOGIN'],$cfg_Current['PASSWORD']);
401     $db_cur       =  @mysql_select_db($cfg_Current['DB'],$res_cur);
403     /* Connect to old home server and remove old entries if necessary */
404     if(($this->initially_was_account) && ($this->init_HomeServer != $this->goFonHomeServer)){
405       $str = $this->remove_from_database($save); 
406       if(!empty($str)){
407         return($str);;
408       }
409     }
411     /* Ensure that we have the new cn in $this->cn and the old cn in $this->old_cn */
412     $this->cn = $this->parent->by_object['ogroup']->cn;
414     if($save){
415   
416       /*****************
417        * Create queue table entry 
418        *****************/
419  
420       /* Check if QUEUE_TABLE entry exists.
421        * If this entry is missing - create it 
422        *  else update the entry with new values.
423        */
424       $query = "SELECT * FROM ".$cfg_Current['QUEUE_TABLE']."  WHERE name='".$this->old_cn."';";
425       $res   = mysql_query($query,$res_cur);
426       if(!$res){
427         gosa_log(@mysql_error($res_cur));
428         return(_("Could not detect old queue entry, query failed.")."&nbsp;"._("Please have a look a the gosa logfiles."));
429       }
430       $cnt = mysql_affected_rows($res_cur);
433       /* Create queue table entry 
434        * Leave unused options empty. 
435        */
436       $queue["announce"]              = "";
437       $queue["monitor_join"]          = "";
438       $queue["monitor_format"]        = "";
439       $queue["announce_round_seconds"]= "";   
440       $queue["wrapuptime"]            = "";
441       $queue["servicelevel"]          = "";
442       $queue["eventmemberstatus"]     = "";
443       $queue["eventwhencalled"]       = "";
444       $queue["memberdelay"]           = "";
445       $queue["weight"]                = "";
446       $queue["timeoutrestart"]        = "";
448       $queue["queue_holdtime"]        = $this->goFonQueueAnnounce;
449       $queue["queue_lessthan"]        = $this->goFonQueueLessThan;   
450       $queue["retry"]                 = $this->goFonQueueRetry;
451       $queue["reportholdtime"]        = "1";
452       $queue["joinempty"]             = "no";
453       $queue["leavewhenempty"]        = "yes";   
455       $queue["context"]               = "default";
456       $queue["name"]                  = $this->cn;  
457       $queue["timeout"]               = $this->goFonTimeOut; 
458       $queue["maxlen"]                = $this->goFonMaxLen;
459       $queue["strategy" ]             = $this->goFonQueueStrategyOptionsR[$this->goFonQueueStrategy];
460       $queue["queue_thankyou"]        = $this->goFonQueueThankYou;   
461       $queue["queue_reporthold"]      = $this->goFonQueueReportHold; 
462       $queue["announce_frequency"]    = $this->goFonAnnounceFrequency;
463       $queue["queue_youarenext"]      = $this->goFonQueueYouAreNext;   
464       $queue["queue_thereare"]        = $this->goFonQueueThereAre;   
465       $queue["queue_callswaiting"]    = $this->goFonQueueCallsWaiting;
466       $queue["queue_minutes"]         = $this->goFonQueueMinutes;
467       $queue["queue_seconds"]         = $this->goFonQueueSeconds;   
468       $queue["announce_holdtime"]     = $this->goFonQueueAnnounceHoldtime;   
469       $queue["musiconhold"]           = $this->goFonMusiconHold;
472       /* Check if we must create a new queue entry 
473        *  or if we can update an existing entry 
474        *  $cnt contains the number of entries matching this cn
475        */
477       /* Create new queue table entry 
478        */
479       if($cnt == 0){
481         /* Parse and Add Queue */
482         $entries = "";
483         $values  = "";
484         foreach($queue as $attr=>$val){
485           if($val == "") continue;
486           $entries.= "`".$attr."`,";
487           $values .= "'".$val."',";
488         }
489         $values  = preg_replace("/,$/","",$values);
490         $entries = preg_replace("/,$/","",$entries );
491         $SQL[]="INSERT INTO ".$cfg_Current['QUEUE_TABLE']." (".$entries.") VALUES (".$values.");";
492       }elseif($cnt == 1){
494         /* Update queue table entry 
495          */
496         $queue_old = @mysql_fetch_assoc($res);
497         foreach($queue_old as $name => $value){
498           if(isset($queue[$name]) && $queue[$name] == $value){
499             unset($queue[$name]);
500           }
501         }
503         /* Parse and Add Queue */
504         if(count($queue)){
505           $query = "UPDATE ".$cfg_Current['QUEUE_TABLE']." SET ";
506           foreach($queue as $key => $val){
507             $query.= "".$key."='".$val."',";
508           }
509           $query = preg_replace("/,$/","",$query);
510           $query.= " WHERE name='".$this->old_cn."';";
511           $SQL[] = $query;
512         }
513       }else{
514         return(sprintf(_("More than one entry in queue table found, that uses the name ('%s'). Please fix this issue manually first."),$this->cn));
515       }
518       /*****************
519        * Create queue member entries
520        *****************/
521       
522       /* Add the queue member entries 
523        * First we must remove all old user entries. 
524        * to be able to add a clean set of members.
525        */ 
526       $SQL[]= "DELETE FROM ".$cfg_Current['QUEUE_MEMBER_TABLE']." WHERE queue_name='".$this->cn."';";
527       $SQL[]= "DELETE FROM ".$cfg_Current['QUEUE_MEMBER_TABLE']." WHERE queue_name='".$this->old_cn."';";
528       
529       /* Append new Member for this queue */ 
530       $queueuser =array();
531       $i = 0;
532       $parent = $this->parent->by_object['ogroup'];
533       foreach($parent->memberList as $member => $mem_data){
534         $obj = $parent->objcache[$member];
535         if(isset($obj['objectClass'])){
536           if(in_array("goFonAccount",$obj['objectClass'])){
537             $i ++ ;
538             $queueuser[$i]['queue_name']  = $this->cn; 
539             $queueuser[$i]['interface']   = "SIP/".$obj['uid'][0]; 
540             $queueuser[$i]['penalty']     = 1; 
541           }
542         }
543       }
545       /* Parse and Add members to query Array */
546       if(is_array($queueuser)){
547         foreach($queueuser as $user){
548           $entries = "";
549           $values  = "";
550           foreach($user as $attr => $val){
551             $entries.= "`".$attr."`,"; 
552             $values .= "'".$val."',";
553           }
554           $values  = preg_replace("/,$/","",$values);
555           $entries = preg_replace("/,$/","",$entries );
557           $SQL[]="INSERT INTO ".$cfg_Current['QUEUE_MEMBER_TABLE']." (".$entries.") VALUES (".$values.")"; 
558         }
559       }
560       
562       /*****************
563        * Create extension entries
564        *****************/
565       
566       /* Add the extension entries 
567        * First we must remove all old entensions. 
568        */ 
569       $SQL[]=  "DELETE FROM ".$cfg_Current['EXT_TABLE']."  WHERE exten='".$this->cn."';\n";
570       $SQL[]=  "DELETE FROM ".$cfg_Current['EXT_TABLE']."  WHERE exten='".$this->old_cn."';\n";
572       /* Delete old enxtension entries for the old telephone nubmer  */
573       if(is_array($this->old_phone_numbers)){
574         foreach($this->old_phone_numbers as $phone){
575           $SQL[]= "DELETE FROM ".$cfg_Current['EXT_TABLE']." WHERE exten='".$phone."';\n";
576         }
577       }
578       
579       /* Delete enxtension entries for telephone numbers  */
580       if(is_array($this->telephoneNumber)){
581         foreach($this->telephoneNumber as $phone){
582           $SQL[]= "DELETE FROM ".$cfg_Current['EXT_TABLE']." WHERE exten='".$phone."';\n";
583         }
584       }
586       /* Create a extension entry fpr each telephoneNumber */
587       $i_insert_only_once = false;
588       $prio = 11;   // This represents the priority for each telephoneNumber 
589       foreach($this->telephoneNumber as $num){
591         /* The naming refrences */
592         if($i_insert_only_once == false){
593           $i_insert_only_once = true;
594           $a_ext[$i]['context']  = 'GOsa';
595           $a_ext[$i]['exten']    = $this->cn;
596           $a_ext[$i]['priority'] = 1;
597           $a_ext[$i]['app']      = "Goto";
598           $a_ext[$i]['appdata']  = $num."|1";
599           $i ++ ; 
600         }
602         /* If there is currently no user for this queue 
603          * Play no service sound file and return to default context.  
604          */
605         if(count($queueuser)==0){
606           $a_ext[$i]['context']  = 'GOsa';
607           $a_ext[$i]['exten']    = $num;
608           $a_ext[$i]['priority'] = 1;
609           $a_ext[$i]['app']      = "SetLanguage";
610           $a_ext[$i]['appdata']  = "de";
611           $i ++ ; 
613           $a_ext[$i]['context']  = 'GOsa';
614           $a_ext[$i]['exten']    = $num;
615           $a_ext[$i]['priority'] = 2;
616           $a_ext[$i]['app']      = "Playback";
617           $a_ext[$i]['appdata']  = "ss-noservice";
618           $i ++ ; 
620           $a_ext[$i]['context']  = 'GOsa';
621           $a_ext[$i]['exten']    = $num;
622           $a_ext[$i]['priority'] = 3;
623           $a_ext[$i]['app']      = "Goto";
624           $a_ext[$i]['appdata']  = "default";
625           $i ++ ; 
626         }else{
628           /* Dcrement priority to avoid using same priority twice */
629           $prio --;
631           /* Wait for 2 seconds */
632           $a_ext[$i]['context']  = 'GOsa';
633           $a_ext[$i]['exten']    = $num;
634           $a_ext[$i]['priority'] = 1;
635           $a_ext[$i]['app']      = "Wait";
636           $a_ext[$i]['appdata']  = "2";
637           $i ++ ; 
638     
639           /* Set language to queue language */
640           $a_ext[$i]['context']  = 'GOsa';
641           $a_ext[$i]['exten']    = $num;
642           $a_ext[$i]['priority'] = 2;
643           $a_ext[$i]['app']      = "SetLanguage";
644           $a_ext[$i]['appdata']  = $this->goFonQueueLanguage;
645           $i ++ ; 
646   
647           /* Play welcome sound file */
648           $a_ext[$i]['context']  = 'GOsa';
649           $a_ext[$i]['exten']    = $num;
650           $a_ext[$i]['priority'] = 3;
651           $a_ext[$i]['app']      = "Playback";
652           $a_ext[$i]['appdata']  = $this->goFonWelcomeMusic;
653           $i ++ ; 
655           /* Set CID name */
656           $a_ext[$i]['context']  = 'GOsa';
657           $a_ext[$i]['exten']    = $num;
658           $a_ext[$i]['priority'] = 4;
659           $a_ext[$i]['app']      = "SetCIDName";
660           if(!empty($this->parent->by_object['ogroup']->description)){
661             $a_ext[$i]['appdata']  = $this->parent->by_object['ogroup']->description;
662           }else{
663             $a_ext[$i]['appdata']  = $this->cn." - ".$num;
664           }
665           $i ++ ; 
667           /* Set queue priority */
668           $a_ext[$i]['context']  = 'GOsa';
669           $a_ext[$i]['exten']    = $num;
670           $a_ext[$i]['priority'] = 5;
671           $a_ext[$i]['app']      = "SetVar";
672           $a_ext[$i]['appdata']  = "QUEUE_PRIO=".$prio;
673           $i ++ ; 
675           /* Open queue */
676           $a_ext[$i]['context']  = 'GOsa';
677           $a_ext[$i]['exten']    = $num;
678           $a_ext[$i]['priority'] = 6;
679           $a_ext[$i]['app']      = "Queue";
680           $a_ext[$i]['appdata']  =  $this->cn;
681             "|".
682             $this->goFonDialOption_t.
683             $this->goFonDialOption_T.
684             $this->goFonDialOption_h.
685             $this->goFonDialOption_H.
686             $this->goFonDialOption_r;
687         }
689         $i++;
690       }
692       /* Parse and Add Extension entries */
693       foreach($a_ext as $ext){
694         $entries = "";
695         $values  = "";
696         foreach($ext as $attr => $val){
697           $entries.= "`".$attr."`,";
698           $values .= "'".$val."',";
699         }
700         $values  = preg_replace("/,$/","",$values);
701         $entries = preg_replace("/,$/","",$entries );
702         $SQL[]="INSERT INTO ".$cfg_Current['EXT_TABLE']." (".$entries.") VALUES (".$values.")";
703       }
705       /* Do all collected mysql queries 
706        */
707       foreach($SQL as $query)
708       $res   = mysql_query($query,$res_cur);
709       if(!$res){
710         gosa_log(@mysql_error($res_cur));
711         return(_("Mysql query failed.")."&nbsp;"._("Please have a look a the gosa logfiles."));
712       }
713     }
714     @mysql_close($r_con);
715     return(false);
716   }
719   /* This function checks if the given phonenumbers 
720    *  are available or already in use
721    */
722   function is_number_used()
723   {
724     $ldap= $this->config->get_ldap_link();
725     $ldap->cd($this->config->current['BASE']);
726     $ldap->search("(&(& (!(uid=".$this->cn."))
727                         (!(cn=".$this->cn.")))
728                      (| (objectClass=goFonAccount)
729                         (objectClass=goFonQueue)
730                         (objectClass=goFonConference)))", array("telephoneNumber","cn","uid"));
731     while($attrs = $ldap->fetch()) {
732       unset($attrs['telephoneNumber']['count']);
733       foreach($attrs['telephoneNumber'] as $tele){
734         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
735         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
736         $numbers[$tele]=$attrs;
737       }
738     }
740     foreach($this->telephoneNumber as $num){
741       if((isset($numbers[$num]))&&(($numbers[$num]['cn'][0]!= $this->attrs['cn'][0]))){
742         if(isset($numbers[$num]['uid'][0])){
743           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
744         }else{
745           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
746         }
747       }
748     }
749   }
752   /* Get posted attributes */
753   function save_object()
754   {
755     plugin::save_object();  
756     if(isset($_POST['phonenumber'])){
757       foreach(array("goFonDialOption_t","goFonDialOption_T","goFonDialOption_h","goFonDialOption_r","goFonDialOption_H","goFonMusiconHold") as $val){
758         if(isset($_POST[$val])){
759           $this->$val = $_POST[$val];
760         }else{
761           $this->$val = false;
762         }
763       }
764       if(isset($_POST['goFonQueueAnnounceHoldtime'])){
765         $this->goFonQueueAnnounceHoldtime = "yes";
766       }else{
767         $this->goFonQueueAnnounceHoldtime = false;
768       }
769     }
770   }
773   function save()
774   {
775     $ldap= $this->config->get_ldap_link();
777     plugin::save();
779     /* Create dial option attribute */
780     $this->attrs['goFonDialOption'] = "";
781     foreach(array("goFonDialOption_t","goFonDialOption_T","goFonDialOption_r","goFonDialOption_h","goFonDialOption_H","cn") as $val){
782       $this->attrs['goFonDialOption'].=$this->$val; 
783       unset($this->attrs[$val]); 
784     }
785     if(empty($this->attrs['goFonDialOption'])) {
786       $this->attrs['goFonDialOption']=array();
787     }
789     /* Set announce hold time to yes no .. */
790     if($this->goFonQueueAnnounceHoldtime != "no" ){
791       $this->attrs['goFonQueueAnnounceHoldtime'] = "yes";
792     }else{
793       $this->attrs['goFonQueueAnnounceHoldtime'] = "no";
794     }
796     /* Set strategy */
797     $this->attrs['goFonQueueStrategy'] = $this->goFonQueueStrategyOptionsR[$this->goFonQueueStrategy];
799     /* Add database entry, display error and abort if this fails */
800     $str = $this->add_to_database(true);
801     if(!empty($str)){
802       print_red($str);
803     }
805     /* Save data to LDAP */
806     $ldap->cd($this->dn);
807     $this->cleanup();
808     $ldap->modify ($this->attrs); 
810     show_ldap_error($ldap->get_error(), _("Saving phone queue failed"));
812     /* Optionally execute a command after we're done */
813     if ($this->initially_was_account == $this->is_account){
814       if ($this->is_modified){
815         $this->handle_post_events("modify");
816       }
817     } else {
818       $this->handle_post_events("add");
819     }
820   }
823   /* remove object from parent */
824   function remove_from_parent()
825   {
826     /* Cancel if nothing is to do here */
827     if (!$this->initially_was_account){
828       return;
829     }
831     /* Remove database entries, 
832      *  if fails display errors and abort
833      */
834     $str = $this->remove_from_database(true);
835     if(!empty($str)){
836       print_red($str);
837       return false;
838     }
839   
840     /* Remove all temporary attributes */
841     $tmp = array_flip($this->attributes);
842     foreach(array("goFonDialOption_t","goFonDialOption_T","goFonDialOption_r","goFonDialOption_h","goFonDialOption_H","cn") as $val){
843       unset($this->$val);
844       unset($this->attrs[$val]);
845       unset($tmp[$val]);
846     }   
847     foreach(array_flip($tmp) as $key => $val){
848       $tmp2[]=$val;
849     } 
850     $this->attributes = $tmp2;
852     /* include global link_info */
853     $ldap= $this->config->get_ldap_link();
855     /* Remove and write to LDAP */
856     plugin::remove_from_parent();
858     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,$this->attributes, "Save");
859     $ldap->cd($this->dn);
860     $this->cleanup();
861     $ldap->modify ($this->attrs); 
862     show_ldap_error($ldap->get_error(), _("Removing phone queue failed"));
863   }
865   
866   function getCopyDialog()
867   {
868     $str  = "";
869     $str .= _("Phone number");
870     $str .= "&nbsp;<input type='text' name='telephoneNumber' value='".$this->telephoneNumber."'>";
871     return($str);
872   }
875   function saveCopyDialog()
876   {
877     if(isset($_POST['telephoneNumber'])){
878       $this->telephoneNumber = $_POST['telephoneNumber'];
879     }
880   }
885 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
886 ?>