Code

Removed {default} checks from plugin
[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();
131   var $multi_boxes = array();
133   /*! \brief plugin constructor
135     If 'dn' is set, the node loads the given 'dn' from LDAP
137     \param dn Distinguished name to initialize plugin from
138     \sa plugin()
139    */
140   function plugin (&$config, $dn= NULL, $parent= NULL)
141   {
142     /* Configuration is fine, allways */
143     $this->config= &$config;    
144     $this->dn= $dn;
146     /* Handle new accounts, don't read information from LDAP */
147     if ($dn == "new"){
148       return;
149     }
151     /* Save current dn as acl_base */
152     $this->acl_base= $dn;
154     /* Get LDAP descriptor */
155     $ldap= $this->config->get_ldap_link();
156     if ($dn !== NULL){
158       /* Load data to 'attrs' and save 'dn' */
159       if ($parent !== NULL){
160         $this->attrs= $parent->attrs;
161       } else {
162         $ldap->cat ($dn);
163         $this->attrs= $ldap->fetch();
164       }
166       /* Copy needed attributes */
167       foreach ($this->attributes as $val){
168         $found= array_key_ics($val, $this->attrs);
169         if ($found != ""){
170           $this->$val= $this->attrs["$found"][0];
171         }
172       }
174       /* gosaUnitTag loading... */
175       if (isset($this->attrs['gosaUnitTag'][0])){
176         $this->gosaUnitTag= $this->attrs['gosaUnitTag'][0];
177       }
179       /* Set the template flag according to the existence of objectClass
180          gosaUserTemplate */
181       if (isset($this->attrs['objectClass'])){
182         if (in_array ("gosaUserTemplate", $this->attrs['objectClass'])){
183           $this->is_template= TRUE;
184           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
185               "found", "Template check");
186         }
187       }
189       /* Is Account? */
190       $found= TRUE;
191       foreach ($this->objectclasses as $obj){
192         if (preg_match('/top/i', $obj)){
193           continue;
194         }
195         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
196           $found= FALSE;
197           break;
198         }
199       }
200       if ($found){
201         $this->is_account= TRUE;
202         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
203             "found", "Object check");
204       }
206       /* Prepare saved attributes */
207       $this->saved_attributes= $this->attrs;
208       foreach ($this->saved_attributes as $index => $value){
209         if (preg_match('/^[0-9]+$/', $index)){
210           unset($this->saved_attributes[$index]);
211           continue;
212         }
213         if (!in_array($index, $this->attributes) && $index != "objectClass"){
214           unset($this->saved_attributes[$index]);
215           continue;
216         }
217         if ($this->saved_attributes[$index]["count"] == 1){
218           $tmp= $this->saved_attributes[$index][0];
219           unset($this->saved_attributes[$index]);
220           $this->saved_attributes[$index]= $tmp;
221           continue;
222         }
224         unset($this->saved_attributes["$index"]["count"]);
225       }
226     }
228     /* Save initial account state */
229     $this->initially_was_account= $this->is_account;
230   }
233   /*! \brief execute plugin
235     Generates the html output for this node
236    */
237   function execute()
238   {
239     /* This one is empty currently. Fabian - please fill in the docu code */
240     $_SESSION['current_class_for_help'] = get_class($this);
242     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
243     $_SESSION['LOCK_VARS_TO_USE'] = $_SESSION['LOCK_VARS_USED'] =array();
244   }
246   /*! \brief execute plugin
247      Removes object from parent
248    */
249   function remove_from_parent()
250   {
251     /* include global link_info */
252     $ldap= $this->config->get_ldap_link();
254     /* Get current objectClasses in order to add the required ones */
255     $ldap->cat($this->dn);
256     $tmp= $ldap->fetch ();
257     $oc= array();
258     if (isset($tmp['objectClass'])){
259       $oc= $tmp['objectClass'];
260       unset($oc['count']);
261     }
263     /* Remove objectClasses from entry */
264     $ldap->cd($this->dn);
265     $this->attrs= array();
266     $this->attrs['objectClass']= array_remove_entries($this->objectclasses,$oc);
268     /* Unset attributes from entry */
269     foreach ($this->attributes as $val){
270       $this->attrs["$val"]= array();
271     }
273     /* Unset account info */
274     $this->is_account= FALSE;
276     /* Do not write in plugin base class, this must be done by
277        children, since there are normally additional attribs,
278        lists, etc. */
279     /*
280        $ldap->modify($this->attrs);
281      */
282   }
285   /*! \brief   Save HTML posted data to object 
286    */
287   function save_object()
288   {
289     /* Update entry CSN if it is empty. */
290     if(empty($this->entryCSN) && $this->CSN_check_active){
291       $this->entryCSN = getEntryCSN($this->dn);
292     }
294     /* Save values to object */
295     foreach ($this->attributes as $val){
296       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
297         /* Check for modifications */
298         if (get_magic_quotes_gpc()) {
299           $data= stripcslashes($_POST["$val"]);
300         } else {
301           $data= $this->$val = $_POST["$val"];
302         }
303         if ($this->$val != $data){
304           $this->is_modified= TRUE;
305         }
306     
307         /* Okay, how can I explain this fix ... 
308          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
309          * So IE posts these 'unselectable' option, with value = chr(194) 
310          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
311          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
312          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
313          */
314         if(isset($data[0]) && $data[0] == chr(194)) {
315           $data = "";  
316         }
317         $this->$val= $data;
318         //echo "<font color='blue'>".$val."</font><br>";
319       }else{
320         //echo "<font color='red'>".$val."</font><br>";
321       }
322     }
323   }
326   /* Save data to LDAP, depending on is_account we save or delete */
327   function save()
328   {
329     /* include global link_info */
330     $ldap= $this->config->get_ldap_link();
332     /* Save all plugins */
333     $this->entryCSN = "";
335     /* Start with empty array */
336     $this->attrs= array();
338     /* Get current objectClasses in order to add the required ones */
339     $ldap->cat($this->dn);
340     
341     $tmp= $ldap->fetch ();
343     $oc= array();
344     if (isset($tmp['objectClass'])){
345       $oc= $tmp["objectClass"];
346       $this->is_new= FALSE;
347       unset($oc['count']);
348     } else {
349       $this->is_new= TRUE;
350     }
352     /* Load (minimum) attributes, add missing ones */
353     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
355     /* Copy standard attributes */
356     foreach ($this->attributes as $val){
357       if ($this->$val != ""){
358         $this->attrs["$val"]= $this->$val;
359       } elseif (!$this->is_new) {
360         $this->attrs["$val"]= array();
361       }
362     }
364   }
367   function cleanup()
368   {
369     foreach ($this->attrs as $index => $value){
371       /* Convert arrays with one element to non arrays, if the saved
372          attributes are no array, too */
373       if (is_array($this->attrs[$index]) && 
374           count ($this->attrs[$index]) == 1 &&
375           isset($this->saved_attributes[$index]) &&
376           !is_array($this->saved_attributes[$index])){
377           
378         $tmp= $this->attrs[$index][0];
379         $this->attrs[$index]= $tmp;
380       }
382       /* Remove emtpy arrays if they do not differ */
383       if (is_array($this->attrs[$index]) &&
384           count($this->attrs[$index]) == 0 &&
385           !isset($this->saved_attributes[$index])){
386           
387         unset ($this->attrs[$index]);
388         continue;
389       }
391       /* Remove single attributes that do not differ */
392       if (!is_array($this->attrs[$index]) &&
393           isset($this->saved_attributes[$index]) &&
394           !is_array($this->saved_attributes[$index]) &&
395           $this->attrs[$index] == $this->saved_attributes[$index]){
397         unset ($this->attrs[$index]);
398         continue;
399       }
401       /* Remove arrays that do not differ */
402       if (is_array($this->attrs[$index]) && 
403           isset($this->saved_attributes[$index]) &&
404           is_array($this->saved_attributes[$index])){
405           
406         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
407           unset ($this->attrs[$index]);
408           continue;
409         }
410       }
411     }
413     /* Update saved attributes and ensure that next cleanups will be successful too */
414     foreach($this->attrs as $name => $value){
415       $this->saved_attributes[$name] = $value;
416     }
417   }
419   /* Check formular input */
420   function check()
421   {
422     $message= array();
424     /* Skip if we've no config object */
425     if (!isset($this->config) || !is_object($this->config)){
426       return $message;
427     }
429     /* Find hooks entries for this class */
430     $command= $this->config->search(get_class($this), "CHECK", array('menu', 'tabs'));
432     if ($command != ""){
434       if (!check_command($command)){
435         $message[]= sprintf(_("Command '%s', specified as CHECK hook for plugin '%s' doesn't seem to exist."), $command,
436                             get_class($this));
437       } else {
439         /* Generate "ldif" for check hook */
440         $ldif= "dn: $this->dn\n";
441         
442         /* ... objectClasses */
443         foreach ($this->objectclasses as $oc){
444           $ldif.= "objectClass: $oc\n";
445         }
446         
447         /* ... attributes */
448         foreach ($this->attributes as $attr){
449           if ($this->$attr == ""){
450             continue;
451           }
452           if (is_array($this->$attr)){
453             foreach ($this->$attr as $val){
454               $ldif.= "$attr: $val\n";
455             }
456           } else {
457               $ldif.= "$attr: ".$this->$attr."\n";
458           }
459         }
461         /* Append empty line */
462         $ldif.= "\n";
464         /* Feed "ldif" into hook and retrieve result*/
465         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
466         $fh= proc_open($command, $descriptorspec, $pipes);
467         if (is_resource($fh)) {
468           fwrite ($pipes[0], $ldif);
469           fclose($pipes[0]);
470           
471           $result= stream_get_contents($pipes[1]);
472           if ($result != ""){
473             $message[]= $result;
474           }
475           
476           fclose($pipes[1]);
477           fclose($pipes[2]);
478           proc_close($fh);
479         }
480       }
482     }
484     /* Check entryCSN */
485     if($this->CSN_check_active){
486       $current_csn = getEntryCSN($this->dn);
487       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
488         $this->entryCSN = $current_csn;
489         $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.");
490       }
491     }
492     return ($message);
493   }
495   /* Adapt from template, using 'dn' */
496   function adapt_from_template($dn)
497   {
498     /* Include global link_info */
499     $ldap= $this->config->get_ldap_link();
501     /* Load requested 'dn' to 'attrs' */
502     $ldap->cat ($dn);
503     $this->attrs= $ldap->fetch();
505     /* Walk through attributes */
506     foreach ($this->attributes as $val){
508       if (isset($this->attrs["$val"][0])){
510         /* If attribute is set, replace dynamic parts: 
511            %sn, %givenName and %uid. Fill these in our local variables. */
512         $value= $this->attrs["$val"][0];
514         foreach (array("sn", "givenName", "uid") as $repl){
515           if (preg_match("/%$repl/i", $value)){
516             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
517           }
518         }
519         $this->$val= $value;
520       }
521     }
523     /* Is Account? */
524     $found= TRUE;
525     foreach ($this->objectclasses as $obj){
526       if (preg_match('/top/i', $obj)){
527         continue;
528       }
529       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
530         $found= FALSE;
531         break;
532       }
533     }
534     if ($found){
535       $this->is_account= TRUE;
536     }
537   }
539   /* Indicate whether a password change is needed or not */
540   function password_change_needed()
541   {
542     return FALSE;
543   }
546   /* Show header message for tab dialogs */
547   function show_enable_header($button_text, $text, $disabled= FALSE)
548   {
549     if (($disabled == TRUE) || (!$this->acl_is_createable())){
550       $state= "disabled";
551     } else {
552       $state= "";
553     }
554     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
555     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
556       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
558     return($display);
559   }
562   /* Show header message for tab dialogs */
563   function show_disable_header($button_text, $text, $disabled= FALSE)
564   {
565     if (($disabled == TRUE) || !$this->acl_is_removeable()){
566       $state= "disabled";
567     } else {
568       $state= "";
569     }
570     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
571     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
572       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
574     return($display);
575   }
578   /* Show header message for tab dialogs */
579   function show_header($button_text, $text, $disabled= FALSE)
580   {
581     echo "FIXME: show_header should be replaced by show_disable_header and show_enable_header<br>";
582     if ($disabled == TRUE){
583       $state= "disabled";
584     } else {
585       $state= "";
586     }
587     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
588     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
589       ($this->acl_is_createable()?'':'disabled')." ".$state.
590       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
592     return($display);
593   }
596   function postcreate($add_attrs= array())
597   {
598     /* Find postcreate entries for this class */
599     $command= $this->config->search(get_class($this), "POSTCREATE",array('menu', 'tabs'));
601     if ($command != ""){
603       /* Additional attributes */
604       foreach ($add_attrs as $name => $value){
605         $command= preg_replace("/%$name/", $value, $command);
606       }
608       /* Walk through attribute list */
609       foreach ($this->attributes as $attr){
610         if (!is_array($this->$attr)){
611           $command= preg_replace("/%$attr/", $this->$attr, $command);
612         }
613       }
614       $command= preg_replace("/%dn/", $this->dn, $command);
616       if (check_command($command)){
617         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
618             $command, "Execute");
620         exec($command);
621       } else {
622         $message= sprintf(_("Command '%s', specified as POSTCREATE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
623         print_red ($message);
624       }
625     }
626   }
628   function postmodify($add_attrs= array())
629   {
630     /* Find postcreate entries for this class */
631     $command= $this->config->search(get_class($this), "POSTMODIFY",array('menu','tabs'));
633     if ($command != ""){
635       /* Additional attributes */
636       foreach ($add_attrs as $name => $value){
637         $command= preg_replace("/%$name/", $value, $command);
638       }
640       /* Walk through attribute list */
641       foreach ($this->attributes as $attr){
642         if (!is_array($this->$attr)){
643           $command= preg_replace("/%$attr/", $this->$attr, $command);
644         }
645       }
646       $command= preg_replace("/%dn/", $this->dn, $command);
648       if (check_command($command)){
649         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
650             $command, "Execute");
652         exec($command);
653       } else {
654         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, get_class($this));
655         print_red ($message);
656       }
657     }
658   }
660   function postremove($add_attrs= array())
661   {
662     /* Find postremove entries for this class */
663     $command= $this->config->search(get_class($this), "POSTREMOVE",array('menu','tabs'));
664     if ($command != ""){
666       /* Additional attributes */
667       foreach ($add_attrs as $name => $value){
668         $command= preg_replace("/%$name/", $value, $command);
669       }
671       /* Walk through attribute list */
672       foreach ($this->attributes as $attr){
673         if (!is_array($this->$attr)){
674           $command= preg_replace("/%$attr/", $this->$attr, $command);
675         }
676       }
677       $command= preg_replace("/%dn/", $this->dn, $command);
679       /* Additional attributes */
680       foreach ($add_attrs as $name => $value){
681         $command= preg_replace("/%$name/", $value, $command);
682       }
684       if (check_command($command)){
685         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
686             $command, "Execute");
688         exec($command);
689       } else {
690         $message= sprintf(_("Command '%s', specified as POSTREMOVE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
691         print_red ($message);
692       }
693     }
694   }
696   /* Create unique DN */
697   function create_unique_dn($attribute, $base)
698   {
699     $ldap= $this->config->get_ldap_link();
700     $base= preg_replace("/^,*/", "", $base);
702     /* Try to use plain entry first */
703     $dn= "$attribute=".$this->$attribute.",$base";
704     $ldap->cat ($dn, array('dn'));
705     if (!$ldap->fetch()){
706       return ($dn);
707     }
709     /* Look for additional attributes */
710     foreach ($this->attributes as $attr){
711       if ($attr == $attribute || $this->$attr == ""){
712         continue;
713       }
715       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
716       $ldap->cat ($dn, array('dn'));
717       if (!$ldap->fetch()){
718         return ($dn);
719       }
720     }
722     /* None found */
723     return ("none");
724   }
726   function rebind($ldap, $referral)
727   {
728     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
729     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
730       $this->error = "Success";
731       $this->hascon=true;
732       $this->reconnect= true;
733       return (0);
734     } else {
735       $this->error = "Could not bind to " . $credentials['ADMIN'];
736       return NULL;
737     }
738   }
741   /* Recursively copy ldap object */
742   function _copy($src_dn,$dst_dn)
743   {
744     $ldap=$this->config->get_ldap_link();
745     $ldap->cat($src_dn);
746     $attrs= $ldap->fetch();
748     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
749     $ds= ldap_connect($this->config->current['SERVER']);
750     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
751     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
752       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
753     }
755     $r=ldap_bind($ds,$this->config->current['ADMIN'], $this->config->current['PASSWORD']);
756     $sr=ldap_read($ds, @LDAP::fix($src_dn), "objectClass=*");
758     /* Fill data from LDAP */
759     $new= array();
760     if ($sr) {
761       $ei=ldap_first_entry($ds, $sr);
762       if ($ei) {
763         foreach($attrs as $attr => $val){
764           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
765             for ($i= 0; $i<$info['count']; $i++){
766               if ($info['count'] == 1){
767                 $new[$attr]= $info[$i];
768               } else {
769                 $new[$attr][]= $info[$i];
770               }
771             }
772           }
773         }
774       }
775     }
777     /* close conncetion */
778     ldap_unbind($ds);
780     /* Adapt naming attribute */
781     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
782     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
783     $new[$dst_name]= @LDAP::fix($dst_val);
785     /* Check if this is a department.
786      * If it is a dep. && there is a , override in his ou 
787      *  change \2C to , again, else this entry can't be saved ...
788      */
789     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
790       $new['ou'] = preg_replace("/\\\\,/",",",$new['ou']);
791     }
793     /* Save copy */
794     $ldap->connect();
795     $ldap->cd($this->config->current['BASE']);
796     
797     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
799     /* FAIvariable=.../..., cn=.. 
800         could not be saved, because the attribute FAIvariable was different to 
801         the dn FAIvariable=..., cn=... */
802     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
803       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
804     }
805     $ldap->cd($dst_dn);
806     $ldap->add($new);
808     if ($ldap->error != "Success"){
809       trigger_error("Trying to save $dst_dn failed.",
810           E_USER_WARNING);
811       return(FALSE);
812     }
813     return(TRUE);
814   }
817   /* This is a workaround function. */
818   function copy($src_dn, $dst_dn)
819   {
820     /* Rename dn in possible object groups */
821     $ldap= $this->config->get_ldap_link();
822     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::fix($src_dn).'))',
823         array('cn'));
824     while ($attrs= $ldap->fetch()){
825       $og= new ogroup($this->config, $ldap->getDN());
826       unset($og->member[$src_dn]);
827       $og->member[$dst_dn]= $dst_dn;
828       $og->save ();
829     }
831     $ldap->cat($dst_dn);
832     $attrs= $ldap->fetch();
833     if (count($attrs)){
834       trigger_error("Trying to overwrite ".@LDAP::fix($dst_dn).", which already exists.",
835           E_USER_WARNING);
836       return (FALSE);
837     }
839     $ldap->cat($src_dn);
840     $attrs= $ldap->fetch();
841     if (!count($attrs)){
842       trigger_error("Trying to move ".@LDAP::fix($src_dn).", which does not seem to exist.",
843           E_USER_WARNING);
844       return (FALSE);
845     }
847     $ldap->cd($src_dn);
848     $ldap->search("objectClass=*",array("dn"));
849     while($attrs = $ldap->fetch()){
850       $src = $attrs['dn'];
851       $dst = preg_replace("/".normalizePreg($src_dn)."$/",$dst_dn,$attrs['dn']);
852       $this->_copy($src,$dst);
853     }
854     return (TRUE);
855   }
858   function move($src_dn, $dst_dn)
859   {
860     /* Copy source to destination */
861     if (!$this->copy($src_dn, $dst_dn)){
862       return (FALSE);
863     }
865     /* Delete source */
866     $ldap= $this->config->get_ldap_link();
867     $ldap->rmdir_recursive($src_dn);
868     if ($ldap->error != "Success"){
869       trigger_error("Trying to delete $src_dn failed.",
870           E_USER_WARNING);
871       return (FALSE);
872     }
874     return (TRUE);
875   }
878   /* Move/Rename complete trees */
879   function recursive_move($src_dn, $dst_dn)
880   {
881     /* Check if the destination entry exists */
882     $ldap= $this->config->get_ldap_link();
884     /* Check if destination exists - abort */
885     $ldap->cat($dst_dn, array('dn'));
886     if ($ldap->fetch()){
887       trigger_error("recursive_move $dst_dn already exists.",
888           E_USER_WARNING);
889       return (FALSE);
890     }
892     /* Perform a search for all objects to be moved */
893     $objects= array();
894     $ldap->cd($src_dn);
895     $ldap->search("(objectClass=*)", array("dn"));
896     while($attrs= $ldap->fetch()){
897       $dn= $attrs['dn'];
898       $objects[$dn]= strlen($dn);
899     }
901     /* Sort objects by indent level */
902     asort($objects);
903     reset($objects);
905     /* Copy objects from small to big indent levels by replacing src_dn by dst_dn */
906     foreach ($objects as $object => $len){
907       $src= $object;
908       $dst= preg_replace("/$src_dn$/", "$dst_dn", $object);
909       if (!$this->copy($src, $dst)){
910         return (FALSE);
911       }
912     }
914     /* Remove src_dn */
915     $ldap->cd($src_dn);
916     $ldap->recursive_remove();
917     return (TRUE);
918   }
921   function handle_post_events($mode, $add_attrs= array())
922   {
923     switch ($mode){
924       case "add":
925         $this->postcreate($add_attrs);
926       break;
928       case "modify":
929         $this->postmodify($add_attrs);
930       break;
932       case "remove":
933         $this->postremove($add_attrs);
934       break;
935     }
936   }
939   function saveCopyDialog(){
940   }
943   function getCopyDialog(){
944     return(array("string"=>"","status"=>""));
945   }
948   function PrepareForCopyPaste($source)
949   {
950     $todo = $this->attributes;
951     if(isset($this->CopyPasteVars)){
952       $todo = array_merge($todo,$this->CopyPasteVars);
953     }
955     if(count($this->objectclasses)){
956       $this->is_account = TRUE;
957       foreach($this->objectclasses as $class){
958         if(!in_array($class,$source['objectClass'])){
959           $this->is_account = FALSE;
960         }
961       }
962     }
964     foreach($todo as $var){
965       if (isset($source[$var])){
966         if(isset($source[$var]['count'])){
967           if($source[$var]['count'] > 1){
968             $this->$var = array();
969             $tmp = array();
970             for($i = 0 ; $i < $source[$var]['count']; $i++){
971               $tmp = $source[$var][$i];
972             }
973             $this->$var = $tmp;
974 #            echo $var."=".$tmp."<br>";
975           }else{
976             $this->$var = $source[$var][0];
977 #            echo $var."=".$source[$var][0]."<br>";
978           }
979         }else{
980           $this->$var= $source[$var];
981 #          echo $var."=".$source[$var]."<br>";
982         }
983       }
984     }
985   }
988   function handle_object_tagging($dn= "", $tag= "", $show= false)
989   {
990     //FIXME: How to optimize this? We have at least two
991     //       LDAP accesses per object. It would be a good
992     //       idea to have it integrated.
994     /* No dn? Self-operation... */
995     if ($dn == ""){
996       $dn= $this->dn;
998       /* No tag? Find it yourself... */
999       if ($tag == ""){
1000         $len= strlen($dn);
1002         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1003         $relevant= array();
1004         foreach ($this->config->adepartments as $key => $ntag){
1006           /* This one is bigger than our dn, its not relevant... */
1007           if ($len <= strlen($key)){
1008             continue;
1009           }
1011           /* This one matches with the latter part. Break and don't fix this entry */
1012           if (preg_match('/(^|,)'.normalizePreg($key).'$/', $dn)){
1013             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1014             $relevant[strlen($key)]= $ntag;
1015             continue;
1016           }
1018         }
1020         /* If we've some relevant tags to set, just get the longest one */
1021         if (count($relevant)){
1022           ksort($relevant);
1023           $tmp= array_keys($relevant);
1024           $idx= end($tmp);
1025           $tag= $relevant[$idx];
1026           $this->gosaUnitTag= $tag;
1027         }
1028       }
1029     }
1032     /* Set tag? */
1033     if ($tag != ""){
1034       /* Set objectclass and attribute */
1035       $ldap= $this->config->get_ldap_link();
1036       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
1037       $attrs= $ldap->fetch();
1038       if(isset($attrs['gosaUnitTag'][0]) && $attrs['gosaUnitTag'][0] == $tag){
1039         if ($show) {
1040           echo sprintf(_("Object '%s' is already tagged"), @LDAP::fix($dn))."<br>";
1041           flush();
1042         }
1043         return;
1044       }
1045       if (count($attrs)){
1046         if ($show){
1047           echo sprintf(_("Adding tag (%s) to object '%s'"), $tag, @LDAP::fix($dn))."<br>";
1048           flush();
1049         }
1050         $nattrs= array("gosaUnitTag" => $tag);
1051         $nattrs['objectClass']= array();
1052         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
1053           $oc= $attrs['objectClass'][$i];
1054           if ($oc != "gosaAdministrativeUnitTag"){
1055             $nattrs['objectClass'][]= $oc;
1056           }
1057         }
1058         $nattrs['objectClass'][]= "gosaAdministrativeUnitTag";
1059         $ldap->cd($dn);
1060         $ldap->modify($nattrs);
1061         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
1062       } else {
1063         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not tagging ($tag) $dn - seems to have moved away", "Tagging");
1064       }
1066     } else {
1067       /* Remove objectclass and attribute */
1068       $ldap= $this->config->get_ldap_link();
1069       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
1070       $attrs= $ldap->fetch();
1071       if (isset($attrs['objectClass']) && !in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass'])){
1072         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "$dn is not tagged", "Tagging");
1073         return;
1074       }
1075       if (count($attrs)){
1076         if ($show){
1077           echo sprintf(_("Removing tag from object '%s'"), @LDAP::fix($dn))."<br>";
1078           flush();
1079         }
1080         $nattrs= array("gosaUnitTag" => array());
1081         $nattrs['objectClass']= array();
1082         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
1083           $oc= $attrs['objectClass'][$i];
1084           if ($oc != "gosaAdministrativeUnitTag"){
1085             $nattrs['objectClass'][]= $oc;
1086           }
1087         }
1088         $ldap->cd($dn);
1089         $ldap->modify($nattrs);
1090         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
1091       } else {
1092         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not removing tag ($tag) $dn - seems to have moved away", "Tagging");
1093       }
1094     }
1096   }
1099   /* Add possibility to stop remove process */
1100   function allow_remove()
1101   {
1102     $reason= "";
1103     return $reason;
1104   }
1107   /* Create a snapshot of the current object */
1108   function create_snapshot($type= "snapshot", $description= array())
1109   {
1111     /* Check if snapshot functionality is enabled */
1112     if(!$this->snapshotEnabled()){
1113       return;
1114     }
1116     /* Get configuration from gosa.conf */
1117     $tmp = $this->config->current;
1119     /* Create lokal ldap connection */
1120     $ldap= $this->config->get_ldap_link();
1121     $ldap->cd($this->config->current['BASE']);
1123     /* check if there are special server configurations for snapshots */
1124     if(!isset($tmp['SNAPSHOT_SERVER'])){
1126       /* Source and destination server are both the same, just copy source to dest obj */
1127       $ldap_to      = $ldap;
1128       $snapldapbase = $this->config->current['BASE'];
1130     }else{
1131       $server         = $tmp['SNAPSHOT_SERVER'];
1132       $user           = $tmp['SNAPSHOT_USER'];
1133       $password       = $tmp['SNAPSHOT_PASSWORD'];
1134       $snapldapbase   = $tmp['SNAPSHOT_BASE'];
1136       $ldap_to        = new LDAP($user,$password, $server);
1137       $ldap_to -> cd($snapldapbase);
1138       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$snapldapbase));
1139     }
1141     /* check if the dn exists */ 
1142     if ($ldap->dn_exists($this->dn)){
1144       /* Extract seconds & mysecs, they are used as entry index */
1145       list($usec, $sec)= explode(" ", microtime());
1147       /* Collect some infos */
1148       $base           = $this->config->current['BASE'];
1149       $snap_base      = $tmp['SNAPSHOT_BASE'];
1150       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1151       $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1153       /* Create object */
1154 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1155       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1156       $newName          = preg_replace("/\./", "", $sec."-".$usec);
1157       $target= array();
1158       $target['objectClass']            = array("top", "gosaSnapshotObject");
1159       $target['gosaSnapshotData']       = gzcompress($data, 6);
1160       $target['gosaSnapshotType']       = $type;
1161       $target['gosaSnapshotDN']         = $this->dn;
1162       $target['description']            = $description;
1163       $target['gosaSnapshotTimestamp']  = $newName;
1165       /* Insert the new snapshot 
1166          But we have to check first, if the given gosaSnapshotTimestamp
1167          is already used, in this case we should increment this value till there is 
1168          an unused value. */ 
1169       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1170       $ldap_to->cat($new_dn);
1171       while($ldap_to->count()){
1172         $ldap_to->cat($new_dn);
1173         $newName = preg_replace("/\./", "", $sec."-".($usec++));
1174         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1175         $target['gosaSnapshotTimestamp']  = $newName;
1176       } 
1178       /* Inset this new snapshot */
1179       $ldap_to->cd($snapldapbase);
1180       $ldap_to->create_missing_trees($snapldapbase);
1181       $ldap_to->create_missing_trees($new_base);
1182       $ldap_to->cd($new_dn);
1183       $ldap_to->add($target);
1184     
1185       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1186       show_ldap_error($ldap_to->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1187     }
1188   }
1190   function remove_snapshot($dn)
1191   {
1192     $ui       = get_userinfo();
1193     $old_dn   = $this->dn; 
1194     $this->dn = $dn;
1195     $ldap = $this->config->get_ldap_link();
1196     $ldap->cd($this->config->current['BASE']);
1197     $ldap->rmdir_recursive($dn);
1198     $this->dn = $old_dn;
1199   }
1202   /* returns true if snapshots are enabled, and false if it is disalbed
1203      There will also be some errors psoted, if the configuration failed */
1204   function snapshotEnabled()
1205   {
1206     $tmp = $this->config->current;
1207     if(isset($tmp['ENABLE_SNAPSHOT'])){
1208       if (preg_match("/^true$/i", $tmp['ENABLE_SNAPSHOT']) || preg_match("/yes/i", $tmp['ENABLE_SNAPSHOT'])){
1210         /* Check if the snapshot_base is defined */
1211         if(!isset($tmp['SNAPSHOT_BASE'])){
1212           print_red(sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not configured in your gosa.conf."),"SNAPSHOT_BASE"));
1213           return(FALSE);
1214         }
1216         /* check if there are special server configurations for snapshots */
1217         if(isset($tmp['SNAPSHOT_SERVER'])){
1219           /* check if all required vars are available to create a new ldap connection */
1220           $missing = "";
1221           foreach(array("SNAPSHOT_SERVER","SNAPSHOT_USER","SNAPSHOT_PASSWORD","SNAPSHOT_BASE") as $var){
1222             if(!isset($tmp[$var])){
1223               $missing .= $var." ";
1224               print_red(sprintf(_("The snapshot functionality is enabled, but the required variable(s) '%s' is not configured in your gosa.conf."),$missing));
1225               return(FALSE);
1226             }
1227           }
1228         }
1229         return(TRUE);
1230       }
1231     }
1232     return(FALSE);
1233   }
1236   /* Return available snapshots for the given base 
1237    */
1238   function Available_SnapsShots($dn,$raw = false)
1239   {
1240     if(!$this->snapshotEnabled()) return(array());
1242     /* Create an additional ldap object which
1243        points to our ldap snapshot server */
1244     $ldap= $this->config->get_ldap_link();
1245     $ldap->cd($this->config->current['BASE']);
1246     $cfg= &$this->config->current;
1248     /* check if there are special server configurations for snapshots */
1250     if(isset($cfg['SERVER']) && isset($cfg['SNAPSHOT_SERVER']) && $cfg['SERVER'] == $cfg['SNAPSHOT_SERVER']){
1251       $ldap_to    = $ldap;
1252     }elseif(isset($cfg['SNAPSHOT_SERVER'])){
1253       $server       = $cfg['SNAPSHOT_SERVER'];
1254       $user         = $cfg['SNAPSHOT_USER'];
1255       $password     = $cfg['SNAPSHOT_PASSWORD'];
1256       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1258       $ldap_to      = new LDAP($user,$password, $server);
1259       $ldap_to -> cd ($snapldapbase);
1260       show_ldap_error($ldap->get_error(), sprintf(_("Method get available snapshots with dn '%s' failed."),$this->dn));
1261     }else{
1262       $ldap_to    = $ldap;
1263     }
1265     /* Prepare bases and some other infos */
1266     $base           = $this->config->current['BASE'];
1267     $snap_base      = $cfg['SNAPSHOT_BASE'];
1268     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1269     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1270     $tmp            = array(); 
1272     /* Fetch all objects with  gosaSnapshotDN=$dn */
1273     $ldap_to->cd($new_base);
1274     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1275         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1277     /* Put results into a list and add description if missing */
1278     while($entry = $ldap_to->fetch()){ 
1279       if(!isset($entry['description'][0])){
1280         $entry['description'][0]  = "";
1281       }
1282       $tmp[] = $entry; 
1283     }
1285     /* Return the raw array, or format the result */
1286     if($raw){
1287       return($tmp);
1288     }else{  
1289       $tmp2 = array();
1290       foreach($tmp as $entry){
1291         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1292       }
1293     }
1294     return($tmp2);
1295   }
1298   function getAllDeletedSnapshots($base_of_object,$raw = false)
1299   {
1300     if(!$this->snapshotEnabled()) return(array());
1302     /* Create an additional ldap object which
1303        points to our ldap snapshot server */
1304     $ldap= $this->config->get_ldap_link();
1305     $ldap->cd($this->config->current['BASE']);
1306     $cfg= &$this->config->current;
1308     /* check if there are special server configurations for snapshots */
1309     if(isset($cfg['SNAPSHOT_SERVER'])){
1310       $server       = $cfg['SNAPSHOT_SERVER'];
1311       $user         = $cfg['SNAPSHOT_USER'];
1312       $password     = $cfg['SNAPSHOT_PASSWORD'];
1313       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1314       $ldap_to      = new LDAP($user,$password, $server);
1315       $ldap_to->cd ($snapldapbase);
1316       show_ldap_error($ldap_to->get_error(), sprintf(_("Method get deleted snapshots with dn '%s' failed."),$this->dn));
1317     }else{
1318       $ldap_to    = $ldap;
1319     }
1321     /* Prepare bases */ 
1322     $base           = $this->config->current['BASE'];
1323     $snap_base      = $cfg['SNAPSHOT_BASE'];
1324     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1326     /* Fetch all objects and check if they do not exist anymore */
1327     $ui = get_userinfo();
1328     $tmp = array();
1329     $ldap_to->cd($new_base);
1330     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1331     while($entry = $ldap_to->fetch()){
1333       $chk =  str_replace($new_base,"",$entry['dn']);
1334       if(preg_match("/,ou=/",$chk)) continue;
1336       if(!isset($entry['description'][0])){
1337         $entry['description'][0]  = "";
1338       }
1339       $tmp[] = $entry; 
1340     }
1342     /* Check if entry still exists */
1343     foreach($tmp as $key => $entry){
1344       $ldap->cat($entry['gosaSnapshotDN'][0]);
1345       if($ldap->count()){
1346         unset($tmp[$key]);
1347       }
1348     }
1350     /* Format result as requested */
1351     if($raw) {
1352       return($tmp);
1353     }else{
1354       $tmp2 = array();
1355       foreach($tmp as $key => $entry){
1356         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1357       }
1358     }
1359     return($tmp2);
1360   } 
1363   /* Restore selected snapshot */
1364   function restore_snapshot($dn)
1365   {
1366     if(!$this->snapshotEnabled()) return(array());
1368     $ldap= $this->config->get_ldap_link();
1369     $ldap->cd($this->config->current['BASE']);
1370     $cfg= &$this->config->current;
1372     /* check if there are special server configurations for snapshots */
1373     if(isset($cfg['SNAPSHOT_SERVER'])){
1374       $server       = $cfg['SNAPSHOT_SERVER'];
1375       $user         = $cfg['SNAPSHOT_USER'];
1376       $password     = $cfg['SNAPSHOT_PASSWORD'];
1377       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1378       $ldap_to      = new LDAP($user,$password, $server);
1379       $ldap_to->cd ($snapldapbase);
1380       show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$snapldapbase));
1381     }else{
1382       $ldap_to    = $ldap;
1383     }
1385     /* Get the snapshot */ 
1386     $ldap_to->cat($dn);
1387     $restoreObject = $ldap_to->fetch();
1389     /* Prepare import string */
1390     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1392     /* Import the given data */
1393     $ldap->import_complete_ldif($data,$err,false,false);
1394     show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$dn));
1395   }
1398   function showSnapshotDialog($base,$baseSuffixe)
1399   {
1400     $once = true;
1401     foreach($_POST as $name => $value){
1403       /* Create a new snapshot, display a dialog */
1404       if(preg_match("/^CreateSnapShotDialog_/",$name) && $once){
1405         $once = false;
1406         $entry = preg_replace("/^CreateSnapShotDialog_/","",$name);
1407         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1408         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1409       }
1411       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1412       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1413         $once = false;
1414         $entry = preg_replace("/^RestoreSnapShotDialog_/","",$name);
1415         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1416         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1417         $this->snapDialog->display_restore_dialog = true;
1418       }
1420       /* Restore one of the already deleted objects */
1421       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1422           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1423         $once = false;
1424         $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1425         $this->snapDialog->set_snapshot_bases($baseSuffixe);
1426         $this->snapDialog->display_restore_dialog      = true;
1427         $this->snapDialog->display_all_removed_objects  = true;
1428       }
1430       /* Restore selected snapshot */
1431       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1432         $once = false;
1433         $entry = preg_replace("/^RestoreSnapShot_/","",$name);
1434         $entry = base64_decode(trim(preg_replace("/_[xy]$/","",$entry)));
1435         if(!empty($entry)){
1436           $this->restore_snapshot($entry);
1437           $this->snapDialog = NULL;
1438         }
1439       }
1440     }
1442     /* Create a new snapshot requested, check
1443        the given attributes and create the snapshot*/
1444     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1445       $this->snapDialog->save_object();
1446       $msgs = $this->snapDialog->check();
1447       if(count($msgs)){
1448         foreach($msgs as $msg){
1449           print_red($msg);
1450         }
1451       }else{
1452         $this->dn =  $this->snapDialog->dn;
1453         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1454         $this->snapDialog = NULL;
1455       }
1456     }
1458     /* Restore is requested, restore the object with the posted dn .*/
1459     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1460     }
1462     if(isset($_POST['CancelSnapshot'])){
1463       $this->snapDialog = NULL;
1464     }
1466     if(is_object($this->snapDialog )){
1467       $this->snapDialog->save_object();
1468       return($this->snapDialog->execute());
1469     }
1470   }
1473   static function plInfo()
1474   {
1475     return array();
1476   }
1479   function set_acl_base($base)
1480   {
1481     $this->acl_base= $base;
1482   }
1485   function set_acl_category($category)
1486   {
1487     $this->acl_category= "$category/";
1488   }
1491   function acl_is_writeable($attribute,$skip_write = FALSE)
1492   {
1493     $ui= get_userinfo();
1494     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1495   }
1498   function acl_is_readable($attribute)
1499   {
1500     $ui= get_userinfo();
1501     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1502   }
1505   function acl_is_createable()
1506   {
1507     $ui= get_userinfo();
1508     return preg_match('/c/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1509   }
1512   function acl_is_removeable()
1513   {
1514     $ui= get_userinfo();
1515     return preg_match('/d/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1516   }
1519   function acl_is_moveable()
1520   {
1521     $ui= get_userinfo();
1522     return preg_match('/m/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1523   }
1526   function acl_have_any_permissions()
1527   {
1528   }
1531   function getacl($attribute,$skip_write= FALSE)
1532   {
1533     $ui= get_userinfo();
1534     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1535   }
1537   /* Get all allowed bases to move an object to or to create a new object.
1538      Idepartments also contains all base departments which lead to the allowed bases */
1539   function get_allowed_bases($category = "")
1540   {
1541     $ui = get_userinfo();
1542     $deps = array();
1544     /* Set category */ 
1545     if(empty($category)){
1546       $category = $this->acl_category.get_class($this);
1547     }
1549     /* Is this a new object ? Or just an edited existing object */
1550     if(!$this->initially_was_account && $this->is_account){
1551       $new = true;
1552     }else{
1553       $new = false;
1554     }
1556     $cat_bases = $ui->get_module_departments(preg_replace("/\/.*$/","",$category));
1557     foreach($this->config->idepartments as $dn => $name){
1558       
1559       if(!in_array_ics($dn,$cat_bases)){
1560         continue;
1561       }
1562       
1563       $acl = $ui->get_permissions($dn,$category);
1564       if($new && preg_match("/c/",$acl)){
1565         $deps[$dn] = $name;
1566       }elseif(!$new && preg_match("/m/",$acl)){
1567         $deps[$dn] = $name;
1568       }
1569     }
1571     /* Add current base */      
1572     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1573       $deps[$this->base] = $this->config->idepartments[$this->base];
1574     }else{
1575       echo "No default base found. ".$this->base."<br> ";
1576     }
1578     return($deps);
1579   }
1581   /* This function modifies object acls too, if an object is moved.
1582    *  $old_dn   specifies the actually used dn
1583    *  $new_dn   specifies the destiantion dn
1584    */
1585   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1586   {
1587     /* Check if old_dn is empty. This should never happen */
1588     if(empty($old_dn) || empty($new_dn)){
1589       trigger_error("Failed to check acl dependencies, wrong dn given.");
1590       return;
1591     }
1593     /* Update userinfo if necessary */
1594     if($_SESSION['ui']->dn == $old_dn){
1595       $_SESSION['ui']->dn = $new_dn;
1596       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current user dn from '".$old_dn."' to '".$new_dn."'");
1597     }
1599     /* Object was moved, ensure that all acls will be moved too */
1600     if($new_dn != $old_dn && $old_dn != "new"){
1602       /* get_ldap configuration */
1603       $update = array();
1604       $ldap = $this->config->get_ldap_link();
1605       $ldap->cd ($this->config->current['BASE']);
1606       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*))",array("cn","gosaAclEntry"));
1607       while($attrs = $ldap->fetch()){
1609         $acls = array();
1611         /* Walk through acls */
1612         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1614           /* Reset vars */
1615           $found = false;
1617           /* Get Acl parts */
1618           $acl_parts = split(":",$attrs['gosaAclEntry'][$i]);
1620           /* Get every single member for this acl */  
1621           $members = array();  
1622           if(preg_match("/,/",$acl_parts[2])){
1623             $members = split(",",$acl_parts[2]);
1624           }else{
1625             $members = array($acl_parts[2]);
1626           } 
1627       
1628           /* Check if member match current dn */
1629           foreach($members as $key => $member){
1630             $member = base64_decode($member);
1631             if($member == $old_dn){
1632               $found = true;
1633               $members[$key] = base64_encode($new_dn);
1634             }
1635           } 
1636          
1637           /* Create new member string */ 
1638           $new_members = "";
1639           foreach($members as $member){
1640             $new_members .= $member.",";
1641           }
1642           $new_members = preg_replace("/,$/","",$new_members);
1643           $acl_parts[2] = $new_members;
1644         
1645           /* Reconstruckt acl entry */
1646           $acl_str  ="";
1647           foreach($acl_parts as $t){
1648            $acl_str .= $t.":";
1649           }
1650           $acl_str = preg_replace("/:$/","",$acl_str);
1651        }
1653        /* Acls for this object must be adjusted */
1654        if($found){
1656           if($output_changes){
1657             echo "<font color='green'>".
1658                   _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1659                   $old_dn.
1660                   "</b><br>&nbsp;-"._("to")."&nbsp;<b>".
1661                   $new_dn.
1662                   "</b></font><br>";
1663           }
1664           $update[$attrs['dn']] =array();
1665           foreach($acls as $acl){
1666             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1667           }
1668         }
1669       }
1671       /* Write updated acls */
1672       foreach($update as $dn => $attrs){
1673         $ldap->cd($dn);
1674         $ldap->modify($attrs);
1675       }
1676     }
1677   }
1679   
1681   /* This function enables the entry Serial ID check.
1682    * If an entry was edited while we have edited the entry too,
1683    *  an error message will be shown. 
1684    * To configure this check correctly read the FAQ.
1685    */    
1686   function enable_CSN_check()
1687   {
1688     $this->CSN_check_active =TRUE;
1689     $this->entryCSN = getEntryCSN($this->dn);
1690   }
1693   
1695   function set_multi_edit_value()
1696   {
1698   }
1701   /*! \brief  Prepares the plugin to be used for multiple edit
1702    */
1703   function init_multiple_support()
1704   {
1705   }
1708   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1709       @return array Cotaining all mdofied values. 
1710    */
1711   function get_multi_edit_values()
1712   {
1713     $ret = array();
1714     foreach($this->attributes as $attr){
1715       if(in_array($attr,$this->multi_boxes)){
1716         $ret[$attr] = $this->$attr;
1717       }
1718     }
1719     return($ret);
1720   }
1723   /*! \brief execute plugin
1725     Generates the html output for this node
1726    */
1727   function multiple_execute()
1728   {
1729     /* This one is empty currently. Fabian - please fill in the docu code */
1730     $_SESSION['current_class_for_help'] = get_class($this);
1732     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1733     $_SESSION['LOCK_VARS_TO_USE'] = $_SESSION['LOCK_VARS_USED'] =array();
1734     
1735     return("Multiple edit is currently not implemented for this plugin.");
1736   }
1739   /*! \brief   Save HTML posted data to object for multiple edit
1740    */
1741   function multiple_save_object()
1742   {
1743     if(empty($this->entryCSN) && $this->CSN_check_active){
1744       $this->entryCSN = getEntryCSN($this->dn);
1745     }
1747     /* Save values to object */
1748     foreach ($this->attributes as $val){
1749       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
1751         /* Check for modifications */
1752         if (get_magic_quotes_gpc()) {
1753           $data= stripcslashes($_POST["$val"]);
1754         } else {
1755           $data= $this->$val = $_POST["$val"];
1756         }
1757         if ($this->$val != $data){
1758           $this->is_modified= TRUE;
1759         }
1760     
1761         /* IE post fix */
1762         if(isset($data[0]) && $data[0] == chr(194)) {
1763           $data = "";  
1764         }
1765         $this->$val= $data;
1766       }
1767     }
1768   }
1771   /*! \brief  Check given values in multiple edit
1772       @return array Error messages
1773    */
1774   function multiple_check()
1775   {
1776     $message = plugin::check();
1777     return($message);
1778   }
1781 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1782 ?>