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(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'];
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 }
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 ";
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 }
333 /* Remove last , from query string */
334 $sql = preg_replace("/,$/","",$sql);
336 /* Save current changes to the database */
337 if($save){
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 }
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 }
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 /* Macro content must be smaller than 100 lines */
448 if(count(split("\n",$this->goFonMacroContent))>100){
449 $message[] = _("Makro length must be lower than 100 lines");
450 }
452 /* Macro content must be smaller than 100 lines */
453 if(empty($this->goFonMacroContent)){
454 $message[] = _("You can't save an empty macro.");
455 }
456 return $message;
457 }
460 /*! Remove makro from all given databases
461 * and ldap too.
462 */
463 function remove_from_parent()
464 {
465 $ldap= $this->config->get_ldap_link();
467 /* Skip remove if this macro is still in use */
468 $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
469 while ($val = $ldap->fetch()){
470 if(strstr($val['goFonMacro'][0],$this->dn)){
471 print_red(_("This macro is still in use. To delete this Macro ensure that nobody has selected it."));
472 return false;
473 }
474 }
476 /* Try to remove from database */
477 if(count($this->goFonHomeServers)){
478 $str = $this->remove_from_database(true);
479 if($str){
480 print_red($str);
481 return false;
482 }
483 }else{
484 print_red(_("Could not remove the macro entry from asterisk databases. Please check your asterisk database configurations."));
485 return false;
486 }
488 /* Remove phone macro */
489 $ldap->rmDir($this->dn);
490 new log("remove","gofonmacro/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
491 show_ldap_error($ldap->get_error(), sprintf(_("Removing of goFonMacro/generic account with dn '%s' failed."),$this->dn));
493 /* Delete references to object groups */
494 $ldap->cd ($this->config->current['BASE']);
495 $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
496 while ($ldap->fetch()){
497 $og= new ogroup($this->config, $ldap->getDN());
498 unset($og->member[$this->dn]);
499 $og->save ();
500 show_ldap_error($ldap->get_error(), sprintf(_("Removing of goFonMacro/generic account with dn '%s' failed."),$this->dn));
501 }
502 }
505 /*! Save to LDAP */
506 function save()
507 {
508 plugin::save();
509 unset($this->attrs['base']);
511 /* Try to add entries to databases */
512 $str = $this->add_to_database(true);
513 if($str){
514 print_red($str);
515 }else{
516 /* Write back to ldap */
517 $ldap= $this->config->get_ldap_link();
518 $ldap->cat($this->dn, array('dn'));
519 $a= $ldap->fetch();
521 if (count($a)){
522 $ldap->cd($this->dn);
523 $this->cleanup();
524 $ldap->modify ($this->attrs);
526 $this->handle_post_events("modify");
527 } else {
528 $ldap->cd($this->config->current['BASE']);
529 $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
530 $ldap->cd($this->dn);
531 $ldap->add($this->attrs);
532 $this->handle_post_events("add");
533 }
534 show_ldap_error($ldap->get_error(), sprintf(_("Saving of goFonMacro/generic account with dn '%s' failed."),$this->dn));
536 /* Log last action */
537 if($this->initially_was_account){
538 new log("modify","gofonmacro/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
539 }else{
540 new log("create","gofonmacro/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
541 }
542 }
543 }
546 function getCopyDialog()
547 {
548 $smarty = get_smarty();
549 $smarty->assign("cn" ,$this->cn);
550 $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE));
551 $ret = array();
552 $ret['string'] = $str;
553 $ret['status'] = "";
554 return($ret);
555 }
558 function saveCopyDialog()
559 {
560 if(isset($_POST['cn'])){
561 $this->cn = $_POST['cn'];
562 }
563 }
566 static function plInfo()
567 {
568 return (array(
569 "plShortName" => _("Generic"),
570 "plDescription" => _("Asterisk macro management"),
571 "plSelfModify" => FALSE,
572 "plDepends" => array(),
573 "plPriority" => 0,
574 "plSection" => array("administration"),
575 "plCategory" => array("gofonmacro" => array("description" => _("GOfon macro"),
576 "objectClass" => "gofonMacro")),
578 "plProvidedAcls" => array(
579 "cn" => _("Macro name"),
580 "base" => _("Base"),
581 "description" => _("Description"),
582 "displayName" => _("Display name"),
583 "goFonMacroContent" => _("Macro content and parameter"),
584 "goFonMacroVisible" => _("Visibility flag"))
585 ));
586 }
588 }
589 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
590 ?>