Code

Fixed proxy account (squid). Selection of worktime filtering wasn't working.
[gosa.git] / gosa-plugins / gofon / gofon / macro / class_gofonMacro.inc
1 <?php
3 //!  The Phone Macro Class: Handles Macro Contents, and some attributes. 
4 /*!
5      This class handles the basic information about phone macros, like
6      cn base description displayName goFonMacroContent goFonMacroVisible
8      This is not the only Class that manages phone Macros, there ist also the class_goFonMacroParameter.
9 */
10 class macro extends plugin
11 {
13   /*! Macro attributes,  */
14   var $generate_error= "";
15   
16   /*! The name of the Macro in the openldap drirectory */
17   var $cn               = ""; 
18  
19   /*! Display error once */
20   var $error_shown = false; 
22   /*! This ist the variable that contains the description of the macro*/
23   var $description      = "";
25   /*! The base of the macro, is used to save the macro in the correct directory tree */
26   var $base             = "";
28   /*! This is the name of the macro which the enduser will see, instead of the cn */
29   var $displayName      = "";
30     
31   /*! Here is the macro content, the real macroscript */
32   var $goFonMacroContent= "";
33   
34   /*! To allow user to use this macro this var must be true, else false */
35   var $goFonMacroVisible= 0;
37   /*! attribute list for save action */
38   var $attributes     = array("cn","base", "description","displayName","goFonMacroContent","goFonMacroVisible");
39   var $view_logged = FALSE;
40   var $orig_cn = ""; 
41   var $orig_base = ""; 
42   var $orig_dn = ""; 
43   /*! Objectclasses that this calls handles */
44   var $objectclasses  = array("top", "goFonMacro");
46   var $goFonHomeServers = array(); // Contains all available asterisk database server 
48   //! The Konstructor   
49   /*!  Konstructor, load class with  attributes of the given dn*/
50   function macro (&$config, $dn= NULL, $parent= NULL)
51   {
52     plugin::plugin ($config, $dn, $parent);
54     /* This is always an account */
55     $this->is_account= TRUE;
57     /* Edit or new one ?*/
58     if ($this->dn == "new"){
59       if(session::is_set('CurrentMainBase')){
60         $this->base  = session::get('CurrentMainBase');
61       }else{
62         $ui= get_userinfo();
63         $this->base= dn2base($ui->dn);
64       }
65     } else {
66       $this->orig_cn=$this->cn;
67       $this->base= preg_replace ("/^[^,]+,".normalizePreg(get_ou("macroou"))."/i", "", $this->dn);
68     }
70     /* Check server configurations
71      * Load all server configuration in $this->goFonHomeServers if available
72      */
73     $a_SETUP= array();
74     if(isset($config->data['SERVERS']['FON'])){
76       /* Set available server */
77       $this->goFonHomeServers = $config->data['SERVERS']['FON'];
78   
79       /* Remove default entry, not necessary here */
80       if(isset($this->goFonHomeServers[0])){
81         unset($this->goFonHomeServers[0]);  
82       }
83     }
84     
85     $this->orig_base = $this->base;
86     $this->orig_dn = $this->dn;
87   }
90   /*!  Execute this plugin */
91   function execute()
92   {
93     /* Call parent execute */
94     plugin::execute();
96     /* Log view */
97     if($this->is_account && !$this->view_logged){
98       $this->view_logged = TRUE;
99       new log("view","gofonmacro/".get_class($this),$this->dn);
100     }
102     /* Variables */
103     $vars       = "";
104     $tmp        = array();
105     $number = 0; 
107     /* Base select dialog */
108     $once = true;
109     foreach($_POST as $name => $value){
110       if(preg_match("/^chooseBase/",$name) && $once){
111         $once = false;
112         $this->dialog = new baseSelectDialog($this->config,$this,$this->allowedBasesToMoveTo());
113         $this->dialog->setCurrentBase($this->base);
114       }
115     }
117     /* Dialog handling */
118     if(is_object($this->dialog)){
119       /* Must be called before save_object */
120       $this->dialog->save_object();
122       if($this->dialog->isClosed()){
123         $this->dialog = false;
124       }elseif($this->dialog->isSelected()){
126         /* A new base was selected, check if it is a valid one */
127         $tmp = $this->get_allowed_bases();
128         if(isset($tmp[$this->dialog->isSelected()])){
129           $this->base = $this->dialog->isSelected();
130         }
132         $this->dialog= false;
133       }else{
134         return($this->dialog->execute());
135       }
136     }
138     /* Fill templating stuff */
139     $smarty= get_smarty();
140     $smarty->assign("bases", $this->get_allowed_bases());
142     $tmp = $this->plInfo();
143     foreach($tmp['plProvidedAcls'] as $name => $translation){
144       $smarty->assign($name."ACL",$this->getacl($name));
145     }
147     if($this->acl_is_writeable("base")){
148       $smarty->assign("baseSelect",true);
149     }else{
150       $smarty->assign("baseSelect",false);
151     }
154     /* Assign all vars to Smarty */
155     foreach($this->attributes as $ar){
156       $smarty->assign($ar, $this->$ar);
157     }
158     /* Checkboxes */
159     $smarty->assign("base_select", $this->base);
160     $smarty->assign("vars", $vars);
162     if($this->goFonMacroVisible){
163       $smarty->assign("goFonMacroVisibleChecked"," checked ");
164     }else{
165       $smarty->assign("goFonMacroVisibleChecked","");
166     }
168     $smarty->assign("cnACL",$this->getacl("cn",$this->initially_was_account));
169     $smarty->assign("cn",$this->cn);
171     /* Ensure that macro content is displayed correctly encoded */
172     $smarty->assign("goFonMacroContent",htmlentities(utf8_decode ($this->goFonMacroContent)));
174     /* Show main page */
175     return($smarty->fetch (get_template_path('generic.tpl', TRUE)));
176   }
179   /* This method check if all databases are reachable.  
180    *  Returns with error message or an empty string on success.
181    * 
182    * - Is mysql extension available  
183    * - Is every server reachable 
184    * - Does the database exists/is accessible
185    */
186   function check_database_accessibility()
187   {
188     /* Check if mysql extension is available */
189     if(!is_callable("mysql_pconnect")){
190       return(msgPool::missingext("php-mysql"));
191     }
193     /********************
194      * Check all home server
195      ********************/
196     foreach($this->goFonHomeServers as $goFonHomeServer => $cfg_Current){
197       $r_current    =  @mysql_pconnect($cfg_Current['SERVER'],$cfg_Current['LOGIN'],$cfg_Current['PASSWORD']);
198       if(!$r_current){
199         new log("debug","gofonmacro/".get_class($this),"",array(),@mysql_error($r_current));
200         return ( msgPool::dbconnect("GOfon",@mysql_error(),$cfg_Current['SERVER']));
201       }
202       $db_current  =  @mysql_select_db($cfg_Current['DB'],$r_current);
203       if(!$db_current){
204         new log("debug","gofonmacro/".get_class($this),"",array(),@mysql_error($r_current));
205         mysql_close($r_current);
206         return ( msgPool::dbselect("GOfon",@mysql_error(),$cfg_Current['DB']));
207       }
208     }
209   }
212   /* Remove current macro from all asterisk server.
213    * First of all check if we have access to all databases. 
214    * - Remove old entries 
215    */ 
216   function remove_from_database($save)
217   {
218     /* Check if all databases are reachable */
219     $str = $this->check_database_accessibility();
220     if($str){
221       return($str);
222     }
224     /* Create query string */
225     $context  = addslashes("macro-".$this->cn);
227     /* Remove current macro from each server available */ 
228     if($save){
229       foreach($this->goFonHomeServers as $dn => $Server){
230         $query      = "DELETE FROM ".$Server['EXT_TABLE']." WHERE context='".$context."';";
231         $r_current  =  @mysql_pconnect($Server['SERVER'],$Server['LOGIN'],$Server['PASSWORD']);
232         $db_current =  @mysql_select_db($Server['DB'],$r_current);
233         $res = @mysql_query($query,$r_current);
234         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
235         if(!$res){
236           new log("debug","gofonmacro/".get_class($this),"",array(),@mysql_error($r_current));
237           return ( msgPool::dbquery("GOfon",@mysql_error($r_current),$Server['SERVER']));
238         }
239         @mysql_close($r_current);
240       }
241     }
242   }
244  
245   /* Add current macro to all asterisk server.
246    * First of all check if we have access to all databases. 
247    * - Remove old entries 
248    * - Add new entries 
249    */ 
250   function add_to_database($save)
251   {
252     /* Check if all databases are reachable */
253     $str = $this->check_database_accessibility();
254     if($str){
255       return($str);
256     }
258     /* Remove old entries first. Else we got duplicated entries */
259     $str = $this->remove_from_database($save);
260     if($str){
261       return($str);
262     }
264     /* Create query string */
265     $context      = "macro-".$this->cn;
267     /************
268      * Parse Macro content
269      ************/
270     $sql = 
271       "INSERT INTO %TABLENAME% ".
272       " (context,exten,priority,app,appdata) ".
273       " VALUES ";
274       
275     $a_contentLines = split("\n",$this->goFonMacroContent);
276     foreach($a_contentLines as $i_linenum => $s_linestr){
278       /* Remove the 'exten => ' string in front of the macro content line 
279        *  example line  'exten => s,2,GotoIf(${ARG3}?3:5)'
280        * Remove comments introduced by ;
281        * Skip empty lines 
282        */ 
283       $s_linestr = trim($s_linestr);
284       $s_linestr = preg_replace("/;.*$/","",$s_linestr) ;
285       $s_linestr = preg_replace ("/^.*=\> /","",$s_linestr);
287       if(empty($s_linestr)){
288         continue;
289       }
291       /* A line that passes the check above should look like this 
292        *  s,1,SetLanguage(de)
293        * 3 parts seperated by , 
294        * If there are more or less parts, abort.
295        * The preg_replace exclude parameters from split .. 
296        */
297       $tmp  = split(",", $s_linestr,3);
299       /* Multiple () are not supproted currently ... */  
300       if(substr_count($s_linestr,"(") >1 ){
301         return(sprintf(_("Not supported multiple brace in line %s!"),$i_linenum));
302       }
303       if(substr_count($s_linestr,")") >1 ){
304         return(sprintf(_("Not supported multiple brace in line %s!"),$i_linenum));
305       }
306       /* Check if there is an application given */
307       if(empty($tmp[1])){
308         return(sprintf(_("Application missing in line %s!"),$i_linenum));
309       } 
310       /* Check if there is an extension given */
311       if(empty($tmp[0])){
312         return(sprintf(_("Extension missing in line %s!"),$i_linenum));
313       } 
315       /* Create extension entry for current line 
316        *  and add this line to an array that will be inserted 
317        *  to each database.
318        */
319       $exten  = addslashes($tmp[0]);
320       $prio   = addslashes($tmp[1]);
321       $app    = addslashes(preg_replace("/\(.*\).*$/","",$tmp[2]));
322       $para   = addslashes(preg_replace("/^.*\(/","",$tmp[2]));
323       $para   = preg_replace("/\).*$/","",$para);
324       $sql.= " ('".$context."','".$exten."','".$prio."','".$app."','".$para."'),";
325     }
326     
327     /* Remove last , from query string */
328     $sql = preg_replace("/,$/","",$sql);
330     /* Save current changes to the database */
331     if($save){
332     
333       /* Macro are spread to each asterisk server */
334       foreach($this->goFonHomeServers as $dn => $cfg){
335         $r_con  = @mysql_pconnect($cfg['SERVER'],$cfg['LOGIN'],$cfg['PASSWORD']); 
336         $db     = @mysql_select_db($cfg['DB'],$r_con);
337         $query  = preg_replace("/%TABLENAME%/",$cfg['EXT_TABLE'],$sql);
338         $res    = @mysql_query($query,$r_con);
339         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
340         if(!$res){
341           new log("debug","gofonmacro/".get_class($this),"",array(),@mysql_error($r_con));
342         }
343         @mysql_close($r_con);
344       }
345     }
346   }
349   function save_object()
350   {
351     if (isset($_POST['gofonMacroGenericPosted'])){
353       $old_cn       = $this->cn;
354       $old_visible  = $this->goFonMacroVisible;
356       /* Create a base backup and reset the
357          base directly after calling plugin::save_object();
358          Base will be set seperatly a few lines below */
359       $base_tmp = $this->base;
360       plugin::save_object();
361       $this->base = $base_tmp;
363       /* Save base, since this is no LDAP attribute */
364       $tmp = $this->get_allowed_bases();
365       if(isset($_POST['base'])){
366         if(isset($tmp[$_POST['base']])){
367           $this->base= $_POST['base'];
368         }
369       }
371       /* Restore old cn if we have insuficient acls to change cn ... */
372       if(!$this->acl_is_writeable("cn",$this->initially_was_account)){
373         $this->cn = $old_cn;
374       }
376       /* check if we are allowed to toggle visibility */
377       if($this->acl_is_writeable("goFonMacroVisible")) {
379         /* Checkbox selected ? */
380         if(isset($_POST['goFonMacroVisible'])) {
381           $this->goFonMacroVisible= 1 ;
382         }else  {
383           if(isset($_POST['displayName'])){
384             $this->goFonMacroVisible= 0 ;
385           }
386         }
387       }else{
388         $this->goFonMacroVisible = $old_visible;
389       }
390     }
391   }
394   /*! Check values */
395   function check()
396   {
397     /* Call common method to give check the hook */
398     $message= plugin::check();
400     if(!count($this->goFonHomeServers)){
401       $message[] = msgPool::noserver(_("GOfon"));
402     }
404     /* Check if insert/replace is possible and all servers are available */
405     $str = $this->add_to_database(false);
406     if($str){
407       $message[] = $str;
408     }
410     /* Check if cn is already used  */
411     if(($this->dn=="new")||($this->orig_cn!=$this->cn)){
412       $ldap = $this->config->get_ldap_link();
413       $ldap->search("(&(objectClass=goFonMacro)(cn=".$this->cn."))",array("cn"));
414       if($ldap->count()>0){
415         $message[]= msgPool::duplicated(_("Name"));
416       }
417     }
418   
419     /* Check if display name is set */
420     if(empty($this->displayName)){
421       $message[] = msgPool::required(_("Name"));
422     }  
423     /* CN is restricted to 20 chars */
424     if(strlen("Makro-".$this->cn)>20 ){
425       $message[]=_("Name can be 20 characters at maximum!");
426     }
427   
428     /* If this macro is still in use we should not change the visible for user flag to invisible */
429     if(!$this->goFonMacroVisible){
430       $ldap = $this->config->get_ldap_link();
431       $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
432       while ($val = $ldap->fetch()){
433         if(strstr($val['goFonMacro'][0],$this->dn)){
434           $message[] = _("Macro is still in use!");
435           return($message);
436         }
437       }
438     }
440     if(empty($this->goFonMacroContent)){
441       $message[] = _("Macro is empty!");
442     }
444     /* Check if we are allowed to create or move this object
445      */
446     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
447       $message[] = msgPool::permCreate();
448     }elseif($this->orig_dn != "new" && $this->base != $this->orig_base && !$this->acl_is_moveable($this->base)){
449       $message[] = msgPool::permMove();
450     }
452     return $message;
453   }
456   /*! Remove makro from all given databases 
457    *   and ldap too.
458    */
459   function remove_from_parent()
460   {
461     $ldap= $this->config->get_ldap_link();
463     /* Skip remove if this macro is still in use */
464     $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro", "cn"));
465     while ($val = $ldap->fetch()){ 
466       if(strstr($val['goFonMacro'][0],$this->dn)){ 
467         msg_dialog::display(_("Error"), sprintf(_("Cannot delete entry because it is still in use by '%s'!"), $val['cn'][0]), ERROR_DIALOG);
468         return false;
469       }
470     }
472     /* Try to remove from database */
473     if(count($this->goFonHomeServers)){
474       $str = $this->remove_from_database(true);
475       if($str){ 
476         msg_dialog::display(_("Error"), $str, ERROR_DIALOG);
477         return false;
478       }
479     }else{
480       msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
481       return false;
482     }
484     /* Remove phone macro */ 
485     $ldap->rmDir($this->dn);
486     new log("remove","gofonmacro/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error()); 
487     if (!$ldap->success()){
488       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
489     }
491     /* Delete references to object groups */
492     $ldap->cd ($this->config->current['BASE']);
493     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
494     while ($ldap->fetch()){
495       $og= new ogroup($this->config, $ldap->getDN());
496       unset($og->member[$this->dn]);
497       $og->save ();
498       if (!$ldap->success()){
499         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
500       }
501     }
502   }
505   /*! Save to LDAP */
506   function save()
507   {
508     plugin::save();
509     unset($this->attrs['base']);
511     /* Try to add entries to databases */
512     $str = $this->add_to_database(true);
513     if($str){
514       msg_dialog::display(_("Error"), $str, ERROR_DIALOG);
515     }else{
516       /* Write back to ldap */
517       $ldap= $this->config->get_ldap_link();
518       $ldap->cat($this->dn, array('dn'));
519       $a= $ldap->fetch();
521       if (count($a)){
522         $ldap->cd($this->dn);
523         $this->cleanup();
524         $ldap->modify ($this->attrs); 
526         $this->handle_post_events("modify");
527       } else {
528         $ldap->cd($this->config->current['BASE']);
529         $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
530         $ldap->cd($this->dn);
531         $ldap->add($this->attrs);
532         $this->handle_post_events("add");
533       }
534       if (!$ldap->success()){
535         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
536       }
538       /* Log last action */
539       if($this->initially_was_account){
540         new log("modify","gofonmacro/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
541       }else{
542         new log("create","gofonmacro/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
543       }
544     }
545   }
548   function getCopyDialog()
549   {
550     $smarty = get_smarty();
551     $smarty->assign("cn" ,$this->cn);
552     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE));
553     $ret = array();
554     $ret['string'] = $str;
555     $ret['status'] = "";
556     return($ret);
557   }
560   function saveCopyDialog()
561   {
562     if(isset($_POST['cn'])){
563       $this->cn = $_POST['cn'];
564     }
565   }
568   static function plInfo()
569   {
570     return (array(
571           "plShortName"   => _("Generic"),
572           "plDescription" => _("Asterisk macro management"),
573           "plSelfModify"  => FALSE,
574           "plDepends"     => array(),
575           "plPriority"    => 0,
576           "plSection"     => array("administration"),
577           "plCategory"    => array("gofonmacro" => array("description" => _("GOfon macro"),
578               "objectClass" => "gofonMacro")),
580           "plProvidedAcls" => array(
581             "cn"                            => _("Macro name"),
582             "base"                          => _("Base"),
583             "description"                   => _("Description"),
584             "displayName"                   => _("Display name"),
585             "goFonMacroContent"             => _("Macro content and parameter"),
586             "goFonMacroVisible"             => _("Visibility flag"))
587           ));
588   }
591 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
592 ?>