Code

38bd1cf9436b30d4807e6da09edfad3870b10d9d
[gosa.git] / gosa-core / include / class_plugin.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 /*! \brief   The plugin base class
24   \author  Cajus Pollmeier <pollmeier@gonicus.de>
25   \version 2.00
26   \date    24.07.2003
28   This is the base class for all plugins. It can be used standalone or
29   can be included by the tabs class. All management should be done 
30   within this class. Extend your plugins from this class.
31  */
33 class plugin
34 {
35   /*!
36     \brief Reference to parent object
38     This variable is used when the plugin is included in tabs
39     and keeps reference to the tab class. Communication to other
40     tabs is possible by 'name'. So the 'fax' plugin can ask the
41     'userinfo' plugin for the fax number.
43     \sa tab
44    */
45   var $parent= NULL;
47   /*!
48     \brief Configuration container
50     Access to global configuration
51    */
52   var $config= NULL;
54   /*!
55     \brief Mark plugin as account
57     Defines whether this plugin is defined as an account or not.
58     This has consequences for the plugin to be saved from tab
59     mode. If it is set to 'FALSE' the tab will call the delete
60     function, else the save function. Should be set to 'TRUE' if
61     the construtor detects a valid LDAP object.
63     \sa plugin::plugin()
64    */
65   var $is_account= FALSE;
66   var $initially_was_account= FALSE;
68   /*!
69     \brief Mark plugin as template
71     Defines whether we are creating a template or a normal object.
72     Has conseqences on the way execute() shows the formular and how
73     save() puts the data to LDAP.
75     \sa plugin::save() plugin::execute()
76    */
77   var $is_template= FALSE;
78   var $ignore_account= FALSE;
79   var $is_modified= FALSE;
81   /*!
82     \brief Represent temporary LDAP data
84     This is only used internally.
85    */
86   var $attrs= array();
88   /* Keep set of conflicting plugins */
89   var $conflicts= array();
91   /* Save unit tags */
92   var $gosaUnitTag= "";
93   var $skipTagging= FALSE;
95   /*!
96     \brief Used standard values
98     dn
99    */
100   var $dn= "";
101   var $uid= "";
102   var $sn= "";
103   var $givenName= "";
104   var $acl= "*none*";
105   var $dialog= FALSE;
106   var $snapDialog = NULL;
108   /* attribute list for save action */
109   var $attributes= array();
110   var $objectclasses= array();
111   var $is_new= TRUE;
112   var $saved_attributes= array();
114   var $acl_base= "";
115   var $acl_category= "";
116   var $read_only = FALSE; // Used when the entry is opened as "readonly" due to locks.
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, $object= 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     /* Check if this entry was opened in read only mode */
154     if(isset($_POST['open_readonly'])){
155       if(session::global_is_set("LOCK_CACHE")){
156         $cache = &session::get("LOCK_CACHE");
157         if(isset($cache['READ_ONLY'][$this->dn])){
158           $this->read_only = TRUE;
159         }
160       }
161     }
163     /* Save current dn as acl_base */
164     $this->acl_base= $dn;
166     /* Get LDAP descriptor */
167     if ($dn !== NULL){
169       /* Load data to 'attrs' and save 'dn' */
170       if ($object !== NULL){
171         $this->attrs= $object->attrs;
172       } else {
173         $ldap= $this->config->get_ldap_link();
174         $ldap->cat ($dn);
175         $this->attrs= $ldap->fetch();
176       }
178       /* Copy needed attributes */
179       foreach ($this->attributes as $val){
180         $found= array_key_ics($val, $this->attrs);
181         if ($found != ""){
182           $this->$val= $found[0];
183         }
184       }
186       /* gosaUnitTag loading... */
187       if (isset($this->attrs['gosaUnitTag'][0])){
188         $this->gosaUnitTag= $this->attrs['gosaUnitTag'][0];
189       }
191       /* Set the template flag according to the existence of objectClass
192          gosaUserTemplate */
193       if (isset($this->attrs['objectClass'])){
194         if (in_array_ics ("gosaUserTemplate", $this->attrs['objectClass'])){
195           $this->is_template= TRUE;
196           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
197               "found", "Template check");
198         }
199       }
201       /* Is Account? */
202       $found= TRUE;
203       foreach ($this->objectclasses as $obj){
204         if (preg_match('/top/i', $obj)){
205           continue;
206         }
207         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
208           $found= FALSE;
209           break;
210         }
211       }
212       if ($found){
213         $this->is_account= TRUE;
214         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
215             "found", "Object check");
216       }
218       /* Prepare saved attributes */
219       $this->saved_attributes= $this->attrs;
220       foreach ($this->saved_attributes as $index => $value){
221         if (is_numeric($index)){
222           unset($this->saved_attributes[$index]);
223           continue;
224         }
226         if (!in_array_ics($index, $this->attributes) && strcasecmp('objectClass', $index)){
227           unset($this->saved_attributes[$index]);
228           continue;
229         }
231         if (isset($this->saved_attributes[$index][0])){
232           if(!isset($this->saved_attributes[$index]["count"])){
233             $this->saved_attributes[$index]["count"] = count($this->saved_attributes[$index]);
234           }
235           if($this->saved_attributes[$index]["count"] == 1){
236             $tmp= $this->saved_attributes[$index][0];
237             unset($this->saved_attributes[$index]);
238             $this->saved_attributes[$index]= $tmp;
239             continue;
240           }
241         }
242         unset($this->saved_attributes["$index"]["count"]);
243       }
245       if(isset($this->attrs['gosaUnitTag'])){
246         $this->saved_attributes['gosaUnitTag'] = $this->attrs['gosaUnitTag'][0];
247       }
248     }
250     /* Save initial account state */
251     $this->initially_was_account= $this->is_account;
252   }
255   /*! \brief execute plugin
257     Generates the html output for this node
258    */
259   function execute()
260   {
261     /* This one is empty currently. Fabian - please fill in the docu code */
262     session::global_set('current_class_for_help',get_class($this));
264     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
265     session::set('LOCK_VARS_TO_USE',array());
266     session::set('LOCK_VARS_USED_GET',array());
267     session::set('LOCK_VARS_USED_POST',array());
268     session::set('LOCK_VARS_USED_REQUEST',array());
269   }
271   /*! \brief execute plugin
272      Removes object from parent
273    */
274   function remove_from_parent()
275   {
276     /* include global link_info */
277     $ldap= $this->config->get_ldap_link();
279     /* Get current objectClasses in order to add the required ones */
280     $ldap->cat($this->dn);
281     $tmp= $ldap->fetch ();
282     $oc= array();
283     if (isset($tmp['objectClass'])){
284       $oc= $tmp['objectClass'];
285       unset($oc['count']);
286     }
288     /* Remove objectClasses from entry */
289     $ldap->cd($this->dn);
290     $this->attrs= array();
291     $this->attrs['objectClass']= array_remove_entries_ics($this->objectclasses,$oc);
293     /* Unset attributes from entry */
294     foreach ($this->attributes as $val){
295       $this->attrs["$val"]= array();
296     }
298     /* Unset account info */
299     $this->is_account= FALSE;
301     /* Do not write in plugin base class, this must be done by
302        children, since there are normally additional attribs,
303        lists, etc. */
304     /*
305        $ldap->modify($this->attrs);
306      */
307   }
310   /*! \brief   Save HTML posted data to object 
311    */
312   function save_object()
313   {
314     /* Update entry CSN if it is empty. */
315     if(empty($this->entryCSN) && $this->CSN_check_active){
316       $this->entryCSN = getEntryCSN($this->dn);
317     }
319     /* Save values to object */
320     foreach ($this->attributes as $val){
321       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
322         /* Check for modifications */
323         if (get_magic_quotes_gpc()) {
324           $data= stripcslashes($_POST["$val"]);
325         } else {
326           $data= $this->$val = $_POST["$val"];
327         }
328         if ($this->$val != $data){
329           $this->is_modified= TRUE;
330         }
331     
332         /* Okay, how can I explain this fix ... 
333          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
334          * So IE posts these 'unselectable' option, with value = chr(194) 
335          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
336          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
337          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
338          */
339         if(isset($data[0]) && $data[0] == chr(194)) {
340           $data = "";  
341         }
342         $this->$val= $data;
343       }
344     }
345   }
348   /* Save data to LDAP, depending on is_account we save or delete */
349   function save()
350   {
351     /* include global link_info */
352     $ldap= $this->config->get_ldap_link();
354     /* Save all plugins */
355     $this->entryCSN = "";
357     /* Start with empty array */
358     $this->attrs= array();
360     /* Get current objectClasses in order to add the required ones */
361     $ldap->cat($this->dn);
362     
363     $tmp= $ldap->fetch ();
365     $oc= array();
366     if (isset($tmp['objectClass'])){
367       $oc= $tmp["objectClass"];
368       $this->is_new= FALSE;
369       unset($oc['count']);
370     } else {
371       $this->is_new= TRUE;
372     }
374     /* Load (minimum) attributes, add missing ones */
375     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
377     /* Copy standard attributes */
378     foreach ($this->attributes as $val){
379       if ($this->$val != ""){
380         $this->attrs["$val"]= $this->$val;
381       } elseif (!$this->is_new) {
382         $this->attrs["$val"]= array();
383       }
384     }
386     /* Handle tagging */
387     $this->tag_attrs($this->attrs);
388   }
391   function cleanup()
392   {
393     foreach ($this->attrs as $index => $value){
394       
395       /* Convert arrays with one element to non arrays, if the saved
396          attributes are no array, too */
397       if (is_array($this->attrs[$index]) && 
398           count ($this->attrs[$index]) == 1 &&
399           isset($this->saved_attributes[$index]) &&
400           !is_array($this->saved_attributes[$index])){
401           
402         $tmp= $this->attrs[$index][0];
403         $this->attrs[$index]= $tmp;
404       }
406       /* Remove emtpy arrays if they do not differ */
407       if (is_array($this->attrs[$index]) &&
408           count($this->attrs[$index]) == 0 &&
409           !isset($this->saved_attributes[$index])){
410           
411         unset ($this->attrs[$index]);
412         continue;
413       }
415       /* Remove single attributes that do not differ */
416       if (!is_array($this->attrs[$index]) &&
417           isset($this->saved_attributes[$index]) &&
418           !is_array($this->saved_attributes[$index]) &&
419           $this->attrs[$index] == $this->saved_attributes[$index]){
421         unset ($this->attrs[$index]);
422         continue;
423       }
425       /* Remove arrays that do not differ */
426       if (is_array($this->attrs[$index]) && 
427           isset($this->saved_attributes[$index]) &&
428           is_array($this->saved_attributes[$index])){
429           
430         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
431           unset ($this->attrs[$index]);
432           continue;
433         }
434       }
435     }
437     /* Update saved attributes and ensure that next cleanups will be successful too */
438     foreach($this->attrs as $name => $value){
439       $this->saved_attributes[$name] = $value;
440     }
441   }
443   /* Check formular input */
444   function check()
445   {
446     $message= array();
448     /* Skip if we've no config object */
449     if (!isset($this->config) || !is_object($this->config)){
450       return $message;
451     }
453     /* Find hooks entries for this class */
454     $command= $this->config->search(get_class($this), "CHECK", array('menu', 'tabs'));
456     if ($command != ""){
458       if (!check_command($command)){
459         $message[]= msgPool::cmdnotfound("CHECK", get_class($this));
460       } else {
462         /* Generate "ldif" for check hook */
463         $ldif= "dn: $this->dn\n";
464         
465         /* ... objectClasses */
466         foreach ($this->objectclasses as $oc){
467           $ldif.= "objectClass: $oc\n";
468         }
469         
470         /* ... attributes */
471         foreach ($this->attributes as $attr){
472           if ($this->$attr == ""){
473             continue;
474           }
475           if (is_array($this->$attr)){
476             foreach ($this->$attr as $val){
477               $ldif.= "$attr: $val\n";
478             }
479           } else {
480               $ldif.= "$attr: ".$this->$attr."\n";
481           }
482         }
484         /* Append empty line */
485         $ldif.= "\n";
487         /* Feed "ldif" into hook and retrieve result*/
488         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
489         $fh= proc_open($command, $descriptorspec, $pipes);
490         if (is_resource($fh)) {
491           fwrite ($pipes[0], $ldif);
492           fclose($pipes[0]);
493           
494           $result= stream_get_contents($pipes[1]);
495           if ($result != ""){
496             $message[]= $result;
497           }
498           
499           fclose($pipes[1]);
500           fclose($pipes[2]);
501           proc_close($fh);
502         }
503       }
505     }
507     /* Check entryCSN */
508     if($this->CSN_check_active){
509       $current_csn = getEntryCSN($this->dn);
510       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
511         $this->entryCSN = $current_csn;
512         $message[] = _("The object has changed since opened in GOsa. All changes that may be done by others get lost if you save this entry!");
513       }
514     }
515     return ($message);
516   }
518   /* Adapt from template, using 'dn' */
519   function adapt_from_template($dn, $skip= array())
520   {
521     /* Include global link_info */
522     $ldap= $this->config->get_ldap_link();
524     /* Load requested 'dn' to 'attrs' */
525     $ldap->cat ($dn);
526     $this->attrs= $ldap->fetch();
528     /* Walk through attributes */
529     foreach ($this->attributes as $val){
531       /* Skip the ones in skip list */
532       if (in_array($val, $skip)){
533         continue;
534       }
536       if (isset($this->attrs["$val"][0])){
538         /* If attribute is set, replace dynamic parts: 
539            %sn, %givenName and %uid. Fill these in our local variables. */
540         $value= $this->attrs["$val"][0];
542         foreach (array("sn", "givenName", "uid") as $repl){
543           if (preg_match("/%$repl/i", $value)){
544             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
545           }
546         }
547         $this->$val= $value;
548       }
549     }
551     /* Is Account? */
552     $found= TRUE;
553     foreach ($this->objectclasses as $obj){
554       if (preg_match('/top/i', $obj)){
555         continue;
556       }
557       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
558         $found= FALSE;
559         break;
560       }
561     }
562     if ($found){
563       $this->is_account= TRUE;
564     }
565   }
567   /* Indicate whether a password change is needed or not */
568   function password_change_needed()
569   {
570     return FALSE;
571   }
574   /* Show header message for tab dialogs */
575   function show_enable_header($button_text, $text, $disabled= FALSE)
576   {
577     if (($disabled == TRUE) || (!$this->acl_is_createable())){
578       $state= "disabled";
579     } else {
580       $state= "";
581     }
582     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
583     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
584       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
586     return($display);
587   }
590   /* Show header message for tab dialogs */
591   function show_disable_header($button_text, $text, $disabled= FALSE)
592   {
593     if (($disabled == TRUE) || !$this->acl_is_removeable()){
594       $state= "disabled";
595     } else {
596       $state= "";
597     }
598     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
599     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
600       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
602     return($display);
603   }
606   /* Show header message for tab dialogs */
607   function show_header($button_text, $text, $disabled= FALSE)
608   {
609     echo "FIXME: show_header should be replaced by show_disable_header and show_enable_header<br>";
610     if ($disabled == TRUE){
611       $state= "disabled";
612     } else {
613       $state= "";
614     }
615     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
616     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
617       ($this->acl_is_createable()?'':'disabled')." ".$state.
618       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
620     return($display);
621   }
624   function postcreate($add_attrs= array())
625   {
626     /* Find postcreate entries for this class */
627     $command= $this->config->search(get_class($this), "POSTCREATE",array('menu', 'tabs'));
629     if ($command != ""){
631       /* Walk through attribute list */
632       foreach ($this->attributes as $attr){
633         if (!is_array($this->$attr)){
634           $add_attrs[$attr] = $this->$attr;
635         }
636       }
637       $add_attrs['dn']=$this->dn;
639       $tmp = array();
640       foreach($add_attrs as $name => $value){
641         $tmp[$name] =  strlen($name);
642       }
643       arsort($tmp);
644       
645       /* Additional attributes */
646       foreach ($tmp as $name => $len){
647         $value = $add_attrs[$name];
648         $command= str_replace("%$name", "$value", $command);
649       }
651       if (check_command($command)){
652         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
653             $command, "Execute");
654         exec($command,$arr);
655         foreach($arr as $str){
656           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
657             $command, "Result: ".$str);
658         }
659       } else {
660         $message= msgPool::cmdnotfound("POSTCREATE", get_class($this));
661         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
662       }
663     }
664   }
666   function postmodify($add_attrs= array())
667   {
668     /* Find postcreate entries for this class */
669     $command= $this->config->search(get_class($this), "POSTMODIFY",array('menu','tabs'));
671     if ($command != ""){
673       /* Walk through attribute list */
674       foreach ($this->attributes as $attr){
675         if (!is_array($this->$attr)){
676           $add_attrs[$attr] = $this->$attr;
677         }
678       }
679       $add_attrs['dn']=$this->dn;
681       $tmp = array();
682       foreach($add_attrs as $name => $value){
683         $tmp[$name] =  strlen($name);
684       }
685       arsort($tmp);
686       
687       /* Additional attributes */
688       foreach ($tmp as $name => $len){
689         $value = $add_attrs[$name];
690         $command= str_replace("%$name", "$value", $command);
691       }
693       if (check_command($command)){
694         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,$command, "Execute");
695         exec($command,$arr);
696         foreach($arr as $str){
697           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
698             $command, "Result: ".$str);
699         }
700       } else {
701         $message= msgPool::cmdnotfound("POSTMODIFY", get_class($this));
702         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
703       }
704     }
705   }
707   function postremove($add_attrs= array())
708   {
709     /* Find postremove entries for this class */
710     $command= $this->config->search(get_class($this), "POSTREMOVE",array('menu','tabs'));
711     if ($command != ""){
713       /* Walk through attribute list */
714       foreach ($this->attributes as $attr){
715         if (!is_array($this->$attr)){
716           $add_attrs[$attr] = $this->$attr;
717         }
718       }
719       $add_attrs['dn']=$this->dn;
721       $tmp = array();
722       foreach($add_attrs as $name => $value){
723         $tmp[$name] =  strlen($name);
724       }
725       arsort($tmp);
726       
727       /* Additional attributes */
728       foreach ($tmp as $name => $len){
729         $value = $add_attrs[$name];
730         $command= str_replace("%$name", "$value", $command);
731       }
733       if (check_command($command)){
734         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
735             $command, "Execute");
737         exec($command,$arr);
738         foreach($arr as $str){
739           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
740             $command, "Result: ".$str);
741         }
742       } else {
743         $message= msgPool::cmdnotfound("POSTREMOVE", get_class($this));
744         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
745       }
746     }
747   }
750   /* Create unique DN */
751   function create_unique_dn2($data, $base)
752   {
753     $ldap= $this->config->get_ldap_link();
754     $base= preg_replace("/^,*/", "", $base);
756     /* Try to use plain entry first */
757     $dn= "$data,$base";
758     $attribute= preg_replace('/=.*$/', '', $data);
759     $ldap->cat ($dn, array('dn'));
760     if (!$ldap->fetch()){
761       return ($dn);
762     }
764     /* Look for additional attributes */
765     foreach ($this->attributes as $attr){
766       if ($attr == $attribute || $this->$attr == ""){
767         continue;
768       }
770       $dn= "$data+$attr=".$this->$attr.",$base";
771       $ldap->cat ($dn, array('dn'));
772       if (!$ldap->fetch()){
773         return ($dn);
774       }
775     }
777     /* None found */
778     return ("none");
779   }
782   /* Create unique DN */
783   function create_unique_dn($attribute, $base)
784   {
785     $ldap= $this->config->get_ldap_link();
786     $base= preg_replace("/^,*/", "", $base);
788     /* Try to use plain entry first */
789     $dn= "$attribute=".$this->$attribute.",$base";
790     $ldap->cat ($dn, array('dn'));
791     if (!$ldap->fetch()){
792       return ($dn);
793     }
795     /* Look for additional attributes */
796     foreach ($this->attributes as $attr){
797       if ($attr == $attribute || $this->$attr == ""){
798         continue;
799       }
801       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
802       $ldap->cat ($dn, array('dn'));
803       if (!$ldap->fetch()){
804         return ($dn);
805       }
806     }
808     /* None found */
809     return ("none");
810   }
813   function rebind($ldap, $referral)
814   {
815     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
816     if (ldap_bind($ldap, $credentials['ADMIN'], $this->config->get_credentials($credentials['PASSWORD']))) {
817       $this->error = "Success";
818       $this->hascon=true;
819       $this->reconnect= true;
820       return (0);
821     } else {
822       $this->error = "Could not bind to " . $credentials['ADMIN'];
823       return NULL;
824     }
825   }
828   /* Recursively copy ldap object */
829   function _copy($src_dn,$dst_dn)
830   {
831     $ldap=$this->config->get_ldap_link();
832     $ldap->cat($src_dn);
833     $attrs= $ldap->fetch();
835     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
836     $ds= ldap_connect($this->config->current['SERVER']);
837     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
838     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
839       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
840     }
842     $pwd = $this->config->get_credentials($this->config->current['ADMINPASSWORD']);
843     $r=ldap_bind($ds,$this->config->current['ADMINDN'], $pwd);
844     $sr=ldap_read($ds, LDAP::fix($src_dn), "objectClass=*");
846     /* Fill data from LDAP */
847     $new= array();
848     if ($sr) {
849       $ei=ldap_first_entry($ds, $sr);
850       if ($ei) {
851         foreach($attrs as $attr => $val){
852           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
853             for ($i= 0; $i<$info['count']; $i++){
854               if ($info['count'] == 1){
855                 $new[$attr]= $info[$i];
856               } else {
857                 $new[$attr][]= $info[$i];
858               }
859             }
860           }
861         }
862       }
863     }
865     /* close conncetion */
866     ldap_unbind($ds);
868     /* Adapt naming attribute */
869     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
870     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
871     $new[$dst_name]= LDAP::fix($dst_val);
873     /* Check if this is a department.
874      * If it is a dep. && there is a , override in his ou 
875      *  change \2C to , again, else this entry can't be saved ...
876      */
877     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
878       $new['ou'] = str_replace("\\\\,",",",$new['ou']);
879     }
881     /* Save copy */
882     $ldap->connect();
883     $ldap->cd($this->config->current['BASE']);
884     
885     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
887     /* FAIvariable=.../..., cn=.. 
888         could not be saved, because the attribute FAIvariable was different to 
889         the dn FAIvariable=..., cn=... */
890     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
891       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
892     }
893     $ldap->cd($dst_dn);
894     $ldap->add($new);
896     if (!$ldap->success()){
897       trigger_error("Trying to save $dst_dn failed.",
898           E_USER_WARNING);
899       return(FALSE);
900     }
901     return(TRUE);
902   }
905   /* This is a workaround function. */
906   function copy($src_dn, $dst_dn)
907   {
908     /* Rename dn in possible object groups */
909     $ldap= $this->config->get_ldap_link();
910     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::prepare4filter($src_dn).'))',
911         array('cn'));
912     while ($attrs= $ldap->fetch()){
913       $og= new ogroup($this->config, $ldap->getDN());
914       unset($og->member[$src_dn]);
915       $og->member[$dst_dn]= $dst_dn;
916       $og->save ();
917     }
919     $ldap->cat($dst_dn);
920     $attrs= $ldap->fetch();
921     if (count($attrs)){
922       trigger_error("Trying to overwrite ".LDAP::fix($dst_dn).", which already exists.",
923           E_USER_WARNING);
924       return (FALSE);
925     }
927     $ldap->cat($src_dn);
928     $attrs= $ldap->fetch();
929     if (!count($attrs)){
930       trigger_error("Trying to move ".LDAP::fix($src_dn).", which does not seem to exist.",
931           E_USER_WARNING);
932       return (FALSE);
933     }
935     $ldap->cd($src_dn);
936     $ldap->search("objectClass=*",array("dn"));
937     while($attrs = $ldap->fetch()){
938       $src = $attrs['dn'];
939       $dst = preg_replace("/".preg_quote($src_dn, '/')."$/",$dst_dn,$attrs['dn']);
940       $this->_copy($src,$dst);
941     }
942     return (TRUE);
943   }
947   /*! \brief  Move a given ldap object indentified by $src_dn   \
948                to the given destination $dst_dn   \
949               * Ensure that all references are updated (ogroups) \
950               * Update ACLs   \
951               * Update accessTo   \
952       @param  String  The source dn.
953       @param  String  The destination dn.
954       @return Boolean TRUE on success else FALSE.
955    */
956   function rename($src_dn, $dst_dn)
957   {
958     $start = microtime(1);
960     /* Try to move the source entry to the destination position */
961     $ldap = $this->config->get_ldap_link();
962     $ldap->cd($this->config->current['BASE']);
963     $ldap->create_missing_trees(preg_replace("/^[^,]+,/","",$dst_dn));
964     if (!$ldap->rename_dn($src_dn,$dst_dn)){
965 #      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $src_dn, "", get_class()));
966       new log("debug","Ldap Protocol v3 implementation error, ldap_rename failed, falling back to manual copy.","FROM: $src_dn  -- TO: $dst_dn",array(),$ldap->get_error());
967       @DEBUG(DEBUG_LDAP,__LINE__,__FUNCTION__,__FILE__,"Rename failed FROM: $src_dn  -- TO:  $dst_dn", 
968           "Ldap Protocol v3 implementation error, falling back to maunal method.");
969       return(FALSE);
970     }
972     /* Get list of users,groups and roles within this tree,
973         maybe we have to update ACL references.
974      */
975     $leaf_objs = get_list("(|(objectClass=posixGroup)(objectClass=gosaAccount)(objectClass=gosaRole))",array("all"),$dst_dn,
976           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
977     foreach($leaf_objs as $obj){
978       $new_dn = $obj['dn'];
979       $old_dn = preg_replace("/".preg_quote(LDAP::convert($dst_dn), '/')."$/i",$src_dn,LDAP::convert($new_dn));
980       $this->update_acls($old_dn,$new_dn); 
981     }
983     // Migrate objectgroups if needed
984     $ogroups = get_sub_list("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter(LDAP::fix($src_dn))."))","ogroups", array(get_ou("ogroupRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
986     // Walk through all objectGroups
987     foreach($ogroups as $ogroup){
988       // Migrate old to new dn
989       $o_ogroup= new ogroup($this->config,$ogroup['dn']);
990       if (isset($o_group->member[$src_dn])) {
991         unset($o_ogroup->member[$src_dn]);
992       }
993       $o_ogroup->member[$dst_dn]= $dst_dn;
994       
995       // Save object group
996       $o_ogroup->save();
997     }
999     // Migrate rfc groups if needed
1000     $groups = get_sub_list("(&(objectClass=posixGroup)(member=".LDAP::prepare4filter(LDAP::fix($src_dn))."))","groups", array(get_ou("groupRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
1002     // Walk through all POSIX groups
1003     foreach($groups as $group){
1004       // Migrate old to new dn
1005       $o_group= new group($this->config,$group['dn']);
1006       if (isset($o_group->member[$src_dn])) {
1007         unset($o_group->member[$src_dn]);
1008       }
1009       $o_group->member[$dst_dn]= $dst_dn;
1010       
1011       // Save object group
1012       $o_group->save();
1013     }
1015     /* Update roles to use the new entry dn */
1016     $roles = get_sub_list("(&(objectClass=organizationalRole)(roleOccupant=".LDAP::prepare4filter(LDAP::fix($src_dn))."))","roles", array(get_ou("roleRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
1018     // Walk through all roles
1019     foreach($roles as $role){
1020       $role = new roleGeneric($this->config,$role['dn']);
1021       $key= array_search($src_dn, $role->roleOccupant);      
1022       if($key !== FALSE){
1023         $role->roleOccupant[$key] = $dst_dn;
1024         $role->save();
1025       }
1026     }
1027  
1028     /* Check if there are gosa departments moved. 
1029        If there were deps moved, the force reload of config->deps.
1030      */
1031     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
1032           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
1033   
1034     if(count($leaf_deps)){
1035       $this->config->get_departments();
1036       $this->config->make_idepartments();
1037       session::global_set("config",$this->config);
1038       $ui =get_userinfo();
1039       $ui->reset_acl_cache();
1040     }
1042     return(TRUE); 
1043   }
1047   function move($src_dn, $dst_dn)
1048   {
1049     /* Do not copy if only upper- lowercase has changed */
1050     if(strtolower($src_dn) == strtolower($dst_dn)){
1051       return(TRUE);
1052     }
1054     
1055     /* Try to move the entry instead of copy & delete
1056      */
1057     if(TRUE){
1059       /* Try to move with ldap routines, if this was not successfull
1060           fall back to the old style copy & remove method 
1061        */
1062       if($this->rename($src_dn, $dst_dn)){
1063         return(TRUE);
1064       }else{
1065         // See code below.
1066       }
1067     }
1069     /* Copy source to destination */
1070     if (!$this->copy($src_dn, $dst_dn)){
1071       return (FALSE);
1072     }
1074     /* Delete source */
1075     $ldap= $this->config->get_ldap_link();
1076     $ldap->rmdir_recursive($src_dn);
1077     if (!$ldap->success()){
1078       trigger_error("Trying to delete $src_dn failed.",
1079           E_USER_WARNING);
1080       return (FALSE);
1081     }
1083     return (TRUE);
1084   }
1087   /* Move/Rename complete trees */
1088   function recursive_move($src_dn, $dst_dn)
1089   {
1090     /* Check if the destination entry exists */
1091     $ldap= $this->config->get_ldap_link();
1093     /* Check if destination exists - abort */
1094     $ldap->cat($dst_dn, array('dn'));
1095     if ($ldap->fetch()){
1096       trigger_error("recursive_move $dst_dn already exists.",
1097           E_USER_WARNING);
1098       return (FALSE);
1099     }
1101     $this->copy($src_dn, $dst_dn);
1103     /* Remove src_dn */
1104     $ldap->cd($src_dn);
1105     $ldap->recursive_remove($src_dn);
1106     return (TRUE);
1107   }
1110   function handle_post_events($mode, $add_attrs= array())
1111   {
1112     switch ($mode){
1113       case "add":
1114         $this->postcreate($add_attrs);
1115       break;
1117       case "modify":
1118         $this->postmodify($add_attrs);
1119       break;
1121       case "remove":
1122         $this->postremove($add_attrs);
1123       break;
1124     }
1125   }
1128   function saveCopyDialog(){
1129   }
1132   function getCopyDialog(){
1133     return(array("string"=>"","status"=>""));
1134   }
1137   function PrepareForCopyPaste($source)
1138   {
1139     $todo = $this->attributes;
1140     if(isset($this->CopyPasteVars)){
1141       $todo = array_merge($todo,$this->CopyPasteVars);
1142     }
1144     if(count($this->objectclasses)){
1145       $this->is_account = TRUE;
1146       foreach($this->objectclasses as $class){
1147         if(!in_array($class,$source['objectClass'])){
1148           $this->is_account = FALSE;
1149         }
1150       }
1151     }
1153     foreach($todo as $var){
1154       if (isset($source[$var])){
1155         if(isset($source[$var]['count'])){
1156           if($source[$var]['count'] > 1){
1157             $this->$var = array();
1158             $tmp = array();
1159             for($i = 0 ; $i < $source[$var]['count']; $i++){
1160               $tmp = $source[$var][$i];
1161             }
1162             $this->$var = $tmp;
1163           }else{
1164             $this->$var = $source[$var][0];
1165           }
1166         }else{
1167           $this->$var= $source[$var];
1168         }
1169       }
1170     }
1171   }
1173   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1174   {
1175     /* Skip tagging? 
1176        If this is called from departmentGeneric, we have to skip this
1177         tagging procedure. 
1178      */
1179     if($this->skipTagging){
1180       return;
1181     }
1183     /* No dn? Self-operation... */
1184     if ($dn == ""){
1185       $dn= $this->dn;
1187       /* No tag? Find it yourself... */
1188       if ($tag == ""){
1189         $len= strlen($dn);
1191         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1192         $relevant= array();
1193         foreach ($this->config->adepartments as $key => $ntag){
1195           /* This one is bigger than our dn, its not relevant... */
1196           if ($len < strlen($key)){
1197             continue;
1198           }
1200           /* This one matches with the latter part. Break and don't fix this entry */
1201           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
1202             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1203             $relevant[strlen($key)]= $ntag;
1204             continue;
1205           }
1207         }
1209         /* If we've some relevant tags to set, just get the longest one */
1210         if (count($relevant)){
1211           ksort($relevant);
1212           $tmp= array_keys($relevant);
1213           $idx= end($tmp);
1214           $tag= $relevant[$idx];
1215           $this->gosaUnitTag= $tag;
1216         }
1217       }
1218     }
1219   
1220     /* Remove tags that may already be here... */
1221     remove_objectClass("gosaAdministrativeUnitTag", $at);
1222     if (isset($at['gosaUnitTag'])){
1223         unset($at['gosaUnitTag']);
1224     }
1226     /* Set tag? */
1227     if ($tag != ""){
1228       add_objectClass("gosaAdministrativeUnitTag", $at);
1229       $at['gosaUnitTag']= $tag;
1230     }
1232     /* Initially this object was tagged. 
1233        - But now, it is no longer inside a tagged department. 
1234        So force the remove of the tag.
1235        (objectClass was already removed obove)
1236      */
1237     if($tag == "" && $this->gosaUnitTag){
1238       $at['gosaUnitTag'] = array();
1239     }
1240   }
1243   /* Add possibility to stop remove process */
1244   function allow_remove()
1245   {
1246     $reason= "";
1247     return $reason;
1248   }
1251   /* Create a snapshot of the current object */
1252   function create_snapshot($type= "snapshot", $description= array())
1253   {
1255     /* Check if snapshot functionality is enabled */
1256     if(!$this->snapshotEnabled()){
1257       return;
1258     }
1260     /* Get configuration from gosa.conf */
1261     $config = $this->config;
1263     /* Create lokal ldap connection */
1264     $ldap= $this->config->get_ldap_link();
1265     $ldap->cd($this->config->current['BASE']);
1267     /* check if there are special server configurations for snapshots */
1268     if($config->get_cfg_value("snapshotURI") == ""){
1270       /* Source and destination server are both the same, just copy source to dest obj */
1271       $ldap_to      = $ldap;
1272       $snapldapbase = $this->config->current['BASE'];
1274     }else{
1275       $server         = $config->get_cfg_value("snapshotURI");
1276       $user           = $config->get_cfg_value("snapshotAdminDn");
1277       $password       = $this->config->get_credentials($config->get_cfg_value("snapshotAdminPassword"));
1278       $snapldapbase   = $config->get_cfg_value("snapshotBase");
1280       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1281       $ldap_to -> cd($snapldapbase);
1283       if (!$ldap_to->success()){
1284         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1285       }
1287     }
1289     /* check if the dn exists */ 
1290     if ($ldap->dn_exists($this->dn)){
1292       /* Extract seconds & mysecs, they are used as entry index */
1293       list($usec, $sec)= explode(" ", microtime());
1295       /* Collect some infos */
1296       $base           = $this->config->current['BASE'];
1297       $snap_base      = $config->get_cfg_value("snapshotBase");
1298       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1299       $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1301       /* Create object */
1302 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1303       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1304       $newName          = str_replace(".", "", $sec."-".$usec);
1305       $target= array();
1306       $target['objectClass']            = array("top", "gosaSnapshotObject");
1307       $target['gosaSnapshotData']       = gzcompress($data, 6);
1308       $target['gosaSnapshotType']       = $type;
1309       $target['gosaSnapshotDN']         = $this->dn;
1310       $target['description']            = $description;
1311       $target['gosaSnapshotTimestamp']  = $newName;
1313       /* Insert the new snapshot 
1314          But we have to check first, if the given gosaSnapshotTimestamp
1315          is already used, in this case we should increment this value till there is 
1316          an unused value. */ 
1317       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1318       $ldap_to->cat($new_dn);
1319       while($ldap_to->count()){
1320         $ldap_to->cat($new_dn);
1321         $newName = str_replace(".", "", $sec."-".($usec++));
1322         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1323         $target['gosaSnapshotTimestamp']  = $newName;
1324       } 
1326       /* Inset this new snapshot */
1327       $ldap_to->cd($snapldapbase);
1328       $ldap_to->create_missing_trees($snapldapbase);
1329       $ldap_to->create_missing_trees($new_base);
1330       $ldap_to->cd($new_dn);
1331       $ldap_to->add($target);
1332       if (!$ldap_to->success()){
1333         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $new_dn, LDAP_ADD, get_class()));
1334       }
1336       if (!$ldap->success()){
1337         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $new_base, "", get_class()));
1338       }
1340     }
1341   }
1343   function remove_snapshot($dn)
1344   {
1345     $ui       = get_userinfo();
1346     $old_dn   = $this->dn; 
1347     $this->dn = $dn;
1348     $ldap = $this->config->get_ldap_link();
1349     $ldap->cd($this->config->current['BASE']);
1350     $ldap->rmdir_recursive($this->dn);
1351     if(!$ldap->success()){
1352       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn));
1353     }
1354     $this->dn = $old_dn;
1355   }
1358   /* returns true if snapshots are enabled, and false if it is disalbed
1359      There will also be some errors psoted, if the configuration failed */
1360   function snapshotEnabled()
1361   {
1362     return $this->config->snapshotEnabled();
1363   }
1366   /* Return available snapshots for the given base 
1367    */
1368   function Available_SnapsShots($dn,$raw = false)
1369   {
1370     if(!$this->snapshotEnabled()) return(array());
1372     /* Create an additional ldap object which
1373        points to our ldap snapshot server */
1374     $ldap= $this->config->get_ldap_link();
1375     $ldap->cd($this->config->current['BASE']);
1376     $cfg= &$this->config->current;
1378     /* check if there are special server configurations for snapshots */
1379     if($this->config->get_cfg_value("snapshotURI") == ""){
1380       $ldap_to      = $ldap;
1381     }else{
1382       $server         = $this->config->get_cfg_value("snapshotURI");
1383       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1384       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1385       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1386       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1387       $ldap_to -> cd($snapldapbase);
1388       if (!$ldap_to->success()){
1389         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1390       }
1391     }
1393     /* Prepare bases and some other infos */
1394     $base           = $this->config->current['BASE'];
1395     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1396     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1397     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1398     $tmp            = array(); 
1400     /* Fetch all objects with  gosaSnapshotDN=$dn */
1401     $ldap_to->cd($new_base);
1402     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1403         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1405     /* Put results into a list and add description if missing */
1406     while($entry = $ldap_to->fetch()){ 
1407       if(!isset($entry['description'][0])){
1408         $entry['description'][0]  = "";
1409       }
1410       $tmp[] = $entry; 
1411     }
1413     /* Return the raw array, or format the result */
1414     if($raw){
1415       return($tmp);
1416     }else{  
1417       $tmp2 = array();
1418       foreach($tmp as $entry){
1419         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1420       }
1421     }
1422     return($tmp2);
1423   }
1426   function getAllDeletedSnapshots($base_of_object,$raw = false)
1427   {
1428     if(!$this->snapshotEnabled()) return(array());
1430     /* Create an additional ldap object which
1431        points to our ldap snapshot server */
1432     $ldap= $this->config->get_ldap_link();
1433     $ldap->cd($this->config->current['BASE']);
1434     $cfg= &$this->config->current;
1436     /* check if there are special server configurations for snapshots */
1437     if($this->config->get_cfg_value("snapshotURI") == ""){
1438       $ldap_to      = $ldap;
1439     }else{
1440       $server         = $this->config->get_cfg_value("snapshotURI");
1441       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1442       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1443       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1444       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1445       $ldap_to -> cd($snapldapbase);
1446       if (!$ldap_to->success()){
1447         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1448       }
1449     }
1451     /* Prepare bases */ 
1452     $base           = $this->config->current['BASE'];
1453     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1454     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1456     /* Fetch all objects and check if they do not exist anymore */
1457     $ui = get_userinfo();
1458     $tmp = array();
1459     $ldap_to->cd($new_base);
1460     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1461     while($entry = $ldap_to->fetch()){
1463       $chk =  str_replace($new_base,"",$entry['dn']);
1464       if(preg_match("/,ou=/",$chk)) continue;
1466       if(!isset($entry['description'][0])){
1467         $entry['description'][0]  = "";
1468       }
1469       $tmp[] = $entry; 
1470     }
1472     /* Check if entry still exists */
1473     foreach($tmp as $key => $entry){
1474       $ldap->cat($entry['gosaSnapshotDN'][0]);
1475       if($ldap->count()){
1476         unset($tmp[$key]);
1477       }
1478     }
1480     /* Format result as requested */
1481     if($raw) {
1482       return($tmp);
1483     }else{
1484       $tmp2 = array();
1485       foreach($tmp as $key => $entry){
1486         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1487       }
1488     }
1489     return($tmp2);
1490   } 
1493   /* Restore selected snapshot */
1494   function restore_snapshot($dn)
1495   {
1496     if(!$this->snapshotEnabled()) return(array());
1498     $ldap= $this->config->get_ldap_link();
1499     $ldap->cd($this->config->current['BASE']);
1500     $cfg= &$this->config->current;
1502     /* check if there are special server configurations for snapshots */
1503     if($this->config->get_cfg_value("snapshotURI") == ""){
1504       $ldap_to      = $ldap;
1505     }else{
1506       $server         = $this->config->get_cfg_value("snapshotURI");
1507       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1508       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1509       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1510       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1511       $ldap_to -> cd($snapldapbase);
1512       if (!$ldap_to->success()){
1513         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1514       }
1515     }
1517     /* Get the snapshot */ 
1518     $ldap_to->cat($dn);
1519     $restoreObject = $ldap_to->fetch();
1521     /* Prepare import string */
1522     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1524     /* Import the given data */
1525     $err = "";
1526     $ldap->import_complete_ldif($data,$err,false,false);
1527     if (!$ldap->success()){
1528       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, "", get_class()));
1529     }
1530   }
1533   function showSnapshotDialog($base,$baseSuffixe,&$parent)
1534   {
1535     $once = true;
1536     $ui = get_userinfo();
1537     $this->parent = $parent;
1539     foreach($_POST as $name => $value){
1541       /* Create a new snapshot, display a dialog */
1542       if(preg_match("/^CreateSnapShotDialog_[^_]*_[xy]$/",$name) && $once){
1544                           $entry = base64_decode(preg_replace("/^CreateSnapShotDialog_([^_]*)_[xy]$/","\\1",$name));
1545         $once = false;
1546         $entry = preg_replace("/^CreateSnapShotDialog_/","",$entry);
1548         if(!empty($entry) && $ui->allow_snapshot_create($entry,$this->parent->acl_module)){
1549           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1550         }else{
1551           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to create a snapshot for %s."),$entry),ERROR_DIALOG);
1552         }
1553       }  
1554   
1555       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1556       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1557         $once = false;
1558         $entry = base64_decode(preg_replace("/^RestoreSnapShotDialog_([^_]*)_[xy]$/i","\\1",$name));
1559         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1560           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1561           $this->snapDialog->display_restore_dialog = true;
1562         }else{
1563           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1564         }
1565       }
1567       /* Restore one of the already deleted objects */
1568       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1569           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1570         $once = false;
1572         if($ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1573           $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1574           $this->snapDialog->set_snapshot_bases($baseSuffixe);
1575           $this->snapDialog->display_restore_dialog      = true;
1576           $this->snapDialog->display_all_removed_objects  = true;
1577         }else{
1578           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$base),ERROR_DIALOG);
1579         }
1580       }
1582       /* Restore selected snapshot */
1583       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1584         $once = false;
1585         $entry = base64_decode(preg_replace("/^RestoreSnapShot_([^_]*)_[xy]$/i","\\1",$name));
1587         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1588           $this->restore_snapshot($entry);
1589           $this->snapDialog = NULL;
1590         }else{
1591           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1592         }
1593       }
1594     }
1596     /* Create a new snapshot requested, check
1597        the given attributes and create the snapshot*/
1598     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1599       $this->snapDialog->save_object();
1600       $msgs = $this->snapDialog->check();
1601       if(count($msgs)){
1602         foreach($msgs as $msg){
1603           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
1604         }
1605       }else{
1606         $this->dn =  $this->snapDialog->dn;
1607         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1608         $this->snapDialog = NULL;
1609       }
1610     }
1612     /* Restore is requested, restore the object with the posted dn .*/
1613     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1614     }
1616     if(isset($_POST['CancelSnapshot'])){
1617       $this->snapDialog = NULL;
1618     }
1620     if(is_object($this->snapDialog )){
1621       $this->snapDialog->save_object();
1622       return($this->snapDialog->execute());
1623     }
1624   }
1627   static function plInfo()
1628   {
1629     return array();
1630   }
1633   function set_acl_base($base)
1634   {
1635     $this->acl_base= $base;
1636   }
1639   function set_acl_category($category)
1640   {
1641     $this->acl_category= "$category/";
1642   }
1645   function acl_is_writeable($attribute,$skip_write = FALSE)
1646   {
1647     if($this->read_only) return(FALSE);
1648     $ui= get_userinfo();
1649     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1650   }
1653   function acl_is_readable($attribute)
1654   {
1655     $ui= get_userinfo();
1656     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1657   }
1660   function acl_is_createable($base ="")
1661   {
1662     if($this->read_only) return(FALSE);
1663     $ui= get_userinfo();
1664     if($base == "") $base = $this->acl_base;
1665     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1666   }
1669   function acl_is_removeable($base ="")
1670   {
1671     if($this->read_only) return(FALSE);
1672     $ui= get_userinfo();
1673     if($base == "") $base = $this->acl_base;
1674     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1675   }
1678   function acl_is_moveable($base = "")
1679   {
1680     if($this->read_only) return(FALSE);
1681     $ui= get_userinfo();
1682     if($base == "") $base = $this->acl_base;
1683     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1684   }
1687   function acl_have_any_permissions()
1688   {
1689   }
1692   function getacl($attribute,$skip_write= FALSE)
1693   {
1694     $ui= get_userinfo();
1695     $skip_write |= $this->read_only;
1696     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1697   }
1700   /*! \brief    Returns a list of all available departments for this object.  
1701                 If this object is new, all departments we are allowed to create a new user in are returned.
1702                 If this is an existing object, return all deps. we are allowed to move tis object too.
1704       @return   Array [dn] => "..name"  // All deps. we are allowed to act on.
1705   */
1706   function get_allowed_bases()
1707   {
1708     $ui = get_userinfo();
1709     $deps = array();
1711     /* Is this a new object ? Or just an edited existing object */
1712     if(!$this->initially_was_account && $this->is_account){
1713       $new = true;
1714     }else{
1715       $new = false;
1716     }
1718     foreach($this->config->idepartments as $dn => $name){
1719       if($new && $this->acl_is_createable($dn)){
1720         $deps[$dn] = $name;
1721       }elseif(!$new && $this->acl_is_moveable($dn)){
1722         $deps[$dn] = $name;
1723       }
1724     }
1726     /* Add current base */      
1727     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1728       $deps[$this->base] = $this->config->idepartments[$this->base];
1729     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1731     }else{
1732       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1733     }
1734     return($deps);
1735   }
1738   /* This function updates ACL settings if $old_dn was used.
1739    *  $old_dn   specifies the actually used dn
1740    *  $new_dn   specifies the destiantion dn
1741    */
1742   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1743   {
1744     /* Check if old_dn is empty. This should never happen */
1745     if(empty($old_dn) || empty($new_dn)){
1746       trigger_error("Failed to check acl dependencies, wrong dn given.");
1747       return;
1748     }
1750     /* Update userinfo if necessary */
1751     $ui = session::global_get('ui');
1752     if($ui->dn == $old_dn){
1753       $ui->dn = $new_dn;
1754       session::global_set('ui',$ui);
1755       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1756     }
1758     /* Object was moved, ensure that all acls will be moved too */
1759     if($new_dn != $old_dn && $old_dn != "new"){
1761       /* get_ldap configuration */
1762       $update = array();
1763       $ldap = $this->config->get_ldap_link();
1764       $ldap->cd ($this->config->current['BASE']);
1765       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1766       while($attrs = $ldap->fetch()){
1767         $acls = array();
1768         $found = false;
1769         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1770           $acl_parts = split(":",$attrs['gosaAclEntry'][$i]);
1772           /* Roles uses antoher data storage order, members are stored int the third part, 
1773              while the members in direct ACL assignments are stored in the second part.
1774            */
1775           $id = ($acl_parts[1] == "role") ? 3 : 2;
1777           /* Update member entries to use $new_dn instead of old_dn
1778            */
1779           $members = explode(",",$acl_parts[$id]);
1780           foreach($members as $key => $member){
1781             $member = base64_decode($member);
1782             if($member == $old_dn){
1783               $members[$key] = base64_encode($new_dn);
1784               $found = TRUE;
1785             }
1786           } 
1788           /* Check if the selected role has to updated
1789            */
1790           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1791             $acl_parts[2] = base64_encode($new_dn);
1792             $found = TRUE;
1793           }
1795           /* Build new acl string */ 
1796           $acl_parts[$id] = implode($members,",");
1797           $acls[] = implode($acl_parts,":");
1798         }
1800         /* Acls for this object must be adjusted */
1801         if($found){
1803           $debug_info=  _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1804             $old_dn."</b><br>&nbsp;-"._("to")."&nbsp;<b>".$new_dn."</b><br>";
1805           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1807           $update[$attrs['dn']] =array();
1808           foreach($acls as $acl){
1809             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1810           }
1811         }
1812       }
1814       /* Write updated acls */
1815       foreach($update as $dn => $attrs){
1816         $ldap->cd($dn);
1817         $ldap->modify($attrs);
1818       }
1819     }
1820   }
1822   
1824   /* This function enables the entry Serial ID check.
1825    * If an entry was edited while we have edited the entry too,
1826    *  an error message will be shown. 
1827    * To configure this check correctly read the FAQ.
1828    */    
1829   function enable_CSN_check()
1830   {
1831     $this->CSN_check_active =TRUE;
1832     $this->entryCSN = getEntryCSN($this->dn);
1833   }
1836   /*! \brief  Prepares the plugin to be used for multiple edit
1837    *          Update plugin attributes with given array of attribtues.
1838    *  @param  array   Array with attributes that must be updated.
1839    */
1840   function init_multiple_support($attrs,$all)
1841   {
1842     $ldap= $this->config->get_ldap_link();
1843     $this->multi_attrs    = $attrs;
1844     $this->multi_attrs_all= $all;
1846     /* Copy needed attributes */
1847     foreach ($this->attributes as $val){
1848       $found= array_key_ics($val, $this->multi_attrs);
1849  
1850       if ($found != ""){
1851         if(isset($this->multi_attrs["$val"][0])){
1852           $this->$val= $this->multi_attrs["$val"][0];
1853         }
1854       }
1855     }
1856   }
1858  
1859   /*! \brief  Enables multiple support for this plugin
1860    */
1861   function enable_multiple_support()
1862   {
1863     $this->ignore_account = TRUE;
1864     $this->multiple_support_active = TRUE;
1865   }
1868   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1869       @return array Cotaining all mdofied values. 
1870    */
1871   function get_multi_edit_values()
1872   {
1873     $ret = array();
1874     foreach($this->attributes as $attr){
1875       if(in_array($attr,$this->multi_boxes)){
1876         $ret[$attr] = $this->$attr;
1877       }
1878     }
1879     return($ret);
1880   }
1882   
1883   /*! \brief  Update class variables with values collected by multiple edit.
1884    */
1885   function set_multi_edit_values($attrs)
1886   {
1887     foreach($attrs as $name => $value){
1888       $this->$name = $value;
1889     }
1890   }
1893   /*! \brief execute plugin
1895     Generates the html output for this node
1896    */
1897   function multiple_execute()
1898   {
1899     /* This one is empty currently. Fabian - please fill in the docu code */
1900     session::global_set('current_class_for_help',get_class($this));
1902     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1903     session::set('LOCK_VARS_TO_USE',array());
1904     session::set('LOCK_VARS_USED_GET',array());
1905     session::set('LOCK_VARS_USED_POST',array());
1906     session::set('LOCK_VARS_USED_REQUEST',array());
1907     
1908     return("Multiple edit is currently not implemented for this plugin.");
1909   }
1912   /*! \brief   Save HTML posted data to object for multiple edit
1913    */
1914   function multiple_save_object()
1915   {
1916     if(empty($this->entryCSN) && $this->CSN_check_active){
1917       $this->entryCSN = getEntryCSN($this->dn);
1918     }
1920     /* Save values to object */
1921     $this->multi_boxes = array();
1922     foreach ($this->attributes as $val){
1923   
1924       /* Get selected checkboxes from multiple edit */
1925       if(isset($_POST["use_".$val])){
1926         $this->multi_boxes[] = $val;
1927       }
1929       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
1931         /* Check for modifications */
1932         if (get_magic_quotes_gpc()) {
1933           $data= stripcslashes($_POST["$val"]);
1934         } else {
1935           $data= $this->$val = $_POST["$val"];
1936         }
1937         if ($this->$val != $data){
1938           $this->is_modified= TRUE;
1939         }
1940     
1941         /* IE post fix */
1942         if(isset($data[0]) && $data[0] == chr(194)) {
1943           $data = "";  
1944         }
1945         $this->$val= $data;
1946       }
1947     }
1948   }
1951   /*! \brief  Returns all attributes of this plugin, 
1952                to be able to detect multiple used attributes 
1953                in multi_plugg::detect_multiple_used_attributes().
1954       @return array Attributes required for intialization of multi_plug
1955    */
1956   public function get_multi_init_values()
1957   {
1958     $attrs = $this->attrs;
1959     return($attrs);
1960   }
1963   /*! \brief  Check given values in multiple edit
1964       @return array Error messages
1965    */
1966   function multiple_check()
1967   {
1968     $message = plugin::check();
1969     return($message);
1970   }
1973   /*! \brief  Returns the snapshot header part for "Actions" menu in management dialogs 
1974       @param  $layer_menu  
1975    */   
1976   function get_snapshot_header($base,$category)
1977   {
1978     $str = "";
1979     $ui = get_userinfo();
1980     if($this->snapshotEnabled() && $ui->allow_snapshot_restore($base,$category)){
1982       $ok = false;
1983       foreach($this->get_used_snapshot_bases() as $base){
1984         $ok |= count($this->getAllDeletedSnapshots($base)) >= 1 ;
1985       }
1987       if($ok){
1988         $str = "..|<img class='center' src='images/lists/restore.png' ".
1989           "alt='"._("Restore")."'>&nbsp;"._("Restore").                       "|RestoreDeletedSnapShot|\n";
1990       }else{
1991         $str = "..|<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;"._("Restore")."||\n";
1992       }
1993     }
1994     return($str);
1995   }
1998   function get_snapshot_action($base,$category)
1999   {
2000     $str= ""; 
2001     $ui = get_userinfo();
2002     if($this->snapshotEnabled()){
2003       if ($ui->allow_snapshot_restore($base,$category)){
2005         if(count($this->Available_SnapsShots($base))){
2006           $str.= "<input class='center' type='image' src='images/lists/restore.png'
2007             alt='"._("Restore snapshot")."' name='RestoreSnapShotDialog_".base64_encode($base)."' title='"._("Restore snapshot")."'>&nbsp;";
2008         } else {
2009           $str = "<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;";
2010         }
2011       }
2012       if($ui->allow_snapshot_create($base,$category)){
2013         $str.= "<input class='center' type='image' src='images/snapshot.png'
2014           alt='"._("Create snapshot")."' name='CreateSnapShotDialog_".base64_encode($base)."' 
2015           title='"._("Create a new snapshot from this object")."'>&nbsp;";
2016       }else{
2017         $str = "<img class='center' src='images/empty.png' alt=' '>&nbsp;";
2018       }
2019     }
2021     return($str);
2022   }
2025   function get_copypaste_action($base,$category,$class,$copy = TRUE, $cut = TRUE)
2026   {
2027     $ui = get_userinfo();
2028     $action = "";
2029     if($this->CopyPasteHandler){
2030       if($cut){
2031         if($ui->is_cutable($base,$category,$class)){
2032           $action .= "<input class='center' type='image'
2033             src='images/lists/cut.png' alt='"._("cut")."' name='cut_%KEY%' title='"._("Cut this entry")."'>&nbsp;";
2034         }else{
2035           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
2036         }
2037       }
2038       if($copy){
2039         if($ui->is_copyable($base,$category,$class)){
2040           $action.= "<input class='center' type='image'
2041             src='images/lists/copy.png' alt='"._("copy")."' name='copy_%KEY%' title='"._("Copy this entry")."'>&nbsp;";
2042         }else{
2043           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
2044         }
2045       }
2046     }
2048     return($action); 
2049   }
2052   function get_copypaste_header($base,$category,$copy = TRUE, $cut = TRUE)
2053   {
2054     $s = "";
2055     $ui =get_userinfo();
2057     if(!is_array($category)){
2058       $category = array($category);
2059     }
2061     /* Check permissions for each category, if there is at least one category which 
2062         support read or paste permissions for the given base, then display the specific actions.
2063      */
2064     $readable = $pasteable = false;
2065     foreach($category as $cat){
2066       $readable= $readable || preg_match('/r/', $ui->get_category_permissions($base, $cat));
2067       $pasteable= $pasteable || $ui->is_pasteable($base, $cat) == 1;
2068     }
2069   
2070     if(($cut || $copy) && isset($this->CopyPasteHandler) && is_object($this->CopyPasteHandler)){
2071       if($readable){
2072         $s.= "..|---|\n";
2073         if($copy){
2074           $s.= "..|<img src='images/lists/copy.png' alt='' border='0' class='center'>".
2075             "&nbsp;"._("Copy")."|"."multiple_copy_systems|\n";
2076         }
2077         if($cut){
2078           $s.= "..|<img src='images/lists/cut.png' alt='' border='0' class='center'>".
2079             "&nbsp;"._("Cut")."|"."multiple_cut_systems|\n";
2080         }
2081       }
2083       if($pasteable){
2084         if($this->CopyPasteHandler->entries_queued()){
2085           $img = "<img border='0' class='center' src='images/lists/paste.png' alt=''>";
2086           $s.="..|".$img."&nbsp;"._("Paste")."|editPaste|\n";
2087         }else{
2088           $img = "<img border='0' class='center' src='images/lists/paste-grey.png' alt=''>";
2089           $s.="..|".$img."&nbsp;"._("Paste")."\n";
2090         }
2091       }
2092     }
2093     return($s);
2094   }
2097   function get_used_snapshot_bases()
2098   {
2099      return(array());
2100   }
2102   function is_modal_dialog()
2103   {
2104     return(isset($this->dialog) && $this->dialog);
2105   }
2108 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2109 ?>