Code

Updated contrib file.
[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   /*! \brief plugin constructor
123     If 'dn' is set, the node loads the given 'dn' from LDAP
125     \param dn Distinguished name to initialize plugin from
126     \sa plugin()
127    */
128   function plugin ($config, $dn= NULL, $parent= NULL)
129   {
130     /* Configuration is fine, allways */
131     $this->config= $config;     
132     $this->dn= $dn;
134     /* Handle new accounts, don't read information from LDAP */
135     if ($dn == "new"){
136       return;
137     }
139     /* Save current dn as acl_base */
140     $this->acl_base= $dn;
142     /* Get LDAP descriptor */
143     $ldap= $this->config->get_ldap_link();
144     if ($dn != NULL){
146       /* Load data to 'attrs' and save 'dn' */
147       if ($parent != NULL){
148         $this->attrs= $parent->attrs;
149       } else {
150         $ldap->cat ($dn);
151         $this->attrs= $ldap->fetch();
152       }
154       /* Copy needed attributes */
155       foreach ($this->attributes as $val){
156         $found= array_key_ics($val, $this->attrs);
157         if ($found != ""){
158           $this->$val= $this->attrs["$found"][0];
159         }
160       }
162       /* gosaUnitTag loading... */
163       if (isset($this->attrs['gosaUnitTag'][0])){
164         $this->gosaUnitTag= $this->attrs['gosaUnitTag'][0];
165       }
167       /* Set the template flag according to the existence of objectClass
168          gosaUserTemplate */
169       if (isset($this->attrs['objectClass'])){
170         if (in_array ("gosaUserTemplate", $this->attrs['objectClass'])){
171           $this->is_template= TRUE;
172           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
173               "found", "Template check");
174         }
175       }
177       /* Is Account? */
178       error_reporting(0);
179       $found= TRUE;
180       foreach ($this->objectclasses as $obj){
181         if (preg_match('/top/i', $obj)){
182           continue;
183         }
184         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
185           $found= FALSE;
186           break;
187         }
188       }
189       error_reporting(E_ALL);
190       if ($found){
191         $this->is_account= TRUE;
192         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
193             "found", "Object check");
194       }
196       /* Prepare saved attributes */
197       $this->saved_attributes= $this->attrs;
198       foreach ($this->saved_attributes as $index => $value){
199         if (preg_match('/^[0-9]+$/', $index)){
200           unset($this->saved_attributes[$index]);
201           continue;
202         }
203         if (!in_array($index, $this->attributes) && $index != "objectClass"){
204           unset($this->saved_attributes[$index]);
205           continue;
206         }
207         if ($this->saved_attributes[$index]["count"] == 1){
208           $tmp= $this->saved_attributes[$index][0];
209           unset($this->saved_attributes[$index]);
210           $this->saved_attributes[$index]= $tmp;
211           continue;
212         }
214         unset($this->saved_attributes["$index"]["count"]);
215       }
216     }
218     /* Save initial account state */
219     $this->initially_was_account= $this->is_account;
220   }
222   /*! \brief execute plugin
224     Generates the html output for this node
225    */
226   function execute()
227   {
228     /* This one is empty currently. Fabian - please fill in the docu code */
229     $_SESSION['current_class_for_help'] = get_class($this);
231     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
232     $_SESSION['LOCK_VARS_TO_USE'] = $_SESSION['LOCK_VARS_USED'] =array();
233   }
235   /*! \brief execute plugin
236      Removes object from parent
237    */
238   function remove_from_parent()
239   {
240     /* include global link_info */
241     $ldap= $this->config->get_ldap_link();
243     /* Get current objectClasses in order to add the required ones */
244     $ldap->cat($this->dn);
245     $tmp= $ldap->fetch ();
246     if (isset($tmp['objectClass'])){
247       $oc= $tmp['objectClass'];
248     } else {
249       $oc= array("count" => 0);
250     }
252     /* Remove objectClasses from entry */
253     $ldap->cd($this->dn);
254     $this->attrs= array();
255     $this->attrs['objectClass']= array();
256     for ($i= 0; $i<$oc["count"]; $i++){
257       if (!in_array_ics($oc[$i], $this->objectclasses)){
258         $this->attrs['objectClass'][]= $oc[$i];
259       }
260     }
262     /* Unset attributes from entry */
263     foreach ($this->attributes as $val){
264       $this->attrs["$val"]= array();
265     }
267     /* Unset account info */
268     $this->is_account= FALSE;
270     /* Do not write in plugin base class, this must be done by
271        children, since there are normally additional attribs,
272        lists, etc. */
273     /*
274        $ldap->modify($this->attrs);
275      */
276   }
279   /* Save data to object */
280   function save_object()
281   {
282     /* Save values to object */
283     foreach ($this->attributes as $val){
284       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
285         /* Check for modifications */
286         if (get_magic_quotes_gpc()) {
287           $data= stripcslashes($_POST["$val"]);
288         } else {
289           $data= $this->$val = $_POST["$val"];
290         }
291         if ($this->$val != $data){
292           $this->is_modified= TRUE;
293         }
294     
295         /* Okay, how can I explain this fix ... 
296          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
297          * So IE posts these 'unselectable' option, with value = chr(194) 
298          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
299          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
300          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
301          */
302         if(isset($data[0]) && $data[0] == chr(194)) {
303           $data = "";  
304         }
305         $this->$val= $data;
306         //echo "<font color='blue'>".$val."</font><br>";
307       }else{
308         //echo "<font color='red'>".$val."</font><br>";
309       }
310     }
311   }
314   /* Save data to LDAP, depending on is_account we save or delete */
315   function save()
316   {
317     /* include global link_info */
318     $ldap= $this->config->get_ldap_link();
320     /* Start with empty array */
321     $this->attrs= array();
323     /* Get current objectClasses in order to add the required ones */
324     $ldap->cat($this->dn);
325     
326     $tmp= $ldap->fetch ();
327     
328     if (isset($tmp['objectClass'])){
329       $oc= $tmp["objectClass"];
330       $this->is_new= FALSE;
331     } else {
332       $oc= array("count" => 0);
333       $this->is_new= TRUE;
334     }
336     /* Load (minimum) attributes, add missing ones */
337     $this->attrs['objectClass']= $this->objectclasses;
338     for ($i= 0; $i<$oc["count"]; $i++){
339       if (!in_array_ics($oc[$i], $this->objectclasses)){
340         $this->attrs['objectClass'][]= $oc[$i];
341       }
342     }
344     /* Copy standard attributes */
345     foreach ($this->attributes as $val){
346       if ($this->$val != ""){
347         $this->attrs["$val"]= $this->$val;
348       } elseif (!$this->is_new) {
349         $this->attrs["$val"]= array();
350       }
351     }
353   }
356   function cleanup()
357   {
358     foreach ($this->attrs as $index => $value){
360       /* Convert arrays with one element to non arrays, if the saved
361          attributes are no array, too */
362       if (is_array($this->attrs[$index]) && 
363           count ($this->attrs[$index]) == 1 &&
364           isset($this->saved_attributes[$index]) &&
365           !is_array($this->saved_attributes[$index])){
366           
367         $tmp= $this->attrs[$index][0];
368         $this->attrs[$index]= $tmp;
369       }
371       /* Remove emtpy arrays if they do not differ */
372       if (is_array($this->attrs[$index]) &&
373           count($this->attrs[$index]) == 0 &&
374           !isset($this->saved_attributes[$index])){
375           
376         unset ($this->attrs[$index]);
377         continue;
378       }
380       /* Remove single attributes that do not differ */
381       if (!is_array($this->attrs[$index]) &&
382           isset($this->saved_attributes[$index]) &&
383           !is_array($this->saved_attributes[$index]) &&
384           $this->attrs[$index] == $this->saved_attributes[$index]){
386         unset ($this->attrs[$index]);
387         continue;
388       }
390       /* Remove arrays that do not differ */
391       if (is_array($this->attrs[$index]) && 
392           isset($this->saved_attributes[$index]) &&
393           is_array($this->saved_attributes[$index])){
394           
395         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
396           unset ($this->attrs[$index]);
397           continue;
398         }
399       }
400     }
402     /* Update saved attributes and ensure that next cleanups will be successful too */
403     foreach($this->attrs as $name => $value){
404       $this->saved_attributes[$name] = $value;
405     }
406   }
408   /* Check formular input */
409   function check()
410   {
411     $message= array();
413     /* Skip if we've no config object */
414     if (!isset($this->config)){
415       return $message;
416     }
418     /* Find hooks entries for this class */
419     $command= search_config($this->config->data['MENU'], get_class($this), "CHECK");
420     if ($command == "" && isset($this->config->data['TABS'])){
421       $command= search_config($this->config->data['TABS'], get_class($this), "CHECK");
422     }
424     if ($command != ""){
426       if (!check_command($command)){
427         $message[]= sprintf(_("Command '%s', specified as CHECK hook for plugin '%s' doesn't seem to exist."), $command,
428                             get_class($this));
429       } else {
431         /* Generate "ldif" for check hook */
432         $ldif= "dn: $this->dn\n";
433         
434         /* ... objectClasses */
435         foreach ($this->objectclasses as $oc){
436           $ldif.= "objectClass: $oc\n";
437         }
438         
439         /* ... attributes */
440         foreach ($this->attributes as $attr){
441           if ($this->$attr == ""){
442             continue;
443           }
444           if (is_array($this->$attr)){
445             foreach ($this->$attr as $val){
446               $ldif.= "$attr: $val\n";
447             }
448           } else {
449               $ldif.= "$attr: ".$this->$attr."\n";
450           }
451         }
453         /* Append empty line */
454         $ldif.= "\n";
456         /* Feed "ldif" into hook and retrieve result*/
457         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
458         $fh= proc_open($command, $descriptorspec, $pipes);
459         if (is_resource($fh)) {
460           fwrite ($pipes[0], $ldif);
461           fclose($pipes[0]);
462           
463           $result= stream_get_contents($pipes[1]);
464           if ($result != ""){
465             $message[]= $result;
466           }
467           
468           fclose($pipes[1]);
469           fclose($pipes[2]);
470           proc_close($fh);
471         }
472       }
474     }
476     return ($message);
477   }
479   /* Adapt from template, using 'dn' */
480   function adapt_from_template($dn)
481   {
482     /* Include global link_info */
483     $ldap= $this->config->get_ldap_link();
485     /* Load requested 'dn' to 'attrs' */
486     $ldap->cat ($dn);
487     $this->attrs= $ldap->fetch();
489     /* Walk through attributes */
490     foreach ($this->attributes as $val){
492       if (isset($this->attrs["$val"][0])){
494         /* If attribute is set, replace dynamic parts: 
495            %sn, %givenName and %uid. Fill these in our local variables. */
496         $value= $this->attrs["$val"][0];
498         foreach (array("sn", "givenName", "uid") as $repl){
499           if (preg_match("/%$repl/i", $value)){
500             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
501           }
502         }
503         $this->$val= $value;
504       }
505     }
507     /* Is Account? */
508     $found= TRUE;
509     foreach ($this->objectclasses as $obj){
510       if (preg_match('/top/i', $obj)){
511         continue;
512       }
513       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
514         $found= FALSE;
515         break;
516       }
517     }
518     if ($found){
519       $this->is_account= TRUE;
520     }
521   }
523   /* Indicate whether a password change is needed or not */
524   function password_change_needed()
525   {
526     return FALSE;
527   }
530   /* Show header message for tab dialogs */
531   function show_enable_header($button_text, $text, $disabled= FALSE)
532   {
533     if (($disabled == TRUE) || (!$this->acl_is_createable())){
534       $state= "disabled";
535     } else {
536       $state= "";
537     }
538     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
539     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
540       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
542     return($display);
543   }
546   /* Show header message for tab dialogs */
547   function show_disable_header($button_text, $text, $disabled= FALSE)
548   {
549     if (($disabled == TRUE) || !$this->acl_is_removeable()){
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_header($button_text, $text, $disabled= FALSE)
564   {
565     echo "FIXME: show_header should be replaced by show_disable_header and show_enable_header<br>";
566     if ($disabled == TRUE){
567       $state= "disabled";
568     } else {
569       $state= "";
570     }
571     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
572     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
573       ($this->acl_is_createable()?'':'disabled')." ".$state.
574       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
576     return($display);
577   }
580   function postcreate($add_attrs= array())
581   {
582     /* Find postcreate entries for this class */
583     $command= search_config($this->config->data['MENU'], get_class($this), "POSTCREATE");
584     if ($command == "" && isset($this->config->data['TABS'])){
585       $command= search_config($this->config->data['TABS'], get_class($this), "POSTCREATE");
586     }
588     if ($command != ""){
589       /* Walk through attribute list */
590       foreach ($this->attributes as $attr){
591         if (!is_array($this->$attr)){
592           $command= preg_replace("/%$attr/", $this->$attr, $command);
593         }
594       }
595       $command= preg_replace("/%dn/", $this->dn, $command);
597       /* Additional attributes */
598       foreach ($add_attrs as $name => $value){
599         $command= preg_replace("/%$name/", $value, $command);
600       }
602       if (check_command($command)){
603         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
604             $command, "Execute");
606         exec($command);
607       } else {
608         $message= sprintf(_("Command '%s', specified as POSTCREATE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
609         print_red ($message);
610       }
611     }
612   }
614   function postmodify($add_attrs= array())
615   {
616     /* Find postcreate entries for this class */
617     $command= search_config($this->config->data['MENU'], get_class($this), "POSTMODIFY");
618     if ($command == "" && isset($this->config->data['TABS'])){
619       $command= search_config($this->config->data['TABS'], get_class($this), "POSTMODIFY");
620     }
622     if ($command != ""){
623       /* Walk through attribute list */
624       foreach ($this->attributes as $attr){
625         if (!is_array($this->$attr)){
626           $command= preg_replace("/%$attr/", $this->$attr, $command);
627         }
628       }
629       $command= preg_replace("/%dn/", $this->dn, $command);
631       /* Additional attributes */
632       foreach ($add_attrs as $name => $value){
633         $command= preg_replace("/%$name/", $value, $command);
634       }
636       if (check_command($command)){
637         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
638             $command, "Execute");
640         exec($command);
641       } else {
642         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, get_class($this));
643         print_red ($message);
644       }
645     }
646   }
648   function postremove($add_attrs= array())
649   {
650     /* Find postremove entries for this class */
651     $command= search_config($this->config->data['MENU'], get_class($this), "POSTREMOVE");
652     if ($command == "" && isset($this->config->data['TABS'])){
653       $command= search_config($this->config->data['TABS'], get_class($this), "POSTREMOVE");
654     }
656     if ($command != ""){
657       /* Walk through attribute list */
658       foreach ($this->attributes as $attr){
659         if (!is_array($this->$attr)){
660           $command= preg_replace("/%$attr/", $this->$attr, $command);
661         }
662       }
663       $command= preg_replace("/%dn/", $this->dn, $command);
665       /* Additional attributes */
666       foreach ($add_attrs as $name => $value){
667         $command= preg_replace("/%$name/", $value, $command);
668       }
670       if (check_command($command)){
671         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
672             $command, "Execute");
674         exec($command);
675       } else {
676         $message= sprintf(_("Command '%s', specified as POSTREMOVE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
677         print_red ($message);
678       }
679     }
680   }
682   /* Create unique DN */
683   function create_unique_dn($attribute, $base)
684   {
685     $ldap= $this->config->get_ldap_link();
686     $base= preg_replace("/^,*/", "", $base);
688     /* Try to use plain entry first */
689     $dn= "$attribute=".$this->$attribute.",$base";
690     $ldap->cat ($dn, array('dn'));
691     if (!$ldap->fetch()){
692       return ($dn);
693     }
695     /* Look for additional attributes */
696     foreach ($this->attributes as $attr){
697       if ($attr == $attribute || $this->$attr == ""){
698         continue;
699       }
701       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
702       $ldap->cat ($dn, array('dn'));
703       if (!$ldap->fetch()){
704         return ($dn);
705       }
706     }
708     /* None found */
709     return ("none");
710   }
712   function rebind($ldap, $referral)
713   {
714     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
715     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
716       $this->error = "Success";
717       $this->hascon=true;
718       $this->reconnect= true;
719       return (0);
720     } else {
721       $this->error = "Could not bind to " . $credentials['ADMIN'];
722       return NULL;
723     }
724   }
726   /* This is a workaround function. */
727   function copy($src_dn, $dst_dn)
728   {
729     /* Rename dn in possible object groups */
730     $ldap= $this->config->get_ldap_link();
731     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::fix($src_dn).'))',
732         array('cn'));
733     while ($attrs= $ldap->fetch()){
734       $og= new ogroup($this->config, $ldap->getDN());
735       unset($og->member[$src_dn]);
736       $og->member[$dst_dn]= $dst_dn;
737       $og->save ();
738     }
740     $ldap->cat($dst_dn);
741     $attrs= $ldap->fetch();
742     if (count($attrs)){
743       trigger_error("Trying to overwrite ".@LDAP::fix($dst_dn).", which already exists.",
744           E_USER_WARNING);
745       return (FALSE);
746     }
748     $ldap->cat($src_dn);
749     $attrs= $ldap->fetch();
750     if (!count($attrs)){
751       trigger_error("Trying to move ".@LDAP::fix($src_dn).", which does not seem to exist.",
752           E_USER_WARNING);
753       return (FALSE);
754     }
756     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
757     $ds= ldap_connect($this->config->current['SERVER']);
758     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
759     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
760       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
761     }
763     $r=ldap_bind($ds,$this->config->current['ADMIN'], $this->config->current['PASSWORD']);
764     error_reporting (0);
765     $sr=ldap_read($ds, @LDAP::fix($src_dn), "objectClass=*");
767     /* Fill data from LDAP */
768     $new= array();
769     if ($sr) {
770       $ei=ldap_first_entry($ds, $sr);
771       if ($ei) {
772         foreach($attrs as $attr => $val){
773           if ($info = ldap_get_values_len($ds, $ei, $attr)){
774             for ($i= 0; $i<$info['count']; $i++){
775               if ($info['count'] == 1){
776                 $new[$attr]= $info[$i];
777               } else {
778                 $new[$attr][]= $info[$i];
779               }
780             }
781           }
782         }
783       }
784     }
786     /* close conncetion */
787     error_reporting (E_ALL);
788     ldap_unbind($ds);
790     /* Adapt naming attribute */
791     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
792     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
793     $new[$dst_name]= @LDAP::fix($dst_val);
795     /* Check if this is a department.
796      * If it is a dep. && there is a , override in his ou 
797      *  change \2C to , again, else this entry can't be saved ...
798      */
799     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
800       $new['ou'] = preg_replace("/\\\\,/",",",$new['ou']);
801     }
803     /* Save copy */
804     $ldap->connect();
805     $ldap->cd($this->config->current['BASE']);
806     
807     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
809     /* FAIvariable=.../..., cn=.. 
810         could not be saved, because the attribute FAIvariable was different to 
811         the dn FAIvariable=..., cn=... */
812     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
813       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
814     }
815     $ldap->cd($dst_dn);
816     $ldap->add($new);
818     if ($ldap->error != "Success"){
819       trigger_error("Trying to save $dst_dn failed.",
820           E_USER_WARNING);
821       return(FALSE);
822     }
824     return (TRUE);
825   }
828   function move($src_dn, $dst_dn)
829   {
830     /* Copy source to destination */
831     if (!$this->copy($src_dn, $dst_dn)){
832       return (FALSE);
833     }
835     /* Delete source */
836     $ldap= $this->config->get_ldap_link();
837     $ldap->rmdir($src_dn);
838     if ($ldap->error != "Success"){
839       trigger_error("Trying to delete $src_dn failed.",
840           E_USER_WARNING);
841       return (FALSE);
842     }
844     return (TRUE);
845   }
848   /* Move/Rename complete trees */
849   function recursive_move($src_dn, $dst_dn)
850   {
851     /* Check if the destination entry exists */
852     $ldap= $this->config->get_ldap_link();
854     /* Check if destination exists - abort */
855     $ldap->cat($dst_dn, array('dn'));
856     if ($ldap->fetch()){
857       trigger_error("recursive_move $dst_dn already exists.",
858           E_USER_WARNING);
859       return (FALSE);
860     }
862     /* Perform a search for all objects to be moved */
863     $objects= array();
864     $ldap->cd($src_dn);
865     $ldap->search("(objectClass=*)", array("dn"));
866     while($attrs= $ldap->fetch()){
867       $dn= $attrs['dn'];
868       $objects[$dn]= strlen($dn);
869     }
871     /* Sort objects by indent level */
872     asort($objects);
873     reset($objects);
875     /* Copy objects from small to big indent levels by replacing src_dn by dst_dn */
876     foreach ($objects as $object => $len){
877       $src= $object;
878       $dst= preg_replace("/$src_dn$/", "$dst_dn", $object);
879       if (!$this->copy($src, $dst)){
880         return (FALSE);
881       }
882     }
884     /* Remove src_dn */
885     $ldap->cd($src_dn);
886     $ldap->recursive_remove();
887     return (TRUE);
888   }
891   function handle_post_events($mode, $add_attrs= array())
892   {
893     switch ($mode){
894       case "add":
895         $this->postcreate($add_attrs);
896       break;
898       case "modify":
899         $this->postmodify($add_attrs);
900       break;
902       case "remove":
903         $this->postremove($add_attrs);
904       break;
905     }
906   }
909   function saveCopyDialog(){
910   }
913   function getCopyDialog(){
914     return(array("string"=>"","status"=>""));
915   }
918   function PrepareForCopyPaste($source)
919   {
920     $todo = $this->attributes;
921     if(isset($this->CopyPasteVars)){
922       $todo = array_merge($todo,$this->CopyPasteVars);
923     }
925     if(count($this->objectclasses)){
926       $this->is_account = TRUE;
927       foreach($this->objectclasses as $class){
928         if(!in_array($class,$source['objectClass'])){
929           $this->is_account = FALSE;
930         }
931       }
932     }
934     foreach($todo as $var){
935       if (isset($source[$var])){
936         if(isset($source[$var]['count'])){
937           if($source[$var]['count'] > 1){
938             $this->$var = array();
939             $tmp = array();
940             for($i = 0 ; $i < $source[$var]['count']; $i++){
941               $tmp = $source[$var][$i];
942             }
943             $this->$var = $tmp;
944 #            echo $var."=".$tmp."<br>";
945           }else{
946             $this->$var = $source[$var][0];
947 #            echo $var."=".$source[$var][0]."<br>";
948           }
949         }else{
950           $this->$var= $source[$var];
951 #          echo $var."=".$source[$var]."<br>";
952         }
953       }
954     }
955   }
958   function handle_object_tagging($dn= "", $tag= "", $show= false)
959   {
960     //FIXME: How to optimize this? We have at least two
961     //       LDAP accesses per object. It would be a good
962     //       idea to have it integrated.
964     /* No dn? Self-operation... */
965     if ($dn == ""){
966       $dn= $this->dn;
968       /* No tag? Find it yourself... */
969       if ($tag == ""){
970         $len= strlen($dn);
972         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
973         $relevant= array();
974         foreach ($this->config->adepartments as $key => $ntag){
976           /* This one is bigger than our dn, its not relevant... */
977           if ($len <= strlen($key)){
978             continue;
979           }
981           /* This one matches with the latter part. Break and don't fix this entry */
982           if (preg_match('/(^|,)'.normalizePreg($key).'$/', $dn)){
983             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
984             $relevant[strlen($key)]= $ntag;
985             continue;
986           }
988         }
990         /* If we've some relevant tags to set, just get the longest one */
991         if (count($relevant)){
992           ksort($relevant);
993           $tmp= array_keys($relevant);
994           $idx= end($tmp);
995           $tag= $relevant[$idx];
996           $this->gosaUnitTag= $tag;
997         }
998       }
999     }
1002     /* Set tag? */
1003     if ($tag != ""){
1004       /* Set objectclass and attribute */
1005       $ldap= $this->config->get_ldap_link();
1006       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
1007       $attrs= $ldap->fetch();
1008       if(isset($attrs['gosaUnitTag'][0]) && $attrs['gosaUnitTag'][0] == $tag){
1009         if ($show) {
1010           echo sprintf(_("Object '%s' is already tagged"), @LDAP::fix($dn))."<br>";
1011           flush();
1012         }
1013         return;
1014       }
1015       if (count($attrs)){
1016         if ($show){
1017           echo sprintf(_("Adding tag (%s) to object '%s'"), $tag, @LDAP::fix($dn))."<br>";
1018           flush();
1019         }
1020         $nattrs= array("gosaUnitTag" => $tag);
1021         $nattrs['objectClass']= array();
1022         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
1023           $oc= $attrs['objectClass'][$i];
1024           if ($oc != "gosaAdministrativeUnitTag"){
1025             $nattrs['objectClass'][]= $oc;
1026           }
1027         }
1028         $nattrs['objectClass'][]= "gosaAdministrativeUnitTag";
1029         $ldap->cd($dn);
1030         $ldap->modify($nattrs);
1031         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
1032       } else {
1033         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not tagging ($tag) $dn - seems to have moved away", "Tagging");
1034       }
1036     } else {
1037       /* Remove 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['objectClass']) && !in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass'])){
1042         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "$dn is not tagged", "Tagging");
1043         return;
1044       }
1045       if (count($attrs)){
1046         if ($show){
1047           echo sprintf(_("Removing tag from object '%s'"), @LDAP::fix($dn))."<br>";
1048           flush();
1049         }
1050         $nattrs= array("gosaUnitTag" => array());
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         $ldap->cd($dn);
1059         $ldap->modify($nattrs);
1060         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
1061       } else {
1062         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not removing tag ($tag) $dn - seems to have moved away", "Tagging");
1063       }
1064     }
1066   }
1069   /* Add possibility to stop remove process */
1070   function allow_remove()
1071   {
1072     $reason= "";
1073     return $reason;
1074   }
1077   /* Create a snapshot of the current object */
1078   function create_snapshot($type= "snapshot", $description= array())
1079   {
1081     /* Check if snapshot functionality is enabled */
1082     if(!$this->snapshotEnabled()){
1083       return;
1084     }
1086     /* Get configuration from gosa.conf */
1087     $tmp = $this->config->current;
1089     /* Create lokal ldap connection */
1090     $ldap= $this->config->get_ldap_link();
1091     $ldap->cd($this->config->current['BASE']);
1093     /* check if there are special server configurations for snapshots */
1094     if(!isset($tmp['SNAPSHOT_SERVER'])){
1096       /* Source and destination server are both the same, just copy source to dest obj */
1097       $ldap_to      = $ldap;
1098       $snapldapbase = $this->config->current['BASE'];
1100     }else{
1101       $server         = $tmp['SNAPSHOT_SERVER'];
1102       $user           = $tmp['SNAPSHOT_USER'];
1103       $password       = $tmp['SNAPSHOT_PASSWORD'];
1104       $snapldapbase   = $tmp['SNAPSHOT_BASE'];
1106       $ldap_to        = new LDAP($user,$password, $server);
1107       $ldap_to -> cd($snapldapbase);
1108       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$snapldapbase));
1109     }
1111     /* check if the dn exists */ 
1112     if ($ldap->dn_exists($this->dn)){
1114       /* Extract seconds & mysecs, they are used as entry index */
1115       list($usec, $sec)= explode(" ", microtime());
1117       /* Collect some infos */
1118       $base           = $this->config->current['BASE'];
1119       $snap_base      = $tmp['SNAPSHOT_BASE'];
1120       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1121       $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1123       /* Create object */
1124 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1125       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1126       $newName          = preg_replace("/\./", "", $sec."-".$usec);
1127       $target= array();
1128       $target['objectClass']            = array("top", "gosaSnapshotObject");
1129       $target['gosaSnapshotData']       = gzcompress($data, 6);
1130       $target['gosaSnapshotType']       = $type;
1131       $target['gosaSnapshotDN']         = $this->dn;
1132       $target['description']            = $description;
1133       $target['gosaSnapshotTimestamp']  = $newName;
1135       /* Insert the new snapshot 
1136          But we have to check first, if the given gosaSnapshotTimestamp
1137          is already used, in this case we should increment this value till there is 
1138          an unused value. */ 
1139       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1140       $ldap_to->cat($new_dn);
1141       while($ldap_to->count()){
1142         $ldap_to->cat($new_dn);
1143         $newName = preg_replace("/\./", "", $sec."-".($usec++));
1144         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1145         $target['gosaSnapshotTimestamp']  = $newName;
1146       } 
1148       /* Inset this new snapshot */
1149       $ldap_to->cd($snapldapbase);
1150       $ldap_to->create_missing_trees($new_base);
1151       $ldap_to->cd($new_dn);
1152       $ldap_to->add($target);
1154       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1155       show_ldap_error($ldap_to->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1156     }
1157   }
1159   function remove_snapshot($dn)
1160   {
1161     $ui       = get_userinfo();
1162     $old_dn   = $this->dn; 
1163     $this->dn = $dn;
1164     $ldap = $this->config->get_ldap_link();
1165     $ldap->cd($this->config->current['BASE']);
1166     $ldap->rmdir_recursive($dn);
1167     $this->dn = $old_dn;
1168   }
1171   /* returns true if snapshots are enabled, and false if it is disalbed
1172      There will also be some errors psoted, if the configuration failed */
1173   function snapshotEnabled()
1174   {
1175     $tmp = $this->config->current;
1176     if(isset($tmp['ENABLE_SNAPSHOT'])){
1177       if (preg_match("/^true$/i", $tmp['ENABLE_SNAPSHOT']) || preg_match("/yes/i", $tmp['ENABLE_SNAPSHOT'])){
1179         /* Check if the snapshot_base is defined */
1180         if(!isset($tmp['SNAPSHOT_BASE'])){
1181           print_red(sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not configured in your gosa.conf."),"SNAPSHOT_BASE"));
1182           return(FALSE);
1183         }
1185         /* check if there are special server configurations for snapshots */
1186         if(isset($tmp['SNAPSHOT_SERVER'])){
1188           /* check if all required vars are available to create a new ldap connection */
1189           $missing = "";
1190           foreach(array("SNAPSHOT_SERVER","SNAPSHOT_USER","SNAPSHOT_PASSWORD","SNAPSHOT_BASE") as $var){
1191             if(!isset($tmp[$var])){
1192               $missing .= $var." ";
1193               print_red(sprintf(_("The snapshot functionality is enabled, but the required variable(s) '%s' is not configured in your gosa.conf."),$missing));
1194               return(FALSE);
1195             }
1196           }
1197         }
1198         return(TRUE);
1199       }
1200     }
1201     return(FALSE);
1202   }
1205   /* Return available snapshots for the given base 
1206    */
1207   function Available_SnapsShots($dn,$raw = false)
1208   {
1209     if(!$this->snapshotEnabled()) return(array());
1211     /* Create an additional ldap object which
1212        points to our ldap snapshot server */
1213     $ldap= $this->config->get_ldap_link();
1214     $ldap->cd($this->config->current['BASE']);
1215     $tmp = $this->config->current;
1217     /* check if there are special server configurations for snapshots */
1218     if(isset($tmp['SNAPSHOT_SERVER'])){
1219       $server       = $tmp['SNAPSHOT_SERVER'];
1220       $user         = $tmp['SNAPSHOT_USER'];
1221       $password     = $tmp['SNAPSHOT_PASSWORD'];
1222       $snapldapbase = $tmp['SNAPSHOT_BASE'];
1223       $ldap_to      = new LDAP($user,$password, $server);
1224       $ldap_to -> cd ($snapldapbase);
1225       show_ldap_error($ldap->get_error(), sprintf(_("Method get available snapshots with dn '%s' failed."),$this->dn));
1226     }else{
1227       $ldap_to    = $ldap;
1228     }
1230     /* Prepare bases and some other infos */
1231     $base           = $this->config->current['BASE'];
1232     $snap_base      = $tmp['SNAPSHOT_BASE'];
1233     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1234     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1235     $tmp            = array(); 
1237     /* Fetch all objects with  gosaSnapshotDN=$dn */
1238     $ldap_to->cd($new_base);
1239     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1240         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1242     /* Put results into a list and add description if missing */
1243     while($entry = $ldap_to->fetch()){ 
1244       if(!isset($entry['description'][0])){
1245         $entry['description'][0]  = "";
1246       }
1247       $tmp[] = $entry; 
1248     }
1250     /* Return the raw array, or format the result */
1251     if($raw){
1252       return($tmp);
1253     }else{  
1254       $tmp2 = array();
1255       foreach($tmp as $entry){
1256         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1257       }
1258     }
1259     return($tmp2);
1260   }
1263   function getAllDeletedSnapshots($base_of_object,$raw = false)
1264   {
1265     if(!$this->snapshotEnabled()) return(array());
1267     /* Create an additional ldap object which
1268        points to our ldap snapshot server */
1269     $ldap= $this->config->get_ldap_link();
1270     $ldap->cd($this->config->current['BASE']);
1271     $tmp = $this->config->current;
1273     /* check if there are special server configurations for snapshots */
1274     if(isset($tmp['SNAPSHOT_SERVER'])){
1275       $server       = $tmp['SNAPSHOT_SERVER'];
1276       $user         = $tmp['SNAPSHOT_USER'];
1277       $password     = $tmp['SNAPSHOT_PASSWORD'];
1278       $snapldapbase = $tmp['SNAPSHOT_BASE'];
1279       $ldap_to      = new LDAP($user,$password, $server);
1280       $ldap_to->cd ($snapldapbase);
1281       show_ldap_error($ldap->get_error(), sprintf(_("Method get deleted snapshots with dn '%s' failed."),$this->dn));
1282     }else{
1283       $ldap_to    = $ldap;
1284     }
1286     /* Prepare bases */ 
1287     $base           = $this->config->current['BASE'];
1288     $snap_base      = $tmp['SNAPSHOT_BASE'];
1289     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1291     /* Fetch all objects and check if they do not exist anymore */
1292     $ui = get_userinfo();
1293     $tmp = array();
1294     $ldap_to->cd($new_base);
1295     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1296     while($entry = $ldap_to->fetch()){
1298       $chk =  str_replace($new_base,"",$entry['dn']);
1299       if(preg_match("/,ou=/",$chk)) continue;
1301       if(!isset($entry['description'][0])){
1302         $entry['description'][0]  = "";
1303       }
1304       $tmp[] = $entry; 
1305     }
1307     /* Check if entry still exists */
1308     foreach($tmp as $key => $entry){
1309       $ldap->cat($entry['gosaSnapshotDN'][0]);
1310       if($ldap->count()){
1311         unset($tmp[$key]);
1312       }
1313     }
1315     /* Format result as requested */
1316     if($raw) {
1317       return($tmp);
1318     }else{
1319       $tmp2 = array();
1320       foreach($tmp as $key => $entry){
1321         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1322       }
1323     }
1324     return($tmp2);
1325   } 
1328   /* Restore selected snapshot */
1329   function restore_snapshot($dn)
1330   {
1331     if(!$this->snapshotEnabled()) return(array());
1333     $ldap= $this->config->get_ldap_link();
1334     $ldap->cd($this->config->current['BASE']);
1335     $tmp = $this->config->current;
1337     /* check if there are special server configurations for snapshots */
1338     if(isset($tmp['SNAPSHOT_SERVER'])){
1339       $server       = $tmp['SNAPSHOT_SERVER'];
1340       $user         = $tmp['SNAPSHOT_USER'];
1341       $password     = $tmp['SNAPSHOT_PASSWORD'];
1342       $snapldapbase = $tmp['SNAPSHOT_BASE'];
1343       $ldap_to      = new LDAP($user,$password, $server);
1344       $ldap_to->cd ($snapldapbase);
1345       show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$snapldapbase));
1346     }else{
1347       $ldap_to    = $ldap;
1348     }
1350     /* Get the snapshot */ 
1351     $ldap_to->cat($dn);
1352     $restoreObject = $ldap_to->fetch();
1354     /* Prepare import string */
1355     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1357     /* Import the given data */
1358     $ldap->import_complete_ldif($data,$err,false,false);
1359     show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$dn));
1360   }
1363   function showSnapshotDialog($base,$baseSuffixe)
1364   {
1365     $once = true;
1366     foreach($_POST as $name => $value){
1368       /* Create a new snapshot, display a dialog */
1369       if(preg_match("/^CreateSnapShotDialog_/",$name) && $once){
1370         $once = false;
1371         $entry = preg_replace("/^CreateSnapShotDialog_/","",$name);
1372         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1373         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1374       }
1376       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1377       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1378         $once = false;
1379         $entry = preg_replace("/^RestoreSnapShotDialog_/","",$name);
1380         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1381         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1382         $this->snapDialog->display_restore_dialog = true;
1383       }
1385       /* Restore one of the already deleted objects */
1386       if(preg_match("/^RestoreDeletedSnapShot_/",$name) && $once){
1387         $once = false;
1388         $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1389         $this->snapDialog->set_snapshot_bases($baseSuffixe);
1390         $this->snapDialog->display_restore_dialog      = true;
1391         $this->snapDialog->display_all_removed_objects  = true;
1392       }
1394       /* Restore selected snapshot */
1395       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1396         $once = false;
1397         $entry = preg_replace("/^RestoreSnapShot_/","",$name);
1398         $entry = base64_decode(trim(preg_replace("/_[xy]$/","",$entry)));
1399         if(!empty($entry)){
1400           $this->restore_snapshot($entry);
1401           $this->snapDialog = NULL;
1402         }
1403       }
1404     }
1406     /* Create a new snapshot requested, check
1407        the given attributes and create the snapshot*/
1408     if(isset($_POST['CreateSnapshot'])){
1409       $this->snapDialog->save_object();
1410       $msgs = $this->snapDialog->check();
1411       if(count($msgs)){
1412         foreach($msgs as $msg){
1413           print_red($msg);
1414         }
1415       }else{
1416         $this->dn =  $this->snapDialog->dn;
1417         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1418         $this->snapDialog = NULL;
1419       }
1420     }
1422     /* Restore is requested, restore the object with the posted dn .*/
1423     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1424     }
1426     if(isset($_POST['CancelSnapshot'])){
1427       $this->snapDialog = NULL;
1428     }
1430     if($this->snapDialog){
1431       $this->snapDialog->save_object();
1432       return($this->snapDialog->execute());
1433     }
1434   }
1437   function plInfo()
1438   {
1439     return array();
1440   }
1443   function set_acl_base($base)
1444   {
1445     $this->acl_base= $base;
1446   }
1449   function set_acl_category($category)
1450   {
1451     $this->acl_category= "$category/";
1452   }
1455   function acl_is_writeable($attribute,$skip_write = FALSE)
1456   {
1457     $ui= get_userinfo();
1458     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1459   }
1462   function acl_is_readable($attribute)
1463   {
1464     $ui= get_userinfo();
1465     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1466   }
1469   function acl_is_createable()
1470   {
1471     $ui= get_userinfo();
1472     return preg_match('/c/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1473   }
1476   function acl_is_removeable()
1477   {
1478     $ui= get_userinfo();
1479     return preg_match('/d/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1480   }
1483   function acl_is_moveable()
1484   {
1485     $ui= get_userinfo();
1486     return preg_match('/m/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1487   }
1490   function acl_have_any_permissions()
1491   {
1492   }
1495   function getacl($attribute,$skip_write= FALSE)
1496   {
1497     $ui= get_userinfo();
1498     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1499   }
1501   /* Get all allowed bases to move an object to or to create a new object.
1502      Idepartments also contains all base departments which lead to the allowed bases */
1503   function get_allowed_bases($category = "")
1504   {
1505     $ui = get_userinfo();
1506     $deps = array();
1508     /* Set category */ 
1509     if(empty($category)){
1510       $category = $this->acl_category.get_class($this);
1511     }
1513     /* Is this a new object ? Or just an edited existing object */
1514     if(!$this->initially_was_account && $this->is_account){
1515       $new = true;
1516     }else{
1517       $new = false;
1518     }
1520     $cat_bases = $ui->get_module_departments(preg_replace("/\/.*$/","",$category));
1521     foreach($this->config->idepartments as $dn => $name){
1522       
1523       if(!in_array_ics($dn,$cat_bases)){
1524         continue;
1525       }
1526       
1527       $acl = $ui->get_permissions($dn,$category);
1528       if($new && preg_match("/c/",$acl)){
1529         $deps[$dn] = $name;
1530       }elseif(!$new && preg_match("/m/",$acl)){
1531         $deps[$dn] = $name;
1532       }
1533     }
1535     /* Add current base */      
1536     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1537       $deps[$this->base] = $this->config->idepartments[$this->base];
1538     }else{
1539       echo "No default base found. ".$this->base."<br> ";
1540     }
1542     return($deps);
1543   }
1545   /* This function modifies object acls too, if an object is moved.
1546    *  $old_dn   specifies the actually used dn
1547    *  $new_dn   specifies the destiantion dn
1548    */
1549   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1550   {
1551     global $config;
1553     /* Check if old_dn is empty. This should never happen */
1554     if(empty($old_dn) || empty($new_dn)){
1555       trigger_error("Failed to check acl dependencies, wrong dn given.");
1556       return;
1557     }
1559     /* Update userinfo if necessary */
1560     if($_SESSION['ui']->dn == $old_dn){
1561       $_SESSION['ui']->dn = $new_dn;
1562       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current user dn from '".$old_dn."' to '".$new_dn."'");
1563     }
1565     /* Object was moved, ensure that all acls will be moved too */
1566     if($new_dn != $old_dn && $old_dn != "new"){
1568       /* get_ldap configuration */
1569       $update = array();
1570       $ldap = $config->get_ldap_link();
1571       $ldap->cd ($config->current['BASE']);
1572       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*))",array("cn","gosaAclEntry"));
1573       while($attrs = $ldap->fetch()){
1575         $acls = array();
1577         /* Walk through acls */
1578         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1580           /* Reset vars */
1581           $found = false;
1583           /* Get Acl parts */
1584           $acl_parts = split(":",$attrs['gosaAclEntry'][$i]);
1586           /* Get every single member for this acl */  
1587           $members = array();  
1588           if(preg_match("/,/",$acl_parts[2])){
1589             $members = split(",",$acl_parts[2]);
1590           }else{
1591             $members = array($acl_parts[2]);
1592           } 
1593       
1594           /* Check if member match current dn */
1595           foreach($members as $key => $member){
1596             $member = base64_decode($member);
1597             if($member == $old_dn){
1598               $found = true;
1599               $members[$key] = base64_encode($new_dn);
1600             }
1601           } 
1602          
1603           /* Create new member string */ 
1604           $new_members = "";
1605           foreach($members as $member){
1606             $new_members .= $member.",";
1607           }
1608           $new_members = preg_replace("/,$/","",$new_members);
1609           $acl_parts[2] = $new_members;
1610         
1611           /* Reconstruckt acl entry */
1612           $acl_str  ="";
1613           foreach($acl_parts as $t){
1614            $acl_str .= $t.":";
1615           }
1616           $acl_str = preg_replace("/:$/","",$acl_str);
1617        }
1619        /* Acls for this object must be adjusted */
1620        if($found){
1622           if($output_changes){
1623             echo "<font color='green'>".
1624                   _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1625                   $old_dn.
1626                   "</b><br>&nbsp;-"._("to")."&nbsp;<b>".
1627                   $new_dn.
1628                   "</b></font><br>";
1629           }
1630           $update[$attrs['dn']] =array();
1631           foreach($acls as $acl){
1632             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1633           }
1634         }
1635       }
1637       /* Write updated acls */
1638       foreach($update as $dn => $attrs){
1639         $ldap->cd($dn);
1640         $ldap->modify($attrs);
1641       }
1642     }
1643   }
1645 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1646 ?>