Code

Shrinked down aclRole class to half size.
[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           gosa_log($query);
344           return(sprintf(_("Insert of new macro failed for server '%s'."),$cfg['SERVER']));
345         }
346         @mysql_close($r_con);
347       }
348     }
349   }
352   function save_object()
353   {
354     if (isset($_POST['gofonMacroGenericPosted'])){
356       $old_cn       = $this->cn;
357       $old_visible  = $this->goFonMacroVisible;
359       /* Create a base backup and reset the
360          base directly after calling plugin::save_object();
361          Base will be set seperatly a few lines below */
362       $base_tmp = $this->base;
363       plugin::save_object();
364       $this->base = $base_tmp;
366       /* Save base, since this is no LDAP attribute */
367       $tmp = $this->get_allowed_bases();
368       if(isset($_POST['base'])){
369         if(isset($tmp[$_POST['base']])){
370           $this->base= $_POST['base'];
371         }
372       }
374       /* Restore old cn if we have insuficient acls to change cn ... */
375       if(!$this->acl_is_writeable("cn",$this->initially_was_account)){
376         $this->cn = $old_cn;
377       }
379       /* check if we are allowed to toggle visibility */
380       if($this->acl_is_writeable("goFonMacroVisible")) {
382         /* Checkbox selected ? */
383         if(isset($_POST['goFonMacroVisible'])) {
384           $this->goFonMacroVisible= 1 ;
385         }else  {
386           if(isset($_POST['displayName'])){
387             $this->goFonMacroVisible= 0 ;
388           }
389         }
390       }else{
391         $this->goFonMacroVisible = $old_visible;
392       }
393     }
394   }
397   /*! Check values */
398   function check()
399   {
400     /* Call common method to give check the hook */
401     $message= plugin::check();
403     if(!count($this->goFonHomeServers)){
404       $message[] = _("There must be at least one server with an asterisk database to save this phone macro.");
405     }
407     /* Check if insert/replace is possible and all servers are available */
408     $str = $this->add_to_database(false);
409     if($str){
410       $message[] = $str;
411     }
413     /* Check if cn is already used  */
414     if(($this->dn=="new")||($this->orig_cn!=$this->cn)){
415       $ldap = $this->config->get_ldap_link();
416       $ldap->search("(&(objectClass=goFonMacro)(cn=".$this->cn."))",array("cn"));
417       if($ldap->count()>0){
418         $message[]=sprintf(_("The given cn '%s' already exists."),$this->cn);
419       }
420     }
421   
422     /* Check if display name is set */
423     if(empty($this->displayName)){
424       $message[] = _("You must specify the 'Display Name' in order to save this macro");
425     }  
426     /* CN is restricted to 20 chars */
427     if(strlen("Makro-".$this->cn)>20 ){
428       $message[]=_("The given cn is too long, to create a Makro entry, maximum 20 chars.");
429     }
430   
431     /* If this macro is still in use we should not change the visible for user flag to invisible */
432     if(!$this->goFonMacroVisible){
433       $ldap = $this->config->get_ldap_link();
434       $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
435       while ($val = $ldap->fetch()){
436         if(strstr($val['goFonMacro'][0],$this->dn)){
437           $message[] = _("This macro is still in use. It is necessary to mark this macro as visible for users.");
438           return($message);
439         }
440       }
441     }
443     /* Macro content must be smaller than 100 lines */
444     if(count(split("\n",$this->goFonMacroContent))>100){
445       $message[] = _("Makro length must be lower than 100 lines");
446     }
448     /* Macro content must be smaller than 100 lines */
449     if(empty($this->goFonMacroContent)){
450       $message[] = _("You can't save an empty macro.");
451     }
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"));
465     while ($val = $ldap->fetch()){ 
466       if(strstr($val['goFonMacro'][0],$this->dn)){ 
467         print_red(_("This macro is still in use. To delete this Macro ensure that nobody has selected it."));
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         print_red($str);
477         return false;
478       }
479     }else{
480       print_red(_("Could not remove the macro entry from asterisk databases. Please check your asterisk database configurations."));
481       return false;
482     }
484     /* Remove phone macro */ 
485     $ldap->rmDir($this->dn); 
486     show_ldap_error($ldap->get_error(), sprintf(_("Removing of goFonMacro/generic account with dn '%s' failed."),$this->dn));
488     /* Delete references to object groups */
489     $ldap->cd ($this->config->current['BASE']);
490     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
491     while ($ldap->fetch()){
492       $og= new ogroup($this->config, $ldap->getDN());
493       unset($og->member[$this->dn]);
494       $og->save ();
495       show_ldap_error($ldap->get_error(), sprintf(_("Removing of goFonMacro/generic account with dn '%s' failed."),$this->dn));
496     }
497   }
500   /*! Save to LDAP */
501   function save()
502   {
503     plugin::save();
504     unset($this->attrs['base']);
506     /* Try to add entries to databases */
507     $str = $this->add_to_database(true);
508     if($str){
509       print_red($str);
510     }else{
511       /* Write back to ldap */
512       $ldap= $this->config->get_ldap_link();
513       $ldap->cat($this->dn, array('dn'));
514       $a= $ldap->fetch();
516       if (count($a)){
517         $ldap->cd($this->dn);
518         $this->cleanup();
519         $ldap->modify ($this->attrs); 
521         $this->handle_post_events("modify");
522       } else {
523         $ldap->cd($this->config->current['BASE']);
524         $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
525         $ldap->cd($this->dn);
526         $ldap->add($this->attrs);
527         $this->handle_post_events("add");
528       }
529       show_ldap_error($ldap->get_error(), sprintf(_("Saving of goFonMacro/generic account with dn '%s' failed."),$this->dn));
530     }
531   }
534   function plInfo()
535   {
536     return (array(
537           "plShortName"   => _("Generic"),
538           "plDescription" => _("Asterisk macro management"),
539           "plSelfModify"  => FALSE,
540           "plDepends"     => array(),
541           "plPriority"    => 0,
542           "plSection"     => array("administration"),
543           "plCategory"    => array("gofonmacro" => array("description" => _("GOfon macro"),
544               "objectClass" => "gofonMacro")),
546           "plProvidedAcls" => array(
547             "cn"                            => _("Macro name"),
548             "base"                          => _("Base"),
549             "description"                   => _("Description"),
550             "displayName"                   => _("Display name"),
551             "goFonMacroContent"             => _("Macro content and parameter"),
552             "goFonMacroVisible"             => _("Visibility flag"))
553           ));
554   }
557 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
558 ?>