Code

bb7d7354c19c2d5d4cb24ff415cccf6e5060ae12
[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       $found= TRUE;
179       foreach ($this->objectclasses as $obj){
180         if (preg_match('/top/i', $obj)){
181           continue;
182         }
183         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
184           $found= FALSE;
185           break;
186         }
187       }
188       if ($found){
189         $this->is_account= TRUE;
190         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
191             "found", "Object check");
192       }
194       /* Prepare saved attributes */
195       $this->saved_attributes= $this->attrs;
196       foreach ($this->saved_attributes as $index => $value){
197         if (preg_match('/^[0-9]+$/', $index)){
198           unset($this->saved_attributes[$index]);
199           continue;
200         }
201         if (!in_array($index, $this->attributes) && $index != "objectClass"){
202           unset($this->saved_attributes[$index]);
203           continue;
204         }
205         if ($this->saved_attributes[$index]["count"] == 1){
206           $tmp= $this->saved_attributes[$index][0];
207           unset($this->saved_attributes[$index]);
208           $this->saved_attributes[$index]= $tmp;
209           continue;
210         }
212         unset($this->saved_attributes["$index"]["count"]);
213       }
214     }
216     /* Save initial account state */
217     $this->initially_was_account= $this->is_account;
218   }
220   /*! \brief execute plugin
222     Generates the html output for this node
223    */
224   function execute()
225   {
226     /* This one is empty currently. Fabian - please fill in the docu code */
227     $_SESSION['current_class_for_help'] = get_class($this);
229     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
230     $_SESSION['LOCK_VARS_TO_USE'] = $_SESSION['LOCK_VARS_USED'] =array();
231   }
233   /*! \brief execute plugin
234      Removes object from parent
235    */
236   function remove_from_parent()
237   {
238     /* include global link_info */
239     $ldap= $this->config->get_ldap_link();
241     /* Get current objectClasses in order to add the required ones */
242     $ldap->cat($this->dn);
243     $tmp= $ldap->fetch ();
244     $oc= array();
245     if (isset($tmp['objectClass'])){
246       $oc= $tmp['objectClass'];
247       unset($oc['count']);
248     }
250     /* Remove objectClasses from entry */
251     $ldap->cd($this->dn);
252     $this->attrs= array();
253     $this->attrs['objectClass']= array_remove_entries($this->objectclasses,$oc);
255     /* Unset attributes from entry */
256     foreach ($this->attributes as $val){
257       $this->attrs["$val"]= array();
258     }
260     /* Unset account info */
261     $this->is_account= FALSE;
263     /* Do not write in plugin base class, this must be done by
264        children, since there are normally additional attribs,
265        lists, etc. */
266     /*
267        $ldap->modify($this->attrs);
268      */
269   }
272   /* Save data to object */
273   function save_object()
274   {
275     /* Save values to object */
276     foreach ($this->attributes as $val){
277       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
278         /* Check for modifications */
279         if (get_magic_quotes_gpc()) {
280           $data= stripcslashes($_POST["$val"]);
281         } else {
282           $data= $this->$val = $_POST["$val"];
283         }
284         if ($this->$val != $data){
285           $this->is_modified= TRUE;
286         }
287     
288         /* Okay, how can I explain this fix ... 
289          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
290          * So IE posts these 'unselectable' option, with value = chr(194) 
291          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
292          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
293          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
294          */
295         if(isset($data[0]) && $data[0] == chr(194)) {
296           $data = "";  
297         }
298         $this->$val= $data;
299         //echo "<font color='blue'>".$val."</font><br>";
300       }else{
301         //echo "<font color='red'>".$val."</font><br>";
302       }
303     }
304   }
307   /* Save data to LDAP, depending on is_account we save or delete */
308   function save()
309   {
310     /* include global link_info */
311     $ldap= $this->config->get_ldap_link();
313     /* Start with empty array */
314     $this->attrs= array();
316     /* Get current objectClasses in order to add the required ones */
317     $ldap->cat($this->dn);
318     
319     $tmp= $ldap->fetch ();
321     $oc= array();
322     if (isset($tmp['objectClass'])){
323       $oc= $tmp["objectClass"];
324       $this->is_new= FALSE;
325       unset($oc['count']);
326     } else {
327       $this->is_new= TRUE;
328     }
330     /* Load (minimum) attributes, add missing ones */
331     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
333     /* Copy standard attributes */
334     foreach ($this->attributes as $val){
335       if ($this->$val != ""){
336         $this->attrs["$val"]= $this->$val;
337       } elseif (!$this->is_new) {
338         $this->attrs["$val"]= array();
339       }
340     }
342   }
345   function cleanup()
346   {
347     foreach ($this->attrs as $index => $value){
349       /* Convert arrays with one element to non arrays, if the saved
350          attributes are no array, too */
351       if (is_array($this->attrs[$index]) && 
352           count ($this->attrs[$index]) == 1 &&
353           isset($this->saved_attributes[$index]) &&
354           !is_array($this->saved_attributes[$index])){
355           
356         $tmp= $this->attrs[$index][0];
357         $this->attrs[$index]= $tmp;
358       }
360       /* Remove emtpy arrays if they do not differ */
361       if (is_array($this->attrs[$index]) &&
362           count($this->attrs[$index]) == 0 &&
363           !isset($this->saved_attributes[$index])){
364           
365         unset ($this->attrs[$index]);
366         continue;
367       }
369       /* Remove single attributes that do not differ */
370       if (!is_array($this->attrs[$index]) &&
371           isset($this->saved_attributes[$index]) &&
372           !is_array($this->saved_attributes[$index]) &&
373           $this->attrs[$index] == $this->saved_attributes[$index]){
375         unset ($this->attrs[$index]);
376         continue;
377       }
379       /* Remove arrays that do not differ */
380       if (is_array($this->attrs[$index]) && 
381           isset($this->saved_attributes[$index]) &&
382           is_array($this->saved_attributes[$index])){
383           
384         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
385           unset ($this->attrs[$index]);
386           continue;
387         }
388       }
389     }
391     /* Update saved attributes and ensure that next cleanups will be successful too */
392     foreach($this->attrs as $name => $value){
393       $this->saved_attributes[$name] = $value;
394     }
395   }
397   /* Check formular input */
398   function check()
399   {
400     $message= array();
402     /* Skip if we've no config object */
403     if (!isset($this->config)){
404       return $message;
405     }
407     /* Find hooks entries for this class */
408     $command= search_config($this->config->data['MENU'], get_class($this), "CHECK");
409     if ($command == "" && isset($this->config->data['TABS'])){
410       $command= search_config($this->config->data['TABS'], get_class($this), "CHECK");
411     }
413     if ($command != ""){
415       if (!check_command($command)){
416         $message[]= sprintf(_("Command '%s', specified as CHECK hook for plugin '%s' doesn't seem to exist."), $command,
417                             get_class($this));
418       } else {
420         /* Generate "ldif" for check hook */
421         $ldif= "dn: $this->dn\n";
422         
423         /* ... objectClasses */
424         foreach ($this->objectclasses as $oc){
425           $ldif.= "objectClass: $oc\n";
426         }
427         
428         /* ... attributes */
429         foreach ($this->attributes as $attr){
430           if ($this->$attr == ""){
431             continue;
432           }
433           if (is_array($this->$attr)){
434             foreach ($this->$attr as $val){
435               $ldif.= "$attr: $val\n";
436             }
437           } else {
438               $ldif.= "$attr: ".$this->$attr."\n";
439           }
440         }
442         /* Append empty line */
443         $ldif.= "\n";
445         /* Feed "ldif" into hook and retrieve result*/
446         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
447         $fh= proc_open($command, $descriptorspec, $pipes);
448         if (is_resource($fh)) {
449           fwrite ($pipes[0], $ldif);
450           fclose($pipes[0]);
451           
452           $result= stream_get_contents($pipes[1]);
453           if ($result != ""){
454             $message[]= $result;
455           }
456           
457           fclose($pipes[1]);
458           fclose($pipes[2]);
459           proc_close($fh);
460         }
461       }
463     }
465     return ($message);
466   }
468   /* Adapt from template, using 'dn' */
469   function adapt_from_template($dn)
470   {
471     /* Include global link_info */
472     $ldap= $this->config->get_ldap_link();
474     /* Load requested 'dn' to 'attrs' */
475     $ldap->cat ($dn);
476     $this->attrs= $ldap->fetch();
478     /* Walk through attributes */
479     foreach ($this->attributes as $val){
481       if (isset($this->attrs["$val"][0])){
483         /* If attribute is set, replace dynamic parts: 
484            %sn, %givenName and %uid. Fill these in our local variables. */
485         $value= $this->attrs["$val"][0];
487         foreach (array("sn", "givenName", "uid") as $repl){
488           if (preg_match("/%$repl/i", $value)){
489             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
490           }
491         }
492         $this->$val= $value;
493       }
494     }
496     /* Is Account? */
497     $found= TRUE;
498     foreach ($this->objectclasses as $obj){
499       if (preg_match('/top/i', $obj)){
500         continue;
501       }
502       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
503         $found= FALSE;
504         break;
505       }
506     }
507     if ($found){
508       $this->is_account= TRUE;
509     }
510   }
512   /* Indicate whether a password change is needed or not */
513   function password_change_needed()
514   {
515     return FALSE;
516   }
519   /* Show header message for tab dialogs */
520   function show_enable_header($button_text, $text, $disabled= FALSE)
521   {
522     if (($disabled == TRUE) || (!$this->acl_is_createable())){
523       $state= "disabled";
524     } else {
525       $state= "";
526     }
527     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
528     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
529       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
531     return($display);
532   }
535   /* Show header message for tab dialogs */
536   function show_disable_header($button_text, $text, $disabled= FALSE)
537   {
538     if (($disabled == TRUE) || !$this->acl_is_removeable()){
539       $state= "disabled";
540     } else {
541       $state= "";
542     }
543     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
544     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
545       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
547     return($display);
548   }
551   /* Show header message for tab dialogs */
552   function show_header($button_text, $text, $disabled= FALSE)
553   {
554     echo "FIXME: show_header should be replaced by show_disable_header and show_enable_header<br>";
555     if ($disabled == TRUE){
556       $state= "disabled";
557     } else {
558       $state= "";
559     }
560     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
561     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
562       ($this->acl_is_createable()?'':'disabled')." ".$state.
563       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
565     return($display);
566   }
569   function postcreate($add_attrs= array())
570   {
571     /* Find postcreate entries for this class */
572     $command= search_config($this->config->data['MENU'], get_class($this), "POSTCREATE");
573     if ($command == "" && isset($this->config->data['TABS'])){
574       $command= search_config($this->config->data['TABS'], get_class($this), "POSTCREATE");
575     }
577     if ($command != ""){
579       /* Additional attributes */
580       foreach ($add_attrs as $name => $value){
581         $command= preg_replace("/%$name/", $value, $command);
582       }
584       /* Walk through attribute list */
585       foreach ($this->attributes as $attr){
586         if (!is_array($this->$attr)){
587           $command= preg_replace("/%$attr/", $this->$attr, $command);
588         }
589       }
590       $command= preg_replace("/%dn/", $this->dn, $command);
592       if (check_command($command)){
593         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
594             $command, "Execute");
596         exec($command);
597       } else {
598         $message= sprintf(_("Command '%s', specified as POSTCREATE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
599         print_red ($message);
600       }
601     }
602   }
604   function postmodify($add_attrs= array())
605   {
606     /* Find postcreate entries for this class */
607     $command= search_config($this->config->data['MENU'], get_class($this), "POSTMODIFY");
608     if ($command == "" && isset($this->config->data['TABS'])){
609       $command= search_config($this->config->data['TABS'], get_class($this), "POSTMODIFY");
610     }
612     if ($command != ""){
614       /* Additional attributes */
615       foreach ($add_attrs as $name => $value){
616         $command= preg_replace("/%$name/", $value, $command);
617       }
619       /* Walk through attribute list */
620       foreach ($this->attributes as $attr){
621         if (!is_array($this->$attr)){
622           $command= preg_replace("/%$attr/", $this->$attr, $command);
623         }
624       }
625       $command= preg_replace("/%dn/", $this->dn, $command);
627       if (check_command($command)){
628         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
629             $command, "Execute");
631         exec($command);
632       } else {
633         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, get_class($this));
634         print_red ($message);
635       }
636     }
637   }
639   function postremove($add_attrs= array())
640   {
641     /* Find postremove entries for this class */
642     $command= search_config($this->config->data['MENU'], get_class($this), "POSTREMOVE");
643     if ($command == "" && isset($this->config->data['TABS'])){
644       $command= search_config($this->config->data['TABS'], get_class($this), "POSTREMOVE");
645     }
647     if ($command != ""){
649       /* Additional attributes */
650       foreach ($add_attrs as $name => $value){
651         $command= preg_replace("/%$name/", $value, $command);
652       }
654       /* Walk through attribute list */
655       foreach ($this->attributes as $attr){
656         if (!is_array($this->$attr)){
657           $command= preg_replace("/%$attr/", $this->$attr, $command);
658         }
659       }
660       $command= preg_replace("/%dn/", $this->dn, $command);
662       /* Additional attributes */
663       foreach ($add_attrs as $name => $value){
664         $command= preg_replace("/%$name/", $value, $command);
665       }
667       if (check_command($command)){
668         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
669             $command, "Execute");
671         exec($command);
672       } else {
673         $message= sprintf(_("Command '%s', specified as POSTREMOVE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
674         print_red ($message);
675       }
676     }
677   }
679   /* Create unique DN */
680   function create_unique_dn($attribute, $base)
681   {
682     $ldap= $this->config->get_ldap_link();
683     $base= preg_replace("/^,*/", "", $base);
685     /* Try to use plain entry first */
686     $dn= "$attribute=".$this->$attribute.",$base";
687     $ldap->cat ($dn, array('dn'));
688     if (!$ldap->fetch()){
689       return ($dn);
690     }
692     /* Look for additional attributes */
693     foreach ($this->attributes as $attr){
694       if ($attr == $attribute || $this->$attr == ""){
695         continue;
696       }
698       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
699       $ldap->cat ($dn, array('dn'));
700       if (!$ldap->fetch()){
701         return ($dn);
702       }
703     }
705     /* None found */
706     return ("none");
707   }
709   function rebind($ldap, $referral)
710   {
711     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
712     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
713       $this->error = "Success";
714       $this->hascon=true;
715       $this->reconnect= true;
716       return (0);
717     } else {
718       $this->error = "Could not bind to " . $credentials['ADMIN'];
719       return NULL;
720     }
721   }
723   /* This is a workaround function. */
724   function copy($src_dn, $dst_dn)
725   {
726     /* Rename dn in possible object groups */
727     $ldap= $this->config->get_ldap_link();
728     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::fix($src_dn).'))',
729         array('cn'));
730     while ($attrs= $ldap->fetch()){
731       $og= new ogroup($this->config, $ldap->getDN());
732       unset($og->member[$src_dn]);
733       $og->member[$dst_dn]= $dst_dn;
734       $og->save ();
735     }
737     $ldap->cat($dst_dn);
738     $attrs= $ldap->fetch();
739     if (count($attrs)){
740       trigger_error("Trying to overwrite ".@LDAP::fix($dst_dn).", which already exists.",
741           E_USER_WARNING);
742       return (FALSE);
743     }
745     $ldap->cat($src_dn);
746     $attrs= $ldap->fetch();
747     if (!count($attrs)){
748       trigger_error("Trying to move ".@LDAP::fix($src_dn).", which does not seem to exist.",
749           E_USER_WARNING);
750       return (FALSE);
751     }
753     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
754     $ds= ldap_connect($this->config->current['SERVER']);
755     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
756     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
757       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
758     }
760     $r=ldap_bind($ds,$this->config->current['ADMIN'], $this->config->current['PASSWORD']);
761     $sr=ldap_read($ds, @LDAP::fix($src_dn), "objectClass=*");
763     /* Fill data from LDAP */
764     $new= array();
765     if ($sr) {
766       $ei=ldap_first_entry($ds, $sr);
767       if ($ei) {
768         foreach($attrs as $attr => $val){
769           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
770             for ($i= 0; $i<$info['count']; $i++){
771               if ($info['count'] == 1){
772                 $new[$attr]= $info[$i];
773               } else {
774                 $new[$attr][]= $info[$i];
775               }
776             }
777           }
778         }
779       }
780     }
782     /* close conncetion */
783     ldap_unbind($ds);
785     /* Adapt naming attribute */
786     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
787     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
788     $new[$dst_name]= @LDAP::fix($dst_val);
790     /* Check if this is a department.
791      * If it is a dep. && there is a , override in his ou 
792      *  change \2C to , again, else this entry can't be saved ...
793      */
794     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
795       $new['ou'] = preg_replace("/\\\\,/",",",$new['ou']);
796     }
798     /* Save copy */
799     $ldap->connect();
800     $ldap->cd($this->config->current['BASE']);
801     
802     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
804     /* FAIvariable=.../..., cn=.. 
805         could not be saved, because the attribute FAIvariable was different to 
806         the dn FAIvariable=..., cn=... */
807     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
808       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
809     }
810     $ldap->cd($dst_dn);
811     $ldap->add($new);
813     if ($ldap->error != "Success"){
814       trigger_error("Trying to save $dst_dn failed.",
815           E_USER_WARNING);
816       return(FALSE);
817     }
819     return (TRUE);
820   }
823   function move($src_dn, $dst_dn)
824   {
825     /* Copy source to destination */
826     if (!$this->copy($src_dn, $dst_dn)){
827       return (FALSE);
828     }
830     /* Delete source */
831     $ldap= $this->config->get_ldap_link();
832     $ldap->rmdir($src_dn);
833     if ($ldap->error != "Success"){
834       trigger_error("Trying to delete $src_dn failed.",
835           E_USER_WARNING);
836       return (FALSE);
837     }
839     return (TRUE);
840   }
843   /* Move/Rename complete trees */
844   function recursive_move($src_dn, $dst_dn)
845   {
846     /* Check if the destination entry exists */
847     $ldap= $this->config->get_ldap_link();
849     /* Check if destination exists - abort */
850     $ldap->cat($dst_dn, array('dn'));
851     if ($ldap->fetch()){
852       trigger_error("recursive_move $dst_dn already exists.",
853           E_USER_WARNING);
854       return (FALSE);
855     }
857     /* Perform a search for all objects to be moved */
858     $objects= array();
859     $ldap->cd($src_dn);
860     $ldap->search("(objectClass=*)", array("dn"));
861     while($attrs= $ldap->fetch()){
862       $dn= $attrs['dn'];
863       $objects[$dn]= strlen($dn);
864     }
866     /* Sort objects by indent level */
867     asort($objects);
868     reset($objects);
870     /* Copy objects from small to big indent levels by replacing src_dn by dst_dn */
871     foreach ($objects as $object => $len){
872       $src= $object;
873       $dst= preg_replace("/$src_dn$/", "$dst_dn", $object);
874       if (!$this->copy($src, $dst)){
875         return (FALSE);
876       }
877     }
879     /* Remove src_dn */
880     $ldap->cd($src_dn);
881     $ldap->recursive_remove();
882     return (TRUE);
883   }
886   function handle_post_events($mode, $add_attrs= array())
887   {
888     switch ($mode){
889       case "add":
890         $this->postcreate($add_attrs);
891       break;
893       case "modify":
894         $this->postmodify($add_attrs);
895       break;
897       case "remove":
898         $this->postremove($add_attrs);
899       break;
900     }
901   }
904   function saveCopyDialog(){
905   }
908   function getCopyDialog(){
909     return(array("string"=>"","status"=>""));
910   }
913   function PrepareForCopyPaste($source)
914   {
915     $todo = $this->attributes;
916     if(isset($this->CopyPasteVars)){
917       $todo = array_merge($todo,$this->CopyPasteVars);
918     }
920     if(count($this->objectclasses)){
921       $this->is_account = TRUE;
922       foreach($this->objectclasses as $class){
923         if(!in_array($class,$source['objectClass'])){
924           $this->is_account = FALSE;
925         }
926       }
927     }
929     foreach($todo as $var){
930       if (isset($source[$var])){
931         if(isset($source[$var]['count'])){
932           if($source[$var]['count'] > 1){
933             $this->$var = array();
934             $tmp = array();
935             for($i = 0 ; $i < $source[$var]['count']; $i++){
936               $tmp = $source[$var][$i];
937             }
938             $this->$var = $tmp;
939 #            echo $var."=".$tmp."<br>";
940           }else{
941             $this->$var = $source[$var][0];
942 #            echo $var."=".$source[$var][0]."<br>";
943           }
944         }else{
945           $this->$var= $source[$var];
946 #          echo $var."=".$source[$var]."<br>";
947         }
948       }
949     }
950   }
953   function handle_object_tagging($dn= "", $tag= "", $show= false)
954   {
955     //FIXME: How to optimize this? We have at least two
956     //       LDAP accesses per object. It would be a good
957     //       idea to have it integrated.
959     /* No dn? Self-operation... */
960     if ($dn == ""){
961       $dn= $this->dn;
963       /* No tag? Find it yourself... */
964       if ($tag == ""){
965         $len= strlen($dn);
967         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
968         $relevant= array();
969         foreach ($this->config->adepartments as $key => $ntag){
971           /* This one is bigger than our dn, its not relevant... */
972           if ($len <= strlen($key)){
973             continue;
974           }
976           /* This one matches with the latter part. Break and don't fix this entry */
977           if (preg_match('/(^|,)'.normalizePreg($key).'$/', $dn)){
978             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
979             $relevant[strlen($key)]= $ntag;
980             continue;
981           }
983         }
985         /* If we've some relevant tags to set, just get the longest one */
986         if (count($relevant)){
987           ksort($relevant);
988           $tmp= array_keys($relevant);
989           $idx= end($tmp);
990           $tag= $relevant[$idx];
991           $this->gosaUnitTag= $tag;
992         }
993       }
994     }
997     /* Set tag? */
998     if ($tag != ""){
999       /* Set objectclass and attribute */
1000       $ldap= $this->config->get_ldap_link();
1001       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
1002       $attrs= $ldap->fetch();
1003       if(isset($attrs['gosaUnitTag'][0]) && $attrs['gosaUnitTag'][0] == $tag){
1004         if ($show) {
1005           echo sprintf(_("Object '%s' is already tagged"), @LDAP::fix($dn))."<br>";
1006           flush();
1007         }
1008         return;
1009       }
1010       if (count($attrs)){
1011         if ($show){
1012           echo sprintf(_("Adding tag (%s) to object '%s'"), $tag, @LDAP::fix($dn))."<br>";
1013           flush();
1014         }
1015         $nattrs= array("gosaUnitTag" => $tag);
1016         $nattrs['objectClass']= array();
1017         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
1018           $oc= $attrs['objectClass'][$i];
1019           if ($oc != "gosaAdministrativeUnitTag"){
1020             $nattrs['objectClass'][]= $oc;
1021           }
1022         }
1023         $nattrs['objectClass'][]= "gosaAdministrativeUnitTag";
1024         $ldap->cd($dn);
1025         $ldap->modify($nattrs);
1026         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
1027       } else {
1028         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not tagging ($tag) $dn - seems to have moved away", "Tagging");
1029       }
1031     } else {
1032       /* Remove objectclass and attribute */
1033       $ldap= $this->config->get_ldap_link();
1034       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
1035       $attrs= $ldap->fetch();
1036       if (isset($attrs['objectClass']) && !in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass'])){
1037         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "$dn is not tagged", "Tagging");
1038         return;
1039       }
1040       if (count($attrs)){
1041         if ($show){
1042           echo sprintf(_("Removing tag from object '%s'"), @LDAP::fix($dn))."<br>";
1043           flush();
1044         }
1045         $nattrs= array("gosaUnitTag" => array());
1046         $nattrs['objectClass']= array();
1047         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
1048           $oc= $attrs['objectClass'][$i];
1049           if ($oc != "gosaAdministrativeUnitTag"){
1050             $nattrs['objectClass'][]= $oc;
1051           }
1052         }
1053         $ldap->cd($dn);
1054         $ldap->modify($nattrs);
1055         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
1056       } else {
1057         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not removing tag ($tag) $dn - seems to have moved away", "Tagging");
1058       }
1059     }
1061   }
1064   /* Add possibility to stop remove process */
1065   function allow_remove()
1066   {
1067     $reason= "";
1068     return $reason;
1069   }
1072   /* Create a snapshot of the current object */
1073   function create_snapshot($type= "snapshot", $description= array())
1074   {
1076     /* Check if snapshot functionality is enabled */
1077     if(!$this->snapshotEnabled()){
1078       return;
1079     }
1081     /* Get configuration from gosa.conf */
1082     $tmp = $this->config->current;
1084     /* Create lokal ldap connection */
1085     $ldap= $this->config->get_ldap_link();
1086     $ldap->cd($this->config->current['BASE']);
1088     /* check if there are special server configurations for snapshots */
1089     if(!isset($tmp['SNAPSHOT_SERVER'])){
1091       /* Source and destination server are both the same, just copy source to dest obj */
1092       $ldap_to      = $ldap;
1093       $snapldapbase = $this->config->current['BASE'];
1095     }else{
1096       $server         = $tmp['SNAPSHOT_SERVER'];
1097       $user           = $tmp['SNAPSHOT_USER'];
1098       $password       = $tmp['SNAPSHOT_PASSWORD'];
1099       $snapldapbase   = $tmp['SNAPSHOT_BASE'];
1101       $ldap_to        = new LDAP($user,$password, $server);
1102       $ldap_to -> cd($snapldapbase);
1103       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$snapldapbase));
1104     }
1106     /* check if the dn exists */ 
1107     if ($ldap->dn_exists($this->dn)){
1109       /* Extract seconds & mysecs, they are used as entry index */
1110       list($usec, $sec)= explode(" ", microtime());
1112       /* Collect some infos */
1113       $base           = $this->config->current['BASE'];
1114       $snap_base      = $tmp['SNAPSHOT_BASE'];
1115       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1116       $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1118       /* Create object */
1119 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1120       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1121       $newName          = preg_replace("/\./", "", $sec."-".$usec);
1122       $target= array();
1123       $target['objectClass']            = array("top", "gosaSnapshotObject");
1124       $target['gosaSnapshotData']       = gzcompress($data, 6);
1125       $target['gosaSnapshotType']       = $type;
1126       $target['gosaSnapshotDN']         = $this->dn;
1127       $target['description']            = $description;
1128       $target['gosaSnapshotTimestamp']  = $newName;
1130       /* Insert the new snapshot 
1131          But we have to check first, if the given gosaSnapshotTimestamp
1132          is already used, in this case we should increment this value till there is 
1133          an unused value. */ 
1134       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1135       $ldap_to->cat($new_dn);
1136       while($ldap_to->count()){
1137         $ldap_to->cat($new_dn);
1138         $newName = preg_replace("/\./", "", $sec."-".($usec++));
1139         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1140         $target['gosaSnapshotTimestamp']  = $newName;
1141       } 
1143       /* Inset this new snapshot */
1144       $ldap_to->cd($snapldapbase);
1145       $ldap_to->create_missing_trees($new_base);
1146       $ldap_to->cd($new_dn);
1147       $ldap_to->add($target);
1149       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1150       show_ldap_error($ldap_to->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1151     }
1152   }
1154   function remove_snapshot($dn)
1155   {
1156     $ui       = get_userinfo();
1157     $old_dn   = $this->dn; 
1158     $this->dn = $dn;
1159     $ldap = $this->config->get_ldap_link();
1160     $ldap->cd($this->config->current['BASE']);
1161     $ldap->rmdir_recursive($dn);
1162     $this->dn = $old_dn;
1163   }
1166   /* returns true if snapshots are enabled, and false if it is disalbed
1167      There will also be some errors psoted, if the configuration failed */
1168   function snapshotEnabled()
1169   {
1170     $tmp = $this->config->current;
1171     if(isset($tmp['ENABLE_SNAPSHOT'])){
1172       if (preg_match("/^true$/i", $tmp['ENABLE_SNAPSHOT']) || preg_match("/yes/i", $tmp['ENABLE_SNAPSHOT'])){
1174         /* Check if the snapshot_base is defined */
1175         if(!isset($tmp['SNAPSHOT_BASE'])){
1176           print_red(sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not configured in your gosa.conf."),"SNAPSHOT_BASE"));
1177           return(FALSE);
1178         }
1180         /* check if there are special server configurations for snapshots */
1181         if(isset($tmp['SNAPSHOT_SERVER'])){
1183           /* check if all required vars are available to create a new ldap connection */
1184           $missing = "";
1185           foreach(array("SNAPSHOT_SERVER","SNAPSHOT_USER","SNAPSHOT_PASSWORD","SNAPSHOT_BASE") as $var){
1186             if(!isset($tmp[$var])){
1187               $missing .= $var." ";
1188               print_red(sprintf(_("The snapshot functionality is enabled, but the required variable(s) '%s' is not configured in your gosa.conf."),$missing));
1189               return(FALSE);
1190             }
1191           }
1192         }
1193         return(TRUE);
1194       }
1195     }
1196     return(FALSE);
1197   }
1200   /* Return available snapshots for the given base 
1201    */
1202   function Available_SnapsShots($dn,$raw = false)
1203   {
1204     if(!$this->snapshotEnabled()) return(array());
1206     /* Create an additional ldap object which
1207        points to our ldap snapshot server */
1208     $ldap= $this->config->get_ldap_link();
1209     $ldap->cd($this->config->current['BASE']);
1210     $cfg= &$this->config->current;
1212     /* check if there are special server configurations for snapshots */
1213     if(isset($cfg['SNAPSHOT_SERVER'])){
1214       $server       = $cfg['SNAPSHOT_SERVER'];
1215       $user         = $cfg['SNAPSHOT_USER'];
1216       $password     = $cfg['SNAPSHOT_PASSWORD'];
1217       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1218       $ldap_to      = new LDAP($user,$password, $server);
1219       $ldap_to -> cd ($snapldapbase);
1220       show_ldap_error($ldap->get_error(), sprintf(_("Method get available snapshots with dn '%s' failed."),$this->dn));
1221     }else{
1222       $ldap_to    = $ldap;
1223     }
1225     /* Prepare bases and some other infos */
1226     $base           = $this->config->current['BASE'];
1227     $snap_base      = $cfg['SNAPSHOT_BASE'];
1228     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1229     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1230     $tmp            = array(); 
1232     /* Fetch all objects with  gosaSnapshotDN=$dn */
1233     $ldap_to->cd($new_base);
1234     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1235         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1237     /* Put results into a list and add description if missing */
1238     while($entry = $ldap_to->fetch()){ 
1239       if(!isset($entry['description'][0])){
1240         $entry['description'][0]  = "";
1241       }
1242       $tmp[] = $entry; 
1243     }
1245     /* Return the raw array, or format the result */
1246     if($raw){
1247       return($tmp);
1248     }else{  
1249       $tmp2 = array();
1250       foreach($tmp as $entry){
1251         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1252       }
1253     }
1254     return($tmp2);
1255   }
1258   function getAllDeletedSnapshots($base_of_object,$raw = false)
1259   {
1260     if(!$this->snapshotEnabled()) return(array());
1262     /* Create an additional ldap object which
1263        points to our ldap snapshot server */
1264     $ldap= $this->config->get_ldap_link();
1265     $ldap->cd($this->config->current['BASE']);
1266     $cfg= &$this->config->current;
1268     /* check if there are special server configurations for snapshots */
1269     if(isset($cfg['SNAPSHOT_SERVER'])){
1270       $server       = $cfg['SNAPSHOT_SERVER'];
1271       $user         = $cfg['SNAPSHOT_USER'];
1272       $password     = $cfg['SNAPSHOT_PASSWORD'];
1273       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1274       $ldap_to      = new LDAP($user,$password, $server);
1275       $ldap_to->cd ($snapldapbase);
1276       show_ldap_error($ldap->get_error(), sprintf(_("Method get deleted snapshots with dn '%s' failed."),$this->dn));
1277     }else{
1278       $ldap_to    = $ldap;
1279     }
1281     /* Prepare bases */ 
1282     $base           = $this->config->current['BASE'];
1283     $snap_base      = $cfg['SNAPSHOT_BASE'];
1284     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1286     /* Fetch all objects and check if they do not exist anymore */
1287     $ui = get_userinfo();
1288     $tmp = array();
1289     $ldap_to->cd($new_base);
1290     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1291     while($entry = $ldap_to->fetch()){
1293       $chk =  str_replace($new_base,"",$entry['dn']);
1294       if(preg_match("/,ou=/",$chk)) continue;
1296       if(!isset($entry['description'][0])){
1297         $entry['description'][0]  = "";
1298       }
1299       $tmp[] = $entry; 
1300     }
1302     /* Check if entry still exists */
1303     foreach($tmp as $key => $entry){
1304       $ldap->cat($entry['gosaSnapshotDN'][0]);
1305       if($ldap->count()){
1306         unset($tmp[$key]);
1307       }
1308     }
1310     /* Format result as requested */
1311     if($raw) {
1312       return($tmp);
1313     }else{
1314       $tmp2 = array();
1315       foreach($tmp as $key => $entry){
1316         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1317       }
1318     }
1319     return($tmp2);
1320   } 
1323   /* Restore selected snapshot */
1324   function restore_snapshot($dn)
1325   {
1326     if(!$this->snapshotEnabled()) return(array());
1328     $ldap= $this->config->get_ldap_link();
1329     $ldap->cd($this->config->current['BASE']);
1330     $cfg= &$this->config->current;
1332     /* check if there are special server configurations for snapshots */
1333     if(isset($cfg['SNAPSHOT_SERVER'])){
1334       $server       = $cfg['SNAPSHOT_SERVER'];
1335       $user         = $cfg['SNAPSHOT_USER'];
1336       $password     = $cfg['SNAPSHOT_PASSWORD'];
1337       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1338       $ldap_to      = new LDAP($user,$password, $server);
1339       $ldap_to->cd ($snapldapbase);
1340       show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$snapldapbase));
1341     }else{
1342       $ldap_to    = $ldap;
1343     }
1345     /* Get the snapshot */ 
1346     $ldap_to->cat($dn);
1347     $restoreObject = $ldap_to->fetch();
1349     /* Prepare import string */
1350     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1352     /* Import the given data */
1353     $ldap->import_complete_ldif($data,$err,false,false);
1354     show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$dn));
1355   }
1358   function showSnapshotDialog($base,$baseSuffixe)
1359   {
1360     $once = true;
1361     foreach($_POST as $name => $value){
1363       /* Create a new snapshot, display a dialog */
1364       if(preg_match("/^CreateSnapShotDialog_/",$name) && $once){
1365         $once = false;
1366         $entry = preg_replace("/^CreateSnapShotDialog_/","",$name);
1367         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1368         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1369       }
1371       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1372       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1373         $once = false;
1374         $entry = preg_replace("/^RestoreSnapShotDialog_/","",$name);
1375         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1376         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1377         $this->snapDialog->display_restore_dialog = true;
1378       }
1380       /* Restore one of the already deleted objects */
1381       if(preg_match("/^RestoreDeletedSnapShot_/",$name) && $once){
1382         $once = false;
1383         $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1384         $this->snapDialog->set_snapshot_bases($baseSuffixe);
1385         $this->snapDialog->display_restore_dialog      = true;
1386         $this->snapDialog->display_all_removed_objects  = true;
1387       }
1389       /* Restore selected snapshot */
1390       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1391         $once = false;
1392         $entry = preg_replace("/^RestoreSnapShot_/","",$name);
1393         $entry = base64_decode(trim(preg_replace("/_[xy]$/","",$entry)));
1394         if(!empty($entry)){
1395           $this->restore_snapshot($entry);
1396           $this->snapDialog = NULL;
1397         }
1398       }
1399     }
1401     /* Create a new snapshot requested, check
1402        the given attributes and create the snapshot*/
1403     if(isset($_POST['CreateSnapshot'])){
1404       $this->snapDialog->save_object();
1405       $msgs = $this->snapDialog->check();
1406       if(count($msgs)){
1407         foreach($msgs as $msg){
1408           print_red($msg);
1409         }
1410       }else{
1411         $this->dn =  $this->snapDialog->dn;
1412         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1413         $this->snapDialog = NULL;
1414       }
1415     }
1417     /* Restore is requested, restore the object with the posted dn .*/
1418     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1419     }
1421     if(isset($_POST['CancelSnapshot'])){
1422       $this->snapDialog = NULL;
1423     }
1425     if($this->snapDialog){
1426       $this->snapDialog->save_object();
1427       return($this->snapDialog->execute());
1428     }
1429   }
1432   function plInfo()
1433   {
1434     return array();
1435   }
1438   function set_acl_base($base)
1439   {
1440     $this->acl_base= $base;
1441   }
1444   function set_acl_category($category)
1445   {
1446     $this->acl_category= "$category/";
1447   }
1450   function acl_is_writeable($attribute,$skip_write = FALSE)
1451   {
1452     $ui= get_userinfo();
1453     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1454   }
1457   function acl_is_readable($attribute)
1458   {
1459     $ui= get_userinfo();
1460     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1461   }
1464   function acl_is_createable()
1465   {
1466     $ui= get_userinfo();
1467     return preg_match('/c/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1468   }
1471   function acl_is_removeable()
1472   {
1473     $ui= get_userinfo();
1474     return preg_match('/d/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1475   }
1478   function acl_is_moveable()
1479   {
1480     $ui= get_userinfo();
1481     return preg_match('/m/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1482   }
1485   function acl_have_any_permissions()
1486   {
1487   }
1490   function getacl($attribute,$skip_write= FALSE)
1491   {
1492     $ui= get_userinfo();
1493     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1494   }
1496   /* Get all allowed bases to move an object to or to create a new object.
1497      Idepartments also contains all base departments which lead to the allowed bases */
1498   function get_allowed_bases($category = "")
1499   {
1500     $ui = get_userinfo();
1501     $deps = array();
1503     /* Set category */ 
1504     if(empty($category)){
1505       $category = $this->acl_category.get_class($this);
1506     }
1508     /* Is this a new object ? Or just an edited existing object */
1509     if(!$this->initially_was_account && $this->is_account){
1510       $new = true;
1511     }else{
1512       $new = false;
1513     }
1515     $cat_bases = $ui->get_module_departments(preg_replace("/\/.*$/","",$category));
1516     foreach($this->config->idepartments as $dn => $name){
1517       
1518       if(!in_array_ics($dn,$cat_bases)){
1519         continue;
1520       }
1521       
1522       $acl = $ui->get_permissions($dn,$category);
1523       if($new && preg_match("/c/",$acl)){
1524         $deps[$dn] = $name;
1525       }elseif(!$new && preg_match("/m/",$acl)){
1526         $deps[$dn] = $name;
1527       }
1528     }
1530     /* Add current base */      
1531     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1532       $deps[$this->base] = $this->config->idepartments[$this->base];
1533     }else{
1534       echo "No default base found. ".$this->base."<br> ";
1535     }
1537     return($deps);
1538   }
1540   /* This function modifies object acls too, if an object is moved.
1541    *  $old_dn   specifies the actually used dn
1542    *  $new_dn   specifies the destiantion dn
1543    */
1544   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1545   {
1546     /* Check if old_dn is empty. This should never happen */
1547     if(empty($old_dn) || empty($new_dn)){
1548       trigger_error("Failed to check acl dependencies, wrong dn given.");
1549       return;
1550     }
1552     /* Update userinfo if necessary */
1553     if($_SESSION['ui']->dn == $old_dn){
1554       $_SESSION['ui']->dn = $new_dn;
1555       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current user dn from '".$old_dn."' to '".$new_dn."'");
1556     }
1558     /* Object was moved, ensure that all acls will be moved too */
1559     if($new_dn != $old_dn && $old_dn != "new"){
1561       /* get_ldap configuration */
1562       $update = array();
1563       $ldap = $this->config->get_ldap_link();
1564       $ldap->cd ($this->config->current['BASE']);
1565       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*))",array("cn","gosaAclEntry"));
1566       while($attrs = $ldap->fetch()){
1568         $acls = array();
1570         /* Walk through acls */
1571         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1573           /* Reset vars */
1574           $found = false;
1576           /* Get Acl parts */
1577           $acl_parts = split(":",$attrs['gosaAclEntry'][$i]);
1579           /* Get every single member for this acl */  
1580           $members = array();  
1581           if(preg_match("/,/",$acl_parts[2])){
1582             $members = split(",",$acl_parts[2]);
1583           }else{
1584             $members = array($acl_parts[2]);
1585           } 
1586       
1587           /* Check if member match current dn */
1588           foreach($members as $key => $member){
1589             $member = base64_decode($member);
1590             if($member == $old_dn){
1591               $found = true;
1592               $members[$key] = base64_encode($new_dn);
1593             }
1594           } 
1595          
1596           /* Create new member string */ 
1597           $new_members = "";
1598           foreach($members as $member){
1599             $new_members .= $member.",";
1600           }
1601           $new_members = preg_replace("/,$/","",$new_members);
1602           $acl_parts[2] = $new_members;
1603         
1604           /* Reconstruckt acl entry */
1605           $acl_str  ="";
1606           foreach($acl_parts as $t){
1607            $acl_str .= $t.":";
1608           }
1609           $acl_str = preg_replace("/:$/","",$acl_str);
1610        }
1612        /* Acls for this object must be adjusted */
1613        if($found){
1615           if($output_changes){
1616             echo "<font color='green'>".
1617                   _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1618                   $old_dn.
1619                   "</b><br>&nbsp;-"._("to")."&nbsp;<b>".
1620                   $new_dn.
1621                   "</b></font><br>";
1622           }
1623           $update[$attrs['dn']] =array();
1624           foreach($acls as $acl){
1625             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1626           }
1627         }
1628       }
1630       /* Write updated acls */
1631       foreach($update as $dn => $attrs){
1632         $ldap->cd($dn);
1633         $ldap->modify($attrs);
1634       }
1635     }
1636   }
1638 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1639 ?>