Code

Added set of common plugin options to handle next generation
[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 $new= TRUE;
109   var $saved_attributes= array();
111   /* Plugin identifier */
112   var $pl_object_name= "";
113   var $pl_provided_acls= array();
114   var $pl_self_modify= FALSE;
115   var $pl_options= array();
116   var $pl_section= "";
117   var $pl_task= array();
118   var $pl_priority= 0;
119   var $pl_depends= array();
120   var $pl_conflicts= array();
122   /*! \brief plugin constructor
124     If 'dn' is set, the node loads the given 'dn' from LDAP
126     \param dn Distinguished name to initialize plugin from
127     \sa plugin()
128    */
129   function plugin ($config, $dn= NULL)
130   {
131     /* Configuration is fine, allways */
132     $this->config= $config;     
133     $this->dn= $dn;
135     /* Handle new accounts, don't read information from LDAP */
136     if ($dn == "new"){
137       return;
138     }
140     /* Get LDAP descriptor */
141     $ldap= $this->config->get_ldap_link();
142     if ($dn != NULL){
144       /* Load data to 'attrs' and save 'dn' */
145       $ldap->cat ($dn);
146       $this->attrs= $ldap->fetch();
148       /* Copy needed attributes */
149       foreach ($this->attributes as $val){
150         $found= array_key_ics($val, $this->attrs);
151         if ($found != ""){
152           $this->$val= $this->attrs["$found"][0];
153         }
154       }
156       /* gosaUnitTag loading... */
157       if (isset($this->attrs['gosaUnitTag'][0])){
158         $this->gosaUnitTag= $this->attrs['gosaUnitTag'][0];
159       }
161       /* Set the template flag according to the existence of objectClass
162          gosaUserTemplate */
163       if (isset($this->attrs['objectClass'])){
164         if (in_array ("gosaUserTemplate", $this->attrs['objectClass'])){
165           $this->is_template= TRUE;
166           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
167               "found", "Template check");
168         }
169       }
171       /* Is Account? */
172       error_reporting(0);
173       $found= TRUE;
174       foreach ($this->objectclasses as $obj){
175         if (preg_match('/top/i', $obj)){
176           continue;
177         }
178         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
179           $found= FALSE;
180           break;
181         }
182       }
183       error_reporting(E_ALL);
184       if ($found){
185         $this->is_account= TRUE;
186         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
187             "found", "Object check");
188       }
190       /* Prepare saved attributes */
191       $this->saved_attributes= $this->attrs;
192       foreach ($this->saved_attributes as $index => $value){
193         if (preg_match('/^[0-9]+$/', $index)){
194           unset($this->saved_attributes[$index]);
195           continue;
196         }
197         if (!in_array($index, $this->attributes) && $index != "objectClass"){
198           unset($this->saved_attributes[$index]);
199           continue;
200         }
201         if ($this->saved_attributes[$index]["count"] == 1){
202           $tmp= $this->saved_attributes[$index][0];
203           unset($this->saved_attributes[$index]);
204           $this->saved_attributes[$index]= $tmp;
205           continue;
206         }
208         unset($this->saved_attributes["$index"]["count"]);
209       }
210     }
212     /* Save initial account state */
213     $this->initially_was_account= $this->is_account;
214   }
216   /*! \brief execute plugin
218     Generates the html output for this node
219    */
220   function execute()
221   {
222     # This one is empty currently. Fabian - please fill in the docu code
223     $_SESSION['current_class_for_help'] = get_class($this);
224     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
225     $_SESSION['LOCK_VARS_TO_USE'] =array();
226   }
228   /*! \brief execute plugin
229      Removes object from parent
230    */
231   function remove_from_parent()
232   {
233     /* include global link_info */
234     $ldap= $this->config->get_ldap_link();
236     /* Get current objectClasses in order to add the required ones */
237     $ldap->cat($this->dn);
238     $tmp= $ldap->fetch ();
239     if (isset($tmp['objectClass'])){
240       $oc= $tmp['objectClass'];
241     } else {
242       $oc= array("count" => 0);
243     }
245     /* Remove objectClasses from entry */
246     $ldap->cd($this->dn);
247     $this->attrs= array();
248     $this->attrs['objectClass']= array();
249     for ($i= 0; $i<$oc["count"]; $i++){
250       if (!in_array_ics($oc[$i], $this->objectclasses)){
251         $this->attrs['objectClass'][]= $oc[$i];
252       }
253     }
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 (chkacl ($this->acl, "$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       }
300     }
301   }
304   /* Save data to LDAP, depending on is_account we save or delete */
305   function save()
306   {
307     /* include global link_info */
308     $ldap= $this->config->get_ldap_link();
310     /* Start with empty array */
311     $this->attrs= array();
313     /* Get current objectClasses in order to add the required ones */
314     $ldap->cat($this->dn);
315     
316     $tmp= $ldap->fetch ();
317     
318     if (isset($tmp['objectClass'])){
319       $oc= $tmp["objectClass"];
320       $this->new= FALSE;
321     } else {
322       $oc= array("count" => 0);
323       $this->new= TRUE;
324     }
326     /* Load (minimum) attributes, add missing ones */
327     $this->attrs['objectClass']= $this->objectclasses;
328     for ($i= 0; $i<$oc["count"]; $i++){
329       if (!in_array_ics($oc[$i], $this->objectclasses)){
330         $this->attrs['objectClass'][]= $oc[$i];
331       }
332     }
334     /* Copy standard attributes */
335     foreach ($this->attributes as $val){
336       if ($this->$val != ""){
337         $this->attrs["$val"]= $this->$val;
338       } elseif (!$this->new) {
339         $this->attrs["$val"]= array();
340       }
341     }
343   }
346   function cleanup()
347   {
348     foreach ($this->attrs as $index => $value){
350       /* Convert arrays with one element to non arrays, if the saved
351          attributes are no array, too */
352       if (is_array($this->attrs[$index]) && 
353           count ($this->attrs[$index]) == 1 &&
354           isset($this->saved_attributes[$index]) &&
355           !is_array($this->saved_attributes[$index])){
356           
357         $tmp= $this->attrs[$index][0];
358         $this->attrs[$index]= $tmp;
359       }
361       /* Remove emtpy arrays if they do not differ */
362       if (is_array($this->attrs[$index]) &&
363           count($this->attrs[$index]) == 0 &&
364           !isset($this->saved_attributes[$index])){
365           
366         unset ($this->attrs[$index]);
367         continue;
368       }
370       /* Remove single attributes that do not differ */
371       if (!is_array($this->attrs[$index]) &&
372           isset($this->saved_attributes[$index]) &&
373           !is_array($this->saved_attributes[$index]) &&
374           $this->attrs[$index] == $this->saved_attributes[$index]){
376         unset ($this->attrs[$index]);
377         continue;
378       }
380       /* Remove arrays that do not differ */
381       if (is_array($this->attrs[$index]) && 
382           isset($this->saved_attributes[$index]) &&
383           is_array($this->saved_attributes[$index])){
384           
385         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
386           unset ($this->attrs[$index]);
387           continue;
388         }
389       }
390     }
391   }
393   /* Check formular input */
394   function check()
395   {
396     $message= array();
398     /* Skip if we've no config object */
399     if (!isset($this->config)){
400       return $message;
401     }
403     /* Find hooks entries for this class */
404     $command= search_config($this->config->data['MENU'], get_class($this), "CHECK");
405     if ($command == "" && isset($this->config->data['TABS'])){
406       $command= search_config($this->config->data['TABS'], get_class($this), "CHECK");
407     }
409     if ($command != ""){
411       if (!check_command($command)){
412         $message[]= sprintf(_("Command '%s', specified as CHECK hook for plugin '%s' doesn't seem to exist."), $command,
413                             get_class($this));
414       } else {
416         /* Generate "ldif" for check hook */
417         $ldif= "dn: $this->dn\n";
418         
419         /* ... objectClasses */
420         foreach ($this->objectclasses as $oc){
421           $ldif.= "objectClass: $oc\n";
422         }
423         
424         /* ... attributes */
425         foreach ($this->attributes as $attr){
426           if ($this->$attr == ""){
427             continue;
428           }
429           if (is_array($this->$attr)){
430             foreach ($this->$attr as $val){
431               $ldif.= "$attr: $val\n";
432             }
433           } else {
434               $ldif.= "$attr: ".$this->$attr."\n";
435           }
436         }
438         /* Append empty line */
439         $ldif.= "\n";
441         /* Feed "ldif" into hook and retrieve result*/
442         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
443         $fh= proc_open($command, $descriptorspec, $pipes);
444         if (is_resource($fh)) {
445           fwrite ($pipes[0], $ldif);
446           fclose($pipes[0]);
447           
448           $result= stream_get_contents($pipes[1]);
449           if ($result != ""){
450             $message[]= $result;
451           }
452           
453           fclose($pipes[1]);
454           fclose($pipes[2]);
455           proc_close($fh);
456         }
457       }
459     }
461     return ($message);
462   }
464   /* Adapt from template, using 'dn' */
465   function adapt_from_template($dn)
466   {
467     /* Include global link_info */
468     $ldap= $this->config->get_ldap_link();
470     /* Load requested 'dn' to 'attrs' */
471     $ldap->cat ($dn);
472     $this->attrs= $ldap->fetch();
474     /* Walk through attributes */
475     foreach ($this->attributes as $val){
477       if (isset($this->attrs["$val"][0])){
479         /* If attribute is set, replace dynamic parts: 
480            %sn, %givenName and %uid. Fill these in our local variables. */
481         $value= $this->attrs["$val"][0];
483         foreach (array("sn", "givenName", "uid") as $repl){
484           if (preg_match("/%$repl/i", $value)){
485             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
486           }
487         }
488         $this->$val= $value;
489       }
490     }
492     /* Is Account? */
493     $found= TRUE;
494     foreach ($this->objectclasses as $obj){
495       if (preg_match('/top/i', $obj)){
496         continue;
497       }
498       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
499         $found= FALSE;
500         break;
501       }
502     }
503     if ($found){
504       $this->is_account= TRUE;
505     }
506   }
508   /* Indicate whether a password change is needed or not */
509   function password_change_needed()
510   {
511     return FALSE;
512   }
514   /* Show header message for tab dialogs */
515   function show_header($button_text, $text, $disabled= FALSE)
516   {
517     if ($disabled == TRUE){
518       $state= "disabled";
519     } else {
520       $state= "";
521     }
522     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
523     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
524       chkacl($this->acl, "all")." ".$state.
525       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
527     return($display);
528   }
530   function postcreate($add_attrs= array())
531   {
532     /* Find postcreate entries for this class */
533     $command= search_config($this->config->data['MENU'], get_class($this), "POSTCREATE");
534     if ($command == "" && isset($this->config->data['TABS'])){
535       $command= search_config($this->config->data['TABS'], get_class($this), "POSTCREATE");
536     }
538     if ($command != ""){
539       /* Walk through attribute list */
540       foreach ($this->attributes as $attr){
541         if (!is_array($this->$attr)){
542           $command= preg_replace("/%$attr/", $this->$attr, $command);
543         }
544       }
545       $command= preg_replace("/%dn/", $this->dn, $command);
547       /* Additional attributes */
548       foreach ($add_attrs as $name => $value){
549         $command= preg_replace("/%$name/", $value, $command);
550       }
552       if (check_command($command)){
553         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
554             $command, "Execute");
556         exec($command);
557       } else {
558         $message= sprintf(_("Command '%s', specified as POSTCREATE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
559         print_red ($message);
560       }
561     }
562   }
564   function postmodify($add_attrs= array())
565   {
566     /* Find postcreate entries for this class */
567     $command= search_config($this->config->data['MENU'], get_class($this), "POSTMODIFY");
568     if ($command == "" && isset($this->config->data['TABS'])){
569       $command= search_config($this->config->data['TABS'], get_class($this), "POSTMODIFY");
570     }
572     if ($command != ""){
573       /* Walk through attribute list */
574       foreach ($this->attributes as $attr){
575         if (!is_array($this->$attr)){
576           $command= preg_replace("/%$attr/", $this->$attr, $command);
577         }
578       }
579       $command= preg_replace("/%dn/", $this->dn, $command);
581       /* Additional attributes */
582       foreach ($add_attrs as $name => $value){
583         $command= preg_replace("/%$name/", $value, $command);
584       }
586       if (check_command($command)){
587         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
588             $command, "Execute");
590         exec($command);
591       } else {
592         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, get_class($this));
593         print_red ($message);
594       }
595     }
596   }
598   function postremove($add_attrs= array())
599   {
600     /* Find postremove entries for this class */
601     $command= search_config($this->config->data['MENU'], get_class($this), "POSTREMOVE");
602     if ($command == "" && isset($this->config->data['TABS'])){
603       $command= search_config($this->config->data['TABS'], get_class($this), "POSTREMOVE");
604     }
606     if ($command != ""){
607       /* Walk through attribute list */
608       foreach ($this->attributes as $attr){
609         if (!is_array($this->$attr)){
610           $command= preg_replace("/%$attr/", $this->$attr, $command);
611         }
612       }
613       $command= preg_replace("/%dn/", $this->dn, $command);
615       /* Additional attributes */
616       foreach ($add_attrs as $name => $value){
617         $command= preg_replace("/%$name/", $value, $command);
618       }
620       if (check_command($command)){
621         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
622             $command, "Execute");
624         exec($command);
625       } else {
626         $message= sprintf(_("Command '%s', specified as POSTREMOVE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
627         print_red ($message);
628       }
629     }
630   }
632   /* Create unique DN */
633   function create_unique_dn($attribute, $base)
634   {
635     $ldap= $this->config->get_ldap_link();
636     $base= preg_replace("/^,*/", "", $base);
638     /* Try to use plain entry first */
639     $dn= "$attribute=".$this->$attribute.",$base";
640     $ldap->cat ($dn, array('dn'));
641     if (!$ldap->fetch()){
642       return ($dn);
643     }
645     /* Look for additional attributes */
646     foreach ($this->attributes as $attr){
647       if ($attr == $attribute || $this->$attr == ""){
648         continue;
649       }
651       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
652       $ldap->cat ($dn, array('dn'));
653       if (!$ldap->fetch()){
654         return ($dn);
655       }
656     }
658     /* None found */
659     return ("none");
660   }
662   function rebind($ldap, $referral)
663   {
664     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
665     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
666       $this->error = "Success";
667       $this->hascon=true;
668       $this->reconnect= true;
669       return (0);
670     } else {
671       $this->error = "Could not bind to " . $credentials['ADMIN'];
672       return NULL;
673     }
674   }
676   /* This is a workaround function. */
677   function copy($src_dn, $dst_dn)
678   {
679     /* Rename dn in possible object groups */
680     $ldap= $this->config->get_ldap_link();
681     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::fix($src_dn).'))',
682         array('cn'));
683     while ($attrs= $ldap->fetch()){
684       $og= new ogroup($this->config, $ldap->getDN());
685       unset($og->member[$src_dn]);
686       $og->member[$dst_dn]= $dst_dn;
687       $og->save ();
688     }
690     $ldap->cat($dst_dn);
691     $attrs= $ldap->fetch();
692     if (count($attrs)){
693       trigger_error("Trying to overwrite ".@LDAP::fix($dst_dn).", which already exists.",
694           E_USER_WARNING);
695       return (FALSE);
696     }
698     $ldap->cat($src_dn);
699     $attrs= $ldap->fetch();
700     if (!count($attrs)){
701       trigger_error("Trying to move ".@LDAP::fix($src_dn).", which does not seem to exist.",
702           E_USER_WARNING);
703       return (FALSE);
704     }
706     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
707     $ds= ldap_connect($this->config->current['SERVER']);
708     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
709     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
710       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
711     }
713     $r=ldap_bind($ds,$this->config->current['ADMIN'], $this->config->current['PASSWORD']);
714     error_reporting (0);
715     $sr=ldap_read($ds, @LDAP::fix($src_dn), "objectClass=*");
717     /* Fill data from LDAP */
718     $new= array();
719     if ($sr) {
720       $ei=ldap_first_entry($ds, $sr);
721       if ($ei) {
722         foreach($attrs as $attr => $val){
723           if ($info = ldap_get_values_len($ds, $ei, $attr)){
724             for ($i= 0; $i<$info['count']; $i++){
725               if ($info['count'] == 1){
726                 $new[$attr]= $info[$i];
727               } else {
728                 $new[$attr][]= $info[$i];
729               }
730             }
731           }
732         }
733       }
734     }
736     /* close conncetion */
737     error_reporting (E_ALL);
738     ldap_unbind($ds);
740     /* Adapt naming attribute */
741     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
742     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
743     $new[$dst_name]= @LDAP::fix($dst_val);
745     /* Check if this is a department.
746      * If it is a dep. && there is a , override in his ou 
747      *  change \2C to , again, else this entry can't be saved ...
748      */
749     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
750       $new['ou'] = preg_replace("/\\\\,/",",",$new['ou']);
751     }
753     /* Save copy */
754     $ldap->connect();
755     $ldap->cd($this->config->current['BASE']);
756     
757     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
759     /* FAIvariable=.../..., cn=.. 
760         could not be saved, because the attribute FAIvariable was different to 
761         the dn FAIvariable=..., cn=... */
762     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
763       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
764     }
765     $ldap->cd($dst_dn);
766     $ldap->add($new);
768     if ($ldap->error != "Success"){
769       trigger_error("Trying to save $dst_dn failed.",
770           E_USER_WARNING);
771       return(FALSE);
772     }
774     return (TRUE);
775   }
778   function move($src_dn, $dst_dn)
779   {
780     /* Copy source to destination */
781     if (!$this->copy($src_dn, $dst_dn)){
782       return (FALSE);
783     }
785     /* Delete source */
786     $ldap= $this->config->get_ldap_link();
787     $ldap->rmdir($src_dn);
788     if ($ldap->error != "Success"){
789       trigger_error("Trying to delete $src_dn failed.",
790           E_USER_WARNING);
791       return (FALSE);
792     }
794     return (TRUE);
795   }
798   /* Move/Rename complete trees */
799   function recursive_move($src_dn, $dst_dn)
800   {
801     /* Check if the destination entry exists */
802     $ldap= $this->config->get_ldap_link();
804     /* Check if destination exists - abort */
805     $ldap->cat($dst_dn, array('dn'));
806     if ($ldap->fetch()){
807       trigger_error("recursive_move $dst_dn already exists.",
808           E_USER_WARNING);
809       return (FALSE);
810     }
812     /* Perform a search for all objects to be moved */
813     $objects= array();
814     $ldap->cd($src_dn);
815     $ldap->search("(objectClass=*)", array("dn"));
816     while($attrs= $ldap->fetch()){
817       $dn= $attrs['dn'];
818       $objects[$dn]= strlen($dn);
819     }
821     /* Sort objects by indent level */
822     asort($objects);
823     reset($objects);
825     /* Copy objects from small to big indent levels by replacing src_dn by dst_dn */
826     foreach ($objects as $object => $len){
827       $src= $object;
828       $dst= preg_replace("/$src_dn$/", "$dst_dn", $object);
829       if (!$this->copy($src, $dst)){
830         return (FALSE);
831       }
832     }
834     /* Remove src_dn */
835     $ldap->cd($src_dn);
836     $ldap->recursive_remove();
837     return (TRUE);
838   }
841   function handle_post_events($mode, $add_attrs= array())
842   {
843     switch ($mode){
844       case "add":
845         $this->postcreate($add_attrs);
846       break;
848       case "modify":
849         $this->postmodify($add_attrs);
850       break;
852       case "remove":
853         $this->postremove($add_attrs);
854       break;
855     }
856   }
859   function saveCopyDialog(){
860   }
863   function getCopyDialog(){
864     return(array("string"=>"","status"=>""));
865   }
868   function PrepareForCopyPaste($source){
869     $todo = $this->attributes;
870     if(isset($this->CopyPasteVars)){
871       $todo = array_merge($todo,$this->CopyPasteVars);
872     }
873     $todo[] = "is_account";
874     foreach($todo as $var){
875       $this->$var = $source->$var;
876     }
877   }
880   function handle_object_tagging($dn= "", $tag= "", $show= false)
881   {
882     //FIXME: How to optimize this? We have at least two
883     //       LDAP accesses per object. It would be a good
884     //       idea to have it integrated.
886     /* No dn? Self-operation... */
887     if ($dn == ""){
888       $dn= $this->dn;
890       /* No tag? Find it yourself... */
891       if ($tag == ""){
892         $len= strlen($dn);
894         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
895         $relevant= array();
896         foreach ($this->config->adepartments as $key => $ntag){
898           /* This one is bigger than our dn, its not relevant... */
899           if ($len <= strlen($key)){
900             continue;
901           }
903           /* This one matches with the latter part. Break and don't fix this entry */
904           if (preg_match('/(^|,)'.normalizePreg($key).'$/', $dn)){
905             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
906             $relevant[strlen($key)]= $ntag;
907             continue;
908           }
910         }
912         /* If we've some relevant tags to set, just get the longest one */
913         if (count($relevant)){
914           ksort($relevant);
915           $tmp= array_keys($relevant);
916           $idx= end($tmp);
917           $tag= $relevant[$idx];
918           $this->gosaUnitTag= $tag;
919         }
920       }
921     }
924     /* Set tag? */
925     if ($tag != ""){
926       /* Set objectclass and attribute */
927       $ldap= $this->config->get_ldap_link();
928       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
929       $attrs= $ldap->fetch();
930       if(isset($attrs['gosaUnitTag'][0]) && $attrs['gosaUnitTag'][0] == $tag){
931         if ($show) {
932           echo sprintf(_("Object '%s' is already tagged"), @LDAP::fix($dn))."<br>";
933           flush();
934         }
935         return;
936       }
937       if (count($attrs)){
938         if ($show){
939           echo sprintf(_("Adding tag (%s) to object '%s'"), $tag, @LDAP::fix($dn))."<br>";
940           flush();
941         }
942         $nattrs= array("gosaUnitTag" => $this->gosaUnitTag);
943         $nattrs['objectClass']= array();
944         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
945           $oc= $attrs['objectClass'][$i];
946           if ($oc != "gosaAdministrativeUnitTag"){
947             $nattrs['objectClass'][]= $oc;
948           }
949         }
950         $nattrs['objectClass'][]= "gosaAdministrativeUnitTag";
951         $ldap->cd($dn);
952         $ldap->modify($nattrs);
953         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
954       } else {
955         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not tagging ($tag) $dn - seems to have moved away", "Tagging");
956       }
958     } else {
959       /* Remove objectclass and attribute */
960       $ldap= $this->config->get_ldap_link();
961       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
962       $attrs= $ldap->fetch();
963       if (isset($attrs['objectClass']) && !in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass'])){
964         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "$dn is not tagged", "Tagging");
965         return;
966       }
967       if (count($attrs)){
968         if ($show){
969           echo sprintf(_("Removing tag from object '%s'"), @LDAP::fix($dn))."<br>";
970           flush();
971         }
972         $nattrs= array("gosaUnitTag" => array());
973         $nattrs['objectClass']= array();
974         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
975           $oc= $attrs['objectClass'][$i];
976           if ($oc != "gosaAdministrativeUnitTag"){
977             $nattrs['objectClass'][]= $oc;
978           }
979         }
980         $ldap->cd($dn);
981         $ldap->modify($nattrs);
982         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
983       } else {
984         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not removing tag ($tag) $dn - seems to have moved away", "Tagging");
985       }
986     }
988   }
991   /* Add possibility to stop remove process */
992   function allow_remove()
993   {
994     $reason= "";
995     return $reason;
996   }
999   /* Create a snapshot of the current object */
1000   function create_snapshot($type= "snapshot", $description= array())
1001   {
1003     /* Check if snapshot functionality is enabled */
1004     if(!$this->snapshotEnabled()){
1005       return;
1006     }
1008     /* Get configuration from gosa.conf */
1009     $tmp = $this->config->current;
1011     /* Create lokal ldap connection */
1012     $ldap= $this->config->get_ldap_link();
1013     $ldap->cd($this->config->current['BASE']);
1015     /* check if there are special server configurations for snapshots */
1016     if(!isset($tmp['SNAPSHOT_SERVER'])){
1018       /* Source and destination server are both the same, just copy source to dest obj */
1019       $ldap_to      = $ldap;
1020       $snapldapbase = $this->config->current['BASE'];
1022     }else{
1023       $server         = $tmp['SNAPSHOT_SERVER'];
1024       $user           = $tmp['SNAPSHOT_USER'];
1025       $password       = $tmp['SNAPSHOT_PASSWORD'];
1026       $snapldapbase   = $tmp['SNAPSHOT_LDAP_BASE'];
1028       $ldap_to        = new LDAP($user,$password, $server);
1029       $ldap_to -> cd($snapldapbase);
1030       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$snapldapbase));
1031     }
1033     /* check if the dn exists */ 
1034     if ($ldap->dn_exists($this->dn)){
1036       /* Extract seconds & mysecs, they are used as entry index */
1037       list($usec, $sec)= explode(" ", microtime());
1039       /* Collect some infos */
1040       $base           = $this->config->current['BASE'];
1041       $snap_base      = $tmp['SNAPSHOT_BASE'];
1042       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1043       $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1045       /* Create object */
1046 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1047       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1048       $newName          = preg_replace("/\./", "", $sec."-".$usec);
1049       $target= array();
1050       $target['objectClass']            = array("top", "gosaSnapshotObject");
1051       $target['gosaSnapshotData']       = gzcompress($data, 6);
1052       $target['gosaSnapshotType']       = $type;
1053       $target['gosaSnapshotDN']         = $this->dn;
1054       $target['description']            = $description;
1055       $target['gosaSnapshotTimestamp']  = $newName;
1057       /* Insert the new snapshot 
1058          But we have to check first, if the given gosaSnapshotTimestamp
1059          is already used, in this case we should increment this value till there is 
1060          an unused value. */ 
1061       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1062       $ldap_to->cat($new_dn);
1063       while($ldap_to->count()){
1064         $ldap_to->cat($new_dn);
1065         $newName = preg_replace("/\./", "", $sec."-".($usec++));
1066         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1067         $target['gosaSnapshotTimestamp']  = $newName;
1068       } 
1070       /* Inset this new snapshot */
1071       $ldap_to->cd($snapldapbase);
1072       $ldap_to->create_missing_trees($new_base);
1073       $ldap_to->cd($new_dn);
1074       $ldap_to->add($target);
1076       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1077       show_ldap_error($ldap_to->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1078     }
1079   }
1081   function remove_snapshot($dn)
1082   {
1083     $ui   = get_userinfo();
1084     $acl  = get_permissions ($dn, $ui->subtreeACL);
1085     $acl  = get_module_permission($acl, "snapshot", $dn);
1087     if (chkacl($this->acl, "delete") == ""){
1088     $ldap = $this->config->get_ldap_link();
1089     $ldap->cd($this->config->current['BASE']);
1090     $ldap->rmdir_recursive($dn);
1091     }else{
1092       print_red (_("You are not allowed to delete this snap shot!"));
1093     }
1094   }
1097   /* returns true if snapshots are enabled, and false if it is disalbed
1098      There will also be some errors psoted, if the configuration failed */
1099   function snapshotEnabled()
1100   {
1101     $tmp = $this->config->current;
1102     if(isset($tmp['ENABLE_SNAPSHOT'])){
1103       if (preg_match("/^true$/i", $tmp['ENABLE_SNAPSHOT']) || preg_match("/yes/i", $tmp['ENABLE_SNAPSHOT'])){
1105         /* Check if the snapshot_base is defined */
1106         if(!isset($tmp['SNAPSHOT_BASE'])){
1107           print_red(sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not configured in your gosa.conf."),$missing));
1108           return(FALSE);
1109         }
1111         /* check if there are special server configurations for snapshots */
1112         if(isset($tmp['SNAPSHOT_SERVER'])){
1114           /* check if all required vars are available to create a new ldap connection */
1115           $missing = "";
1116           foreach(array("SNAPSHOT_SERVER","SNAPSHOT_USER","SNAPSHOT_PASSWORD","SNAPSHOT_LDAP_BASE") as $var){
1117             if(!isset($tmp[$var])){
1118               $missing .= $var." ";
1119               print_red(sprintf(_("The snapshot functionality is enabled, but the required variable(s) '%s' is not configured in your gosa.conf."),$missing));
1120               return(FALSE);
1121             }
1122           }
1123         }
1124         return(TRUE);
1125       }
1126     }
1127     return(FALSE);
1128   }
1131   /* Return available snapshots for the given base 
1132    */
1133   function Available_SnapsShots($dn,$raw = false)
1134   {
1135     if(!$this->snapshotEnabled()) return(array());
1137     /* Create an additional ldap object which
1138        points to our ldap snapshot server */
1139     $ldap= $this->config->get_ldap_link();
1140     $ldap->cd($this->config->current['BASE']);
1141     $tmp = $this->config->current;
1143     /* check if there are special server configurations for snapshots */
1144     if(isset($tmp['SNAPSHOT_SERVER'])){
1145       $server       = $tmp['SNAPSHOT_SERVER'];
1146       $user         = $tmp['SNAPSHOT_USER'];
1147       $password     = $tmp['SNAPSHOT_PASSWORD'];
1148       $snapldapbase = $tmp['SNAPSHOT_LDAP_BASE'];
1149       $ldap_to      = new LDAP($user,$password, $server);
1150       $ldap_to -> cd ($snapldapbase);
1151       show_ldap_error($ldap->get_error(), sprintf(_("Method get available snapshots with dn '%s' failed."),$this->dn));
1152     }else{
1153       $ldap_to    = $ldap;
1154     }
1156     /* Prepare bases and some other infos */
1157     $base           = $this->config->current['BASE'];
1158     $snap_base      = $tmp['SNAPSHOT_BASE'];
1159     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1160     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1161     $tmp            = array(); 
1163     /* Fetch all objects with  gosaSnapshotDN=$dn */
1164     $ldap_to->cd($new_base);
1165     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1166         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1168     /* Put results into a list and add description if missing */
1169     while($entry = $ldap_to->fetch()){ 
1170       if(!isset($entry['description'][0])){
1171         $entry['description'][0]  = "";
1172       }
1173       $tmp[] = $entry; 
1174     }
1176     /* Return the raw array, or format the result */
1177     if($raw){
1178       return($tmp);
1179     }else{  
1180       $tmp2 = array();
1181       foreach($tmp as $entry){
1182         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1183       }
1184     }
1185     return($tmp2);
1186   }
1189   function getAllDeletedSnapshots($base_of_object,$raw = false)
1190   {
1191     if(!$this->snapshotEnabled()) return(array());
1193     /* Create an additional ldap object which
1194        points to our ldap snapshot server */
1195     $ldap= $this->config->get_ldap_link();
1196     $ldap->cd($this->config->current['BASE']);
1197     $tmp = $this->config->current;
1199     /* check if there are special server configurations for snapshots */
1200     if(isset($tmp['SNAPSHOT_SERVER'])){
1201       $server       = $tmp['SNAPSHOT_SERVER'];
1202       $user         = $tmp['SNAPSHOT_USER'];
1203       $password     = $tmp['SNAPSHOT_PASSWORD'];
1204       $snapldapbase = $tmp['SNAPSHOT_LDAP_BASE'];
1205       $ldap_to      = new LDAP($user,$password, $server);
1206       $ldap_to->cd ($snapldapbase);
1207       show_ldap_error($ldap->get_error(), sprintf(_("Method get deleted snapshots with dn '%s' failed."),$this->dn));
1208     }else{
1209       $ldap_to    = $ldap;
1210     }
1212     /* Prepare bases */ 
1213     $base           = $this->config->current['BASE'];
1214     $snap_base      = $tmp['SNAPSHOT_BASE'];
1215     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1217     /* Fetch all objects and check if they do not exist anymore */
1218     $ui = get_userinfo();
1219     $tmp = array();
1220     $ldap_to->cd($new_base);
1221     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1222     while($entry = $ldap_to->fetch()){
1224       $chk =  str_replace($new_base,"",$entry['dn']);
1225       if(preg_match("/,ou=/",$chk)) continue;
1227       if(!isset($entry['description'][0])){
1228         $entry['description'][0]  = "";
1229       }
1230       $tmp[] = $entry; 
1231     }
1233     /* Check if entry still exists */
1234     foreach($tmp as $key => $entry){
1235       $ldap->cat($entry['gosaSnapshotDN'][0]);
1236       if($ldap->count()){
1237         unset($tmp[$key]);
1238       }
1239     }
1241     /* Format result as requested */
1242     if($raw) {
1243       return($tmp);
1244     }else{
1245       $tmp2 = array();
1246       foreach($tmp as $key => $entry){
1247         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1248       }
1249     }
1250     return($tmp2);
1251   } 
1254   /* Restore selected snapshot */
1255   function restore_snapshot($dn)
1256   {
1257     if(!$this->snapshotEnabled()) return(array());
1259     $ldap= $this->config->get_ldap_link();
1260     $ldap->cd($this->config->current['BASE']);
1261     $tmp = $this->config->current;
1263     /* check if there are special server configurations for snapshots */
1264     if(isset($tmp['SNAPSHOT_SERVER'])){
1265       $server       = $tmp['SNAPSHOT_SERVER'];
1266       $user         = $tmp['SNAPSHOT_USER'];
1267       $password     = $tmp['SNAPSHOT_PASSWORD'];
1268       $snapldapbase = $tmp['SNAPSHOT_LDAP_BASE'];
1269       $ldap_to      = new LDAP($user,$password, $server);
1270       $ldap_to->cd ($snapldapbase);
1271       show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$snapldapbase));
1272     }else{
1273       $ldap_to    = $ldap;
1274     }
1276     /* Get the snapshot */ 
1277     $ldap_to->cat($dn);
1278     $restoreObject = $ldap_to->fetch();
1280     /* Prepare import string */
1281     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1283     /* Import the given data */
1284     $ldap->import_complete_ldif($data,$err,false,false);
1285     show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$dn));
1286   }
1289   function showSnapshotDialog($base,$baseSuffixe)
1290   {
1291     $once = true;
1292     foreach($_POST as $name => $value){
1294       /* Create a new snapshot, display a dialog */
1295       if(preg_match("/^CreateSnapShotDialog_/",$name) && $once){
1296         $once = false;
1297         $entry = preg_replace("/^CreateSnapShotDialog_/","",$name);
1298         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1299         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1300       }
1302       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1303       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1304         $once = false;
1305         $entry = preg_replace("/^RestoreSnapShotDialog_/","",$name);
1306         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1307         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1308         $this->snapDialog->display_restore_dialog = true;
1309       }
1311       /* Restore one of the already deleted objects */
1312       if(preg_match("/^RestoreDeletedSnapShot_/",$name) && $once){
1313         $once = false;
1314         $this->snapDialog = new SnapShotDialog($this->config,$baseSuffixe,$this);
1315         $this->snapDialog->display_restore_dialog      = true;
1316         $this->snapDialog->display_all_removed_objects  = true;
1317       }
1319       /* Restore selected snapshot */
1320       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1321         $once = false;
1322         $entry = preg_replace("/^RestoreSnapShot_/","",$name);
1323         $entry = base64_decode(trim(preg_replace("/_[xy]$/","",$entry)));
1324         if(!empty($entry)){
1325           $this->restore_snapshot($entry);
1326           $this->snapDialog = NULL;
1327         }
1328       }
1329     }
1331     /* Create a new snapshot requested, check
1332        the given attributes and create the snapshot*/
1333     if(isset($_POST['CreateSnapshot'])){
1334       $this->snapDialog->save_object();
1335       $msgs = $this->snapDialog->check();
1336       if(count($msgs)){
1337         foreach($msgs as $msg){
1338           print_red($msg);
1339         }
1340       }else{
1341         $this->dn =  $this->snapDialog->dn;
1342         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1343         $this->snapDialog = NULL;
1344       }
1345     }
1347     /* Restore is requested, restore the object with the posted dn .*/
1348     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1349     }
1351     if(isset($_POST['CancelSnapshot'])){
1352       $this->snapDialog = NULL;
1353     }
1355     if($this->snapDialog){
1356       $this->snapDialog->save_object();
1357       return($this->snapDialog->execute());
1358     }
1359   }
1361 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1362 ?>