Code

fixed macro plugin image.
[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("phoneMacroRDN"))."/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       /* Check if there is an application given */
299       if(empty($tmp[1])){
300         return(sprintf(_("Application missing in line %s!"),$i_linenum));
301       } 
302       /* Check if there is an extension given */
303       if(empty($tmp[0])){
304         return(sprintf(_("Extension missing in line %s!"),$i_linenum));
305       } 
307       /* Create extension entry for current line 
308        *  and add this line to an array that will be inserted 
309        *  to each database.
310        */
311       $exten  = addslashes($tmp[0]);
312       $prio   = addslashes($tmp[1]);
313       $app    = addslashes(preg_replace("/\(.*\).*$/","",$tmp[2]));
314       $para   = addslashes(preg_replace("/^[^(]*\((.*)\)[^)]*$/", "$1", $tmp[2]));
315       $sql.= " ('".$context."','".$exten."','".$prio."','".$app."','".$para."'),";
316     }
317     
318     /* Remove last , from query string */
319     $sql = preg_replace("/,$/","",$sql);
321     /* Save current changes to the database */
322     if($save){
323     
324       /* Macro are spread to each asterisk server */
325       foreach($this->goFonHomeServers as $dn => $cfg){
326         $r_con  = @mysql_pconnect($cfg['SERVER'],$cfg['LOGIN'],$cfg['PASSWORD']); 
327         $db     = @mysql_select_db($cfg['DB'],$r_con);
328         $query  = preg_replace("/%TABLENAME%/",$cfg['EXT_TABLE'],$sql);
329         $res    = @mysql_query($query,$r_con);
330         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
331         if(!$res){
332           new log("debug","gofonmacro/".get_class($this),"",array(),@mysql_error($r_con));
333         }
334         @mysql_close($r_con);
335       }
336     }
337   }
340   function save_object()
341   {
342     if (isset($_POST['gofonMacroGenericPosted'])){
344       $old_cn       = $this->cn;
345       $old_visible  = $this->goFonMacroVisible;
347       /* Create a base backup and reset the
348          base directly after calling plugin::save_object();
349          Base will be set seperatly a few lines below */
350       $base_tmp = $this->base;
351       plugin::save_object();
352       $this->base = $base_tmp;
354       /* Save base, since this is no LDAP attribute */
355       $tmp = $this->get_allowed_bases();
356       if(isset($_POST['base'])){
357         if(isset($tmp[$_POST['base']])){
358           $this->base= $_POST['base'];
359         }
360       }
362       /* Restore old cn if we have insuficient acls to change cn ... */
363       if(!$this->acl_is_writeable("cn",$this->initially_was_account)){
364         $this->cn = $old_cn;
365       }
367       /* check if we are allowed to toggle visibility */
368       if($this->acl_is_writeable("goFonMacroVisible")) {
370         /* Checkbox selected ? */
371         if(isset($_POST['goFonMacroVisible'])) {
372           $this->goFonMacroVisible= 1 ;
373         }else  {
374           if(isset($_POST['displayName'])){
375             $this->goFonMacroVisible= 0 ;
376           }
377         }
378       }else{
379         $this->goFonMacroVisible = $old_visible;
380       }
381     }
382   }
385   /*! Check values */
386   function check()
387   {
388     /* Call common method to give check the hook */
389     $message= plugin::check();
391     if(!count($this->goFonHomeServers)){
392       $message[] = msgPool::noserver(_("GOfon"));
393     }
395     /* Check if insert/replace is possible and all servers are available */
396     $str = $this->add_to_database(false);
397     if($str){
398       $message[] = $str;
399     }
401     /* Check if cn is already used  */
402     if(($this->dn=="new")||($this->orig_cn!=$this->cn)){
403       $ldap = $this->config->get_ldap_link();
404       $ldap->search("(&(objectClass=goFonMacro)(cn=".$this->cn."))",array("cn"));
405       if($ldap->count()>0){
406         $message[]= msgPool::duplicated(_("Name"));
407       }
408     }
409   
410     /* Check if display name is set */
411     if($this->displayName == ""){
412       $message[] = msgPool::required(_("Name"));
413     }  
414     /* CN is restricted to 20 chars */
415     if(strlen("Makro-".$this->cn)>20 ){
416       $message[]=_("Name can be 20 characters at maximum!");
417     }
418   
419     /* If this macro is still in use we should not change the visible for user flag to invisible */
420     if(!$this->goFonMacroVisible){
421       $ldap = $this->config->get_ldap_link();
422       $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
423       while ($val = $ldap->fetch()){
424         if(strstr($val['goFonMacro'][0],$this->dn)){
425           $message[] = _("Macro is still in use!");
426           return($message);
427         }
428       }
429     }
431     if(empty($this->goFonMacroContent)){
432       $message[] = _("Macro is empty!");
433     }
435     /* Check if we are allowed to create or move this object
436      */
437     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
438       $message[] = msgPool::permCreate();
439     }elseif($this->orig_dn != "new" && $this->base != $this->orig_base && !$this->acl_is_moveable($this->base)){
440       $message[] = msgPool::permMove();
441     }
443     return $message;
444   }
447   /*! Remove makro from all given databases 
448    *   and ldap too.
449    */
450   function remove_from_parent()
451   {
452     $ldap= $this->config->get_ldap_link();
454     /* Skip remove if this macro is still in use */
455     $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro", "cn"));
456     while ($val = $ldap->fetch()){ 
457       if(strstr($val['goFonMacro'][0],$this->dn)){ 
458         msg_dialog::display(_("Error"), sprintf(_("Cannot delete entry because it is still in use by '%s'!"), $val['cn'][0]), ERROR_DIALOG);
459         return false;
460       }
461     }
463     /* Try to remove from database */
464     if(count($this->goFonHomeServers)){
465       $str = $this->remove_from_database(true);
466       if($str){ 
467         msg_dialog::display(_("Error"), $str, ERROR_DIALOG);
468         return false;
469       }
470     }else{
471       msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
472       return false;
473     }
475     /* Remove phone macro */ 
476     $ldap->rmDir($this->dn);
477     new log("remove","gofonmacro/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error()); 
478     if (!$ldap->success()){
479       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
480     }
482     /* Delete references to object groups */
483     $ldap->cd ($this->config->current['BASE']);
484     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
485     while ($ldap->fetch()){
486       $og= new ogroup($this->config, $ldap->getDN());
487       unset($og->member[$this->dn]);
488       $og->save ();
489       if (!$ldap->success()){
490         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
491       }
492     }
493   }
496   /*! Save to LDAP */
497   function save()
498   {
499     plugin::save();
500     unset($this->attrs['base']);
502     /* Try to add entries to databases */
503     $str = $this->add_to_database(true);
504     if($str){
505       msg_dialog::display(_("Error"), $str, ERROR_DIALOG);
506     }else{
507       /* Write back to ldap */
508       $ldap= $this->config->get_ldap_link();
509       $ldap->cat($this->dn, array('dn'));
510       $a= $ldap->fetch();
512       if (count($a)){
513         $ldap->cd($this->dn);
514         $this->cleanup();
515         $ldap->modify ($this->attrs); 
517         $this->handle_post_events("modify");
518       } else {
519         $ldap->cd($this->config->current['BASE']);
520         $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
521         $ldap->cd($this->dn);
522         $ldap->add($this->attrs);
523         $this->handle_post_events("add");
524       }
525       if (!$ldap->success()){
526         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
527       }
529       /* Log last action */
530       if($this->initially_was_account){
531         new log("modify","gofonmacro/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
532       }else{
533         new log("create","gofonmacro/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
534       }
535     }
536   }
539   function getCopyDialog()
540   {
541     $smarty = get_smarty();
542     $smarty->assign("cn" ,$this->cn);
543     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE));
544     $ret = array();
545     $ret['string'] = $str;
546     $ret['status'] = "";
547     return($ret);
548   }
551   function saveCopyDialog()
552   {
553     if(isset($_POST['cn'])){
554       $this->cn = $_POST['cn'];
555     }
556   }
559   static function plInfo()
560   {
561     return (array(
562           "plShortName"   => _("Generic"),
563           "plDescription" => _("Asterisk macro management"),
564           "plSelfModify"  => FALSE,
565           "plDepends"     => array(),
566           "plPriority"    => 0,
567           "plSection"     => array("administration"),
568           "plCategory"    => array("gofonmacro" => array("description" => _("GOfon macro"),
569               "objectClass" => "gofonMacro")),
571           "plProvidedAcls" => array(
572             "cn"                            => _("Macro name"),
573             "base"                          => _("Base"),
574             "description"                   => _("Description"),
575             "displayName"                   => _("Display name"),
576             "goFonMacroContent"             => _("Macro content and parameter"),
577             "goFonMacroVisible"             => _("Visibility flag"))
578           ));
579   }
582 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
583 ?>