Code

Some updates
[gosa.git] / plugins / 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   /*! CLI vars */
13   var $cli_summary= "Handling of GOsa's macro object";
14   /*! CLI vars */
15   var $cli_description= "Some longer text\nfor help";
16   /*! CLI vars */
17   var $cli_parameters= array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
19   /*! Macro attributes,  */
20   var $generate_error= "";
21   
22   /*! The name of the Macro in the openldap drirectory */
23   var $cn               = ""; 
24  
25   /*! Display error once */
26   var $error_shown = false; 
28   /*! This ist the variable that contains the description of the macro*/
29   var $description      = "";
31   /*! The base of the macro, is used to save the macro in the correct directory tree */
32   var $base             = "";
34   /*! This is the name of the macro which the enduser will see, instead of the cn */
35   var $displayName      = "";
36     
37   /*! Here is the macro content, the real macroscript */
38   var $goFonMacroContent= "";
39   
40   /*! To allow user to use this macro this var must be true, else false */
41   var $goFonMacroVisible= 0;
43   /*! attribute list for save action */
44   var $attributes     = array("cn","base", "description","displayName","goFonMacroContent","goFonMacroVisible");
46   var $orig_cn = ""; 
47   /*! Objectclasses that this calls handles */
48   var $objectclasses  = array("top", "goFonMacro");
50   var $goFonHomeServers = array(); // Contains all available asterisk database server 
52   //! The Konstructor   
53   /*!  Konstructor, load class with  attributes of the given dn*/
54   function macro ($config, $dn= NULL, $parent= NULL)
55   {
56     plugin::plugin ($config, $dn, $parent);
58     /* This is always an account */
59     $this->is_account= TRUE;
61     /* Edit or new one ?*/
62     if ($this->dn == "new"){
63       if(isset($_SESSION['CurrentMainBase'])){
64         $this->base = $_SESSION['CurrentMainBase'];
65       }else{
66         $ui= get_userinfo();
67         $this->base= dn2base($ui->dn);
68       }
69     } else {
70       $this->orig_cn=$this->cn;
71       $this->base= preg_replace ("/^[^,]+,[^,]+,[^,]+,[^,]+,[^,]+,/", "", $this->dn);
72     }
74     /* Check server configurations
75      * Load all server configuration in $this->goFonHomeServers if available
76      */
77     $a_SETUP= array();
78     if(array_key_exists('config',$_SESSION) &&
79        array_key_exists('SERVERS',$_SESSION['config']->data) &&
80        count($_SESSION['config']->data['SERVERS']['FON']) && 
81        array_key_exists('FON',$_SESSION['config']->data['SERVERS'])) {
83       /* Set available server */
84       $this->goFonHomeServers = $_SESSION['config']->data['SERVERS']['FON'];
85   
86       /* Remove default entry, not necessary here */
87       if(isset($this->goFonHomeServers[0])){
88         unset($this->goFonHomeServers[0]);  
89       }
90     }
91   }
94   /*!  Execute this plugin */
95   function execute()
96   {
97     /* Call parent execute */
98     plugin::execute();
100     /* Variables */
101     $vars       = "";
102     $tmp        = array();
103     $number = 0; 
105     /* Base select dialog */
106     $once = true;
107     foreach($_POST as $name => $value){
108       if(preg_match("/^chooseBase/",$name) && $once){
109         $once = false;
110         $this->dialog = new baseSelectDialog($this->config,$this,$this->allowedBasesToMoveTo());
111         $this->dialog->setCurrentBase($this->base);
112       }
113     }
115     /* Dialog handling */
116     if(is_object($this->dialog)){
117       /* Must be called before save_object */
118       $this->dialog->save_object();
120       if($this->dialog->isClosed()){
121         $this->dialog = false;
122       }elseif($this->dialog->isSelected()){
124         /* A new base was selected, check if it is a valid one */
125         $tmp = $this->get_allowed_bases();
126         if(isset($tmp[$this->dialog->isSelected()])){
127           $this->base = $this->dialog->isSelected();
128         }
130         $this->dialog= false;
131       }else{
132         return($this->dialog->execute());
133       }
134     }
136     /* Fill templating stuff */
137     $smarty= get_smarty();
138     $smarty->assign("bases", $this->get_allowed_bases());
140     $tmp = $this->plInfo();
141     foreach($tmp['plProvidedAcls'] as $name => $translation){
142       $smarty->assign($name."ACL",$this->getacl($name));
143     }
145     if($this->acl_is_writeable("base")){
146       $smarty->assign("baseSelect",true);
147     }else{
148       $smarty->assign("baseSelect",false);
149     }
152     /* Assign all vars to Smarty */
153     foreach($this->attributes as $ar){
154       $smarty->assign($ar, $this->$ar);
155     }
156     /* Checkboxes */
157     $smarty->assign("base_select", $this->base);
158     $smarty->assign("vars", $vars);
160     if($this->goFonMacroVisible){
161       $smarty->assign("goFonMacroVisibleChecked"," checked ");
162     }else{
163       $smarty->assign("goFonMacroVisibleChecked","");
164     }
166     $smarty->assign("cnACL",$this->getacl("cn",$this->initially_was_account));
167     $smarty->assign("cn",$this->cn);
169     /* Ensure that macro content is displayed correctly encoded */
170     $smarty->assign("goFonMacroContent",htmlentities(utf8_decode ($this->goFonMacroContent)));
172     /* Show main page */
173     return($smarty->fetch (get_template_path('generic.tpl', TRUE)));
174   }
177   /* This method check if all databases are reachable.  
178    *  Returns with error message or an empty string on success.
179    * 
180    * - Is mysql extension available  
181    * - Is every server reachable 
182    * - Does the database exists/is accessible
183    */
184   function check_database_accessibility()
185   {
186     /* Check if mysql extension is available */
187     if(!is_callable("mysql_pconnect")){
188       return(_("Can't save any changes to asterisk database, there is currently no mysql extension available in your php setup."));
189     }
191     /********************
192      * Check all home server
193      ********************/
194     foreach($this->goFonHomeServers as $goFonHomeServer => $cfg_Current){
195       $r_current    =  @mysql_pconnect($cfg_Current['SERVER'],$cfg_Current['LOGIN'],$cfg_Current['PASSWORD']);
196       if(!$r_current){
197         gosa_log(@mysql_error($r_current));
198         return(sprintf(_("The MySQL home server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
199               $cfg_Current['SERVER'],$cfg_Current['LOGIN']));
200       }
201       $db_current  =  @mysql_select_db($cfg_Current['DB'],$r_current);
202       if(!$db_current){
203         gosa_log(@mysql_error($r_current));
204         mysql_close($r_current);
205         return( sprintf(_("Can't select database '%s' on home server '%s'."),$cfg_Current['DB'],$cfg_Current['SERVER']));
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         if(!$res){
234           gosa_log(@mysql_error($r_current));
235           return(sprintf(_("Removing macro from '%s' failed. Check GOsa log for mysql error."),$Server['SERVER']));
236         }
237         @mysql_close($r_current);
238       }
239     }
240   }
242  
243   /* Add current macro to all asterisk server.
244    * First of all check if we have access to all databases. 
245    * - Remove old entries 
246    * - Add new entries 
247    */ 
248   function add_to_database($save)
249   {
250     /* Check if all databases are reachable */
251     $str = $this->check_database_accessibility();
252     if($str){
253       return($str);
254     }
256     /* Remove old entries first. Else we got duplicated entries */
257     $str = $this->remove_from_database($save);
258     if($str){
259       return($str);
260     }
262     /* Create query string */
263     $context      = "macro-".$this->cn;
265     /************
266      * Parse Macro content
267      ************/
268     $sql = 
269       "INSERT INTO %TABLENAME% ".
270       " (context,exten,priority,app,appdata) ".
271       " VALUES ";
272       
273     $a_contentLines = split("\n",$this->goFonMacroContent);
274     foreach($a_contentLines as $i_linenum => $s_linestr){
276       /* Remove the 'exten => ' string in front of the macro content line 
277        *  example line  'exten => s,2,GotoIf(${ARG3}?3:5)'
278        * Remove comments introduced by ;
279        * Skip empty lines 
280        */ 
281       $s_linestr = trim($s_linestr);
282       $s_linestr = preg_replace("/;.*$/","",$s_linestr) ;
283       $s_linestr = preg_replace ("/^.*=\> /","",$s_linestr);
285       if(empty($s_linestr)){
286         continue;
287       }
289       /* A line that passes the check above should look like this 
290        *  s,1,SetLanguage(de)
291        * 3 parts seperated by , 
292        * If there are more or less parts, abort.
293        * The preg_replace exclude parameters from split .. 
294        */
295       $tmp  = split(",", $s_linestr,3);
297       /* Check if there are exactly 2 , */ 
298 #      if(substr_count($s_linestr,",") !=2){
299 #        return(sprintf(_("More than two ',' given in line : '%s'. Remember that parameters are seperated by '|'."),$i_linenum));
300 #      }
301       /* Multiple () are not supproted currently ... */  
302       if(substr_count($s_linestr,"(") >1 ){
303         return(sprintf(_("More than one '(' is currently not supported. Line : '%s'."),$i_linenum));
304       }
305       if(substr_count($s_linestr,")") >1 ){
306         return(sprintf(_("More than one ')' is currently not supported. Line : '%s'."),$i_linenum));
307       }
308       /* Check if there is an application given */
309       if(empty($tmp[1])){
310         return(sprintf(_("There is no application given in line : '%s'."),$i_linenum));
311       } 
312       /* Check if there is an extension given */
313       if(empty($tmp[0])){
314         return(sprintf(_("There is no extension type given in line : '%s'."),$i_linenum));
315       } 
317       /* Create extension entry for current line 
318        *  and add this line to an array that will be inserted 
319        *  to each database.
320        */
321       $exten  = addslashes($tmp[0]);
322       $prio   = addslashes($tmp[1]);
323       $app    = addslashes(preg_replace("/\(.*\).*$/","",$tmp[2]));
324       $para   = addslashes(preg_replace("/^.*\(/","",$tmp[2]));
325       $para   = preg_replace("/\).*$/","",$para);
326       $sql.= " ('".$context."','".$exten."','".$prio."','".$app."','".$para."'),";
327     }
328     
329     /* Remove last , from query string */
330     $sql = preg_replace("/,$/","",$sql);
332     /* Save current changes to the database */
333     if($save){
334     
335       /* Macro are spread to each asterisk server */
336       foreach($this->goFonHomeServers as $dn => $cfg){
337         $r_con  = @mysql_pconnect($cfg['SERVER'],$cfg['LOGIN'],$cfg['PASSWORD']); 
338         $db     = @mysql_select_db($cfg['DB'],$r_con);
339         $query  = preg_replace("/%TABLENAME%/",$cfg['EXT_TABLE'],$sql);
340         $res    = @mysql_query($query,$r_con);
341         if(!$res){
342           gosa_log(@mysql_error($r_con));
343           return(sprintf(_("Insert of new macro failed for server '%s'."),$cfg['SERVER']));
344         }
345         @mysql_close($r_con);
346       }
347     }
348   }
351   function save_object()
352   {
353     if (isset($_POST['gofonMacroGenericPosted'])){
355       $old_cn       = $this->cn;
356       $old_visible  = $this->goFonMacroVisible;
358       /* Create a base backup and reset the
359          base directly after calling plugin::save_object();
360          Base will be set seperatly a few lines below */
361       $base_tmp = $this->base;
362       plugin::save_object();
363       $this->base = $base_tmp;
365       /* Save base, since this is no LDAP attribute */
366       $tmp = $this->get_allowed_bases();
367       if(isset($_POST['base'])){
368         if(isset($tmp[$_POST['base']])){
369           $this->base= $_POST['base'];
370         }
371       }
373       /* Restore old cn if we have insuficient acls to change cn ... */
374       if(!$this->acl_is_writeable("cn",$this->initially_was_account)){
375         $this->cn = $old_cn;
376       }
378       /* check if we are allowed to toggle visibility */
379       if($this->acl_is_writeable("goFonMacroVisible")) {
381         /* Checkbox selected ? */
382         if(isset($_POST['goFonMacroVisible'])) {
383           $this->goFonMacroVisible= 1 ;
384         }else  {
385           if(isset($_POST['displayName'])){
386             $this->goFonMacroVisible= 0 ;
387           }
388         }
389       }else{
390         $this->goFonMacroVisible = $old_visible;
391       }
392     }
393   }
396   /*! Check values */
397   function check()
398   {
399     /* Call common method to give check the hook */
400     $message= plugin::check();
402     if(!count($this->goFonHomeServers)){
403       $message[] = _("There must be at least one server with an asterisk database to save this phone macro.");
404     }
406     /* Check if insert/replace is possible and all servers are available */
407     $str = $this->add_to_database(false);
408     if($str){
409       $message[] = $str;
410     }
412     /* Check if cn is already used  */
413     if(($this->dn=="new")||($this->orig_cn!=$this->cn)){
414       $ldap = $this->config->get_ldap_link();
415       $ldap->search("(&(objectClass=goFonMacro)(cn=".$this->cn."))",array("cn"));
416       if($ldap->count()>0){
417         $message[]=sprintf(_("The given cn '%s' already exists."),$this->cn);
418       }
419     }
420   
421     /* Check if display name is set */
422     if(empty($this->displayName)){
423       $message[] = _("You must specify the 'Display Name' in order to save this macro");
424     }  
425     /* CN is restricted to 20 chars */
426     if(strlen("Makro-".$this->cn)>20 ){
427       $message[]=_("The given cn is too long, to create a Makro entry, maximum 20 chars.");
428     }
429   
430     /* If this macro is still in use we should not change the visible for user flag to invisible */
431     if(!$this->goFonMacroVisible){
432       $ldap = $this->config->get_ldap_link();
433       $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
434       while ($val = $ldap->fetch()){
435         if(strstr($val['goFonMacro'][0],$this->dn)){
436           $message[] = _("This macro is still in use. It is necessary to mark this macro as visible for users.");
437           return($message);
438         }
439       }
440     }
442     /* Macro content must be smaller than 100 lines */
443     if(count(split("\n",$this->goFonMacroContent))>100){
444       $message[] = _("Makro length must be lower than 100 lines");
445     }
447     return $message;
448   }
451   /*! Remove makro from all given databases 
452    *   and ldap too.
453    */
454   function remove_from_parent()
455   {
456     $ldap= $this->config->get_ldap_link();
458     /* Skip remove if this macro is still in use */
459     $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
460     while ($val = $ldap->fetch()){ 
461       if(strstr($val['goFonMacro'][0],$this->dn)){ 
462         print_red(_("This macro is still in use. To delete this Macro ensure that nobody has selected it."));
463         return false;
464       }
465     }
467     /* Try to remove from database */
468     if(count($this->goFonHomeServers)){
469       $str = $this->remove_from_database(true);
470       if($str){ 
471         print_red($str);
472         return false;
473       }
474     }else{
475       print_red(_("Could not remove the macro entry from asterisk databases. Please check your asterisk database configurations."));
476       return false;
477     }
479     /* Remove phone macro */ 
480     $ldap->rmDir($this->dn); 
481     show_ldap_error($ldap->get_error(), sprintf(_("Removing of goFonMacro/generic account with dn '%s' failed."),$this->dn));
483     /* Delete references to object groups */
484     $ldap->cd ($this->config->current['BASE']);
485     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
486     while ($ldap->fetch()){
487       $og= new ogroup($this->config, $ldap->getDN());
488       unset($og->member[$this->dn]);
489       $og->save ();
490       show_ldap_error($ldap->get_error(), sprintf(_("Removing of goFonMacro/generic account with dn '%s' failed."),$this->dn));
491     }
492   }
495   /*! Save to LDAP */
496   function save()
497   {
498     plugin::save();
499     unset($this->attrs['base']);
501     /* Try to add entries to databases */
502     $str = $this->add_to_database(true);
503     if($str){
504       print_red($str);
505     }else{
506       /* Write back to ldap */
507       $ldap= $this->config->get_ldap_link();
508       $ldap->cat($this->dn, array('dn'));
509       $a= $ldap->fetch();
511       if (count($a)){
512         $ldap->cd($this->dn);
513         $this->cleanup();
514         $ldap->modify ($this->attrs); 
516         $this->handle_post_events("modify");
517       } else {
518         $ldap->cd($this->config->current['BASE']);
519         $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
520         $ldap->cd($this->dn);
521         $ldap->add($this->attrs);
522         $this->handle_post_events("add");
523       }
524       show_ldap_error($ldap->get_error(), sprintf(_("Saving of goFonMacro/generic account with dn '%s' failed."),$this->dn));
525     }
526   }
529   function plInfo()
530   {
531     return (array(
532           "plShortName"   => _("Generic"),
533           "plDescription" => _("Asterisk macro management"),
534           "plSelfModify"  => FALSE,
535           "plDepends"     => array(),
536           "plPriority"    => 0,
537           "plSection"     => array("administration"),
538           "plCategory"    => array("gofonmacro" => array("description" => _("GOfon macro"),
539               "objectClass" => "gofonMacro")),
541           "plProvidedAcls" => array(
542             "cn"                            => _("Macro name"),
543             "base"                          => _("Base"),
544             "description"                   => _("Description"),
545             "displayName"                   => _("Display name"),
546             "goFonMacroContent"             => _("Macro content and parameter"),
547             "goFonMacroVisible"             => _("Visibility flag"))
548           ));
549   }
552 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
553 ?>