Code

Updated macro checks
[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         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
221         if(!$res){
222           gosa_log(@mysql_error($r_current));
223           return(sprintf(_("Removing macro from '%s' failed. Check GOsa log for mysql error."),$Server['SERVER']));
224         }
225         @mysql_close($r_current);
226       }
227     }
228   }
230  
231   /* Add current macro to all asterisk server.
232    * First of all check if we have access to all databases. 
233    * - Remove old entries 
234    * - Add new entries 
235    */ 
236   function add_to_database($save)
237   {
238     /* Check if all databases are reachable */
239     $str = $this->check_database_accessibility();
240     if($str){
241       return($str);
242     }
244     /* Remove old entries first. Else we got duplicated entries */
245     $str = $this->remove_from_database($save);
246     if($str){
247       return($str);
248     }
250     /* Create query string */
251     $context      = "macro-".$this->cn;
253     /************
254      * Parse Macro content
255      ************/
256     $sql = 
257       "INSERT INTO %TABLENAME% ".
258       " (context,exten,priority,app,appdata) ".
259       " VALUES ";
260       
261     $a_contentLines = split("\n",$this->goFonMacroContent);
262     foreach($a_contentLines as $i_linenum => $s_linestr){
264       /* Remove the 'exten => ' string in front of the macro content line 
265        *  example line  'exten => s,2,GotoIf(${ARG3}?3:5)'
266        * Remove comments introduced by ;
267        * Skip empty lines 
268        */ 
269       $s_linestr = trim($s_linestr);
270       $s_linestr = preg_replace("/;.*$/","",$s_linestr) ;
271       $s_linestr = preg_replace ("/^.*=\> /","",$s_linestr);
273       if(empty($s_linestr)){
274         continue;
275       }
277       /* A line that passes the check above should look like this 
278        *  s,1,SetLanguage(de)
279        * 3 parts seperated by , 
280        * If there are more or less parts, abort.
281        * The preg_replace exclude parameters from split .. 
282        */
283       $tmp  = split(",", $s_linestr,3);
285       /* Check if there are exactly 2 , */ 
286 #      if(substr_count($s_linestr,",") !=2){
287 #        return(sprintf(_("More than two ',' given in line : '%s'. Remember that parameters are seperated by '|'."),$i_linenum));
288 #      }
290 #     /* Multiple () are not supproted currently ... */  
291 #     if(substr_count($s_linestr,"(") >1 ){
292 #       return(sprintf(_("More than one '(' is currently not supported. Line : '%s'."),$i_linenum));
293 #     }
294 #     if(substr_count($s_linestr,")") >1 ){
295 #       return(sprintf(_("More than one ')' is currently not supported. Line : '%s'."),$i_linenum));
296 #     }
298       /* Check if there is an application given */
299       if(empty($tmp[1])){
300         return(sprintf(_("There is no application given in line : '%s'."),$i_linenum));
301       }
302       /* Check if there is an extension given */
303       if(empty($tmp[0])){
304         return(sprintf(_("There is no extension type given 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           gosa_log(@mysql_error($r_con));
333           return(sprintf(_("Insert of new macro failed for server '%s'."),$cfg['SERVER']));
334         }
335         @mysql_close($r_con);
336       }
337     }
338   }
341   /*! Save data to object */
342   function save_object()
343   {
344     if (isset($_POST['displayName'])){
345       plugin::save_object();
347       /* The cn can't be changed if this entry is not new */
348       if(!$this->is_new){
349         $this->cn = $this->orig_cn;
350       }
352       if(isset($_POST['goFonMacroVisible'])) {
353         $this->goFonMacroVisible= 1 ;
354       }else  {
355         $this->goFonMacroVisible= 0 ;
356       }
357     }
358   }
361   /*! Check values */
362   function check()
363   {
364     /* Call common method to give check the hook */
365     $message= plugin::check();
367     if(!count($this->goFonHomeServers)){
368       $message[] = _("There must be at least one server with an asterisk database to save this phone macro.");
369     }
371     /* Check if insert/replace is possible and all servers are available */
372     $str = $this->add_to_database(false);
373     if($str){
374       $message[] = $str;
375     }
377     /* Check if cn is already used  */
378     if(($this->dn=="new")||($this->orig_cn!=$this->cn)){
379       $ldap = $this->config->get_ldap_link();
380       $ldap->search("(&(objectClass=goFonMacro)(cn=".$this->cn."))",array("cn"));
381       if($ldap->count()>0){
382         $message[]=sprintf(_("The given cn '%s' already exists."),$this->cn);
383       }
384     }
385   
386     /* Check if display name is set */
387     if(empty($this->displayName)){
388       $message[] = _("You must specify the 'Display Name' in order to save this macro");
389     }  
390     /* CN is restricted to 20 chars */
391     if(strlen("Makro-".$this->cn)>20 ){
392       $message[]=_("The given cn is too long, to create a Makro entry, maximum 20 chars.");
393     }
394   
395     /* Check permissions */
396     foreach($this->attributes as $attr){
397       if(chkacl($this->acl,"edit")){
398         $str =  sprintf( _("Insufficient permissions, can't change attribute '%s' in goFonMacro"),$attr) ;
399         return(array($str));
400       }
401     }
403     /* If this macro is still in use we should not change the visible for user flag to invisible */
404     if(!$this->goFonMacroVisible){
405       $ldap = $this->config->get_ldap_link();
406       $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
407       while ($val = $ldap->fetch()){
408         if(strstr($val['goFonMacro'][0],$this->dn)){
409           $message[] = _("This macro is still in use. It is necessary to mark this macro as visible for users.");
410           return($message);
411         }
412       }
413     }
414     return $message;
415   }
418   /*! Remove makro from all given databases 
419    *   and ldap too.
420    */
421   function remove_from_parent()
422   {
423     $ldap= $this->config->get_ldap_link();
425     /* Skip remove if this macro is still in use */
426     $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
427     while ($val = $ldap->fetch()){ 
428       if(strstr($val['goFonMacro'][0],$this->dn)){ 
429         print_red(_("This macro is still in use. To delete this Macro ensure that nobody has selected it."));
430         return false;
431       }
432     }
434     /* Try to remove from database */
435     if(count($this->goFonHomeServers)){
436       $str = $this->remove_from_database(true);
437       if($str){ 
438         print_red($str);
439         return false;
440       }
441     }else{
442       print_red(_("Could not remove the macro entry from asterisk databases. Please check your asterisk database configurations."));
443       return false;
444     }
446     /* Remove phone macro */ 
447     $ldap->rmDir($this->dn); 
448     show_ldap_error($ldap->get_error(), _("Removing phone macro failed"));
450     /* Delete references to object groups */
451     $ldap->cd ($this->config->current['BASE']);
452     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".@LDAP::prepare4filter($this->dn)."))", array("cn"));
453     while ($ldap->fetch()){
454       $og= new ogroup($this->config, $ldap->getDN());
455       unset($og->member[$this->dn]);
456       $og->save ();
457       show_ldap_error($ldap->get_error(), _("Removing phone macro reverences failed"));
458     }
459   }
462   /*! Save to LDAP */
463   function save()
464   {
465     plugin::save();
466     unset($this->attrs['base']);
468     /* Try to add entries to databases */
469     $str = $this->add_to_database(true);
470     if($str){
471       print_red($str);
472     }else{
473       /* Write back to ldap */
474       $ldap= $this->config->get_ldap_link();
475       $ldap->cat($this->dn, array('dn'));
476       $a= $ldap->fetch();
478       if (count($a)){
479         $ldap->cd($this->dn);
480         $this->cleanup();
481         $ldap->modify ($this->attrs); 
483         $this->handle_post_events("modify");
484       } else {
485         $ldap->cd($this->config->current['BASE']);
486         $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
487         $ldap->cd($this->dn);
488         $ldap->add($this->attrs);
489         $this->handle_post_events("add");
490       }
491       show_ldap_error($ldap->get_error(), _("Saving phone macro failed"));
492     }
493   }
496 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
497 ?>