Code

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