Code

47dd20c517adc7de44330e857ac973e9059d537f
[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 | E_STRICT);
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     $oc= array();
247     if (isset($tmp['objectClass'])){
248       $oc= $tmp['objectClass'];
249       unset($oc['count']);
250     }
252     /* Remove objectClasses from entry */
253     $ldap->cd($this->dn);
254     $this->attrs= array();
255     $this->attrs['objectClass']= array_remove_entries($this->objectclasses,$oc);
257     /* Unset attributes from entry */
258     foreach ($this->attributes as $val){
259       $this->attrs["$val"]= array();
260     }
262     /* Unset account info */
263     $this->is_account= FALSE;
265     /* Do not write in plugin base class, this must be done by
266        children, since there are normally additional attribs,
267        lists, etc. */
268     /*
269        $ldap->modify($this->attrs);
270      */
271   }
274   /* Save data to object */
275   function save_object()
276   {
277     /* Save values to object */
278     foreach ($this->attributes as $val){
279       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
280         /* Check for modifications */
281         if (get_magic_quotes_gpc()) {
282           $data= stripcslashes($_POST["$val"]);
283         } else {
284           $data= $this->$val = $_POST["$val"];
285         }
286         if ($this->$val != $data){
287           $this->is_modified= TRUE;
288         }
289     
290         /* Okay, how can I explain this fix ... 
291          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
292          * So IE posts these 'unselectable' option, with value = chr(194) 
293          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
294          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
295          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
296          */
297         if(isset($data[0]) && $data[0] == chr(194)) {
298           $data = "";  
299         }
300         $this->$val= $data;
301         //echo "<font color='blue'>".$val."</font><br>";
302       }else{
303         //echo "<font color='red'>".$val."</font><br>";
304       }
305     }
306   }
309   /* Save data to LDAP, depending on is_account we save or delete */
310   function save()
311   {
312     /* include global link_info */
313     $ldap= $this->config->get_ldap_link();
315     /* Start with empty array */
316     $this->attrs= array();
318     /* Get current objectClasses in order to add the required ones */
319     $ldap->cat($this->dn);
320     
321     $tmp= $ldap->fetch ();
323     $oc= array();
324     if (isset($tmp['objectClass'])){
325       $oc= $tmp["objectClass"];
326       $this->is_new= FALSE;
327       unset($oc['count']);
328     } else {
329       $this->is_new= TRUE;
330     }
332     /* Load (minimum) attributes, add missing ones */
333     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
335     /* Copy standard attributes */
336     foreach ($this->attributes as $val){
337       if ($this->$val != ""){
338         $this->attrs["$val"]= $this->$val;
339       } elseif (!$this->is_new) {
340         $this->attrs["$val"]= array();
341       }
342     }
344   }
347   function cleanup()
348   {
349     foreach ($this->attrs as $index => $value){
351       /* Convert arrays with one element to non arrays, if the saved
352          attributes are no array, too */
353       if (is_array($this->attrs[$index]) && 
354           count ($this->attrs[$index]) == 1 &&
355           isset($this->saved_attributes[$index]) &&
356           !is_array($this->saved_attributes[$index])){
357           
358         $tmp= $this->attrs[$index][0];
359         $this->attrs[$index]= $tmp;
360       }
362       /* Remove emtpy arrays if they do not differ */
363       if (is_array($this->attrs[$index]) &&
364           count($this->attrs[$index]) == 0 &&
365           !isset($this->saved_attributes[$index])){
366           
367         unset ($this->attrs[$index]);
368         continue;
369       }
371       /* Remove single attributes that do not differ */
372       if (!is_array($this->attrs[$index]) &&
373           isset($this->saved_attributes[$index]) &&
374           !is_array($this->saved_attributes[$index]) &&
375           $this->attrs[$index] == $this->saved_attributes[$index]){
377         unset ($this->attrs[$index]);
378         continue;
379       }
381       /* Remove arrays that do not differ */
382       if (is_array($this->attrs[$index]) && 
383           isset($this->saved_attributes[$index]) &&
384           is_array($this->saved_attributes[$index])){
385           
386         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
387           unset ($this->attrs[$index]);
388           continue;
389         }
390       }
391     }
393     /* Update saved attributes and ensure that next cleanups will be successful too */
394     foreach($this->attrs as $name => $value){
395       $this->saved_attributes[$name] = $value;
396     }
397   }
399   /* Check formular input */
400   function check()
401   {
402     $message= array();
404     /* Skip if we've no config object */
405     if (!isset($this->config)){
406       return $message;
407     }
409     /* Find hooks entries for this class */
410     $command= search_config($this->config->data['MENU'], get_class($this), "CHECK");
411     if ($command == "" && isset($this->config->data['TABS'])){
412       $command= search_config($this->config->data['TABS'], get_class($this), "CHECK");
413     }
415     if ($command != ""){
417       if (!check_command($command)){
418         $message[]= sprintf(_("Command '%s', specified as CHECK hook for plugin '%s' doesn't seem to exist."), $command,
419                             get_class($this));
420       } else {
422         /* Generate "ldif" for check hook */
423         $ldif= "dn: $this->dn\n";
424         
425         /* ... objectClasses */
426         foreach ($this->objectclasses as $oc){
427           $ldif.= "objectClass: $oc\n";
428         }
429         
430         /* ... attributes */
431         foreach ($this->attributes as $attr){
432           if ($this->$attr == ""){
433             continue;
434           }
435           if (is_array($this->$attr)){
436             foreach ($this->$attr as $val){
437               $ldif.= "$attr: $val\n";
438             }
439           } else {
440               $ldif.= "$attr: ".$this->$attr."\n";
441           }
442         }
444         /* Append empty line */
445         $ldif.= "\n";
447         /* Feed "ldif" into hook and retrieve result*/
448         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
449         $fh= proc_open($command, $descriptorspec, $pipes);
450         if (is_resource($fh)) {
451           fwrite ($pipes[0], $ldif);
452           fclose($pipes[0]);
453           
454           $result= stream_get_contents($pipes[1]);
455           if ($result != ""){
456             $message[]= $result;
457           }
458           
459           fclose($pipes[1]);
460           fclose($pipes[2]);
461           proc_close($fh);
462         }
463       }
465     }
467     return ($message);
468   }
470   /* Adapt from template, using 'dn' */
471   function adapt_from_template($dn)
472   {
473     /* Include global link_info */
474     $ldap= $this->config->get_ldap_link();
476     /* Load requested 'dn' to 'attrs' */
477     $ldap->cat ($dn);
478     $this->attrs= $ldap->fetch();
480     /* Walk through attributes */
481     foreach ($this->attributes as $val){
483       if (isset($this->attrs["$val"][0])){
485         /* If attribute is set, replace dynamic parts: 
486            %sn, %givenName and %uid. Fill these in our local variables. */
487         $value= $this->attrs["$val"][0];
489         foreach (array("sn", "givenName", "uid") as $repl){
490           if (preg_match("/%$repl/i", $value)){
491             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
492           }
493         }
494         $this->$val= $value;
495       }
496     }
498     /* Is Account? */
499     $found= TRUE;
500     foreach ($this->objectclasses as $obj){
501       if (preg_match('/top/i', $obj)){
502         continue;
503       }
504       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
505         $found= FALSE;
506         break;
507       }
508     }
509     if ($found){
510       $this->is_account= TRUE;
511     }
512   }
514   /* Indicate whether a password change is needed or not */
515   function password_change_needed()
516   {
517     return FALSE;
518   }
521   /* Show header message for tab dialogs */
522   function show_enable_header($button_text, $text, $disabled= FALSE)
523   {
524     if (($disabled == TRUE) || (!$this->acl_is_createable())){
525       $state= "disabled";
526     } else {
527       $state= "";
528     }
529     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
530     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
531       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
533     return($display);
534   }
537   /* Show header message for tab dialogs */
538   function show_disable_header($button_text, $text, $disabled= FALSE)
539   {
540     if (($disabled == TRUE) || !$this->acl_is_removeable()){
541       $state= "disabled";
542     } else {
543       $state= "";
544     }
545     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
546     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
547       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
549     return($display);
550   }
553   /* Show header message for tab dialogs */
554   function show_header($button_text, $text, $disabled= FALSE)
555   {
556     echo "FIXME: show_header should be replaced by show_disable_header and show_enable_header<br>";
557     if ($disabled == TRUE){
558       $state= "disabled";
559     } else {
560       $state= "";
561     }
562     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
563     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
564       ($this->acl_is_createable()?'':'disabled')." ".$state.
565       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
567     return($display);
568   }
571   function postcreate($add_attrs= array())
572   {
573     /* Find postcreate entries for this class */
574     $command= search_config($this->config->data['MENU'], get_class($this), "POSTCREATE");
575     if ($command == "" && isset($this->config->data['TABS'])){
576       $command= search_config($this->config->data['TABS'], get_class($this), "POSTCREATE");
577     }
579     if ($command != ""){
581       /* Additional attributes */
582       foreach ($add_attrs as $name => $value){
583         $command= preg_replace("/%$name/", $value, $command);
584       }
586       /* Walk through attribute list */
587       foreach ($this->attributes as $attr){
588         if (!is_array($this->$attr)){
589           $command= preg_replace("/%$attr/", $this->$attr, $command);
590         }
591       }
592       $command= preg_replace("/%dn/", $this->dn, $command);
594       if (check_command($command)){
595         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
596             $command, "Execute");
598         exec($command);
599       } else {
600         $message= sprintf(_("Command '%s', specified as POSTCREATE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
601         print_red ($message);
602       }
603     }
604   }
606   function postmodify($add_attrs= array())
607   {
608     /* Find postcreate entries for this class */
609     $command= search_config($this->config->data['MENU'], get_class($this), "POSTMODIFY");
610     if ($command == "" && isset($this->config->data['TABS'])){
611       $command= search_config($this->config->data['TABS'], get_class($this), "POSTMODIFY");
612     }
614     if ($command != ""){
616       /* Additional attributes */
617       foreach ($add_attrs as $name => $value){
618         $command= preg_replace("/%$name/", $value, $command);
619       }
621       /* Walk through attribute list */
622       foreach ($this->attributes as $attr){
623         if (!is_array($this->$attr)){
624           $command= preg_replace("/%$attr/", $this->$attr, $command);
625         }
626       }
627       $command= preg_replace("/%dn/", $this->dn, $command);
629       if (check_command($command)){
630         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
631             $command, "Execute");
633         exec($command);
634       } else {
635         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, get_class($this));
636         print_red ($message);
637       }
638     }
639   }
641   function postremove($add_attrs= array())
642   {
643     /* Find postremove entries for this class */
644     $command= search_config($this->config->data['MENU'], get_class($this), "POSTREMOVE");
645     if ($command == "" && isset($this->config->data['TABS'])){
646       $command= search_config($this->config->data['TABS'], get_class($this), "POSTREMOVE");
647     }
649     if ($command != ""){
651       /* Additional attributes */
652       foreach ($add_attrs as $name => $value){
653         $command= preg_replace("/%$name/", $value, $command);
654       }
656       /* Walk through attribute list */
657       foreach ($this->attributes as $attr){
658         if (!is_array($this->$attr)){
659           $command= preg_replace("/%$attr/", $this->$attr, $command);
660         }
661       }
662       $command= preg_replace("/%dn/", $this->dn, $command);
664       /* Additional attributes */
665       foreach ($add_attrs as $name => $value){
666         $command= preg_replace("/%$name/", $value, $command);
667       }
669       if (check_command($command)){
670         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
671             $command, "Execute");
673         exec($command);
674       } else {
675         $message= sprintf(_("Command '%s', specified as POSTREMOVE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
676         print_red ($message);
677       }
678     }
679   }
681   /* Create unique DN */
682   function create_unique_dn($attribute, $base)
683   {
684     $ldap= $this->config->get_ldap_link();
685     $base= preg_replace("/^,*/", "", $base);
687     /* Try to use plain entry first */
688     $dn= "$attribute=".$this->$attribute.",$base";
689     $ldap->cat ($dn, array('dn'));
690     if (!$ldap->fetch()){
691       return ($dn);
692     }
694     /* Look for additional attributes */
695     foreach ($this->attributes as $attr){
696       if ($attr == $attribute || $this->$attr == ""){
697         continue;
698       }
700       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
701       $ldap->cat ($dn, array('dn'));
702       if (!$ldap->fetch()){
703         return ($dn);
704       }
705     }
707     /* None found */
708     return ("none");
709   }
711   function rebind($ldap, $referral)
712   {
713     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
714     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
715       $this->error = "Success";
716       $this->hascon=true;
717       $this->reconnect= true;
718       return (0);
719     } else {
720       $this->error = "Could not bind to " . $credentials['ADMIN'];
721       return NULL;
722     }
723   }
725   /* This is a workaround function. */
726   function copy($src_dn, $dst_dn)
727   {
728     /* Rename dn in possible object groups */
729     $ldap= $this->config->get_ldap_link();
730     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::fix($src_dn).'))',
731         array('cn'));
732     while ($attrs= $ldap->fetch()){
733       $og= new ogroup($this->config, $ldap->getDN());
734       unset($og->member[$src_dn]);
735       $og->member[$dst_dn]= $dst_dn;
736       $og->save ();
737     }
739     $ldap->cat($dst_dn);
740     $attrs= $ldap->fetch();
741     if (count($attrs)){
742       trigger_error("Trying to overwrite ".@LDAP::fix($dst_dn).", which already exists.",
743           E_USER_WARNING);
744       return (FALSE);
745     }
747     $ldap->cat($src_dn);
748     $attrs= $ldap->fetch();
749     if (!count($attrs)){
750       trigger_error("Trying to move ".@LDAP::fix($src_dn).", which does not seem to exist.",
751           E_USER_WARNING);
752       return (FALSE);
753     }
755     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
756     $ds= ldap_connect($this->config->current['SERVER']);
757     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
758     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
759       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
760     }
762     $r=ldap_bind($ds,$this->config->current['ADMIN'], $this->config->current['PASSWORD']);
763     error_reporting (0);
764     $sr=ldap_read($ds, @LDAP::fix($src_dn), "objectClass=*");
766     /* Fill data from LDAP */
767     $new= array();
768     if ($sr) {
769       $ei=ldap_first_entry($ds, $sr);
770       if ($ei) {
771         foreach($attrs as $attr => $val){
772           if ($info = ldap_get_values_len($ds, $ei, $attr)){
773             for ($i= 0; $i<$info['count']; $i++){
774               if ($info['count'] == 1){
775                 $new[$attr]= $info[$i];
776               } else {
777                 $new[$attr][]= $info[$i];
778               }
779             }
780           }
781         }
782       }
783     }
785     /* close conncetion */
786     error_reporting (E_ALL | E_STRICT);
787     ldap_unbind($ds);
789     /* Adapt naming attribute */
790     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
791     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
792     $new[$dst_name]= @LDAP::fix($dst_val);
794     /* Check if this is a department.
795      * If it is a dep. && there is a , override in his ou 
796      *  change \2C to , again, else this entry can't be saved ...
797      */
798     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
799       $new['ou'] = preg_replace("/\\\\,/",",",$new['ou']);
800     }
802     /* Save copy */
803     $ldap->connect();
804     $ldap->cd($this->config->current['BASE']);
805     
806     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
808     /* FAIvariable=.../..., cn=.. 
809         could not be saved, because the attribute FAIvariable was different to 
810         the dn FAIvariable=..., cn=... */
811     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
812       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
813     }
814     $ldap->cd($dst_dn);
815     $ldap->add($new);
817     if ($ldap->error != "Success"){
818       trigger_error("Trying to save $dst_dn failed.",
819           E_USER_WARNING);
820       return(FALSE);
821     }
823     return (TRUE);
824   }
827   function move($src_dn, $dst_dn)
828   {
829     /* Copy source to destination */
830     if (!$this->copy($src_dn, $dst_dn)){
831       return (FALSE);
832     }
834     /* Delete source */
835     $ldap= $this->config->get_ldap_link();
836     $ldap->rmdir($src_dn);
837     if ($ldap->error != "Success"){
838       trigger_error("Trying to delete $src_dn failed.",
839           E_USER_WARNING);
840       return (FALSE);
841     }
843     return (TRUE);
844   }
847   /* Move/Rename complete trees */
848   function recursive_move($src_dn, $dst_dn)
849   {
850     /* Check if the destination entry exists */
851     $ldap= $this->config->get_ldap_link();
853     /* Check if destination exists - abort */
854     $ldap->cat($dst_dn, array('dn'));
855     if ($ldap->fetch()){
856       trigger_error("recursive_move $dst_dn already exists.",
857           E_USER_WARNING);
858       return (FALSE);
859     }
861     /* Perform a search for all objects to be moved */
862     $objects= array();
863     $ldap->cd($src_dn);
864     $ldap->search("(objectClass=*)", array("dn"));
865     while($attrs= $ldap->fetch()){
866       $dn= $attrs['dn'];
867       $objects[$dn]= strlen($dn);
868     }
870     /* Sort objects by indent level */
871     asort($objects);
872     reset($objects);
874     /* Copy objects from small to big indent levels by replacing src_dn by dst_dn */
875     foreach ($objects as $object => $len){
876       $src= $object;
877       $dst= preg_replace("/$src_dn$/", "$dst_dn", $object);
878       if (!$this->copy($src, $dst)){
879         return (FALSE);
880       }
881     }
883     /* Remove src_dn */
884     $ldap->cd($src_dn);
885     $ldap->recursive_remove();
886     return (TRUE);
887   }
890   function handle_post_events($mode, $add_attrs= array())
891   {
892     switch ($mode){
893       case "add":
894         $this->postcreate($add_attrs);
895       break;
897       case "modify":
898         $this->postmodify($add_attrs);
899       break;
901       case "remove":
902         $this->postremove($add_attrs);
903       break;
904     }
905   }
908   function saveCopyDialog(){
909   }
912   function getCopyDialog(){
913     return(array("string"=>"","status"=>""));
914   }
917   function PrepareForCopyPaste($source)
918   {
919     $todo = $this->attributes;
920     if(isset($this->CopyPasteVars)){
921       $todo = array_merge($todo,$this->CopyPasteVars);
922     }
924     if(count($this->objectclasses)){
925       $this->is_account = TRUE;
926       foreach($this->objectclasses as $class){
927         if(!in_array($class,$source['objectClass'])){
928           $this->is_account = FALSE;
929         }
930       }
931     }
933     foreach($todo as $var){
934       if (isset($source[$var])){
935         if(isset($source[$var]['count'])){
936           if($source[$var]['count'] > 1){
937             $this->$var = array();
938             $tmp = array();
939             for($i = 0 ; $i < $source[$var]['count']; $i++){
940               $tmp = $source[$var][$i];
941             }
942             $this->$var = $tmp;
943 #            echo $var."=".$tmp."<br>";
944           }else{
945             $this->$var = $source[$var][0];
946 #            echo $var."=".$source[$var][0]."<br>";
947           }
948         }else{
949           $this->$var= $source[$var];
950 #          echo $var."=".$source[$var]."<br>";
951         }
952       }
953     }
954   }
957   function handle_object_tagging($dn= "", $tag= "", $show= false)
958   {
959     //FIXME: How to optimize this? We have at least two
960     //       LDAP accesses per object. It would be a good
961     //       idea to have it integrated.
963     /* No dn? Self-operation... */
964     if ($dn == ""){
965       $dn= $this->dn;
967       /* No tag? Find it yourself... */
968       if ($tag == ""){
969         $len= strlen($dn);
971         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
972         $relevant= array();
973         foreach ($this->config->adepartments as $key => $ntag){
975           /* This one is bigger than our dn, its not relevant... */
976           if ($len <= strlen($key)){
977             continue;
978           }
980           /* This one matches with the latter part. Break and don't fix this entry */
981           if (preg_match('/(^|,)'.normalizePreg($key).'$/', $dn)){
982             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
983             $relevant[strlen($key)]= $ntag;
984             continue;
985           }
987         }
989         /* If we've some relevant tags to set, just get the longest one */
990         if (count($relevant)){
991           ksort($relevant);
992           $tmp= array_keys($relevant);
993           $idx= end($tmp);
994           $tag= $relevant[$idx];
995           $this->gosaUnitTag= $tag;
996         }
997       }
998     }
1001     /* Set tag? */
1002     if ($tag != ""){
1003       /* Set objectclass and attribute */
1004       $ldap= $this->config->get_ldap_link();
1005       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
1006       $attrs= $ldap->fetch();
1007       if(isset($attrs['gosaUnitTag'][0]) && $attrs['gosaUnitTag'][0] == $tag){
1008         if ($show) {
1009           echo sprintf(_("Object '%s' is already tagged"), @LDAP::fix($dn))."<br>";
1010           flush();
1011         }
1012         return;
1013       }
1014       if (count($attrs)){
1015         if ($show){
1016           echo sprintf(_("Adding tag (%s) to object '%s'"), $tag, @LDAP::fix($dn))."<br>";
1017           flush();
1018         }
1019         $nattrs= array("gosaUnitTag" => $tag);
1020         $nattrs['objectClass']= array();
1021         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
1022           $oc= $attrs['objectClass'][$i];
1023           if ($oc != "gosaAdministrativeUnitTag"){
1024             $nattrs['objectClass'][]= $oc;
1025           }
1026         }
1027         $nattrs['objectClass'][]= "gosaAdministrativeUnitTag";
1028         $ldap->cd($dn);
1029         $ldap->modify($nattrs);
1030         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
1031       } else {
1032         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not tagging ($tag) $dn - seems to have moved away", "Tagging");
1033       }
1035     } else {
1036       /* Remove objectclass and attribute */
1037       $ldap= $this->config->get_ldap_link();
1038       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
1039       $attrs= $ldap->fetch();
1040       if (isset($attrs['objectClass']) && !in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass'])){
1041         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "$dn is not tagged", "Tagging");
1042         return;
1043       }
1044       if (count($attrs)){
1045         if ($show){
1046           echo sprintf(_("Removing tag from object '%s'"), @LDAP::fix($dn))."<br>";
1047           flush();
1048         }
1049         $nattrs= array("gosaUnitTag" => array());
1050         $nattrs['objectClass']= array();
1051         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
1052           $oc= $attrs['objectClass'][$i];
1053           if ($oc != "gosaAdministrativeUnitTag"){
1054             $nattrs['objectClass'][]= $oc;
1055           }
1056         }
1057         $ldap->cd($dn);
1058         $ldap->modify($nattrs);
1059         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
1060       } else {
1061         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not removing tag ($tag) $dn - seems to have moved away", "Tagging");
1062       }
1063     }
1065   }
1068   /* Add possibility to stop remove process */
1069   function allow_remove()
1070   {
1071     $reason= "";
1072     return $reason;
1073   }
1076   /* Create a snapshot of the current object */
1077   function create_snapshot($type= "snapshot", $description= array())
1078   {
1080     /* Check if snapshot functionality is enabled */
1081     if(!$this->snapshotEnabled()){
1082       return;
1083     }
1085     /* Get configuration from gosa.conf */
1086     $tmp = $this->config->current;
1088     /* Create lokal ldap connection */
1089     $ldap= $this->config->get_ldap_link();
1090     $ldap->cd($this->config->current['BASE']);
1092     /* check if there are special server configurations for snapshots */
1093     if(!isset($tmp['SNAPSHOT_SERVER'])){
1095       /* Source and destination server are both the same, just copy source to dest obj */
1096       $ldap_to      = $ldap;
1097       $snapldapbase = $this->config->current['BASE'];
1099     }else{
1100       $server         = $tmp['SNAPSHOT_SERVER'];
1101       $user           = $tmp['SNAPSHOT_USER'];
1102       $password       = $tmp['SNAPSHOT_PASSWORD'];
1103       $snapldapbase   = $tmp['SNAPSHOT_BASE'];
1105       $ldap_to        = new LDAP($user,$password, $server);
1106       $ldap_to -> cd($snapldapbase);
1107       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$snapldapbase));
1108     }
1110     /* check if the dn exists */ 
1111     if ($ldap->dn_exists($this->dn)){
1113       /* Extract seconds & mysecs, they are used as entry index */
1114       list($usec, $sec)= explode(" ", microtime());
1116       /* Collect some infos */
1117       $base           = $this->config->current['BASE'];
1118       $snap_base      = $tmp['SNAPSHOT_BASE'];
1119       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1120       $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1122       /* Create object */
1123 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1124       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1125       $newName          = preg_replace("/\./", "", $sec."-".$usec);
1126       $target= array();
1127       $target['objectClass']            = array("top", "gosaSnapshotObject");
1128       $target['gosaSnapshotData']       = gzcompress($data, 6);
1129       $target['gosaSnapshotType']       = $type;
1130       $target['gosaSnapshotDN']         = $this->dn;
1131       $target['description']            = $description;
1132       $target['gosaSnapshotTimestamp']  = $newName;
1134       /* Insert the new snapshot 
1135          But we have to check first, if the given gosaSnapshotTimestamp
1136          is already used, in this case we should increment this value till there is 
1137          an unused value. */ 
1138       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1139       $ldap_to->cat($new_dn);
1140       while($ldap_to->count()){
1141         $ldap_to->cat($new_dn);
1142         $newName = preg_replace("/\./", "", $sec."-".($usec++));
1143         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1144         $target['gosaSnapshotTimestamp']  = $newName;
1145       } 
1147       /* Inset this new snapshot */
1148       $ldap_to->cd($snapldapbase);
1149       $ldap_to->create_missing_trees($new_base);
1150       $ldap_to->cd($new_dn);
1151       $ldap_to->add($target);
1153       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1154       show_ldap_error($ldap_to->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1155     }
1156   }
1158   function remove_snapshot($dn)
1159   {
1160     $ui       = get_userinfo();
1161     $old_dn   = $this->dn; 
1162     $this->dn = $dn;
1163     $ldap = $this->config->get_ldap_link();
1164     $ldap->cd($this->config->current['BASE']);
1165     $ldap->rmdir_recursive($dn);
1166     $this->dn = $old_dn;
1167   }
1170   /* returns true if snapshots are enabled, and false if it is disalbed
1171      There will also be some errors psoted, if the configuration failed */
1172   function snapshotEnabled()
1173   {
1174     $tmp = $this->config->current;
1175     if(isset($tmp['ENABLE_SNAPSHOT'])){
1176       if (preg_match("/^true$/i", $tmp['ENABLE_SNAPSHOT']) || preg_match("/yes/i", $tmp['ENABLE_SNAPSHOT'])){
1178         /* Check if the snapshot_base is defined */
1179         if(!isset($tmp['SNAPSHOT_BASE'])){
1180           print_red(sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not configured in your gosa.conf."),"SNAPSHOT_BASE"));
1181           return(FALSE);
1182         }
1184         /* check if there are special server configurations for snapshots */
1185         if(isset($tmp['SNAPSHOT_SERVER'])){
1187           /* check if all required vars are available to create a new ldap connection */
1188           $missing = "";
1189           foreach(array("SNAPSHOT_SERVER","SNAPSHOT_USER","SNAPSHOT_PASSWORD","SNAPSHOT_BASE") as $var){
1190             if(!isset($tmp[$var])){
1191               $missing .= $var." ";
1192               print_red(sprintf(_("The snapshot functionality is enabled, but the required variable(s) '%s' is not configured in your gosa.conf."),$missing));
1193               return(FALSE);
1194             }
1195           }
1196         }
1197         return(TRUE);
1198       }
1199     }
1200     return(FALSE);
1201   }
1204   /* Return available snapshots for the given base 
1205    */
1206   function Available_SnapsShots($dn,$raw = false)
1207   {
1208     if(!$this->snapshotEnabled()) return(array());
1210     /* Create an additional ldap object which
1211        points to our ldap snapshot server */
1212     $ldap= $this->config->get_ldap_link();
1213     $ldap->cd($this->config->current['BASE']);
1214     $cfg= &$this->config->current;
1216     /* check if there are special server configurations for snapshots */
1217     if(isset($cfg['SNAPSHOT_SERVER'])){
1218       $server       = $cfg['SNAPSHOT_SERVER'];
1219       $user         = $cfg['SNAPSHOT_USER'];
1220       $password     = $cfg['SNAPSHOT_PASSWORD'];
1221       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1222       $ldap_to      = new LDAP($user,$password, $server);
1223       $ldap_to -> cd ($snapldapbase);
1224       show_ldap_error($ldap->get_error(), sprintf(_("Method get available snapshots with dn '%s' failed."),$this->dn));
1225     }else{
1226       $ldap_to    = $ldap;
1227     }
1229     /* Prepare bases and some other infos */
1230     $base           = $this->config->current['BASE'];
1231     $snap_base      = $cfg['SNAPSHOT_BASE'];
1232     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1233     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1234     $tmp            = array(); 
1236     /* Fetch all objects with  gosaSnapshotDN=$dn */
1237     $ldap_to->cd($new_base);
1238     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1239         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1241     /* Put results into a list and add description if missing */
1242     while($entry = $ldap_to->fetch()){ 
1243       if(!isset($entry['description'][0])){
1244         $entry['description'][0]  = "";
1245       }
1246       $tmp[] = $entry; 
1247     }
1249     /* Return the raw array, or format the result */
1250     if($raw){
1251       return($tmp);
1252     }else{  
1253       $tmp2 = array();
1254       foreach($tmp as $entry){
1255         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1256       }
1257     }
1258     return($tmp2);
1259   }
1262   function getAllDeletedSnapshots($base_of_object,$raw = false)
1263   {
1264     if(!$this->snapshotEnabled()) return(array());
1266     /* Create an additional ldap object which
1267        points to our ldap snapshot server */
1268     $ldap= $this->config->get_ldap_link();
1269     $ldap->cd($this->config->current['BASE']);
1270     $cfg= &$this->config->current;
1272     /* check if there are special server configurations for snapshots */
1273     if(isset($cfg['SNAPSHOT_SERVER'])){
1274       $server       = $cfg['SNAPSHOT_SERVER'];
1275       $user         = $cfg['SNAPSHOT_USER'];
1276       $password     = $cfg['SNAPSHOT_PASSWORD'];
1277       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1278       $ldap_to      = new LDAP($user,$password, $server);
1279       $ldap_to->cd ($snapldapbase);
1280       show_ldap_error($ldap->get_error(), sprintf(_("Method get deleted snapshots with dn '%s' failed."),$this->dn));
1281     }else{
1282       $ldap_to    = $ldap;
1283     }
1285     /* Prepare bases */ 
1286     $base           = $this->config->current['BASE'];
1287     $snap_base      = $cfg['SNAPSHOT_BASE'];
1288     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1290     /* Fetch all objects and check if they do not exist anymore */
1291     $ui = get_userinfo();
1292     $tmp = array();
1293     $ldap_to->cd($new_base);
1294     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1295     while($entry = $ldap_to->fetch()){
1297       $chk =  str_replace($new_base,"",$entry['dn']);
1298       if(preg_match("/,ou=/",$chk)) continue;
1300       if(!isset($entry['description'][0])){
1301         $entry['description'][0]  = "";
1302       }
1303       $tmp[] = $entry; 
1304     }
1306     /* Check if entry still exists */
1307     foreach($tmp as $key => $entry){
1308       $ldap->cat($entry['gosaSnapshotDN'][0]);
1309       if($ldap->count()){
1310         unset($tmp[$key]);
1311       }
1312     }
1314     /* Format result as requested */
1315     if($raw) {
1316       return($tmp);
1317     }else{
1318       $tmp2 = array();
1319       foreach($tmp as $key => $entry){
1320         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1321       }
1322     }
1323     return($tmp2);
1324   } 
1327   /* Restore selected snapshot */
1328   function restore_snapshot($dn)
1329   {
1330     if(!$this->snapshotEnabled()) return(array());
1332     $ldap= $this->config->get_ldap_link();
1333     $ldap->cd($this->config->current['BASE']);
1334     $cfg= &$this->config->current;
1336     /* check if there are special server configurations for snapshots */
1337     if(isset($cfg['SNAPSHOT_SERVER'])){
1338       $server       = $cfg['SNAPSHOT_SERVER'];
1339       $user         = $cfg['SNAPSHOT_USER'];
1340       $password     = $cfg['SNAPSHOT_PASSWORD'];
1341       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1342       $ldap_to      = new LDAP($user,$password, $server);
1343       $ldap_to->cd ($snapldapbase);
1344       show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$snapldapbase));
1345     }else{
1346       $ldap_to    = $ldap;
1347     }
1349     /* Get the snapshot */ 
1350     $ldap_to->cat($dn);
1351     $restoreObject = $ldap_to->fetch();
1353     /* Prepare import string */
1354     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1356     /* Import the given data */
1357     $ldap->import_complete_ldif($data,$err,false,false);
1358     show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$dn));
1359   }
1362   function showSnapshotDialog($base,$baseSuffixe)
1363   {
1364     $once = true;
1365     foreach($_POST as $name => $value){
1367       /* Create a new snapshot, display a dialog */
1368       if(preg_match("/^CreateSnapShotDialog_/",$name) && $once){
1369         $once = false;
1370         $entry = preg_replace("/^CreateSnapShotDialog_/","",$name);
1371         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1372         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1373       }
1375       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1376       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1377         $once = false;
1378         $entry = preg_replace("/^RestoreSnapShotDialog_/","",$name);
1379         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1380         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1381         $this->snapDialog->display_restore_dialog = true;
1382       }
1384       /* Restore one of the already deleted objects */
1385       if(preg_match("/^RestoreDeletedSnapShot_/",$name) && $once){
1386         $once = false;
1387         $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1388         $this->snapDialog->set_snapshot_bases($baseSuffixe);
1389         $this->snapDialog->display_restore_dialog      = true;
1390         $this->snapDialog->display_all_removed_objects  = true;
1391       }
1393       /* Restore selected snapshot */
1394       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1395         $once = false;
1396         $entry = preg_replace("/^RestoreSnapShot_/","",$name);
1397         $entry = base64_decode(trim(preg_replace("/_[xy]$/","",$entry)));
1398         if(!empty($entry)){
1399           $this->restore_snapshot($entry);
1400           $this->snapDialog = NULL;
1401         }
1402       }
1403     }
1405     /* Create a new snapshot requested, check
1406        the given attributes and create the snapshot*/
1407     if(isset($_POST['CreateSnapshot'])){
1408       $this->snapDialog->save_object();
1409       $msgs = $this->snapDialog->check();
1410       if(count($msgs)){
1411         foreach($msgs as $msg){
1412           print_red($msg);
1413         }
1414       }else{
1415         $this->dn =  $this->snapDialog->dn;
1416         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1417         $this->snapDialog = NULL;
1418       }
1419     }
1421     /* Restore is requested, restore the object with the posted dn .*/
1422     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1423     }
1425     if(isset($_POST['CancelSnapshot'])){
1426       $this->snapDialog = NULL;
1427     }
1429     if($this->snapDialog){
1430       $this->snapDialog->save_object();
1431       return($this->snapDialog->execute());
1432     }
1433   }
1436   function plInfo()
1437   {
1438     return array();
1439   }
1442   function set_acl_base($base)
1443   {
1444     $this->acl_base= $base;
1445   }
1448   function set_acl_category($category)
1449   {
1450     $this->acl_category= "$category/";
1451   }
1454   function acl_is_writeable($attribute,$skip_write = FALSE)
1455   {
1456     $ui= get_userinfo();
1457     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1458   }
1461   function acl_is_readable($attribute)
1462   {
1463     $ui= get_userinfo();
1464     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1465   }
1468   function acl_is_createable()
1469   {
1470     $ui= get_userinfo();
1471     return preg_match('/c/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1472   }
1475   function acl_is_removeable()
1476   {
1477     $ui= get_userinfo();
1478     return preg_match('/d/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1479   }
1482   function acl_is_moveable()
1483   {
1484     $ui= get_userinfo();
1485     return preg_match('/m/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1486   }
1489   function acl_have_any_permissions()
1490   {
1491   }
1494   function getacl($attribute,$skip_write= FALSE)
1495   {
1496     $ui= get_userinfo();
1497     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1498   }
1500   /* Get all allowed bases to move an object to or to create a new object.
1501      Idepartments also contains all base departments which lead to the allowed bases */
1502   function get_allowed_bases($category = "")
1503   {
1504     $ui = get_userinfo();
1505     $deps = array();
1507     /* Set category */ 
1508     if(empty($category)){
1509       $category = $this->acl_category.get_class($this);
1510     }
1512     /* Is this a new object ? Or just an edited existing object */
1513     if(!$this->initially_was_account && $this->is_account){
1514       $new = true;
1515     }else{
1516       $new = false;
1517     }
1519     $cat_bases = $ui->get_module_departments(preg_replace("/\/.*$/","",$category));
1520     foreach($this->config->idepartments as $dn => $name){
1521       
1522       if(!in_array_ics($dn,$cat_bases)){
1523         continue;
1524       }
1525       
1526       $acl = $ui->get_permissions($dn,$category);
1527       if($new && preg_match("/c/",$acl)){
1528         $deps[$dn] = $name;
1529       }elseif(!$new && preg_match("/m/",$acl)){
1530         $deps[$dn] = $name;
1531       }
1532     }
1534     /* Add current base */      
1535     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1536       $deps[$this->base] = $this->config->idepartments[$this->base];
1537     }else{
1538       echo "No default base found. ".$this->base."<br> ";
1539     }
1541     return($deps);
1542   }
1544   /* This function modifies object acls too, if an object is moved.
1545    *  $old_dn   specifies the actually used dn
1546    *  $new_dn   specifies the destiantion dn
1547    */
1548   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1549   {
1550     /* Check if old_dn is empty. This should never happen */
1551     if(empty($old_dn) || empty($new_dn)){
1552       trigger_error("Failed to check acl dependencies, wrong dn given.");
1553       return;
1554     }
1556     /* Update userinfo if necessary */
1557     if($_SESSION['ui']->dn == $old_dn){
1558       $_SESSION['ui']->dn = $new_dn;
1559       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current user dn from '".$old_dn."' to '".$new_dn."'");
1560     }
1562     /* Object was moved, ensure that all acls will be moved too */
1563     if($new_dn != $old_dn && $old_dn != "new"){
1565       /* get_ldap configuration */
1566       $update = array();
1567       $ldap = $this->config->get_ldap_link();
1568       $ldap->cd ($this->config->current['BASE']);
1569       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*))",array("cn","gosaAclEntry"));
1570       while($attrs = $ldap->fetch()){
1572         $acls = array();
1574         /* Walk through acls */
1575         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1577           /* Reset vars */
1578           $found = false;
1580           /* Get Acl parts */
1581           $acl_parts = split(":",$attrs['gosaAclEntry'][$i]);
1583           /* Get every single member for this acl */  
1584           $members = array();  
1585           if(preg_match("/,/",$acl_parts[2])){
1586             $members = split(",",$acl_parts[2]);
1587           }else{
1588             $members = array($acl_parts[2]);
1589           } 
1590       
1591           /* Check if member match current dn */
1592           foreach($members as $key => $member){
1593             $member = base64_decode($member);
1594             if($member == $old_dn){
1595               $found = true;
1596               $members[$key] = base64_encode($new_dn);
1597             }
1598           } 
1599          
1600           /* Create new member string */ 
1601           $new_members = "";
1602           foreach($members as $member){
1603             $new_members .= $member.",";
1604           }
1605           $new_members = preg_replace("/,$/","",$new_members);
1606           $acl_parts[2] = $new_members;
1607         
1608           /* Reconstruckt acl entry */
1609           $acl_str  ="";
1610           foreach($acl_parts as $t){
1611            $acl_str .= $t.":";
1612           }
1613           $acl_str = preg_replace("/:$/","",$acl_str);
1614        }
1616        /* Acls for this object must be adjusted */
1617        if($found){
1619           if($output_changes){
1620             echo "<font color='green'>".
1621                   _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1622                   $old_dn.
1623                   "</b><br>&nbsp;-"._("to")."&nbsp;<b>".
1624                   $new_dn.
1625                   "</b></font><br>";
1626           }
1627           $update[$attrs['dn']] =array();
1628           foreach($acls as $acl){
1629             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1630           }
1631         }
1632       }
1634       /* Write updated acls */
1635       foreach($update as $dn => $attrs){
1636         $ldap->cd($dn);
1637         $ldap->modify($attrs);
1638       }
1639     }
1640   }
1642 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1643 ?>