Code

Fixed handling for newly created macros.
[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   /*! 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");
39   var $orig_cn = ""; 
40   /*! Objectclasses that this calls handles */
41   var $objectclasses  = array("top", "goFonMacro");
43   var $goFonHomeServers = array(); // Contains all available asterisk database server 
45   var $is_new = FALSE;
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       $this->is_new = TRUE;
59       if(isset($_SESSION['CurrentMainBase'])){
60         $this->base = $_SESSION['CurrentMainBase'];
61       }else{
62         $ui= get_userinfo();
63         $this->base= dn2base($ui->dn);
64       }
65     } else {
66       $this->orig_cn=$this->cn;
67       $this->base= preg_replace ("/^[^,]+,[^,]+,[^,]+,[^,]+,[^,]+,/", "", $this->dn);
68     }
70     /* Check server configurations
71      * Load all server configuration in $this->goFonHomeServers if available
72      */
73     $a_SETUP= array();
74     if(array_key_exists('config',$_SESSION) &&
75        array_key_exists('SERVERS',$_SESSION['config']->data) &&
76        count($_SESSION['config']->data['SERVERS']['FON']) && 
77        array_key_exists('FON',$_SESSION['config']->data['SERVERS'])) {
79       /* Set available server */
80       $this->goFonHomeServers = $_SESSION['config']->data['SERVERS']['FON'];
81   
82       /* Remove default entry, not necessary here */
83       if(isset($this->goFonHomeServers[0])){
84         unset($this->goFonHomeServers[0]);  
85       }
86     }
88     /* Load acl */
89     $ui       = get_userinfo();
90     $acl      = get_permissions ($ui->dn, $ui->subtreeACL);
91     $this->acl= get_module_permission($acl, "goFonMacro", $ui->dn);
92   }
95   /*!  Execute this plugin */
96   function execute()
97   {
98     /* Call parent execute */
99     plugin::execute();
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->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()){
124         $this->base = $this->dialog->isSelected();
125         $this->dialog= false;
126       }else{
127         return($this->dialog->execute());
128       }
129     }
131     /* Fill templating stuff */
132     $smarty= get_smarty();
133     $smarty->assign("bases", $this->config->idepartments);
135     /* Assign all vars to Smarty */
136     foreach($this->attributes as $ar){
137       $smarty->assign($ar, $this->$ar);
138       $smarty->assign($ar."ACL", chkacl($this->acl,$ar));
139     }
140     /* Checkboxes */
141     $smarty->assign("base_select", $this->base);
142     $smarty->assign("vars", $vars);
144     if($this->goFonMacroVisible){
145       $smarty->assign("goFonMacroVisibleChecked"," checked ");
146     }else{
147       $smarty->assign("goFonMacroVisibleChecked","");
148     }
150     if($this->dn != "new"){
151       $smarty->assign("disable_cn"," disabled ");
152     }else{
153       $smarty->assign("disable_cn","  ");
154     }
156     /* Ensure that macro content is displayed correctly encoded */
157     $smarty->assign("goFonMacroContent",htmlentities(utf8_decode ($this->goFonMacroContent)));
159     /* Show main page */
160     return($smarty->fetch (get_template_path('generic.tpl', TRUE)));
161   }
164   /* This method check if all databases are reachable.  
165    *  Returns with error message or an empty string on success.
166    * 
167    * - Is mysql extension available  
168    * - Is every server reachable 
169    * - Does the database exists/is accessible
170    */
171   function check_database_accessibility()
172   {
173     /* Check if mysql extension is available */
174     if(!is_callable("mysql_pconnect")){
175       return(_("Can't save any changes to asterisk database, there is currently no mysql extension available in your php setup."));
176     }
178     /********************
179      * Check all home server
180      ********************/
181     foreach($this->goFonHomeServers as $goFonHomeServer => $cfg_Current){
182       $r_current    =  @mysql_pconnect($cfg_Current['SERVER'],$cfg_Current['LOGIN'],$cfg_Current['PASSWORD']);
183       if(!$r_current){
184         gosa_log(@mysql_error($r_current));
185         return(sprintf(_("The MySQL home server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
186               $cfg_Current['SERVER'],$cfg_Current['LOGIN']));
187       }
188       $db_current  =  @mysql_select_db($cfg_Current['DB'],$r_current);
189       if(!$db_current){
190         gosa_log(@mysql_error($r_current));
191         mysql_close($r_current);
192         return( sprintf(_("Can't select database '%s' on home server '%s'."),$cfg_Current['DB'],$cfg_Current['SERVER']));
193       }
194     }
195   }
198   /* Remove current macro from all asterisk server.
199    * First of all check if we have access to all databases. 
200    * - Remove old entries 
201    */ 
202   function remove_from_database($save)
203   {
204     /* Check if all databases are reachable */
205     $str = $this->check_database_accessibility();
206     if($str){
207       return($str);
208     }
210     /* Create query string */
211     $context  = addslashes("macro-".$this->cn);
213     /* Remove current macro from each server available */ 
214     if($save){
215       foreach($this->goFonHomeServers as $dn => $Server){
216         $query      = "DELETE FROM ".$Server['EXT_TABLE']." WHERE context='".$context."';";
217         $r_current  =  @mysql_pconnect($Server['SERVER'],$Server['LOGIN'],$Server['PASSWORD']);
218         $db_current =  @mysql_select_db($Server['DB'],$r_current);
219         $res = @mysql_query($query,$r_current);
220         if(!$res){
221           gosa_log(@mysql_error($r_current));
222           return(sprintf(_("Removing macro from '%s' failed. Check GOsa log for mysql error."),$Server['SERVER']));
223         }
224         @mysql_close($r_current);
225       }
226     }
227   }
229  
230   /* Add current macro to all asterisk server.
231    * First of all check if we have access to all databases. 
232    * - Remove old entries 
233    * - Add new entries 
234    */ 
235   function add_to_database($save)
236   {
237     /* Check if all databases are reachable */
238     $str = $this->check_database_accessibility();
239     if($str){
240       return($str);
241     }
243     /* Remove old entries first. Else we got duplicated entries */
244     $str = $this->remove_from_database($save);
245     if($str){
246       return($str);
247     }
249     /* Create query string */
250     $context      = "macro-".$this->cn;
252     /************
253      * Parse Macro content
254      ************/
255     $sql = 
256       "INSERT INTO %TABLENAME% ".
257       " (context,exten,priority,app,appdata) ".
258       " VALUES ";
259       
260     $a_contentLines = split("\n",$this->goFonMacroContent);
261     foreach($a_contentLines as $i_linenum => $s_linestr){
263       /* Remove the 'exten => ' string in front of the macro content line 
264        *  example line  'exten => s,2,GotoIf(${ARG3}?3:5)'
265        * Remove comments introduced by ;
266        * Skip empty lines 
267        */ 
268       $s_linestr = trim($s_linestr);
269       $s_linestr = preg_replace("/;.*$/","",$s_linestr) ;
270       $s_linestr = preg_replace ("/^.*=\> /","",$s_linestr);
272       if(empty($s_linestr)){
273         continue;
274       }
276       /* A line that passes the check above should look like this 
277        *  s,1,SetLanguage(de)
278        * 3 parts seperated by , 
279        * If there are more or less parts, abort.
280        * The preg_replace exclude parameters from split .. 
281        */
282       $tmp  = split(",", $s_linestr,3);
284       /* Check if there are exactly 2 , */ 
285 #      if(substr_count($s_linestr,",") !=2){
286 #        return(sprintf(_("More than two ',' given in line : '%s'. Remember that parameters are seperated by '|'."),$i_linenum));
287 #      }
288       /* Multiple () are not supproted currently ... */  
289       if(substr_count($s_linestr,"(") >1 ){
290         return(sprintf(_("More than one '(' is currently not supported. Line : '%s'."),$i_linenum));
291       }
292       if(substr_count($s_linestr,")") >1 ){
293         return(sprintf(_("More than one ')' is currently not supported. Line : '%s'."),$i_linenum));
294       }
295       /* Check if there is an application given */
296       if(empty($tmp[1])){
297         return(sprintf(_("There is no application given in line : '%s'."),$i_linenum));
298       } 
299       /* Check if there is an extension given */
300       if(empty($tmp[0])){
301         return(sprintf(_("There is no extension type given in line : '%s'."),$i_linenum));
302       } 
304       /* Create extension entry for current line 
305        *  and add this line to an array that will be inserted 
306        *  to each database.
307        */
308       $exten  = addslashes($tmp[0]);
309       $prio   = addslashes($tmp[1]);
310       $app    = addslashes(preg_replace("/\(.*\).*$/","",$tmp[2]));
311       $para   = addslashes(preg_replace("/^.*\(/","",$tmp[2]));
312       $para   = preg_replace("/\).*$/","",$para);
313       $sql.= " ('".$context."','".$exten."','".$prio."','".$app."','".$para."'),";
314     }
315     
316     /* Remove last , from query string */
317     $sql = preg_replace("/,$/","",$sql);
319     /* Save current changes to the database */
320     if($save){
321     
322       /* Macro are spread to each asterisk server */
323       foreach($this->goFonHomeServers as $dn => $cfg){
324         $r_con  = @mysql_pconnect($cfg['SERVER'],$cfg['LOGIN'],$cfg['PASSWORD']); 
325         $db     = @mysql_select_db($cfg['DB'],$r_con);
326         $query  = preg_replace("/%TABLENAME%/",$cfg['EXT_TABLE'],$sql);
327         $res    = @mysql_query($query,$r_con);
328         if(!$res){
329           gosa_log(@mysql_error($r_con));
330           return(sprintf(_("Insert of new macro failed for server '%s'."),$cfg['SERVER']));
331         }
332         @mysql_close($r_con);
333       }
334     }
335   }
338   /*! Save data to object */
339   function save_object()
340   {
341     if (isset($_POST['displayName'])){
342       plugin::save_object();
344       /* The cn can't be changed if this entry is not new */
345       if(!$this->is_new){
346         $this->cn = $this->orig_cn;
347       }
349       if(isset($_POST['goFonMacroVisible'])) {
350         $this->goFonMacroVisible= 1 ;
351       }else  {
352         $this->goFonMacroVisible= 0 ;
353       }
354     }
355   }
358   /*! Check values */
359   function check()
360   {
361     /* Call common method to give check the hook */
362     $message= plugin::check();
364     if(!count($this->goFonHomeServers)){
365       $message[] = _("There must be at least one server with an asterisk database to save this phone macro.");
366     }
368     /* Check if insert/replace is possible and all servers are available */
369     $str = $this->add_to_database(false);
370     if($str){
371       $message[] = $str;
372     }
374     /* Check if cn is already used  */
375     if(($this->dn=="new")||($this->orig_cn!=$this->cn)){
376       $ldap = $this->config->get_ldap_link();
377       $ldap->search("(&(objectClass=goFonMacro)(cn=".$this->cn."))",array("cn"));
378       if($ldap->count()>0){
379         $message[]=sprintf(_("The given cn '%s' already exists."),$this->cn);
380       }
381     }
382   
383     /* Check if display name is set */
384     if(empty($this->displayName)){
385       $message[] = _("You must specify the 'Display Name' in order to save this macro");
386     }  
387     /* CN is restricted to 20 chars */
388     if(strlen("Makro-".$this->cn)>20 ){
389       $message[]=_("The given cn is too long, to create a Makro entry, maximum 20 chars.");
390     }
391   
392     /* Check permissions */
393     foreach($this->attributes as $attr){
394       if(chkacl($this->acl,"edit")){
395         $str =  sprintf( _("Insufficient permissions, can't change attribute '%s' in goFonMacro"),$attr) ;
396         return(array($str));
397       }
398     }
400     /* If this macro is still in use we should not change the visible for user flag to invisible */
401     if(!$this->goFonMacroVisible){
402       $ldap = $this->config->get_ldap_link();
403       $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
404       while ($val = $ldap->fetch()){
405         if(strstr($val['goFonMacro'][0],$this->dn)){
406           $message[] = _("This macro is still in use. It is necessary to mark this macro as visible for users.");
407           return($message);
408         }
409       }
410     }
412     /* Macro content must be smaller than 100 lines */
413     if(count(split("\n",$this->goFonMacroContent))>100){
414       $message[] = _("Makro length must be lower than 100 lines");
415     }
417     return $message;
418   }
421   /*! Remove makro from all given databases 
422    *   and ldap too.
423    */
424   function remove_from_parent()
425   {
426     $ldap= $this->config->get_ldap_link();
428     /* Skip remove if this macro is still in use */
429     $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
430     while ($val = $ldap->fetch()){ 
431       if(strstr($val['goFonMacro'][0],$this->dn)){ 
432         print_red(_("This macro is still in use. To delete this Macro ensure that nobody has selected it."));
433         return false;
434       }
435     }
437     /* Try to remove from database */
438     if(count($this->goFonHomeServers)){
439       $str = $this->remove_from_database(true);
440       if($str){ 
441         print_red($str);
442         return false;
443       }
444     }else{
445       print_red(_("Could not remove the macro entry from asterisk databases. Please check your asterisk database configurations."));
446       return false;
447     }
449     /* Remove phone macro */ 
450     $ldap->rmDir($this->dn); 
451     show_ldap_error($ldap->get_error(), _("Removing phone macro failed"));
453     /* Delete references to object groups */
454     $ldap->cd ($this->config->current['BASE']);
455     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
456     while ($ldap->fetch()){
457       $og= new ogroup($this->config, $ldap->getDN());
458       unset($og->member[$this->dn]);
459       $og->save ();
460       show_ldap_error($ldap->get_error(), _("Removing phone macro reverences failed"));
461     }
462   }
465   /*! Save to LDAP */
466   function save()
467   {
468     plugin::save();
469     unset($this->attrs['base']);
471     /* Try to add entries to databases */
472     $str = $this->add_to_database(true);
473     if($str){
474       print_red($str);
475     }else{
476       /* Write back to ldap */
477       $ldap= $this->config->get_ldap_link();
478       $ldap->cat($this->dn, array('dn'));
479       $a= $ldap->fetch();
481       if (count($a)){
482         $ldap->cd($this->dn);
483         $this->cleanup();
484         $ldap->modify ($this->attrs); 
486         $this->handle_post_events("modify");
487       } else {
488         $ldap->cd($this->config->current['BASE']);
489         $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
490         $ldap->cd($this->dn);
491         $ldap->add($this->attrs);
492         $this->handle_post_events("add");
493       }
494       show_ldap_error($ldap->get_error(), _("Saving phone macro failed"));
495     }
496   }
499 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
500 ?>