Code

Use a template for the management dialog.
[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 add 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     /* Check given parameter */
64     if(!isset($parent->$uattrib)){
65       trigger_error("Sieve Management implementation error. Parameter 4 must be part of the given parent element.");
66     }
68     $this->uattrib = $uattrib;
69     $this->parent = $parent;
70     plugin::plugin($config,$dn);
72     /* Get sieve */
73     if(!$this->sieve_handle = $this->get_sieve()){
74 #      print_red(
75  #       sprintf(
76   #        _("Can't log into SIEVE server. Server says '%s'."),
77    #       to_string($this->Sieve_Error)));
78       return;
79     }
82     /* Get all sieve scripts names */
83     if($this->sieve_handle->sieve_listscripts()){
84       if (is_array($this->sieve_handle->response)){
85         foreach($this->sieve_handle->response as $key => $name){
87           $data = array();
88           $data['NAME'] = $name;
90           if($key == "ACTIVE" && $key === "ACTIVE"){
91             $data['ACTIVE'] = TRUE;
92           }else{
93             $data['ACTIVE'] = FALSE;
94           }
95           $this->scripts[] = $data;          
96         }
97       } 
98     }
100     /* Get script contents */
101     foreach($this->scripts as $key => $script){
102       $p = new My_Parser($this);
103       $this->sieve_handle->sieve_getscript($script['NAME']);
105       $script = "";
106       foreach($this->sieve_handle->response as $line){
107         $script.=$line;
108       }
110       $this->scripts[$key]['IS_NEW'] = FALSE;;
111       $this->scripts[$key]['SCRIPT'] = $script;
112       $this->scripts[$key]['ORIG_SCRIPT'] = $script;
113       $this->scripts[$key]['MSG']   = "";
114       $ret = $p->parse($script);
115       if(!$ret){
116         $this->scripts[$key]['STATUS']   = FALSE;
117         $this->scripts[$key]['MODE']    = "Source";
118         $this->scripts[$key]['MSG'] = _("Parse failed")."<font color='red'>".$p->status_text."</font>";
119       }else{
120         $this->scripts[$key]['STATUS']   = TRUE;
121         $this->scripts[$key]['MODE']    = "Structured";
122         $this->scripts[$key]['MSG'] = _("Parse successful");
123       }
124       $this->scripts[$key]['PARSER'] = $p;
125       $this->scripts[$key]['EDITED'] = FALSE;
126     }
127     $this->sieve_handle = $this->sieve_handle;
128   }
131   /* Return a sieve class hanlde,
132    *  false if login fails
133    */
134   function get_sieve()
135   {
136     
137     /* Connect to sieve class and try to get all available sieve scripts */
138     if(isset($this->config->data['SERVERS']['IMAP'][$this->parent->gosaMailServer])){
139       $cfg=  $this->config->data['SERVERS']['IMAP'][$this->parent->gosaMailServer];
140       $this->Sieve_Error = "";
142       $uattrib = $this->uattrib;
144       /* Log into the mail server */
145       $this->sieve_handle= new sieve(
146           $cfg["sieve_server"], 
147           $cfg["sieve_port"], 
148           $this->parent->$uattrib, 
149           $cfg["password"], 
150           $cfg["admin"]);
152       /* Try to login */
153       if (!$this->sieve_handle->sieve_login()){
154         $this->Sieve_Error = $this->sieve_handle->error_raw;
155         return(FALSE);
156       }
157       return($this->sieve_handle);
158     }else{
159       $this->Sieve_Error = sprintf(_("The specified mail server '%s' does not exist within the GOsa configuration."),
160         $this->parent->gosaMailServer);
161       return(FALSE);
162     }
163   }
166   /* Handle sieve list 
167    */
168   function execute()
169   {
170     /***************
171      * Create a new Script 
172      ***************/
174     /* Force opening the add script dialog */
175     if(isset($_POST['create_new_script'])){
176       $this->create_script = TRUE;
177     }
179     /* Close add script dialog, without adding a new one */
180     if(isset($_POST['create_script_cancel'])){
181       $this->create_script = FALSE;
182     }
184     /* Display create script dialog 
185      *  handle posts, display warnings if specified 
186      *  name is not useable. 
187      * Create a new script with given name
188      */
189     if($this->create_script){
190     
191       /* Set initial name or used posted name if available */
192       $name = "";
193       if(isset($_POST['NewScriptName'])){
194         $name = trim($_POST['NewScriptName']);
195       }
196  
197       /* Check given name */ 
198       $err = "";
200       /* Is given name in lower case characters ? */
201       if(isset($_POST['create_script_save'])){
202         if(!strlen($name)){
203           $err = _("You should specify a name for your new script.");
204         }
205         /* Is given name in lower case characters ? */
206         if($name != strtolower($name)){
207           $err = _("Only lower case names are allowed here.");
208         }
210         /* Only chars are allowed here */
211         if(preg_match("/[^a-z]/i",$name)){
212           $err = _("Only a-z are allowed in script names.");
213         }
215         $tmp = $this->get_used_script_names();
216         if(in_array_ics($name,$tmp)){
217           $err =_("The specified name is already in use.");
218         }
219       }
221       /* Create script if everything is ok */
222       if($this->create_script && isset($_POST['create_script_save']) && $err == "" ){
224         /* Close dialog */
225         $this->create_script = FALSE;
227         /* Script contents to use */
228         $script = "/*New script */".
229                   "stop;";
231         /* Create a new parser and initialize default values */
232         $p = new My_Parser($this);
233         $ret = $p->parse($script);
234         $sc['SCRIPT'] = $script;
235         $sc['ORIG_SCRIPT'] = $script;
236         $sc['IS_NEW'] = TRUE;
237         $sc['MSG']   = "";
238         if(!$ret){
239           $sc['STATUS']   = FALSE;
240           $sc['MODE']    = "Source";
241           $sc['MSG'] = _("Parse failed")."<font color='red'>".$p->status_text."</font>";
242         }else{
243           $sc['STATUS']   = TRUE;
244           $sc['MODE']    = "Structured";
245           $sc['MSG'] = _("Parse successful");
246         }
247         $sc['PARSER'] = $p;
248         $sc['EDITED'] = TRUE;
249         $sc['ACTIVE'] = FALSE;
250         $sc['NAME']   = $name;
251       
252         /* Add script */
253         $this->scripts[$name] = $sc;
254       }else{
255       
256         /* Display dialog to enter new script name */
257         $smarty = get_smarty();
258         $smarty->assign("NewScriptName",$name);
259         $smarty->assign("Error",$err);
260         return($smarty->fetch(get_template_path("templates/create_script.tpl",TRUE,dirname(__FILE__))));
261       }
262     }
265     /*************
266      * Handle several posts 
267      *************/
269     $once = TRUE;
270     foreach($_POST as $name => $value){
272       /* Edit script requested */
273       if(preg_match("/^editscript_/",$name) && $once && !$this->current_handler){
274         $script = preg_replace("/^editscript_/","",$name);
275         $script = preg_replace("/_(x|y)/","",$script);
276         $once = FALSE;
278         $this->current_script = $script;
279         $this->current_handler = $this->scripts[$script]['PARSER'];
280         $this->scripts[$script]['SCRIPT_BACKUP'] = $this->scripts[$script]['SCRIPT'];
281       }
283       /* remove script requested */
284       if($this->parent->acl_is_writeable("sieveManagement") && preg_match("/^delscript_/",$name) && $once && !$this->current_handler){
285         $script = preg_replace("/^delscript_/","",$name);
286         $script = preg_replace("/_(x|y)/","",$script);
287         $once = FALSE;
288         $this->script_to_delete = $script;  
289       }
291       /* Activate script */
292       if($this->parent->acl_is_writeable("sieveManagement") && preg_match("/^active_script_/",$name) && $once && !$this->current_handler){
293         $script = preg_replace("/^active_script_/","",$name);
294         $script = preg_replace("/_(x|y)/","",$script);
295         $once = FALSE;
297         /* We can only activate existing scripts */
298         if(!$this->scripts[$script]['IS_NEW']){
300           /* Get sieve */
301           if(!$this->sieve_handle = $this->get_sieve()){
302             print_red(
303                 sprintf(
304                   _("Can't log into SIEVE server. Server says '%s'."),
305                   to_string($this->Sieve_Error)));
306           }
308           /* Try to activate the given script and update 
309            *  class script array. 
310            */
311           if(!$this->sieve_handle->sieve_setactivescript($this->scripts[$script]['NAME'])){
312             print_red(sprintf(_("Can't activate sieve script on server. Server says '%s'."),to_string($this->sieve_handle->error_raw)));
313           }else{
314             foreach($this->scripts as $key => $data){
315               if($key == $script){
316                 $this->scripts[$key]['ACTIVE'] = TRUE;
317               }else{
318                 $this->scripts[$key]['ACTIVE'] = FALSE;
319               }
320             }
321           }
322         }
323       }
324     }
326     
327     /*************
328      * Remove script handling 
329      *************/
331     /* Remove aborted */
332     if(isset($_POST['delete_cancel'])){
333       $this->script_to_delete = -1;
334     }
336     /* Remove confirmed */
337     if($this->parent->acl_is_writeable("sieveManagement") && isset($_POST['delete_script_confirm'])){
339       $script = $this->scripts[$this->script_to_delete];
341       /* Just remove from array if it is a new script */
342       if($script['IS_NEW']){
343         unset($this->scripts[$this->script_to_delete]);
344       }else{
346         /* Get sieve */
347         if(!$this->sieve_handle = $this->get_sieve()){
348           print_red(
349               sprintf(
350                 _("Can't log into SIEVE server. Server says '%s'."),
351                 to_string($this->Sieve_Error)));
352         }
354         if(!$this->sieve_handle->sieve_deletescript($this->scripts[$this->script_to_delete]['NAME'])){
355           print_red(sprintf(_("Can't remove sieve script from server. Server says '%s'."),to_string($this->sieve_handle->error_raw)));
356         }else{
357           unset($this->scripts[$this->script_to_delete]);
358         }
359       }
360       $this->script_to_delete = -1;
361     }
363     /* Display confirm dialog */
364     if($this->script_to_delete != -1){
365       $smarty = get_smarty();
366       $smarty->assign("Warning",
367           sprintf(_("You are going to remove the sieve script '%s' from your mail server."),
368             $this->scripts[$this->script_to_delete]['NAME']));
369       return($smarty->fetch(get_template_path("templates/remove_script.tpl",TRUE,dirname(__FILE__))));
370     }
373     /**************
374      * Save script changes 
375      **************/
377     /* Abort saving */
378     if(isset($_POST['cancel_sieve_changes'])){
379       $tmp = $this->scripts[$this->current_script]['SCRIPT_BACKUP'];
380       $this->scripts[$this->current_script]['SCRIPT'] = $tmp;
381       $this->scripts[$this->current_script]['PARSER']->parse($tmp);
382       $this->current_handler = NULL;
383     }
385     /* Save currently edited sieve script. */
386     if($this->parent->acl_is_writeable("sieveManagement") && 
387        isset($_POST['save_sieve_changes']) && 
388        is_object($this->current_handler)){
389       $chk = $this->current_handler->check();
390       if(!count($chk)){
392         $sc = $this->scripts[$this->current_script]['SCRIPT'];
393         $p = new My_Parser($this);
394         if($p -> parse($sc)){
396           if($this->scripts[$this->current_script]['MODE'] == "Source-Only"){
397             $this->scripts[$this->current_script]['MODE'] = "Source";
398           }
399   
400           $this->scripts[$this->current_script]['PARSER'] = $p;
401           $this->scripts[$this->current_script]['EDITED'] = TRUE;
402           $this->scripts[$this->current_script]['STATUS'] = TRUE;
403           $this->scripts[$this->current_script]['MSG'] = _("Edited");
404           $this->current_handler = NULL;
405         }else{
406           print_red($p->status_text);;
407         }
408       }else{
409         foreach($chk as $msgs){
410           print_red(sprintf(_("Please fix all errors before saving. Last error was : %s"),$msgs));
411         }
412       }
413     }
416     /*************
417      * Display edit dialog 
418      *************/
420     /* Display edit dialog, depending on Mode display different uis
421      */
422     if($this->current_handler){
424         if(isset($_POST['Import_Script'])){
425           $this->Import_Script = TRUE;
426         }
428         if(isset($_POST['Import_Script_Cancel'])){
429           $this->Import_Script = FALSE;
430         }
432         if(isset($_POST['Import_Script_Save']) && isset($_FILES['Script_To_Import'])){
434           $file     = $_FILES['Script_To_Import'];
436           if($file['size'] == 0){
437             print_red(_("Specified file seams to empty."));
438           }elseif(!file_exists($file['tmp_name'])){
439             print_red(_("Upload failed, somehow nothing was uploaded or the temporary file can't be accessed."));
440           }elseif(!is_readable ($file['tmp_name'])){
441             print_red(sprintf(_("Can't open file '%s' to read uploaded file contents."),$file['tmp_name']));
442           }else{
443             
444             
445  
446             $contents = file_get_contents($file['tmp_name']);
447            
448             $this->scripts[$this->current_script]['SCRIPT'] = $contents;
449             if(!$this->current_handler->parse($contents)){
450               $this->scripts[$this->current_script]['MODE'] = "Source";
451             }else{
452               $this->scripts[$this->current_script]['MODE'] = "Structured";
453             }
454             $this->Script_Error = "";
455             $this->Import_Script = FALSE;
456           }
457         }
459         if($this->Import_Script){
460           $smarty = get_smarty();
461           $str = $smarty->fetch(get_template_path("templates/import_script.tpl",TRUE,dirname(__FILE__)));
462           return($str);
463         }
464   
466         /* Create dump of current sieve script */
467         if(isset($_POST['Save_Copy'])){
469             /* force download dialog */
470             header("Content-type: application/tiff\n");
471             if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) ||
472                     preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
473                 header('Content-Disposition: filename="dump.script"');
474             } else {
475                 header('Content-Disposition: attachment; filename="dump.script"');
476             }
477             header("Content-transfer-encoding: binary\n");
478             header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
479             header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
480             header("Cache-Control: no-cache");
481             header("Pragma: no-cache");
482             header("Cache-Control: post-check=0, pre-check=0");
483             echo $this->scripts[$this->current_script]['SCRIPT'];
484             exit();
485         }
488       /****
489        * Add new element to ui
490        ****/
492       /* Abort add dialog */ 
493       if(isset($_POST['select_new_element_type_cancel'])){
494         $this->add_new_element = FALSE;
495       }
497       /* Add a new element */
498       if($this->add_new_element){
500         $element_types= array(
501             "sieve_keep"      => _("Keep"),
502             "sieve_comment"   => _("Comment"),
503             "sieve_fileinto"  => _("File into"),
504             "sieve_keep"      => _("Keep"),
505             "sieve_discard"   => _("Discard"),
506             "sieve_redirect"  => _("Redirect"),
507             "sieve_reject"    => _("Reject"),
508             "sieve_require"   => _("Require"),
509             "sieve_stop"      => _("Stop"),
510             "sieve_vacation"  => _("Vacation message"),
511             "sieve_if"        => _("If"));
514         /* Element selected */
515         if(isset($_POST['element_type']) && isset($element_types[$_POST['element_type']]) 
516            || isset($_POST['element_type']) &&in_array($_POST['element_type'],array("sieve_else","sieve_elsif"))){
517           $this->add_element_type = $_POST['element_type'];
518         }
520         /* Create new element and add it to
521          *  the selected position 
522          */
523         if(isset($_POST['select_new_element_type'])){
524           if($this->add_new_element_to_current_script($this->add_element_type,$this->add_new_id,$this->add_above_below)){
525             $this->add_new_element = FALSE;
526           }else{
527             print_red(_("Failed to add new element."));
528           }
529         }
530       }
532       /* Only display select dialog if it is necessary */
533       if($this->add_new_element){
534         $smarty = get_smarty();
535     
536         $add_else_elsif = FALSE;
538         /* Check if we should add else/elsif to the select box 
539          *  or not. We can't add else twice!.
540          */
541         if($this->add_above_below == "below"){
543           /* Get posistion of the current element 
544            */
545           foreach($this->current_handler->tree_->pap as $key => $obj){
546         
547             if($obj->object_id == $this->add_new_id && in_array(get_class($obj),array("sieve_if","sieve_elsif"))){
548   
549               /* Get block start/end */
550               $end_id = $this->current_handler->tree_->get_block_end($key);
551               $else_found = FALSE;
552               $elsif_found = FALSE;
553           
554               /* Check if there is already an else in this block 
555                */
556               for($i =  $key ; $i < $end_id ; $i ++){
557                 if(get_class($this->current_handler->tree_->pap[$i]) == "sieve_else"){
558                   $else_found = TRUE;
559                 }
560                 if(get_class($this->current_handler->tree_->pap[$i]) == "sieve_elsif"){
561                   $elsif_found = TRUE;
562                 }
563               }
564   
565               /* Only allow adding 'else' if there is currently 
566                *  no 'else' statement. And don't allow adding 
567                *  'else' before 'elseif'
568                */ 
569               if(!$else_found && (!(get_class($obj) == "sieve_if" && $elsif_found))){
570                 $element_types['sieve_else'] = _("Else");
571               }
572               $element_types['sieve_elsif'] = _("Else if");
573             }
574           }
575         }
577         $smarty->assign("element_types",$element_types );
578         $smarty->assign("element_type",$this->add_element_type);
579         $str = $smarty->fetch(get_template_path("templates/add_element.tpl",TRUE,dirname(__FILE__)));
580         return($str);
581       }
585       /****************
586        * Handle test posts 
587        ****************/
589       /* handle some special posts from test elements 
590        */
591       foreach($_POST as $name => $value){
592         if(preg_match("/^Add_Test_Object_/",$name)) {
593           $name = preg_replace("/^Add_Test_Object_/","",$name);
594           $name = preg_replace("/_(x|y)$/","",$name);
596           $test_types_to_add = array(
597               "address" =>_("Address"),
598               "header"  =>_("Header"),
599               "envelope"=>_("Envelope"),
600               "size"    =>_("Size"),
601               "exists"  =>_("Exists"),
602               "allof"   =>_("All of"),
603               "anyof"   =>_("Any of"),
604               "true"    =>_("True"),
605               "false"   =>_("False"));
607           $smarty = get_smarty();
608           $smarty->assign("ID",$name);
609           $smarty->assign("test_types_to_add",$test_types_to_add);
610           $ret = $smarty->fetch(get_template_path("templates/select_test_type.tpl",TRUE,dirname(__FILE__)));
611           return($ret);
612         }
613       }
615       $current = $this->scripts[$this->current_script];
617       /* Create html results */
618       $smarty = get_smarty();
619       $smarty->assign("Mode",$current['MODE']);
620       if($current['MODE'] == "Structured"){
621         $smarty->assign("Contents",$this->current_handler->tree_->execute());
622       }else{
623         $smarty->assign("Contents",$current['SCRIPT']);
624       }
625       $smarty->assign("Script_Error",$this->Script_Error);
626       $ret = $smarty->fetch(get_template_path("templates/edit_frame_base.tpl",TRUE,dirname(__FILE__)));
627       return($ret);
628     }
631     /* Create list of available sieve scripts 
632      */
633     $List = new divSelectBox("sieveManagement");
634     foreach($this->scripts as $key => $script){
635   
636       $edited =  $script['EDITED'];
637       $active =  $script['ACTIVE'];
638       
639       $field1 = array("string" => "&nbsp;",
640                       "attach" => "style='width:20px;'");  
641       if($active){
642         $field1 = array("string" => "<img src='images/true.png' alt='"._("Active")."' 
643                                       title='"._("This script is marked as active")."'>",
644                         "attach" => "style='width:20px;'");  
645       }
646       $field2 = array("string" => $script['NAME']);  
647       $field3 = array("string" => $script['MSG']);
648       $field4 = array("string" => _("Script length")."&nbsp;:&nbsp;".strlen($script['SCRIPT']));
650       if($this->parent->acl_is_writeable("sieveManagement")){
651         $del = "<input type='image' name='delscript_".$key."' src='images/edittrash.png'
652                   title='"._("Remove script")."'>";
653       }else{
654         $del = "<img src='images/empty' alt=' '>";
655       }
657       if($active || $script['IS_NEW'] || !$this->parent->acl_is_writeable("sieveManagement")){
658         $activate = "<img src='images/empty' alt=' '>";
659       }else{
660         $activate = "<input type='image' name='active_script_".$key."' src='images/true.png'
661                        title='"._("Activate script")."'>";
662       }
664       $field6 = array("string" => $activate."<input type='image' name='editscript_".$key."' src='images/edit.png'
665                         title='"._("Edit script")."'>".$del,
666                       "attach" => "style='border-right:0px; width:70px;'");
667       $List ->AddEntry(array($field1,$field2,$field3,$field4,$field6)); 
668     }
669  
670     /* If the uattrib is empty   (Attribute to use for atuthentification with sieve)
671      *  Display a message that a connection can't be established right now.
672      */
673     $uattrib = $this->uattrib;
674     $smarty = get_smarty();
677     if(!$this->get_sieve()){
678       $smarty->assign("Sieve_Error",sprintf(
679         _("Can't log into SIEVE server. Server says '%s'."),
680           to_string($this->Sieve_Error)));
681     }else{
682       $smarty->assign("Sieve_Error","");
683     }
685     $smarty->assign("uattrib_empty",empty($this->parent->$uattrib));
686     $smarty->assign("List",$List->DrawList());
687     return($smarty->fetch(get_template_path("templates/management.tpl",TRUE,dirname(__FILE__))));
688   }
691   /* Add a new element to the currently opened script editor.
692    * The insert position is specified by 
693    */
694   function add_new_element_to_current_script($type,$id,$position)
695   {
696     /* Test given data */
697     if(!in_array_ics($position,array("above","below"))){
698       trigger_error("Can't add new element with \$position=".$position.". Only 'above','below' are allowed here.");
699       return(FALSE);
700     }
701     if(!is_numeric($id)){
702       trigger_error("Can't add new element, given id is not numeric.");
703       return(FALSE);
704     }
705     $tmp = get_declared_classes();  
706     if(!in_array($type,$tmp)){
707       trigger_error("Can't add new element, given \$class=".$class." does not exists.");
708       return(FALSE);
709     }
710     if(!is_object($this->current_handler) || get_class($this->current_handler) != "My_Parser"){
711       trigger_error("Can't add new element, there is no valid script editor opened.");
712       return(FALSE);
713     }
715     /* Create elements we should add 
716      * -Some element require also surrounding block elements
717      */
718     $parent = $this->current_handler->tree_;
719     if($this->add_element_type == "sieve_if"){
720       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
721       $ele[] = new sieve_block_start(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
722       $ele[] = new sieve_block_end(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
723     }elseif($this->add_element_type == "sieve_else"){
724       $ele[] = new sieve_block_end(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
725       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
726       $ele[] = new sieve_block_start(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
727     }elseif($this->add_element_type == "sieve_elsif"){
728       $ele[] = new sieve_block_end(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
729       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
730       $ele[] = new sieve_block_start(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
731     }else{
732       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
733     }
735     /* Get index of the element identified by object_id == $id; 
736      */
737     $index = -1;
738     $data = $this->current_handler->tree_->pap;
739     foreach($data as $key => $obj){
740       if($obj->object_id == $id && $index==-1){
741         $index = $key;
742       }
743     }
745     /* Tell to user that we couldn't find the given object 
746      *  so we can't add an element. 
747      */
748     if($index == -1 ){
749       trigger_error("Can't add new element, specified \$id=".$id." could not be found in object tree.");
750       return(FALSE);
751     }
753     /* We have found the specified object_id 
754      *  and want to detect the next free position 
755      *  to insert the new element.
756      */
757     if($position == "above"){
758       $direction ="up";
759       $next_free = $this->current_handler->tree_->_get_next_free_move_slot($index,$direction,TRUE);
760     }else{
761       $direction = "down";
762       $next_free = $this->current_handler->tree_->_get_next_free_move_slot($index,$direction,TRUE);
763     }
764     /* This is extremly necessary, cause some objects 
765      *  updates the tree objects ... Somehow i should change this ... 
766      */
767     $data = $this->current_handler->tree_->pap;
768     $start = $end = array();
770     if($position == "above"){
771       $start = array_slice($data,0,$next_free);
772       $end   = array_slice($data,$next_free);
773     }else{
774       $start = array_slice($data,0,$next_free+1);
775       $end   = array_slice($data,$next_free+1);
776     }
778     $new = array();
779     foreach($start as $obj){
780       $new[] = $obj;
781     }
782     foreach($ele as $el){
783       $new[] = $el;
784     }
785     foreach($end as $obj){
786       $new[] = $obj;
787     }
788     $data= $new;
789     $this->current_handler->tree_->pap = $data;
790     return(TRUE);
791   }
795   function save_object()
796   {
797     if($this->current_handler){
799       if(isset($_GET['Add_Object_Top_ID'])){
800         $this->add_new_element    = TRUE;
801         $this->add_new_id         = $_GET['Add_Object_Top_ID'];
802         $this->add_above_below    = "above";
803       }  
805       if(isset($_GET['Add_Object_Bottom_ID'])){
806         $this->add_new_element    = TRUE;
807         $this->add_new_id         = $_GET['Add_Object_Bottom_ID'];
808         $this->add_above_below    = "below";
809       }  
811       if(isset($_GET['Remove_Object_ID'])){
812         $found_id = -1;
813         foreach($this->current_handler->tree_->pap as $key => $element){
814           if($element->object_id == $_GET['Remove_Object_ID']){
815             $found_id = $key;
816           }
817         }
818         if($found_id != -1 ){
819           $this->current_handler->tree_->remove_object($found_id);  
820         }
821       }  
822  
823       if(isset($_GET['Move_Up_Object_ID'])){
824         $found_id = -1;
825         foreach($this->current_handler->tree_->pap as $key => $element){
826           if($element->object_id == $_GET['Move_Up_Object_ID']){
827             $found_id = $key;
828           }
829         }
830         if($found_id != -1 ){
831           $this->current_handler->tree_->move_up_down($found_id,"up");
832         }
833       }  
834  
835       if(isset($_GET['Move_Down_Object_ID'])){
836         $found_id = -1;
837         foreach($this->current_handler->tree_->pap as $key => $element){
838           if($element->object_id == $_GET['Move_Down_Object_ID']){
839             $found_id = $key;
840           }
841         }
842         if($found_id != -1 ){
843           $this->current_handler->tree_->move_up_down($found_id,"down");
844         }
845       }  
846   
848       /* Check if there is an add object requested 
849        */
850       $data = $this->current_handler->tree_->pap;
851       $once = TRUE;
852       foreach($_POST as $name => $value){
853         foreach($data as $key => $obj){
854           if(isset($obj->object_id) && preg_match("/^Add_Object_Top_".$obj->object_id."_/",$name) && $once){
855             $once = FALSE;
856             $this->add_new_element    = TRUE;
857             $this->add_new_id         = $obj->object_id;
858             $this->add_above_below    = "above";
859           }
860           if(isset($obj->object_id) && preg_match("/^Add_Object_Bottom_".$obj->object_id."_/",$name) && $once){
861             $once = FALSE;
862             $this->add_new_element    = TRUE;
863             $this->add_new_id         = $obj->object_id;
864             $this->add_above_below    = "below";
865           }
866         
867           if(isset($obj->object_id) && preg_match("/^Remove_Object_".$obj->object_id."_/",$name) && $once){
868             $once = FALSE;
869             $this->current_handler->tree_->remove_object($key);
870           }
871           if(isset($obj->object_id) && preg_match("/^Move_Up_Object_".$obj->object_id."_/",$name) && $once){
872             $this->current_handler->tree_->move_up_down($key,"up");
873             $once = FALSE;
874           }
875           if(isset($obj->object_id) && preg_match("/^Move_Down_Object_".$obj->object_id."_/",$name) && $once){
876             $this->current_handler->tree_->move_up_down($key,"down");
877             $once = FALSE;
878           }
879         }
880       }
882       /* Skip Mode changes and Parse tests 
883        *  if we are currently in a subdialog 
884        */
886       $this->current_handler->save_object();
887       $Mode = $this->scripts[$this->current_script]['MODE'];
888       $skip_mode_change = false;
889       if(in_array($Mode,array("Source-Only","Source"))){
890         if(isset($_POST['script_contents'])){
891           $sc = stripslashes($_POST['script_contents']);
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       }
902       if(in_array($Mode,array("Structured"))){
903         $sc = $this->current_handler->get_sieve_script();
904         $this->scripts[$this->current_script]['SCRIPT'] = $sc;
905         $p = new My_Parser($this);
906         if($p -> parse($sc)){
907           $this->Script_Error = "";
908         } else {
909           $this->Script_Error = $p->status_text;
910           $skip_mode_change = TRUE;
911         }
912       }
913       if(!$skip_mode_change){
914         if($this->scripts[$this->current_script]['MODE'] != "Source-Only"){
915           $old_mode = $this->scripts[$this->current_script]['MODE'];
916           if(isset($_POST['View_Source'])){
917             $this->scripts[$this->current_script]['MODE'] = "Source";
918           }
919           if(isset($_POST['View_Structured'])){
920             $this->scripts[$this->current_script]['MODE'] = "Structured";
921           }
922           $new_mode = $this->scripts[$this->current_script]['MODE'];
924           if($old_mode != $new_mode){
926             $sc = $this->scripts[$this->current_script]['SCRIPT'];
927             $p = new My_Parser($this);
929             if($p -> parse($sc)){
930               $this->current_handler->parse($sc);
931               $this->Script_Error = "";
932             } else {
933               $this->Script_Error = $p->status_text;
934             }
935           } 
936         }
937       }
938     }
939   }
941   
942   function get_used_script_names()
943   {
944     $ret = array();
945     foreach($this->scripts as $script){
946       $ret[] = $script['NAME'];
947     }
948     return($ret);
949   }
953   function save()
954   {
955     /* Get sieve */
956     if(!$this->sieve_handle = $this->get_sieve()){
957       print_red(
958           sprintf(
959             _("Can't log into SIEVE server. Server says '%s'."),
960             to_string($this->Sieve_Error)));
961     }
963     $everything_went_fine = TRUE;
965     foreach($this->scripts as $key => $script){
966       if($script['EDITED']){
967         $data = $this->scripts[$key]['SCRIPT'];
968         if(!$this->sieve_handle->sieve_sendscript($script['NAME'], addcslashes ($data,"\\"))){
969           gosa_log("Failed to save sieve script named '".$script['NAME']."': ".to_string($this->sieve_handle->error_raw));
970           $everything_went_fine = FALSE;
971           print_red(to_string($this->sieve_handle->error_raw));
972           $this->scripts[$key]['MSG'] = "<font color='red'>".
973                                            _("Failed to save sieve script").": ".
974                                            to_string($this->sieve_handle->error_raw).
975                                            "</font>";
976         }
977       }
978     }
979     return($everything_went_fine);
980   }
982 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
983 ?>