Code

Closes #310 Moved copy_FAI_resource_recursive to faiManagement. It is only used there.
[gosa.git] / gosa-core / 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;
127   var $multi_attrs      = array();
128   var $multi_attrs_all  = array(); 
130   /* This aviable indicates, that we are currently in multiple edit handle */
131   var $multiple_support_active = FALSE; 
132   var $selected_edit_values = array();
133   var $multi_boxes = array();
135   /*! \brief plugin constructor
137     If 'dn' is set, the node loads the given 'dn' from LDAP
139     \param dn Distinguished name to initialize plugin from
140     \sa plugin()
141    */
142   function plugin (&$config, $dn= NULL, $parent= NULL)
143   {
144     /* Configuration is fine, allways */
145     $this->config= &$config;    
146     $this->dn= $dn;
148     /* Handle new accounts, don't read information from LDAP */
149     if ($dn == "new"){
150       return;
151     }
153     /* Save current dn as acl_base */
154     $this->acl_base= $dn;
156     /* Get LDAP descriptor */
157     $ldap= $this->config->get_ldap_link();
158     if ($dn !== NULL){
160       /* Load data to 'attrs' and save 'dn' */
161       if ($parent !== NULL){
162         $this->attrs= $parent->attrs;
163       } else {
164         $ldap->cat ($dn);
165         $this->attrs= $ldap->fetch();
166       }
168       /* Copy needed attributes */
169       foreach ($this->attributes as $val){
170         $found= array_key_ics($val, $this->attrs);
171         if ($found != ""){
172           $this->$val= $this->attrs["$found"][0];
173         }
174       }
176       /* gosaUnitTag loading... */
177       if (isset($this->attrs['gosaUnitTag'][0])){
178         $this->gosaUnitTag= $this->attrs['gosaUnitTag'][0];
179       }
181       /* Set the template flag according to the existence of objectClass
182          gosaUserTemplate */
183       if (isset($this->attrs['objectClass'])){
184         if (in_array ("gosaUserTemplate", $this->attrs['objectClass'])){
185           $this->is_template= TRUE;
186           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
187               "found", "Template check");
188         }
189       }
191       /* Is Account? */
192       $found= TRUE;
193       foreach ($this->objectclasses as $obj){
194         if (preg_match('/top/i', $obj)){
195           continue;
196         }
197         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
198           $found= FALSE;
199           break;
200         }
201       }
202       if ($found){
203         $this->is_account= TRUE;
204         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
205             "found", "Object check");
206       }
208       /* Prepare saved attributes */
209       $this->saved_attributes= $this->attrs;
210       foreach ($this->saved_attributes as $index => $value){
211         if (preg_match('/^[0-9]+$/', $index)){
212           unset($this->saved_attributes[$index]);
213           continue;
214         }
215         if (!in_array($index, $this->attributes) && $index != "objectClass"){
216           unset($this->saved_attributes[$index]);
217           continue;
218         }
219         if ($this->saved_attributes[$index]["count"] == 1){
220           $tmp= $this->saved_attributes[$index][0];
221           unset($this->saved_attributes[$index]);
222           $this->saved_attributes[$index]= $tmp;
223           continue;
224         }
226         unset($this->saved_attributes["$index"]["count"]);
227       }
228     }
230     /* Save initial account state */
231     $this->initially_was_account= $this->is_account;
232   }
235   /*! \brief execute plugin
237     Generates the html output for this node
238    */
239   function execute()
240   {
241     /* This one is empty currently. Fabian - please fill in the docu code */
242     session::set('current_class_for_help',get_class($this));
244     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
245     session::set('LOCK_VARS_TO_USE',array());
246     session::set('LOCK_VARS_USED',array());
247   }
249   /*! \brief execute plugin
250      Removes object from parent
251    */
252   function remove_from_parent()
253   {
254     /* include global link_info */
255     $ldap= $this->config->get_ldap_link();
257     /* Get current objectClasses in order to add the required ones */
258     $ldap->cat($this->dn);
259     $tmp= $ldap->fetch ();
260     $oc= array();
261     if (isset($tmp['objectClass'])){
262       $oc= $tmp['objectClass'];
263       unset($oc['count']);
264     }
266     /* Remove objectClasses from entry */
267     $ldap->cd($this->dn);
268     $this->attrs= array();
269     $this->attrs['objectClass']= array_remove_entries($this->objectclasses,$oc);
271     /* Unset attributes from entry */
272     foreach ($this->attributes as $val){
273       $this->attrs["$val"]= array();
274     }
276     /* Unset account info */
277     $this->is_account= FALSE;
279     /* Do not write in plugin base class, this must be done by
280        children, since there are normally additional attribs,
281        lists, etc. */
282     /*
283        $ldap->modify($this->attrs);
284      */
285   }
288   /*! \brief   Save HTML posted data to object 
289    */
290   function save_object()
291   {
292     /* Update entry CSN if it is empty. */
293     if(empty($this->entryCSN) && $this->CSN_check_active){
294       $this->entryCSN = getEntryCSN($this->dn);
295     }
297     /* Save values to object */
298     foreach ($this->attributes as $val){
299       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
300         /* Check for modifications */
301         if (get_magic_quotes_gpc()) {
302           $data= stripcslashes($_POST["$val"]);
303         } else {
304           $data= $this->$val = $_POST["$val"];
305         }
306         if ($this->$val != $data){
307           $this->is_modified= TRUE;
308         }
309     
310         /* Okay, how can I explain this fix ... 
311          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
312          * So IE posts these 'unselectable' option, with value = chr(194) 
313          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
314          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
315          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
316          */
317         if(isset($data[0]) && $data[0] == chr(194)) {
318           $data = "";  
319         }
320         $this->$val= $data;
321         //echo "<font color='blue'>".$val."</font><br>";
322       }else{
323         //echo "<font color='red'>".$val."</font><br>";
324       }
325     }
326   }
329   /* Save data to LDAP, depending on is_account we save or delete */
330   function save()
331   {
332     /* include global link_info */
333     $ldap= $this->config->get_ldap_link();
335     /* Save all plugins */
336     $this->entryCSN = "";
338     /* Start with empty array */
339     $this->attrs= array();
341     /* Get current objectClasses in order to add the required ones */
342     $ldap->cat($this->dn);
343     
344     $tmp= $ldap->fetch ();
346     $oc= array();
347     if (isset($tmp['objectClass'])){
348       $oc= $tmp["objectClass"];
349       $this->is_new= FALSE;
350       unset($oc['count']);
351     } else {
352       $this->is_new= TRUE;
353     }
355     /* Load (minimum) attributes, add missing ones */
356     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
358     /* Copy standard attributes */
359     foreach ($this->attributes as $val){
360       if ($this->$val != ""){
361         $this->attrs["$val"]= $this->$val;
362       } elseif (!$this->is_new) {
363         $this->attrs["$val"]= array();
364       }
365     }
367   }
370   function cleanup()
371   {
372     foreach ($this->attrs as $index => $value){
374       /* Convert arrays with one element to non arrays, if the saved
375          attributes are no array, too */
376       if (is_array($this->attrs[$index]) && 
377           count ($this->attrs[$index]) == 1 &&
378           isset($this->saved_attributes[$index]) &&
379           !is_array($this->saved_attributes[$index])){
380           
381         $tmp= $this->attrs[$index][0];
382         $this->attrs[$index]= $tmp;
383       }
385       /* Remove emtpy arrays if they do not differ */
386       if (is_array($this->attrs[$index]) &&
387           count($this->attrs[$index]) == 0 &&
388           !isset($this->saved_attributes[$index])){
389           
390         unset ($this->attrs[$index]);
391         continue;
392       }
394       /* Remove single attributes that do not differ */
395       if (!is_array($this->attrs[$index]) &&
396           isset($this->saved_attributes[$index]) &&
397           !is_array($this->saved_attributes[$index]) &&
398           $this->attrs[$index] == $this->saved_attributes[$index]){
400         unset ($this->attrs[$index]);
401         continue;
402       }
404       /* Remove arrays that do not differ */
405       if (is_array($this->attrs[$index]) && 
406           isset($this->saved_attributes[$index]) &&
407           is_array($this->saved_attributes[$index])){
408           
409         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
410           unset ($this->attrs[$index]);
411           continue;
412         }
413       }
414     }
416     /* Update saved attributes and ensure that next cleanups will be successful too */
417     foreach($this->attrs as $name => $value){
418       $this->saved_attributes[$name] = $value;
419     }
420   }
422   /* Check formular input */
423   function check()
424   {
425     $message= array();
427     /* Skip if we've no config object */
428     if (!isset($this->config) || !is_object($this->config)){
429       return $message;
430     }
432     /* Find hooks entries for this class */
433     $command= $this->config->search(get_class($this), "CHECK", array('menu', 'tabs'));
435     if ($command != ""){
437       if (!check_command($command)){
438         $message[]= sprintf(_("Command '%s', specified as CHECK hook for plugin '%s' doesn't seem to exist."), $command,
439                             get_class($this));
440       } else {
442         /* Generate "ldif" for check hook */
443         $ldif= "dn: $this->dn\n";
444         
445         /* ... objectClasses */
446         foreach ($this->objectclasses as $oc){
447           $ldif.= "objectClass: $oc\n";
448         }
449         
450         /* ... attributes */
451         foreach ($this->attributes as $attr){
452           if ($this->$attr == ""){
453             continue;
454           }
455           if (is_array($this->$attr)){
456             foreach ($this->$attr as $val){
457               $ldif.= "$attr: $val\n";
458             }
459           } else {
460               $ldif.= "$attr: ".$this->$attr."\n";
461           }
462         }
464         /* Append empty line */
465         $ldif.= "\n";
467         /* Feed "ldif" into hook and retrieve result*/
468         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
469         $fh= proc_open($command, $descriptorspec, $pipes);
470         if (is_resource($fh)) {
471           fwrite ($pipes[0], $ldif);
472           fclose($pipes[0]);
473           
474           $result= stream_get_contents($pipes[1]);
475           if ($result != ""){
476             $message[]= $result;
477           }
478           
479           fclose($pipes[1]);
480           fclose($pipes[2]);
481           proc_close($fh);
482         }
483       }
485     }
487     /* Check entryCSN */
488     if($this->CSN_check_active){
489       $current_csn = getEntryCSN($this->dn);
490       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
491         $this->entryCSN = $current_csn;
492         $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.");
493       }
494     }
495     return ($message);
496   }
498   /* Adapt from template, using 'dn' */
499   function adapt_from_template($dn)
500   {
501     /* Include global link_info */
502     $ldap= $this->config->get_ldap_link();
504     /* Load requested 'dn' to 'attrs' */
505     $ldap->cat ($dn);
506     $this->attrs= $ldap->fetch();
508     /* Walk through attributes */
509     foreach ($this->attributes as $val){
511       if (isset($this->attrs["$val"][0])){
513         /* If attribute is set, replace dynamic parts: 
514            %sn, %givenName and %uid. Fill these in our local variables. */
515         $value= $this->attrs["$val"][0];
517         foreach (array("sn", "givenName", "uid") as $repl){
518           if (preg_match("/%$repl/i", $value)){
519             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
520           }
521         }
522         $this->$val= $value;
523       }
524     }
526     /* Is Account? */
527     $found= TRUE;
528     foreach ($this->objectclasses as $obj){
529       if (preg_match('/top/i', $obj)){
530         continue;
531       }
532       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
533         $found= FALSE;
534         break;
535       }
536     }
537     if ($found){
538       $this->is_account= TRUE;
539     }
540   }
542   /* Indicate whether a password change is needed or not */
543   function password_change_needed()
544   {
545     return FALSE;
546   }
549   /* Show header message for tab dialogs */
550   function show_enable_header($button_text, $text, $disabled= FALSE)
551   {
552     if (($disabled == TRUE) || (!$this->acl_is_createable())){
553       $state= "disabled";
554     } else {
555       $state= "";
556     }
557     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
558     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
559       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
561     return($display);
562   }
565   /* Show header message for tab dialogs */
566   function show_disable_header($button_text, $text, $disabled= FALSE)
567   {
568     if (($disabled == TRUE) || !$this->acl_is_removeable()){
569       $state= "disabled";
570     } else {
571       $state= "";
572     }
573     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
574     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
575       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
577     return($display);
578   }
581   /* Show header message for tab dialogs */
582   function show_header($button_text, $text, $disabled= FALSE)
583   {
584     echo "FIXME: show_header should be replaced by show_disable_header and show_enable_header<br>";
585     if ($disabled == TRUE){
586       $state= "disabled";
587     } else {
588       $state= "";
589     }
590     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
591     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
592       ($this->acl_is_createable()?'':'disabled')." ".$state.
593       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
595     return($display);
596   }
599   function postcreate($add_attrs= array())
600   {
601     /* Find postcreate entries for this class */
602     $command= $this->config->search(get_class($this), "POSTCREATE",array('menu', 'tabs'));
604     if ($command != ""){
606       /* Additional attributes */
607       foreach ($add_attrs as $name => $value){
608         $command= preg_replace("/%$name/", $value, $command);
609       }
611       /* Walk through attribute list */
612       foreach ($this->attributes as $attr){
613         if (!is_array($this->$attr)){
614           $command= preg_replace("/%$attr/", $this->$attr, $command);
615         }
616       }
617       $command= preg_replace("/%dn/", $this->dn, $command);
619       if (check_command($command)){
620         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
621             $command, "Execute");
623         exec($command);
624       } else {
625         $message= sprintf(_("Command '%s', specified as POSTCREATE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
626         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
627       }
628     }
629   }
631   function postmodify($add_attrs= array())
632   {
633     /* Find postcreate entries for this class */
634     $command= $this->config->search(get_class($this), "POSTMODIFY",array('menu','tabs'));
636     if ($command != ""){
638       /* Additional attributes */
639       foreach ($add_attrs as $name => $value){
640         $command= preg_replace("/%$name/", $value, $command);
641       }
643       /* Walk through attribute list */
644       foreach ($this->attributes as $attr){
645         if (!is_array($this->$attr)){
646           $command= preg_replace("/%$attr/", $this->$attr, $command);
647         }
648       }
649       $command= preg_replace("/%dn/", $this->dn, $command);
651       if (check_command($command)){
652         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
653             $command, "Execute");
655         exec($command);
656       } else {
657         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, get_class($this));
658         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
659       }
660     }
661   }
663   function postremove($add_attrs= array())
664   {
665     /* Find postremove entries for this class */
666     $command= $this->config->search(get_class($this), "POSTREMOVE",array('menu','tabs'));
667     if ($command != ""){
669       /* Additional attributes */
670       foreach ($add_attrs as $name => $value){
671         $command= preg_replace("/%$name/", $value, $command);
672       }
674       /* Walk through attribute list */
675       foreach ($this->attributes as $attr){
676         if (!is_array($this->$attr)){
677           $command= preg_replace("/%$attr/", $this->$attr, $command);
678         }
679       }
680       $command= preg_replace("/%dn/", $this->dn, $command);
682       /* Additional attributes */
683       foreach ($add_attrs as $name => $value){
684         $command= preg_replace("/%$name/", $value, $command);
685       }
687       if (check_command($command)){
688         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
689             $command, "Execute");
691         exec($command);
692       } else {
693         $message= sprintf(_("Command '%s', specified as POSTREMOVE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
694         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
695       }
696     }
697   }
699   /* Create unique DN */
700   function create_unique_dn($attribute, $base)
701   {
702     $ldap= $this->config->get_ldap_link();
703     $base= preg_replace("/^,*/", "", $base);
705     /* Try to use plain entry first */
706     $dn= "$attribute=".$this->$attribute.",$base";
707     $ldap->cat ($dn, array('dn'));
708     if (!$ldap->fetch()){
709       return ($dn);
710     }
712     /* Look for additional attributes */
713     foreach ($this->attributes as $attr){
714       if ($attr == $attribute || $this->$attr == ""){
715         continue;
716       }
718       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
719       $ldap->cat ($dn, array('dn'));
720       if (!$ldap->fetch()){
721         return ($dn);
722       }
723     }
725     /* None found */
726     return ("none");
727   }
729   function rebind($ldap, $referral)
730   {
731     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
732     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
733       $this->error = "Success";
734       $this->hascon=true;
735       $this->reconnect= true;
736       return (0);
737     } else {
738       $this->error = "Could not bind to " . $credentials['ADMIN'];
739       return NULL;
740     }
741   }
744   /* Recursively copy ldap object */
745   function _copy($src_dn,$dst_dn)
746   {
747     $ldap=$this->config->get_ldap_link();
748     $ldap->cat($src_dn);
749     $attrs= $ldap->fetch();
751     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
752     $ds= ldap_connect($this->config->current['SERVER']);
753     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
754     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
755       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
756     }
758     $r=ldap_bind($ds,$this->config->current['ADMIN'], $this->config->current['PASSWORD']);
759     $sr=ldap_read($ds, @LDAP::fix($src_dn), "objectClass=*");
761     /* Fill data from LDAP */
762     $new= array();
763     if ($sr) {
764       $ei=ldap_first_entry($ds, $sr);
765       if ($ei) {
766         foreach($attrs as $attr => $val){
767           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
768             for ($i= 0; $i<$info['count']; $i++){
769               if ($info['count'] == 1){
770                 $new[$attr]= $info[$i];
771               } else {
772                 $new[$attr][]= $info[$i];
773               }
774             }
775           }
776         }
777       }
778     }
780     /* close conncetion */
781     ldap_unbind($ds);
783     /* Adapt naming attribute */
784     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
785     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
786     $new[$dst_name]= @LDAP::fix($dst_val);
788     /* Check if this is a department.
789      * If it is a dep. && there is a , override in his ou 
790      *  change \2C to , again, else this entry can't be saved ...
791      */
792     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
793       $new['ou'] = preg_replace("/\\\\,/",",",$new['ou']);
794     }
796     /* Save copy */
797     $ldap->connect();
798     $ldap->cd($this->config->current['BASE']);
799     
800     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
802     /* FAIvariable=.../..., cn=.. 
803         could not be saved, because the attribute FAIvariable was different to 
804         the dn FAIvariable=..., cn=... */
805     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
806       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
807     }
808     $ldap->cd($dst_dn);
809     $ldap->add($new);
811     if ($ldap->error != "Success"){
812       trigger_error("Trying to save $dst_dn failed.",
813           E_USER_WARNING);
814       return(FALSE);
815     }
816     return(TRUE);
817   }
820   /* This is a workaround function. */
821   function copy($src_dn, $dst_dn)
822   {
823     /* Rename dn in possible object groups */
824     $ldap= $this->config->get_ldap_link();
825     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::fix($src_dn).'))',
826         array('cn'));
827     while ($attrs= $ldap->fetch()){
828       $og= new ogroup($this->config, $ldap->getDN());
829       unset($og->member[$src_dn]);
830       $og->member[$dst_dn]= $dst_dn;
831       $og->save ();
832     }
834     $ldap->cat($dst_dn);
835     $attrs= $ldap->fetch();
836     if (count($attrs)){
837       trigger_error("Trying to overwrite ".@LDAP::fix($dst_dn).", which already exists.",
838           E_USER_WARNING);
839       return (FALSE);
840     }
842     $ldap->cat($src_dn);
843     $attrs= $ldap->fetch();
844     if (!count($attrs)){
845       trigger_error("Trying to move ".@LDAP::fix($src_dn).", which does not seem to exist.",
846           E_USER_WARNING);
847       return (FALSE);
848     }
850     $ldap->cd($src_dn);
851     $ldap->search("objectClass=*",array("dn"));
852     while($attrs = $ldap->fetch()){
853       $src = $attrs['dn'];
854       $dst = preg_replace("/".normalizePreg($src_dn)."$/",$dst_dn,$attrs['dn']);
855       $this->_copy($src,$dst);
856     }
857     return (TRUE);
858   }
861   function move($src_dn, $dst_dn)
862   {
863     /* Copy source to destination */
864     if (!$this->copy($src_dn, $dst_dn)){
865       return (FALSE);
866     }
868     /* Delete source */
869     $ldap= $this->config->get_ldap_link();
870     $ldap->rmdir_recursive($src_dn);
871     if ($ldap->error != "Success"){
872       trigger_error("Trying to delete $src_dn failed.",
873           E_USER_WARNING);
874       return (FALSE);
875     }
877     return (TRUE);
878   }
881   /* Move/Rename complete trees */
882   function recursive_move($src_dn, $dst_dn)
883   {
884     /* Check if the destination entry exists */
885     $ldap= $this->config->get_ldap_link();
887     /* Check if destination exists - abort */
888     $ldap->cat($dst_dn, array('dn'));
889     if ($ldap->fetch()){
890       trigger_error("recursive_move $dst_dn already exists.",
891           E_USER_WARNING);
892       return (FALSE);
893     }
895     /* Perform a search for all objects to be moved */
896     $objects= array();
897     $ldap->cd($src_dn);
898     $ldap->search("(objectClass=*)", array("dn"));
899     while($attrs= $ldap->fetch()){
900       $dn= $attrs['dn'];
901       $objects[$dn]= strlen($dn);
902     }
904     /* Sort objects by indent level */
905     asort($objects);
906     reset($objects);
908     /* Copy objects from small to big indent levels by replacing src_dn by dst_dn */
909     foreach ($objects as $object => $len){
910       $src= $object;
911       $dst= preg_replace("/$src_dn$/", "$dst_dn", $object);
912       if (!$this->copy($src, $dst)){
913         return (FALSE);
914       }
915     }
917     /* Remove src_dn */
918     $ldap->cd($src_dn);
919     $ldap->recursive_remove();
920     return (TRUE);
921   }
924   function handle_post_events($mode, $add_attrs= array())
925   {
926     switch ($mode){
927       case "add":
928         $this->postcreate($add_attrs);
929       break;
931       case "modify":
932         $this->postmodify($add_attrs);
933       break;
935       case "remove":
936         $this->postremove($add_attrs);
937       break;
938     }
939   }
942   function saveCopyDialog(){
943   }
946   function getCopyDialog(){
947     return(array("string"=>"","status"=>""));
948   }
951   function PrepareForCopyPaste($source)
952   {
953     $todo = $this->attributes;
954     if(isset($this->CopyPasteVars)){
955       $todo = array_merge($todo,$this->CopyPasteVars);
956     }
958     if(count($this->objectclasses)){
959       $this->is_account = TRUE;
960       foreach($this->objectclasses as $class){
961         if(!in_array($class,$source['objectClass'])){
962           $this->is_account = FALSE;
963         }
964       }
965     }
967     foreach($todo as $var){
968       if (isset($source[$var])){
969         if(isset($source[$var]['count'])){
970           if($source[$var]['count'] > 1){
971             $this->$var = array();
972             $tmp = array();
973             for($i = 0 ; $i < $source[$var]['count']; $i++){
974               $tmp = $source[$var][$i];
975             }
976             $this->$var = $tmp;
977 #            echo $var."=".$tmp."<br>";
978           }else{
979             $this->$var = $source[$var][0];
980 #            echo $var."=".$source[$var][0]."<br>";
981           }
982         }else{
983           $this->$var= $source[$var];
984 #          echo $var."=".$source[$var]."<br>";
985         }
986       }
987     }
988   }
991   function handle_object_tagging($dn= "", $tag= "", $show= false)
992   {
993     //FIXME: How to optimize this? We have at least two
994     //       LDAP accesses per object. It would be a good
995     //       idea to have it integrated.
997     /* No dn? Self-operation... */
998     if ($dn == ""){
999       $dn= $this->dn;
1001       /* No tag? Find it yourself... */
1002       if ($tag == ""){
1003         $len= strlen($dn);
1005         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1006         $relevant= array();
1007         foreach ($this->config->adepartments as $key => $ntag){
1009           /* This one is bigger than our dn, its not relevant... */
1010           if ($len <= strlen($key)){
1011             continue;
1012           }
1014           /* This one matches with the latter part. Break and don't fix this entry */
1015           if (preg_match('/(^|,)'.normalizePreg($key).'$/', $dn)){
1016             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1017             $relevant[strlen($key)]= $ntag;
1018             continue;
1019           }
1021         }
1023         /* If we've some relevant tags to set, just get the longest one */
1024         if (count($relevant)){
1025           ksort($relevant);
1026           $tmp= array_keys($relevant);
1027           $idx= end($tmp);
1028           $tag= $relevant[$idx];
1029           $this->gosaUnitTag= $tag;
1030         }
1031       }
1032     }
1035     /* Set tag? */
1036     if ($tag != ""){
1037       /* Set objectclass and attribute */
1038       $ldap= $this->config->get_ldap_link();
1039       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
1040       $attrs= $ldap->fetch();
1041       if(isset($attrs['gosaUnitTag'][0]) && $attrs['gosaUnitTag'][0] == $tag){
1042         if ($show) {
1043           echo sprintf(_("Object '%s' is already tagged"), @LDAP::fix($dn))."<br>";
1044           flush();
1045         }
1046         return;
1047       }
1048       if (count($attrs)){
1049         if ($show){
1050           echo sprintf(_("Adding tag (%s) to object '%s'"), $tag, @LDAP::fix($dn))."<br>";
1051           flush();
1052         }
1053         $nattrs= array("gosaUnitTag" => $tag);
1054         $nattrs['objectClass']= array();
1055         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
1056           $oc= $attrs['objectClass'][$i];
1057           if ($oc != "gosaAdministrativeUnitTag"){
1058             $nattrs['objectClass'][]= $oc;
1059           }
1060         }
1061         $nattrs['objectClass'][]= "gosaAdministrativeUnitTag";
1062         $ldap->cd($dn);
1063         $ldap->modify($nattrs);
1064         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
1065       } else {
1066         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not tagging ($tag) $dn - seems to have moved away", "Tagging");
1067       }
1069     } else {
1070       /* Remove objectclass and attribute */
1071       $ldap= $this->config->get_ldap_link();
1072       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
1073       $attrs= $ldap->fetch();
1074       if (isset($attrs['objectClass']) && !in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass'])){
1075         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "$dn is not tagged", "Tagging");
1076         return;
1077       }
1078       if (count($attrs)){
1079         if ($show){
1080           echo sprintf(_("Removing tag from object '%s'"), @LDAP::fix($dn))."<br>";
1081           flush();
1082         }
1083         $nattrs= array("gosaUnitTag" => array());
1084         $nattrs['objectClass']= array();
1085         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
1086           $oc= $attrs['objectClass'][$i];
1087           if ($oc != "gosaAdministrativeUnitTag"){
1088             $nattrs['objectClass'][]= $oc;
1089           }
1090         }
1091         $ldap->cd($dn);
1092         $ldap->modify($nattrs);
1093         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
1094       } else {
1095         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not removing tag ($tag) $dn - seems to have moved away", "Tagging");
1096       }
1097     }
1099   }
1102   /* Add possibility to stop remove process */
1103   function allow_remove()
1104   {
1105     $reason= "";
1106     return $reason;
1107   }
1110   /* Create a snapshot of the current object */
1111   function create_snapshot($type= "snapshot", $description= array())
1112   {
1114     /* Check if snapshot functionality is enabled */
1115     if(!$this->snapshotEnabled()){
1116       return;
1117     }
1119     /* Get configuration from gosa.conf */
1120     $tmp = $this->config->current;
1122     /* Create lokal ldap connection */
1123     $ldap= $this->config->get_ldap_link();
1124     $ldap->cd($this->config->current['BASE']);
1126     /* check if there are special server configurations for snapshots */
1127     if(!isset($tmp['SNAPSHOT_SERVER'])){
1129       /* Source and destination server are both the same, just copy source to dest obj */
1130       $ldap_to      = $ldap;
1131       $snapldapbase = $this->config->current['BASE'];
1133     }else{
1134       $server         = $tmp['SNAPSHOT_SERVER'];
1135       $user           = $tmp['SNAPSHOT_USER'];
1136       $password       = $tmp['SNAPSHOT_PASSWORD'];
1137       $snapldapbase   = $tmp['SNAPSHOT_BASE'];
1139       $ldap_to        = new LDAP($user,$password, $server);
1140       $ldap_to -> cd($snapldapbase);
1141       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$snapldapbase));
1142     }
1144     /* check if the dn exists */ 
1145     if ($ldap->dn_exists($this->dn)){
1147       /* Extract seconds & mysecs, they are used as entry index */
1148       list($usec, $sec)= explode(" ", microtime());
1150       /* Collect some infos */
1151       $base           = $this->config->current['BASE'];
1152       $snap_base      = $tmp['SNAPSHOT_BASE'];
1153       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1154       $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1156       /* Create object */
1157 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1158       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1159       $newName          = preg_replace("/\./", "", $sec."-".$usec);
1160       $target= array();
1161       $target['objectClass']            = array("top", "gosaSnapshotObject");
1162       $target['gosaSnapshotData']       = gzcompress($data, 6);
1163       $target['gosaSnapshotType']       = $type;
1164       $target['gosaSnapshotDN']         = $this->dn;
1165       $target['description']            = $description;
1166       $target['gosaSnapshotTimestamp']  = $newName;
1168       /* Insert the new snapshot 
1169          But we have to check first, if the given gosaSnapshotTimestamp
1170          is already used, in this case we should increment this value till there is 
1171          an unused value. */ 
1172       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1173       $ldap_to->cat($new_dn);
1174       while($ldap_to->count()){
1175         $ldap_to->cat($new_dn);
1176         $newName = preg_replace("/\./", "", $sec."-".($usec++));
1177         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1178         $target['gosaSnapshotTimestamp']  = $newName;
1179       } 
1181       /* Inset this new snapshot */
1182       $ldap_to->cd($snapldapbase);
1183       $ldap_to->create_missing_trees($snapldapbase);
1184       $ldap_to->create_missing_trees($new_base);
1185       $ldap_to->cd($new_dn);
1186       $ldap_to->add($target);
1187     
1188       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1189       show_ldap_error($ldap_to->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1190     }
1191   }
1193   function remove_snapshot($dn)
1194   {
1195     $ui       = get_userinfo();
1196     $old_dn   = $this->dn; 
1197     $this->dn = $dn;
1198     $ldap = $this->config->get_ldap_link();
1199     $ldap->cd($this->config->current['BASE']);
1200     $ldap->rmdir_recursive($dn);
1201     $this->dn = $old_dn;
1202   }
1205   /* returns true if snapshots are enabled, and false if it is disalbed
1206      There will also be some errors psoted, if the configuration failed */
1207   function snapshotEnabled()
1208   {
1209     $tmp = $this->config->current;
1210     if(isset($tmp['ENABLE_SNAPSHOT'])){
1211       if (preg_match("/^true$/i", $tmp['ENABLE_SNAPSHOT']) || preg_match("/yes/i", $tmp['ENABLE_SNAPSHOT'])){
1213         /* Check if the snapshot_base is defined */
1214         if(!isset($tmp['SNAPSHOT_BASE'])){
1215           msg_dialog::display(_("Configuration error"), sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."),"SNAPSHOT_BASE"), ERROR_DIALOG);
1216           return(FALSE);
1217         }
1219         /* check if there are special server configurations for snapshots */
1220         if(isset($tmp['SNAPSHOT_SERVER'])){
1222           /* check if all required vars are available to create a new ldap connection */
1223           $missing = "";
1224           foreach(array("SNAPSHOT_SERVER","SNAPSHOT_USER","SNAPSHOT_PASSWORD","SNAPSHOT_BASE") as $var){
1225             if(!isset($tmp[$var])){
1226               $missing .= $var." ";
1227               msg_dialog::display(_("Configuration error"), sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."), $missing), ERROR_DIALOG);
1228               return(FALSE);
1229             }
1230           }
1231         }
1232         return(TRUE);
1233       }
1234     }
1235     return(FALSE);
1236   }
1239   /* Return available snapshots for the given base 
1240    */
1241   function Available_SnapsShots($dn,$raw = false)
1242   {
1243     if(!$this->snapshotEnabled()) return(array());
1245     /* Create an additional ldap object which
1246        points to our ldap snapshot server */
1247     $ldap= $this->config->get_ldap_link();
1248     $ldap->cd($this->config->current['BASE']);
1249     $cfg= &$this->config->current;
1251     /* check if there are special server configurations for snapshots */
1253     if(isset($cfg['SERVER']) && isset($cfg['SNAPSHOT_SERVER']) && $cfg['SERVER'] == $cfg['SNAPSHOT_SERVER']){
1254       $ldap_to    = $ldap;
1255     }elseif(isset($cfg['SNAPSHOT_SERVER'])){
1256       $server       = $cfg['SNAPSHOT_SERVER'];
1257       $user         = $cfg['SNAPSHOT_USER'];
1258       $password     = $cfg['SNAPSHOT_PASSWORD'];
1259       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1261       $ldap_to      = new LDAP($user,$password, $server);
1262       $ldap_to -> cd ($snapldapbase);
1263       show_ldap_error($ldap->get_error(), sprintf(_("Method get available snapshots with dn '%s' failed."),$this->dn));
1264     }else{
1265       $ldap_to    = $ldap;
1266     }
1268     /* Prepare bases and some other infos */
1269     $base           = $this->config->current['BASE'];
1270     $snap_base      = $cfg['SNAPSHOT_BASE'];
1271     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1272     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1273     $tmp            = array(); 
1275     /* Fetch all objects with  gosaSnapshotDN=$dn */
1276     $ldap_to->cd($new_base);
1277     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1278         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1280     /* Put results into a list and add description if missing */
1281     while($entry = $ldap_to->fetch()){ 
1282       if(!isset($entry['description'][0])){
1283         $entry['description'][0]  = "";
1284       }
1285       $tmp[] = $entry; 
1286     }
1288     /* Return the raw array, or format the result */
1289     if($raw){
1290       return($tmp);
1291     }else{  
1292       $tmp2 = array();
1293       foreach($tmp as $entry){
1294         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1295       }
1296     }
1297     return($tmp2);
1298   }
1301   function getAllDeletedSnapshots($base_of_object,$raw = false)
1302   {
1303     if(!$this->snapshotEnabled()) return(array());
1305     /* Create an additional ldap object which
1306        points to our ldap snapshot server */
1307     $ldap= $this->config->get_ldap_link();
1308     $ldap->cd($this->config->current['BASE']);
1309     $cfg= &$this->config->current;
1311     /* check if there are special server configurations for snapshots */
1312     if(isset($cfg['SNAPSHOT_SERVER'])){
1313       $server       = $cfg['SNAPSHOT_SERVER'];
1314       $user         = $cfg['SNAPSHOT_USER'];
1315       $password     = $cfg['SNAPSHOT_PASSWORD'];
1316       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1317       $ldap_to      = new LDAP($user,$password, $server);
1318       $ldap_to->cd ($snapldapbase);
1319       show_ldap_error($ldap_to->get_error(), sprintf(_("Method get deleted snapshots with dn '%s' failed."),$this->dn));
1320     }else{
1321       $ldap_to    = $ldap;
1322     }
1324     /* Prepare bases */ 
1325     $base           = $this->config->current['BASE'];
1326     $snap_base      = $cfg['SNAPSHOT_BASE'];
1327     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1329     /* Fetch all objects and check if they do not exist anymore */
1330     $ui = get_userinfo();
1331     $tmp = array();
1332     $ldap_to->cd($new_base);
1333     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1334     while($entry = $ldap_to->fetch()){
1336       $chk =  str_replace($new_base,"",$entry['dn']);
1337       if(preg_match("/,ou=/",$chk)) continue;
1339       if(!isset($entry['description'][0])){
1340         $entry['description'][0]  = "";
1341       }
1342       $tmp[] = $entry; 
1343     }
1345     /* Check if entry still exists */
1346     foreach($tmp as $key => $entry){
1347       $ldap->cat($entry['gosaSnapshotDN'][0]);
1348       if($ldap->count()){
1349         unset($tmp[$key]);
1350       }
1351     }
1353     /* Format result as requested */
1354     if($raw) {
1355       return($tmp);
1356     }else{
1357       $tmp2 = array();
1358       foreach($tmp as $key => $entry){
1359         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1360       }
1361     }
1362     return($tmp2);
1363   } 
1366   /* Restore selected snapshot */
1367   function restore_snapshot($dn)
1368   {
1369     if(!$this->snapshotEnabled()) return(array());
1371     $ldap= $this->config->get_ldap_link();
1372     $ldap->cd($this->config->current['BASE']);
1373     $cfg= &$this->config->current;
1375     /* check if there are special server configurations for snapshots */
1376     if(isset($cfg['SNAPSHOT_SERVER'])){
1377       $server       = $cfg['SNAPSHOT_SERVER'];
1378       $user         = $cfg['SNAPSHOT_USER'];
1379       $password     = $cfg['SNAPSHOT_PASSWORD'];
1380       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1381       $ldap_to      = new LDAP($user,$password, $server);
1382       $ldap_to->cd ($snapldapbase);
1383       show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$snapldapbase));
1384     }else{
1385       $ldap_to    = $ldap;
1386     }
1388     /* Get the snapshot */ 
1389     $ldap_to->cat($dn);
1390     $restoreObject = $ldap_to->fetch();
1392     /* Prepare import string */
1393     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1395     /* Import the given data */
1396     $ldap->import_complete_ldif($data,$err,false,false);
1397     show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$dn));
1398   }
1401   function showSnapshotDialog($base,$baseSuffixe)
1402   {
1403     $once = true;
1404     foreach($_POST as $name => $value){
1406       /* Create a new snapshot, display a dialog */
1407       if(preg_match("/^CreateSnapShotDialog_/",$name) && $once){
1408         $once = false;
1409         $entry = preg_replace("/^CreateSnapShotDialog_/","",$name);
1410         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1411         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1412       }
1414       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1415       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1416         $once = false;
1417         $entry = preg_replace("/^RestoreSnapShotDialog_/","",$name);
1418         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1419         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1420         $this->snapDialog->display_restore_dialog = true;
1421       }
1423       /* Restore one of the already deleted objects */
1424       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1425           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1426         $once = false;
1427         $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1428         $this->snapDialog->set_snapshot_bases($baseSuffixe);
1429         $this->snapDialog->display_restore_dialog      = true;
1430         $this->snapDialog->display_all_removed_objects  = true;
1431       }
1433       /* Restore selected snapshot */
1434       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1435         $once = false;
1436         $entry = preg_replace("/^RestoreSnapShot_/","",$name);
1437         $entry = base64_decode(trim(preg_replace("/_[xy]$/","",$entry)));
1438         if(!empty($entry)){
1439           $this->restore_snapshot($entry);
1440           $this->snapDialog = NULL;
1441         }
1442       }
1443     }
1445     /* Create a new snapshot requested, check
1446        the given attributes and create the snapshot*/
1447     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1448       $this->snapDialog->save_object();
1449       $msgs = $this->snapDialog->check();
1450       if(count($msgs)){
1451         foreach($msgs as $msg){
1452           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
1453         }
1454       }else{
1455         $this->dn =  $this->snapDialog->dn;
1456         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1457         $this->snapDialog = NULL;
1458       }
1459     }
1461     /* Restore is requested, restore the object with the posted dn .*/
1462     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1463     }
1465     if(isset($_POST['CancelSnapshot'])){
1466       $this->snapDialog = NULL;
1467     }
1469     if(is_object($this->snapDialog )){
1470       $this->snapDialog->save_object();
1471       return($this->snapDialog->execute());
1472     }
1473   }
1476   static function plInfo()
1477   {
1478     return array();
1479   }
1482   function set_acl_base($base)
1483   {
1484     $this->acl_base= $base;
1485   }
1488   function set_acl_category($category)
1489   {
1490     $this->acl_category= "$category/";
1491   }
1494   function acl_is_writeable($attribute,$skip_write = FALSE)
1495   {
1496     $ui= get_userinfo();
1497     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1498   }
1501   function acl_is_readable($attribute)
1502   {
1503     $ui= get_userinfo();
1504     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1505   }
1508   function acl_is_createable()
1509   {
1510     $ui= get_userinfo();
1511     return preg_match('/c/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1512   }
1515   function acl_is_removeable()
1516   {
1517     $ui= get_userinfo();
1518     return preg_match('/d/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1519   }
1522   function acl_is_moveable()
1523   {
1524     $ui= get_userinfo();
1525     return preg_match('/m/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1526   }
1529   function acl_have_any_permissions()
1530   {
1531   }
1534   function getacl($attribute,$skip_write= FALSE)
1535   {
1536     $ui= get_userinfo();
1537     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1538   }
1540   /* Get all allowed bases to move an object to or to create a new object.
1541      Idepartments also contains all base departments which lead to the allowed bases */
1542   function get_allowed_bases($category = "")
1543   {
1544     $ui = get_userinfo();
1545     $deps = array();
1547     /* Set category */ 
1548     if(empty($category)){
1549       $category = $this->acl_category.get_class($this);
1550     }
1552     /* Is this a new object ? Or just an edited existing object */
1553     if(!$this->initially_was_account && $this->is_account){
1554       $new = true;
1555     }else{
1556       $new = false;
1557     }
1559     $cat_bases = $ui->get_module_departments(preg_replace("/\/.*$/","",$category));
1560     foreach($this->config->idepartments as $dn => $name){
1561       
1562       if(!in_array_ics($dn,$cat_bases)){
1563         continue;
1564       }
1565       
1566       $acl = $ui->get_permissions($dn,$category);
1567       if($new && preg_match("/c/",$acl)){
1568         $deps[$dn] = $name;
1569       }elseif(!$new && preg_match("/m/",$acl)){
1570         $deps[$dn] = $name;
1571       }
1572     }
1574     /* Add current base */      
1575     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1576       $deps[$this->base] = $this->config->idepartments[$this->base];
1577     }else{
1578       echo "No default base found. ".$this->base."<br> ";
1579     }
1581     return($deps);
1582   }
1584   /* This function modifies object acls too, if an object is moved.
1585    *  $old_dn   specifies the actually used dn
1586    *  $new_dn   specifies the destiantion dn
1587    */
1588   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1589   {
1590     /* Check if old_dn is empty. This should never happen */
1591     if(empty($old_dn) || empty($new_dn)){
1592       trigger_error("Failed to check acl dependencies, wrong dn given.");
1593       return;
1594     }
1596     /* Update userinfo if necessary */
1597     $ui = session::get('ui');
1598     if($ui->dn == $old_dn){
1599       $ui->dn = $new_dn;
1600       session::set('ui',$ui);
1601       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current user dn from '".$old_dn."' to '".$new_dn."'");
1602     }
1604     /* Object was moved, ensure that all acls will be moved too */
1605     if($new_dn != $old_dn && $old_dn != "new"){
1607       /* get_ldap configuration */
1608       $update = array();
1609       $ldap = $this->config->get_ldap_link();
1610       $ldap->cd ($this->config->current['BASE']);
1611       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*))",array("cn","gosaAclEntry"));
1612       while($attrs = $ldap->fetch()){
1614         $acls = array();
1616         /* Walk through acls */
1617         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1619           /* Reset vars */
1620           $found = false;
1622           /* Get Acl parts */
1623           $acl_parts = split(":",$attrs['gosaAclEntry'][$i]);
1625           /* Get every single member for this acl */  
1626           $members = array();  
1627           if(preg_match("/,/",$acl_parts[2])){
1628             $members = split(",",$acl_parts[2]);
1629           }else{
1630             $members = array($acl_parts[2]);
1631           } 
1632       
1633           /* Check if member match current dn */
1634           foreach($members as $key => $member){
1635             $member = base64_decode($member);
1636             if($member == $old_dn){
1637               $found = true;
1638               $members[$key] = base64_encode($new_dn);
1639             }
1640           } 
1641          
1642           /* Create new member string */ 
1643           $new_members = "";
1644           foreach($members as $member){
1645             $new_members .= $member.",";
1646           }
1647           $new_members = preg_replace("/,$/","",$new_members);
1648           $acl_parts[2] = $new_members;
1649         
1650           /* Reconstruckt acl entry */
1651           $acl_str  ="";
1652           foreach($acl_parts as $t){
1653            $acl_str .= $t.":";
1654           }
1655           $acl_str = preg_replace("/:$/","",$acl_str);
1656        }
1658        /* Acls for this object must be adjusted */
1659        if($found){
1661           if($output_changes){
1662             echo "<font color='green'>".
1663                   _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1664                   $old_dn.
1665                   "</b><br>&nbsp;-"._("to")."&nbsp;<b>".
1666                   $new_dn.
1667                   "</b></font><br>";
1668           }
1669           $update[$attrs['dn']] =array();
1670           foreach($acls as $acl){
1671             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1672           }
1673         }
1674       }
1676       /* Write updated acls */
1677       foreach($update as $dn => $attrs){
1678         $ldap->cd($dn);
1679         $ldap->modify($attrs);
1680       }
1681     }
1682   }
1684   
1686   /* This function enables the entry Serial ID check.
1687    * If an entry was edited while we have edited the entry too,
1688    *  an error message will be shown. 
1689    * To configure this check correctly read the FAQ.
1690    */    
1691   function enable_CSN_check()
1692   {
1693     $this->CSN_check_active =TRUE;
1694     $this->entryCSN = getEntryCSN($this->dn);
1695   }
1698   /*! \brief  Prepares the plugin to be used for multiple edit
1699    *          Update plugin attributes with given array of attribtues.
1700    *  @param  array   Array with attributes that must be updated.
1701    */
1702   function init_multiple_support($attrs,$all)
1703   {
1704     $ldap= $this->config->get_ldap_link();
1705     $this->multi_attrs    = $attrs;
1706     $this->multi_attrs_all= $all;
1708     /* Copy needed attributes */
1709     foreach ($this->attributes as $val){
1710       $found= array_key_ics($val, $this->multi_attrs);
1711       if ($found != ""){
1712         if(isset($this->multi_attrs["$found"][0])){
1713           $this->$val= $this->multi_attrs["$found"][0];
1714         }
1715       }
1716     }
1717   }
1719  
1720   /*! \brief  Enables multiple support for this plugin
1721    */
1722   function enable_multiple_support()
1723   {
1724     $this->ignore_account = TRUE;
1725     $this->multiple_support_active = TRUE;
1726   }
1729   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1730       @return array Cotaining all mdofied values. 
1731    */
1732   function get_multi_edit_values()
1733   {
1734     $ret = array();
1735     foreach($this->attributes as $attr){
1736       if(in_array($attr,$this->multi_boxes)){
1737         $ret[$attr] = $this->$attr;
1738       }
1739     }
1740     return($ret);
1741   }
1743   
1744   /*! \brief  Update class variables with values collected by multiple edit.
1745    */
1746   function set_multi_edit_values($attrs)
1747   {
1748     foreach($attrs as $name => $value){
1749       $this->$name = $value;
1750     }
1751   }
1754   /*! \brief execute plugin
1756     Generates the html output for this node
1757    */
1758   function multiple_execute()
1759   {
1760     /* This one is empty currently. Fabian - please fill in the docu code */
1761     session::set('current_class_for_help',get_class($this));
1763     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1764     session::set('LOCK_VARS_TO_USE',array());
1765     session::set('LOCK_VARS_USED',array());
1766     
1767     return("Multiple edit is currently not implemented for this plugin.");
1768   }
1771   /*! \brief   Save HTML posted data to object for multiple edit
1772    */
1773   function multiple_save_object()
1774   {
1775     if(empty($this->entryCSN) && $this->CSN_check_active){
1776       $this->entryCSN = getEntryCSN($this->dn);
1777     }
1779     /* Save values to object */
1780     $this->multi_boxes = array();
1781     foreach ($this->attributes as $val){
1782   
1783       /* Get selected checkboxes from multiple edit */
1784       if(isset($_POST["use_".$val])){
1785         $this->multi_boxes[] = $val;
1786       }
1788       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
1790         /* Check for modifications */
1791         if (get_magic_quotes_gpc()) {
1792           $data= stripcslashes($_POST["$val"]);
1793         } else {
1794           $data= $this->$val = $_POST["$val"];
1795         }
1796         if ($this->$val != $data){
1797           $this->is_modified= TRUE;
1798         }
1799     
1800         /* IE post fix */
1801         if(isset($data[0]) && $data[0] == chr(194)) {
1802           $data = "";  
1803         }
1804         $this->$val= $data;
1805       }
1806     }
1807   }
1810   /*! \brief  Returns all attributes of this plugin, 
1811                to be able to detect multiple used attributes 
1812                in multi_plugg::detect_multiple_used_attributes().
1813       @return array Attributes required for intialization of multi_plug
1814    */
1815   public function get_multi_init_values()
1816   {
1817     $attrs = $this->attrs;
1818     return($attrs);
1819   }
1822   /*! \brief  Check given values in multiple edit
1823       @return array Error messages
1824    */
1825   function multiple_check()
1826   {
1827     $message = plugin::check();
1828     return($message);
1829   }
1832 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1833 ?>