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