Code

Added "multiple action checkboxes" to object group list.
[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 $goFonDialOptiont         ="";
14   var $goFonDialOptionT         ="";
15   var $goFonDialOptionh         ="";
16   var $goFonDialOptionr         ="";
17   var $goFonDialOptionH         ="";
18   var $goFonQueueAnnounce       ="gonicus-berlin-welcome";
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","goFonDialOptiont","goFonDialOptionT",
48       "goFonDialOptionh","goFonDialOptionr","cn","goFonHomeServer",
49       "goFonDialOptionH","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     if(isset($_POST['modify_state'])){
198       if($this->is_account && $this->acl_is_removeable()){
199         $this->is_account= FALSE;
200       }elseif(!$this->is_account && $this->acl_is_createable()){
201         $this->is_account= TRUE;
202       }
203     }
205     /* Show tab dialog headers */
206     if ($this->parent != NULL){
207       if ($this->is_account){
208         $display= $this->show_disable_header(_("Remove the phone queue from this Account"),
209             _("Phone queue is enabled for this group. You can disable it by clicking below."));
210       } else {
211         $display= $this->show_enable_header(_("Create phone queue"),
212             _("For this group the phone queues are disabled. You can enable them by clicking below."));
213         return ($display);
214       }
215     }
217     if($this->acl_is_writeable("telephoneNumber")){
219       /* Add queue number */ 
220       if(isset($_POST['add_phonenumber'])&&(isset($_POST['phonenumber']))&&(!empty($_POST['phonenumber']))){
221         if((!in_array($_POST['phonenumber'],$this->telephoneNumber))&&(is_numeric($_POST['phonenumber']))){
222           $this->telephoneNumber[]=$_POST['phonenumber'];
223         }
224       }
226       /* Delete queue number */ 
227       if(isset($_POST['delete_phonenumber'])&&(isset($_POST['goFonQueueNumber_List']))){
228         unset($this->telephoneNumber[$_POST['goFonQueueNumber_List']]);
229       }
231       /* queue number up */ 
232       if(isset($_POST['up_phonenumber'])&&(isset($_POST['goFonQueueNumber_List']))){
233         if($_POST['goFonQueueNumber_List']>0){
234           $up   = $this->telephoneNumber[$_POST['goFonQueueNumber_List']];
235           $down = $this->telephoneNumber[$_POST['goFonQueueNumber_List']-1];
236           $this->telephoneNumber[$_POST['goFonQueueNumber_List']]    = $down;
237           $this->telephoneNumber[$_POST['goFonQueueNumber_List']-1]  = $up;
238         }
239       }
241       /* Queuenumber down */
242       if(isset($_POST['down_phonenumber'])&&(isset($_POST['goFonQueueNumber_List']))){
243         if(isset($this->telephoneNumber[($_POST['goFonQueueNumber_List']+1)])){
244           $up   = $this->telephoneNumber[$_POST['goFonQueueNumber_List']+1];
245           $down = $this->telephoneNumber[$_POST['goFonQueueNumber_List']];
246           $this->telephoneNumber[$_POST['goFonQueueNumber_List']+1]    = $down;
247           $this->telephoneNumber[$_POST['goFonQueueNumber_List']]  = $up;
248         }
249         $this->telephoneNumber[$_POST['goFonQueueNumber_List']]  = $up;
250       }
251     }
253     $tmp = array();
254     foreach($this->telephoneNumber as $val){
255       if(!empty($val)){
256         $tmp[]= $val;
257       }
258     }  
259     $this->telephoneNumber=$tmp;
261     /* Assign samrty variables */
262     $smarty= get_smarty();
263     $smarty->assign("goFonQueueLanguageOptions",array('de'=>_('German')));
264     $smarty->assign("goFonQueueStrategyOptions", $this->goFonQueueStrategyOptions);
266     /* Set acls */
267     $tmp = $this->plInfo();
268     foreach($tmp['plProvidedAcls'] as $name => $translated){
269       $smarty->assign($name."ACL",$this->getacl($name));
270     }
272     foreach($this->attributes as $key => $val){
273       $smarty->assign($val,$this->$val);  
274       if($this->$val == false){
275         $smarty->assign($val."CHK","");
276       }else{
277         $smarty->assign($val."CHK"," checked ");
278       }
279     }
280     
281     /* Create array with goFonHomeServer */
282     $tmp = array();
283     foreach($this->goFonHomeServers as $dn => $val){
284       if(!is_numeric($dn)){
285         $tmp[$dn]  = $val['SERVER'];
286       }
287     }
288     $smarty->assign("goFonHomeServers",$tmp);
290     return ($display.$smarty->fetch (get_template_path('phonequeue.tpl', TRUE)));
291   }
294   /* Check formular input */
295   function check()
296   {
297     /* Call common method to give check the hook */
298     $message= plugin::check();
299     if(!count($this->goFonHomeServers)){
300       $message[] = _("There must be at least one server with an asterisk database to create a phone queue.");
301     }
302     if(empty($this->goFonHomeServer)){
303       $message[] = _("Please select a valid goFonHomeServer.");
304     }
305     if($this->is_number_used()){
306       $message[] = $this->is_number_used();
307     }
308     if(!((is_numeric($this->goFonTimeOut))||(empty($this->goFonTimeOut)))){
309       $message[] = _("Timeout must be numeric");
310     }
311     if(!((is_numeric($this->goFonQueueRetry))||(empty($this->goFonQueueRetry)))){
312       $message[] = _("Retry must be numeric");
313     }
314     if(!((is_numeric($this->goFonMaxLen))||(empty($this->goFonMaxLen)))){
315       $message[] = _("Max queue length must be numeric");
316     }
317     if(!((is_numeric($this->goFonAnnounceFrequency))||(empty($this->goFonAnnounceFrequency)))){
318       $message[] = _("Announce frequency must be numeric");
319     }
320     if(count($this->telephoneNumber)==0){
321       $message[] = _("There must be least one queue number defined.");
322     }
324     /* check if add to database could be successfull  */
325     $str = $this->add_to_database();
326     if(!empty($str)){
327       $message[] = $str;
328     }
329     return $message;
330   }
333   /* This function removes the old database entries. 
334    * If this entry should be removed or the home server has changed
335    *  this function is called to ensure that all old entries will be deleted.
336    */
337   function remove_from_database($save = false)
338   {
339     /* Check if we must remove old entries */
340     if($this->initially_was_account){
342       /* Check if there is at least on server configuration */
343       if(!count($this->goFonHomeServers)){
344         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."));
345       }
347       /********************
348        * Get configuration and check it
349        ********************/
351       /* Check if databases are reachable, returns an error string if anything fails  */
352       $error_str = $this->check_database_accessibility();
353       if($error_str){
354         return($error_str);
355       }
357       /* Connect to current database to be able to add new entries */
358       $cfg_Current  = $this->goFonHomeServers[$this->init_HomeServer] ;
359       $res_cur      =  @mysql_pconnect($cfg_Current['SERVER'],$cfg_Current['LOGIN'],$cfg_Current['PASSWORD']);
360       $db_cur       =  @mysql_select_db($cfg_Current['DB'],$res_cur);
362       /* Create sql entries */
363       $delete[]=    "DELETE FROM ".$cfg_Current['EXT_TABLE']."    WHERE exten='".$this->old_cn."';\n";
364       $delete[]=    "DELETE FROM ".$cfg_Current['QUEUE_TABLE']."  WHERE name='".$this->old_cn."'; \n";
365       $delete[]=    "DELETE FROM ".$cfg_Current['QUEUE_MEMBER_TABLE']." WHERE queue_name='".$this->old_cn."';\n";
366       foreach($this->old_phone_numbers as $number){
367         $delete[]=    "DELETE FROM ".$cfg_Current['EXT_TABLE']."    WHERE exten='".$number."';\n";
368       }
370       /* Execute the queries */  
371       if($save){
372         foreach($delete as $sql){
373           $res = @mysql_query($sql,$res_cur);
374           if(!$res){
375             gosa_log(@mysql_error($res_cur));
376             return(_("Error while removing old queue entries from database.").
377                 "&nbsp;"._("Please have a look a the gosa logfiles."));
378           }
379         }
380       }
381     }
382   }
385   /* This function handles the database entries for this 
386    *  queue. 
387    * Existing entries will be updated if possible.
388    */
389   function add_to_database($save = false)
390   {
391     /* Check if there is at least on server configuration */
392     if(!count($this->goFonHomeServers)){
393       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."));
394     }
396     /********************
397      * Get configuration and check it
398      ********************/
400     /* Check if databases are reachable, returns an error string if anything fails  */
401     $error_str = $this->check_database_accessibility();
402     if($error_str){
403       return($error_str);
404     }
406     /* Connect to current database to be able to add new entries */
407     $cfg_Current  = $this->goFonHomeServers[$this->goFonHomeServer] ;
408     $res_cur      =  @mysql_pconnect($cfg_Current['SERVER'],$cfg_Current['LOGIN'],$cfg_Current['PASSWORD']);
409     $db_cur       =  @mysql_select_db($cfg_Current['DB'],$res_cur);
411     /* Connect to old home server and remove old entries if necessary */
412     if(($this->initially_was_account) && ($this->init_HomeServer != $this->goFonHomeServer)){
413       $str = $this->remove_from_database($save); 
414       if(!empty($str)){
415         return($str);;
416       }
417     }
419     /* Ensure that we have the new cn in $this->cn and the old cn in $this->old_cn */
420     $this->cn = $this->parent->by_object['ogroup']->cn;
422     if($save){
423   
424       /*****************
425        * Create queue table entry 
426        *****************/
427  
428       /* Check if QUEUE_TABLE entry exists.
429        * If this entry is missing - create it 
430        *  else update the entry with new values.
431        */
432       $query = "SELECT * FROM ".$cfg_Current['QUEUE_TABLE']."  WHERE name='".$this->old_cn."';";
433       $res   = mysql_query($query,$res_cur);
434       if(!$res){
435         gosa_log(@mysql_error($res_cur));
436         return(_("Could not detect old queue entry, query failed.")."&nbsp;"._("Please have a look a the gosa logfiles."));
437       }
438       $cnt = mysql_affected_rows($res_cur);
441       /* Create queue table entry 
442        * Leave unused options empty. 
443        */
444       $queue["announce"]              = "";
445       $queue["monitor_join"]          = "";
446       $queue["monitor_format"]        = "";
447       $queue["announce_round_seconds"]= "";   
448       $queue["wrapuptime"]            = "";
449       $queue["servicelevel"]          = "";
450       $queue["eventmemberstatus"]     = "";
451       $queue["eventwhencalled"]       = "";
452       $queue["memberdelay"]           = "";
453       $queue["weight"]                = "";
454       $queue["timeoutrestart"]        = "";
456       $queue["queue_holdtime"]        = $this->goFonQueueAnnounce;
457       $queue["queue_lessthan"]        = $this->goFonQueueLessThan;   
458       $queue["retry"]                 = $this->goFonQueueRetry;
459       $queue["reportholdtime"]        = "1";
460       $queue["joinempty"]             = "no";
461       $queue["leavewhenempty"]        = "yes";   
463       $queue["context"]               = "default";
464       $queue["name"]                  = $this->cn;  
465       $queue["timeout"]               = $this->goFonTimeOut; 
466       $queue["maxlen"]                = $this->goFonMaxLen;
467       $queue["strategy" ]             = $this->goFonQueueStrategyOptionsR[$this->goFonQueueStrategy];
468       $queue["queue_thankyou"]        = $this->goFonQueueThankYou;   
469       $queue["queue_reporthold"]      = $this->goFonQueueReportHold; 
470       $queue["announce_frequency"]    = $this->goFonAnnounceFrequency;
471       $queue["queue_youarenext"]      = $this->goFonQueueYouAreNext;   
472       $queue["queue_thereare"]        = $this->goFonQueueThereAre;   
473       $queue["queue_callswaiting"]    = $this->goFonQueueCallsWaiting;
474       $queue["queue_minutes"]         = $this->goFonQueueMinutes;
475       $queue["queue_seconds"]         = $this->goFonQueueSeconds;   
476       $queue["announce_holdtime"]     = $this->goFonQueueAnnounceHoldtime;   
477       $queue["musiconhold"]           = $this->goFonMusiconHold;
480       /* Check if we must create a new queue entry 
481        *  or if we can update an existing entry 
482        *  $cnt contains the number of entries matching this cn
483        */
485       /* Create new queue table entry 
486        */
487       if($cnt == 0){
489         /* Parse and Add Queue */
490         $entries = "";
491         $values  = "";
492         foreach($queue as $attr=>$val){
493           if($val == "") continue;
494           $entries.= "`".$attr."`,";
495           $values .= "'".$val."',";
496         }
497         $values  = preg_replace("/,$/","",$values);
498         $entries = preg_replace("/,$/","",$entries );
499         $SQL[]="INSERT INTO ".$cfg_Current['QUEUE_TABLE']." (".$entries.") VALUES (".$values.");";
500       }elseif($cnt == 1){
502         /* Update queue table entry 
503          */
504         $queue_old = @mysql_fetch_assoc($res);
505         foreach($queue_old as $name => $value){
506           if(isset($queue[$name]) && $queue[$name] == $value){
507             unset($queue[$name]);
508           }
509         }
511         /* Parse and Add Queue */
512         if(count($queue)){
513           $query = "UPDATE ".$cfg_Current['QUEUE_TABLE']." SET ";
514           foreach($queue as $key => $val){
515             $query.= "".$key."='".$val."',";
516           }
517           $query = preg_replace("/,$/","",$query);
518           $query.= " WHERE name='".$this->old_cn."';";
519           $SQL[] = $query;
520         }
521       }else{
522         return(sprintf(_("More than one entry in queue table found, that uses the name ('%s'). Please fix this issue manually first."),$this->cn));
523       }
526       /*****************
527        * Create queue member entries
528        *****************/
529       
530       /* Add the queue member entries 
531        * First we must remove all old user entries. 
532        * to be able to add a clean set of members.
533        */ 
534       $SQL[]= "DELETE FROM ".$cfg_Current['QUEUE_MEMBER_TABLE']." WHERE queue_name='".$this->cn."';";
535       $SQL[]= "DELETE FROM ".$cfg_Current['QUEUE_MEMBER_TABLE']." WHERE queue_name='".$this->old_cn."';";
536       
537       /* Append new Member for this queue */ 
538       $queueuser =array();
539       $i = 0;
540       $parent = $this->parent->by_object['ogroup'];
542       
543       $ldap = $this->config->get_ldap_link();
544       foreach($parent->memberList as $member => $mem_data){
545         $ldap->cat($member,array("goFonHomeServer","objectClass","dn","uid"));
546         if($ldap->count()){
548           $obj = $ldap->fetch();
550           /* Calculate server and account dependencies */
551           $is_acc = in_array("goFonAccount",$obj['objectClass']);
552           $is_home= isset($obj['goFonHomeServer'][0]) && $obj['goFonHomeServer'][0] == $this->goFonHomeServer; 
554           /* Append user to list of queue member,
555            *  only if user has phoneAccount extension && is on same home server */
556           if($is_acc && $is_home){
557             $i ++ ;
558             $queueuser[$i]['queue_name']  = $this->cn; 
559             $queueuser[$i]['interface']   = "SIP/".$obj['uid'][0]; 
560             $queueuser[$i]['penalty']     = 1; 
561           }
562         }
563       }
565       /* Parse and Add members to query Array */
566       if(is_array($queueuser)){
567         foreach($queueuser as $user){
568           $entries = "";
569           $values  = "";
570           foreach($user as $attr => $val){
571             $entries.= "`".$attr."`,"; 
572             $values .= "'".$val."',";
573           }
574           $values  = preg_replace("/,$/","",$values);
575           $entries = preg_replace("/,$/","",$entries );
577           $SQL[]="INSERT INTO ".$cfg_Current['QUEUE_MEMBER_TABLE']." (".$entries.") VALUES (".$values.")"; 
578         }
579       }
580       
582       /*****************
583        * Create extension entries
584        *****************/
585       
586       /* Add the extension entries 
587        * First we must remove all old entensions. 
588        */ 
589       $SQL[]=  "DELETE FROM ".$cfg_Current['EXT_TABLE']."  WHERE exten='".$this->cn."';\n";
590       $SQL[]=  "DELETE FROM ".$cfg_Current['EXT_TABLE']."  WHERE exten='".$this->old_cn."';\n";
592       /* Delete old enxtension entries for the old telephone nubmer  */
593       if(is_array($this->old_phone_numbers)){
594         foreach($this->old_phone_numbers as $phone){
595           $SQL[]= "DELETE FROM ".$cfg_Current['EXT_TABLE']." WHERE exten='".$phone."';\n";
596         }
597       }
598       
599       /* Delete enxtension entries for telephone numbers  */
600       if(is_array($this->telephoneNumber)){
601         foreach($this->telephoneNumber as $phone){
602           $SQL[]= "DELETE FROM ".$cfg_Current['EXT_TABLE']." WHERE exten='".$phone."';\n";
603         }
604       }
606       /* Create a extension entry fpr each telephoneNumber */
607       $i_insert_only_once = false;
608       $prio = 11;   // This represents the priority for each telephoneNumber 
609       foreach($this->telephoneNumber as $num){
611         /* The naming refrences */
612         if($i_insert_only_once == false){
613           $i_insert_only_once = true;
614           $a_ext[$i]['context']  = 'GOsa';
615           $a_ext[$i]['exten']    = $this->cn;
616           $a_ext[$i]['priority'] = 1;
617           $a_ext[$i]['app']      = "Goto";
618           $a_ext[$i]['appdata']  = $num."|1";
619           $i ++ ; 
620         }
622         /* If there is currently no user for this queue 
623          * Play no service sound file and return to default context.  
624          */
625         if(count($queueuser)==0){
626           $a_ext[$i]['context']  = 'GOsa';
627           $a_ext[$i]['exten']    = $num;
628           $a_ext[$i]['priority'] = 1;
629           $a_ext[$i]['app']      = "SetLanguage";
630           $a_ext[$i]['appdata']  = "de";
631           $i ++ ; 
633           $a_ext[$i]['context']  = 'GOsa';
634           $a_ext[$i]['exten']    = $num;
635           $a_ext[$i]['priority'] = 2;
636           $a_ext[$i]['app']      = "Playback";
637           $a_ext[$i]['appdata']  = "ss-noservice";
638           $i ++ ; 
640           $a_ext[$i]['context']  = 'GOsa';
641           $a_ext[$i]['exten']    = $num;
642           $a_ext[$i]['priority'] = 3;
643           $a_ext[$i]['app']      = "Goto";
644           $a_ext[$i]['appdata']  = "default";
645           $i ++ ; 
646         }else{
648           /* Dcrement priority to avoid using same priority twice */
649           $prio --;
651           /* Wait for 2 seconds */
652           $a_ext[$i]['context']  = 'GOsa';
653           $a_ext[$i]['exten']    = $num;
654           $a_ext[$i]['priority'] = 1;
655           $a_ext[$i]['app']      = "Wait";
656           $a_ext[$i]['appdata']  = "2";
657           $i ++ ; 
658     
659           /* Set language to queue language */
660           $a_ext[$i]['context']  = 'GOsa';
661           $a_ext[$i]['exten']    = $num;
662           $a_ext[$i]['priority'] = 2;
663           $a_ext[$i]['app']      = "SetLanguage";
664           $a_ext[$i]['appdata']  = $this->goFonQueueLanguage;
665           $i ++ ; 
666   
667           /* Play welcome sound file */
668           $a_ext[$i]['context']  = 'GOsa';
669           $a_ext[$i]['exten']    = $num;
670           $a_ext[$i]['priority'] = 3;
671           $a_ext[$i]['app']      = "Playback";
672           $a_ext[$i]['appdata']  = $this->goFonWelcomeMusic;
673           $i ++ ; 
675           /* Set CID name */
676           $a_ext[$i]['context']  = 'GOsa';
677           $a_ext[$i]['exten']    = $num;
678           $a_ext[$i]['priority'] = 4;
679           $a_ext[$i]['app']      = "SetCIDName";
680           if(!empty($this->parent->by_object['ogroup']->description)){
681             $a_ext[$i]['appdata']  = $this->parent->by_object['ogroup']->description;
682           }else{
683             $a_ext[$i]['appdata']  = $this->cn." - ".$num;
684           }
685           $i ++ ; 
687           /* Set queue priority */
688           $a_ext[$i]['context']  = 'GOsa';
689           $a_ext[$i]['exten']    = $num;
690           $a_ext[$i]['priority'] = 5;
691           $a_ext[$i]['app']      = "SetVar";
692           $a_ext[$i]['appdata']  = "QUEUE_PRIO=".$prio;
693           $i ++ ; 
695           /* Open queue */
696           $a_ext[$i]['context']  = 'GOsa';
697           $a_ext[$i]['exten']    = $num;
698           $a_ext[$i]['priority'] = 6;
699           $a_ext[$i]['app']      = "Queue";
700           $a_ext[$i]['appdata']  =  $this->cn;
701             "|".
702             $this->goFonDialOptiont.
703             $this->goFonDialOptionT.
704             $this->goFonDialOptionh.
705             $this->goFonDialOptionH.
706             $this->goFonDialOptionr;
707         }
709         $i++;
710       }
712       /* Parse and Add Extension entries */
713       foreach($a_ext as $ext){
714         $entries = "";
715         $values  = "";
716         foreach($ext as $attr => $val){
717           $entries.= "`".$attr."`,";
718           $values .= "'".$val."',";
719         }
720         $values  = preg_replace("/,$/","",$values);
721         $entries = preg_replace("/,$/","",$entries );
722         $SQL[]="INSERT INTO ".$cfg_Current['EXT_TABLE']." (".$entries.") VALUES (".$values.")";
723       }
725       /* Do all collected mysql queries 
726        */
727       foreach($SQL as $query)
728       $res   = mysql_query($query,$res_cur);
729       if(!$res){
730         gosa_log(@mysql_error($res_cur));
731         return(_("Mysql query failed.")."&nbsp;"._("Please have a look a the gosa logfiles."));
732       }
733     }
734     @mysql_close($r_con);
735     return(false);
736   }
739   /* This function checks if the given phonenumbers 
740    *  are available or already in use
741    */
742   function is_number_used()
743   {
744     $ldap= $this->config->get_ldap_link();
745     $ldap->cd($this->config->current['BASE']);
746     $ldap->search("(&(& (!(uid=".$this->cn."))
747                         (!(cn=".$this->cn.")))
748                      (| (objectClass=goFonAccount)
749                         (objectClass=goFonQueue)
750                         (objectClass=goFonConference)))", array("telephoneNumber","cn","uid"));
751     while($attrs = $ldap->fetch()) {
752       unset($attrs['telephoneNumber']['count']);
753       foreach($attrs['telephoneNumber'] as $tele){
754         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
755         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
756         $numbers[$tele]=$attrs;
757       }
758     }
760     foreach($this->telephoneNumber as $num){
761       if((isset($numbers[$num]))&&(($numbers[$num]['cn'][0]!= $this->attrs['cn'][0]))){
762         if(isset($numbers[$num]['uid'][0])){
763           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
764         }else{
765           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
766         }
767       }
768     }
769   }
772   /* Get posted attributes */
773   function save_object()
774   {
775     plugin::save_object();  
776     if(isset($_POST['phonenumber'])){
777       foreach(array("goFonDialOptiont","goFonDialOptionT","goFonDialOptionh","goFonDialOptionr","goFonDialOptionH","goFonMusiconHold") as $val){
778         if(isset($_POST[$val])){
779           $this->$val = $_POST[$val];
780         }else{
781           $this->$val = false;
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("goFonDialOptiont","goFonDialOptionT","goFonDialOptionr","goFonDialOptionh","goFonDialOptionH","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("goFonDialOptiont","goFonDialOptionT","goFonDialOptionr","goFonDialOptionh","goFonDialOptionH","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   }
903   function plInfo()
904   {
905     return (array(
906           "plShortName"   => _("Phone"),
907           "plDescription" => _("Phone group"),
908           "plSelfModify"  => FALSE,
909           "plDepends"     => array(),
910           "plPriority"    => 3,
911           "plSection"     => array("administration"),
912           "plCategory"    => array("ogroups"),
913           "plProvidedAcls"=> array(
915             "goFonTimeOut"              => _("Timeout"),
916             "goFonMaxLen"               => _("Max queue length"),
917             "goFonHomeServer"           => _("Home server"),
918             "goFonAnnounceFrequency"    => _("Announce frequency"),
919             "goFonDialOptiont"          => _("Allow the called user to transfer his call"),
920             "goFonDialOptionT"          => _("Allows calling user to transfer call"),
921             "goFonDialOptionh"          => _("Allow the called to hangup by pressing *"),
922             "goFonDialOptionr"          => _("Ring instead of playing background music"),
923             "goFonDialOptionH"          => _("Allows calling to hangup by pressing *"),
925             "goFonMusiconHold"          => _("Music on hold"),
926             "goFonWelcomeMusic"         => _("Welcome music"),
927             "goFonQueueReportHold"      => _("Report hold time"),
928             "goFonQueueYouAreNext"      => _("'You are next' sound"),
929             "goFonQueueThereAre"        => _("'There are' sound"),
930             "goFonQueueCallsWaiting"    => _("'Call waiting' sound"),
931             "goFonQueueThankYou"        => _("'Thank you' sound"),
932             "goFonQueueMinutes"         => _("'Minutes' sound"),
933             "goFonQueueSeconds"         => _("'Seconds' sound"),
934             "goFonQueueLessThan"        => _("'Less than' sound"),
935             "telephoneNumber"           => _("Queue phone number"),
936             "goFonQueueLanguage"        => _("Language"),
937             "goFonQueueStrategy"        => _("Method"),
938             "goFonQueueAnnounceHoldtime"=> _("Announce holdtime"),
939             "goFonQueueAnnounce"        => _("Announce"),
940             "goFonQueueRetry"           => _("Retry"))
941               ));
942   }
946 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
947 ?>