Code

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