Code

Udpated ogroup queues .
[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'];
534       
535       $ldap = $this->config->get_ldap_link();
536       foreach($parent->memberList as $member => $mem_data){
537         $ldap->cat($member,array("goFonHomeServer","objectClass","dn","uid"));
538         if($ldap->count()){
540           $obj = $ldap->fetch();
542           /* Calculate server and account dependencies */
543           $is_acc = in_array("goFonAccount",$obj['objectClass']);
544           $is_home= isset($obj['goFonHomeServer'][0]) && $obj['goFonHomeServer'][0] == $this->goFonHomeServer; 
546           /* Append user to list of queue member,
547            *  only if user has phoneAccount extension && is on same home server */
548           if($is_acc && $is_home){
549             $i ++ ;
550             $queueuser[$i]['queue_name']  = $this->cn; 
551             $queueuser[$i]['interface']   = "SIP/".$obj['uid'][0]; 
552             $queueuser[$i]['penalty']     = 1; 
553           }
554         }
555       }
557       /* Parse and Add members to query Array */
558       if(is_array($queueuser)){
559         foreach($queueuser as $user){
560           $entries = "";
561           $values  = "";
562           foreach($user as $attr => $val){
563             $entries.= "`".$attr."`,"; 
564             $values .= "'".$val."',";
565           }
566           $values  = preg_replace("/,$/","",$values);
567           $entries = preg_replace("/,$/","",$entries );
569           $SQL[]="INSERT INTO ".$cfg_Current['QUEUE_MEMBER_TABLE']." (".$entries.") VALUES (".$values.")"; 
570         }
571       }
572       
574       /*****************
575        * Create extension entries
576        *****************/
577       
578       /* Add the extension entries 
579        * First we must remove all old entensions. 
580        */ 
581       $SQL[]=  "DELETE FROM ".$cfg_Current['EXT_TABLE']."  WHERE exten='".$this->cn."';\n";
582       $SQL[]=  "DELETE FROM ".$cfg_Current['EXT_TABLE']."  WHERE exten='".$this->old_cn."';\n";
584       /* Delete old enxtension entries for the old telephone nubmer  */
585       if(is_array($this->old_phone_numbers)){
586         foreach($this->old_phone_numbers as $phone){
587           $SQL[]= "DELETE FROM ".$cfg_Current['EXT_TABLE']." WHERE exten='".$phone."';\n";
588         }
589       }
590       
591       /* Delete enxtension entries for telephone numbers  */
592       if(is_array($this->telephoneNumber)){
593         foreach($this->telephoneNumber as $phone){
594           $SQL[]= "DELETE FROM ".$cfg_Current['EXT_TABLE']." WHERE exten='".$phone."';\n";
595         }
596       }
598       /* Create a extension entry fpr each telephoneNumber */
599       $i_insert_only_once = false;
600       $prio = 11;   // This represents the priority for each telephoneNumber 
601       foreach($this->telephoneNumber as $num){
603         /* The naming refrences */
604         if($i_insert_only_once == false){
605           $i_insert_only_once = true;
606           $a_ext[$i]['context']  = 'GOsa';
607           $a_ext[$i]['exten']    = $this->cn;
608           $a_ext[$i]['priority'] = 1;
609           $a_ext[$i]['app']      = "Goto";
610           $a_ext[$i]['appdata']  = $num."|1";
611           $i ++ ; 
612         }
614         /* If there is currently no user for this queue 
615          * Play no service sound file and return to default context.  
616          */
617         if(count($queueuser)==0){
618           $a_ext[$i]['context']  = 'GOsa';
619           $a_ext[$i]['exten']    = $num;
620           $a_ext[$i]['priority'] = 1;
621           $a_ext[$i]['app']      = "SetLanguage";
622           $a_ext[$i]['appdata']  = "de";
623           $i ++ ; 
625           $a_ext[$i]['context']  = 'GOsa';
626           $a_ext[$i]['exten']    = $num;
627           $a_ext[$i]['priority'] = 2;
628           $a_ext[$i]['app']      = "Playback";
629           $a_ext[$i]['appdata']  = "ss-noservice";
630           $i ++ ; 
632           $a_ext[$i]['context']  = 'GOsa';
633           $a_ext[$i]['exten']    = $num;
634           $a_ext[$i]['priority'] = 3;
635           $a_ext[$i]['app']      = "Goto";
636           $a_ext[$i]['appdata']  = "default";
637           $i ++ ; 
638         }else{
640           /* Dcrement priority to avoid using same priority twice */
641           $prio --;
643           /* Wait for 2 seconds */
644           $a_ext[$i]['context']  = 'GOsa';
645           $a_ext[$i]['exten']    = $num;
646           $a_ext[$i]['priority'] = 1;
647           $a_ext[$i]['app']      = "Wait";
648           $a_ext[$i]['appdata']  = "2";
649           $i ++ ; 
650     
651           /* Set language to queue language */
652           $a_ext[$i]['context']  = 'GOsa';
653           $a_ext[$i]['exten']    = $num;
654           $a_ext[$i]['priority'] = 2;
655           $a_ext[$i]['app']      = "SetLanguage";
656           $a_ext[$i]['appdata']  = $this->goFonQueueLanguage;
657           $i ++ ; 
658   
659           /* Play welcome sound file */
660           $a_ext[$i]['context']  = 'GOsa';
661           $a_ext[$i]['exten']    = $num;
662           $a_ext[$i]['priority'] = 3;
663           $a_ext[$i]['app']      = "Playback";
664           $a_ext[$i]['appdata']  = $this->goFonWelcomeMusic;
665           $i ++ ; 
667           /* Set CID name */
668           $a_ext[$i]['context']  = 'GOsa';
669           $a_ext[$i]['exten']    = $num;
670           $a_ext[$i]['priority'] = 4;
671           $a_ext[$i]['app']      = "SetCIDName";
672           if(!empty($this->parent->by_object['ogroup']->description)){
673             $a_ext[$i]['appdata']  = $this->parent->by_object['ogroup']->description;
674           }else{
675             $a_ext[$i]['appdata']  = $this->cn." - ".$num;
676           }
677           $i ++ ; 
679           /* Set queue priority */
680           $a_ext[$i]['context']  = 'GOsa';
681           $a_ext[$i]['exten']    = $num;
682           $a_ext[$i]['priority'] = 5;
683           $a_ext[$i]['app']      = "SetVar";
684           $a_ext[$i]['appdata']  = "QUEUE_PRIO=".$prio;
685           $i ++ ; 
687           /* Open queue */
688           $a_ext[$i]['context']  = 'GOsa';
689           $a_ext[$i]['exten']    = $num;
690           $a_ext[$i]['priority'] = 6;
691           $a_ext[$i]['app']      = "Queue";
692           $a_ext[$i]['appdata']  =  $this->cn;
693             "|".
694             $this->goFonDialOption_t.
695             $this->goFonDialOption_T.
696             $this->goFonDialOption_h.
697             $this->goFonDialOption_H.
698             $this->goFonDialOption_r;
699         }
701         $i++;
702       }
704       /* Parse and Add Extension entries */
705       foreach($a_ext as $ext){
706         $entries = "";
707         $values  = "";
708         foreach($ext as $attr => $val){
709           $entries.= "`".$attr."`,";
710           $values .= "'".$val."',";
711         }
712         $values  = preg_replace("/,$/","",$values);
713         $entries = preg_replace("/,$/","",$entries );
714         $SQL[]="INSERT INTO ".$cfg_Current['EXT_TABLE']." (".$entries.") VALUES (".$values.")";
715       }
717       /* Do all collected mysql queries 
718        */
719       foreach($SQL as $query)
720       $res   = mysql_query($query,$res_cur);
721       if(!$res){
722         gosa_log(@mysql_error($res_cur));
723         return(_("Mysql query failed.")."&nbsp;"._("Please have a look a the gosa logfiles."));
724       }
725     }
726     @mysql_close($r_con);
727     return(false);
728   }
731   /* This function checks if the given phonenumbers 
732    *  are available or already in use
733    */
734   function is_number_used()
735   {
736     $ldap= $this->config->get_ldap_link();
737     $ldap->cd($this->config->current['BASE']);
738     $ldap->search("(&(& (!(uid=".$this->cn."))
739                         (!(cn=".$this->cn.")))
740                      (| (objectClass=goFonAccount)
741                         (objectClass=goFonQueue)
742                         (objectClass=goFonConference)))", array("telephoneNumber","cn","uid"));
743     while($attrs = $ldap->fetch()) {
744       unset($attrs['telephoneNumber']['count']);
745       foreach($attrs['telephoneNumber'] as $tele){
746         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
747         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
748         $numbers[$tele]=$attrs;
749       }
750     }
752     foreach($this->telephoneNumber as $num){
753       if((isset($numbers[$num]))&&(($numbers[$num]['cn'][0]!= $this->attrs['cn'][0]))){
754         if(isset($numbers[$num]['uid'][0])){
755           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
756         }else{
757           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
758         }
759       }
760     }
761   }
764   /* Get posted attributes */
765   function save_object()
766   {
767     plugin::save_object();  
768     if(isset($_POST['phonenumber'])){
769       foreach(array("goFonDialOption_t","goFonDialOption_T","goFonDialOption_h","goFonDialOption_r","goFonDialOption_H","goFonMusiconHold") as $val){
770         if(isset($_POST[$val])){
771           $this->$val = $_POST[$val];
772         }else{
773           $this->$val = false;
774         }
775       }
776       if(isset($_POST['goFonQueueAnnounceHoldtime'])){
777         $this->goFonQueueAnnounceHoldtime = "yes";
778       }else{
779         $this->goFonQueueAnnounceHoldtime = false;
780       }
781     }
782   }
785   function save()
786   {
787     $ldap= $this->config->get_ldap_link();
789     plugin::save();
791     /* Create dial option attribute */
792     $this->attrs['goFonDialOption'] = "";
793     foreach(array("goFonDialOption_t","goFonDialOption_T","goFonDialOption_r","goFonDialOption_h","goFonDialOption_H","cn") as $val){
794       $this->attrs['goFonDialOption'].=$this->$val; 
795       unset($this->attrs[$val]); 
796     }
797     if(empty($this->attrs['goFonDialOption'])) {
798       $this->attrs['goFonDialOption']=array();
799     }
801     /* Set announce hold time to yes no .. */
802     if($this->goFonQueueAnnounceHoldtime != "no" ){
803       $this->attrs['goFonQueueAnnounceHoldtime'] = "yes";
804     }else{
805       $this->attrs['goFonQueueAnnounceHoldtime'] = "no";
806     }
808     /* Set strategy */
809     $this->attrs['goFonQueueStrategy'] = $this->goFonQueueStrategyOptionsR[$this->goFonQueueStrategy];
811     /* Add database entry, display error and abort if this fails */
812     $str = $this->add_to_database(true);
813     if(!empty($str)){
814       print_red($str);
815     }
817     /* Save data to LDAP */
818     $ldap->cd($this->dn);
819     $this->cleanup();
820     $ldap->modify ($this->attrs); 
822     show_ldap_error($ldap->get_error(), _("Saving phone queue failed"));
824     /* Optionally execute a command after we're done */
825     if ($this->initially_was_account == $this->is_account){
826       if ($this->is_modified){
827         $this->handle_post_events("modify");
828       }
829     } else {
830       $this->handle_post_events("add");
831     }
832   }
835   /* remove object from parent */
836   function remove_from_parent()
837   {
838     /* Cancel if nothing is to do here */
839     if (!$this->initially_was_account){
840       return;
841     }
843     /* Remove database entries, 
844      *  if fails display errors and abort
845      */
846     $str = $this->remove_from_database(true);
847     if(!empty($str)){
848       print_red($str);
849       return false;
850     }
851   
852     /* Remove all temporary attributes */
853     $tmp = array_flip($this->attributes);
854     foreach(array("goFonDialOption_t","goFonDialOption_T","goFonDialOption_r","goFonDialOption_h","goFonDialOption_H","cn") as $val){
855       unset($this->$val);
856       unset($this->attrs[$val]);
857       unset($tmp[$val]);
858     }   
859     foreach(array_flip($tmp) as $key => $val){
860       $tmp2[]=$val;
861     } 
862     $this->attributes = $tmp2;
864     /* include global link_info */
865     $ldap= $this->config->get_ldap_link();
867     /* Remove and write to LDAP */
868     plugin::remove_from_parent();
870     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,$this->attributes, "Save");
871     $ldap->cd($this->dn);
872     $this->cleanup();
873     $ldap->modify ($this->attrs); 
874     show_ldap_error($ldap->get_error(), _("Removing phone queue failed"));
875   }
877   
878   function getCopyDialog()
879   {
880     $str  = "";
881     $str .= _("Phone number");
882     $str .= "&nbsp;<input type='text' name='telephoneNumber' value='".$this->telephoneNumber."'>";
883     return($str);
884   }
887   function saveCopyDialog()
888   {
889     if(isset($_POST['telephoneNumber'])){
890       $this->telephoneNumber = $_POST['telephoneNumber'];
891     }
892   }
897 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
898 ?>