Code

Added queue entry start / stop
[gosa.git] / gosa-core / include / class_plugin.inc
1 <?php
2 /*
3    This code is part of GOsa (https://gosa.gonicus.de)
4    Copyright (C) 2003  Cajus Pollmeier
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
21 /*! \brief   The plugin base class
22   \author  Cajus Pollmeier <pollmeier@gonicus.de>
23   \version 2.00
24   \date    24.07.2003
26   This is the base class for all plugins. It can be used standalone or
27   can be included by the tabs class. All management should be done 
28   within this class. Extend your plugins from this class.
29  */
31 class plugin
32 {
33   /*!
34     \brief Reference to parent object
36     This variable is used when the plugin is included in tabs
37     and keeps reference to the tab class. Communication to other
38     tabs is possible by 'name'. So the 'fax' plugin can ask the
39     'userinfo' plugin for the fax number.
41     \sa tab
42    */
43   var $parent= NULL;
45   /*!
46     \brief Configuration container
48     Access to global configuration
49    */
50   var $config= NULL;
52   /*!
53     \brief Mark plugin as account
55     Defines whether this plugin is defined as an account or not.
56     This has consequences for the plugin to be saved from tab
57     mode. If it is set to 'FALSE' the tab will call the delete
58     function, else the save function. Should be set to 'TRUE' if
59     the construtor detects a valid LDAP object.
61     \sa plugin::plugin()
62    */
63   var $is_account= FALSE;
64   var $initially_was_account= FALSE;
66   /*!
67     \brief Mark plugin as template
69     Defines whether we are creating a template or a normal object.
70     Has conseqences on the way execute() shows the formular and how
71     save() puts the data to LDAP.
73     \sa plugin::save() plugin::execute()
74    */
75   var $is_template= FALSE;
76   var $ignore_account= FALSE;
77   var $is_modified= FALSE;
79   /*!
80     \brief Represent temporary LDAP data
82     This is only used internally.
83    */
84   var $attrs= array();
86   /* Keep set of conflicting plugins */
87   var $conflicts= array();
89   /* Save unit tags */
90   var $gosaUnitTag= "";
92   /*!
93     \brief Used standard values
95     dn
96    */
97   var $dn= "";
98   var $uid= "";
99   var $sn= "";
100   var $givenName= "";
101   var $acl= "*none*";
102   var $dialog= FALSE;
103   var $snapDialog = NULL;
105   /* attribute list for save action */
106   var $attributes= array();
107   var $objectclasses= array();
108   var $is_new= TRUE;
109   var $saved_attributes= array();
111   var $acl_base= "";
112   var $acl_category= "";
114   /* This can be set to render the tabulators in another stylesheet */
115   var $pl_notify= FALSE;
117   /* Object entry CSN */
118   var $entryCSN         = "";
119   var $CSN_check_active = FALSE;
121   /* This variable indicates that this class can handle multiple dns at once. */
122   var $multiple_support = FALSE;
123   var $multi_attrs      = array();
124   var $multi_attrs_all  = array(); 
126   /* This aviable indicates, that we are currently in multiple edit handle */
127   var $multiple_support_active = FALSE; 
128   var $selected_edit_values = array();
129   var $multi_boxes = array();
131   /*! \brief plugin constructor
133     If 'dn' is set, the node loads the given 'dn' from LDAP
135     \param dn Distinguished name to initialize plugin from
136     \sa plugin()
137    */
138   function plugin (&$config, $dn= NULL, $parent= NULL)
139   {
140     /* Configuration is fine, allways */
141     $this->config= &$config;    
142     $this->dn= $dn;
144     /* Handle new accounts, don't read information from LDAP */
145     if ($dn == "new"){
146       return;
147     }
149     /* Save current dn as acl_base */
150     $this->acl_base= $dn;
152     /* Get LDAP descriptor */
153     $ldap= $this->config->get_ldap_link();
154     if ($dn !== NULL){
156       /* Load data to 'attrs' and save 'dn' */
157       if ($parent !== NULL){
158         $this->attrs= $parent->attrs;
159       } else {
160         $ldap->cat ($dn);
161         $this->attrs= $ldap->fetch();
162       }
164       /* Copy needed attributes */
165       foreach ($this->attributes as $val){
166         $found= array_key_ics($val, $this->attrs);
167         if ($found != ""){
168           $this->$val= $this->attrs["$found"][0];
169         }
170       }
172       /* gosaUnitTag loading... */
173       if (isset($this->attrs['gosaUnitTag'][0])){
174         $this->gosaUnitTag= $this->attrs['gosaUnitTag'][0];
175       }
177       /* Set the template flag according to the existence of objectClass
178          gosaUserTemplate */
179       if (isset($this->attrs['objectClass'])){
180         if (in_array ("gosaUserTemplate", $this->attrs['objectClass'])){
181           $this->is_template= TRUE;
182           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
183               "found", "Template check");
184         }
185       }
187       /* Is Account? */
188       $found= TRUE;
189       foreach ($this->objectclasses as $obj){
190         if (preg_match('/top/i', $obj)){
191           continue;
192         }
193         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
194           $found= FALSE;
195           break;
196         }
197       }
198       if ($found){
199         $this->is_account= TRUE;
200         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
201             "found", "Object check");
202       }
204       /* Prepare saved attributes */
205       $this->saved_attributes= $this->attrs;
206       foreach ($this->saved_attributes as $index => $value){
207         if (preg_match('/^[0-9]+$/', $index)){
208           unset($this->saved_attributes[$index]);
209           continue;
210         }
211         if (!in_array($index, $this->attributes) && $index != "objectClass"){
212           unset($this->saved_attributes[$index]);
213           continue;
214         }
215         if ($this->saved_attributes[$index]["count"] == 1){
216           $tmp= $this->saved_attributes[$index][0];
217           unset($this->saved_attributes[$index]);
218           $this->saved_attributes[$index]= $tmp;
219           continue;
220         }
222         unset($this->saved_attributes["$index"]["count"]);
223       }
224     }
226     /* Save initial account state */
227     $this->initially_was_account= $this->is_account;
228   }
231   /*! \brief execute plugin
233     Generates the html output for this node
234    */
235   function execute()
236   {
237     /* This one is empty currently. Fabian - please fill in the docu code */
238     session::set('current_class_for_help',get_class($this));
240     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
241     session::set('LOCK_VARS_TO_USE',array());
242     session::set('LOCK_VARS_USED',array());
243   }
245   /*! \brief execute plugin
246      Removes object from parent
247    */
248   function remove_from_parent()
249   {
250     /* include global link_info */
251     $ldap= $this->config->get_ldap_link();
253     /* Get current objectClasses in order to add the required ones */
254     $ldap->cat($this->dn);
255     $tmp= $ldap->fetch ();
256     $oc= array();
257     if (isset($tmp['objectClass'])){
258       $oc= $tmp['objectClass'];
259       unset($oc['count']);
260     }
262     /* Remove objectClasses from entry */
263     $ldap->cd($this->dn);
264     $this->attrs= array();
265     $this->attrs['objectClass']= array_remove_entries($this->objectclasses,$oc);
267     /* Unset attributes from entry */
268     foreach ($this->attributes as $val){
269       $this->attrs["$val"]= array();
270     }
272     /* Unset account info */
273     $this->is_account= FALSE;
275     /* Do not write in plugin base class, this must be done by
276        children, since there are normally additional attribs,
277        lists, etc. */
278     /*
279        $ldap->modify($this->attrs);
280      */
281   }
284   /*! \brief   Save HTML posted data to object 
285    */
286   function save_object()
287   {
288     /* Update entry CSN if it is empty. */
289     if(empty($this->entryCSN) && $this->CSN_check_active){
290       $this->entryCSN = getEntryCSN($this->dn);
291     }
293     /* Save values to object */
294     foreach ($this->attributes as $val){
295       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
296         /* Check for modifications */
297         if (get_magic_quotes_gpc()) {
298           $data= stripcslashes($_POST["$val"]);
299         } else {
300           $data= $this->$val = $_POST["$val"];
301         }
302         if ($this->$val != $data){
303           $this->is_modified= TRUE;
304         }
305     
306         /* Okay, how can I explain this fix ... 
307          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
308          * So IE posts these 'unselectable' option, with value = chr(194) 
309          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
310          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
311          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
312          */
313         if(isset($data[0]) && $data[0] == chr(194)) {
314           $data = "";  
315         }
316         $this->$val= $data;
317         //echo "<font color='blue'>".$val."</font><br>";
318       }else{
319         //echo "<font color='red'>".$val."</font><br>";
320       }
321     }
322   }
325   /* Save data to LDAP, depending on is_account we save or delete */
326   function save()
327   {
328     /* include global link_info */
329     $ldap= $this->config->get_ldap_link();
331     /* Save all plugins */
332     $this->entryCSN = "";
334     /* Start with empty array */
335     $this->attrs= array();
337     /* Get current objectClasses in order to add the required ones */
338     $ldap->cat($this->dn);
339     
340     $tmp= $ldap->fetch ();
342     $oc= array();
343     if (isset($tmp['objectClass'])){
344       $oc= $tmp["objectClass"];
345       $this->is_new= FALSE;
346       unset($oc['count']);
347     } else {
348       $this->is_new= TRUE;
349     }
351     /* Load (minimum) attributes, add missing ones */
352     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
354     /* Copy standard attributes */
355     foreach ($this->attributes as $val){
356       if ($this->$val != ""){
357         $this->attrs["$val"]= $this->$val;
358       } elseif (!$this->is_new) {
359         $this->attrs["$val"]= array();
360       }
361     }
363     /* Handle tagging */
364     $this->tag_attrs(&$this->attrs);
365   }
368   function cleanup()
369   {
370     foreach ($this->attrs as $index => $value){
372       /* Convert arrays with one element to non arrays, if the saved
373          attributes are no array, too */
374       if (is_array($this->attrs[$index]) && 
375           count ($this->attrs[$index]) == 1 &&
376           isset($this->saved_attributes[$index]) &&
377           !is_array($this->saved_attributes[$index])){
378           
379         $tmp= $this->attrs[$index][0];
380         $this->attrs[$index]= $tmp;
381       }
383       /* Remove emtpy arrays if they do not differ */
384       if (is_array($this->attrs[$index]) &&
385           count($this->attrs[$index]) == 0 &&
386           !isset($this->saved_attributes[$index])){
387           
388         unset ($this->attrs[$index]);
389         continue;
390       }
392       /* Remove single attributes that do not differ */
393       if (!is_array($this->attrs[$index]) &&
394           isset($this->saved_attributes[$index]) &&
395           !is_array($this->saved_attributes[$index]) &&
396           $this->attrs[$index] == $this->saved_attributes[$index]){
398         unset ($this->attrs[$index]);
399         continue;
400       }
402       /* Remove arrays that do not differ */
403       if (is_array($this->attrs[$index]) && 
404           isset($this->saved_attributes[$index]) &&
405           is_array($this->saved_attributes[$index])){
406           
407         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
408           unset ($this->attrs[$index]);
409           continue;
410         }
411       }
412     }
414     /* Update saved attributes and ensure that next cleanups will be successful too */
415     foreach($this->attrs as $name => $value){
416       $this->saved_attributes[$name] = $value;
417     }
418   }
420   /* Check formular input */
421   function check()
422   {
423     $message= array();
425     /* Skip if we've no config object */
426     if (!isset($this->config) || !is_object($this->config)){
427       return $message;
428     }
430     /* Find hooks entries for this class */
431     $command= $this->config->search(get_class($this), "CHECK", array('menu', 'tabs'));
433     if ($command != ""){
435       if (!check_command($command)){
436         $message[]= sprintf(_("Command '%s', specified as CHECK hook for plugin '%s' doesn't seem to exist."), $command,
437                             get_class($this));
438       } else {
440         /* Generate "ldif" for check hook */
441         $ldif= "dn: $this->dn\n";
442         
443         /* ... objectClasses */
444         foreach ($this->objectclasses as $oc){
445           $ldif.= "objectClass: $oc\n";
446         }
447         
448         /* ... attributes */
449         foreach ($this->attributes as $attr){
450           if ($this->$attr == ""){
451             continue;
452           }
453           if (is_array($this->$attr)){
454             foreach ($this->$attr as $val){
455               $ldif.= "$attr: $val\n";
456             }
457           } else {
458               $ldif.= "$attr: ".$this->$attr."\n";
459           }
460         }
462         /* Append empty line */
463         $ldif.= "\n";
465         /* Feed "ldif" into hook and retrieve result*/
466         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
467         $fh= proc_open($command, $descriptorspec, $pipes);
468         if (is_resource($fh)) {
469           fwrite ($pipes[0], $ldif);
470           fclose($pipes[0]);
471           
472           $result= stream_get_contents($pipes[1]);
473           if ($result != ""){
474             $message[]= $result;
475           }
476           
477           fclose($pipes[1]);
478           fclose($pipes[2]);
479           proc_close($fh);
480         }
481       }
483     }
485     /* Check entryCSN */
486     if($this->CSN_check_active){
487       $current_csn = getEntryCSN($this->dn);
488       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
489         $this->entryCSN = $current_csn;
490         $message[] = _("The object has changed since opened in GOsa. Please ensure that nobody has done serious changes that may get lost   if you save this entry.");
491       }
492     }
493     return ($message);
494   }
496   /* Adapt from template, using 'dn' */
497   function adapt_from_template($dn)
498   {
499     /* Include global link_info */
500     $ldap= $this->config->get_ldap_link();
502     /* Load requested 'dn' to 'attrs' */
503     $ldap->cat ($dn);
504     $this->attrs= $ldap->fetch();
506     /* Walk through attributes */
507     foreach ($this->attributes as $val){
509       if (isset($this->attrs["$val"][0])){
511         /* If attribute is set, replace dynamic parts: 
512            %sn, %givenName and %uid. Fill these in our local variables. */
513         $value= $this->attrs["$val"][0];
515         foreach (array("sn", "givenName", "uid") as $repl){
516           if (preg_match("/%$repl/i", $value)){
517             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
518           }
519         }
520         $this->$val= $value;
521       }
522     }
524     /* Is Account? */
525     $found= TRUE;
526     foreach ($this->objectclasses as $obj){
527       if (preg_match('/top/i', $obj)){
528         continue;
529       }
530       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
531         $found= FALSE;
532         break;
533       }
534     }
535     if ($found){
536       $this->is_account= TRUE;
537     }
538   }
540   /* Indicate whether a password change is needed or not */
541   function password_change_needed()
542   {
543     return FALSE;
544   }
547   /* Show header message for tab dialogs */
548   function show_enable_header($button_text, $text, $disabled= FALSE)
549   {
550     if (($disabled == TRUE) || (!$this->acl_is_createable())){
551       $state= "disabled";
552     } else {
553       $state= "";
554     }
555     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
556     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
557       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
559     return($display);
560   }
563   /* Show header message for tab dialogs */
564   function show_disable_header($button_text, $text, $disabled= FALSE)
565   {
566     if (($disabled == TRUE) || !$this->acl_is_removeable()){
567       $state= "disabled";
568     } else {
569       $state= "";
570     }
571     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
572     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
573       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
575     return($display);
576   }
579   /* Show header message for tab dialogs */
580   function show_header($button_text, $text, $disabled= FALSE)
581   {
582     echo "FIXME: show_header should be replaced by show_disable_header and show_enable_header<br>";
583     if ($disabled == TRUE){
584       $state= "disabled";
585     } else {
586       $state= "";
587     }
588     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
589     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
590       ($this->acl_is_createable()?'':'disabled')." ".$state.
591       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
593     return($display);
594   }
597   function postcreate($add_attrs= array())
598   {
599     /* Find postcreate entries for this class */
600     $command= $this->config->search(get_class($this), "POSTCREATE",array('menu', 'tabs'));
602     if ($command != ""){
604       /* Additional attributes */
605       foreach ($add_attrs as $name => $value){
606         $command= preg_replace("/%$name/", $value, $command);
607       }
609       /* Walk through attribute list */
610       foreach ($this->attributes as $attr){
611         if (!is_array($this->$attr)){
612           $command= preg_replace("/%$attr/", $this->$attr, $command);
613         }
614       }
615       $command= preg_replace("/%dn/", $this->dn, $command);
617       if (check_command($command)){
618         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
619             $command, "Execute");
621         exec($command);
622       } else {
623         $message= sprintf(_("Command '%s', specified as POSTCREATE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
624         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
625       }
626     }
627   }
629   function postmodify($add_attrs= array())
630   {
631     /* Find postcreate entries for this class */
632     $command= $this->config->search(get_class($this), "POSTMODIFY",array('menu','tabs'));
634     if ($command != ""){
636       /* Additional attributes */
637       foreach ($add_attrs as $name => $value){
638         $command= preg_replace("/%$name/", $value, $command);
639       }
641       /* Walk through attribute list */
642       foreach ($this->attributes as $attr){
643         if (!is_array($this->$attr)){
644           $command= preg_replace("/%$attr/", $this->$attr, $command);
645         }
646       }
647       $command= preg_replace("/%dn/", $this->dn, $command);
649       if (check_command($command)){
650         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
651             $command, "Execute");
653         exec($command);
654       } else {
655         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, get_class($this));
656         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
657       }
658     }
659   }
661   function postremove($add_attrs= array())
662   {
663     /* Find postremove entries for this class */
664     $command= $this->config->search(get_class($this), "POSTREMOVE",array('menu','tabs'));
665     if ($command != ""){
667       /* Additional attributes */
668       foreach ($add_attrs as $name => $value){
669         $command= preg_replace("/%$name/", $value, $command);
670       }
672       /* Walk through attribute list */
673       foreach ($this->attributes as $attr){
674         if (!is_array($this->$attr)){
675           $command= preg_replace("/%$attr/", $this->$attr, $command);
676         }
677       }
678       $command= preg_replace("/%dn/", $this->dn, $command);
680       /* Additional attributes */
681       foreach ($add_attrs as $name => $value){
682         $command= preg_replace("/%$name/", $value, $command);
683       }
685       if (check_command($command)){
686         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
687             $command, "Execute");
689         exec($command);
690       } else {
691         $message= sprintf(_("Command '%s', specified as POSTREMOVE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
692         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
693       }
694     }
695   }
697   /* Create unique DN */
698   function create_unique_dn($attribute, $base)
699   {
700     $ldap= $this->config->get_ldap_link();
701     $base= preg_replace("/^,*/", "", $base);
703     /* Try to use plain entry first */
704     $dn= "$attribute=".$this->$attribute.",$base";
705     $ldap->cat ($dn, array('dn'));
706     if (!$ldap->fetch()){
707       return ($dn);
708     }
710     /* Look for additional attributes */
711     foreach ($this->attributes as $attr){
712       if ($attr == $attribute || $this->$attr == ""){
713         continue;
714       }
716       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
717       $ldap->cat ($dn, array('dn'));
718       if (!$ldap->fetch()){
719         return ($dn);
720       }
721     }
723     /* None found */
724     return ("none");
725   }
727   function rebind($ldap, $referral)
728   {
729     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
730     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
731       $this->error = "Success";
732       $this->hascon=true;
733       $this->reconnect= true;
734       return (0);
735     } else {
736       $this->error = "Could not bind to " . $credentials['ADMIN'];
737       return NULL;
738     }
739   }
742   /* Recursively copy ldap object */
743   function _copy($src_dn,$dst_dn)
744   {
745     $ldap=$this->config->get_ldap_link();
746     $ldap->cat($src_dn);
747     $attrs= $ldap->fetch();
749     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
750     $ds= ldap_connect($this->config->current['SERVER']);
751     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
752     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
753       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
754     }
756     $r=ldap_bind($ds,$this->config->current['ADMIN'], $this->config->current['PASSWORD']);
757     $sr=ldap_read($ds, @LDAP::fix($src_dn), "objectClass=*");
759     /* Fill data from LDAP */
760     $new= array();
761     if ($sr) {
762       $ei=ldap_first_entry($ds, $sr);
763       if ($ei) {
764         foreach($attrs as $attr => $val){
765           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
766             for ($i= 0; $i<$info['count']; $i++){
767               if ($info['count'] == 1){
768                 $new[$attr]= $info[$i];
769               } else {
770                 $new[$attr][]= $info[$i];
771               }
772             }
773           }
774         }
775       }
776     }
778     /* close conncetion */
779     ldap_unbind($ds);
781     /* Adapt naming attribute */
782     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
783     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
784     $new[$dst_name]= @LDAP::fix($dst_val);
786     /* Check if this is a department.
787      * If it is a dep. && there is a , override in his ou 
788      *  change \2C to , again, else this entry can't be saved ...
789      */
790     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
791       $new['ou'] = preg_replace("/\\\\,/",",",$new['ou']);
792     }
794     /* Save copy */
795     $ldap->connect();
796     $ldap->cd($this->config->current['BASE']);
797     
798     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
800     /* FAIvariable=.../..., cn=.. 
801         could not be saved, because the attribute FAIvariable was different to 
802         the dn FAIvariable=..., cn=... */
803     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
804       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
805     }
806     $ldap->cd($dst_dn);
807     $ldap->add($new);
809     if ($ldap->error != "Success"){
810       trigger_error("Trying to save $dst_dn failed.",
811           E_USER_WARNING);
812       return(FALSE);
813     }
814     return(TRUE);
815   }
818   /* This is a workaround function. */
819   function copy($src_dn, $dst_dn)
820   {
821     /* Rename dn in possible object groups */
822     $ldap= $this->config->get_ldap_link();
823     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::preapre4filter($src_dn).'))',
824         array('cn'));
825     while ($attrs= $ldap->fetch()){
826       $og= new ogroup($this->config, $ldap->getDN());
827       unset($og->member[$src_dn]);
828       $og->member[$dst_dn]= $dst_dn;
829       $og->save ();
830     }
832     $ldap->cat($dst_dn);
833     $attrs= $ldap->fetch();
834     if (count($attrs)){
835       trigger_error("Trying to overwrite ".@LDAP::fix($dst_dn).", which already exists.",
836           E_USER_WARNING);
837       return (FALSE);
838     }
840     $ldap->cat($src_dn);
841     $attrs= $ldap->fetch();
842     if (!count($attrs)){
843       trigger_error("Trying to move ".@LDAP::fix($src_dn).", which does not seem to exist.",
844           E_USER_WARNING);
845       return (FALSE);
846     }
848     $ldap->cd($src_dn);
849     $ldap->search("objectClass=*",array("dn"));
850     while($attrs = $ldap->fetch()){
851       $src = $attrs['dn'];
852       $dst = preg_replace("/".normalizePreg($src_dn)."$/",$dst_dn,$attrs['dn']);
853       $this->_copy($src,$dst);
854     }
855     return (TRUE);
856   }
859   function move($src_dn, $dst_dn)
860   {
861     /* Copy source to destination */
862     if (!$this->copy($src_dn, $dst_dn)){
863       return (FALSE);
864     }
866     /* Delete source */
867     $ldap= $this->config->get_ldap_link();
868     $ldap->rmdir_recursive($src_dn);
869     if ($ldap->error != "Success"){
870       trigger_error("Trying to delete $src_dn failed.",
871           E_USER_WARNING);
872       return (FALSE);
873     }
875     return (TRUE);
876   }
879   /* Move/Rename complete trees */
880   function recursive_move($src_dn, $dst_dn)
881   {
882     /* Check if the destination entry exists */
883     $ldap= $this->config->get_ldap_link();
885     /* Check if destination exists - abort */
886     $ldap->cat($dst_dn, array('dn'));
887     if ($ldap->fetch()){
888       trigger_error("recursive_move $dst_dn already exists.",
889           E_USER_WARNING);
890       return (FALSE);
891     }
893     /* Perform a search for all objects to be moved */
894     $objects= array();
895     $ldap->cd($src_dn);
896     $ldap->search("(objectClass=*)", array("dn"));
897     while($attrs= $ldap->fetch()){
898       $dn= $attrs['dn'];
899       $objects[$dn]= strlen($dn);
900     }
902     /* Sort objects by indent level */
903     asort($objects);
904     reset($objects);
906     /* Copy objects from small to big indent levels by replacing src_dn by dst_dn */
907     foreach ($objects as $object => $len){
908       $src= $object;
909       $dst= preg_replace("/$src_dn$/", "$dst_dn", $object);
910       if (!$this->copy($src, $dst)){
911         return (FALSE);
912       }
913     }
915     /* Remove src_dn */
916     $ldap->cd($src_dn);
917     $ldap->recursive_remove();
918     return (TRUE);
919   }
922   function handle_post_events($mode, $add_attrs= array())
923   {
924     switch ($mode){
925       case "add":
926         $this->postcreate($add_attrs);
927       break;
929       case "modify":
930         $this->postmodify($add_attrs);
931       break;
933       case "remove":
934         $this->postremove($add_attrs);
935       break;
936     }
937   }
940   function saveCopyDialog(){
941   }
944   function getCopyDialog(){
945     return(array("string"=>"","status"=>""));
946   }
949   function PrepareForCopyPaste($source)
950   {
951     $todo = $this->attributes;
952     if(isset($this->CopyPasteVars)){
953       $todo = array_merge($todo,$this->CopyPasteVars);
954     }
956     if(count($this->objectclasses)){
957       $this->is_account = TRUE;
958       foreach($this->objectclasses as $class){
959         if(!in_array($class,$source['objectClass'])){
960           $this->is_account = FALSE;
961         }
962       }
963     }
965     foreach($todo as $var){
966       if (isset($source[$var])){
967         if(isset($source[$var]['count'])){
968           if($source[$var]['count'] > 1){
969             $this->$var = array();
970             $tmp = array();
971             for($i = 0 ; $i < $source[$var]['count']; $i++){
972               $tmp = $source[$var][$i];
973             }
974             $this->$var = $tmp;
975 #            echo $var."=".$tmp."<br>";
976           }else{
977             $this->$var = $source[$var][0];
978 #            echo $var."=".$source[$var][0]."<br>";
979           }
980         }else{
981           $this->$var= $source[$var];
982 #          echo $var."=".$source[$var]."<br>";
983         }
984       }
985     }
986   }
988   function tag_attrs($at, $dn= "", $tag= "", $show= false)
989   {
990     /* No dn? Self-operation... */
991     if ($dn == ""){
992       $dn= $this->dn;
994       /* No tag? Find it yourself... */
995       if ($tag == ""){
996         $len= strlen($dn);
998         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
999         $relevant= array();
1000         foreach ($this->config->adepartments as $key => $ntag){
1002           /* This one is bigger than our dn, its not relevant... */
1003           if ($len <= strlen($key)){
1004             continue;
1005           }
1007           /* This one matches with the latter part. Break and don't fix this entry */
1008           if (preg_match('/(^|,)'.normalizePreg($key).'$/', $dn)){
1009             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1010             $relevant[strlen($key)]= $ntag;
1011             continue;
1012           }
1014         }
1016         /* If we've some relevant tags to set, just get the longest one */
1017         if (count($relevant)){
1018           ksort($relevant);
1019           $tmp= array_keys($relevant);
1020           $idx= end($tmp);
1021           $tag= $relevant[$idx];
1022           $this->gosaUnitTag= $tag;
1023         }
1024       }
1025     }
1027     /* Remove tags that may already be here... */
1028     remove_objectClass("gosaAdministrativeUnitTag", &$at);
1029     if (isset($at['gosaUnitTag'])){
1030         unset($at['gosaUnitTag']);
1031     }
1033     /* Set tag? */
1034     if ($tag != ""){
1035       add_objectClass("gosaAdministrativeUnitTag", &$at);
1036       $at['gosaUnitTag']= $tag;
1037     }
1038   }
1041   /* Add possibility to stop remove process */
1042   function allow_remove()
1043   {
1044     $reason= "";
1045     return $reason;
1046   }
1049   /* Create a snapshot of the current object */
1050   function create_snapshot($type= "snapshot", $description= array())
1051   {
1053     /* Check if snapshot functionality is enabled */
1054     if(!$this->snapshotEnabled()){
1055       return;
1056     }
1058     /* Get configuration from gosa.conf */
1059     $tmp = $this->config->current;
1061     /* Create lokal ldap connection */
1062     $ldap= $this->config->get_ldap_link();
1063     $ldap->cd($this->config->current['BASE']);
1065     /* check if there are special server configurations for snapshots */
1066     if(!isset($tmp['SNAPSHOT_SERVER'])){
1068       /* Source and destination server are both the same, just copy source to dest obj */
1069       $ldap_to      = $ldap;
1070       $snapldapbase = $this->config->current['BASE'];
1072     }else{
1073       $server         = $tmp['SNAPSHOT_SERVER'];
1074       $user           = $tmp['SNAPSHOT_USER'];
1075       $password       = $tmp['SNAPSHOT_PASSWORD'];
1076       $snapldapbase   = $tmp['SNAPSHOT_BASE'];
1078       $ldap_to        = new LDAP($user,$password, $server);
1079       $ldap_to -> cd($snapldapbase);
1080       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$snapldapbase));
1081     }
1083     /* check if the dn exists */ 
1084     if ($ldap->dn_exists($this->dn)){
1086       /* Extract seconds & mysecs, they are used as entry index */
1087       list($usec, $sec)= explode(" ", microtime());
1089       /* Collect some infos */
1090       $base           = $this->config->current['BASE'];
1091       $snap_base      = $tmp['SNAPSHOT_BASE'];
1092       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1093       $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1095       /* Create object */
1096 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1097       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1098       $newName          = preg_replace("/\./", "", $sec."-".$usec);
1099       $target= array();
1100       $target['objectClass']            = array("top", "gosaSnapshotObject");
1101       $target['gosaSnapshotData']       = gzcompress($data, 6);
1102       $target['gosaSnapshotType']       = $type;
1103       $target['gosaSnapshotDN']         = $this->dn;
1104       $target['description']            = $description;
1105       $target['gosaSnapshotTimestamp']  = $newName;
1107       /* Insert the new snapshot 
1108          But we have to check first, if the given gosaSnapshotTimestamp
1109          is already used, in this case we should increment this value till there is 
1110          an unused value. */ 
1111       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1112       $ldap_to->cat($new_dn);
1113       while($ldap_to->count()){
1114         $ldap_to->cat($new_dn);
1115         $newName = preg_replace("/\./", "", $sec."-".($usec++));
1116         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1117         $target['gosaSnapshotTimestamp']  = $newName;
1118       } 
1120       /* Inset this new snapshot */
1121       $ldap_to->cd($snapldapbase);
1122       $ldap_to->create_missing_trees($snapldapbase);
1123       $ldap_to->create_missing_trees($new_base);
1124       $ldap_to->cd($new_dn);
1125       $ldap_to->add($target);
1126     
1127       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1128       show_ldap_error($ldap_to->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1129     }
1130   }
1132   function remove_snapshot($dn)
1133   {
1134     $ui       = get_userinfo();
1135     $old_dn   = $this->dn; 
1136     $this->dn = $dn;
1137     $ldap = $this->config->get_ldap_link();
1138     $ldap->cd($this->config->current['BASE']);
1139     $ldap->rmdir_recursive($dn);
1140     $this->dn = $old_dn;
1141   }
1144   /* returns true if snapshots are enabled, and false if it is disalbed
1145      There will also be some errors psoted, if the configuration failed */
1146   function snapshotEnabled()
1147   {
1148     $tmp = $this->config->current;
1149     if(isset($tmp['ENABLE_SNAPSHOT'])){
1150       if (preg_match("/^true$/i", $tmp['ENABLE_SNAPSHOT']) || preg_match("/yes/i", $tmp['ENABLE_SNAPSHOT'])){
1152         /* Check if the snapshot_base is defined */
1153         if(!isset($tmp['SNAPSHOT_BASE'])){
1154           msg_dialog::display(_("Configuration error"), sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."),"SNAPSHOT_BASE"), ERROR_DIALOG);
1155           return(FALSE);
1156         }
1158         /* check if there are special server configurations for snapshots */
1159         if(isset($tmp['SNAPSHOT_SERVER'])){
1161           /* check if all required vars are available to create a new ldap connection */
1162           $missing = "";
1163           foreach(array("SNAPSHOT_SERVER","SNAPSHOT_USER","SNAPSHOT_PASSWORD","SNAPSHOT_BASE") as $var){
1164             if(!isset($tmp[$var])){
1165               $missing .= $var." ";
1166               msg_dialog::display(_("Configuration error"), sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."), $missing), ERROR_DIALOG);
1167               return(FALSE);
1168             }
1169           }
1170         }
1171         return(TRUE);
1172       }
1173     }
1174     return(FALSE);
1175   }
1178   /* Return available snapshots for the given base 
1179    */
1180   function Available_SnapsShots($dn,$raw = false)
1181   {
1182     if(!$this->snapshotEnabled()) return(array());
1184     /* Create an additional ldap object which
1185        points to our ldap snapshot server */
1186     $ldap= $this->config->get_ldap_link();
1187     $ldap->cd($this->config->current['BASE']);
1188     $cfg= &$this->config->current;
1190     /* check if there are special server configurations for snapshots */
1192     if(isset($cfg['SERVER']) && isset($cfg['SNAPSHOT_SERVER']) && $cfg['SERVER'] == $cfg['SNAPSHOT_SERVER']){
1193       $ldap_to    = $ldap;
1194     }elseif(isset($cfg['SNAPSHOT_SERVER'])){
1195       $server       = $cfg['SNAPSHOT_SERVER'];
1196       $user         = $cfg['SNAPSHOT_USER'];
1197       $password     = $cfg['SNAPSHOT_PASSWORD'];
1198       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1200       $ldap_to      = new LDAP($user,$password, $server);
1201       $ldap_to -> cd ($snapldapbase);
1202       show_ldap_error($ldap->get_error(), sprintf(_("Method get available snapshots with dn '%s' failed."),$this->dn));
1203     }else{
1204       $ldap_to    = $ldap;
1205     }
1207     /* Prepare bases and some other infos */
1208     $base           = $this->config->current['BASE'];
1209     $snap_base      = $cfg['SNAPSHOT_BASE'];
1210     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1211     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1212     $tmp            = array(); 
1214     /* Fetch all objects with  gosaSnapshotDN=$dn */
1215     $ldap_to->cd($new_base);
1216     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1217         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1219     /* Put results into a list and add description if missing */
1220     while($entry = $ldap_to->fetch()){ 
1221       if(!isset($entry['description'][0])){
1222         $entry['description'][0]  = "";
1223       }
1224       $tmp[] = $entry; 
1225     }
1227     /* Return the raw array, or format the result */
1228     if($raw){
1229       return($tmp);
1230     }else{  
1231       $tmp2 = array();
1232       foreach($tmp as $entry){
1233         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1234       }
1235     }
1236     return($tmp2);
1237   }
1240   function getAllDeletedSnapshots($base_of_object,$raw = false)
1241   {
1242     if(!$this->snapshotEnabled()) return(array());
1244     /* Create an additional ldap object which
1245        points to our ldap snapshot server */
1246     $ldap= $this->config->get_ldap_link();
1247     $ldap->cd($this->config->current['BASE']);
1248     $cfg= &$this->config->current;
1250     /* check if there are special server configurations for snapshots */
1251     if(isset($cfg['SNAPSHOT_SERVER'])){
1252       $server       = $cfg['SNAPSHOT_SERVER'];
1253       $user         = $cfg['SNAPSHOT_USER'];
1254       $password     = $cfg['SNAPSHOT_PASSWORD'];
1255       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1256       $ldap_to      = new LDAP($user,$password, $server);
1257       $ldap_to->cd ($snapldapbase);
1258       show_ldap_error($ldap_to->get_error(), sprintf(_("Method get deleted snapshots with dn '%s' failed."),$this->dn));
1259     }else{
1260       $ldap_to    = $ldap;
1261     }
1263     /* Prepare bases */ 
1264     $base           = $this->config->current['BASE'];
1265     $snap_base      = $cfg['SNAPSHOT_BASE'];
1266     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1268     /* Fetch all objects and check if they do not exist anymore */
1269     $ui = get_userinfo();
1270     $tmp = array();
1271     $ldap_to->cd($new_base);
1272     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1273     while($entry = $ldap_to->fetch()){
1275       $chk =  str_replace($new_base,"",$entry['dn']);
1276       if(preg_match("/,ou=/",$chk)) continue;
1278       if(!isset($entry['description'][0])){
1279         $entry['description'][0]  = "";
1280       }
1281       $tmp[] = $entry; 
1282     }
1284     /* Check if entry still exists */
1285     foreach($tmp as $key => $entry){
1286       $ldap->cat($entry['gosaSnapshotDN'][0]);
1287       if($ldap->count()){
1288         unset($tmp[$key]);
1289       }
1290     }
1292     /* Format result as requested */
1293     if($raw) {
1294       return($tmp);
1295     }else{
1296       $tmp2 = array();
1297       foreach($tmp as $key => $entry){
1298         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1299       }
1300     }
1301     return($tmp2);
1302   } 
1305   /* Restore selected snapshot */
1306   function restore_snapshot($dn)
1307   {
1308     if(!$this->snapshotEnabled()) return(array());
1310     $ldap= $this->config->get_ldap_link();
1311     $ldap->cd($this->config->current['BASE']);
1312     $cfg= &$this->config->current;
1314     /* check if there are special server configurations for snapshots */
1315     if(isset($cfg['SNAPSHOT_SERVER'])){
1316       $server       = $cfg['SNAPSHOT_SERVER'];
1317       $user         = $cfg['SNAPSHOT_USER'];
1318       $password     = $cfg['SNAPSHOT_PASSWORD'];
1319       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1320       $ldap_to      = new LDAP($user,$password, $server);
1321       $ldap_to->cd ($snapldapbase);
1322       show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$snapldapbase));
1323     }else{
1324       $ldap_to    = $ldap;
1325     }
1327     /* Get the snapshot */ 
1328     $ldap_to->cat($dn);
1329     $restoreObject = $ldap_to->fetch();
1331     /* Prepare import string */
1332     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1334     /* Import the given data */
1335     $ldap->import_complete_ldif($data,$err,false,false);
1336     show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$dn));
1337   }
1340   function showSnapshotDialog($base,$baseSuffixe)
1341   {
1342     $once = true;
1343     foreach($_POST as $name => $value){
1345       /* Create a new snapshot, display a dialog */
1346       if(preg_match("/^CreateSnapShotDialog_/",$name) && $once){
1347         $once = false;
1348         $entry = preg_replace("/^CreateSnapShotDialog_/","",$name);
1349         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1350         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1351       }
1353       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1354       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1355         $once = false;
1356         $entry = preg_replace("/^RestoreSnapShotDialog_/","",$name);
1357         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1358         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1359         $this->snapDialog->display_restore_dialog = true;
1360       }
1362       /* Restore one of the already deleted objects */
1363       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1364           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1365         $once = false;
1366         $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1367         $this->snapDialog->set_snapshot_bases($baseSuffixe);
1368         $this->snapDialog->display_restore_dialog      = true;
1369         $this->snapDialog->display_all_removed_objects  = true;
1370       }
1372       /* Restore selected snapshot */
1373       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1374         $once = false;
1375         $entry = preg_replace("/^RestoreSnapShot_/","",$name);
1376         $entry = base64_decode(trim(preg_replace("/_[xy]$/","",$entry)));
1377         if(!empty($entry)){
1378           $this->restore_snapshot($entry);
1379           $this->snapDialog = NULL;
1380         }
1381       }
1382     }
1384     /* Create a new snapshot requested, check
1385        the given attributes and create the snapshot*/
1386     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1387       $this->snapDialog->save_object();
1388       $msgs = $this->snapDialog->check();
1389       if(count($msgs)){
1390         foreach($msgs as $msg){
1391           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
1392         }
1393       }else{
1394         $this->dn =  $this->snapDialog->dn;
1395         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1396         $this->snapDialog = NULL;
1397       }
1398     }
1400     /* Restore is requested, restore the object with the posted dn .*/
1401     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1402     }
1404     if(isset($_POST['CancelSnapshot'])){
1405       $this->snapDialog = NULL;
1406     }
1408     if(is_object($this->snapDialog )){
1409       $this->snapDialog->save_object();
1410       return($this->snapDialog->execute());
1411     }
1412   }
1415   static function plInfo()
1416   {
1417     return array();
1418   }
1421   function set_acl_base($base)
1422   {
1423     $this->acl_base= $base;
1424   }
1427   function set_acl_category($category)
1428   {
1429     $this->acl_category= "$category/";
1430   }
1433   function acl_is_writeable($attribute,$skip_write = FALSE)
1434   {
1435     $ui= get_userinfo();
1436     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1437   }
1440   function acl_is_readable($attribute)
1441   {
1442     $ui= get_userinfo();
1443     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1444   }
1447   function acl_is_createable()
1448   {
1449     $ui= get_userinfo();
1450     return preg_match('/c/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1451   }
1454   function acl_is_removeable()
1455   {
1456     $ui= get_userinfo();
1457     return preg_match('/d/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1458   }
1461   function acl_is_moveable()
1462   {
1463     $ui= get_userinfo();
1464     return preg_match('/m/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1465   }
1468   function acl_have_any_permissions()
1469   {
1470   }
1473   function getacl($attribute,$skip_write= FALSE)
1474   {
1475     $ui= get_userinfo();
1476     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1477   }
1479   /* Get all allowed bases to move an object to or to create a new object.
1480      Idepartments also contains all base departments which lead to the allowed bases */
1481   function get_allowed_bases($category = "")
1482   {
1483     $ui = get_userinfo();
1484     $deps = array();
1486     /* Set category */ 
1487     if(empty($category)){
1488       $category = $this->acl_category.get_class($this);
1489     }
1491     /* Is this a new object ? Or just an edited existing object */
1492     if(!$this->initially_was_account && $this->is_account){
1493       $new = true;
1494     }else{
1495       $new = false;
1496     }
1498     $cat_bases = $ui->get_module_departments(preg_replace("/\/.*$/","",$category));
1499     foreach($this->config->idepartments as $dn => $name){
1500       
1501       if(!in_array_ics($dn,$cat_bases)){
1502         continue;
1503       }
1504       
1505       $acl = $ui->get_permissions($dn,$category);
1506       if($new && preg_match("/c/",$acl)){
1507         $deps[$dn] = $name;
1508       }elseif(!$new && preg_match("/m/",$acl)){
1509         $deps[$dn] = $name;
1510       }
1511     }
1513     /* Add current base */      
1514     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1515       $deps[$this->base] = $this->config->idepartments[$this->base];
1516     }else{
1517       echo "No default base found. ".$this->base."<br> ";
1518     }
1520     return($deps);
1521   }
1523   /* This function modifies object acls too, if an object is moved.
1524    *  $old_dn   specifies the actually used dn
1525    *  $new_dn   specifies the destiantion dn
1526    */
1527   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1528   {
1529     /* Check if old_dn is empty. This should never happen */
1530     if(empty($old_dn) || empty($new_dn)){
1531       trigger_error("Failed to check acl dependencies, wrong dn given.");
1532       return;
1533     }
1535     /* Update userinfo if necessary */
1536     $ui = session::get('ui');
1537     if($ui->dn == $old_dn){
1538       $ui->dn = $new_dn;
1539       session::set('ui',$ui);
1540       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current user dn from '".$old_dn."' to '".$new_dn."'");
1541     }
1543     /* Object was moved, ensure that all acls will be moved too */
1544     if($new_dn != $old_dn && $old_dn != "new"){
1546       /* get_ldap configuration */
1547       $update = array();
1548       $ldap = $this->config->get_ldap_link();
1549       $ldap->cd ($this->config->current['BASE']);
1550       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*))",array("cn","gosaAclEntry"));
1551       while($attrs = $ldap->fetch()){
1553         $acls = array();
1555         /* Walk through acls */
1556         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1558           /* Reset vars */
1559           $found = false;
1561           /* Get Acl parts */
1562           $acl_parts = split(":",$attrs['gosaAclEntry'][$i]);
1564           /* Get every single member for this acl */  
1565           $members = array();  
1566           if(preg_match("/,/",$acl_parts[2])){
1567             $members = split(",",$acl_parts[2]);
1568           }else{
1569             $members = array($acl_parts[2]);
1570           } 
1571       
1572           /* Check if member match current dn */
1573           foreach($members as $key => $member){
1574             $member = base64_decode($member);
1575             if($member == $old_dn){
1576               $found = true;
1577               $members[$key] = base64_encode($new_dn);
1578             }
1579           } 
1580          
1581           /* Create new member string */ 
1582           $new_members = "";
1583           foreach($members as $member){
1584             $new_members .= $member.",";
1585           }
1586           $new_members = preg_replace("/,$/","",$new_members);
1587           $acl_parts[2] = $new_members;
1588         
1589           /* Reconstruckt acl entry */
1590           $acl_str  ="";
1591           foreach($acl_parts as $t){
1592            $acl_str .= $t.":";
1593           }
1594           $acl_str = preg_replace("/:$/","",$acl_str);
1595        }
1597        /* Acls for this object must be adjusted */
1598        if($found){
1600           if($output_changes){
1601             echo "<font color='green'>".
1602                   _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1603                   $old_dn.
1604                   "</b><br>&nbsp;-"._("to")."&nbsp;<b>".
1605                   $new_dn.
1606                   "</b></font><br>";
1607           }
1608           $update[$attrs['dn']] =array();
1609           foreach($acls as $acl){
1610             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1611           }
1612         }
1613       }
1615       /* Write updated acls */
1616       foreach($update as $dn => $attrs){
1617         $ldap->cd($dn);
1618         $ldap->modify($attrs);
1619       }
1620     }
1621   }
1623   
1625   /* This function enables the entry Serial ID check.
1626    * If an entry was edited while we have edited the entry too,
1627    *  an error message will be shown. 
1628    * To configure this check correctly read the FAQ.
1629    */    
1630   function enable_CSN_check()
1631   {
1632     $this->CSN_check_active =TRUE;
1633     $this->entryCSN = getEntryCSN($this->dn);
1634   }
1637   /*! \brief  Prepares the plugin to be used for multiple edit
1638    *          Update plugin attributes with given array of attribtues.
1639    *  @param  array   Array with attributes that must be updated.
1640    */
1641   function init_multiple_support($attrs,$all)
1642   {
1643     $ldap= $this->config->get_ldap_link();
1644     $this->multi_attrs    = $attrs;
1645     $this->multi_attrs_all= $all;
1647     /* Copy needed attributes */
1648     foreach ($this->attributes as $val){
1649       $found= array_key_ics($val, $this->multi_attrs);
1650       if ($found != ""){
1651         if(isset($this->multi_attrs["$found"][0])){
1652           $this->$val= $this->multi_attrs["$found"][0];
1653         }
1654       }
1655     }
1656   }
1658  
1659   /*! \brief  Enables multiple support for this plugin
1660    */
1661   function enable_multiple_support()
1662   {
1663     $this->ignore_account = TRUE;
1664     $this->multiple_support_active = TRUE;
1665   }
1668   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1669       @return array Cotaining all mdofied values. 
1670    */
1671   function get_multi_edit_values()
1672   {
1673     $ret = array();
1674     foreach($this->attributes as $attr){
1675       if(in_array($attr,$this->multi_boxes)){
1676         $ret[$attr] = $this->$attr;
1677       }
1678     }
1679     return($ret);
1680   }
1682   
1683   /*! \brief  Update class variables with values collected by multiple edit.
1684    */
1685   function set_multi_edit_values($attrs)
1686   {
1687     foreach($attrs as $name => $value){
1688       $this->$name = $value;
1689     }
1690   }
1693   /*! \brief execute plugin
1695     Generates the html output for this node
1696    */
1697   function multiple_execute()
1698   {
1699     /* This one is empty currently. Fabian - please fill in the docu code */
1700     session::set('current_class_for_help',get_class($this));
1702     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1703     session::set('LOCK_VARS_TO_USE',array());
1704     session::set('LOCK_VARS_USED',array());
1705     
1706     return("Multiple edit is currently not implemented for this plugin.");
1707   }
1710   /*! \brief   Save HTML posted data to object for multiple edit
1711    */
1712   function multiple_save_object()
1713   {
1714     if(empty($this->entryCSN) && $this->CSN_check_active){
1715       $this->entryCSN = getEntryCSN($this->dn);
1716     }
1718     /* Save values to object */
1719     $this->multi_boxes = array();
1720     foreach ($this->attributes as $val){
1721   
1722       /* Get selected checkboxes from multiple edit */
1723       if(isset($_POST["use_".$val])){
1724         $this->multi_boxes[] = $val;
1725       }
1727       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
1729         /* Check for modifications */
1730         if (get_magic_quotes_gpc()) {
1731           $data= stripcslashes($_POST["$val"]);
1732         } else {
1733           $data= $this->$val = $_POST["$val"];
1734         }
1735         if ($this->$val != $data){
1736           $this->is_modified= TRUE;
1737         }
1738     
1739         /* IE post fix */
1740         if(isset($data[0]) && $data[0] == chr(194)) {
1741           $data = "";  
1742         }
1743         $this->$val= $data;
1744       }
1745     }
1746   }
1749   /*! \brief  Returns all attributes of this plugin, 
1750                to be able to detect multiple used attributes 
1751                in multi_plugg::detect_multiple_used_attributes().
1752       @return array Attributes required for intialization of multi_plug
1753    */
1754   public function get_multi_init_values()
1755   {
1756     $attrs = $this->attrs;
1757     return($attrs);
1758   }
1761   /*! \brief  Check given values in multiple edit
1762       @return array Error messages
1763    */
1764   function multiple_check()
1765   {
1766     $message = plugin::check();
1767     return($message);
1768   }
1771 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1772 ?>