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");
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'];
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 }
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 ";
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 # }
289 /* Multiple () are not supproted currently ... */
290 if(substr_count($s_linestr,"(") >1 ){
291 return(sprintf(_("More than one '(' is currently not supported. Line : '%s'."),$i_linenum));
292 }
293 if(substr_count($s_linestr,")") >1 ){
294 return(sprintf(_("More than one ')' is currently not supported. Line : '%s'."),$i_linenum));
295 }
297 /* Create extension entry for current line
298 * and add this line to an array that will be inserted
299 * to each database.
300 */
301 $exten = addslashes($tmp[0]);
302 $prio = addslashes($tmp[1]);
303 $app = addslashes(preg_replace("/\(.*\).*$/","",$tmp[2]));
304 $para = addslashes(preg_replace("/^[^(]*\((.*)\)[^)]*$/", "$1", $tmp[2]));
305 $sql.= " ('".$context."','".$exten."','".$prio."','".$app."','".$para."'),";
306 }
308 /* Remove last , from query string */
309 $sql = preg_replace("/,$/","",$sql);
311 /* Save current changes to the database */
312 if($save){
314 /* Macro are spread to each asterisk server */
315 foreach($this->goFonHomeServers as $dn => $cfg){
316 $r_con = @mysql_pconnect($cfg['SERVER'],$cfg['LOGIN'],$cfg['PASSWORD']);
317 $db = @mysql_select_db($cfg['DB'],$r_con);
318 $query = preg_replace("/%TABLENAME%/",$cfg['EXT_TABLE'],$sql);
319 $res = @mysql_query($query,$r_con);
320 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
321 if(!$res){
322 gosa_log(@mysql_error($r_con));
323 return(sprintf(_("Insert of new macro failed for server '%s'."),$cfg['SERVER']));
324 }
325 @mysql_close($r_con);
326 }
327 }
328 }
331 /*! Save data to object */
332 function save_object()
333 {
334 if (isset($_POST['displayName'])){
335 plugin::save_object();
337 /* The cn can't be changed if this entry is not new */
338 if(!$this->is_new){
339 $this->cn = $this->orig_cn;
340 }
342 if(isset($_POST['goFonMacroVisible'])) {
343 $this->goFonMacroVisible= 1 ;
344 }else {
345 $this->goFonMacroVisible= 0 ;
346 }
347 }
348 }
351 /*! Check values */
352 function check()
353 {
354 /* Call common method to give check the hook */
355 $message= plugin::check();
357 if(!count($this->goFonHomeServers)){
358 $message[] = _("There must be at least one server with an asterisk database to save this phone macro.");
359 }
361 /* Check if insert/replace is possible and all servers are available */
362 $str = $this->add_to_database(false);
363 if($str){
364 $message[] = $str;
365 }
367 /* Check if cn is already used */
368 if(($this->dn=="new")||($this->orig_cn!=$this->cn)){
369 $ldap = $this->config->get_ldap_link();
370 $ldap->search("(&(objectClass=goFonMacro)(cn=".$this->cn."))",array("cn"));
371 if($ldap->count()>0){
372 $message[]=sprintf(_("The given cn '%s' already exists."),$this->cn);
373 }
374 }
376 /* Check if display name is set */
377 if(empty($this->displayName)){
378 $message[] = _("You must specify the 'Display Name' in order to save this macro");
379 }
380 /* CN is restricted to 20 chars */
381 if(strlen("Makro-".$this->cn)>20 ){
382 $message[]=_("The given cn is too long, to create a Makro entry, maximum 20 chars.");
383 }
385 /* Check permissions */
386 foreach($this->attributes as $attr){
387 if(chkacl($this->acl,"edit")){
388 $str = sprintf( _("Insufficient permissions, can't change attribute '%s' in goFonMacro"),$attr) ;
389 return(array($str));
390 }
391 }
393 /* If this macro is still in use we should not change the visible for user flag to invisible */
394 if(!$this->goFonMacroVisible){
395 $ldap = $this->config->get_ldap_link();
396 $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
397 while ($val = $ldap->fetch()){
398 if(strstr($val['goFonMacro'][0],$this->dn)){
399 $message[] = _("This macro is still in use. It is necessary to mark this macro as visible for users.");
400 return($message);
401 }
402 }
403 }
404 return $message;
405 }
408 /*! Remove makro from all given databases
409 * and ldap too.
410 */
411 function remove_from_parent()
412 {
413 $ldap= $this->config->get_ldap_link();
415 /* Skip remove if this macro is still in use */
416 $res = $ldap->search("(&(objectClass=goFonAccount)(objectClass=gosaAccount)(goFonMacro=*))", array("goFonMacro"));
417 while ($val = $ldap->fetch()){
418 if(strstr($val['goFonMacro'][0],$this->dn)){
419 print_red(_("This macro is still in use. To delete this Macro ensure that nobody has selected it."));
420 return false;
421 }
422 }
424 /* Try to remove from database */
425 if(count($this->goFonHomeServers)){
426 $str = $this->remove_from_database(true);
427 if($str){
428 print_red($str);
429 return false;
430 }
431 }else{
432 print_red(_("Could not remove the macro entry from asterisk databases. Please check your asterisk database configurations."));
433 return false;
434 }
436 /* Remove phone macro */
437 $ldap->rmDir($this->dn);
438 show_ldap_error($ldap->get_error(), _("Removing phone macro failed"));
440 /* Delete references to object groups */
441 $ldap->cd ($this->config->current['BASE']);
442 $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".@LDAP::prepare4filter($this->dn)."))", array("cn"));
443 while ($ldap->fetch()){
444 $og= new ogroup($this->config, $ldap->getDN());
445 unset($og->member[$this->dn]);
446 $og->save ();
447 show_ldap_error($ldap->get_error(), _("Removing phone macro reverences failed"));
448 }
449 }
452 /*! Save to LDAP */
453 function save()
454 {
455 plugin::save();
456 unset($this->attrs['base']);
458 /* Try to add entries to databases */
459 $str = $this->add_to_database(true);
460 if($str){
461 print_red($str);
462 }else{
463 /* Write back to ldap */
464 $ldap= $this->config->get_ldap_link();
465 $ldap->cat($this->dn, array('dn'));
466 $a= $ldap->fetch();
468 if (count($a)){
469 $ldap->cd($this->dn);
470 $this->cleanup();
471 $ldap->modify ($this->attrs);
473 $this->handle_post_events("modify");
474 } else {
475 $ldap->cd($this->config->current['BASE']);
476 $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
477 $ldap->cd($this->dn);
478 $ldap->add($this->attrs);
479 $this->handle_post_events("add");
480 }
481 show_ldap_error($ldap->get_error(), _("Saving phone macro failed"));
482 }
483 }
485 }
486 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
487 ?>