Code

Updated gofon macro
[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   /*! 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");
45   var $view_logged = FALSE;
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(session::is_set('CurrentMainBase')){
64         $this->base  = session::get('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(isset($config->data['SERVERS']['FON'])){
80       /* Set available server */
81       $this->goFonHomeServers = $config->data['SERVERS']['FON'];
82   
83       /* Remove default entry, not necessary here */
84       if(isset($this->goFonHomeServers[0])){
85         unset($this->goFonHomeServers[0]);  
86       }
87     }
88   }
91   /*!  Execute this plugin */
92   function execute()
93   {
94     /* Call parent execute */
95     plugin::execute();
97     /* Log view */
98     if($this->is_account && !$this->view_logged){
99       $this->view_logged = TRUE;
100       new log("view","gofonmacro/".get_class($this),$this->dn);
101     }
103     /* Variables */
104     $vars       = "";
105     $tmp        = array();
106     $number = 0; 
108     /* Base select dialog */
109     $once = true;
110     foreach($_POST as $name => $value){
111       if(preg_match("/^chooseBase/",$name) && $once){
112         $once = false;
113         $this->dialog = new baseSelectDialog($this->config,$this,$this->allowedBasesToMoveTo());
114         $this->dialog->setCurrentBase($this->base);
115       }
116     }
118     /* Dialog handling */
119     if(is_object($this->dialog)){
120       /* Must be called before save_object */
121       $this->dialog->save_object();
123       if($this->dialog->isClosed()){
124         $this->dialog = false;
125       }elseif($this->dialog->isSelected()){
127         /* A new base was selected, check if it is a valid one */
128         $tmp = $this->get_allowed_bases();
129         if(isset($tmp[$this->dialog->isSelected()])){
130           $this->base = $this->dialog->isSelected();
131         }
133         $this->dialog= false;
134       }else{
135         return($this->dialog->execute());
136       }
137     }
139     /* Fill templating stuff */
140     $smarty= get_smarty();
141     $smarty->assign("bases", $this->get_allowed_bases());
143     $tmp = $this->plInfo();
144     foreach($tmp['plProvidedAcls'] as $name => $translation){
145       $smarty->assign($name."ACL",$this->getacl($name));
146     }
148     if($this->acl_is_writeable("base")){
149       $smarty->assign("baseSelect",true);
150     }else{
151       $smarty->assign("baseSelect",false);
152     }
155     /* Assign all vars to Smarty */
156     foreach($this->attributes as $ar){
157       $smarty->assign($ar, $this->$ar);
158     }
159     /* Checkboxes */
160     $smarty->assign("base_select", $this->base);
161     $smarty->assign("vars", $vars);
163     if($this->goFonMacroVisible){
164       $smarty->assign("goFonMacroVisibleChecked"," checked ");
165     }else{
166       $smarty->assign("goFonMacroVisibleChecked","");
167     }
169     $smarty->assign("cnACL",$this->getacl("cn",$this->initially_was_account));
170     $smarty->assign("cn",$this->cn);
172     /* Ensure that macro content is displayed correctly encoded */
173     $smarty->assign("goFonMacroContent",htmlentities(utf8_decode ($this->goFonMacroContent)));
175     /* Show main page */
176     return($smarty->fetch (get_template_path('generic.tpl', TRUE)));
177   }
180   /* This method check if all databases are reachable.  
181    *  Returns with error message or an empty string on success.
182    * 
183    * - Is mysql extension available  
184    * - Is every server reachable 
185    * - Does the database exists/is accessible
186    */
187   function check_database_accessibility()
188   {
189     /* Check if mysql extension is available */
190     if(!is_callable("mysql_pconnect")){
191       return(_("Can't save any changes to asterisk database, there is currently no mysql extension available in your php setup."));
192     }
194     /********************
195      * Check all home server
196      ********************/
197     foreach($this->goFonHomeServers as $goFonHomeServer => $cfg_Current){
198       $r_current    =  @mysql_pconnect($cfg_Current['SERVER'],$cfg_Current['LOGIN'],$cfg_Current['PASSWORD']);
199       if(!$r_current){
200         new log("debug","gofonmacro/".get_class($this),"",array(),@mysql_error($r_current));
201         return(sprintf(_("The MySQL home server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
202               $cfg_Current['SERVER'],$cfg_Current['LOGIN']));
203       }
204       $db_current  =  @mysql_select_db($cfg_Current['DB'],$r_current);
205       if(!$db_current){
206         new log("debug","gofonmacro/".get_class($this),"",array(),@mysql_error($r_current));
207         mysql_close($r_current);
208         return( sprintf(_("Can't select database '%s' on home server '%s'."),$cfg_Current['DB'],$cfg_Current['SERVER']));
209       }
210     }
211   }
214   /* Remove current macro from all asterisk server.
215    * First of all check if we have access to all databases. 
216    * - Remove old entries 
217    */ 
218   function remove_from_database($save)
219   {
220     /* Check if all databases are reachable */
221     $str = $this->check_database_accessibility();
222     if($str){
223       return($str);
224     }
226     /* Create query string */
227     $context  = addslashes("macro-".$this->cn);
229     /* Remove current macro from each server available */ 
230     if($save){
231       foreach($this->goFonHomeServers as $dn => $Server){
232         $query      = "DELETE FROM ".$Server['EXT_TABLE']." WHERE context='".$context."';";
233         $r_current  =  @mysql_pconnect($Server['SERVER'],$Server['LOGIN'],$Server['PASSWORD']);
234         $db_current =  @mysql_select_db($Server['DB'],$r_current);
235         $res = @mysql_query($query,$r_current);
236         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
237         if(!$res){
238           new log("debug","gofonmacro/".get_class($this),"",array(),@mysql_error($r_current));
239           return(sprintf(_("Removing macro from '%s' failed. Check GOsa log for mysql error."),$Server['SERVER']));
240         }
241         @mysql_close($r_current);
242       }
243     }
244   }
246  
247   /* Add current macro to all asterisk server.
248    * First of all check if we have access to all databases. 
249    * - Remove old entries 
250    * - Add new entries 
251    */ 
252   function add_to_database($save)
253   {
254     /* Check if all databases are reachable */
255     $str = $this->check_database_accessibility();
256     if($str){
257       return($str);
258     }
260     /* Remove old entries first. Else we got duplicated entries */
261     $str = $this->remove_from_database($save);
262     if($str){
263       return($str);
264     }
266     /* Create query string */
267     $context      = "macro-".$this->cn;
269     /************
270      * Parse Macro content
271      ************/
272     $sql = 
273       "INSERT INTO %TABLENAME% ".
274       " (context,exten,priority,app,appdata) ".
275       " VALUES ";
276       
277     $a_contentLines = split("\n",$this->goFonMacroContent);
278     foreach($a_contentLines as $i_linenum => $s_linestr){
280       /* Remove the 'exten => ' string in front of the macro content line 
281        *  example line  'exten => s,2,GotoIf(${ARG3}?3:5)'
282        * Remove comments introduced by ;
283        * Skip empty lines 
284        */ 
285       $s_linestr = trim($s_linestr);
286       $s_linestr = preg_replace("/;.*$/","",$s_linestr) ;
287       $s_linestr = preg_replace ("/^.*=\> /","",$s_linestr);
289       if(empty($s_linestr)){
290         continue;
291       }
293       /* A line that passes the check above should look like this 
294        *  s,1,SetLanguage(de)
295        * 3 parts seperated by , 
296        * If there are more or less parts, abort.
297        * The preg_replace exclude parameters from split .. 
298        */
299       $tmp  = split(",", $s_linestr,3);
301       /* Check if there are exactly 2 , */ 
302 #      if(substr_count($s_linestr,",") !=2){
303 #        return(sprintf(_("More than two ',' given in line : '%s'. Remember that parameters are seperated by '|'."),$i_linenum));
304 #      }
305       /* Multiple () are not supproted currently ... */  
306       if(substr_count($s_linestr,"(") >1 ){
307         return(sprintf(_("More than one '(' is currently not supported. Line : '%s'."),$i_linenum));
308       }
309       if(substr_count($s_linestr,")") >1 ){
310         return(sprintf(_("More than one ')' is currently not supported. Line : '%s'."),$i_linenum));
311       }
312       /* Check if there is an application given */
313       if(empty($tmp[1])){
314         return(sprintf(_("There is no application given in line : '%s'."),$i_linenum));
315       } 
316       /* Check if there is an extension given */
317       if(empty($tmp[0])){
318         return(sprintf(_("There is no extension type given in line : '%s'."),$i_linenum));
319       } 
321       /* Create extension entry for current line 
322        *  and add this line to an array that will be inserted 
323        *  to each database.
324        */
325       $exten  = addslashes($tmp[0]);
326       $prio   = addslashes($tmp[1]);
327       $app    = addslashes(preg_replace("/\(.*\).*$/","",$tmp[2]));
328       $para   = addslashes(preg_replace("/^.*\(/","",$tmp[2]));
329       $para   = preg_replace("/\).*$/","",$para);
330       $sql.= " ('".$context."','".$exten."','".$prio."','".$app."','".$para."'),";
331     }
332     
333     /* Remove last , from query string */
334     $sql = preg_replace("/,$/","",$sql);
336     /* Save current changes to the database */
337     if($save){
338     
339       /* Macro are spread to each asterisk server */
340       foreach($this->goFonHomeServers as $dn => $cfg){
341         $r_con  = @mysql_pconnect($cfg['SERVER'],$cfg['LOGIN'],$cfg['PASSWORD']); 
342         $db     = @mysql_select_db($cfg['DB'],$r_con);
343         $query  = preg_replace("/%TABLENAME%/",$cfg['EXT_TABLE'],$sql);
344         $res    = @mysql_query($query,$r_con);
345         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
346         if(!$res){
347           new log("debug","gofonmacro/".get_class($this),"",array(),@mysql_error($r_con));
348           return(sprintf(_("Insert of new macro failed for server '%s'."),$cfg['SERVER']));
349         }
350         @mysql_close($r_con);
351       }
352     }
353   }
356   function save_object()
357   {
358     if (isset($_POST['gofonMacroGenericPosted'])){
360       $old_cn       = $this->cn;
361       $old_visible  = $this->goFonMacroVisible;
363       /* Create a base backup and reset the
364          base directly after calling plugin::save_object();
365          Base will be set seperatly a few lines below */
366       $base_tmp = $this->base;
367       plugin::save_object();
368       $this->base = $base_tmp;
370       /* Save base, since this is no LDAP attribute */
371       $tmp = $this->get_allowed_bases();
372       if(isset($_POST['base'])){
373         if(isset($tmp[$_POST['base']])){
374           $this->base= $_POST['base'];
375         }
376       }
378       /* Restore old cn if we have insuficient acls to change cn ... */
379       if(!$this->acl_is_writeable("cn",$this->initially_was_account)){
380         $this->cn = $old_cn;
381       }
383       /* check if we are allowed to toggle visibility */
384       if($this->acl_is_writeable("goFonMacroVisible")) {
386         /* Checkbox selected ? */
387         if(isset($_POST['goFonMacroVisible'])) {
388           $this->goFonMacroVisible= 1 ;
389         }else  {
390           if(isset($_POST['displayName'])){
391             $this->goFonMacroVisible= 0 ;
392           }
393         }
394       }else{
395         $this->goFonMacroVisible = $old_visible;
396       }
397     }
398   }
401   /*! Check values */
402   function check()
403   {
404     /* Call common method to give check the hook */
405     $message= plugin::check();
407     if(!count($this->goFonHomeServers)){
408       $message[] = _("There must be at least one server with an asterisk database to save this phone macro.");
409     }
411     /* Check if insert/replace is possible and all servers are available */
412     $str = $this->add_to_database(false);
413     if($str){
414       $message[] = $str;
415     }
417     /* Check if cn is already used  */
418     if(($this->dn=="new")||($this->orig_cn!=$this->cn)){
419       $ldap = $this->config->get_ldap_link();
420       $ldap->search("(&(objectClass=goFonMacro)(cn=".$this->cn."))",array("cn"));
421       if($ldap->count()>0){
422         $message[]=sprintf(_("The given cn '%s' already exists."),$this->cn);
423       }
424     }
425   
426     /* Check if display name is set */
427     if(empty($this->displayName)){
428       $message[] = _("You must specify the 'Display Name' in order to save this macro");
429     }  
430     /* CN is restricted to 20 chars */
431     if(strlen("Makro-".$this->cn)>20 ){
432       $message[]=_("The given cn is too long, to create a Makro entry, maximum 20 chars.");
433     }
434   
435     /* If this macro is still in use we should not change the visible for user flag to invisible */
436     if(!$this->goFonMacroVisible){
437       $ldap = $this->config->get_ldap_link();
438       $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
439       while ($val = $ldap->fetch()){
440         if(strstr($val['goFonMacro'][0],$this->dn)){
441           $message[] = _("This macro is still in use. It is necessary to mark this macro as visible for users.");
442           return($message);
443         }
444       }
445     }
447     if(empty($this->goFonMacroContent)){
448       $message[] = _("You can't save an empty macro.");
449     }
450     return $message;
451   }
454   /*! Remove makro from all given databases 
455    *   and ldap too.
456    */
457   function remove_from_parent()
458   {
459     $ldap= $this->config->get_ldap_link();
461     /* Skip remove if this macro is still in use */
462     $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
463     while ($val = $ldap->fetch()){ 
464       if(strstr($val['goFonMacro'][0],$this->dn)){ 
465         print_red(_("This macro is still in use. To delete this Macro ensure that nobody has selected it."));
466         return false;
467       }
468     }
470     /* Try to remove from database */
471     if(count($this->goFonHomeServers)){
472       $str = $this->remove_from_database(true);
473       if($str){ 
474         print_red($str);
475         return false;
476       }
477     }else{
478       print_red(_("Could not remove the macro entry from asterisk databases. Please check your asterisk database configurations."));
479       return false;
480     }
482     /* Remove phone macro */ 
483     $ldap->rmDir($this->dn);
484     new log("remove","gofonmacro/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error()); 
485     show_ldap_error($ldap->get_error(), sprintf(_("Removing of goFonMacro/generic account with dn '%s' failed."),$this->dn));
487     /* Delete references to object groups */
488     $ldap->cd ($this->config->current['BASE']);
489     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
490     while ($ldap->fetch()){
491       $og= new ogroup($this->config, $ldap->getDN());
492       unset($og->member[$this->dn]);
493       $og->save ();
494       show_ldap_error($ldap->get_error(), sprintf(_("Removing of goFonMacro/generic account with dn '%s' failed."),$this->dn));
495     }
496   }
499   /*! Save to LDAP */
500   function save()
501   {
502     plugin::save();
503     unset($this->attrs['base']);
505     /* Try to add entries to databases */
506     $str = $this->add_to_database(true);
507     if($str){
508       print_red($str);
509     }else{
510       /* Write back to ldap */
511       $ldap= $this->config->get_ldap_link();
512       $ldap->cat($this->dn, array('dn'));
513       $a= $ldap->fetch();
515       if (count($a)){
516         $ldap->cd($this->dn);
517         $this->cleanup();
518         $ldap->modify ($this->attrs); 
520         $this->handle_post_events("modify");
521       } else {
522         $ldap->cd($this->config->current['BASE']);
523         $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
524         $ldap->cd($this->dn);
525         $ldap->add($this->attrs);
526         $this->handle_post_events("add");
527       }
528       show_ldap_error($ldap->get_error(), sprintf(_("Saving of goFonMacro/generic account with dn '%s' failed."),$this->dn));
530       /* Log last action */
531       if($this->initially_was_account){
532         new log("modify","gofonmacro/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
533       }else{
534         new log("create","gofonmacro/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
535       }
536     }
537   }
540   function getCopyDialog()
541   {
542     $smarty = get_smarty();
543     $smarty->assign("cn" ,$this->cn);
544     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE));
545     $ret = array();
546     $ret['string'] = $str;
547     $ret['status'] = "";
548     return($ret);
549   }
552   function saveCopyDialog()
553   {
554     if(isset($_POST['cn'])){
555       $this->cn = $_POST['cn'];
556     }
557   }
560   static function plInfo()
561   {
562     return (array(
563           "plShortName"   => _("Generic"),
564           "plDescription" => _("Asterisk macro management"),
565           "plSelfModify"  => FALSE,
566           "plDepends"     => array(),
567           "plPriority"    => 0,
568           "plSection"     => array("administration"),
569           "plCategory"    => array("gofonmacro" => array("description" => _("GOfon macro"),
570               "objectClass" => "gofonMacro")),
572           "plProvidedAcls" => array(
573             "cn"                            => _("Macro name"),
574             "base"                          => _("Base"),
575             "description"                   => _("Description"),
576             "displayName"                   => _("Display name"),
577             "goFonMacroContent"             => _("Macro content and parameter"),
578             "goFonMacroVisible"             => _("Visibility flag"))
579           ));
580   }
583 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
584 ?>