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");
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 }
92 /* Load acl */
93 $ui = get_userinfo();
94 $acl = get_permissions ($ui->dn, $ui->subtreeACL);
95 $this->acl= get_module_permission($acl, "goFonMacro", $ui->dn);
96 }
99 /*! Execute this plugin */
100 function execute()
101 {
102 /* Call parent execute */
103 plugin::execute();
105 /* Variables */
106 $vars = "";
107 $tmp = array();
108 $number = 0;
110 /* Base select dialog */
111 $once = true;
112 foreach($_POST as $name => $value){
113 if(preg_match("/^chooseBase/",$name) && $once){
114 $once = false;
115 $this->dialog = new baseSelectDialog($this->config,$this->allowedBasesToMoveTo());
116 $this->dialog->setCurrentBase($this->base);
117 }
118 }
120 /* Dialog handling */
121 if(is_object($this->dialog)){
122 /* Must be called before save_object */
123 $this->dialog->save_object();
125 if($this->dialog->isClosed()){
126 $this->dialog = false;
127 }elseif($this->dialog->isSelected()){
128 $this->base = $this->dialog->isSelected();
129 $this->dialog= false;
130 }else{
131 return($this->dialog->execute());
132 }
133 }
135 /* Fill templating stuff */
136 $smarty= get_smarty();
137 $smarty->assign("bases", $this->config->idepartments);
139 /* Assign all vars to Smarty */
140 foreach($this->attributes as $ar){
141 $smarty->assign($ar, $this->$ar);
142 $smarty->assign($ar."ACL", chkacl($this->acl,$ar));
143 }
144 /* Checkboxes */
145 $smarty->assign("base_select", $this->base);
146 $smarty->assign("vars", $vars);
148 if($this->goFonMacroVisible){
149 $smarty->assign("goFonMacroVisibleChecked"," checked ");
150 }else{
151 $smarty->assign("goFonMacroVisibleChecked","");
152 }
154 if(isset($_POST['goFonMacroVisible'])) {
155 $this->goFonMacroVisible= 1 ;
156 $smarty->assign("goFonMacroVisibleChecked"," checked ");
157 }else {
158 if(isset($_POST['displayName'])){
159 $this->goFonMacroVisible= 0 ;
160 $smarty->assign("goFonMacroVisibleChecked","");
161 }
162 }
164 if($this->dn != "new"){
165 $smarty->assign("disable_cn"," disabled ");
166 }else{
167 $smarty->assign("disable_cn"," ");
168 }
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(_("Can't save any changes to asterisk database, there is currently no mysql extension available in your php setup."));
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 gosa_log(@mysql_error($r_current));
199 return(sprintf(_("The MySQL home server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
200 $cfg_Current['SERVER'],$cfg_Current['LOGIN']));
201 }
202 $db_current = @mysql_select_db($cfg_Current['DB'],$r_current);
203 if(!$db_current){
204 gosa_log(@mysql_error($r_current));
205 mysql_close($r_current);
206 return( sprintf(_("Can't select database '%s' on home server '%s'."),$cfg_Current['DB'],$cfg_Current['SERVER']));
207 }
208 }
209 }
212 /* Remove current macro from all asterisk server.
213 * First of all check if we have access to all databases.
214 * - Remove old entries
215 */
216 function remove_from_database($save)
217 {
218 /* Check if all databases are reachable */
219 $str = $this->check_database_accessibility();
220 if($str){
221 return($str);
222 }
224 /* Create query string */
225 $context = addslashes("macro-".$this->cn);
227 /* Remove current macro from each server available */
228 if($save){
229 foreach($this->goFonHomeServers as $dn => $Server){
230 $query = "DELETE FROM ".$Server['EXT_TABLE']." WHERE context='".$context."';";
231 $r_current = @mysql_pconnect($Server['SERVER'],$Server['LOGIN'],$Server['PASSWORD']);
232 $db_current = @mysql_select_db($Server['DB'],$r_current);
233 $res = @mysql_query($query,$r_current);
234 if(!$res){
235 gosa_log(@mysql_error($r_current));
236 return(sprintf(_("Removing marco from '%s' failed. Check GOsa log for mysql error."),$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 = preg_replace ("/^.*=\> /","",$s_linestr);
283 $s_linestr = preg_replace("/;.*$/","",$s_linestr) ;
284 $s_linestr = trim($s_linestr);
285 if(empty($s_linestr)){
286 continue;
287 }
289 /* A line that passes the check above should look like this
290 * s,1,SetLanguage(de)
291 * 3 parts seperated by ,
292 * If there are more or less parts, abort.
293 * The preg_replace exclude parameters from split ..
294 */
295 $tmp = split(",", $s_linestr,3);
297 /* Check if there are exactly 2 , */
298 if(substr_count($s_linestr,",") !=2){
299 return(sprintf(_("More than two ',' given in line : '%s'. Remember that parameters are seperated by '|'."),$i_linenum));
300 }
301 /* Multiple () are not supproted currently ... */
302 if(substr_count($s_linestr,"(") >1 ){
303 return(sprintf(_("More than one '(' is currently not supported. Line : '%s'."),$i_linenum));
304 }
305 if(substr_count($s_linestr,")") >1 ){
306 return(sprintf(_("More than one ')' is currently not supported. Line : '%s'."),$i_linenum));
307 }
308 /* Check if there is an application given */
309 if(empty($tmp[1])){
310 return(sprintf(_("There is no application given in line : '%s'."),$i_linenum));
311 }
312 /* Check if there is an extension given */
313 if(empty($tmp[0])){
314 return(sprintf(_("There is no extension type given in line : '%s'."),$i_linenum));
315 }
317 /* Create extension entry for current line
318 * and add this line to an array that will be inserted
319 * to each database.
320 */
321 $exten = addslashes($tmp[0]);
322 $prio = addslashes($tmp[1]);
323 $app = addslashes(preg_replace("/\(.*\).*$/","",$tmp[2]));
324 $para = addslashes(preg_replace("/^.*\(/","",$tmp[2]));
325 $para = preg_replace("/\).*$/","",$para);
326 $sql.= " ('".$context."','".$exten."','".$prio."','".$app."','".$para."'),";
327 }
329 /* Remove last , from query string */
330 $sql = preg_replace("/,$/","",$sql);
332 /* Save current changes to the database */
333 if($save){
335 /* Macro are spread to each asterisk server */
336 foreach($this->goFonHomeServers as $dn => $cfg){
337 $r_con = @mysql_pconnect($cfg['SERVER'],$cfg['LOGIN'],$cfg['PASSWORD']);
338 $db = @mysql_select_db($cfg['DB'],$r_con);
339 $query = preg_replace("/%TABLENAME%/",$cfg['EXT_TABLE'],$sql);
340 $res = @mysql_query($query,$r_con);
341 if(!$res){
342 gosa_log(@mysql_error($r_con));
343 return(sprintf(_("Insert of new macro failed for server '%s'."),$cfg['SERVER']));
344 }
345 @mysql_close($r_con);
346 }
347 }
348 }
351 /*! Save data to object */
352 function save_object()
353 {
354 if (isset($_POST['displayName'])){
355 plugin::save_object();
357 /* The cn can't be changed if this entry is not new */
358 if($this->dn!= "new"){
359 $this->cn = $this->orig_cn;
360 }
361 }
362 }
365 /*! Check values */
366 function check()
367 {
368 /* Call common method to give check the hook */
369 $message= plugin::check();
371 if(!count($this->goFonHomeServers)){
372 $message[] = _("There must be at least one server with an asterisk database to save this phone macro.");
373 }
375 /* Check if insert/replace is possible and all servers are available */
376 $str = $this->add_to_database(false);
377 if($str){
378 $message[] = $str;
379 }
381 /* Check if cn is already used */
382 if(($this->dn=="new")||($this->orig_cn!=$this->cn)){
383 $ldap = $this->config->get_ldap_link();
384 $ldap->search("(&(objectClass=goFonMacro)(cn=".$this->cn."))",array("cn"));
385 if($ldap->count()>0){
386 $message[]=sprintf(_("The given cn '%s' already exists."),$this->cn);
387 }
388 }
390 /* Check if display name is set */
391 if(empty($this->displayName)){
392 $message[] = _("You must specify the 'Display Name' in order to save this macro");
393 }
394 /* CN is restricted to 20 chars */
395 if(strlen("Makro-".$this->cn)>20 ){
396 $message[]=_("The given cn is too long, to create a Makro entry, maximum 20 chars.");
397 }
399 /* Check permissions */
400 foreach($this->attributes as $attr){
401 if(chkacl($this->acl,"edit")){
402 $str = sprintf( _("Insufficient permissions, can't change attribute '%s' in goFonMacro"),$attr) ;
403 return(array($str));
404 }
405 }
407 /* If this macro is still in use we should not change the visible for user flag to invisible */
408 if(!$this->goFonMacroVisible){
409 $ldap = $this->config->get_ldap_link();
410 $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
411 while ($val = $ldap->fetch()){
412 if(strstr($val['goFonMacro'][0],$this->dn)){
413 $message[] = _("This macro is still in use. It is necessary to mark this macro as visible for users.");
414 return($message);
415 }
416 }
417 }
419 /* Macro content must be smaller than 100 lines */
420 if(count(split("\n",$this->goFonMacroContent))>100){
421 $message[] = _("Makro length must be lower than 100 lines");
422 }
424 return $message;
425 }
428 /*! Remove makro from all given databases
429 * and ldap too.
430 */
431 function remove_from_parent()
432 {
433 $ldap= $this->config->get_ldap_link();
435 /* Skip remove if this macro is still in use */
436 $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
437 while ($val = $ldap->fetch()){
438 if(strstr($val['goFonMacro'][0],$this->dn)){
439 print_red(_("This macro is still in use. To delete this Macro ensure that nobody has selected it."));
440 return false;
441 }
442 }
444 /* Try to remove from database */
445 if(count($this->goFonHomeServers)){
446 $str = $this->remove_from_database(true);
447 if($str){
448 print_red($str);
449 }
450 }else{
451 print_red(_("Could not remove the macro entry from asterisk databases. Please check your asterisk database configurations and remove this entry from database manually, if necessary."));
452 }
454 /* Remove phone macro */
455 $ldap->rmDir($this->dn);
456 show_ldap_error($ldap->get_error(), _("Removing phone macro failed"));
458 /* Delete references to object groups */
459 $ldap->cd ($this->config->current['BASE']);
460 $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
461 while ($ldap->fetch()){
462 $og= new ogroup($this->config, $ldap->getDN());
463 unset($og->member[$this->dn]);
464 $og->save ();
465 show_ldap_error($ldap->get_error(), _("Removing phone macro reverences failed"));
466 }
467 }
470 /*! Save to LDAP */
471 function save()
472 {
473 /* Post checks */
474 $this->execute();
476 plugin::save();
477 unset($this->attrs['base']);
479 /* Try to add entries to databases */
480 $str = $this->add_to_database(true);
481 if($str){
482 print_red($str);
483 }else{
484 /* Write back to ldap */
485 $ldap= $this->config->get_ldap_link();
486 $ldap->cat($this->dn, array('dn'));
487 $a= $ldap->fetch();
489 if (count($a)){
490 $ldap->cd($this->dn);
491 $this->cleanup();
492 $ldap->modify ($this->attrs);
494 $this->handle_post_events("modify");
495 } else {
496 $ldap->cd($this->config->current['BASE']);
497 $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
498 $ldap->cd($this->dn);
499 $ldap->add($this->attrs);
500 $this->handle_post_events("add");
501 }
502 show_ldap_error($ldap->get_error(), _("Saving phone macro failed"));
503 }
504 }
506 }
507 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
508 ?>