Code

Added additional check, to avoid connecting to unavailable server
[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();  
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)
62   {
63     $this->parent = $parent;
64     plugin::plugin($config,$dn);
66     /* Get sieve */
67     if(!$this->sieve_handle = $this->get_sieve()){
68       print_red(
69         sprintf(
70           _("Can't log into SIEVE server. Server says '%s'."),
71           to_string($this->Sieve_Error)));
72       return;
73     }
76     /* Get all sieve scripts names */
77     if($this->sieve_handle->sieve_listscripts()){
78       if (is_array($this->sieve_handle->response)){
79         foreach($this->sieve_handle->response as $key => $name){
81           $data = array();
82           $data['NAME'] = $name;
84           if($key == "ACTIVE" && $key === "ACTIVE"){
85             $data['ACTIVE'] = TRUE;
86           }else{
87             $data['ACTIVE'] = FALSE;
88           }
89           $this->scripts[] = $data;          
90         }
91       } 
92     }
94     /* Get script contents */
95     foreach($this->scripts as $key => $script){
96       $p = new My_Parser($this);
97       $this->sieve_handle->sieve_getscript($script['NAME']);
99       $script = "";
100       foreach($this->sieve_handle->response as $line){
101         $script.=$line;
102       }
104       $this->scripts[$key]['IS_NEW'] = FALSE;;
105       $this->scripts[$key]['SCRIPT'] = $script;
106       $this->scripts[$key]['ORIG_SCRIPT'] = $script;
107       $this->scripts[$key]['MSG']   = "";
108       $ret = $p->parse($script);
109       if(!$ret){
110         $this->scripts[$key]['STATUS']   = FALSE;
111         $this->scripts[$key]['MODE']    = "Source";
112         $this->scripts[$key]['MSG'] = _("Parse failed")."<font color='red'>".$p->status_text."</font>";
113       }else{
114         $this->scripts[$key]['STATUS']   = TRUE;
115         $this->scripts[$key]['MODE']    = "Structured";
116         $this->scripts[$key]['MSG'] = _("Parse successful");
117       }
118       $this->scripts[$key]['PARSER'] = $p;
119       $this->scripts[$key]['EDITED'] = FALSE;
120     }
121     $this->sieve_handle = $this->sieve_handle;
122   }
125   /* Return a sieve class hanlde,
126    *  false if login fails
127    */
128   function get_sieve()
129   {
130     
131     /* Connect to sieve class and try to get all available sieve scripts */
132     if(isset($this->config->data['SERVERS']['IMAP'][$this->parent->gosaMailServer])){
133       $cfg=  $this->config->data['SERVERS']['IMAP'][$this->parent->gosaMailServer];
134       $this->Sieve_Error = "";
136       /* Log into the mail server */
137       $this->sieve_handle= new sieve(
138           $cfg["sieve_server"], 
139           $cfg["sieve_port"], 
140           $this->parent->uid, 
141           $cfg["password"], 
142           $cfg["admin"]);
144       /* Try to login */
145       if (!$this->sieve_handle->sieve_login()){
146         $this->Sieve_Error = $this->sieve_handle->error_raw;
147         return(FALSE);
148       }
149       return($this->sieve_handle);
150     }else{
151       $this->Sieve_Error = sprintf(_("The specified mail server '%s' does not exist within the GOsa configuration."),
152         $this->parent->gosaMailServer);
153       return(FALSE);
154     }
155   }
158   /* Handle sieve list 
159    */
160   function execute()
161   {
162     /***************
163      * Create a new Script 
164      ***************/
166     /* Force opening the add script dialog */
167     if(isset($_POST['create_new_script'])){
168       $this->create_script = TRUE;
169     }
171     /* Close add script dialog, without adding a new one */
172     if(isset($_POST['create_script_cancel'])){
173       $this->create_script = FALSE;
174     }
176     /* Display create script dialog 
177      *  handle posts, display warnings if specified 
178      *  name is not useable. 
179      * Create a new script with given name
180      */
181     if($this->create_script){
182     
183       /* Set initial name or used posted name if available */
184       $name = "";
185       if(isset($_POST['NewScriptName'])){
186         $name = trim($_POST['NewScriptName']);
187       }
188  
189       /* Check given name */ 
190       $err = "";
192       /* Is given name in lower case characters ? */
193       if(isset($_POST['create_script_save'])){
194         if(!strlen($name)){
195           $err = _("You should specify a name for your new script.");
196         }
197         /* Is given name in lower case characters ? */
198         if($name != strtolower($name)){
199           $err = _("Only lower case names are allowed here.");
200         }
202         /* Only chars are allowed here */
203         if(preg_match("/[^a-z]/i",$name)){
204           $err = _("Only a-z are allowed in script names.");
205         }
207         $tmp = $this->get_used_script_names();
208         if(in_array_ics($name,$tmp)){
209           $err =_("The specified name is already in use.");
210         }
211       }
213       /* Create script if everything is ok */
214       if($this->create_script && isset($_POST['create_script_save']) && $err == "" ){
216         /* Close dialog */
217         $this->create_script = FALSE;
219         /* Script contents to use */
220         $script = "/*New script */".
221                   "stop;";
223         /* Create a new parser and initialize default values */
224         $p = new My_Parser($this);
225         $ret = $p->parse($script);
226         $sc['SCRIPT'] = $script;
227         $sc['ORIG_SCRIPT'] = $script;
228         $sc['IS_NEW'] = TRUE;
229         $sc['MSG']   = "";
230         if(!$ret){
231           $sc['STATUS']   = FALSE;
232           $sc['MODE']    = "Source";
233           $sc['MSG'] = _("Parse failed")."<font color='red'>".$p->status_text."</font>";
234         }else{
235           $sc['STATUS']   = TRUE;
236           $sc['MODE']    = "Structured";
237           $sc['MSG'] = _("Parse successful");
238         }
239         $sc['PARSER'] = $p;
240         $sc['EDITED'] = TRUE;
241         $sc['ACTIVE'] = FALSE;
242         $sc['NAME']   = $name;
243       
244         /* Add script */
245         $this->scripts[$name] = $sc;
246       }else{
247       
248         /* Display dialog to enter new script name */
249         $smarty = get_smarty();
250         $smarty->assign("NewScriptName",$name);
251         $smarty->assign("Error",$err);
252         return($smarty->fetch(get_template_path("templates/create_script.tpl",TRUE,dirname(__FILE__))));
253       }
254     }
257     /*************
258      * Handle several posts 
259      *************/
261     $once = TRUE;
262     foreach($_POST as $name => $value){
264       /* Edit script requested */
265       if(preg_match("/^editscript_/",$name) && $once && !$this->current_handler){
266         $script = preg_replace("/^editscript_/","",$name);
267         $script = preg_replace("/_(x|y)/","",$script);
268         $once = FALSE;
270         $this->current_script = $script;
271         $this->current_handler = $this->scripts[$script]['PARSER'];
272         $this->scripts[$script]['SCRIPT_BACKUP'] = $this->scripts[$script]['SCRIPT'];
273       }
275       /* remove script requested */
276       if(preg_match("/^delscript_/",$name) && $once && !$this->current_handler){
277         $script = preg_replace("/^delscript_/","",$name);
278         $script = preg_replace("/_(x|y)/","",$script);
279         $once = FALSE;
280  
281         $this->script_to_delete = $script;  
282       }
284       /* Activate script */
285       if(preg_match("/^active_script_/",$name) && $once && !$this->current_handler){
286         $script = preg_replace("/^active_script_/","",$name);
287         $script = preg_replace("/_(x|y)/","",$script);
288         $once = FALSE;
290         /* We can only activate existing scripts */
291         if(!$this->scripts[$script]['IS_NEW']){
293           /* Get sieve */
294           if(!$this->sieve_handle = $this->get_sieve()){
295             print_red(
296                 sprintf(
297                   _("Can't log into SIEVE server. Server says '%s'."),
298                   to_string($this->Sieve_Error)));
299           }
301           /* Try to activate the given script and update 
302            *  class script array. 
303            */
304           if(!$this->sieve_handle->sieve_setactivescript($this->scripts[$script]['NAME'])){
305             print_red(sprintf(_("Can't activate sieve script on server. Server says '%s'."),to_string($this->sieve_handle->error_raw)));
306           }else{
307             foreach($this->scripts as $key => $data){
308               if($key == $script){
309                 $this->scripts[$key]['ACTIVE'] = TRUE;
310               }else{
311                 $this->scripts[$key]['ACTIVE'] = FALSE;
312               }
313             }
314           }
315         }
316       }
317     }
319     
320     /*************
321      * Remove script handling 
322      *************/
324     /* Remove aborted */
325     if(isset($_POST['delete_cancel'])){
326       $this->script_to_delete = -1;
327     }
329     /* Remove confirmed */
330     if(isset($_POST['delete_script_confirm'])){
332       $script = $this->scripts[$this->script_to_delete];
334       /* Just remove from array if it is a new script */
335       if($script['IS_NEW']){
336         unset($this->scripts[$this->script_to_delete]);
337       }else{
339         /* Get sieve */
340         if(!$this->sieve_handle = $this->get_sieve()){
341           print_red(
342               sprintf(
343                 _("Can't log into SIEVE server. Server says '%s'."),
344                 to_string($this->Sieve_Error)));
345         }
347         if(!$this->sieve_handle->sieve_deletescript($this->scripts[$this->script_to_delete]['NAME'])){
348           print_red(sprintf(_("Can't remove sieve script from server. Server says '%s'."),to_string($this->sieve_handle->error_raw)));
349         }else{
350           unset($this->scripts[$this->script_to_delete]);
351         }
352       }
353       $this->script_to_delete = -1;
354     }
356     /* Display confirm dialog */
357     if($this->script_to_delete != -1){
358       $smarty = get_smarty();
359       $smarty->assign("Warning",
360           sprintf(_("You are going to remove the sieve script '%s' from your mail server."),
361             $this->scripts[$this->script_to_delete]['NAME']));
362       return($smarty->fetch(get_template_path("templates/remove_script.tpl",TRUE,dirname(__FILE__))));
363     }
366     /**************
367      * Save script changes 
368      **************/
370     /* Abort saving */
371     if(isset($_POST['cancel_sieve_changes'])){
372       $tmp = $this->scripts[$this->current_script]['SCRIPT_BACKUP'];
373       $this->scripts[$this->current_script]['SCRIPT'] = $tmp;
374       $this->scripts[$this->current_script]['PARSER']->parse($tmp);
375       $this->current_handler = NULL;
376     }
378     /* Save currently edited sieve script. */
379     if(isset($_POST['save_sieve_changes'])){
380       $chk = $this->current_handler->check();
381       if(!count($chk)){
383         $sc = $this->scripts[$this->current_script]['SCRIPT'];
384         $p = new My_Parser($this);
385         if($p -> parse($sc)){
387           if($this->scripts[$this->current_script]['MODE'] == "Source-Only"){
388             $this->scripts[$this->current_script]['MODE'] = "Source";
389           }
390   
391           $this->scripts[$this->current_script]['PARSER'] = $p;
392           $this->scripts[$this->current_script]['EDITED'] = TRUE;
393           $this->scripts[$this->current_script]['STATUS'] = TRUE;
394           $this->scripts[$this->current_script]['MSG'] = _("Edited");
395           $this->current_handler = NULL;
396         }else{
397           print_red($p->status_text);;
398         }
399       }else{
400         print_red(_("Please fix all errors before saving."));
401       }
402     }
405     /*************
406      * Display edit dialog 
407      *************/
409     /* Display edit dialog, depending on Mode display different uis
410      */
411     if($this->current_handler){
413         if(isset($_POST['Import_Script'])){
414           $this->Import_Script = TRUE;
415         }
417         if(isset($_POST['Import_Script_Cancel'])){
418           $this->Import_Script = FALSE;
419         }
421         if(isset($_POST['Import_Script_Save']) && isset($_FILES['Script_To_Import'])){
423           $file     = $_FILES['Script_To_Import'];
425           if($file['size'] == 0){
426             print_red(_("Specified file seams to empty."));
427           }elseif(!file_exists($file['tmp_name'])){
428             print_red(_("Upload failed, somehow nothing was uploaded or the temporary file can't be accessed."));
429           }elseif(!is_readable ($file['tmp_name'])){
430             print_red(sprintf(_("Can't open file '%s' to read uploaded file contents."),$file['tmp_name']));
431           }else{
432             
433             
434  
435             $contents = file_get_contents($file['tmp_name']);
436            
437             $this->scripts[$this->current_script]['SCRIPT'] = $contents;
438             if(!$this->current_handler->parse($contents)){
439               $this->scripts[$this->current_script]['MODE'] = "Source";
440             }else{
441               $this->scripts[$this->current_script]['MODE'] = "Structured";
442             }
443             $this->Import_Script = FALSE;
444           }
445         }
447         if($this->Import_Script){
448           $smarty = get_smarty();
449           $str = $smarty->fetch(get_template_path("templates/import_script.tpl",TRUE,dirname(__FILE__)));
450           return($str);
451         }
452   
454         /* Create dump of current sieve script */
455         if(isset($_POST['Save_Copy'])){
457             /* force download dialog */
458             header("Content-type: application/tiff\n");
459             if (preg_match('/MSIE 5.5/', $HTTP_USER_AGENT) ||
460                     preg_match('/MSIE 6.0/', $HTTP_USER_AGENT)) {
461                 header('Content-Disposition: filename="dump.script"');
462             } else {
463                 header('Content-Disposition: attachment; filename="dump.script"');
464             }
465             header("Content-transfer-encoding: binary\n");
466             header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
467             header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
468             header("Cache-Control: no-cache");
469             header("Pragma: no-cache");
470             header("Cache-Control: post-check=0, pre-check=0");
471             echo $this->scripts[$this->current_script]['SCRIPT'];
472             exit();
473         }
476       /****
477        * Add new element to ui
478        ****/
480       /* Abort add dialog */ 
481       if(isset($_POST['select_new_element_type_cancel'])){
482         $this->add_new_element = FALSE;
483       }
485       /* Add a new element */
486       if($this->add_new_element){
488         $element_types= array(
489             "sieve_keep"      => _("Keep"),
490             "sieve_comment"   => _("Comment"),
491             "sieve_fileinto"  => _("File into"),
492             "sieve_keep"      => _("Keep"),
493             "sieve_discard"   => _("Discard"),
494             "sieve_redirect"  => _("Redirect"),
495             "sieve_reject"    => _("Reject"),
496             "sieve_require"   => _("Require"),
497             "sieve_stop"      => _("Stop"),
498             "sieve_vacation"  => _("Vacation message"),
499             "sieve_if"        => _("If"));
502         /* Element selected */
503         if(isset($_POST['element_type']) && isset($element_types[$_POST['element_type']]) 
504            || isset($_POST['element_type']) &&in_array($_POST['element_type'],array("sieve_else","sieve_elsif"))){
505           $this->add_element_type = $_POST['element_type'];
506         }
508         /* Create new element and add it to
509          *  the selected position 
510          */
511         if(isset($_POST['select_new_element_type'])){
512           if($this->add_new_element_to_current_script($this->add_element_type,$this->add_new_id,$this->add_above_below)){
513             $this->add_new_element = FALSE;
514           }else{
515             print_red(_("Failed to add new element."));
516           }
517         }
518       }
520       /* Only display select dialog if it is necessary */
521       if($this->add_new_element){
522         $smarty = get_smarty();
523     
524         $add_else_elsif = FALSE;
526         /* Check if we should add else/elsif to the select box 
527          *  or not. We can't add else twice!.
528          */
529         if($this->add_above_below == "below"){
531           /* Get posistion of the current element 
532            */
533           foreach($this->current_handler->tree_->pap as $key => $obj){
534         
535             if($obj->object_id == $this->add_new_id && in_array(get_class($obj),array("sieve_if","sieve_elsif"))){
536   
537               /* Get block start/end */
538               $end_id = $this->current_handler->tree_->get_block_end($key);
539               $else_found = FALSE;
540               $elsif_found = FALSE;
541           
542               /* Check if there is already an else in this block 
543                */
544               for($i =  $key ; $i < $end_id ; $i ++){
545                 if(get_class($this->current_handler->tree_->pap[$i]) == "sieve_else"){
546                   $else_found = TRUE;
547                 }
548                 if(get_class($this->current_handler->tree_->pap[$i]) == "sieve_elsif"){
549                   $elsif_found = TRUE;
550                 }
551               }
552   
553               /* Only allow adding 'else' if there is currently 
554                *  no 'else' statement. And don't allow adding 
555                *  'else' before 'elseif'
556                */ 
557               if(!$else_found && (!(get_class($obj) == "sieve_if" && $elsif_found))){
558                 $element_types['sieve_else'] = _("Else");
559               }
560               $element_types['sieve_elsif'] = _("Else if");
561             }
562           }
563         }
565         $smarty->assign("element_types",$element_types );
566         $smarty->assign("element_type",$this->add_element_type);
567         $str = $smarty->fetch(get_template_path("templates/add_element.tpl",TRUE,dirname(__FILE__)));
568         return($str);
569       }
573       /****************
574        * Handle test posts 
575        ****************/
577       /* handle some special posts from test elements 
578        */
579       foreach($_POST as $name => $value){
580         if(preg_match("/^Add_Test_Object_/",$name)) {
581           $name = preg_replace("/^Add_Test_Object_/","",$name);
582           $name = preg_replace("/_(x|y)$/","",$name);
584           $test_types_to_add = array(
585               "address" =>_("Address"),
586               "header"  =>_("Header"),
587               "envelope"=>_("Envelope"),
588               "size"    =>_("Size"),
589               "exists"  =>_("Exists"),
590               "allof"   =>_("All of"),
591               "anyof"   =>_("Any of"),
592               "true"    =>_("True"),
593               "false"   =>_("False"));
595           $smarty = get_smarty();
596           $smarty->assign("ID",$name);
597           $smarty->assign("test_types_to_add",$test_types_to_add);
598           $ret = $smarty->fetch(get_template_path("templates/select_test_type.tpl",TRUE,dirname(__FILE__)));
599           return($ret);
600         }
601       }
603       $current = $this->scripts[$this->current_script];
605       /* Create html results */
606       $smarty = get_smarty();
607       $smarty->assign("Mode",$current['MODE']);
608       if($current['MODE'] == "Structured"){
609         $smarty->assign("Contents",$this->current_handler->tree_->execute());
610       }else{
611         $smarty->assign("Contents",$current['SCRIPT']);
612       }
613       $smarty->assign("Script_Error",$this->Script_Error);
614       $ret = $smarty->fetch(get_template_path("templates/edit_frame_base.tpl",TRUE,dirname(__FILE__)));
615       return($ret);
616     }
619     /* Create list of available sieve scripts 
620      */
621     $List = new divSelectBox("sieveManagement");
622     foreach($this->scripts as $key => $script){
623   
624       $edited =  $script['EDITED'];
625       $active =  $script['ACTIVE'];
626       
627       $field1 = array("string" => "&nbsp;",
628                       "attach" => "style='width:20px;'");  
629       if($active){
630         $field1 = array("string" => "<img src='images/true.png' alt='"._("Active")."'>",
631                         "attach" => "style='width:20px;'");  
632       }
633       $field2 = array("string" => $script['NAME']);  
634       $field3 = array("string" => $script['MSG']);
635       $field4 = array("string" => _("Script length")."&nbsp;:&nbsp;".strlen($script['SCRIPT']));
637       if($edited){
638         $field5 = array("string" => "<img src='images/fai_new_hook.png' alt='"._("Edited")."'>",
639                         "attach" => "style='width:30px;'");
640       }else{
641         $field5 = array("string" => "",
642                         "attach" => "style='width:30px;'");
643       }
645       if($active || $script['IS_NEW']){
646         $field6 = array("string" => "<img src='images/empty.png' alt=' '>".
647                                     "<input type='image' name='editscript_".$key."' src='images/edit.png'>".
648                                     "<input type='image' name='delscript_".$key."' src='images/edittrash.png'>");
649       }else{
650         $field6 = array("string" => "<input type='image' name='active_script_".$key."' src='images/true.png'>".
651                                     "<input type='image' name='editscript_".$key."' src='images/edit.png'>".
652                                     "<input type='image' name='delscript_".$key."' src='images/edittrash.png'>");
653       }
654       $List ->AddEntry(array($field1,$field2,$field3,$field4,$field5,$field6)); 
655     }
656   
657     $display ="<h2>Sieve script management</h2>";
658     $display .= _("Be careful. All your changes will be saved directly to sieve, if you use the save button below.");
659     $display .= "<br><input type='submit' name='create_new_script' value='"._("Create new script")."'>";
660     $display .=  $List->DrawList();
661     
662     $display .= "<p style=\"text-align:right\">\n";
663     $display .= "<input type=submit name=\"sieve_finish\" style=\"width:80px\" value=\""._("Ok")."\">\n";
664     $display .= "&nbsp;\n";
665     $display .= "<input type=submit name=\"sieve_cancel\" value=\""._("Cancel")."\">\n";
666     $display .= "</p>";
667     return($display);;
668   }
671   /* Add a new element to the currently opened script editor.
672    * The insert position is specified by 
673    */
674   function add_new_element_to_current_script($type,$id,$position)
675   {
676     /* Test given data */
677     if(!in_array_ics($position,array("above","below"))){
678       trigger_error("Can't add new element with \$position=".$position.". Only 'above','below' are allowed here.");
679       return(FALSE);
680     }
681     if(!is_numeric($id)){
682       trigger_error("Can't add new element, given id is not numeric.");
683       return(FALSE);
684     }
685     $tmp = get_declared_classes();  
686     if(!in_array($type,$tmp)){
687       trigger_error("Can't add new element, given \$class=".$class." does not exists.");
688       return(FALSE);
689     }
690     if(!is_object($this->current_handler) || get_class($this->current_handler) != "My_Parser"){
691       trigger_error("Can't add new element, there is no valid script editor opened.");
692       return(FALSE);
693     }
695     /* Create elements we should add 
696      * -Some element require also surrounding block elements
697      */
698     $parent = $this->current_handler->tree_;
699     if($this->add_element_type == "sieve_if"){
700       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
701       $ele[] = new sieve_block_start(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
702       $ele[] = new sieve_block_end(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
703     }elseif($this->add_element_type == "sieve_else"){
704       $ele[] = new sieve_block_end(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
705       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
706       $ele[] = new sieve_block_start(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
707     }elseif($this->add_element_type == "sieve_elsif"){
708       $ele[] = new sieve_block_end(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
709       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
710       $ele[] = new sieve_block_start(NULL,preg_replace("/[^0-9]/","",microtime()),$parent);
711     }else{
712       $ele[] = new $this->add_element_type(NULL, preg_replace("/[^0-9]/","",microtime()),$parent);
713     }
715     /* Get index of the element identified by object_id == $id; 
716      */
717     $index = -1;
718     $data = $this->current_handler->tree_->pap;
719     foreach($data as $key => $obj){
720       if($obj->object_id == $id && $index==-1){
721         $index = $key;
722       }
723     }
725     /* Tell to user that we couldn't find the given object 
726      *  so we can't add an element. 
727      */
728     if($index == -1 ){
729       trigger_error("Can't add new element, specified \$id=".$id." could not be found in object tree.");
730       return(FALSE);
731     }
733     /* We have found the specified object_id 
734      *  and want to detect the next free position 
735      *  to insert the new element.
736      */
737     if($position == "above"){
738       $direction ="up";
739       $next_free = $this->current_handler->tree_->_get_next_free_move_slot($index,$direction,TRUE);
740     }else{
741       $direction = "down";
742       $next_free = $this->current_handler->tree_->_get_next_free_move_slot($index,$direction,TRUE);
743     }
744     /* This is extremly necessary, cause some objects 
745      *  updates the tree objects ... Somehow i should change this ... 
746      */
747     $data = $this->current_handler->tree_->pap;
748     $start = $end = array();
750     if($position == "above"){
751       $start = array_slice($data,0,$next_free);
752       $end   = array_slice($data,$next_free);
753     }else{
754       $start = array_slice($data,0,$next_free+1);
755       $end   = array_slice($data,$next_free+1);
756     }
758     $new = array();
759     foreach($start as $obj){
760       $new[] = $obj;
761     }
762     foreach($ele as $el){
763       $new[] = $el;
764     }
765     foreach($end as $obj){
766       $new[] = $obj;
767     }
768     $data= $new;
769     $this->current_handler->tree_->pap = $data;
770     return(TRUE);
771   }
775   function save_object()
776   {
777     if($this->current_handler){
779       /* Check if there is an add object requested 
780        */
781       $data = $this->current_handler->tree_->pap;
782       $once = TRUE;
783       foreach($_POST as $name => $value){
784         foreach($data as $key => $obj){
785           if(isset($obj->object_id) && preg_match("/^Add_Object_Top_".$obj->object_id."_/",$name) && $once){
786             $once = FALSE;
787             $this->add_new_element    = TRUE;
788             $this->add_new_id         = $obj->object_id;
789             $this->add_above_below    = "above";
790           }
791           if(isset($obj->object_id) && preg_match("/^Add_Object_Bottom_".$obj->object_id."_/",$name) && $once){
792             $once = FALSE;
793             $this->add_new_element    = TRUE;
794             $this->add_new_id         = $obj->object_id;
795             $this->add_above_below    = "below";
796           }
797         
798           if(isset($obj->object_id) && preg_match("/^Remove_Object_".$obj->object_id."_/",$name) && $once){
799             $once = FALSE;
800             $this->current_handler->tree_->remove_object($key);
801           }
802           if(isset($obj->object_id) && preg_match("/^Move_Up_Object_".$obj->object_id."_/",$name) && $once){
803             $this->current_handler->tree_->move_up_down($key,"up");
804             $once = FALSE;
805           }
806           if(isset($obj->object_id) && preg_match("/^Move_Down_Object_".$obj->object_id."_/",$name) && $once){
807             $this->current_handler->tree_->move_up_down($key,"down");
808             $once = FALSE;
809           }
810         }
811       }
813       /* Skip Mode changes and Parse tests 
814        *  if we are currently in a subdialog 
815        */
817       $this->current_handler->save_object();
818       $Mode = $this->scripts[$this->current_script]['MODE'];
819       $skip_mode_change = false;
820       if(in_array($Mode,array("Source-Only","Source"))){
821         if(isset($_POST['script_contents'])){
822           $sc = stripslashes($_POST['script_contents']);
823           $this->scripts[$this->current_script]['SCRIPT'] = $sc;
824           $p = new My_Parser($this);
825           if($p -> parse($sc)){
826             $this->Script_Error = "";
827           } else {
828             $this->Script_Error = $p->status_text;
829             $skip_mode_change = TRUE;
830           }
831         }
832       }
833       if(in_array($Mode,array("Structured"))){
834         $sc = $this->current_handler->get_sieve_script();
835         $this->scripts[$this->current_script]['SCRIPT'] = $sc;
836         $p = new My_Parser($this);
837         if($p -> parse($sc)){
838           $this->Script_Error = "";
839         } else {
840           $this->Script_Error = $p->status_text;
841           $skip_mode_change = TRUE;
842         }
843       }
844       if(!$skip_mode_change){
845         if($this->scripts[$this->current_script]['MODE'] != "Source-Only"){
846           $old_mode = $this->scripts[$this->current_script]['MODE'];
847           if(isset($_POST['View_Source'])){
848             $this->scripts[$this->current_script]['MODE'] = "Source";
849           }
850           if(isset($_POST['View_Structured'])){
851             $this->scripts[$this->current_script]['MODE'] = "Structured";
852           }
853           $new_mode = $this->scripts[$this->current_script]['MODE'];
855           if($old_mode != $new_mode){
857             $sc = $this->scripts[$this->current_script]['SCRIPT'];
858             $p = new My_Parser($this);
860             if($p -> parse($sc)){
861               $this->current_handler->parse($sc);
862               $this->Script_Error = "";
863             } else {
864               $this->Script_Error = $p->status_text;
865             }
866           } 
867         }
868       }
869     }
870   }
872   
873   function get_used_script_names()
874   {
875     $ret = array();
876     foreach($this->scripts as $script){
877       $ret[] = $script['NAME'];
878     }
879     return($ret);
880   }
884   function save()
885   {
886     /* Get sieve */
887     if(!$this->sieve_handle = $this->get_sieve()){
888       print_red(
889           sprintf(
890             _("Can't log into SIEVE server. Server says '%s'."),
891             to_string($this->Sieve_Error)));
892     }
894     $everything_went_fine = TRUE;
896     foreach($this->scripts as $key => $script){
897       if($script['EDITED']){
898         $data = $this->scripts[$key]['SCRIPT'];
899         if(!$this->sieve_handle->sieve_sendscript($script['NAME'], addcslashes ($data,"\\"))){
900           gosa_log("Failed to save sieve script named '".$script['NAME']."': ".to_string($this->sieve_handle->error_raw));
901           $everything_went_fine = FALSE;
902           print_red(to_string($this->sieve_handle->error_raw));
903           $this->scripts[$key]['MSG'] = "<font color='red'>".
904                                            _("Failed to save sieve script").": ".
905                                            to_string($this->sieve_handle->error_raw).
906                                            "</font>";
907         }
908       }
909     }
910     return($everything_went_fine);
911   }
913 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
914 ?>