Code

Updated class location table.
[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 (".$uattrib.") must be part of the given parent element (".get_class($parent).").");
66     }
68     $this->uattrib = $uattrib;
69     $this->parent = &$parent;
70     plugin::plugin($config,$dn);
72     /* Get sieve, if this fail abort class initialization */
73     if(!$this->sieve_handle = $this->get_sieve()){
74       return;
75     }
78     /* Get all sieve scripts names */
79     if($this->sieve_handle->sieve_listscripts()){
80       if (is_array($this->sieve_handle->response)){
81         foreach($this->sieve_handle->response as $key => $name){
83           $data = array();
84           $data['NAME'] = $name;
86           if($key == "ACTIVE" && $key === "ACTIVE"){
87             $data['ACTIVE'] = TRUE;
88           }else{
89             $data['ACTIVE'] = FALSE;
90           }
91           $this->scripts[] = $data;          
92         }
93       } 
94     }
96     /* Get script contents */
97     foreach($this->scripts as $key => $script){
98       $p = new My_Parser($this);
99       $this->sieve_handle->sieve_getscript($script['NAME']);
101       $script = "";
102       foreach($this->sieve_handle->response as $line){
103         $script.=$line;
104       }
106       $this->scripts[$key]['IS_NEW'] = FALSE;;
107       $this->scripts[$key]['SCRIPT'] = $script;
108       $this->scripts[$key]['ORIG_SCRIPT'] = $script;
109       $this->scripts[$key]['MSG']   = "";
110       $ret = $p->parse($script);
111       if(!$ret){
112         $this->scripts[$key]['STATUS']   = FALSE;
113         $this->scripts[$key]['MODE']    = "Source";
114         $this->scripts[$key]['MSG'] = _("Parse failed")."<font color='red'>".$p->status_text."</font>";
115       }else{
116         $this->scripts[$key]['STATUS']   = TRUE;
117         $this->scripts[$key]['MODE']    = "Structured";
118         $this->scripts[$key]['MSG'] = _("Parse successful");
119       }
120       $this->scripts[$key]['PARSER'] = $p;
121       $this->scripts[$key]['EDITED'] = FALSE;
122     }
123     $this->sieve_handle = $this->sieve_handle;
124   }
127   /* Return a sieve class handle,
128    *  false if login fails
129    */
130   function get_sieve()
131   {
132     
133     /* Connect to sieve class and try to get all available sieve scripts */
134     if(isset($this->config->data['SERVERS']['IMAP'][$this->parent->gosaMailServer])){
135       $cfg=  $this->config->data['SERVERS']['IMAP'][$this->parent->gosaMailServer];
136       $this->Sieve_Error = "";
138       $uattrib = $this->uattrib;
140       /* Log into the mail server */
141       $this->sieve_handle= new sieve(
142           $cfg["sieve_server"], 
143           $cfg["sieve_port"], 
144           $this->parent->$uattrib, 
145           $cfg["password"], 
146           $cfg["admin"]);
148       /* Try to login */
149       if (!@$this->sieve_handle->sieve_login()){
150         $this->Sieve_Error = $this->sieve_handle->error_raw;
151         return(FALSE);
152       }
153       return($this->sieve_handle);
154     }else{
155       $this->Sieve_Error = sprintf(_("The specified mail server '%s' does not exist within the GOsa configuration."),
156         $this->parent->gosaMailServer);
157       return(FALSE);
158     }
159   }
162   /* Handle sieve list 
163    */
164   function execute()
165   {
166     /***************
167      * Create a new Script 
168      ***************/
170     /* Force opening the add script dialog */
171     if(isset($_POST['create_new_script'])){
172       $this->create_script = TRUE;
173     }
175     /* Close add script dialog, without adding a new one */
176     if(isset($_POST['create_script_cancel'])){
177       $this->create_script = FALSE;
178     }
180     /* Display create script dialog 
181      *  handle posts, display warnings if specified 
182      *  name is not useable. 
183      * Create a new script with given name
184      */
185     if($this->create_script){
186     
187       /* Set initial name or used posted name if available */
188       $name = "";
189       if(isset($_POST['NewScriptName'])){
190         $name = trim($_POST['NewScriptName']);
191       }
192  
193       /* Check given name */ 
194       $err = false;
196       /* Is given name in lower case characters ? */
197       if(isset($_POST['create_script_save'])){
198         if(!strlen($name)){
199           $err =true;
200           print_red(_("You should specify a name for your new script."));
201         }
202         /* Is given name in lower case characters ? */
203         if($name != strtolower($name)){
204           $err =true;
205           print_red(_("Only lower case names are allowed."));
206         }
208         /* Only chars are allowed here */
209         if(preg_match("/[^a-z]/i",$name)){
210           $err =true;
211           print_red(_("Only alphabetical characters are allowed in script names."));
212         }
214         $tmp = $this->get_used_script_names();
215         if(in_array_ics($name,$tmp)){
216           $err =true;
217           print_red(_("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         return($smarty->fetch(get_template_path("templates/create_script.tpl",TRUE,dirname(__FILE__))));
260       }
261     }
264     /*************
265      * Handle several posts 
266      *************/
268     $once = TRUE;
269     foreach($_POST as $name => $value){
271       /* Edit script requested */
272       if(preg_match("/^editscript_/",$name) && $once && !$this->current_handler){
273         $script = preg_replace("/^editscript_/","",$name);
274         $script = preg_replace("/_(x|y)/","",$script);
275         $once = FALSE;
277         $this->current_script = $script;
278         $this->current_handler = $this->scripts[$script]['PARSER'];
279         $this->scripts[$script]['SCRIPT_BACKUP'] = $this->scripts[$script]['SCRIPT'];
280       }
282       /* remove script requested */
283       if($this->parent->acl_is_writeable("sieveManagement") && preg_match("/^delscript_/",$name) && $once && !$this->current_handler){
284         $script = preg_replace("/^delscript_/","",$name);
285         $script = preg_replace("/_(x|y)/","",$script);
286         $once = FALSE;
287         $this->script_to_delete = $script;  
288       }
290       /* Activate script */
291       if($this->parent->acl_is_writeable("sieveManagement") && preg_match("/^active_script_/",$name) && $once && !$this->current_handler){
292         $script = preg_replace("/^active_script_/","",$name);
293         $script = preg_replace("/_(x|y)/","",$script);
294         $once = FALSE;
296         /* We can only activate existing scripts */
297         if(!$this->scripts[$script]['IS_NEW']){
299           /* Get sieve */
300           if(!$this->sieve_handle = $this->get_sieve()){
301             print_red(
302                 sprintf(
303                   _("Can't log into SIEVE server. Server says '%s'."),
304                   to_string($this->Sieve_Error)));
305           }
307           /* Try to activate the given script and update 
308            *  class script array. 
309            */
310           if(!$this->sieve_handle->sieve_setactivescript($this->scripts[$script]['NAME'])){
311             print_red(sprintf(_("Can't activate sieve script on server. Server says '%s'."),to_string($this->sieve_handle->error_raw)));
312           }else{
313             foreach($this->scripts as $key => $data){
314               if($key == $script){
315                 $this->scripts[$key]['ACTIVE'] = TRUE;
316               }else{
317                 $this->scripts[$key]['ACTIVE'] = FALSE;
318               }
319             }
320           }
321         }
322       }
323     }
325     
326     /*************
327      * Remove script handling 
328      *************/
330     /* Remove aborted */
331     if(isset($_POST['delete_cancel'])){
332       $this->script_to_delete = -1;
333     }
335     /* Remove confirmed */
336     if($this->parent->acl_is_writeable("sieveManagement") && isset($_POST['delete_script_confirm'])){
338       $script = $this->scripts[$this->script_to_delete];
340       /* Just remove from array if it is a new script */
341       if($script['IS_NEW']){
342         unset($this->scripts[$this->script_to_delete]);
343       }else{
345         /* Get sieve */
346         if(!$this->sieve_handle = $this->get_sieve()){
347           print_red(
348               sprintf(
349                 _("Can't log into SIEVE server. Server says '%s'."),
350                 to_string($this->Sieve_Error)));
351         }
353         if(!$this->sieve_handle->sieve_deletescript($this->scripts[$this->script_to_delete]['NAME'])){
354           print_red(sprintf(_("Can't remove sieve script from server. Server says '%s'."),to_string($this->sieve_handle->error_raw)));
355         }else{
356           unset($this->scripts[$this->script_to_delete]);
357         }
358       }
359       $this->script_to_delete = -1;
360     }
362     /* Display confirm dialog */
363     if($this->script_to_delete != -1){
364       $smarty = get_smarty();
365       $smarty->assign("Warning",
366           sprintf(_("You are going to remove the sieve script '%s' from your mail server."),
367             $this->scripts[$this->script_to_delete]['NAME']));
368       return($smarty->fetch(get_template_path("templates/remove_script.tpl",TRUE,dirname(__FILE__))));
369     }
372     /**************
373      * Save script changes 
374      **************/
376     /* Abort saving */
377     if(isset($_POST['cancel_sieve_changes'])){
378       $tmp = $this->scripts[$this->current_script]['SCRIPT_BACKUP'];
379       $this->scripts[$this->current_script]['SCRIPT'] = $tmp;
380       $this->scripts[$this->current_script]['PARSER']->parse($tmp);
381       $this->current_handler = NULL;
382     }
384     /* Save currently edited sieve script. */
385     if($this->parent->acl_is_writeable("sieveManagement") && 
386        isset($_POST['save_sieve_changes']) && 
387        is_object($this->current_handler)){
388       $chk = $this->current_handler->check();
389       if(!count($chk)){
391         $sc = $this->scripts[$this->current_script]['SCRIPT'];
392         $p = new My_Parser($this);
393         if($p -> parse($sc)){
395           if($this->scripts[$this->current_script]['MODE'] == "Source-Only"){
396             $this->scripts[$this->current_script]['MODE'] = "Source";
397           }
398   
399           $this->scripts[$this->current_script]['PARSER'] = $p;
400           $this->scripts[$this->current_script]['EDITED'] = TRUE;
401           $this->scripts[$this->current_script]['STATUS'] = TRUE;
402           $this->scripts[$this->current_script]['MSG'] = _("Edited");
403           $this->current_handler = NULL;
404         }else{
405           print_red($p->status_text);;
406         }
407       }else{
408         foreach($chk as $msgs){
409           print_red(sprintf(_("Please fix all errors before saving. Last error was: %s"),$msgs));
410         }
411       }
412     }
415     /*************
416      * Display edit dialog 
417      *************/
419     /* Display edit dialog, depending on Mode display different uis
420      */
421     if($this->current_handler){
423         if(isset($_POST['Import_Script'])){
424           $this->Import_Script = TRUE;
425         }
427         if(isset($_POST['Import_Script_Cancel'])){
428           $this->Import_Script = FALSE;
429         }
431         if(isset($_POST['Import_Script_Save']) && isset($_FILES['Script_To_Import'])){
433           $file     = $_FILES['Script_To_Import'];
435           if($file['size'] == 0){
436             print_red(_("Specified file seems to be empty."));
437           }elseif(!file_exists($file['tmp_name'])){
438             print_red(_("Upload failed. The temporary file can't be accessed."));
439           }elseif(!is_readable ($file['tmp_name'])){
440             print_red(sprintf(_("Can't open file '%s'."),$file['tmp_name']));
441           }else{
442             
443             
444  
445             $contents = file_get_contents($file['tmp_name']);
446            
447             $this->scripts[$this->current_script]['SCRIPT'] = $contents;
448             if(!$this->current_handler->parse($contents)){
449               $this->scripts[$this->current_script]['MODE'] = "Source";
450             }else{
451               $this->scripts[$this->current_script]['MODE'] = "Structured";
452             }
453             $this->Script_Error = "";
454             $this->Import_Script = FALSE;
455           }
456         }
458         if($this->Import_Script){
459           $smarty = get_smarty();
460           $str = $smarty->fetch(get_template_path("templates/import_script.tpl",TRUE,dirname(__FILE__)));
461           return($str);
462         }
463   
465         /* Create dump of current sieve script */
466         if(isset($_POST['Save_Copy'])){
468             /* force download dialog */
469             header("Content-type: application/tiff\n");
470             if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) ||
471                     preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
472                 header('Content-Disposition: filename="dump.script"');
473             } else {
474                 header('Content-Disposition: attachment; filename="dump.script"');
475             }
476             header("Content-transfer-encoding: binary\n");
477             header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
478             header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
479             header("Cache-Control: no-cache");
480             header("Pragma: no-cache");
481             header("Cache-Control: post-check=0, pre-check=0");
482             echo $this->scripts[$this->current_script]['SCRIPT'];
483             exit();
484         }
487       /****
488        * Add new element to ui
489        ****/
491       /* Abort add dialog */ 
492       if(isset($_POST['select_new_element_type_cancel'])){
493         $this->add_new_element = FALSE;
494       }
496       /* Add a new element */
497       if($this->add_new_element){
499         $element_types= array(
500             "sieve_keep"      => _("Keep"),
501             "sieve_comment"   => _("Comment"),
502             "sieve_fileinto"  => _("File into"),
503             "sieve_keep"      => _("Keep"),
504             "sieve_discard"   => _("Discard"),
505             "sieve_redirect"  => _("Redirect"),
506             "sieve_reject"    => _("Reject"),
507             "sieve_require"   => _("Require"),
508             "sieve_stop"      => _("Stop"),
509             "sieve_vacation"  => _("Vacation message"),
510             "sieve_if"        => _("If"));
513         /* Element selected */
514         if(isset($_POST['element_type']) && isset($element_types[$_POST['element_type']]) 
515            || isset($_POST['element_type']) &&in_array($_POST['element_type'],array("sieve_else","sieve_elsif"))){
516           $this->add_element_type = $_POST['element_type'];
517         }
519         /* Create new element and add it to
520          *  the selected position 
521          */
522         if(isset($_POST['select_new_element_type'])){
523           if($this->add_new_element_to_current_script($this->add_element_type,$this->add_new_id,$this->add_above_below)){
524             $this->add_new_element = FALSE;
525           }else{
526             print_red(_("Failed to add new element."));
527           }
528         }
529       }
531       /* Only display select dialog if it is necessary */
532       if($this->add_new_element){
533         $smarty = get_smarty();
534     
535         $add_else_elsif = FALSE;
537         /* Check if we should add else/elsif to the select box 
538          *  or not. We can't add else twice!.
539          */
540         if($this->add_above_below == "below"){
542           /* Get posistion of the current element 
543            */
544           foreach($this->current_handler->tree_->pap as $key => $obj){
545         
546             if($obj->object_id == $this->add_new_id && in_array(get_class($obj),array("sieve_if","sieve_elsif"))){
547   
548               /* Get block start/end */
549               $end_id = $this->current_handler->tree_->get_block_end($key);
550               $else_found = FALSE;
551               $elsif_found = FALSE;
552           
553               /* Check if there is already an else in this block 
554                */
555               for($i =  $key ; $i < $end_id ; $i ++){
556                 if(get_class($this->current_handler->tree_->pap[$i]) == "sieve_else"){
557                   $else_found = TRUE;
558                 }
559                 if(get_class($this->current_handler->tree_->pap[$i]) == "sieve_elsif"){
560                   $elsif_found = TRUE;
561                 }
562               }
563   
564               /* Only allow adding 'else' if there is currently 
565                *  no 'else' statement. And don't allow adding 
566                *  'else' before 'elseif'
567                */ 
568               if(!$else_found && (!(get_class($obj) == "sieve_if" && $elsif_found))){
569                 $element_types['sieve_else'] = _("Else");
570               }
571               $element_types['sieve_elsif'] = _("Else If");
572             }
573           }
574         }
576         $smarty->assign("element_types",$element_types );
577         $smarty->assign("element_type",$this->add_element_type);
578         $str = $smarty->fetch(get_template_path("templates/add_element.tpl",TRUE,dirname(__FILE__)));
579         return($str);
580       }
584       /****************
585        * Handle test posts 
586        ****************/
588       /* handle some special posts from test elements 
589        */
590       foreach($_POST as $name => $value){
591         if(preg_match("/^Add_Test_Object_/",$name)) {
592           $name = preg_replace("/^Add_Test_Object_/","",$name);
593           $name = preg_replace("/_(x|y)$/","",$name);
595           $test_types_to_add = array(
596               "address" =>_("Address"),
597               "header"  =>_("Header"),
598               "envelope"=>_("Envelope"),
599               "size"    =>_("Size"),
600               "exists"  =>_("Exists"),
601               "allof"   =>_("All of"),
602               "anyof"   =>_("Any of"),
603               "true"    =>_("True"),
604               "false"   =>_("False"));
606           $smarty = get_smarty();
607           $smarty->assign("ID",$name);
608           $smarty->assign("test_types_to_add",$test_types_to_add);
609           $ret = $smarty->fetch(get_template_path("templates/select_test_type.tpl",TRUE,dirname(__FILE__)));
610           return($ret);
611         }
612       }
614       $current = $this->scripts[$this->current_script];
616       /* Create html results */
617       $smarty = get_smarty();
618       $smarty->assign("Mode",$current['MODE']);
619       if($current['MODE'] == "Structured"){
620         $smarty->assign("Contents",$this->current_handler->tree_->execute());
621       }else{
622         $smarty->assign("Contents",$current['SCRIPT']);
623       }
624       $smarty->assign("Script_Error",$this->Script_Error);
625       $ret = $smarty->fetch(get_template_path("templates/edit_frame_base.tpl",TRUE,dirname(__FILE__)));
626       return($ret);
627     }
630     /* Create list of available sieve scripts 
631      */
632     $List = new divSelectBox("sieveManagement");
633     foreach($this->scripts as $key => $script){
634   
635       $edited =  $script['EDITED'];
636       $active =  $script['ACTIVE'];
637       
638       $field1 = array("string" => "&nbsp;",
639                       "attach" => "style='width:20px;'");  
640       if($active){
641         $field1 = array("string" => "<img src='images/true.png' alt='"._("Active")."' 
642                                       title='"._("This script is marked as active")."'>",
643                         "attach" => "style='width:20px;'");  
644       }
645       $field2 = array("string" => $script['NAME']);  
646       $field3 = array("string" => $script['MSG']);
647       $field4 = array("string" => _("Script length").":&nbsp;".strlen($script['SCRIPT']));
649       if($this->parent->acl_is_writeable("sieveManagement")){
650         $del = "<input type='image' name='delscript_".$key."' src='images/edittrash.png'
651                   title='"._("Remove script")."'>";
652       }else{
653         $del = "<img src='images/empty' alt=' '>";
654       }
656       if($active || $script['IS_NEW'] || !$this->parent->acl_is_writeable("sieveManagement")){
657         $activate = "<img src='images/empty' alt=' '>";
658       }else{
659         $activate = "<input type='image' name='active_script_".$key."' src='images/true.png'
660                        title='"._("Activate script")."'>";
661       }
663       $field6 = array("string" => $activate."<input type='image' name='editscript_".$key."' src='images/edit.png'
664                         title='"._("Edit script")."'>".$del,
665                       "attach" => "style='border-right:0px; width:70px;'");
666       $List->AddEntry(array($field1,$field2,$field3,$field4,$field6)); 
667     }
669     $List->SetHeight(400);
670  
671     /* If the uattrib is empty   (Attribute to use for authentification with sieve)
672      *  Display a message that the connection can't be established.
673      */
674     $uattrib = $this->uattrib;
675     $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       if(!empty($type)){
708         trigger_error("Can't add new element, given \$class=".$class." does not exists.");
709       }
710       return(FALSE);
711     }
712     if(!is_object($this->current_handler) || get_class($this->current_handler) != "My_Parser"){
713       trigger_error("Can't add new element, there is no valid script editor opened.");
714       return(FALSE);
715     }
717     /* These element types are allowed to be added here */
718     $element_types= array(
719         "sieve_keep"      => _("Keep"),
720         "sieve_comment"   => _("Comment"),
721         "sieve_fileinto"  => _("File into"),
722         "sieve_keep"      => _("Keep"),
723         "sieve_discard"   => _("Discard"),
724         "sieve_redirect"  => _("Redirect"),
725         "sieve_reject"    => _("Reject"),
726         "sieve_require"   => _("Require"),
727         "sieve_stop"      => _("Stop"),
728         "sieve_vacation"  => _("Vacation message"),
729         "sieve_if"        => _("If"));
731     /* Check if we should add else/elsif to the select box
732      *  or not. We can't add else twice!.
733      */
735     /* Get posistion of the current element
736      */
737     foreach($this->current_handler->tree_->pap as $key => $obj){
739       if($obj->object_id == $id && in_array(get_class($obj),array("sieve_if","sieve_elsif"))){
741         /* Get block start/end */
742         $end_id = $this->current_handler->tree_->get_block_end($key);
743         $else_found = FALSE;
744         $elsif_found = FALSE;
746         /* Check if there is already an else in this block
747          */
748         for($i =  $key ; $i < $end_id ; $i ++){
749           if(get_class($this->current_handler->tree_->pap[$i]) == "sieve_else"){
750             $else_found = TRUE;
751           }
752           if(get_class($this->current_handler->tree_->pap[$i]) == "sieve_elsif"){
753             $elsif_found = TRUE;
754           }
755         }
757         if($this->add_above_below == "below"){
759           /* Only allow adding 'else' if there is currently
760            *  no 'else' statement. And don't allow adding
761            *  'else' before 'elseif'
762            */
763           if(!$else_found && (!(get_class($obj) == "sieve_if" && $elsif_found))){
764             $element_types['sieve_else'] = _("Else");
765           }
766           $element_types['sieve_elsif'] = _("Else If");
767         }else{
768          
769           /* Allow adding elsif above elsif */ 
770           if(in_array(get_class($obj),array("sieve_elsif"))){
771             $element_types['sieve_elsif'] = _("Else If");
772           }
773         }
774       }
775     }
777     if(!isset($element_types[$type])){
778       print_red(sprintf(_("Can't add the specified element at the given position.")));
779       return;
780     }
783     /* Create elements we should add 
784      * -Some element require also surrounding block elements
785      */
786     $parent = $this->current_handler->tree_;
787     if($this->add_element_type == "sieve_if"){
788       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
789       $ele[] = new sieve_block_start(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
790       $ele[] = new sieve_block_end(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
791     }elseif($this->add_element_type == "sieve_else"){
792       $ele[] = new sieve_block_end(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
793       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
794       $ele[] = new sieve_block_start(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
795     }elseif($this->add_element_type == "sieve_elsif"){
796       $ele[] = new sieve_block_end(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
797       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
798       $ele[] = new sieve_block_start(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
799     }elseif($this->add_element_type == "sieve_vacation"){
801       /* Automatically add addresses to sieve alternate addresses */
802       $data = NULL;
803       $tmp = new $this->add_element_type($data, preg_replace("/[^0-9]/","",microtime()),$parent);
804       if(isset($this->parent->gosaMailAlternateAddress)){
805         $tmp->addresses = $this->parent->gosaMailAlternateAddress;
806       }
807       $ele[] = $tmp ;
808     }else{
809       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
810     }
812     /* Get index of the element identified by object_id == $id; 
813      */
814     $index = -1;
815     $data = $this->current_handler->tree_->pap;
816     foreach($data as $key => $obj){
817       if($obj->object_id == $id && $index==-1){
818         $index = $key;
819       }
820     }
822     /* Tell to user that we couldn't find the given object 
823      *  so we can't add an element. 
824      */
825     if($index == -1 ){
826       trigger_error("Can't add new element, specified \$id=".$id." could not be found in object tree.");
827       return(FALSE);
828     }
830     /* We have found the specified object_id 
831      *  and want to detect the next free position 
832      *  to insert the new element.
833      */
834     if($position == "above"){
835       $direction ="up";
836       $next_free = $this->current_handler->tree_->_get_next_free_move_slot($index,$direction,TRUE);
837     }else{
838       $direction = "down";
839       $next_free = $this->current_handler->tree_->_get_next_free_move_slot($index,$direction,TRUE);
840     }
841     /* This is extremly necessary, cause some objects 
842      *  updates the tree objects ... Somehow i should change this ... 
843      */
844     $data = $this->current_handler->tree_->pap;
845     $start = $end = array();
847     if($position == "above"){
848       $start = array_slice($data,0,$next_free);
849       $end   = array_slice($data,$next_free);
850     }else{
851       $start = array_slice($data,0,$next_free+1);
852       $end   = array_slice($data,$next_free+1);
853     }
855     $new = array();
856     foreach($start as $obj){
857       $new[] = $obj;
858     }
859     foreach($ele as $el){
860       $new[] = $el;
861     }
862     foreach($end as $obj){
863       $new[] = $obj;
864     }
865     $data= $new;
866     $this->current_handler->tree_->pap = $data;
867     return(TRUE);
868   }
872   function save_object()
873   {
874     if($this->current_handler){
876       if(isset($_GET['Add_Object_Top_ID'])){
877         $this->add_new_element    = TRUE;
878         $this->add_new_id         = $_GET['Add_Object_Top_ID'];
879         $this->add_above_below    = "above";
880       }  
882       if(isset($_GET['Add_Object_Bottom_ID'])){
883         $this->add_new_element    = TRUE;
884         $this->add_new_id         = $_GET['Add_Object_Bottom_ID'];
885         $this->add_above_below    = "below";
886       }  
888       if(isset($_GET['Remove_Object_ID'])){
889         $found_id = -1;
890         foreach($this->current_handler->tree_->pap as $key => $element){
891           if($element->object_id == $_GET['Remove_Object_ID']){
892             $found_id = $key;
893           }
894         }
895         if($found_id != -1 ){
896           $this->current_handler->tree_->remove_object($found_id);  
897         }
898       }  
899  
900       if(isset($_GET['Move_Up_Object_ID'])){
901         $found_id = -1;
902         foreach($this->current_handler->tree_->pap as $key => $element){
903           if($element->object_id == $_GET['Move_Up_Object_ID']){
904             $found_id = $key;
905           }
906         }
907         if($found_id != -1 ){
908           $this->current_handler->tree_->move_up_down($found_id,"up");
909         }
910       }  
911  
912       if(isset($_GET['Move_Down_Object_ID'])){
913         $found_id = -1;
914         foreach($this->current_handler->tree_->pap as $key => $element){
915           if($element->object_id == $_GET['Move_Down_Object_ID']){
916             $found_id = $key;
917           }
918         }
919         if($found_id != -1 ){
920           $this->current_handler->tree_->move_up_down($found_id,"down");
921         }
922       }  
923   
925       /* Check if there is an add object requested 
926        */
927       $data = $this->current_handler->tree_->pap;
928       $once = TRUE;
929       foreach($_POST as $name => $value){
930         foreach($data as $key => $obj){
931           if(isset($obj->object_id) && preg_match("/^Add_Object_Top_".$obj->object_id."_/",$name) && $once){
932             $once = FALSE;
933             $this->add_element_type   =  $_POST['element_type_'.$obj->object_id];
934             $this->add_new_element    = FALSE;
935             $this->add_new_id         = $obj->object_id;
936             $this->add_above_below    = "above";
937             $this->add_new_element_to_current_script($this->add_element_type,$this->add_new_id,$this->add_above_below);
938           }
939           if(isset($obj->object_id) && preg_match("/^Add_Object_Bottom_".$obj->object_id."_/",$name) && $once){
940             $once = FALSE;
941             $this->add_element_type   =  $_POST['element_type_'.$obj->object_id];
942             $this->add_new_element    = FALSE;
943             $this->add_new_id         = $obj->object_id;
944             $this->add_above_below    = "below";
945             $this->add_new_element_to_current_script($this->add_element_type,$this->add_new_id,$this->add_above_below);
946           }
947         
948           if(isset($obj->object_id) && preg_match("/^Remove_Object_".$obj->object_id."_/",$name) && $once){
949             $once = FALSE;
950             $this->current_handler->tree_->remove_object($key);
951           }
952           if(isset($obj->object_id) && preg_match("/^Move_Up_Object_".$obj->object_id."_/",$name) && $once){
953             $this->current_handler->tree_->move_up_down($key,"up");
954             $once = FALSE;
955           }
956           if(isset($obj->object_id) && preg_match("/^Move_Down_Object_".$obj->object_id."_/",$name) && $once){
957             $this->current_handler->tree_->move_up_down($key,"down");
958             $once = FALSE;
959           }
960         }
961       }
963       /* Skip Mode changes and Parse tests 
964        *  if we are currently in a subdialog 
965        */
967       $this->current_handler->save_object();
968       $Mode = $this->scripts[$this->current_script]['MODE'];
969       $skip_mode_change = false;
970       if(in_array($Mode,array("Source-Only","Source"))){
971         if(isset($_POST['script_contents'])){
972           $sc = stripslashes($_POST['script_contents']);
973           $this->scripts[$this->current_script]['SCRIPT'] = $sc;
974           $p = new My_Parser($this);
975           if($p -> parse($sc)){
976             $this->Script_Error = "";
977           } else {
978             $this->Script_Error = $p->status_text;
979             $skip_mode_change = TRUE;
980           }
981         }
982       }
983       if(in_array($Mode,array("Structured"))){
984         $sc = $this->current_handler->get_sieve_script();
985         $this->scripts[$this->current_script]['SCRIPT'] = $sc;
986         $p = new My_Parser($this);
987         if($p -> parse($sc)){
988           $this->Script_Error = "";
989         } else {
990           $this->Script_Error = $p->status_text;
991           $skip_mode_change = TRUE;
992         }
993       }
994       if(!$skip_mode_change){
995         if($this->scripts[$this->current_script]['MODE'] != "Source-Only"){
996           $old_mode = $this->scripts[$this->current_script]['MODE'];
997           if(isset($_POST['View_Source'])){
998             $this->scripts[$this->current_script]['MODE'] = "Source";
999           }
1000           if(isset($_POST['View_Structured'])){
1001             $this->scripts[$this->current_script]['MODE'] = "Structured";
1002           }
1003           $new_mode = $this->scripts[$this->current_script]['MODE'];
1005           if($old_mode != $new_mode){
1007             $sc = $this->scripts[$this->current_script]['SCRIPT'];
1008             $p = new My_Parser($this);
1010             if($p -> parse($sc)){
1011               $this->current_handler->parse($sc);
1012               $this->Script_Error = "";
1013             } else {
1014               $this->Script_Error = $p->status_text;
1015             }
1016           } 
1017         }
1018       }
1019     }
1020   }
1022   
1023   function get_used_script_names()
1024   {
1025     $ret = array();
1026     foreach($this->scripts as $script){
1027       $ret[] = $script['NAME'];
1028     }
1029     return($ret);
1030   }
1034   function save()
1035   {
1036     /* Get sieve */
1037     if(!$this->sieve_handle = $this->get_sieve()){
1038       print_red(
1039           sprintf(
1040             _("Can't log into SIEVE server. Server says '%s'."),
1041             to_string($this->Sieve_Error)));
1042       return;
1043     }
1045     $everything_went_fine = TRUE;
1047     foreach($this->scripts as $key => $script){
1048       if($script['EDITED']){
1049         $data = $this->scripts[$key]['SCRIPT'];
1050         if(!$this->sieve_handle->sieve_sendscript($script['NAME'], addcslashes ($data,"\\"))){
1051           new log("modify","users/mailAccount".get_class($this),$script['NAME'],"Failed to save sieve script named '".$script['NAME']."': ".to_string($this->sieve_handle->error_raw));
1053           $everything_went_fine = FALSE;
1054           print_red(to_string($this->sieve_handle->error_raw));
1055           $this->scripts[$key]['MSG'] = "<font color='red'>".
1056                                            _("Failed to save sieve script").": ".
1057                                            to_string($this->sieve_handle->error_raw).
1058                                            "</font>";
1059         }
1060       }
1061     }
1062     return($everything_went_fine);
1063   }
1065 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1066 ?>