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= "";
15 /*! The name of the Macro in the openldap drirectory */
16 var $cn = "";
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 = "";
30 /*! Here is the macro content, the real macroscript */
31 var $goFonMacroContent= "";
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");
38 var $view_logged = FALSE;
39 var $orig_cn = "";
40 var $orig_base = "";
41 var $orig_dn = "";
42 /*! Objectclasses that this calls handles */
43 var $objectclasses = array("top", "goFonMacro");
45 var $goFonHomeServers = array(); // Contains all available asterisk database server
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 if(session::is_set('CurrentMainBase')){
59 $this->base = session::get('CurrentMainBase');
60 }else{
61 $ui= get_userinfo();
62 $this->base= dn2base($ui->dn);
63 }
64 } else {
65 $this->orig_cn=$this->cn;
66 $this->base= preg_replace ("/^[^,]+,".normalizePreg(get_ou("phoneMacroRDN"))."/i", "", $this->dn);
67 }
69 /* Check server configurations
70 * Load all server configuration in $this->goFonHomeServers if available
71 */
72 $a_SETUP= array();
73 if(isset($config->data['SERVERS']['FON'])){
75 /* Set available server */
76 $this->goFonHomeServers = $config->data['SERVERS']['FON'];
78 /* Remove default entry, not necessary here */
79 if(isset($this->goFonHomeServers[0])){
80 unset($this->goFonHomeServers[0]);
81 }
82 }
84 $this->orig_base = $this->base;
85 $this->orig_dn = $this->dn;
86 }
89 /*! Execute this plugin */
90 function execute()
91 {
92 /* Call parent execute */
93 plugin::execute();
95 /* Log view */
96 if($this->is_account && !$this->view_logged){
97 $this->view_logged = TRUE;
98 new log("view","gofonmacro/".get_class($this),$this->dn);
99 }
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,$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()){
125 /* A new base was selected, check if it is a valid one */
126 $tmp = $this->get_allowed_bases();
127 if(isset($tmp[$this->dialog->isSelected()])){
128 $this->base = $this->dialog->isSelected();
129 }
131 $this->dialog= false;
132 }else{
133 return($this->dialog->execute());
134 }
135 }
137 /* Fill templating stuff */
138 $smarty= get_smarty();
139 $smarty->assign("bases", $this->get_allowed_bases());
141 $tmp = $this->plInfo();
142 foreach($tmp['plProvidedAcls'] as $name => $translation){
143 $smarty->assign($name."ACL",$this->getacl($name));
144 }
146 if($this->acl_is_writeable("base")){
147 $smarty->assign("baseSelect",true);
148 }else{
149 $smarty->assign("baseSelect",false);
150 }
153 /* Assign all vars to Smarty */
154 foreach($this->attributes as $ar){
155 $smarty->assign($ar, $this->$ar);
156 }
157 /* Checkboxes */
158 $smarty->assign("base_select", $this->base);
159 $smarty->assign("vars", $vars);
161 if($this->goFonMacroVisible){
162 $smarty->assign("goFonMacroVisibleChecked"," checked ");
163 }else{
164 $smarty->assign("goFonMacroVisibleChecked","");
165 }
167 $smarty->assign("cnACL",$this->getacl("cn",$this->initially_was_account));
168 $smarty->assign("cn",$this->cn);
170 /* Ensure that macro content is displayed correctly encoded */
171 $smarty->assign("goFonMacroContent",htmlentities(utf8_decode ($this->goFonMacroContent)));
173 /* Show main page */
174 return($smarty->fetch (get_template_path('generic.tpl', TRUE)));
175 }
178 /* This method check if all databases are reachable.
179 * Returns with error message or an empty string on success.
180 *
181 * - Is mysql extension available
182 * - Is every server reachable
183 * - Does the database exists/is accessible
184 */
185 function check_database_accessibility()
186 {
187 /* Check if mysql extension is available */
188 if(!is_callable("mysql_pconnect")){
189 return(msgPool::missingext("php-mysql"));
190 }
192 /********************
193 * Check all home server
194 ********************/
195 foreach($this->goFonHomeServers as $goFonHomeServer => $cfg_Current){
196 $r_current = @mysql_pconnect($cfg_Current['SERVER'],$cfg_Current['LOGIN'],$cfg_Current['PASSWORD']);
197 if(!$r_current){
198 new log("debug","gofonmacro/".get_class($this),"",array(),@mysql_error($r_current));
199 return ( msgPool::dbconnect("GOfon",@mysql_error(),$cfg_Current['SERVER']));
200 }
201 $db_current = @mysql_select_db($cfg_Current['DB'],$r_current);
202 if(!$db_current){
203 new log("debug","gofonmacro/".get_class($this),"",array(),@mysql_error($r_current));
204 mysql_close($r_current);
205 return ( msgPool::dbselect("GOfon",@mysql_error(),$cfg_Current['DB']));
206 }
207 }
208 }
211 /* Remove current macro from all asterisk server.
212 * First of all check if we have access to all databases.
213 * - Remove old entries
214 */
215 function remove_from_database($save)
216 {
217 /* Check if all databases are reachable */
218 $str = $this->check_database_accessibility();
219 if($str){
220 return($str);
221 }
223 /* Create query string */
224 $context = addslashes("macro-".$this->cn);
226 /* Remove current macro from each server available */
227 if($save){
228 foreach($this->goFonHomeServers as $dn => $Server){
229 $query = "DELETE FROM ".$Server['EXT_TABLE']." WHERE context='".$context."';";
230 $r_current = @mysql_pconnect($Server['SERVER'],$Server['LOGIN'],$Server['PASSWORD']);
231 $db_current = @mysql_select_db($Server['DB'],$r_current);
232 $res = @mysql_query($query,$r_current);
233 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
234 if(!$res){
235 new log("debug","gofonmacro/".get_class($this),"",array(),@mysql_error($r_current));
236 return ( msgPool::dbquery("GOfon",@mysql_error($r_current),$Server['SERVER']));
237 }
238 @mysql_close($r_current);
239 }
240 }
241 }
244 /* Add current macro to all asterisk server.
245 * First of all check if we have access to all databases.
246 * - Remove old entries
247 * - Add new entries
248 */
249 function add_to_database($save)
250 {
251 /* Check if all databases are reachable */
252 $str = $this->check_database_accessibility();
253 if($str){
254 return($str);
255 }
257 /* Remove old entries first. Else we got duplicated entries */
258 $str = $this->remove_from_database($save);
259 if($str){
260 return($str);
261 }
263 /* Create query string */
264 $context = "macro-".$this->cn;
266 /************
267 * Parse Macro content
268 ************/
269 $sql =
270 "INSERT INTO %TABLENAME% ".
271 " (context,exten,priority,app,appdata) ".
272 " VALUES ";
274 $a_contentLines = split("\n",$this->goFonMacroContent);
275 foreach($a_contentLines as $i_linenum => $s_linestr){
277 /* Remove the 'exten => ' string in front of the macro content line
278 * example line 'exten => s,2,GotoIf(${ARG3}?3:5)'
279 * Remove comments introduced by ;
280 * Skip empty lines
281 */
282 $s_linestr = trim($s_linestr);
283 $s_linestr = preg_replace("/;.*$/","",$s_linestr) ;
284 $s_linestr = preg_replace ("/^.*=\> /","",$s_linestr);
286 if(empty($s_linestr)){
287 continue;
288 }
290 /* A line that passes the check above should look like this
291 * s,1,SetLanguage(de)
292 * 3 parts seperated by ,
293 * If there are more or less parts, abort.
294 * The preg_replace exclude parameters from split ..
295 */
296 $tmp = split(",", $s_linestr,3);
298 /* Multiple () are not supproted currently ... */
299 if(substr_count($s_linestr,"(") >1 ){
300 return(sprintf(_("Not supported multiple brace in line %s!"),$i_linenum));
301 }
302 if(substr_count($s_linestr,")") >1 ){
303 return(sprintf(_("Not supported multiple brace in line %s!"),$i_linenum));
304 }
305 /* Check if there is an application given */
306 if(empty($tmp[1])){
307 return(sprintf(_("Application missing in line %s!"),$i_linenum));
308 }
309 /* Check if there is an extension given */
310 if(empty($tmp[0])){
311 return(sprintf(_("Extension missing in line %s!"),$i_linenum));
312 }
314 /* Create extension entry for current line
315 * and add this line to an array that will be inserted
316 * to each database.
317 */
318 $exten = addslashes($tmp[0]);
319 $prio = addslashes($tmp[1]);
320 $app = addslashes(preg_replace("/\(.*\).*$/","",$tmp[2]));
321 $para = addslashes(preg_replace("/^[^(]*\((.*)\)[^)]*$/", "$1", $tmp[2]));
322 $sql.= " ('".$context."','".$exten."','".$prio."','".$app."','".$para."'),";
323 }
325 /* Remove last , from query string */
326 $sql = preg_replace("/,$/","",$sql);
328 /* Save current changes to the database */
329 if($save){
331 /* Macro are spread to each asterisk server */
332 foreach($this->goFonHomeServers as $dn => $cfg){
333 $r_con = @mysql_pconnect($cfg['SERVER'],$cfg['LOGIN'],$cfg['PASSWORD']);
334 $db = @mysql_select_db($cfg['DB'],$r_con);
335 $query = preg_replace("/%TABLENAME%/",$cfg['EXT_TABLE'],$sql);
336 $res = @mysql_query($query,$r_con);
337 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
338 if(!$res){
339 new log("debug","gofonmacro/".get_class($this),"",array(),@mysql_error($r_con));
340 }
341 @mysql_close($r_con);
342 }
343 }
344 }
347 function save_object()
348 {
349 if (isset($_POST['gofonMacroGenericPosted'])){
351 $old_cn = $this->cn;
352 $old_visible = $this->goFonMacroVisible;
354 /* Create a base backup and reset the
355 base directly after calling plugin::save_object();
356 Base will be set seperatly a few lines below */
357 $base_tmp = $this->base;
358 plugin::save_object();
359 $this->base = $base_tmp;
361 /* Save base, since this is no LDAP attribute */
362 $tmp = $this->get_allowed_bases();
363 if(isset($_POST['base'])){
364 if(isset($tmp[$_POST['base']])){
365 $this->base= $_POST['base'];
366 }
367 }
369 /* Restore old cn if we have insuficient acls to change cn ... */
370 if(!$this->acl_is_writeable("cn",$this->initially_was_account)){
371 $this->cn = $old_cn;
372 }
374 /* check if we are allowed to toggle visibility */
375 if($this->acl_is_writeable("goFonMacroVisible")) {
377 /* Checkbox selected ? */
378 if(isset($_POST['goFonMacroVisible'])) {
379 $this->goFonMacroVisible= 1 ;
380 }else {
381 if(isset($_POST['displayName'])){
382 $this->goFonMacroVisible= 0 ;
383 }
384 }
385 }else{
386 $this->goFonMacroVisible = $old_visible;
387 }
388 }
389 }
392 /*! Check values */
393 function check()
394 {
395 /* Call common method to give check the hook */
396 $message= plugin::check();
398 if(!count($this->goFonHomeServers)){
399 $message[] = msgPool::noserver(_("GOfon"));
400 }
402 /* Check if insert/replace is possible and all servers are available */
403 $str = $this->add_to_database(false);
404 if($str){
405 $message[] = $str;
406 }
408 /* Check if cn is already used */
409 if(($this->dn=="new")||($this->orig_cn!=$this->cn)){
410 $ldap = $this->config->get_ldap_link();
411 $ldap->search("(&(objectClass=goFonMacro)(cn=".$this->cn."))",array("cn"));
412 if($ldap->count()>0){
413 $message[]= msgPool::duplicated(_("Name"));
414 }
415 }
417 /* Check if display name is set */
418 if($this->displayName == ""){
419 $message[] = msgPool::required(_("Name"));
420 }
421 /* CN is restricted to 20 chars */
422 if(strlen("Makro-".$this->cn)>20 ){
423 $message[]=_("Name can be 20 characters at maximum!");
424 }
426 /* If this macro is still in use we should not change the visible for user flag to invisible */
427 if(!$this->goFonMacroVisible){
428 $ldap = $this->config->get_ldap_link();
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 $message[] = _("Macro is still in use!");
433 return($message);
434 }
435 }
436 }
438 if(empty($this->goFonMacroContent)){
439 $message[] = _("Macro is empty!");
440 }
442 /* Check if we are allowed to create or move this object
443 */
444 if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
445 $message[] = msgPool::permCreate();
446 }elseif($this->orig_dn != "new" && $this->base != $this->orig_base && !$this->acl_is_moveable($this->base)){
447 $message[] = msgPool::permMove();
448 }
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", "cn"));
463 while ($val = $ldap->fetch()){
464 if(strstr($val['goFonMacro'][0],$this->dn)){
465 msg_dialog::display(_("Error"), sprintf(_("Cannot delete entry because it is still in use by '%s'!"), $val['cn'][0]), ERROR_DIALOG);
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 msg_dialog::display(_("Error"), $str, ERROR_DIALOG);
475 return false;
476 }
477 }else{
478 msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
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 if (!$ldap->success()){
486 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
487 }
489 /* Delete references to object groups */
490 $ldap->cd ($this->config->current['BASE']);
491 $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
492 while ($ldap->fetch()){
493 $og= new ogroup($this->config, $ldap->getDN());
494 unset($og->member[$this->dn]);
495 $og->save ();
496 if (!$ldap->success()){
497 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
498 }
499 }
500 }
503 /*! Save to LDAP */
504 function save()
505 {
506 plugin::save();
507 unset($this->attrs['base']);
509 /* Try to add entries to databases */
510 $str = $this->add_to_database(true);
511 if($str){
512 msg_dialog::display(_("Error"), $str, ERROR_DIALOG);
513 }else{
514 /* Write back to ldap */
515 $ldap= $this->config->get_ldap_link();
516 $ldap->cat($this->dn, array('dn'));
517 $a= $ldap->fetch();
519 if (count($a)){
520 $ldap->cd($this->dn);
521 $this->cleanup();
522 $ldap->modify ($this->attrs);
524 $this->handle_post_events("modify");
525 } else {
526 $ldap->cd($this->config->current['BASE']);
527 $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
528 $ldap->cd($this->dn);
529 $ldap->add($this->attrs);
530 $this->handle_post_events("add");
531 }
532 if (!$ldap->success()){
533 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
534 }
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 ?>