Code

Fixed error 'calling function on non object' if we use the browser back button after...
[gosa.git] / include / sieve / class_sieveManagement.inc
1 <?php
2 /*
3    This code is part of GOsa (https://gosa.gonicus.de)
4    Copyright (C) 2003-2007 - Fabian Hickert <hickert@gonicus.de>
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
22 /* The sieve management class displays a list of sieve 
23  *  scripts for the given mail account. 
24  * The account is identified by the parents uid attribute. 
25  *
26  *  $config       The config object
27  *  $dn           The object edited 
28  *  $parent       The parent object that provides the uid attribute 
29  */
30 class sieveManagement extends plugin
31 {
32   var $parent = NULL;
33   var $scripts= array();  
34   var $uattrib = "uid";
35   var $current_script  = -1;
36   var $current_handler = NULL;
37   var $script_to_delete =-1;
38   var $sieve_handle = NULL; 
39   var $Script_Error = "";
40   var $Sieve_Error = "";
41   var $create_script = FALSE;
43   /* To add new elements we need to know 
44    *  Where to the element                  -> add_new_id
45    *  Whould we add above or below this id  -> add_above_below
46    *  What kind of element should we add    -> add_element_type
47    */
48   var $add_new_element    = FALSE;
49   var $add_new_id         = -1;
50   var $add_above_below    = "below";
51   var $add_element_type   = "sieve_comment";
53   /* If this variable is TRUE, this indicates that we have the 
54    *  import dialog opened. 
55    */
56   var $Import_Script = FALSE;
58   /* Initialize the class and load all sieve scripts 
59    *  try to parse them and display errors 
60    */ 
61   function sieveManagement($config,$dn,$parent,$uattrib)
62   {
63     $this->uattrib = $uattrib;
64     $this->parent = $parent;
65     plugin::plugin($config,$dn);
67     /* Get sieve */
68     if(!$this->sieve_handle = $this->get_sieve()){
69       print_red(
70         sprintf(
71           _("Can't log into SIEVE server. Server says '%s'."),
72           to_string($this->Sieve_Error)));
73       return;
74     }
77     /* Get all sieve scripts names */
78     if($this->sieve_handle->sieve_listscripts()){
79       if (is_array($this->sieve_handle->response)){
80         foreach($this->sieve_handle->response as $key => $name){
82           $data = array();
83           $data['NAME'] = $name;
85           if($key == "ACTIVE" && $key === "ACTIVE"){
86             $data['ACTIVE'] = TRUE;
87           }else{
88             $data['ACTIVE'] = FALSE;
89           }
90           $this->scripts[] = $data;          
91         }
92       } 
93     }
95     /* Get script contents */
96     foreach($this->scripts as $key => $script){
97       $p = new My_Parser($this);
98       $this->sieve_handle->sieve_getscript($script['NAME']);
100       $script = "";
101       foreach($this->sieve_handle->response as $line){
102         $script.=$line;
103       }
105       $this->scripts[$key]['IS_NEW'] = FALSE;;
106       $this->scripts[$key]['SCRIPT'] = $script;
107       $this->scripts[$key]['ORIG_SCRIPT'] = $script;
108       $this->scripts[$key]['MSG']   = "";
109       $ret = $p->parse($script);
110       if(!$ret){
111         $this->scripts[$key]['STATUS']   = FALSE;
112         $this->scripts[$key]['MODE']    = "Source";
113         $this->scripts[$key]['MSG'] = _("Parse failed")."<font color='red'>".$p->status_text."</font>";
114       }else{
115         $this->scripts[$key]['STATUS']   = TRUE;
116         $this->scripts[$key]['MODE']    = "Structured";
117         $this->scripts[$key]['MSG'] = _("Parse successful");
118       }
119       $this->scripts[$key]['PARSER'] = $p;
120       $this->scripts[$key]['EDITED'] = FALSE;
121     }
122     $this->sieve_handle = $this->sieve_handle;
123   }
126   /* Return a sieve class hanlde,
127    *  false if login fails
128    */
129   function get_sieve()
130   {
131     
132     /* Connect to sieve class and try to get all available sieve scripts */
133     if(isset($this->config->data['SERVERS']['IMAP'][$this->parent->gosaMailServer])){
134       $cfg=  $this->config->data['SERVERS']['IMAP'][$this->parent->gosaMailServer];
135       $this->Sieve_Error = "";
137       $uattrib = $this->uattrib;
139       /* Log into the mail server */
140       $this->sieve_handle= new sieve(
141           $cfg["sieve_server"], 
142           $cfg["sieve_port"], 
143           $this->parent->$uattrib, 
144           $cfg["password"], 
145           $cfg["admin"]);
147       /* Try to login */
148       if (!$this->sieve_handle->sieve_login()){
149         $this->Sieve_Error = $this->sieve_handle->error_raw;
150         return(FALSE);
151       }
152       return($this->sieve_handle);
153     }else{
154       $this->Sieve_Error = sprintf(_("The specified mail server '%s' does not exist within the GOsa configuration."),
155         $this->parent->gosaMailServer);
156       return(FALSE);
157     }
158   }
161   /* Handle sieve list 
162    */
163   function execute()
164   {
165     /***************
166      * Create a new Script 
167      ***************/
169     /* Force opening the add script dialog */
170     if(isset($_POST['create_new_script'])){
171       $this->create_script = TRUE;
172     }
174     /* Close add script dialog, without adding a new one */
175     if(isset($_POST['create_script_cancel'])){
176       $this->create_script = FALSE;
177     }
179     /* Display create script dialog 
180      *  handle posts, display warnings if specified 
181      *  name is not useable. 
182      * Create a new script with given name
183      */
184     if($this->create_script){
185     
186       /* Set initial name or used posted name if available */
187       $name = "";
188       if(isset($_POST['NewScriptName'])){
189         $name = trim($_POST['NewScriptName']);
190       }
191  
192       /* Check given name */ 
193       $err = "";
195       /* Is given name in lower case characters ? */
196       if(isset($_POST['create_script_save'])){
197         if(!strlen($name)){
198           $err = _("You should specify a name for your new script.");
199         }
200         /* Is given name in lower case characters ? */
201         if($name != strtolower($name)){
202           $err = _("Only lower case names are allowed here.");
203         }
205         /* Only chars are allowed here */
206         if(preg_match("/[^a-z]/i",$name)){
207           $err = _("Only a-z are allowed in script names.");
208         }
210         $tmp = $this->get_used_script_names();
211         if(in_array_ics($name,$tmp)){
212           $err =_("The specified name is already in use.");
213         }
214       }
216       /* Create script if everything is ok */
217       if($this->create_script && isset($_POST['create_script_save']) && $err == "" ){
219         /* Close dialog */
220         $this->create_script = FALSE;
222         /* Script contents to use */
223         $script = "/*New script */".
224                   "stop;";
226         /* Create a new parser and initialize default values */
227         $p = new My_Parser($this);
228         $ret = $p->parse($script);
229         $sc['SCRIPT'] = $script;
230         $sc['ORIG_SCRIPT'] = $script;
231         $sc['IS_NEW'] = TRUE;
232         $sc['MSG']   = "";
233         if(!$ret){
234           $sc['STATUS']   = FALSE;
235           $sc['MODE']    = "Source";
236           $sc['MSG'] = _("Parse failed")."<font color='red'>".$p->status_text."</font>";
237         }else{
238           $sc['STATUS']   = TRUE;
239           $sc['MODE']    = "Structured";
240           $sc['MSG'] = _("Parse successful");
241         }
242         $sc['PARSER'] = $p;
243         $sc['EDITED'] = TRUE;
244         $sc['ACTIVE'] = FALSE;
245         $sc['NAME']   = $name;
246       
247         /* Add script */
248         $this->scripts[$name] = $sc;
249       }else{
250       
251         /* Display dialog to enter new script name */
252         $smarty = get_smarty();
253         $smarty->assign("NewScriptName",$name);
254         $smarty->assign("Error",$err);
255         return($smarty->fetch(get_template_path("templates/create_script.tpl",TRUE,dirname(__FILE__))));
256       }
257     }
260     /*************
261      * Handle several posts 
262      *************/
264     $once = TRUE;
265     foreach($_POST as $name => $value){
267       /* Edit script requested */
268       if(preg_match("/^editscript_/",$name) && $once && !$this->current_handler){
269         $script = preg_replace("/^editscript_/","",$name);
270         $script = preg_replace("/_(x|y)/","",$script);
271         $once = FALSE;
273         $this->current_script = $script;
274         $this->current_handler = $this->scripts[$script]['PARSER'];
275         $this->scripts[$script]['SCRIPT_BACKUP'] = $this->scripts[$script]['SCRIPT'];
276       }
278       /* remove script requested */
279       if($this->parent->acl_is_writeable("sieveManagement") && preg_match("/^delscript_/",$name) && $once && !$this->current_handler){
280         $script = preg_replace("/^delscript_/","",$name);
281         $script = preg_replace("/_(x|y)/","",$script);
282         $once = FALSE;
283         $this->script_to_delete = $script;  
284       }
286       /* Activate script */
287       if($this->parent->acl_is_writeable("sieveManagement") && preg_match("/^active_script_/",$name) && $once && !$this->current_handler){
288         $script = preg_replace("/^active_script_/","",$name);
289         $script = preg_replace("/_(x|y)/","",$script);
290         $once = FALSE;
292         /* We can only activate existing scripts */
293         if(!$this->scripts[$script]['IS_NEW']){
295           /* Get sieve */
296           if(!$this->sieve_handle = $this->get_sieve()){
297             print_red(
298                 sprintf(
299                   _("Can't log into SIEVE server. Server says '%s'."),
300                   to_string($this->Sieve_Error)));
301           }
303           /* Try to activate the given script and update 
304            *  class script array. 
305            */
306           if(!$this->sieve_handle->sieve_setactivescript($this->scripts[$script]['NAME'])){
307             print_red(sprintf(_("Can't activate sieve script on server. Server says '%s'."),to_string($this->sieve_handle->error_raw)));
308           }else{
309             foreach($this->scripts as $key => $data){
310               if($key == $script){
311                 $this->scripts[$key]['ACTIVE'] = TRUE;
312               }else{
313                 $this->scripts[$key]['ACTIVE'] = FALSE;
314               }
315             }
316           }
317         }
318       }
319     }
321     
322     /*************
323      * Remove script handling 
324      *************/
326     /* Remove aborted */
327     if(isset($_POST['delete_cancel'])){
328       $this->script_to_delete = -1;
329     }
331     /* Remove confirmed */
332     if($this->parent->acl_is_writeable("sieveManagement") && isset($_POST['delete_script_confirm'])){
334       $script = $this->scripts[$this->script_to_delete];
336       /* Just remove from array if it is a new script */
337       if($script['IS_NEW']){
338         unset($this->scripts[$this->script_to_delete]);
339       }else{
341         /* Get sieve */
342         if(!$this->sieve_handle = $this->get_sieve()){
343           print_red(
344               sprintf(
345                 _("Can't log into SIEVE server. Server says '%s'."),
346                 to_string($this->Sieve_Error)));
347         }
349         if(!$this->sieve_handle->sieve_deletescript($this->scripts[$this->script_to_delete]['NAME'])){
350           print_red(sprintf(_("Can't remove sieve script from server. Server says '%s'."),to_string($this->sieve_handle->error_raw)));
351         }else{
352           unset($this->scripts[$this->script_to_delete]);
353         }
354       }
355       $this->script_to_delete = -1;
356     }
358     /* Display confirm dialog */
359     if($this->script_to_delete != -1){
360       $smarty = get_smarty();
361       $smarty->assign("Warning",
362           sprintf(_("You are going to remove the sieve script '%s' from your mail server."),
363             $this->scripts[$this->script_to_delete]['NAME']));
364       return($smarty->fetch(get_template_path("templates/remove_script.tpl",TRUE,dirname(__FILE__))));
365     }
368     /**************
369      * Save script changes 
370      **************/
372     /* Abort saving */
373     if(isset($_POST['cancel_sieve_changes'])){
374       $tmp = $this->scripts[$this->current_script]['SCRIPT_BACKUP'];
375       $this->scripts[$this->current_script]['SCRIPT'] = $tmp;
376       $this->scripts[$this->current_script]['PARSER']->parse($tmp);
377       $this->current_handler = NULL;
378     }
380     /* Save currently edited sieve script. */
381     if($this->parent->acl_is_writeable("sieveManagement") && 
382        isset($_POST['save_sieve_changes']) && 
383        is_object($this->current_handler)){
384       $chk = $this->current_handler->check();
385       if(!count($chk)){
387         $sc = $this->scripts[$this->current_script]['SCRIPT'];
388         $p = new My_Parser($this);
389         if($p -> parse($sc)){
391           if($this->scripts[$this->current_script]['MODE'] == "Source-Only"){
392             $this->scripts[$this->current_script]['MODE'] = "Source";
393           }
394   
395           $this->scripts[$this->current_script]['PARSER'] = $p;
396           $this->scripts[$this->current_script]['EDITED'] = TRUE;
397           $this->scripts[$this->current_script]['STATUS'] = TRUE;
398           $this->scripts[$this->current_script]['MSG'] = _("Edited");
399           $this->current_handler = NULL;
400         }else{
401           print_red($p->status_text);;
402         }
403       }else{
404         foreach($chk as $msgs){
405           print_red(sprintf(_("Please fix all errors before saving. Last error was : %s"),$msgs));
406         }
407       }
408     }
411     /*************
412      * Display edit dialog 
413      *************/
415     /* Display edit dialog, depending on Mode display different uis
416      */
417     if($this->current_handler){
419         if(isset($_POST['Import_Script'])){
420           $this->Import_Script = TRUE;
421         }
423         if(isset($_POST['Import_Script_Cancel'])){
424           $this->Import_Script = FALSE;
425         }
427         if(isset($_POST['Import_Script_Save']) && isset($_FILES['Script_To_Import'])){
429           $file     = $_FILES['Script_To_Import'];
431           if($file['size'] == 0){
432             print_red(_("Specified file seams to empty."));
433           }elseif(!file_exists($file['tmp_name'])){
434             print_red(_("Upload failed, somehow nothing was uploaded or the temporary file can't be accessed."));
435           }elseif(!is_readable ($file['tmp_name'])){
436             print_red(sprintf(_("Can't open file '%s' to read uploaded file contents."),$file['tmp_name']));
437           }else{
438             
439             
440  
441             $contents = file_get_contents($file['tmp_name']);
442            
443             $this->scripts[$this->current_script]['SCRIPT'] = $contents;
444             if(!$this->current_handler->parse($contents)){
445               $this->scripts[$this->current_script]['MODE'] = "Source";
446             }else{
447               $this->scripts[$this->current_script]['MODE'] = "Structured";
448             }
449             $this->Script_Error = "";
450             $this->Import_Script = FALSE;
451           }
452         }
454         if($this->Import_Script){
455           $smarty = get_smarty();
456           $str = $smarty->fetch(get_template_path("templates/import_script.tpl",TRUE,dirname(__FILE__)));
457           return($str);
458         }
459   
461         /* Create dump of current sieve script */
462         if(isset($_POST['Save_Copy'])){
464             /* force download dialog */
465             header("Content-type: application/tiff\n");
466             if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) ||
467                     preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
468                 header('Content-Disposition: filename="dump.script"');
469             } else {
470                 header('Content-Disposition: attachment; filename="dump.script"');
471             }
472             header("Content-transfer-encoding: binary\n");
473             header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
474             header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
475             header("Cache-Control: no-cache");
476             header("Pragma: no-cache");
477             header("Cache-Control: post-check=0, pre-check=0");
478             echo $this->scripts[$this->current_script]['SCRIPT'];
479             exit();
480         }
483       /****
484        * Add new element to ui
485        ****/
487       /* Abort add dialog */ 
488       if(isset($_POST['select_new_element_type_cancel'])){
489         $this->add_new_element = FALSE;
490       }
492       /* Add a new element */
493       if($this->add_new_element){
495         $element_types= array(
496             "sieve_keep"      => _("Keep"),
497             "sieve_comment"   => _("Comment"),
498             "sieve_fileinto"  => _("File into"),
499             "sieve_keep"      => _("Keep"),
500             "sieve_discard"   => _("Discard"),
501             "sieve_redirect"  => _("Redirect"),
502             "sieve_reject"    => _("Reject"),
503             "sieve_require"   => _("Require"),
504             "sieve_stop"      => _("Stop"),
505             "sieve_vacation"  => _("Vacation message"),
506             "sieve_if"        => _("If"));
509         /* Element selected */
510         if(isset($_POST['element_type']) && isset($element_types[$_POST['element_type']]) 
511            || isset($_POST['element_type']) &&in_array($_POST['element_type'],array("sieve_else","sieve_elsif"))){
512           $this->add_element_type = $_POST['element_type'];
513         }
515         /* Create new element and add it to
516          *  the selected position 
517          */
518         if(isset($_POST['select_new_element_type'])){
519           if($this->add_new_element_to_current_script($this->add_element_type,$this->add_new_id,$this->add_above_below)){
520             $this->add_new_element = FALSE;
521           }else{
522             print_red(_("Failed to add new element."));
523           }
524         }
525       }
527       /* Only display select dialog if it is necessary */
528       if($this->add_new_element){
529         $smarty = get_smarty();
530     
531         $add_else_elsif = FALSE;
533         /* Check if we should add else/elsif to the select box 
534          *  or not. We can't add else twice!.
535          */
536         if($this->add_above_below == "below"){
538           /* Get posistion of the current element 
539            */
540           foreach($this->current_handler->tree_->pap as $key => $obj){
541         
542             if($obj->object_id == $this->add_new_id && in_array(get_class($obj),array("sieve_if","sieve_elsif"))){
543   
544               /* Get block start/end */
545               $end_id = $this->current_handler->tree_->get_block_end($key);
546               $else_found = FALSE;
547               $elsif_found = FALSE;
548           
549               /* Check if there is already an else in this block 
550                */
551               for($i =  $key ; $i < $end_id ; $i ++){
552                 if(get_class($this->current_handler->tree_->pap[$i]) == "sieve_else"){
553                   $else_found = TRUE;
554                 }
555                 if(get_class($this->current_handler->tree_->pap[$i]) == "sieve_elsif"){
556                   $elsif_found = TRUE;
557                 }
558               }
559   
560               /* Only allow adding 'else' if there is currently 
561                *  no 'else' statement. And don't allow adding 
562                *  'else' before 'elseif'
563                */ 
564               if(!$else_found && (!(get_class($obj) == "sieve_if" && $elsif_found))){
565                 $element_types['sieve_else'] = _("Else");
566               }
567               $element_types['sieve_elsif'] = _("Else if");
568             }
569           }
570         }
572         $smarty->assign("element_types",$element_types );
573         $smarty->assign("element_type",$this->add_element_type);
574         $str = $smarty->fetch(get_template_path("templates/add_element.tpl",TRUE,dirname(__FILE__)));
575         return($str);
576       }
580       /****************
581        * Handle test posts 
582        ****************/
584       /* handle some special posts from test elements 
585        */
586       foreach($_POST as $name => $value){
587         if(preg_match("/^Add_Test_Object_/",$name)) {
588           $name = preg_replace("/^Add_Test_Object_/","",$name);
589           $name = preg_replace("/_(x|y)$/","",$name);
591           $test_types_to_add = array(
592               "address" =>_("Address"),
593               "header"  =>_("Header"),
594               "envelope"=>_("Envelope"),
595               "size"    =>_("Size"),
596               "exists"  =>_("Exists"),
597               "allof"   =>_("All of"),
598               "anyof"   =>_("Any of"),
599               "true"    =>_("True"),
600               "false"   =>_("False"));
602           $smarty = get_smarty();
603           $smarty->assign("ID",$name);
604           $smarty->assign("test_types_to_add",$test_types_to_add);
605           $ret = $smarty->fetch(get_template_path("templates/select_test_type.tpl",TRUE,dirname(__FILE__)));
606           return($ret);
607         }
608       }
610       $current = $this->scripts[$this->current_script];
612       /* Create html results */
613       $smarty = get_smarty();
614       $smarty->assign("Mode",$current['MODE']);
615       if($current['MODE'] == "Structured"){
616         $smarty->assign("Contents",$this->current_handler->tree_->execute());
617       }else{
618         $smarty->assign("Contents",$current['SCRIPT']);
619       }
620       $smarty->assign("Script_Error",$this->Script_Error);
621       $ret = $smarty->fetch(get_template_path("templates/edit_frame_base.tpl",TRUE,dirname(__FILE__)));
622       return($ret);
623     }
626     /* Create list of available sieve scripts 
627      */
628     $List = new divSelectBox("sieveManagement");
629     foreach($this->scripts as $key => $script){
630   
631       $edited =  $script['EDITED'];
632       $active =  $script['ACTIVE'];
633       
634       $field1 = array("string" => "&nbsp;",
635                       "attach" => "style='width:20px;'");  
636       if($active){
637         $field1 = array("string" => "<img src='images/true.png' alt='"._("Active")."' 
638                                       title='"._("This script is marked as active")."'>",
639                         "attach" => "style='width:20px;'");  
640       }
641       $field2 = array("string" => $script['NAME']);  
642       $field3 = array("string" => $script['MSG']);
643       $field4 = array("string" => _("Script length")."&nbsp;:&nbsp;".strlen($script['SCRIPT']));
645       if($this->parent->acl_is_writeable("sieveManagement")){
646         $del = "<input type='image' name='delscript_".$key."' src='images/edittrash.png'
647                   title='"._("Remove script")."'>";
648       }else{
649         $del = "<img src='images/empty' alt=' '>";
650       }
652       if($active || $script['IS_NEW'] || !$this->parent->acl_is_writeable("sieveManagement")){
653         $activate = "<img src='images/empty' alt=' '>";
654       }else{
655         $activate = "<input type='image' name='active_script_".$key."' src='images/true.png'
656                        title='"._("Activate script")."'>";
657       }
659       $field6 = array("string" => $activate."<input type='image' name='editscript_".$key."' src='images/edit.png'
660                         title='"._("Edit script")."'>".$del,
661                       "attach" => "style='border-right:0px; width:70px;'");
662       $List ->AddEntry(array($field1,$field2,$field3,$field4,$field6)); 
663     }
664   
665     $display ="<h2>Sieve script management</h2>";
666     $display .= _("Be careful. All your changes will be saved directly to sieve, if you use the save button below.");
667     $display .= "<br><input type='submit' name='create_new_script' value='"._("Create new script")."'>";
668     $display .=  $List->DrawList();
669     
670     $display .= "<p style=\"text-align:right\">\n";
671     $display .= "<input type=submit name=\"sieve_finish\" style=\"width:80px\" value=\""._("Ok")."\">\n";
672     $display .= "&nbsp;\n";
673     $display .= "<input type=submit name=\"sieve_cancel\" value=\""._("Cancel")."\">\n";
674     $display .= "</p>";
675     return($display);;
676   }
679   /* Add a new element to the currently opened script editor.
680    * The insert position is specified by 
681    */
682   function add_new_element_to_current_script($type,$id,$position)
683   {
684     /* Test given data */
685     if(!in_array_ics($position,array("above","below"))){
686       trigger_error("Can't add new element with \$position=".$position.". Only 'above','below' are allowed here.");
687       return(FALSE);
688     }
689     if(!is_numeric($id)){
690       trigger_error("Can't add new element, given id is not numeric.");
691       return(FALSE);
692     }
693     $tmp = get_declared_classes();  
694     if(!in_array($type,$tmp)){
695       trigger_error("Can't add new element, given \$class=".$class." does not exists.");
696       return(FALSE);
697     }
698     if(!is_object($this->current_handler) || get_class($this->current_handler) != "My_Parser"){
699       trigger_error("Can't add new element, there is no valid script editor opened.");
700       return(FALSE);
701     }
703     /* Create elements we should add 
704      * -Some element require also surrounding block elements
705      */
706     $parent = $this->current_handler->tree_;
707     if($this->add_element_type == "sieve_if"){
708       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
709       $ele[] = new sieve_block_start(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
710       $ele[] = new sieve_block_end(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
711     }elseif($this->add_element_type == "sieve_else"){
712       $ele[] = new sieve_block_end(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
713       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
714       $ele[] = new sieve_block_start(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
715     }elseif($this->add_element_type == "sieve_elsif"){
716       $ele[] = new sieve_block_end(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
717       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
718       $ele[] = new sieve_block_start(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
719     }else{
720       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
721     }
723     /* Get index of the element identified by object_id == $id; 
724      */
725     $index = -1;
726     $data = $this->current_handler->tree_->pap;
727     foreach($data as $key => $obj){
728       if($obj->object_id == $id && $index==-1){
729         $index = $key;
730       }
731     }
733     /* Tell to user that we couldn't find the given object 
734      *  so we can't add an element. 
735      */
736     if($index == -1 ){
737       trigger_error("Can't add new element, specified \$id=".$id." could not be found in object tree.");
738       return(FALSE);
739     }
741     /* We have found the specified object_id 
742      *  and want to detect the next free position 
743      *  to insert the new element.
744      */
745     if($position == "above"){
746       $direction ="up";
747       $next_free = $this->current_handler->tree_->_get_next_free_move_slot($index,$direction,TRUE);
748     }else{
749       $direction = "down";
750       $next_free = $this->current_handler->tree_->_get_next_free_move_slot($index,$direction,TRUE);
751     }
752     /* This is extremly necessary, cause some objects 
753      *  updates the tree objects ... Somehow i should change this ... 
754      */
755     $data = $this->current_handler->tree_->pap;
756     $start = $end = array();
758     if($position == "above"){
759       $start = array_slice($data,0,$next_free);
760       $end   = array_slice($data,$next_free);
761     }else{
762       $start = array_slice($data,0,$next_free+1);
763       $end   = array_slice($data,$next_free+1);
764     }
766     $new = array();
767     foreach($start as $obj){
768       $new[] = $obj;
769     }
770     foreach($ele as $el){
771       $new[] = $el;
772     }
773     foreach($end as $obj){
774       $new[] = $obj;
775     }
776     $data= $new;
777     $this->current_handler->tree_->pap = $data;
778     return(TRUE);
779   }
783   function save_object()
784   {
785     if($this->current_handler){
787       if(isset($_GET['Add_Object_Top_ID'])){
788         $this->add_new_element    = TRUE;
789         $this->add_new_id         = $_GET['Add_Object_Top_ID'];
790         $this->add_above_below    = "above";
791       }  
793       if(isset($_GET['Add_Object_Bottom_ID'])){
794         $this->add_new_element    = TRUE;
795         $this->add_new_id         = $_GET['Add_Object_Bottom_ID'];
796         $this->add_above_below    = "below";
797       }  
799       if(isset($_GET['Remove_Object_ID'])){
800         $found_id = -1;
801         foreach($this->current_handler->tree_->pap as $key => $element){
802           if($element->object_id == $_GET['Remove_Object_ID']){
803             $found_id = $key;
804           }
805         }
806         if($found_id != -1 ){
807           $this->current_handler->tree_->remove_object($found_id);  
808         }
809       }  
810  
811       if(isset($_GET['Move_Up_Object_ID'])){
812         $found_id = -1;
813         foreach($this->current_handler->tree_->pap as $key => $element){
814           if($element->object_id == $_GET['Move_Up_Object_ID']){
815             $found_id = $key;
816           }
817         }
818         if($found_id != -1 ){
819           $this->current_handler->tree_->move_up_down($found_id,"up");
820         }
821       }  
822  
823       if(isset($_GET['Move_Down_Object_ID'])){
824         $found_id = -1;
825         foreach($this->current_handler->tree_->pap as $key => $element){
826           if($element->object_id == $_GET['Move_Down_Object_ID']){
827             $found_id = $key;
828           }
829         }
830         if($found_id != -1 ){
831           $this->current_handler->tree_->move_up_down($found_id,"down");
832         }
833       }  
834   
836       /* Check if there is an add object requested 
837        */
838       $data = $this->current_handler->tree_->pap;
839       $once = TRUE;
840       foreach($_POST as $name => $value){
841         foreach($data as $key => $obj){
842           if(isset($obj->object_id) && preg_match("/^Add_Object_Top_".$obj->object_id."_/",$name) && $once){
843             $once = FALSE;
844             $this->add_new_element    = TRUE;
845             $this->add_new_id         = $obj->object_id;
846             $this->add_above_below    = "above";
847           }
848           if(isset($obj->object_id) && preg_match("/^Add_Object_Bottom_".$obj->object_id."_/",$name) && $once){
849             $once = FALSE;
850             $this->add_new_element    = TRUE;
851             $this->add_new_id         = $obj->object_id;
852             $this->add_above_below    = "below";
853           }
854         
855           if(isset($obj->object_id) && preg_match("/^Remove_Object_".$obj->object_id."_/",$name) && $once){
856             $once = FALSE;
857             $this->current_handler->tree_->remove_object($key);
858           }
859           if(isset($obj->object_id) && preg_match("/^Move_Up_Object_".$obj->object_id."_/",$name) && $once){
860             $this->current_handler->tree_->move_up_down($key,"up");
861             $once = FALSE;
862           }
863           if(isset($obj->object_id) && preg_match("/^Move_Down_Object_".$obj->object_id."_/",$name) && $once){
864             $this->current_handler->tree_->move_up_down($key,"down");
865             $once = FALSE;
866           }
867         }
868       }
870       /* Skip Mode changes and Parse tests 
871        *  if we are currently in a subdialog 
872        */
874       $this->current_handler->save_object();
875       $Mode = $this->scripts[$this->current_script]['MODE'];
876       $skip_mode_change = false;
877       if(in_array($Mode,array("Source-Only","Source"))){
878         if(isset($_POST['script_contents'])){
879           $sc = stripslashes($_POST['script_contents']);
880           $this->scripts[$this->current_script]['SCRIPT'] = $sc;
881           $p = new My_Parser($this);
882           if($p -> parse($sc)){
883             $this->Script_Error = "";
884           } else {
885             $this->Script_Error = $p->status_text;
886             $skip_mode_change = TRUE;
887           }
888         }
889       }
890       if(in_array($Mode,array("Structured"))){
891         $sc = $this->current_handler->get_sieve_script();
892         $this->scripts[$this->current_script]['SCRIPT'] = $sc;
893         $p = new My_Parser($this);
894         if($p -> parse($sc)){
895           $this->Script_Error = "";
896         } else {
897           $this->Script_Error = $p->status_text;
898           $skip_mode_change = TRUE;
899         }
900       }
901       if(!$skip_mode_change){
902         if($this->scripts[$this->current_script]['MODE'] != "Source-Only"){
903           $old_mode = $this->scripts[$this->current_script]['MODE'];
904           if(isset($_POST['View_Source'])){
905             $this->scripts[$this->current_script]['MODE'] = "Source";
906           }
907           if(isset($_POST['View_Structured'])){
908             $this->scripts[$this->current_script]['MODE'] = "Structured";
909           }
910           $new_mode = $this->scripts[$this->current_script]['MODE'];
912           if($old_mode != $new_mode){
914             $sc = $this->scripts[$this->current_script]['SCRIPT'];
915             $p = new My_Parser($this);
917             if($p -> parse($sc)){
918               $this->current_handler->parse($sc);
919               $this->Script_Error = "";
920             } else {
921               $this->Script_Error = $p->status_text;
922             }
923           } 
924         }
925       }
926     }
927   }
929   
930   function get_used_script_names()
931   {
932     $ret = array();
933     foreach($this->scripts as $script){
934       $ret[] = $script['NAME'];
935     }
936     return($ret);
937   }
941   function save()
942   {
943     /* Get sieve */
944     if(!$this->sieve_handle = $this->get_sieve()){
945       print_red(
946           sprintf(
947             _("Can't log into SIEVE server. Server says '%s'."),
948             to_string($this->Sieve_Error)));
949     }
951     $everything_went_fine = TRUE;
953     foreach($this->scripts as $key => $script){
954       if($script['EDITED']){
955         $data = $this->scripts[$key]['SCRIPT'];
956         if(!$this->sieve_handle->sieve_sendscript($script['NAME'], addcslashes ($data,"\\"))){
957           gosa_log("Failed to save sieve script named '".$script['NAME']."': ".to_string($this->sieve_handle->error_raw));
958           $everything_went_fine = FALSE;
959           print_red(to_string($this->sieve_handle->error_raw));
960           $this->scripts[$key]['MSG'] = "<font color='red'>".
961                                            _("Failed to save sieve script").": ".
962                                            to_string($this->sieve_handle->error_raw).
963                                            "</font>";
964         }
965       }
966     }
967     return($everything_went_fine);
968   }
970 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
971 ?>