Code

Made faiScript/Hook compatible with the new release management
[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 $plHeadline= "";
113   var $plDescription= "";
114   var $plObject_name= "";
115   var $plProvided_acls= array();
116   var $plSelf_modify= FALSE;
117   var $plOptions= array();
118   var $plSection= "";
119   var $plTask= array();
120   var $plPriority= 0;
121   var $plDepends= array();
122   var $plConflicts= array();
124   /*! \brief plugin constructor
126     If 'dn' is set, the node loads the given 'dn' from LDAP
128     \param dn Distinguished name to initialize plugin from
129     \sa plugin()
130    */
131   function plugin ($config, $dn= NULL)
132   {
133     /* Configuration is fine, allways */
134     $this->config= $config;     
135     $this->dn= $dn;
137     /* Handle new accounts, don't read information from LDAP */
138     if ($dn == "new"){
139       return;
140     }
142     /* Get LDAP descriptor */
143     $ldap= $this->config->get_ldap_link();
144     if ($dn != NULL){
146       /* Load data to 'attrs' and save 'dn' */
147       $ldap->cat ($dn);
148       $this->attrs= $ldap->fetch();
150       /* Copy needed attributes */
151       foreach ($this->attributes as $val){
152         $found= array_key_ics($val, $this->attrs);
153         if ($found != ""){
154           $this->$val= $this->attrs["$found"][0];
155         }
156       }
158       /* gosaUnitTag loading... */
159       if (isset($this->attrs['gosaUnitTag'][0])){
160         $this->gosaUnitTag= $this->attrs['gosaUnitTag'][0];
161       }
163       /* Set the template flag according to the existence of objectClass
164          gosaUserTemplate */
165       if (isset($this->attrs['objectClass'])){
166         if (in_array ("gosaUserTemplate", $this->attrs['objectClass'])){
167           $this->is_template= TRUE;
168           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
169               "found", "Template check");
170         }
171       }
173       /* Is Account? */
174       error_reporting(0);
175       $found= TRUE;
176       foreach ($this->objectclasses as $obj){
177         if (preg_match('/top/i', $obj)){
178           continue;
179         }
180         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
181           $found= FALSE;
182           break;
183         }
184       }
185       error_reporting(E_ALL);
186       if ($found){
187         $this->is_account= TRUE;
188         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
189             "found", "Object check");
190       }
192       /* Prepare saved attributes */
193       $this->saved_attributes= $this->attrs;
194       foreach ($this->saved_attributes as $index => $value){
195         if (preg_match('/^[0-9]+$/', $index)){
196           unset($this->saved_attributes[$index]);
197           continue;
198         }
199         if (!in_array($index, $this->attributes) && $index != "objectClass"){
200           unset($this->saved_attributes[$index]);
201           continue;
202         }
203         if ($this->saved_attributes[$index]["count"] == 1){
204           $tmp= $this->saved_attributes[$index][0];
205           unset($this->saved_attributes[$index]);
206           $this->saved_attributes[$index]= $tmp;
207           continue;
208         }
210         unset($this->saved_attributes["$index"]["count"]);
211       }
212     }
214     /* Save initial account state */
215     $this->initially_was_account= $this->is_account;
216   }
218   /*! \brief execute plugin
220     Generates the html output for this node
221    */
222   function execute()
223   {
224     # This one is empty currently. Fabian - please fill in the docu code
225     $_SESSION['current_class_for_help'] = get_class($this);
226     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
227     $_SESSION['LOCK_VARS_TO_USE'] =array();
228   }
230   /*! \brief execute plugin
231      Removes object from parent
232    */
233   function remove_from_parent()
234   {
235     /* include global link_info */
236     $ldap= $this->config->get_ldap_link();
238     /* Get current objectClasses in order to add the required ones */
239     $ldap->cat($this->dn);
240     $tmp= $ldap->fetch ();
241     if (isset($tmp['objectClass'])){
242       $oc= $tmp['objectClass'];
243     } else {
244       $oc= array("count" => 0);
245     }
247     /* Remove objectClasses from entry */
248     $ldap->cd($this->dn);
249     $this->attrs= array();
250     $this->attrs['objectClass']= array();
251     for ($i= 0; $i<$oc["count"]; $i++){
252       if (!in_array_ics($oc[$i], $this->objectclasses)){
253         $this->attrs['objectClass'][]= $oc[$i];
254       }
255     }
257     /* Unset attributes from entry */
258     foreach ($this->attributes as $val){
259       $this->attrs["$val"]= array();
260     }
262     /* Unset account info */
263     $this->is_account= FALSE;
265     /* Do not write in plugin base class, this must be done by
266        children, since there are normally additional attribs,
267        lists, etc. */
268     /*
269        $ldap->modify($this->attrs);
270      */
271   }
274   /* Save data to object */
275   function save_object()
276   {
277     /* Save values to object */
278     foreach ($this->attributes as $val){
279       if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
280         /* Check for modifications */
281         if (get_magic_quotes_gpc()) {
282           $data= stripcslashes($_POST["$val"]);
283         } else {
284           $data= $this->$val = $_POST["$val"];
285         }
286         if ($this->$val != $data){
287           $this->is_modified= TRUE;
288         }
289     
290         /* Okay, how can I explain this fix ... 
291          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
292          * So IE posts these 'unselectable' option, with value = chr(194) 
293          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
294          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
295          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
296          */
297         if(isset($data[0]) && $data[0] == chr(194)) {
298           $data = "";  
299         }
300         $this->$val= $data;
301       }
302     }
303   }
306   /* Save data to LDAP, depending on is_account we save or delete */
307   function save()
308   {
309     /* include global link_info */
310     $ldap= $this->config->get_ldap_link();
312     /* Start with empty array */
313     $this->attrs= array();
315     /* Get current objectClasses in order to add the required ones */
316     $ldap->cat($this->dn);
317     
318     $tmp= $ldap->fetch ();
319     
320     if (isset($tmp['objectClass'])){
321       $oc= $tmp["objectClass"];
322       $this->new= FALSE;
323     } else {
324       $oc= array("count" => 0);
325       $this->new= TRUE;
326     }
328     /* Load (minimum) attributes, add missing ones */
329     $this->attrs['objectClass']= $this->objectclasses;
330     for ($i= 0; $i<$oc["count"]; $i++){
331       if (!in_array_ics($oc[$i], $this->objectclasses)){
332         $this->attrs['objectClass'][]= $oc[$i];
333       }
334     }
336     /* Copy standard attributes */
337     foreach ($this->attributes as $val){
338       if ($this->$val != ""){
339         $this->attrs["$val"]= $this->$val;
340       } elseif (!$this->new) {
341         $this->attrs["$val"]= array();
342       }
343     }
345   }
348   function cleanup()
349   {
350     foreach ($this->attrs as $index => $value){
352       /* Convert arrays with one element to non arrays, if the saved
353          attributes are no array, too */
354       if (is_array($this->attrs[$index]) && 
355           count ($this->attrs[$index]) == 1 &&
356           isset($this->saved_attributes[$index]) &&
357           !is_array($this->saved_attributes[$index])){
358           
359         $tmp= $this->attrs[$index][0];
360         $this->attrs[$index]= $tmp;
361       }
363       /* Remove emtpy arrays if they do not differ */
364       if (is_array($this->attrs[$index]) &&
365           count($this->attrs[$index]) == 0 &&
366           !isset($this->saved_attributes[$index])){
367           
368         unset ($this->attrs[$index]);
369         continue;
370       }
372       /* Remove single attributes that do not differ */
373       if (!is_array($this->attrs[$index]) &&
374           isset($this->saved_attributes[$index]) &&
375           !is_array($this->saved_attributes[$index]) &&
376           $this->attrs[$index] == $this->saved_attributes[$index]){
378         unset ($this->attrs[$index]);
379         continue;
380       }
382       /* Remove arrays that do not differ */
383       if (is_array($this->attrs[$index]) && 
384           isset($this->saved_attributes[$index]) &&
385           is_array($this->saved_attributes[$index])){
386           
387         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
388           unset ($this->attrs[$index]);
389           continue;
390         }
391       }
392     }
393   }
395   /* Check formular input */
396   function check()
397   {
398     $message= array();
400     /* Skip if we've no config object */
401     if (!isset($this->config)){
402       return $message;
403     }
405     /* Find hooks entries for this class */
406     $command= search_config($this->config->data['MENU'], get_class($this), "CHECK");
407     if ($command == "" && isset($this->config->data['TABS'])){
408       $command= search_config($this->config->data['TABS'], get_class($this), "CHECK");
409     }
411     if ($command != ""){
413       if (!check_command($command)){
414         $message[]= sprintf(_("Command '%s', specified as CHECK hook for plugin '%s' doesn't seem to exist."), $command,
415                             get_class($this));
416       } else {
418         /* Generate "ldif" for check hook */
419         $ldif= "dn: $this->dn\n";
420         
421         /* ... objectClasses */
422         foreach ($this->objectclasses as $oc){
423           $ldif.= "objectClass: $oc\n";
424         }
425         
426         /* ... attributes */
427         foreach ($this->attributes as $attr){
428           if ($this->$attr == ""){
429             continue;
430           }
431           if (is_array($this->$attr)){
432             foreach ($this->$attr as $val){
433               $ldif.= "$attr: $val\n";
434             }
435           } else {
436               $ldif.= "$attr: ".$this->$attr."\n";
437           }
438         }
440         /* Append empty line */
441         $ldif.= "\n";
443         /* Feed "ldif" into hook and retrieve result*/
444         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
445         $fh= proc_open($command, $descriptorspec, $pipes);
446         if (is_resource($fh)) {
447           fwrite ($pipes[0], $ldif);
448           fclose($pipes[0]);
449           
450           $result= stream_get_contents($pipes[1]);
451           if ($result != ""){
452             $message[]= $result;
453           }
454           
455           fclose($pipes[1]);
456           fclose($pipes[2]);
457           proc_close($fh);
458         }
459       }
461     }
463     return ($message);
464   }
466   /* Adapt from template, using 'dn' */
467   function adapt_from_template($dn)
468   {
469     /* Include global link_info */
470     $ldap= $this->config->get_ldap_link();
472     /* Load requested 'dn' to 'attrs' */
473     $ldap->cat ($dn);
474     $this->attrs= $ldap->fetch();
476     /* Walk through attributes */
477     foreach ($this->attributes as $val){
479       if (isset($this->attrs["$val"][0])){
481         /* If attribute is set, replace dynamic parts: 
482            %sn, %givenName and %uid. Fill these in our local variables. */
483         $value= $this->attrs["$val"][0];
485         foreach (array("sn", "givenName", "uid") as $repl){
486           if (preg_match("/%$repl/i", $value)){
487             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
488           }
489         }
490         $this->$val= $value;
491       }
492     }
494     /* Is Account? */
495     $found= TRUE;
496     foreach ($this->objectclasses as $obj){
497       if (preg_match('/top/i', $obj)){
498         continue;
499       }
500       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
501         $found= FALSE;
502         break;
503       }
504     }
505     if ($found){
506       $this->is_account= TRUE;
507     }
508   }
510   /* Indicate whether a password change is needed or not */
511   function password_change_needed()
512   {
513     return FALSE;
514   }
516   /* Show header message for tab dialogs */
517   function show_header($button_text, $text, $disabled= FALSE)
518   {
519     if ($disabled == TRUE){
520       $state= "disabled";
521     } else {
522       $state= "";
523     }
524     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
525     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
526       chkacl($this->acl, "all")." ".$state.
527       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
529     return($display);
530   }
532   function postcreate($add_attrs= array())
533   {
534     /* Find postcreate entries for this class */
535     $command= search_config($this->config->data['MENU'], get_class($this), "POSTCREATE");
536     if ($command == "" && isset($this->config->data['TABS'])){
537       $command= search_config($this->config->data['TABS'], get_class($this), "POSTCREATE");
538     }
540     if ($command != ""){
541       /* Walk through attribute list */
542       foreach ($this->attributes as $attr){
543         if (!is_array($this->$attr)){
544           $command= preg_replace("/%$attr/", $this->$attr, $command);
545         }
546       }
547       $command= preg_replace("/%dn/", $this->dn, $command);
549       /* Additional attributes */
550       foreach ($add_attrs as $name => $value){
551         $command= preg_replace("/%$name/", $value, $command);
552       }
554       if (check_command($command)){
555         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
556             $command, "Execute");
558         exec($command);
559       } else {
560         $message= sprintf(_("Command '%s', specified as POSTCREATE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
561         print_red ($message);
562       }
563     }
564   }
566   function postmodify($add_attrs= array())
567   {
568     /* Find postcreate entries for this class */
569     $command= search_config($this->config->data['MENU'], get_class($this), "POSTMODIFY");
570     if ($command == "" && isset($this->config->data['TABS'])){
571       $command= search_config($this->config->data['TABS'], get_class($this), "POSTMODIFY");
572     }
574     if ($command != ""){
575       /* Walk through attribute list */
576       foreach ($this->attributes as $attr){
577         if (!is_array($this->$attr)){
578           $command= preg_replace("/%$attr/", $this->$attr, $command);
579         }
580       }
581       $command= preg_replace("/%dn/", $this->dn, $command);
583       /* Additional attributes */
584       foreach ($add_attrs as $name => $value){
585         $command= preg_replace("/%$name/", $value, $command);
586       }
588       if (check_command($command)){
589         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
590             $command, "Execute");
592         exec($command);
593       } else {
594         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, get_class($this));
595         print_red ($message);
596       }
597     }
598   }
600   function postremove($add_attrs= array())
601   {
602     /* Find postremove entries for this class */
603     $command= search_config($this->config->data['MENU'], get_class($this), "POSTREMOVE");
604     if ($command == "" && isset($this->config->data['TABS'])){
605       $command= search_config($this->config->data['TABS'], get_class($this), "POSTREMOVE");
606     }
608     if ($command != ""){
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       /* Additional attributes */
618       foreach ($add_attrs as $name => $value){
619         $command= preg_replace("/%$name/", $value, $command);
620       }
622       if (check_command($command)){
623         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
624             $command, "Execute");
626         exec($command);
627       } else {
628         $message= sprintf(_("Command '%s', specified as POSTREMOVE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
629         print_red ($message);
630       }
631     }
632   }
634   /* Create unique DN */
635   function create_unique_dn($attribute, $base)
636   {
637     $ldap= $this->config->get_ldap_link();
638     $base= preg_replace("/^,*/", "", $base);
640     /* Try to use plain entry first */
641     $dn= "$attribute=".$this->$attribute.",$base";
642     $ldap->cat ($dn, array('dn'));
643     if (!$ldap->fetch()){
644       return ($dn);
645     }
647     /* Look for additional attributes */
648     foreach ($this->attributes as $attr){
649       if ($attr == $attribute || $this->$attr == ""){
650         continue;
651       }
653       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
654       $ldap->cat ($dn, array('dn'));
655       if (!$ldap->fetch()){
656         return ($dn);
657       }
658     }
660     /* None found */
661     return ("none");
662   }
664   function rebind($ldap, $referral)
665   {
666     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
667     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
668       $this->error = "Success";
669       $this->hascon=true;
670       $this->reconnect= true;
671       return (0);
672     } else {
673       $this->error = "Could not bind to " . $credentials['ADMIN'];
674       return NULL;
675     }
676   }
678   /* This is a workaround function. */
679   function copy($src_dn, $dst_dn)
680   {
681     /* Rename dn in possible object groups */
682     $ldap= $this->config->get_ldap_link();
683     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::fix($src_dn).'))',
684         array('cn'));
685     while ($attrs= $ldap->fetch()){
686       $og= new ogroup($this->config, $ldap->getDN());
687       unset($og->member[$src_dn]);
688       $og->member[$dst_dn]= $dst_dn;
689       $og->save ();
690     }
692     $ldap->cat($dst_dn);
693     $attrs= $ldap->fetch();
694     if (count($attrs)){
695       trigger_error("Trying to overwrite ".@LDAP::fix($dst_dn).", which already exists.",
696           E_USER_WARNING);
697       return (FALSE);
698     }
700     $ldap->cat($src_dn);
701     $attrs= $ldap->fetch();
702     if (!count($attrs)){
703       trigger_error("Trying to move ".@LDAP::fix($src_dn).", which does not seem to exist.",
704           E_USER_WARNING);
705       return (FALSE);
706     }
708     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
709     $ds= ldap_connect($this->config->current['SERVER']);
710     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
711     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
712       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
713     }
715     $r=ldap_bind($ds,$this->config->current['ADMIN'], $this->config->current['PASSWORD']);
716     error_reporting (0);
717     $sr=ldap_read($ds, @LDAP::fix($src_dn), "objectClass=*");
719     /* Fill data from LDAP */
720     $new= array();
721     if ($sr) {
722       $ei=ldap_first_entry($ds, $sr);
723       if ($ei) {
724         foreach($attrs as $attr => $val){
725           if ($info = ldap_get_values_len($ds, $ei, $attr)){
726             for ($i= 0; $i<$info['count']; $i++){
727               if ($info['count'] == 1){
728                 $new[$attr]= $info[$i];
729               } else {
730                 $new[$attr][]= $info[$i];
731               }
732             }
733           }
734         }
735       }
736     }
738     /* close conncetion */
739     error_reporting (E_ALL);
740     ldap_unbind($ds);
742     /* Adapt naming attribute */
743     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
744     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
745     $new[$dst_name]= @LDAP::fix($dst_val);
747     /* Check if this is a department.
748      * If it is a dep. && there is a , override in his ou 
749      *  change \2C to , again, else this entry can't be saved ...
750      */
751     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
752       $new['ou'] = preg_replace("/\\\\,/",",",$new['ou']);
753     }
755     /* Save copy */
756     $ldap->connect();
757     $ldap->cd($this->config->current['BASE']);
758     
759     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
761     /* FAIvariable=.../..., cn=.. 
762         could not be saved, because the attribute FAIvariable was different to 
763         the dn FAIvariable=..., cn=... */
764     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
765       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
766     }
767     $ldap->cd($dst_dn);
768     $ldap->add($new);
770     if ($ldap->error != "Success"){
771       trigger_error("Trying to save $dst_dn failed.",
772           E_USER_WARNING);
773       return(FALSE);
774     }
776     return (TRUE);
777   }
780   function move($src_dn, $dst_dn)
781   {
782     /* Copy source to destination */
783     if (!$this->copy($src_dn, $dst_dn)){
784       return (FALSE);
785     }
787     /* Delete source */
788     $ldap= $this->config->get_ldap_link();
789     $ldap->rmdir($src_dn);
790     if ($ldap->error != "Success"){
791       trigger_error("Trying to delete $src_dn failed.",
792           E_USER_WARNING);
793       return (FALSE);
794     }
796     return (TRUE);
797   }
800   /* Move/Rename complete trees */
801   function recursive_move($src_dn, $dst_dn)
802   {
803     /* Check if the destination entry exists */
804     $ldap= $this->config->get_ldap_link();
806     /* Check if destination exists - abort */
807     $ldap->cat($dst_dn, array('dn'));
808     if ($ldap->fetch()){
809       trigger_error("recursive_move $dst_dn already exists.",
810           E_USER_WARNING);
811       return (FALSE);
812     }
814     /* Perform a search for all objects to be moved */
815     $objects= array();
816     $ldap->cd($src_dn);
817     $ldap->search("(objectClass=*)", array("dn"));
818     while($attrs= $ldap->fetch()){
819       $dn= $attrs['dn'];
820       $objects[$dn]= strlen($dn);
821     }
823     /* Sort objects by indent level */
824     asort($objects);
825     reset($objects);
827     /* Copy objects from small to big indent levels by replacing src_dn by dst_dn */
828     foreach ($objects as $object => $len){
829       $src= $object;
830       $dst= preg_replace("/$src_dn$/", "$dst_dn", $object);
831       if (!$this->copy($src, $dst)){
832         return (FALSE);
833       }
834     }
836     /* Remove src_dn */
837     $ldap->cd($src_dn);
838     $ldap->recursive_remove();
839     return (TRUE);
840   }
843   function handle_post_events($mode, $add_attrs= array())
844   {
845     switch ($mode){
846       case "add":
847         $this->postcreate($add_attrs);
848       break;
850       case "modify":
851         $this->postmodify($add_attrs);
852       break;
854       case "remove":
855         $this->postremove($add_attrs);
856       break;
857     }
858   }
861   function saveCopyDialog(){
862   }
865   function getCopyDialog(){
866     return(array("string"=>"","status"=>""));
867   }
870   function PrepareForCopyPaste($source){
871     $todo = $this->attributes;
872     if(isset($this->CopyPasteVars)){
873       $todo = array_merge($todo,$this->CopyPasteVars);
874     }
875     $todo[] = "is_account";
876     foreach($todo as $var){
877       $this->$var = $source->$var;
878     }
879   }
882   function handle_object_tagging($dn= "", $tag= "", $show= false)
883   {
884     //FIXME: How to optimize this? We have at least two
885     //       LDAP accesses per object. It would be a good
886     //       idea to have it integrated.
888     /* No dn? Self-operation... */
889     if ($dn == ""){
890       $dn= $this->dn;
892       /* No tag? Find it yourself... */
893       if ($tag == ""){
894         $len= strlen($dn);
896         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
897         $relevant= array();
898         foreach ($this->config->adepartments as $key => $ntag){
900           /* This one is bigger than our dn, its not relevant... */
901           if ($len <= strlen($key)){
902             continue;
903           }
905           /* This one matches with the latter part. Break and don't fix this entry */
906           if (preg_match('/(^|,)'.normalizePreg($key).'$/', $dn)){
907             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
908             $relevant[strlen($key)]= $ntag;
909             continue;
910           }
912         }
914         /* If we've some relevant tags to set, just get the longest one */
915         if (count($relevant)){
916           ksort($relevant);
917           $tmp= array_keys($relevant);
918           $idx= end($tmp);
919           $tag= $relevant[$idx];
920           $this->gosaUnitTag= $tag;
921         }
922       }
923     }
926     /* Set tag? */
927     if ($tag != ""){
928       /* Set objectclass and attribute */
929       $ldap= $this->config->get_ldap_link();
930       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
931       $attrs= $ldap->fetch();
932       if(isset($attrs['gosaUnitTag'][0]) && $attrs['gosaUnitTag'][0] == $tag){
933         if ($show) {
934           echo sprintf(_("Object '%s' is already tagged"), @LDAP::fix($dn))."<br>";
935           flush();
936         }
937         return;
938       }
939       if (count($attrs)){
940         if ($show){
941           echo sprintf(_("Adding tag (%s) to object '%s'"), $tag, @LDAP::fix($dn))."<br>";
942           flush();
943         }
944         $nattrs= array("gosaUnitTag" => $this->gosaUnitTag);
945         $nattrs['objectClass']= array();
946         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
947           $oc= $attrs['objectClass'][$i];
948           if ($oc != "gosaAdministrativeUnitTag"){
949             $nattrs['objectClass'][]= $oc;
950           }
951         }
952         $nattrs['objectClass'][]= "gosaAdministrativeUnitTag";
953         $ldap->cd($dn);
954         $ldap->modify($nattrs);
955         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
956       } else {
957         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not tagging ($tag) $dn - seems to have moved away", "Tagging");
958       }
960     } else {
961       /* Remove objectclass and attribute */
962       $ldap= $this->config->get_ldap_link();
963       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
964       $attrs= $ldap->fetch();
965       if (isset($attrs['objectClass']) && !in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass'])){
966         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "$dn is not tagged", "Tagging");
967         return;
968       }
969       if (count($attrs)){
970         if ($show){
971           echo sprintf(_("Removing tag from object '%s'"), @LDAP::fix($dn))."<br>";
972           flush();
973         }
974         $nattrs= array("gosaUnitTag" => array());
975         $nattrs['objectClass']= array();
976         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
977           $oc= $attrs['objectClass'][$i];
978           if ($oc != "gosaAdministrativeUnitTag"){
979             $nattrs['objectClass'][]= $oc;
980           }
981         }
982         $ldap->cd($dn);
983         $ldap->modify($nattrs);
984         show_ldap_error($ldap->get_error(), sprintf(_("Handle object tagging with dn '%s' failed."),$dn));
985       } else {
986         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not removing tag ($tag) $dn - seems to have moved away", "Tagging");
987       }
988     }
990   }
993   /* Add possibility to stop remove process */
994   function allow_remove()
995   {
996     $reason= "";
997     return $reason;
998   }
1001   /* Create a snapshot of the current object */
1002   function create_snapshot($type= "snapshot", $description= array())
1003   {
1005     /* Check if snapshot functionality is enabled */
1006     if(!$this->snapshotEnabled()){
1007       return;
1008     }
1010     /* Get configuration from gosa.conf */
1011     $tmp = $this->config->current;
1013     /* Create lokal ldap connection */
1014     $ldap= $this->config->get_ldap_link();
1015     $ldap->cd($this->config->current['BASE']);
1017     /* check if there are special server configurations for snapshots */
1018     if(!isset($tmp['SNAPSHOT_SERVER'])){
1020       /* Source and destination server are both the same, just copy source to dest obj */
1021       $ldap_to      = $ldap;
1022       $snapldapbase = $this->config->current['BASE'];
1024     }else{
1025       $server         = $tmp['SNAPSHOT_SERVER'];
1026       $user           = $tmp['SNAPSHOT_USER'];
1027       $password       = $tmp['SNAPSHOT_PASSWORD'];
1028       $snapldapbase   = $tmp['SNAPSHOT_LDAP_BASE'];
1030       $ldap_to        = new LDAP($user,$password, $server);
1031       $ldap_to -> cd($snapldapbase);
1032       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$snapldapbase));
1033     }
1035     /* check if the dn exists */ 
1036     if ($ldap->dn_exists($this->dn)){
1038       /* Extract seconds & mysecs, they are used as entry index */
1039       list($usec, $sec)= explode(" ", microtime());
1041       /* Collect some infos */
1042       $base           = $this->config->current['BASE'];
1043       $snap_base      = $tmp['SNAPSHOT_BASE'];
1044       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1045       $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1047       /* Create object */
1048 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1049       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1050       $newName          = preg_replace("/\./", "", $sec."-".$usec);
1051       $target= array();
1052       $target['objectClass']            = array("top", "gosaSnapshotObject");
1053       $target['gosaSnapshotData']       = gzcompress($data, 6);
1054       $target['gosaSnapshotType']       = $type;
1055       $target['gosaSnapshotDN']         = $this->dn;
1056       $target['description']            = $description;
1057       $target['gosaSnapshotTimestamp']  = $newName;
1059       /* Insert the new snapshot 
1060          But we have to check first, if the given gosaSnapshotTimestamp
1061          is already used, in this case we should increment this value till there is 
1062          an unused value. */ 
1063       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1064       $ldap_to->cat($new_dn);
1065       while($ldap_to->count()){
1066         $ldap_to->cat($new_dn);
1067         $newName = preg_replace("/\./", "", $sec."-".($usec++));
1068         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1069         $target['gosaSnapshotTimestamp']  = $newName;
1070       } 
1072       /* Inset this new snapshot */
1073       $ldap_to->cd($snapldapbase);
1074       $ldap_to->create_missing_trees($new_base);
1075       $ldap_to->cd($new_dn);
1076       $ldap_to->add($target);
1078       show_ldap_error($ldap->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1079       show_ldap_error($ldap_to->get_error(), sprintf(_("Saving object snapshot with dn '%s' failed."),$new_base));
1080     }
1081   }
1083   function remove_snapshot($dn)
1084   {
1085     $ui   = get_userinfo();
1086     $acl  = get_permissions ($dn, $ui->subtreeACL);
1087     $acl  = get_module_permission($acl, "snapshot", $dn);
1089     if (chkacl($this->acl, "delete") == ""){
1090     $ldap = $this->config->get_ldap_link();
1091     $ldap->cd($this->config->current['BASE']);
1092     $ldap->rmdir_recursive($dn);
1093     }else{
1094       print_red (_("You are not allowed to delete this snap shot!"));
1095     }
1096   }
1099   /* returns true if snapshots are enabled, and false if it is disalbed
1100      There will also be some errors psoted, if the configuration failed */
1101   function snapshotEnabled()
1102   {
1103     $tmp = $this->config->current;
1104     if(isset($tmp['ENABLE_SNAPSHOT'])){
1105       if (preg_match("/^true$/i", $tmp['ENABLE_SNAPSHOT']) || preg_match("/yes/i", $tmp['ENABLE_SNAPSHOT'])){
1107         /* Check if the snapshot_base is defined */
1108         if(!isset($tmp['SNAPSHOT_BASE'])){
1109           print_red(sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not configured in your gosa.conf."),$missing));
1110           return(FALSE);
1111         }
1113         /* check if there are special server configurations for snapshots */
1114         if(isset($tmp['SNAPSHOT_SERVER'])){
1116           /* check if all required vars are available to create a new ldap connection */
1117           $missing = "";
1118           foreach(array("SNAPSHOT_SERVER","SNAPSHOT_USER","SNAPSHOT_PASSWORD","SNAPSHOT_LDAP_BASE") as $var){
1119             if(!isset($tmp[$var])){
1120               $missing .= $var." ";
1121               print_red(sprintf(_("The snapshot functionality is enabled, but the required variable(s) '%s' is not configured in your gosa.conf."),$missing));
1122               return(FALSE);
1123             }
1124           }
1125         }
1126         return(TRUE);
1127       }
1128     }
1129     return(FALSE);
1130   }
1133   /* Return available snapshots for the given base 
1134    */
1135   function Available_SnapsShots($dn,$raw = false)
1136   {
1137     if(!$this->snapshotEnabled()) return(array());
1139     /* Create an additional ldap object which
1140        points to our ldap snapshot server */
1141     $ldap= $this->config->get_ldap_link();
1142     $ldap->cd($this->config->current['BASE']);
1143     $tmp = $this->config->current;
1145     /* check if there are special server configurations for snapshots */
1146     if(isset($tmp['SNAPSHOT_SERVER'])){
1147       $server       = $tmp['SNAPSHOT_SERVER'];
1148       $user         = $tmp['SNAPSHOT_USER'];
1149       $password     = $tmp['SNAPSHOT_PASSWORD'];
1150       $snapldapbase = $tmp['SNAPSHOT_LDAP_BASE'];
1151       $ldap_to      = new LDAP($user,$password, $server);
1152       $ldap_to -> cd ($snapldapbase);
1153       show_ldap_error($ldap->get_error(), sprintf(_("Method get available snapshots with dn '%s' failed."),$this->dn));
1154     }else{
1155       $ldap_to    = $ldap;
1156     }
1158     /* Prepare bases and some other infos */
1159     $base           = $this->config->current['BASE'];
1160     $snap_base      = $tmp['SNAPSHOT_BASE'];
1161     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1162     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1163     $tmp            = array(); 
1165     /* Fetch all objects with  gosaSnapshotDN=$dn */
1166     $ldap_to->cd($new_base);
1167     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1168         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1170     /* Put results into a list and add description if missing */
1171     while($entry = $ldap_to->fetch()){ 
1172       if(!isset($entry['description'][0])){
1173         $entry['description'][0]  = "";
1174       }
1175       $tmp[] = $entry; 
1176     }
1178     /* Return the raw array, or format the result */
1179     if($raw){
1180       return($tmp);
1181     }else{  
1182       $tmp2 = array();
1183       foreach($tmp as $entry){
1184         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1185       }
1186     }
1187     return($tmp2);
1188   }
1191   function getAllDeletedSnapshots($base_of_object,$raw = false)
1192   {
1193     if(!$this->snapshotEnabled()) return(array());
1195     /* Create an additional ldap object which
1196        points to our ldap snapshot server */
1197     $ldap= $this->config->get_ldap_link();
1198     $ldap->cd($this->config->current['BASE']);
1199     $tmp = $this->config->current;
1201     /* check if there are special server configurations for snapshots */
1202     if(isset($tmp['SNAPSHOT_SERVER'])){
1203       $server       = $tmp['SNAPSHOT_SERVER'];
1204       $user         = $tmp['SNAPSHOT_USER'];
1205       $password     = $tmp['SNAPSHOT_PASSWORD'];
1206       $snapldapbase = $tmp['SNAPSHOT_LDAP_BASE'];
1207       $ldap_to      = new LDAP($user,$password, $server);
1208       $ldap_to->cd ($snapldapbase);
1209       show_ldap_error($ldap->get_error(), sprintf(_("Method get deleted snapshots with dn '%s' failed."),$this->dn));
1210     }else{
1211       $ldap_to    = $ldap;
1212     }
1214     /* Prepare bases */ 
1215     $base           = $this->config->current['BASE'];
1216     $snap_base      = $tmp['SNAPSHOT_BASE'];
1217     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1219     /* Fetch all objects and check if they do not exist anymore */
1220     $ui = get_userinfo();
1221     $tmp = array();
1222     $ldap_to->cd($new_base);
1223     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1224     while($entry = $ldap_to->fetch()){
1226       $chk =  str_replace($new_base,"",$entry['dn']);
1227       if(preg_match("/,ou=/",$chk)) continue;
1229       if(!isset($entry['description'][0])){
1230         $entry['description'][0]  = "";
1231       }
1232       $tmp[] = $entry; 
1233     }
1235     /* Check if entry still exists */
1236     foreach($tmp as $key => $entry){
1237       $ldap->cat($entry['gosaSnapshotDN'][0]);
1238       if($ldap->count()){
1239         unset($tmp[$key]);
1240       }
1241     }
1243     /* Format result as requested */
1244     if($raw) {
1245       return($tmp);
1246     }else{
1247       $tmp2 = array();
1248       foreach($tmp as $key => $entry){
1249         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1250       }
1251     }
1252     return($tmp2);
1253   } 
1256   /* Restore selected snapshot */
1257   function restore_snapshot($dn)
1258   {
1259     if(!$this->snapshotEnabled()) return(array());
1261     $ldap= $this->config->get_ldap_link();
1262     $ldap->cd($this->config->current['BASE']);
1263     $tmp = $this->config->current;
1265     /* check if there are special server configurations for snapshots */
1266     if(isset($tmp['SNAPSHOT_SERVER'])){
1267       $server       = $tmp['SNAPSHOT_SERVER'];
1268       $user         = $tmp['SNAPSHOT_USER'];
1269       $password     = $tmp['SNAPSHOT_PASSWORD'];
1270       $snapldapbase = $tmp['SNAPSHOT_LDAP_BASE'];
1271       $ldap_to      = new LDAP($user,$password, $server);
1272       $ldap_to->cd ($snapldapbase);
1273       show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$snapldapbase));
1274     }else{
1275       $ldap_to    = $ldap;
1276     }
1278     /* Get the snapshot */ 
1279     $ldap_to->cat($dn);
1280     $restoreObject = $ldap_to->fetch();
1282     /* Prepare import string */
1283     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1285     /* Import the given data */
1286     $ldap->import_complete_ldif($data,$err,false,false);
1287     show_ldap_error($ldap->get_error(), sprintf(_("Restore snapshot with dn '%s' failed."),$dn));
1288   }
1291   function showSnapshotDialog($base,$baseSuffixe)
1292   {
1293     $once = true;
1294     foreach($_POST as $name => $value){
1296       /* Create a new snapshot, display a dialog */
1297       if(preg_match("/^CreateSnapShotDialog_/",$name) && $once){
1298         $once = false;
1299         $entry = preg_replace("/^CreateSnapShotDialog_/","",$name);
1300         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1301         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1302       }
1304       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1305       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1306         $once = false;
1307         $entry = preg_replace("/^RestoreSnapShotDialog_/","",$name);
1308         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1309         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1310         $this->snapDialog->display_restore_dialog = true;
1311       }
1313       /* Restore one of the already deleted objects */
1314       if(preg_match("/^RestoreDeletedSnapShot_/",$name) && $once){
1315         $once = false;
1316         $this->snapDialog = new SnapShotDialog($this->config,$baseSuffixe,$this);
1317         $this->snapDialog->display_restore_dialog      = true;
1318         $this->snapDialog->display_all_removed_objects  = true;
1319       }
1321       /* Restore selected snapshot */
1322       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1323         $once = false;
1324         $entry = preg_replace("/^RestoreSnapShot_/","",$name);
1325         $entry = base64_decode(trim(preg_replace("/_[xy]$/","",$entry)));
1326         if(!empty($entry)){
1327           $this->restore_snapshot($entry);
1328           $this->snapDialog = NULL;
1329         }
1330       }
1331     }
1333     /* Create a new snapshot requested, check
1334        the given attributes and create the snapshot*/
1335     if(isset($_POST['CreateSnapshot'])){
1336       $this->snapDialog->save_object();
1337       $msgs = $this->snapDialog->check();
1338       if(count($msgs)){
1339         foreach($msgs as $msg){
1340           print_red($msg);
1341         }
1342       }else{
1343         $this->dn =  $this->snapDialog->dn;
1344         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1345         $this->snapDialog = NULL;
1346       }
1347     }
1349     /* Restore is requested, restore the object with the posted dn .*/
1350     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1351     }
1353     if(isset($_POST['CancelSnapshot'])){
1354       $this->snapDialog = NULL;
1355     }
1357     if($this->snapDialog){
1358       $this->snapDialog->save_object();
1359       return($this->snapDialog->execute());
1360     }
1361   }
1363 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1364 ?>