Code

Updated locking for multiple edit
[gosa.git] / include / class_plugin.inc
1 <?php
2 /*
3    This code is part of GOsa (https://gosa.gonicus.de)
4    Copyright (C) 2003  Cajus Pollmeier
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  */
21 /*! \brief   The plugin base class
22   \author  Cajus Pollmeier <pollmeier@gonicus.de>
23   \version 2.00
24   \date    24.07.2003
26   This is the base class for all plugins. It can be used standalone or
27   can be included by the tabs class. All management should be done 
28   within this class. Extend your plugins from this class.
29  */
31 class plugin
32 {
33   /*!
34     \brief Reference to parent object
36     This variable is used when the plugin is included in tabs
37     and keeps reference to the tab class. Communication to other
38     tabs is possible by 'name'. So the 'fax' plugin can ask the
39     'userinfo' plugin for the fax number.
41     \sa tab
42    */
43   var $parent= NULL;
45   /*!
46     \brief Configuration container
48     Access to global configuration
49    */
50   var $config= NULL;
52   /*!
53     \brief Mark plugin as account
55     Defines whether this plugin is defined as an account or not.
56     This has consequences for the plugin to be saved from tab
57     mode. If it is set to 'FALSE' the tab will call the delete
58     function, else the save function. Should be set to 'TRUE' if
59     the construtor detects a valid LDAP object.
61     \sa plugin::plugin()
62    */
63   var $is_account= FALSE;
64   var $initially_was_account= FALSE;
66   /*!
67     \brief Mark plugin as template
69     Defines whether we are creating a template or a normal object.
70     Has conseqences on the way execute() shows the formular and how
71     save() puts the data to LDAP.
73     \sa plugin::save() plugin::execute()
74    */
75   var $is_template= FALSE;
76   var $ignore_account= FALSE;
77   var $is_modified= FALSE;
79   /*!
80     \brief Represent temporary LDAP data
82     This is only used internally.
83    */
84   var $attrs= array();
86   /* Keep set of conflicting plugins */
87   var $conflicts= array();
89   /* Save unit tags */
90   var $gosaUnitTag= "";
92   /*!
93     \brief Used standard values
95     dn
96    */
97   var $dn= "";
98   var $uid= "";
99   var $sn= "";
100   var $givenName= "";
101   var $acl= "*none*";
102   var $dialog= FALSE;
103   var $snapDialog = NULL;
105   /* attribute list for save action */
106   var $attributes= array();
107   var $objectclasses= array();
108   var $is_new= TRUE;
109   var $saved_attributes= array();
111   var $acl_base= "";
112   var $acl_category= "";
114   /* Plugin identifier */
115   var $plHeadline= "";
116   var $plDescription= "";
118   /* This can be set to render the tabulators in another stylesheet */
119   var $pl_notify= FALSE;
121   /* Object entry CSN */
122   var $entryCSN         = "";
123   var $CSN_check_active = FALSE;
125   /* This variable indicates that this class can handle multiple dns at once. */
126   var $multiple_support = FALSE; 
128   /* This aviable indicates, that we are currently in multiple edit handle */
129   var $multiple_support_active = FALSE; 
130   var $selected_edit_values = array();
132   /*! \brief plugin constructor
134     If 'dn' is set, the node loads the given 'dn' from LDAP
136     \param dn Distinguished name to initialize plugin from
137     \sa plugin()
138    */
139   function plugin (&$config, $dn= NULL, $parent= NULL)
140   {
141     /* Configuration is fine, allways */
142     $this->config= &$config;    
143     $this->dn= $dn;
145     /* Handle new accounts, don't read information from LDAP */
146     if ($dn == "new"){
147       return;
148     }
150     /* Save current dn as acl_base */
151     $this->acl_base= $dn;
153     /* Get LDAP descriptor */
154     $ldap= $this->config->get_ldap_link();
155     if ($dn !== NULL){
157       /* Load data to 'attrs' and save 'dn' */
158       if ($parent !== NULL){
159         $this->attrs= $parent->attrs;
160       } else {
161         $ldap->cat ($dn);
162         $this->attrs= $ldap->fetch();
163       }
165       /* Copy needed attributes */
166       foreach ($this->attributes as $val){
167         $found= array_key_ics($val, $this->attrs);
168         if ($found != ""){
169           $this->$val= $this->attrs["$found"][0];
170         }
171       }
173       /* gosaUnitTag loading... */
174       if (isset($this->attrs['gosaUnitTag'][0])){
175         $this->gosaUnitTag= $this->attrs['gosaUnitTag'][0];
176       }
178       /* Set the template flag according to the existence of objectClass
179          gosaUserTemplate */
180       if (isset($this->attrs['objectClass'])){
181         if (in_array ("gosaUserTemplate", $this->attrs['objectClass'])){
182           $this->is_template= TRUE;
183           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
184               "found", "Template check");
185         }
186       }
188       /* Is Account? */
189       $found= TRUE;
190       foreach ($this->objectclasses as $obj){
191         if (preg_match('/top/i', $obj)){
192           continue;
193         }
194         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
195           $found= FALSE;
196           break;
197         }
198       }
199       if ($found){
200         $this->is_account= TRUE;
201         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
202             "found", "Object check");
203       }
205       /* Prepare saved attributes */
206       $this->saved_attributes= $this->attrs;
207       foreach ($this->saved_attributes as $index => $value){
208         if (preg_match('/^[0-9]+$/', $index)){
209           unset($this->saved_attributes[$index]);
210           continue;
211         }
212         if (!in_array($index, $this->attributes) && $index != "objectClass"){
213           unset($this->saved_attributes[$index]);
214           continue;
215         }
216         if ($this->saved_attributes[$index]["count"] == 1){
217           $tmp= $this->saved_attributes[$index][0];
218           unset($this->saved_attributes[$index]);
219           $this->saved_attributes[$index]= $tmp;
220           continue;
221         }
223         unset($this->saved_attributes["$index"]["count"]);
224       }
225     }
227     /* Save initial account state */
228     $this->initially_was_account= $this->is_account;
229   }
232   /*! \brief execute plugin
234     Generates the html output for this node
235    */
236   function execute()
237   {
238     /* This one is empty currently. Fabian - please fill in the docu code */
239     $_SESSION['current_class_for_help'] = get_class($this);
241     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
242     $_SESSION['LOCK_VARS_TO_USE'] = $_SESSION['LOCK_VARS_USED'] =array();
243   }
245   /*! \brief execute plugin
246      Removes object from parent
247    */
248   function remove_from_parent()
249   {
250     /* include global link_info */
251     $ldap= $this->config->get_ldap_link();
253     /* Get current objectClasses in order to add the required ones */
254     $ldap->cat($this->dn);
255     $tmp= $ldap->fetch ();
256     $oc= array();
257     if (isset($tmp['objectClass'])){
258       $oc= $tmp['objectClass'];
259       unset($oc['count']);
260     }
262     /* Remove objectClasses from entry */
263     $ldap->cd($this->dn);
264     $this->attrs= array();
265     $this->attrs['objectClass']= array_remove_entries($this->objectclasses,$oc);
267     /* Unset attributes from entry */
268     foreach ($this->attributes as $val){
269       $this->attrs["$val"]= array();
270     }
272     /* Unset account info */
273     $this->is_account= FALSE;
275     /* Do not write in plugin base class, this must be done by
276        children, since there are normally additional attribs,
277        lists, etc. */
278     /*
279        $ldap->modify($this->attrs);
280      */
281   }
284   /*! \brief   Save HTML posted data to object 
285    */
286   function save_object()
287   {
288     /* Update entry CSN if it is empty. */
289     if(empty($this->entryCSN) && $this->CSN_check_active){
290       $this->entryCSN = getEntryCSN($this->dn);
291     }
293     /* Save values to object */
294     foreach ($this->attributes as $val){
295       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
296         /* Check for modifications */
297         if (get_magic_quotes_gpc()) {
298           $data= stripcslashes($_POST["$val"]);
299         } else {
300           $data= $this->$val = $_POST["$val"];
301         }
302         if ($this->$val != $data){
303           $this->is_modified= TRUE;
304         }
305     
306         /* Okay, how can I explain this fix ... 
307          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
308          * So IE posts these 'unselectable' option, with value = chr(194) 
309          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
310          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
311          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
312          */
313         if(isset($data[0]) && $data[0] == chr(194)) {
314           $data = "";  
315         }
316         $this->$val= $data;
317         //echo "<font color='blue'>".$val."</font><br>";
318       }else{
319         //echo "<font color='red'>".$val."</font><br>";
320       }
321     }
322   }
325   /* Save data to LDAP, depending on is_account we save or delete */
326   function save()
327   {
328     /* include global link_info */
329     $ldap= $this->config->get_ldap_link();
331     /* Save all plugins */
332     $this->entryCSN = "";
334     /* Start with empty array */
335     $this->attrs= array();
337     /* Get current objectClasses in order to add the required ones */
338     $ldap->cat($this->dn);
339     
340     $tmp= $ldap->fetch ();
342     $oc= array();
343     if (isset($tmp['objectClass'])){
344       $oc= $tmp["objectClass"];
345       $this->is_new= FALSE;
346       unset($oc['count']);
347     } else {
348       $this->is_new= TRUE;
349     }
351     /* Load (minimum) attributes, add missing ones */
352     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
354     /* Copy standard attributes */
355     foreach ($this->attributes as $val){
356       if ($this->$val != ""){
357         $this->attrs["$val"]= $this->$val;
358       } elseif (!$this->is_new) {
359         $this->attrs["$val"]= array();
360       }
361     }
363   }
366   function cleanup()
367   {
368     foreach ($this->attrs as $index => $value){
370       /* Convert arrays with one element to non arrays, if the saved
371          attributes are no array, too */
372       if (is_array($this->attrs[$index]) && 
373           count ($this->attrs[$index]) == 1 &&
374           isset($this->saved_attributes[$index]) &&
375           !is_array($this->saved_attributes[$index])){
376           
377         $tmp= $this->attrs[$index][0];
378         $this->attrs[$index]= $tmp;
379       }
381       /* Remove emtpy arrays if they do not differ */
382       if (is_array($this->attrs[$index]) &&
383           count($this->attrs[$index]) == 0 &&
384           !isset($this->saved_attributes[$index])){
385           
386         unset ($this->attrs[$index]);
387         continue;
388       }
390       /* Remove single attributes that do not differ */
391       if (!is_array($this->attrs[$index]) &&
392           isset($this->saved_attributes[$index]) &&
393           !is_array($this->saved_attributes[$index]) &&
394           $this->attrs[$index] == $this->saved_attributes[$index]){
396         unset ($this->attrs[$index]);
397         continue;
398       }
400       /* Remove arrays that do not differ */
401       if (is_array($this->attrs[$index]) && 
402           isset($this->saved_attributes[$index]) &&
403           is_array($this->saved_attributes[$index])){
404           
405         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
406           unset ($this->attrs[$index]);
407           continue;
408         }
409       }
410     }
412     /* Update saved attributes and ensure that next cleanups will be successful too */
413     foreach($this->attrs as $name => $value){
414       $this->saved_attributes[$name] = $value;
415     }
416   }
418   /* Check formular input */
419   function check()
420   {
421     $message= array();
423     /* Skip if we've no config object */
424     if (!isset($this->config) || !is_object($this->config)){
425       return $message;
426     }
428     /* Find hooks entries for this class */
429     $command= $this->config->search(get_class($this), "CHECK", array('menu', 'tabs'));
431     if ($command != ""){
433       if (!check_command($command)){
434         $message[]= sprintf(_("Command '%s', specified as CHECK hook for plugin '%s' doesn't seem to exist."), $command,
435                             get_class($this));
436       } else {
438         /* Generate "ldif" for check hook */
439         $ldif= "dn: $this->dn\n";
440         
441         /* ... objectClasses */
442         foreach ($this->objectclasses as $oc){
443           $ldif.= "objectClass: $oc\n";
444         }
445         
446         /* ... attributes */
447         foreach ($this->attributes as $attr){
448           if ($this->$attr == ""){
449             continue;
450           }
451           if (is_array($this->$attr)){
452             foreach ($this->$attr as $val){
453               $ldif.= "$attr: $val\n";
454             }
455           } else {
456               $ldif.= "$attr: ".$this->$attr."\n";
457           }
458         }
460         /* Append empty line */
461         $ldif.= "\n";
463         /* Feed "ldif" into hook and retrieve result*/
464         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
465         $fh= proc_open($command, $descriptorspec, $pipes);
466         if (is_resource($fh)) {
467           fwrite ($pipes[0], $ldif);
468           fclose($pipes[0]);
469           
470           $result= stream_get_contents($pipes[1]);
471           if ($result != ""){
472             $message[]= $result;
473           }
474           
475           fclose($pipes[1]);
476           fclose($pipes[2]);
477           proc_close($fh);
478         }
479       }
481     }
483     /* Check entryCSN */
484     if($this->CSN_check_active){
485       $current_csn = getEntryCSN($this->dn);
486       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
487         $this->entryCSN = $current_csn;
488         $message[] = _("The object has changed since opened in GOsa. Please ensure that nobody has done serious changes that may get lost   if you save this entry.");
489       }
490     }
491     return ($message);
492   }
494   /* Adapt from template, using 'dn' */
495   function adapt_from_template($dn)
496   {
497     /* Include global link_info */
498     $ldap= $this->config->get_ldap_link();
500     /* Load requested 'dn' to 'attrs' */
501     $ldap->cat ($dn);
502     $this->attrs= $ldap->fetch();
504     /* Walk through attributes */
505     foreach ($this->attributes as $val){
507       if (isset($this->attrs["$val"][0])){
509         /* If attribute is set, replace dynamic parts: 
510            %sn, %givenName and %uid. Fill these in our local variables. */
511         $value= $this->attrs["$val"][0];
513         foreach (array("sn", "givenName", "uid") as $repl){
514           if (preg_match("/%$repl/i", $value)){
515             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
516           }
517         }
518         $this->$val= $value;
519       }
520     }
522     /* Is Account? */
523     $found= TRUE;
524     foreach ($this->objectclasses as $obj){
525       if (preg_match('/top/i', $obj)){
526         continue;
527       }
528       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
529         $found= FALSE;
530         break;
531       }
532     }
533     if ($found){
534       $this->is_account= TRUE;
535     }
536   }
538   /* Indicate whether a password change is needed or not */
539   function password_change_needed()
540   {
541     return FALSE;
542   }
545   /* Show header message for tab dialogs */
546   function show_enable_header($button_text, $text, $disabled= FALSE)
547   {
548     if (($disabled == TRUE) || (!$this->acl_is_createable())){
549       $state= "disabled";
550     } else {
551       $state= "";
552     }
553     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
554     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
555       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
557     return($display);
558   }
561   /* Show header message for tab dialogs */
562   function show_disable_header($button_text, $text, $disabled= FALSE)
563   {
564     if (($disabled == TRUE) || !$this->acl_is_removeable()){
565       $state= "disabled";
566     } else {
567       $state= "";
568     }
569     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
570     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
571       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
573     return($display);
574   }
577   /* Show header message for tab dialogs */
578   function show_header($button_text, $text, $disabled= FALSE)
579   {
580     echo "FIXME: show_header should be replaced by show_disable_header and show_enable_header<br>";
581     if ($disabled == TRUE){
582       $state= "disabled";
583     } else {
584       $state= "";
585     }
586     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
587     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
588       ($this->acl_is_createable()?'':'disabled')." ".$state.
589       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
591     return($display);
592   }
595   function postcreate($add_attrs= array())
596   {
597     /* Find postcreate entries for this class */
598     $command= $this->config->search(get_class($this), "POSTCREATE",array('menu', 'tabs'));
600     if ($command != ""){
602       /* Additional attributes */
603       foreach ($add_attrs as $name => $value){
604         $command= preg_replace("/%$name/", $value, $command);
605       }
607       /* Walk through attribute list */
608       foreach ($this->attributes as $attr){
609         if (!is_array($this->$attr)){
610           $command= preg_replace("/%$attr/", $this->$attr, $command);
611         }
612       }
613       $command= preg_replace("/%dn/", $this->dn, $command);
615       if (check_command($command)){
616         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
617             $command, "Execute");
619         exec($command);
620       } else {
621         $message= sprintf(_("Command '%s', specified as POSTCREATE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
622         print_red ($message);
623       }
624     }
625   }
627   function postmodify($add_attrs= array())
628   {
629     /* Find postcreate entries for this class */
630     $command= $this->config->search(get_class($this), "POSTMODIFY",array('menu','tabs'));
632     if ($command != ""){
634       /* Additional attributes */
635       foreach ($add_attrs as $name => $value){
636         $command= preg_replace("/%$name/", $value, $command);
637       }
639       /* Walk through attribute list */
640       foreach ($this->attributes as $attr){
641         if (!is_array($this->$attr)){
642           $command= preg_replace("/%$attr/", $this->$attr, $command);
643         }
644       }
645       $command= preg_replace("/%dn/", $this->dn, $command);
647       if (check_command($command)){
648         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
649             $command, "Execute");
651         exec($command);
652       } else {
653         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, get_class($this));
654         print_red ($message);
655       }
656     }
657   }
659   function postremove($add_attrs= array())
660   {
661     /* Find postremove entries for this class */
662     $command= $this->config->search(get_class($this), "POSTREMOVE",array('menu','tabs'));
663     if ($command != ""){
665       /* Additional attributes */
666       foreach ($add_attrs as $name => $value){
667         $command= preg_replace("/%$name/", $value, $command);
668       }
670       /* Walk through attribute list */
671       foreach ($this->attributes as $attr){
672         if (!is_array($this->$attr)){
673           $command= preg_replace("/%$attr/", $this->$attr, $command);
674         }
675       }
676       $command= preg_replace("/%dn/", $this->dn, $command);
678       /* Additional attributes */
679       foreach ($add_attrs as $name => $value){
680         $command= preg_replace("/%$name/", $value, $command);
681       }
683       if (check_command($command)){
684         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
685             $command, "Execute");
687         exec($command);
688       } else {
689         $message= sprintf(_("Command '%s', specified as POSTREMOVE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
690         print_red ($message);
691       }
692     }
693   }
695   /* Create unique DN */
696   function create_unique_dn($attribute, $base)
697   {
698     $ldap= $this->config->get_ldap_link();
699     $base= preg_replace("/^,*/", "", $base);
701     /* Try to use plain entry first */
702     $dn= "$attribute=".$this->$attribute.",$base";
703     $ldap->cat ($dn, array('dn'));
704     if (!$ldap->fetch()){
705       return ($dn);
706     }
708     /* Look for additional attributes */
709     foreach ($this->attributes as $attr){
710       if ($attr == $attribute || $this->$attr == ""){
711         continue;
712       }
714       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
715       $ldap->cat ($dn, array('dn'));
716       if (!$ldap->fetch()){
717         return ($dn);
718       }
719     }
721     /* None found */
722     return ("none");
723   }
725   function rebind($ldap, $referral)
726   {
727     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
728     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
729       $this->error = "Success";
730       $this->hascon=true;
731       $this->reconnect= true;
732       return (0);
733     } else {
734       $this->error = "Could not bind to " . $credentials['ADMIN'];
735       return NULL;
736     }
737   }
740   /* Recursively copy ldap object */
741   function _copy($src_dn,$dst_dn)
742   {
743     $ldap=$this->config->get_ldap_link();
744     $ldap->cat($src_dn);
745     $attrs= $ldap->fetch();
747     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
748     $ds= ldap_connect($this->config->current['SERVER']);
749     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
750     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
751       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
752     }
754     $r=ldap_bind($ds,$this->config->current['ADMIN'], $this->config->current['PASSWORD']);
755     $sr=ldap_read($ds, @LDAP::fix($src_dn), "objectClass=*");
757     /* Fill data from LDAP */
758     $new= array();
759     if ($sr) {
760       $ei=ldap_first_entry($ds, $sr);
761       if ($ei) {
762         foreach($attrs as $attr => $val){
763           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
764             for ($i= 0; $i<$info['count']; $i++){
765               if ($info['count'] == 1){
766                 $new[$attr]= $info[$i];
767               } else {
768                 $new[$attr][]= $info[$i];
769               }
770             }
771           }
772         }
773       }
774     }
776     /* close conncetion */
777     ldap_unbind($ds);
779     /* Adapt naming attribute */
780     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
781     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
782     $new[$dst_name]= @LDAP::fix($dst_val);
784     /* Check if this is a department.
785      * If it is a dep. && there is a , override in his ou 
786      *  change \2C to , again, else this entry can't be saved ...
787      */
788     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
789       $new['ou'] = preg_replace("/\\\\,/",",",$new['ou']);
790     }
792     /* Save copy */
793     $ldap->connect();
794     $ldap->cd($this->config->current['BASE']);
795     
796     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
798     /* FAIvariable=.../..., cn=.. 
799         could not be saved, because the attribute FAIvariable was different to 
800         the dn FAIvariable=..., cn=... */
801     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
802       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
803     }
804     $ldap->cd($dst_dn);
805     $ldap->add($new);
807     if ($ldap->error != "Success"){
808       trigger_error("Trying to save $dst_dn failed.",
809           E_USER_WARNING);
810       return(FALSE);
811     }
812     return(TRUE);
813   }
816   /* This is a workaround function. */
817   function copy($src_dn, $dst_dn)
818   {
819     /* Rename dn in possible object groups */
820     $ldap= $this->config->get_ldap_link();
821     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::fix($src_dn).'))',
822         array('cn'));
823     while ($attrs= $ldap->fetch()){
824       $og= new ogroup($this->config, $ldap->getDN());
825       unset($og->member[$src_dn]);
826       $og->member[$dst_dn]= $dst_dn;
827       $og->save ();
828     }
830     $ldap->cat($dst_dn);
831     $attrs= $ldap->fetch();
832     if (count($attrs)){
833       trigger_error("Trying to overwrite ".@LDAP::fix($dst_dn).", which already exists.",
834           E_USER_WARNING);
835       return (FALSE);
836     }
838     $ldap->cat($src_dn);
839     $attrs= $ldap->fetch();
840     if (!count($attrs)){
841       trigger_error("Trying to move ".@LDAP::fix($src_dn).", which does not seem to exist.",
842           E_USER_WARNING);
843       return (FALSE);
844     }
846     $ldap->cd($src_dn);
847     $ldap->search("objectClass=*",array("dn"));
848     while($attrs = $ldap->fetch()){
849       $src = $attrs['dn'];
850       $dst = preg_replace("/".normalizePreg($src_dn)."$/",$dst_dn,$attrs['dn']);
851       $this->_copy($src,$dst);
852     }
853     return (TRUE);
854   }
857   function move($src_dn, $dst_dn)
858   {
859     /* Copy source to destination */
860     if (!$this->copy($src_dn, $dst_dn)){
861       return (FALSE);
862     }
864     /* Delete source */
865     $ldap= $this->config->get_ldap_link();
866     $ldap->rmdir_recursive($src_dn);
867     if ($ldap->error != "Success"){
868       trigger_error("Trying to delete $src_dn failed.",
869           E_USER_WARNING);
870       return (FALSE);
871     }
873     return (TRUE);
874   }
877   /* Move/Rename complete trees */
878   function recursive_move($src_dn, $dst_dn)
879   {
880     /* Check if the destination entry exists */
881     $ldap= $this->config->get_ldap_link();
883     /* Check if destination exists - abort */
884     $ldap->cat($dst_dn, array('dn'));
885     if ($ldap->fetch()){
886       trigger_error("recursive_move $dst_dn already exists.",
887           E_USER_WARNING);
888       return (FALSE);
889     }
891     /* Perform a search for all objects to be moved */
892     $objects= array();
893     $ldap->cd($src_dn);
894     $ldap->search("(objectClass=*)", array("dn"));
895     while($attrs= $ldap->fetch()){
896       $dn= $attrs['dn'];
897       $objects[$dn]= strlen($dn);
898     }
900     /* Sort objects by indent level */
901     asort($objects);
902     reset($objects);
904     /* Copy objects from small to big indent levels by replacing src_dn by dst_dn */
905     foreach ($objects as $object => $len){
906       $src= $object;
907       $dst= preg_replace("/$src_dn$/", "$dst_dn", $object);
908       if (!$this->copy($src, $dst)){
909         return (FALSE);
910       }
911     }
913     /* Remove src_dn */
914     $ldap->cd($src_dn);
915     $ldap->recursive_remove();
916     return (TRUE);
917   }
920   function handle_post_events($mode, $add_attrs= array())
921   {
922     switch ($mode){
923       case "add":
924         $this->postcreate($add_attrs);
925       break;
927       case "modify":
928         $this->postmodify($add_attrs);
929       break;
931       case "remove":
932         $this->postremove($add_attrs);
933       break;
934     }
935   }
938   function saveCopyDialog(){
939   }
942   function getCopyDialog(){
943     return(array("string"=>"","status"=>""));
944   }
947   function PrepareForCopyPaste($source)
948   {
949     $todo = $this->attributes;
950     if(isset($this->CopyPasteVars)){
951       $todo = array_merge($todo,$this->CopyPasteVars);
952     }
954     if(count($this->objectclasses)){
955       $this->is_account = TRUE;
956       foreach($this->objectclasses as $class){
957         if(!in_array($class,$source['objectClass'])){
958           $this->is_account = FALSE;
959         }
960       }
961     }
963     foreach($todo as $var){
964       if (isset($source[$var])){
965         if(isset($source[$var]['count'])){
966           if($source[$var]['count'] > 1){
967             $this->$var = array();
968             $tmp = array();
969             for($i = 0 ; $i < $source[$var]['count']; $i++){
970               $tmp = $source[$var][$i];
971             }
972             $this->$var = $tmp;
973 #            echo $var."=".$tmp."<br>";
974           }else{
975             $this->$var = $source[$var][0];
976 #            echo $var."=".$source[$var][0]."<br>";
977           }
978         }else{
979           $this->$var= $source[$var];
980 #          echo $var."=".$source[$var]."<br>";
981         }
982       }
983     }
984   }
987   function handle_object_tagging($dn= "", $tag= "", $show= false)
988   {
989     //FIXME: How to optimize this? We have at least two
990     //       LDAP accesses per object. It would be a good
991     //       idea to have it integrated.
993     /* No dn? Self-operation... */
994     if ($dn == ""){
995       $dn= $this->dn;
997       /* No tag? Find it yourself... */
998       if ($tag == ""){
999         $len= strlen($dn);
1001         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1002         $relevant= array();
1003         foreach ($this->config->adepartments as $key => $ntag){
1005           /* This one is bigger than our dn, its not relevant... */
1006           if ($len <= strlen($key)){
1007             continue;
1008           }
1010           /* This one matches with the latter part. Break and don't fix this entry */
1011           if (preg_match('/(^|,)'.normalizePreg($key).'$/', $dn)){
1012             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1013             $relevant[strlen($key)]= $ntag;
1014             continue;
1015           }
1017         }
1019         /* If we've some relevant tags to set, just get the longest one */
1020         if (count($relevant)){
1021           ksort($relevant);
1022           $tmp= array_keys($relevant);
1023           $idx= end($tmp);
1024           $tag= $relevant[$idx];
1025           $this->gosaUnitTag= $tag;
1026         }
1027       }
1028     }
1031     /* Set tag? */
1032     if ($tag != ""){
1033       /* Set objectclass and attribute */
1034       $ldap= $this->config->get_ldap_link();
1035       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
1036       $attrs= $ldap->fetch();
1037       if(isset($attrs['gosaUnitTag'][0]) && $attrs['gosaUnitTag'][0] == $tag){
1038         if ($show) {
1039           echo sprintf(_("Object '%s' is already tagged"), @LDAP::fix($dn))."<br>";
1040           flush();
1041         }
1042         return;
1043       }
1044       if (count($attrs)){
1045         if ($show){
1046           echo sprintf(_("Adding tag (%s) to object '%s'"), $tag, @LDAP::fix($dn))."<br>";
1047           flush();
1048         }
1049         $nattrs= array("gosaUnitTag" => $tag);
1050         $nattrs['objectClass']= array();
1051         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
1052           $oc= $attrs['objectClass'][$i];
1053           if ($oc != "gosaAdministrativeUnitTag"){
1054             $nattrs['objectClass'][]= $oc;
1055           }
1056         }
1057         $nattrs['objectClass'][]= "gosaAdministrativeUnitTag";
1058         $ldap->cd($dn);
1059         $ldap->modify($nattrs);
1060         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
1061       } else {
1062         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not tagging ($tag) $dn - seems to have moved away", "Tagging");
1063       }
1065     } else {
1066       /* Remove objectclass and attribute */
1067       $ldap= $this->config->get_ldap_link();
1068       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
1069       $attrs= $ldap->fetch();
1070       if (isset($attrs['objectClass']) && !in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass'])){
1071         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "$dn is not tagged", "Tagging");
1072         return;
1073       }
1074       if (count($attrs)){
1075         if ($show){
1076           echo sprintf(_("Removing tag from object '%s'"), @LDAP::fix($dn))."<br>";
1077           flush();
1078         }
1079         $nattrs= array("gosaUnitTag" => array());
1080         $nattrs['objectClass']= array();
1081         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
1082           $oc= $attrs['objectClass'][$i];
1083           if ($oc != "gosaAdministrativeUnitTag"){
1084             $nattrs['objectClass'][]= $oc;
1085           }
1086         }
1087         $ldap->cd($dn);
1088         $ldap->modify($nattrs);
1089         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
1090       } else {
1091         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not removing tag ($tag) $dn - seems to have moved away", "Tagging");
1092       }
1093     }
1095   }
1098   /* Add possibility to stop remove process */
1099   function allow_remove()
1100   {
1101     $reason= "";
1102     return $reason;
1103   }
1106   /* Create a snapshot of the current object */
1107   function create_snapshot($type= "snapshot", $description= array())
1108   {
1110     /* Check if snapshot functionality is enabled */
1111     if(!$this->snapshotEnabled()){
1112       return;
1113     }
1115     /* Get configuration from gosa.conf */
1116     $tmp = $this->config->current;
1118     /* Create lokal ldap connection */
1119     $ldap= $this->config->get_ldap_link();
1120     $ldap->cd($this->config->current['BASE']);
1122     /* check if there are special server configurations for snapshots */
1123     if(!isset($tmp['SNAPSHOT_SERVER'])){
1125       /* Source and destination server are both the same, just copy source to dest obj */
1126       $ldap_to      = $ldap;
1127       $snapldapbase = $this->config->current['BASE'];
1129     }else{
1130       $server         = $tmp['SNAPSHOT_SERVER'];
1131       $user           = $tmp['SNAPSHOT_USER'];
1132       $password       = $tmp['SNAPSHOT_PASSWORD'];
1133       $snapldapbase   = $tmp['SNAPSHOT_BASE'];
1135       $ldap_to        = new LDAP($user,$password, $server);
1136       $ldap_to -> cd($snapldapbase);
1137       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$snapldapbase));
1138     }
1140     /* check if the dn exists */ 
1141     if ($ldap->dn_exists($this->dn)){
1143       /* Extract seconds & mysecs, they are used as entry index */
1144       list($usec, $sec)= explode(" ", microtime());
1146       /* Collect some infos */
1147       $base           = $this->config->current['BASE'];
1148       $snap_base      = $tmp['SNAPSHOT_BASE'];
1149       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1150       $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1152       /* Create object */
1153 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1154       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1155       $newName          = preg_replace("/\./", "", $sec."-".$usec);
1156       $target= array();
1157       $target['objectClass']            = array("top", "gosaSnapshotObject");
1158       $target['gosaSnapshotData']       = gzcompress($data, 6);
1159       $target['gosaSnapshotType']       = $type;
1160       $target['gosaSnapshotDN']         = $this->dn;
1161       $target['description']            = $description;
1162       $target['gosaSnapshotTimestamp']  = $newName;
1164       /* Insert the new snapshot 
1165          But we have to check first, if the given gosaSnapshotTimestamp
1166          is already used, in this case we should increment this value till there is 
1167          an unused value. */ 
1168       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1169       $ldap_to->cat($new_dn);
1170       while($ldap_to->count()){
1171         $ldap_to->cat($new_dn);
1172         $newName = preg_replace("/\./", "", $sec."-".($usec++));
1173         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1174         $target['gosaSnapshotTimestamp']  = $newName;
1175       } 
1177       /* Inset this new snapshot */
1178       $ldap_to->cd($snapldapbase);
1179       $ldap_to->create_missing_trees($snapldapbase);
1180       $ldap_to->create_missing_trees($new_base);
1181       $ldap_to->cd($new_dn);
1182       $ldap_to->add($target);
1183     
1184       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1185       show_ldap_error($ldap_to->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1186     }
1187   }
1189   function remove_snapshot($dn)
1190   {
1191     $ui       = get_userinfo();
1192     $old_dn   = $this->dn; 
1193     $this->dn = $dn;
1194     $ldap = $this->config->get_ldap_link();
1195     $ldap->cd($this->config->current['BASE']);
1196     $ldap->rmdir_recursive($dn);
1197     $this->dn = $old_dn;
1198   }
1201   /* returns true if snapshots are enabled, and false if it is disalbed
1202      There will also be some errors psoted, if the configuration failed */
1203   function snapshotEnabled()
1204   {
1205     $tmp = $this->config->current;
1206     if(isset($tmp['ENABLE_SNAPSHOT'])){
1207       if (preg_match("/^true$/i", $tmp['ENABLE_SNAPSHOT']) || preg_match("/yes/i", $tmp['ENABLE_SNAPSHOT'])){
1209         /* Check if the snapshot_base is defined */
1210         if(!isset($tmp['SNAPSHOT_BASE'])){
1211           print_red(sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not configured in your gosa.conf."),"SNAPSHOT_BASE"));
1212           return(FALSE);
1213         }
1215         /* check if there are special server configurations for snapshots */
1216         if(isset($tmp['SNAPSHOT_SERVER'])){
1218           /* check if all required vars are available to create a new ldap connection */
1219           $missing = "";
1220           foreach(array("SNAPSHOT_SERVER","SNAPSHOT_USER","SNAPSHOT_PASSWORD","SNAPSHOT_BASE") as $var){
1221             if(!isset($tmp[$var])){
1222               $missing .= $var." ";
1223               print_red(sprintf(_("The snapshot functionality is enabled, but the required variable(s) '%s' is not configured in your gosa.conf."),$missing));
1224               return(FALSE);
1225             }
1226           }
1227         }
1228         return(TRUE);
1229       }
1230     }
1231     return(FALSE);
1232   }
1235   /* Return available snapshots for the given base 
1236    */
1237   function Available_SnapsShots($dn,$raw = false)
1238   {
1239     if(!$this->snapshotEnabled()) return(array());
1241     /* Create an additional ldap object which
1242        points to our ldap snapshot server */
1243     $ldap= $this->config->get_ldap_link();
1244     $ldap->cd($this->config->current['BASE']);
1245     $cfg= &$this->config->current;
1247     /* check if there are special server configurations for snapshots */
1249     if(isset($cfg['SERVER']) && isset($cfg['SNAPSHOT_SERVER']) && $cfg['SERVER'] == $cfg['SNAPSHOT_SERVER']){
1250       $ldap_to    = $ldap;
1251     }elseif(isset($cfg['SNAPSHOT_SERVER'])){
1252       $server       = $cfg['SNAPSHOT_SERVER'];
1253       $user         = $cfg['SNAPSHOT_USER'];
1254       $password     = $cfg['SNAPSHOT_PASSWORD'];
1255       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1257       $ldap_to      = new LDAP($user,$password, $server);
1258       $ldap_to -> cd ($snapldapbase);
1259       show_ldap_error($ldap->get_error(), sprintf(_("Method get available snapshots with dn '%s' failed."),$this->dn));
1260     }else{
1261       $ldap_to    = $ldap;
1262     }
1264     /* Prepare bases and some other infos */
1265     $base           = $this->config->current['BASE'];
1266     $snap_base      = $cfg['SNAPSHOT_BASE'];
1267     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1268     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1269     $tmp            = array(); 
1271     /* Fetch all objects with  gosaSnapshotDN=$dn */
1272     $ldap_to->cd($new_base);
1273     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1274         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1276     /* Put results into a list and add description if missing */
1277     while($entry = $ldap_to->fetch()){ 
1278       if(!isset($entry['description'][0])){
1279         $entry['description'][0]  = "";
1280       }
1281       $tmp[] = $entry; 
1282     }
1284     /* Return the raw array, or format the result */
1285     if($raw){
1286       return($tmp);
1287     }else{  
1288       $tmp2 = array();
1289       foreach($tmp as $entry){
1290         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1291       }
1292     }
1293     return($tmp2);
1294   }
1297   function getAllDeletedSnapshots($base_of_object,$raw = false)
1298   {
1299     if(!$this->snapshotEnabled()) return(array());
1301     /* Create an additional ldap object which
1302        points to our ldap snapshot server */
1303     $ldap= $this->config->get_ldap_link();
1304     $ldap->cd($this->config->current['BASE']);
1305     $cfg= &$this->config->current;
1307     /* check if there are special server configurations for snapshots */
1308     if(isset($cfg['SNAPSHOT_SERVER'])){
1309       $server       = $cfg['SNAPSHOT_SERVER'];
1310       $user         = $cfg['SNAPSHOT_USER'];
1311       $password     = $cfg['SNAPSHOT_PASSWORD'];
1312       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1313       $ldap_to      = new LDAP($user,$password, $server);
1314       $ldap_to->cd ($snapldapbase);
1315       show_ldap_error($ldap_to->get_error(), sprintf(_("Method get deleted snapshots with dn '%s' failed."),$this->dn));
1316     }else{
1317       $ldap_to    = $ldap;
1318     }
1320     /* Prepare bases */ 
1321     $base           = $this->config->current['BASE'];
1322     $snap_base      = $cfg['SNAPSHOT_BASE'];
1323     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1325     /* Fetch all objects and check if they do not exist anymore */
1326     $ui = get_userinfo();
1327     $tmp = array();
1328     $ldap_to->cd($new_base);
1329     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1330     while($entry = $ldap_to->fetch()){
1332       $chk =  str_replace($new_base,"",$entry['dn']);
1333       if(preg_match("/,ou=/",$chk)) continue;
1335       if(!isset($entry['description'][0])){
1336         $entry['description'][0]  = "";
1337       }
1338       $tmp[] = $entry; 
1339     }
1341     /* Check if entry still exists */
1342     foreach($tmp as $key => $entry){
1343       $ldap->cat($entry['gosaSnapshotDN'][0]);
1344       if($ldap->count()){
1345         unset($tmp[$key]);
1346       }
1347     }
1349     /* Format result as requested */
1350     if($raw) {
1351       return($tmp);
1352     }else{
1353       $tmp2 = array();
1354       foreach($tmp as $key => $entry){
1355         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1356       }
1357     }
1358     return($tmp2);
1359   } 
1362   /* Restore selected snapshot */
1363   function restore_snapshot($dn)
1364   {
1365     if(!$this->snapshotEnabled()) return(array());
1367     $ldap= $this->config->get_ldap_link();
1368     $ldap->cd($this->config->current['BASE']);
1369     $cfg= &$this->config->current;
1371     /* check if there are special server configurations for snapshots */
1372     if(isset($cfg['SNAPSHOT_SERVER'])){
1373       $server       = $cfg['SNAPSHOT_SERVER'];
1374       $user         = $cfg['SNAPSHOT_USER'];
1375       $password     = $cfg['SNAPSHOT_PASSWORD'];
1376       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1377       $ldap_to      = new LDAP($user,$password, $server);
1378       $ldap_to->cd ($snapldapbase);
1379       show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$snapldapbase));
1380     }else{
1381       $ldap_to    = $ldap;
1382     }
1384     /* Get the snapshot */ 
1385     $ldap_to->cat($dn);
1386     $restoreObject = $ldap_to->fetch();
1388     /* Prepare import string */
1389     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1391     /* Import the given data */
1392     $ldap->import_complete_ldif($data,$err,false,false);
1393     show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$dn));
1394   }
1397   function showSnapshotDialog($base,$baseSuffixe)
1398   {
1399     $once = true;
1400     foreach($_POST as $name => $value){
1402       /* Create a new snapshot, display a dialog */
1403       if(preg_match("/^CreateSnapShotDialog_/",$name) && $once){
1404         $once = false;
1405         $entry = preg_replace("/^CreateSnapShotDialog_/","",$name);
1406         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1407         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1408       }
1410       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1411       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1412         $once = false;
1413         $entry = preg_replace("/^RestoreSnapShotDialog_/","",$name);
1414         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1415         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1416         $this->snapDialog->display_restore_dialog = true;
1417       }
1419       /* Restore one of the already deleted objects */
1420       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1421           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1422         $once = false;
1423         $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1424         $this->snapDialog->set_snapshot_bases($baseSuffixe);
1425         $this->snapDialog->display_restore_dialog      = true;
1426         $this->snapDialog->display_all_removed_objects  = true;
1427       }
1429       /* Restore selected snapshot */
1430       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1431         $once = false;
1432         $entry = preg_replace("/^RestoreSnapShot_/","",$name);
1433         $entry = base64_decode(trim(preg_replace("/_[xy]$/","",$entry)));
1434         if(!empty($entry)){
1435           $this->restore_snapshot($entry);
1436           $this->snapDialog = NULL;
1437         }
1438       }
1439     }
1441     /* Create a new snapshot requested, check
1442        the given attributes and create the snapshot*/
1443     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1444       $this->snapDialog->save_object();
1445       $msgs = $this->snapDialog->check();
1446       if(count($msgs)){
1447         foreach($msgs as $msg){
1448           print_red($msg);
1449         }
1450       }else{
1451         $this->dn =  $this->snapDialog->dn;
1452         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1453         $this->snapDialog = NULL;
1454       }
1455     }
1457     /* Restore is requested, restore the object with the posted dn .*/
1458     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1459     }
1461     if(isset($_POST['CancelSnapshot'])){
1462       $this->snapDialog = NULL;
1463     }
1465     if(is_object($this->snapDialog )){
1466       $this->snapDialog->save_object();
1467       return($this->snapDialog->execute());
1468     }
1469   }
1472   static function plInfo()
1473   {
1474     return array();
1475   }
1478   function set_acl_base($base)
1479   {
1480     $this->acl_base= $base;
1481   }
1484   function set_acl_category($category)
1485   {
1486     $this->acl_category= "$category/";
1487   }
1490   function acl_is_writeable($attribute,$skip_write = FALSE)
1491   {
1492     $ui= get_userinfo();
1493     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1494   }
1497   function acl_is_readable($attribute)
1498   {
1499     $ui= get_userinfo();
1500     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1501   }
1504   function acl_is_createable()
1505   {
1506     $ui= get_userinfo();
1507     return preg_match('/c/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1508   }
1511   function acl_is_removeable()
1512   {
1513     $ui= get_userinfo();
1514     return preg_match('/d/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1515   }
1518   function acl_is_moveable()
1519   {
1520     $ui= get_userinfo();
1521     return preg_match('/m/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1522   }
1525   function acl_have_any_permissions()
1526   {
1527   }
1530   function getacl($attribute,$skip_write= FALSE)
1531   {
1532     $ui= get_userinfo();
1533     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1534   }
1536   /* Get all allowed bases to move an object to or to create a new object.
1537      Idepartments also contains all base departments which lead to the allowed bases */
1538   function get_allowed_bases($category = "")
1539   {
1540     $ui = get_userinfo();
1541     $deps = array();
1543     /* Set category */ 
1544     if(empty($category)){
1545       $category = $this->acl_category.get_class($this);
1546     }
1548     /* Is this a new object ? Or just an edited existing object */
1549     if(!$this->initially_was_account && $this->is_account){
1550       $new = true;
1551     }else{
1552       $new = false;
1553     }
1555     $cat_bases = $ui->get_module_departments(preg_replace("/\/.*$/","",$category));
1556     foreach($this->config->idepartments as $dn => $name){
1557       
1558       if(!in_array_ics($dn,$cat_bases)){
1559         continue;
1560       }
1561       
1562       $acl = $ui->get_permissions($dn,$category);
1563       if($new && preg_match("/c/",$acl)){
1564         $deps[$dn] = $name;
1565       }elseif(!$new && preg_match("/m/",$acl)){
1566         $deps[$dn] = $name;
1567       }
1568     }
1570     /* Add current base */      
1571     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1572       $deps[$this->base] = $this->config->idepartments[$this->base];
1573     }else{
1574       echo "No default base found. ".$this->base."<br> ";
1575     }
1577     return($deps);
1578   }
1580   /* This function modifies object acls too, if an object is moved.
1581    *  $old_dn   specifies the actually used dn
1582    *  $new_dn   specifies the destiantion dn
1583    */
1584   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1585   {
1586     /* Check if old_dn is empty. This should never happen */
1587     if(empty($old_dn) || empty($new_dn)){
1588       trigger_error("Failed to check acl dependencies, wrong dn given.");
1589       return;
1590     }
1592     /* Update userinfo if necessary */
1593     if($_SESSION['ui']->dn == $old_dn){
1594       $_SESSION['ui']->dn = $new_dn;
1595       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current user dn from '".$old_dn."' to '".$new_dn."'");
1596     }
1598     /* Object was moved, ensure that all acls will be moved too */
1599     if($new_dn != $old_dn && $old_dn != "new"){
1601       /* get_ldap configuration */
1602       $update = array();
1603       $ldap = $this->config->get_ldap_link();
1604       $ldap->cd ($this->config->current['BASE']);
1605       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*))",array("cn","gosaAclEntry"));
1606       while($attrs = $ldap->fetch()){
1608         $acls = array();
1610         /* Walk through acls */
1611         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1613           /* Reset vars */
1614           $found = false;
1616           /* Get Acl parts */
1617           $acl_parts = split(":",$attrs['gosaAclEntry'][$i]);
1619           /* Get every single member for this acl */  
1620           $members = array();  
1621           if(preg_match("/,/",$acl_parts[2])){
1622             $members = split(",",$acl_parts[2]);
1623           }else{
1624             $members = array($acl_parts[2]);
1625           } 
1626       
1627           /* Check if member match current dn */
1628           foreach($members as $key => $member){
1629             $member = base64_decode($member);
1630             if($member == $old_dn){
1631               $found = true;
1632               $members[$key] = base64_encode($new_dn);
1633             }
1634           } 
1635          
1636           /* Create new member string */ 
1637           $new_members = "";
1638           foreach($members as $member){
1639             $new_members .= $member.",";
1640           }
1641           $new_members = preg_replace("/,$/","",$new_members);
1642           $acl_parts[2] = $new_members;
1643         
1644           /* Reconstruckt acl entry */
1645           $acl_str  ="";
1646           foreach($acl_parts as $t){
1647            $acl_str .= $t.":";
1648           }
1649           $acl_str = preg_replace("/:$/","",$acl_str);
1650        }
1652        /* Acls for this object must be adjusted */
1653        if($found){
1655           if($output_changes){
1656             echo "<font color='green'>".
1657                   _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1658                   $old_dn.
1659                   "</b><br>&nbsp;-"._("to")."&nbsp;<b>".
1660                   $new_dn.
1661                   "</b></font><br>";
1662           }
1663           $update[$attrs['dn']] =array();
1664           foreach($acls as $acl){
1665             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1666           }
1667         }
1668       }
1670       /* Write updated acls */
1671       foreach($update as $dn => $attrs){
1672         $ldap->cd($dn);
1673         $ldap->modify($attrs);
1674       }
1675     }
1676   }
1678   
1680   /* This function enables the entry Serial ID check.
1681    * If an entry was edited while we have edited the entry too,
1682    *  an error message will be shown. 
1683    * To configure this check correctly read the FAQ.
1684    */    
1685   function enable_CSN_check()
1686   {
1687     $this->CSN_check_active =TRUE;
1688     $this->entryCSN = getEntryCSN($this->dn);
1689   }
1692   
1694   function set_multi_edit_value()
1695   {
1697   }
1700   /*! \brief  Prepares the plugin to be used for multiple edit
1701    */
1702   function init_multiple_support()
1703   {
1704     foreach($this->attributes as $attr){
1705       if(isset($this->$attr) && is_string($this->$attr)){
1706         $this->$attr = "{default}";
1707       }
1708     }
1709   }
1712   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1713       @return array Cotaining all mdofied values. 
1714    */
1715   function get_multi_edit_values()
1716   {
1717     $ret = array();
1718     foreach($this->attributes as $attr){
1719       if($this->$attr != "{default}"){
1720         $ret[$attr] = $this->$attr;
1721       }
1722     }
1723     return($ret);
1724   }
1727   /*! \brief execute plugin
1729     Generates the html output for this node
1730    */
1731   function multiple_execute()
1732   {
1733     /* This one is empty currently. Fabian - please fill in the docu code */
1734     $_SESSION['current_class_for_help'] = get_class($this);
1736     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1737     $_SESSION['LOCK_VARS_TO_USE'] = $_SESSION['LOCK_VARS_USED'] =array();
1738     
1739     return("Multiple edit is currently not implemented for this plugin.");
1740   }
1743   /*! \brief   Save HTML posted data to object for multiple edit
1744    */
1745   function multiple_save_object()
1746   {
1747     if(empty($this->entryCSN) && $this->CSN_check_active){
1748       $this->entryCSN = getEntryCSN($this->dn);
1749     }
1751     /* Save values to object */
1752     foreach ($this->attributes as $val){
1753       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
1755         /* Check for modifications */
1756         if (get_magic_quotes_gpc()) {
1757           $data= stripcslashes($_POST["$val"]);
1758         } else {
1759           $data= $this->$val = $_POST["$val"];
1760         }
1761         if ($this->$val != $data && $data != "{default}"){
1762           $this->is_modified= TRUE;
1763         }
1764     
1765         /* IE post fix */
1766         if(isset($data[0]) && $data[0] == chr(194)) {
1767           $data = "";  
1768         }
1769         if($data != "{default}"){
1770           $this->$val= $data;
1771         }
1772       }
1773     }
1774   }
1777   /*! \brief  Check given values in multiple edit
1778       @return array Error messages
1779    */
1780   function multiple_check()
1781   {
1782     $message = plugin::check();
1783     return($message);
1784   }
1787 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1788 ?>