Code

Hide not allowed options
[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'])){
200       /* Onyl change account state if allowed */
201       if($this->is_account && $this->acl == "#all#"){
202         $this->is_account= !$this->is_account;
203       }elseif(!$this->is_account && chkacl($this->acl,"create") == ""){
204         $this->is_account= !$this->is_account;
205       }
206     }
208     /* Show tab dialog headers */
209     if ($this->parent != NULL){
210       if ($this->is_account){
211         $display= $this->show_header(_("Remove the phone queue from this Account"),
212             _("Phone queue is enabled for this group. You can disable it by clicking below."));
213       } else {
214         $display= $this->show_header(_("Create phone queue"), 
215                   _("For this group the phone queues are disabled. You can enable them by clicking below."));
216         return ($display);
217       }
218     }
220     /* Add queue number */ 
221     if(isset($_POST['add_phonenumber'])&&(isset($_POST['phonenumber']))&&(!empty($_POST['phonenumber']))){
222       if((!in_array($_POST['phonenumber'],$this->telephoneNumber))&&(is_numeric($_POST['phonenumber']))){
223         $this->telephoneNumber[]=$_POST['phonenumber'];
224       }
225     }
227     /* Delete queue number */ 
228     if(isset($_POST['delete_phonenumber'])&&(isset($_POST['goFonQueueNumber_List']))){
229       unset($this->telephoneNumber[$_POST['goFonQueueNumber_List']]);
230     }
231   
232     $tmp = array();
233     foreach($this->telephoneNumber as $val){
234       if(!empty($val)){
235         $tmp[]= $val;
236       }
237     }  
238     $this->telephoneNumber=$tmp;
240     /* queue number up */ 
241     if(isset($_POST['up_phonenumber'])&&(isset($_POST['goFonQueueNumber_List']))){
242       if($_POST['goFonQueueNumber_List']>0){
243         $up   = $this->telephoneNumber[$_POST['goFonQueueNumber_List']];
244         $down = $this->telephoneNumber[$_POST['goFonQueueNumber_List']-1];
245         $this->telephoneNumber[$_POST['goFonQueueNumber_List']]    = $down; 
246         $this->telephoneNumber[$_POST['goFonQueueNumber_List']-1]  = $up;
247       }
248     }
250     /* Queuenumber down */ 
251     if(isset($_POST['down_phonenumber'])&&(isset($_POST['goFonQueueNumber_List']))){
252       if(isset($this->telephoneNumber[($_POST['goFonQueueNumber_List']+1)])){
253         $up   = $this->telephoneNumber[$_POST['goFonQueueNumber_List']+1];
254         $down = $this->telephoneNumber[$_POST['goFonQueueNumber_List']];
255         $this->telephoneNumber[$_POST['goFonQueueNumber_List']+1]    = $down; 
256         $this->telephoneNumber[$_POST['goFonQueueNumber_List']]  = $up;
257       }
258     }
260     /* Assign samrty variables */
261     $smarty= get_smarty();
262     $smarty->assign("goFonQueueLanguageOptions",array('de'=>_('German')));
263     $smarty->assign("goFonQueueStrategyOptions", $this->goFonQueueStrategyOptions);
265     foreach($this->attributes as $key => $val){
266       $smarty->assign($val,$this->$val);  
267       if($this->$val == false){
268         $smarty->assign($val."CHK","");
269       }else{
270         $smarty->assign($val."CHK"," checked ");
271       }
272       if(chkacl($this->acl,$key)==""){
273         $smarty->assign($val."ACL","");
274       }else{
275         $smarty->assign($val."ACL"," disabled ");
276       }
277     }
278     
279     /* Create array with goFonHomeServer */
280     $tmp = array();
281     foreach($this->goFonHomeServers as $dn => $val){
282       if(!is_numeric($dn)){
283         $tmp[$dn]  = $val['SERVER'];
284       }
285     }
286     $smarty->assign("goFonHomeServers",$tmp);
288     return ($display.$smarty->fetch (get_template_path('phonequeue.tpl', TRUE)));
289   }
292   /* Check formular input */
293   function check()
294   {
295     /* Call common method to give check the hook */
296     $message= plugin::check();
297     if(!count($this->goFonHomeServers)){
298       $message[] = _("There must be at least one server with an asterisk database to create a phone queue.");
299     }
300     if(empty($this->goFonHomeServer)){
301       $message[] = _("Please select a valid goFonHomeServer.");
302     }
303     if($this->is_number_used()){
304       $message[] = $this->is_number_used();
305     }
306     if(!((is_numeric($this->goFonTimeOut))||(empty($this->goFonTimeOut)))){
307       $message[] = _("Timeout must be numeric");
308     }
309     if(!((is_numeric($this->goFonQueueRetry))||(empty($this->goFonQueueRetry)))){
310       $message[] = _("Retry must be numeric");
311     }
312     if(!((is_numeric($this->goFonMaxLen))||(empty($this->goFonMaxLen)))){
313       $message[] = _("Max queue length must be numeric");
314     }
315     if(!((is_numeric($this->goFonAnnounceFrequency))||(empty($this->goFonAnnounceFrequency)))){
316       $message[] = _("Announce frequency must be numeric");
317     }
318     if(count($this->telephoneNumber)==0){
319       $message[] = _("There must be least one queue number defined.");
320     }
322     /* check if add to database could be successfull  */
323     $str = $this->add_to_database();
324     if(!empty($str)){
325       $message[] = $str;
326     }
327     return $message;
328   }
331   /* This function removes the old database entries. 
332    * If this entry should be removed or the home server has changed
333    *  this function is called to ensure that all old entries will be deleted.
334    */
335   function remove_from_database($save = false)
336   {
337     /* Check if we must remove old entries */
338     if($this->initially_was_account){
340       /* Check if there is at least on server configuration */
341       if(!count($this->goFonHomeServers)){
342         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."));
343       }
345       /********************
346        * Get configuration and check it
347        ********************/
349       /* Check if databases are reachable, returns an error string if anything fails  */
350       $error_str = $this->check_database_accessibility();
351       if($error_str){
352         return($error_str);
353       }
355       /* Connect to current database to be able to add new entries */
356       $cfg_Current  = $this->goFonHomeServers[$this->init_HomeServer] ;
357       $res_cur      =  @mysql_pconnect($cfg_Current['SERVER'],$cfg_Current['LOGIN'],$cfg_Current['PASSWORD']);
358       $db_cur       =  @mysql_select_db($cfg_Current['DB'],$res_cur);
360       /* Create sql entries */
361       $delete[]=    "DELETE FROM ".$cfg_Current['EXT_TABLE']."    WHERE exten='".$this->old_cn."';\n";
362       $delete[]=    "DELETE FROM ".$cfg_Current['QUEUE_TABLE']."  WHERE name='".$this->old_cn."'; \n";
363       $delete[]=    "DELETE FROM ".$cfg_Current['QUEUE_MEMBER_TABLE']." WHERE queue_name='".$this->old_cn."';\n";
364       foreach($this->old_phone_numbers as $number){
365         $delete[]=    "DELETE FROM ".$cfg_Current['EXT_TABLE']."    WHERE exten='".$number."';\n";
366       }
368       /* Execute the queries */  
369       if($save){
370         foreach($delete as $sql){
371           $res = @mysql_query($sql,$res_cur);
372           if(!$res){
373             gosa_log(@mysql_error($res_cur));
374             return(_("Error while removing old queue entries from database.").
375                 "&nbsp;"._("Please have a look a the gosa logfiles."));
376           }
377         }
378       }
379     }
380   }
383   /* This function handles the database entries for this 
384    *  queue. 
385    * Existing entries will be updated if possible.
386    */
387   function add_to_database($save = false)
388   {
389     /* Check if there is at least on server configuration */
390     if(!count($this->goFonHomeServers)){
391       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."));
392     }
394     /********************
395      * Get configuration and check it
396      ********************/
398     /* Check if databases are reachable, returns an error string if anything fails  */
399     $error_str = $this->check_database_accessibility();
400     if($error_str){
401       return($error_str);
402     }
404     /* Connect to current database to be able to add new entries */
405     $cfg_Current  = $this->goFonHomeServers[$this->goFonHomeServer] ;
406     $res_cur      =  @mysql_pconnect($cfg_Current['SERVER'],$cfg_Current['LOGIN'],$cfg_Current['PASSWORD']);
407     $db_cur       =  @mysql_select_db($cfg_Current['DB'],$res_cur);
409     /* Connect to old home server and remove old entries if necessary */
410     if(($this->initially_was_account) && ($this->init_HomeServer != $this->goFonHomeServer)){
411       $str = $this->remove_from_database($save); 
412       if(!empty($str)){
413         return($str);;
414       }
415     }
417     /* Ensure that we have the new cn in $this->cn and the old cn in $this->old_cn */
418     $this->cn = $this->parent->by_object['ogroup']->cn;
420     if($save){
421   
422       /*****************
423        * Create queue table entry 
424        *****************/
425  
426       /* Check if QUEUE_TABLE entry exists.
427        * If this entry is missing - create it 
428        *  else update the entry with new values.
429        */
430       $query = "SELECT * FROM ".$cfg_Current['QUEUE_TABLE']."  WHERE name='".$this->old_cn."';";
431       $res   = mysql_query($query,$res_cur);
432       if(!$res){
433         gosa_log(@mysql_error($res_cur));
434         return(_("Could not detect old queue entry, query failed.")."&nbsp;"._("Please have a look a the gosa logfiles."));
435       }
436       $cnt = mysql_affected_rows($res_cur);
439       /* Create queue table entry 
440        * Leave unused options empty. 
441        */
442       $queue["announce"]              = "";
443       $queue["monitor_join"]          = "";
444       $queue["monitor_format"]        = "";
445       $queue["announce_round_seconds"]= "";   
446       $queue["wrapuptime"]            = "";
447       $queue["servicelevel"]          = "";
448       $queue["eventmemberstatus"]     = "";
449       $queue["eventwhencalled"]       = "";
450       $queue["memberdelay"]           = "";
451       $queue["weight"]                = "";
452       $queue["timeoutrestart"]        = "";
454       $queue["queue_holdtime"]        = $this->goFonQueueAnnounce;
455       $queue["queue_lessthan"]        = $this->goFonQueueLessThan;   
456       $queue["retry"]                 = $this->goFonQueueRetry;
457       $queue["reportholdtime"]        = "1";
458       $queue["joinempty"]             = "no";
459       $queue["leavewhenempty"]        = "yes";   
461       $queue["context"]               = "default";
462       $queue["name"]                  = $this->cn;  
463       $queue["timeout"]               = $this->goFonTimeOut; 
464       $queue["maxlen"]                = $this->goFonMaxLen;
465       $queue["strategy" ]             = $this->goFonQueueStrategyOptionsR[$this->goFonQueueStrategy];
466       $queue["queue_thankyou"]        = $this->goFonQueueThankYou;   
467       $queue["queue_reporthold"]      = $this->goFonQueueReportHold; 
468       $queue["announce_frequency"]    = $this->goFonAnnounceFrequency;
469       $queue["queue_youarenext"]      = $this->goFonQueueYouAreNext;   
470       $queue["queue_thereare"]        = $this->goFonQueueThereAre;   
471       $queue["queue_callswaiting"]    = $this->goFonQueueCallsWaiting;
472       $queue["queue_minutes"]         = $this->goFonQueueMinutes;
473       $queue["queue_seconds"]         = $this->goFonQueueSeconds;   
474       $queue["announce_holdtime"]     = $this->goFonQueueAnnounceHoldtime;   
475       $queue["musiconhold"]           = $this->goFonMusiconHold;
478       /* Check if we must create a new queue entry 
479        *  or if we can update an existing entry 
480        *  $cnt contains the number of entries matching this cn
481        */
483       /* Create new queue table entry 
484        */
485       if($cnt == 0){
487         /* Parse and Add Queue */
488         $entries = "";
489         $values  = "";
490         foreach($queue as $attr=>$val){
491           if($val == "") continue;
492           $entries.= "`".$attr."`,";
493           $values .= "'".$val."',";
494         }
495         $values  = preg_replace("/,$/","",$values);
496         $entries = preg_replace("/,$/","",$entries );
497         $SQL[]="INSERT INTO ".$cfg_Current['QUEUE_TABLE']." (".$entries.") VALUES (".$values.");";
498       }elseif($cnt == 1){
500         /* Update queue table entry 
501          */
502         $queue_old = @mysql_fetch_assoc($res);
503         foreach($queue_old as $name => $value){
504           if(isset($queue[$name]) && $queue[$name] == $value){
505             unset($queue[$name]);
506           }
507         }
509         /* Parse and Add Queue */
510         if(count($queue)){
511           $query = "UPDATE ".$cfg_Current['QUEUE_TABLE']." SET ";
512           foreach($queue as $key => $val){
513             $query.= "".$key."='".$val."',";
514           }
515           $query = preg_replace("/,$/","",$query);
516           $query.= " WHERE name='".$this->old_cn."';";
517           $SQL[] = $query;
518         }
519       }else{
520         return(sprintf(_("More than one entry in queue table found, that uses the name ('%s'). Please fix this issue manually first."),$this->cn));
521       }
524       /*****************
525        * Create queue member entries
526        *****************/
527       
528       /* Add the queue member entries 
529        * First we must remove all old user entries. 
530        * to be able to add a clean set of members.
531        */ 
532       $SQL[]= "DELETE FROM ".$cfg_Current['QUEUE_MEMBER_TABLE']." WHERE queue_name='".$this->cn."';";
533       $SQL[]= "DELETE FROM ".$cfg_Current['QUEUE_MEMBER_TABLE']." WHERE queue_name='".$this->old_cn."';";
534       
535       /* Append new Member for this queue */ 
536       $queueuser =array();
537       $i = 0;
538       $parent = $this->parent->by_object['ogroup'];
540       
541       $ldap = $this->config->get_ldap_link();
542       foreach($parent->memberList as $member => $mem_data){
543         $ldap->cat($member,array("goFonHomeServer","objectClass","dn","uid"));
544         if($ldap->count()){
546           $obj = $ldap->fetch();
548           /* Calculate server and account dependencies */
549           $is_acc = in_array("goFonAccount",$obj['objectClass']);
550           $is_home= isset($obj['goFonHomeServer'][0]) && $obj['goFonHomeServer'][0] == $this->goFonHomeServer; 
552           /* Append user to list of queue member,
553            *  only if user has phoneAccount extension && is on same home server */
554           if($is_acc && $is_home){
555             $i ++ ;
556             $queueuser[$i]['queue_name']  = $this->cn; 
557             $queueuser[$i]['interface']   = "SIP/".$obj['uid'][0]; 
558             $queueuser[$i]['penalty']     = 1; 
559           }
560         }
561       }
563       /* Parse and Add members to query Array */
564       if(is_array($queueuser)){
565         foreach($queueuser as $user){
566           $entries = "";
567           $values  = "";
568           foreach($user as $attr => $val){
569             $entries.= "`".$attr."`,"; 
570             $values .= "'".$val."',";
571           }
572           $values  = preg_replace("/,$/","",$values);
573           $entries = preg_replace("/,$/","",$entries );
575           $SQL[]="INSERT INTO ".$cfg_Current['QUEUE_MEMBER_TABLE']." (".$entries.") VALUES (".$values.")"; 
576         }
577       }
578       
580       /*****************
581        * Create extension entries
582        *****************/
583       
584       /* Add the extension entries 
585        * First we must remove all old entensions. 
586        */ 
587       $SQL[]=  "DELETE FROM ".$cfg_Current['EXT_TABLE']."  WHERE exten='".$this->cn."';\n";
588       $SQL[]=  "DELETE FROM ".$cfg_Current['EXT_TABLE']."  WHERE exten='".$this->old_cn."';\n";
590       /* Delete old enxtension entries for the old telephone nubmer  */
591       if(is_array($this->old_phone_numbers)){
592         foreach($this->old_phone_numbers as $phone){
593           $SQL[]= "DELETE FROM ".$cfg_Current['EXT_TABLE']." WHERE exten='".$phone."';\n";
594         }
595       }
596       
597       /* Delete enxtension entries for telephone numbers  */
598       if(is_array($this->telephoneNumber)){
599         foreach($this->telephoneNumber as $phone){
600           $SQL[]= "DELETE FROM ".$cfg_Current['EXT_TABLE']." WHERE exten='".$phone."';\n";
601         }
602       }
604       /* Create a extension entry fpr each telephoneNumber */
605       $i_insert_only_once = false;
606       $prio = 11;   // This represents the priority for each telephoneNumber 
607       foreach($this->telephoneNumber as $num){
609         /* The naming refrences */
610         if($i_insert_only_once == false){
611           $i_insert_only_once = true;
612           $a_ext[$i]['context']  = 'GOsa';
613           $a_ext[$i]['exten']    = $this->cn;
614           $a_ext[$i]['priority'] = 1;
615           $a_ext[$i]['app']      = "Goto";
616           $a_ext[$i]['appdata']  = $num."|1";
617           $i ++ ; 
618         }
620         /* If there is currently no user for this queue 
621          * Play no service sound file and return to default context.  
622          */
623         if(count($queueuser)==0){
624           $a_ext[$i]['context']  = 'GOsa';
625           $a_ext[$i]['exten']    = $num;
626           $a_ext[$i]['priority'] = 1;
627           $a_ext[$i]['app']      = "SetLanguage";
628           $a_ext[$i]['appdata']  = "de";
629           $i ++ ; 
631           $a_ext[$i]['context']  = 'GOsa';
632           $a_ext[$i]['exten']    = $num;
633           $a_ext[$i]['priority'] = 2;
634           $a_ext[$i]['app']      = "Playback";
635           $a_ext[$i]['appdata']  = "ss-noservice";
636           $i ++ ; 
638           $a_ext[$i]['context']  = 'GOsa';
639           $a_ext[$i]['exten']    = $num;
640           $a_ext[$i]['priority'] = 3;
641           $a_ext[$i]['app']      = "Goto";
642           $a_ext[$i]['appdata']  = "default";
643           $i ++ ; 
644         }else{
646           /* Dcrement priority to avoid using same priority twice */
647           $prio --;
649           /* Wait for 2 seconds */
650           $a_ext[$i]['context']  = 'GOsa';
651           $a_ext[$i]['exten']    = $num;
652           $a_ext[$i]['priority'] = 1;
653           $a_ext[$i]['app']      = "Wait";
654           $a_ext[$i]['appdata']  = "2";
655           $i ++ ; 
656     
657           /* Set language to queue language */
658           $a_ext[$i]['context']  = 'GOsa';
659           $a_ext[$i]['exten']    = $num;
660           $a_ext[$i]['priority'] = 2;
661           $a_ext[$i]['app']      = "SetLanguage";
662           $a_ext[$i]['appdata']  = $this->goFonQueueLanguage;
663           $i ++ ; 
664   
665           /* Play welcome sound file */
666           $a_ext[$i]['context']  = 'GOsa';
667           $a_ext[$i]['exten']    = $num;
668           $a_ext[$i]['priority'] = 3;
669           $a_ext[$i]['app']      = "Playback";
670           $a_ext[$i]['appdata']  = $this->goFonWelcomeMusic;
671           $i ++ ; 
673           /* Set CID name */
674           $a_ext[$i]['context']  = 'GOsa';
675           $a_ext[$i]['exten']    = $num;
676           $a_ext[$i]['priority'] = 4;
677           $a_ext[$i]['app']      = "SetCIDName";
678           if(!empty($this->parent->by_object['ogroup']->description)){
679             $a_ext[$i]['appdata']  = $this->parent->by_object['ogroup']->description;
680           }else{
681             $a_ext[$i]['appdata']  = $this->cn." - ".$num;
682           }
683           $i ++ ; 
685           /* Set queue priority */
686           $a_ext[$i]['context']  = 'GOsa';
687           $a_ext[$i]['exten']    = $num;
688           $a_ext[$i]['priority'] = 5;
689           $a_ext[$i]['app']      = "SetVar";
690           $a_ext[$i]['appdata']  = "QUEUE_PRIO=".$prio;
691           $i ++ ; 
693           /* Open queue */
694           $a_ext[$i]['context']  = 'GOsa';
695           $a_ext[$i]['exten']    = $num;
696           $a_ext[$i]['priority'] = 6;
697           $a_ext[$i]['app']      = "Queue";
698           $a_ext[$i]['appdata']  =  $this->cn;
699             "|".
700             $this->goFonDialOption_t.
701             $this->goFonDialOption_T.
702             $this->goFonDialOption_h.
703             $this->goFonDialOption_H.
704             $this->goFonDialOption_r;
705         }
707         $i++;
708       }
710       /* Parse and Add Extension entries */
711       foreach($a_ext as $ext){
712         $entries = "";
713         $values  = "";
714         foreach($ext as $attr => $val){
715           $entries.= "`".$attr."`,";
716           $values .= "'".$val."',";
717         }
718         $values  = preg_replace("/,$/","",$values);
719         $entries = preg_replace("/,$/","",$entries );
720         $SQL[]="INSERT INTO ".$cfg_Current['EXT_TABLE']." (".$entries.") VALUES (".$values.")";
721       }
723       /* Do all collected mysql queries 
724        */
725       foreach($SQL as $query)
726       $res   = mysql_query($query,$res_cur);
727       if(!$res){
728         gosa_log(@mysql_error($res_cur));
729         return(_("Mysql query failed.")."&nbsp;"._("Please have a look a the gosa logfiles."));
730       }
731     }
732     @mysql_close($r_con);
733     return(false);
734   }
737   /* This function checks if the given phonenumbers 
738    *  are available or already in use
739    */
740   function is_number_used()
741   {
742     $ldap= $this->config->get_ldap_link();
743     $ldap->cd($this->config->current['BASE']);
744     $ldap->search("(&(& (!(uid=".$this->cn."))
745                         (!(cn=".$this->cn.")))
746                      (| (objectClass=goFonAccount)
747                         (objectClass=goFonQueue)
748                         (objectClass=goFonConference)))", array("telephoneNumber","cn","uid"));
749     while($attrs = $ldap->fetch()) {
750       unset($attrs['telephoneNumber']['count']);
751       foreach($attrs['telephoneNumber'] as $tele){
752         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
753         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
754         $numbers[$tele]=$attrs;
755       }
756     }
758     foreach($this->telephoneNumber as $num){
759       if((isset($numbers[$num]))&&(($numbers[$num]['cn'][0]!= $this->attrs['cn'][0]))){
760         if(isset($numbers[$num]['uid'][0])){
761           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
762         }else{
763           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
764         }
765       }
766     }
767   }
770   /* Get posted attributes */
771   function save_object()
772   {
773     plugin::save_object();  
774     if(isset($_POST['phonenumber'])){
775       foreach(array("goFonDialOption_t","goFonDialOption_T","goFonDialOption_h","goFonDialOption_r","goFonDialOption_H","goFonMusiconHold") as $val){
776         if(chkacl($this->acl,$val) == "") {
777           if(isset($_POST[$val])){
778             $this->$val = $_POST[$val];
779           }else{
780             $this->$val = false;
781           }
782         }
783       }
784       if(isset($_POST['goFonQueueAnnounceHoldtime'])){
785         $this->goFonQueueAnnounceHoldtime = "yes";
786       }else{
787         $this->goFonQueueAnnounceHoldtime = false;
788       }
789     }
790   }
793   function save()
794   {
795     $ldap= $this->config->get_ldap_link();
797     plugin::save();
799     /* Create dial option attribute */
800     $this->attrs['goFonDialOption'] = "";
801     foreach(array("goFonDialOption_t","goFonDialOption_T","goFonDialOption_r","goFonDialOption_h","goFonDialOption_H","cn") as $val){
802       $this->attrs['goFonDialOption'].=$this->$val; 
803       unset($this->attrs[$val]); 
804     }
805     if(empty($this->attrs['goFonDialOption'])) {
806       $this->attrs['goFonDialOption']=array();
807     }
809     /* Set announce hold time to yes no .. */
810     if($this->goFonQueueAnnounceHoldtime != "no" ){
811       $this->attrs['goFonQueueAnnounceHoldtime'] = "yes";
812     }else{
813       $this->attrs['goFonQueueAnnounceHoldtime'] = "no";
814     }
816     /* Set strategy */
817     $this->attrs['goFonQueueStrategy'] = $this->goFonQueueStrategyOptionsR[$this->goFonQueueStrategy];
819     /* Add database entry, display error and abort if this fails */
820     $str = $this->add_to_database(true);
821     if(!empty($str)){
822       print_red($str);
823     }
825     /* Save data to LDAP */
826     $ldap->cd($this->dn);
827     $this->cleanup();
828     $ldap->modify ($this->attrs); 
830     show_ldap_error($ldap->get_error(), _("Saving phone queue failed"));
832     /* Optionally execute a command after we're done */
833     if ($this->initially_was_account == $this->is_account){
834       if ($this->is_modified){
835         $this->handle_post_events("modify");
836       }
837     } else {
838       $this->handle_post_events("add");
839     }
840   }
843   /* remove object from parent */
844   function remove_from_parent()
845   {
846     /* Cancel if nothing is to do here */
847     if (!$this->initially_was_account){
848       return;
849     }
851     /* Remove database entries, 
852      *  if fails display errors and abort
853      */
854     $str = $this->remove_from_database(true);
855     if(!empty($str)){
856       print_red($str);
857       return false;
858     }
859   
860     /* Remove all temporary attributes */
861     $tmp = array_flip($this->attributes);
862     foreach(array("goFonDialOption_t","goFonDialOption_T","goFonDialOption_r","goFonDialOption_h","goFonDialOption_H","cn") as $val){
863       unset($this->$val);
864       unset($this->attrs[$val]);
865       unset($tmp[$val]);
866     }   
867     foreach(array_flip($tmp) as $key => $val){
868       $tmp2[]=$val;
869     } 
870     $this->attributes = $tmp2;
872     /* include global link_info */
873     $ldap= $this->config->get_ldap_link();
875     /* Remove and write to LDAP */
876     plugin::remove_from_parent();
878     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,$this->attributes, "Save");
879     $ldap->cd($this->dn);
880     $this->cleanup();
881     $ldap->modify ($this->attrs); 
882     show_ldap_error($ldap->get_error(), _("Removing phone queue failed"));
883   }
885   
886   function getCopyDialog()
887   {
888     $str  = "";
889     $str .= _("Phone number");
890     $str .= "&nbsp;<input type='text' name='telephoneNumber' value='".$this->telephoneNumber."'>";
891     return($str);
892   }
895   function saveCopyDialog()
896   {
897     if(isset($_POST['telephoneNumber'])){
898       $this->telephoneNumber = $_POST['telephoneNumber'];
899     }
900   }
905 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
906 ?>