Code

Updated management class.
[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, $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     /* 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 ($parent !== NULL){
171         $this->attrs= $parent->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       unset($o_ogroup->member[$src_dn]);
991       $o_ogroup->member[$dst_dn]= $dst_dn;
992       
993       // Save object group
994       $o_ogroup->save();
995     }
997     // Migrate rfc groups if needed
998     $groups = get_sub_list("(&(objectClass=posixGroups)(member=".LDAP::prepare4filter(LDAP::fix($src_dn))."))","groups", array(get_ou("groupRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
1000     // Walk through all POSIX groups
1001     foreach($groups as $group){
1002       // Migrate old to new dn
1003       $o_group= new group($this->config,$group['dn']);
1004       unset($o_group->member[$src_dn]);
1005       $o_group->member[$dst_dn]= $dst_dn;
1006       
1007       // Save object group
1008       $o_group->save();
1009     }
1011     /* Update roles to use the new entry dn */
1012     $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);
1014     // Walk through all roles
1015     foreach($roles as $role){
1016       $role = new roleGeneric($this->config,$role['dn']);
1017       $key= array_search($src_dn, $role->roleOccupant);      
1018       if($key !== FALSE){
1019         $role->roleOccupant[$key] = $dst_dn;
1020         $role->save();
1021       }
1022     }
1023  
1024     /* Check if there are gosa departments moved. 
1025        If there were deps moved, the force reload of config->deps.
1026      */
1027     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
1028           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
1029   
1030     if(count($leaf_deps)){
1031       $this->config->get_departments();
1032       $this->config->make_idepartments();
1033       session::global_set("config",$this->config);
1034       $ui =get_userinfo();
1035       $ui->reset_acl_cache();
1036     }
1038     return(TRUE); 
1039   }
1043   function move($src_dn, $dst_dn)
1044   {
1045     /* Do not copy if only upper- lowercase has changed */
1046     if(strtolower($src_dn) == strtolower($dst_dn)){
1047       return(TRUE);
1048     }
1050     
1051     /* Try to move the entry instead of copy & delete
1052      */
1053     if(TRUE){
1055       /* Try to move with ldap routines, if this was not successfull
1056           fall back to the old style copy & remove method 
1057        */
1058       if($this->rename($src_dn, $dst_dn)){
1059         return(TRUE);
1060       }else{
1061         // See code below.
1062       }
1063     }
1065     /* Copy source to destination */
1066     if (!$this->copy($src_dn, $dst_dn)){
1067       return (FALSE);
1068     }
1070     /* Delete source */
1071     $ldap= $this->config->get_ldap_link();
1072     $ldap->rmdir_recursive($src_dn);
1073     if (!$ldap->success()){
1074       trigger_error("Trying to delete $src_dn failed.",
1075           E_USER_WARNING);
1076       return (FALSE);
1077     }
1079     return (TRUE);
1080   }
1083   /* Move/Rename complete trees */
1084   function recursive_move($src_dn, $dst_dn)
1085   {
1086     /* Check if the destination entry exists */
1087     $ldap= $this->config->get_ldap_link();
1089     /* Check if destination exists - abort */
1090     $ldap->cat($dst_dn, array('dn'));
1091     if ($ldap->fetch()){
1092       trigger_error("recursive_move $dst_dn already exists.",
1093           E_USER_WARNING);
1094       return (FALSE);
1095     }
1097     $this->copy($src_dn, $dst_dn);
1099     /* Remove src_dn */
1100     $ldap->cd($src_dn);
1101     $ldap->recursive_remove($src_dn);
1102     return (TRUE);
1103   }
1106   function handle_post_events($mode, $add_attrs= array())
1107   {
1108     switch ($mode){
1109       case "add":
1110         $this->postcreate($add_attrs);
1111       break;
1113       case "modify":
1114         $this->postmodify($add_attrs);
1115       break;
1117       case "remove":
1118         $this->postremove($add_attrs);
1119       break;
1120     }
1121   }
1124   function saveCopyDialog(){
1125   }
1128   function getCopyDialog(){
1129     return(array("string"=>"","status"=>""));
1130   }
1133   function PrepareForCopyPaste($source)
1134   {
1135     $todo = $this->attributes;
1136     if(isset($this->CopyPasteVars)){
1137       $todo = array_merge($todo,$this->CopyPasteVars);
1138     }
1140     if(count($this->objectclasses)){
1141       $this->is_account = TRUE;
1142       foreach($this->objectclasses as $class){
1143         if(!in_array($class,$source['objectClass'])){
1144           $this->is_account = FALSE;
1145         }
1146       }
1147     }
1149     foreach($todo as $var){
1150       if (isset($source[$var])){
1151         if(isset($source[$var]['count'])){
1152           if($source[$var]['count'] > 1){
1153             $this->$var = array();
1154             $tmp = array();
1155             for($i = 0 ; $i < $source[$var]['count']; $i++){
1156               $tmp = $source[$var][$i];
1157             }
1158             $this->$var = $tmp;
1159           }else{
1160             $this->$var = $source[$var][0];
1161           }
1162         }else{
1163           $this->$var= $source[$var];
1164         }
1165       }
1166     }
1167   }
1169   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1170   {
1171     /* Skip tagging? 
1172        If this is called from departmentGeneric, we have to skip this
1173         tagging procedure. 
1174      */
1175     if($this->skipTagging){
1176       return;
1177     }
1179     /* No dn? Self-operation... */
1180     if ($dn == ""){
1181       $dn= $this->dn;
1183       /* No tag? Find it yourself... */
1184       if ($tag == ""){
1185         $len= strlen($dn);
1187         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1188         $relevant= array();
1189         foreach ($this->config->adepartments as $key => $ntag){
1191           /* This one is bigger than our dn, its not relevant... */
1192           if ($len < strlen($key)){
1193             continue;
1194           }
1196           /* This one matches with the latter part. Break and don't fix this entry */
1197           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
1198             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1199             $relevant[strlen($key)]= $ntag;
1200             continue;
1201           }
1203         }
1205         /* If we've some relevant tags to set, just get the longest one */
1206         if (count($relevant)){
1207           ksort($relevant);
1208           $tmp= array_keys($relevant);
1209           $idx= end($tmp);
1210           $tag= $relevant[$idx];
1211           $this->gosaUnitTag= $tag;
1212         }
1213       }
1214     }
1215   
1216     /* Remove tags that may already be here... */
1217     remove_objectClass("gosaAdministrativeUnitTag", $at);
1218     if (isset($at['gosaUnitTag'])){
1219         unset($at['gosaUnitTag']);
1220     }
1222     /* Set tag? */
1223     if ($tag != ""){
1224       add_objectClass("gosaAdministrativeUnitTag", $at);
1225       $at['gosaUnitTag']= $tag;
1226     }
1228     /* Initially this object was tagged. 
1229        - But now, it is no longer inside a tagged department. 
1230        So force the remove of the tag.
1231        (objectClass was already removed obove)
1232      */
1233     if($tag == "" && $this->gosaUnitTag){
1234       $at['gosaUnitTag'] = array();
1235     }
1236   }
1239   /* Add possibility to stop remove process */
1240   function allow_remove()
1241   {
1242     $reason= "";
1243     return $reason;
1244   }
1247   /* Create a snapshot of the current object */
1248   function create_snapshot($type= "snapshot", $description= array())
1249   {
1251     /* Check if snapshot functionality is enabled */
1252     if(!$this->snapshotEnabled()){
1253       return;
1254     }
1256     /* Get configuration from gosa.conf */
1257     $config = $this->config;
1259     /* Create lokal ldap connection */
1260     $ldap= $this->config->get_ldap_link();
1261     $ldap->cd($this->config->current['BASE']);
1263     /* check if there are special server configurations for snapshots */
1264     if($config->get_cfg_value("snapshotURI") == ""){
1266       /* Source and destination server are both the same, just copy source to dest obj */
1267       $ldap_to      = $ldap;
1268       $snapldapbase = $this->config->current['BASE'];
1270     }else{
1271       $server         = $config->get_cfg_value("snapshotURI");
1272       $user           = $config->get_cfg_value("snapshotAdminDn");
1273       $password       = $this->config->get_credentials($config->get_cfg_value("snapshotAdminPassword"));
1274       $snapldapbase   = $config->get_cfg_value("snapshotBase");
1276       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1277       $ldap_to -> cd($snapldapbase);
1279       if (!$ldap_to->success()){
1280         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1281       }
1283     }
1285     /* check if the dn exists */ 
1286     if ($ldap->dn_exists($this->dn)){
1288       /* Extract seconds & mysecs, they are used as entry index */
1289       list($usec, $sec)= explode(" ", microtime());
1291       /* Collect some infos */
1292       $base           = $this->config->current['BASE'];
1293       $snap_base      = $config->get_cfg_value("snapshotBase");
1294       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1295       $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1297       /* Create object */
1298 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1299       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1300       $newName          = str_replace(".", "", $sec."-".$usec);
1301       $target= array();
1302       $target['objectClass']            = array("top", "gosaSnapshotObject");
1303       $target['gosaSnapshotData']       = gzcompress($data, 6);
1304       $target['gosaSnapshotType']       = $type;
1305       $target['gosaSnapshotDN']         = $this->dn;
1306       $target['description']            = $description;
1307       $target['gosaSnapshotTimestamp']  = $newName;
1309       /* Insert the new snapshot 
1310          But we have to check first, if the given gosaSnapshotTimestamp
1311          is already used, in this case we should increment this value till there is 
1312          an unused value. */ 
1313       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1314       $ldap_to->cat($new_dn);
1315       while($ldap_to->count()){
1316         $ldap_to->cat($new_dn);
1317         $newName = str_replace(".", "", $sec."-".($usec++));
1318         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1319         $target['gosaSnapshotTimestamp']  = $newName;
1320       } 
1322       /* Inset this new snapshot */
1323       $ldap_to->cd($snapldapbase);
1324       $ldap_to->create_missing_trees($snapldapbase);
1325       $ldap_to->create_missing_trees($new_base);
1326       $ldap_to->cd($new_dn);
1327       $ldap_to->add($target);
1328       if (!$ldap_to->success()){
1329         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $new_dn, LDAP_ADD, get_class()));
1330       }
1332       if (!$ldap->success()){
1333         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $new_base, "", get_class()));
1334       }
1336     }
1337   }
1339   function remove_snapshot($dn)
1340   {
1341     $ui       = get_userinfo();
1342     $old_dn   = $this->dn; 
1343     $this->dn = $dn;
1344     $ldap = $this->config->get_ldap_link();
1345     $ldap->cd($this->config->current['BASE']);
1346     $ldap->rmdir_recursive($this->dn);
1347     if(!$ldap->success()){
1348       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn));
1349     }
1350     $this->dn = $old_dn;
1351   }
1354   /* returns true if snapshots are enabled, and false if it is disalbed
1355      There will also be some errors psoted, if the configuration failed */
1356   function snapshotEnabled()
1357   {
1358     return $this->config->snapshotEnabled();
1359   }
1362   /* Return available snapshots for the given base 
1363    */
1364   function Available_SnapsShots($dn,$raw = false)
1365   {
1366     if(!$this->snapshotEnabled()) return(array());
1368     /* Create an additional ldap object which
1369        points to our ldap snapshot server */
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($this->config->get_cfg_value("snapshotURI") == ""){
1376       $ldap_to      = $ldap;
1377     }else{
1378       $server         = $this->config->get_cfg_value("snapshotURI");
1379       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1380       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1381       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1382       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1383       $ldap_to -> cd($snapldapbase);
1384       if (!$ldap_to->success()){
1385         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1386       }
1387     }
1389     /* Prepare bases and some other infos */
1390     $base           = $this->config->current['BASE'];
1391     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1392     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1393     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1394     $tmp            = array(); 
1396     /* Fetch all objects with  gosaSnapshotDN=$dn */
1397     $ldap_to->cd($new_base);
1398     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1399         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1401     /* Put results into a list and add description if missing */
1402     while($entry = $ldap_to->fetch()){ 
1403       if(!isset($entry['description'][0])){
1404         $entry['description'][0]  = "";
1405       }
1406       $tmp[] = $entry; 
1407     }
1409     /* Return the raw array, or format the result */
1410     if($raw){
1411       return($tmp);
1412     }else{  
1413       $tmp2 = array();
1414       foreach($tmp as $entry){
1415         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1416       }
1417     }
1418     return($tmp2);
1419   }
1422   function getAllDeletedSnapshots($base_of_object,$raw = false)
1423   {
1424     if(!$this->snapshotEnabled()) return(array());
1426     /* Create an additional ldap object which
1427        points to our ldap snapshot server */
1428     $ldap= $this->config->get_ldap_link();
1429     $ldap->cd($this->config->current['BASE']);
1430     $cfg= &$this->config->current;
1432     /* check if there are special server configurations for snapshots */
1433     if($this->config->get_cfg_value("snapshotURI") == ""){
1434       $ldap_to      = $ldap;
1435     }else{
1436       $server         = $this->config->get_cfg_value("snapshotURI");
1437       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1438       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1439       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1440       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1441       $ldap_to -> cd($snapldapbase);
1442       if (!$ldap_to->success()){
1443         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1444       }
1445     }
1447     /* Prepare bases */ 
1448     $base           = $this->config->current['BASE'];
1449     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1450     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1452     /* Fetch all objects and check if they do not exist anymore */
1453     $ui = get_userinfo();
1454     $tmp = array();
1455     $ldap_to->cd($new_base);
1456     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1457     while($entry = $ldap_to->fetch()){
1459       $chk =  str_replace($new_base,"",$entry['dn']);
1460       if(preg_match("/,ou=/",$chk)) continue;
1462       if(!isset($entry['description'][0])){
1463         $entry['description'][0]  = "";
1464       }
1465       $tmp[] = $entry; 
1466     }
1468     /* Check if entry still exists */
1469     foreach($tmp as $key => $entry){
1470       $ldap->cat($entry['gosaSnapshotDN'][0]);
1471       if($ldap->count()){
1472         unset($tmp[$key]);
1473       }
1474     }
1476     /* Format result as requested */
1477     if($raw) {
1478       return($tmp);
1479     }else{
1480       $tmp2 = array();
1481       foreach($tmp as $key => $entry){
1482         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1483       }
1484     }
1485     return($tmp2);
1486   } 
1489   /* Restore selected snapshot */
1490   function restore_snapshot($dn)
1491   {
1492     if(!$this->snapshotEnabled()) return(array());
1494     $ldap= $this->config->get_ldap_link();
1495     $ldap->cd($this->config->current['BASE']);
1496     $cfg= &$this->config->current;
1498     /* check if there are special server configurations for snapshots */
1499     if($this->config->get_cfg_value("snapshotURI") == ""){
1500       $ldap_to      = $ldap;
1501     }else{
1502       $server         = $this->config->get_cfg_value("snapshotURI");
1503       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1504       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1505       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1506       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1507       $ldap_to -> cd($snapldapbase);
1508       if (!$ldap_to->success()){
1509         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1510       }
1511     }
1513     /* Get the snapshot */ 
1514     $ldap_to->cat($dn);
1515     $restoreObject = $ldap_to->fetch();
1517     /* Prepare import string */
1518     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1520     /* Import the given data */
1521     $err = "";
1522     $ldap->import_complete_ldif($data,$err,false,false);
1523     if (!$ldap->success()){
1524       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, "", get_class()));
1525     }
1526   }
1529   function showSnapshotDialog($base,$baseSuffixe,&$parent)
1530   {
1531     $once = true;
1532     $ui = get_userinfo();
1533     $this->parent = $parent;
1535     foreach($_POST as $name => $value){
1537       /* Create a new snapshot, display a dialog */
1538       if(preg_match("/^CreateSnapShotDialog_[^_]*_[xy]$/",$name) && $once){
1540                           $entry = base64_decode(preg_replace("/^CreateSnapShotDialog_([^_]*)_[xy]$/","\\1",$name));
1541         $once = false;
1542         $entry = preg_replace("/^CreateSnapShotDialog_/","",$entry);
1544         if(!empty($entry) && $ui->allow_snapshot_create($entry,$this->parent->acl_module)){
1545           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1546         }else{
1547           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to create a snapshot for %s."),$entry),ERROR_DIALOG);
1548         }
1549       }  
1550   
1551       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1552       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1553         $once = false;
1554         $entry = base64_decode(preg_replace("/^RestoreSnapShotDialog_([^_]*)_[xy]$/i","\\1",$name));
1555         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1556           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1557           $this->snapDialog->display_restore_dialog = true;
1558         }else{
1559           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1560         }
1561       }
1563       /* Restore one of the already deleted objects */
1564       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1565           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1566         $once = false;
1568         if($ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1569           $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1570           $this->snapDialog->set_snapshot_bases($baseSuffixe);
1571           $this->snapDialog->display_restore_dialog      = true;
1572           $this->snapDialog->display_all_removed_objects  = true;
1573         }else{
1574           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$base),ERROR_DIALOG);
1575         }
1576       }
1578       /* Restore selected snapshot */
1579       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1580         $once = false;
1581         $entry = base64_decode(preg_replace("/^RestoreSnapShot_([^_]*)_[xy]$/i","\\1",$name));
1583         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1584           $this->restore_snapshot($entry);
1585           $this->snapDialog = NULL;
1586         }else{
1587           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1588         }
1589       }
1590     }
1592     /* Create a new snapshot requested, check
1593        the given attributes and create the snapshot*/
1594     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1595       $this->snapDialog->save_object();
1596       $msgs = $this->snapDialog->check();
1597       if(count($msgs)){
1598         foreach($msgs as $msg){
1599           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
1600         }
1601       }else{
1602         $this->dn =  $this->snapDialog->dn;
1603         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1604         $this->snapDialog = NULL;
1605       }
1606     }
1608     /* Restore is requested, restore the object with the posted dn .*/
1609     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1610     }
1612     if(isset($_POST['CancelSnapshot'])){
1613       $this->snapDialog = NULL;
1614     }
1616     if(is_object($this->snapDialog )){
1617       $this->snapDialog->save_object();
1618       return($this->snapDialog->execute());
1619     }
1620   }
1623   static function plInfo()
1624   {
1625     return array();
1626   }
1629   function set_acl_base($base)
1630   {
1631     $this->acl_base= $base;
1632   }
1635   function set_acl_category($category)
1636   {
1637     $this->acl_category= "$category/";
1638   }
1641   function acl_is_writeable($attribute,$skip_write = FALSE)
1642   {
1643     if($this->read_only) return(FALSE);
1644     $ui= get_userinfo();
1645     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1646   }
1649   function acl_is_readable($attribute)
1650   {
1651     $ui= get_userinfo();
1652     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1653   }
1656   function acl_is_createable($base ="")
1657   {
1658     if($this->read_only) return(FALSE);
1659     $ui= get_userinfo();
1660     if($base == "") $base = $this->acl_base;
1661     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1662   }
1665   function acl_is_removeable($base ="")
1666   {
1667     if($this->read_only) return(FALSE);
1668     $ui= get_userinfo();
1669     if($base == "") $base = $this->acl_base;
1670     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1671   }
1674   function acl_is_moveable($base = "")
1675   {
1676     if($this->read_only) return(FALSE);
1677     $ui= get_userinfo();
1678     if($base == "") $base = $this->acl_base;
1679     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1680   }
1683   function acl_have_any_permissions()
1684   {
1685   }
1688   function getacl($attribute,$skip_write= FALSE)
1689   {
1690     $ui= get_userinfo();
1691     $skip_write |= $this->read_only;
1692     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1693   }
1696   /*! \brief    Returns a list of all available departments for this object.  
1697                 If this object is new, all departments we are allowed to create a new user in are returned.
1698                 If this is an existing object, return all deps. we are allowed to move tis object too.
1700       @return   Array [dn] => "..name"  // All deps. we are allowed to act on.
1701   */
1702   function get_allowed_bases()
1703   {
1704     $ui = get_userinfo();
1705     $deps = array();
1707     /* Is this a new object ? Or just an edited existing object */
1708     if(!$this->initially_was_account && $this->is_account){
1709       $new = true;
1710     }else{
1711       $new = false;
1712     }
1714     foreach($this->config->idepartments as $dn => $name){
1715       if($new && $this->acl_is_createable($dn)){
1716         $deps[$dn] = $name;
1717       }elseif(!$new && $this->acl_is_moveable($dn)){
1718         $deps[$dn] = $name;
1719       }
1720     }
1722     /* Add current base */      
1723     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1724       $deps[$this->base] = $this->config->idepartments[$this->base];
1725     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1727     }else{
1728       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1729     }
1730     return($deps);
1731   }
1734   /* This function updates ACL settings if $old_dn was used.
1735    *  $old_dn   specifies the actually used dn
1736    *  $new_dn   specifies the destiantion dn
1737    */
1738   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1739   {
1740     /* Check if old_dn is empty. This should never happen */
1741     if(empty($old_dn) || empty($new_dn)){
1742       trigger_error("Failed to check acl dependencies, wrong dn given.");
1743       return;
1744     }
1746     /* Update userinfo if necessary */
1747     $ui = session::global_get('ui');
1748     if($ui->dn == $old_dn){
1749       $ui->dn = $new_dn;
1750       session::global_set('ui',$ui);
1751       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1752     }
1754     /* Object was moved, ensure that all acls will be moved too */
1755     if($new_dn != $old_dn && $old_dn != "new"){
1757       /* get_ldap configuration */
1758       $update = array();
1759       $ldap = $this->config->get_ldap_link();
1760       $ldap->cd ($this->config->current['BASE']);
1761       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1762       while($attrs = $ldap->fetch()){
1763         $acls = array();
1764         $found = false;
1765         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1766           $acl_parts = split(":",$attrs['gosaAclEntry'][$i]);
1768           /* Roles uses antoher data storage order, members are stored int the third part, 
1769              while the members in direct ACL assignments are stored in the second part.
1770            */
1771           $id = ($acl_parts[1] == "role") ? 3 : 2;
1773           /* Update member entries to use $new_dn instead of old_dn
1774            */
1775           $members = explode(",",$acl_parts[$id]);
1776           foreach($members as $key => $member){
1777             $member = base64_decode($member);
1778             if($member == $old_dn){
1779               $members[$key] = base64_encode($new_dn);
1780               $found = TRUE;
1781             }
1782           } 
1784           /* Check if the selected role has to updated
1785            */
1786           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1787             $acl_parts[2] = base64_encode($new_dn);
1788             $found = TRUE;
1789           }
1791           /* Build new acl string */ 
1792           $acl_parts[$id] = implode($members,",");
1793           $acls[] = implode($acl_parts,":");
1794         }
1796         /* Acls for this object must be adjusted */
1797         if($found){
1799           $debug_info=  _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1800             $old_dn."</b><br>&nbsp;-"._("to")."&nbsp;<b>".$new_dn."</b><br>";
1801           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1803           $update[$attrs['dn']] =array();
1804           foreach($acls as $acl){
1805             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1806           }
1807         }
1808       }
1810       /* Write updated acls */
1811       foreach($update as $dn => $attrs){
1812         $ldap->cd($dn);
1813         $ldap->modify($attrs);
1814       }
1815     }
1816   }
1818   
1820   /* This function enables the entry Serial ID check.
1821    * If an entry was edited while we have edited the entry too,
1822    *  an error message will be shown. 
1823    * To configure this check correctly read the FAQ.
1824    */    
1825   function enable_CSN_check()
1826   {
1827     $this->CSN_check_active =TRUE;
1828     $this->entryCSN = getEntryCSN($this->dn);
1829   }
1832   /*! \brief  Prepares the plugin to be used for multiple edit
1833    *          Update plugin attributes with given array of attribtues.
1834    *  @param  array   Array with attributes that must be updated.
1835    */
1836   function init_multiple_support($attrs,$all)
1837   {
1838     $ldap= $this->config->get_ldap_link();
1839     $this->multi_attrs    = $attrs;
1840     $this->multi_attrs_all= $all;
1842     /* Copy needed attributes */
1843     foreach ($this->attributes as $val){
1844       $found= array_key_ics($val, $this->multi_attrs);
1845  
1846       if ($found != ""){
1847         if(isset($this->multi_attrs["$val"][0])){
1848           $this->$val= $this->multi_attrs["$val"][0];
1849         }
1850       }
1851     }
1852   }
1854  
1855   /*! \brief  Enables multiple support for this plugin
1856    */
1857   function enable_multiple_support()
1858   {
1859     $this->ignore_account = TRUE;
1860     $this->multiple_support_active = TRUE;
1861   }
1864   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1865       @return array Cotaining all mdofied values. 
1866    */
1867   function get_multi_edit_values()
1868   {
1869     $ret = array();
1870     foreach($this->attributes as $attr){
1871       if(in_array($attr,$this->multi_boxes)){
1872         $ret[$attr] = $this->$attr;
1873       }
1874     }
1875     return($ret);
1876   }
1878   
1879   /*! \brief  Update class variables with values collected by multiple edit.
1880    */
1881   function set_multi_edit_values($attrs)
1882   {
1883     foreach($attrs as $name => $value){
1884       $this->$name = $value;
1885     }
1886   }
1889   /*! \brief execute plugin
1891     Generates the html output for this node
1892    */
1893   function multiple_execute()
1894   {
1895     /* This one is empty currently. Fabian - please fill in the docu code */
1896     session::global_set('current_class_for_help',get_class($this));
1898     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1899     session::set('LOCK_VARS_TO_USE',array());
1900     session::set('LOCK_VARS_USED_GET',array());
1901     session::set('LOCK_VARS_USED_POST',array());
1902     session::set('LOCK_VARS_USED_REQUEST',array());
1903     
1904     return("Multiple edit is currently not implemented for this plugin.");
1905   }
1908   /*! \brief   Save HTML posted data to object for multiple edit
1909    */
1910   function multiple_save_object()
1911   {
1912     if(empty($this->entryCSN) && $this->CSN_check_active){
1913       $this->entryCSN = getEntryCSN($this->dn);
1914     }
1916     /* Save values to object */
1917     $this->multi_boxes = array();
1918     foreach ($this->attributes as $val){
1919   
1920       /* Get selected checkboxes from multiple edit */
1921       if(isset($_POST["use_".$val])){
1922         $this->multi_boxes[] = $val;
1923       }
1925       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
1927         /* Check for modifications */
1928         if (get_magic_quotes_gpc()) {
1929           $data= stripcslashes($_POST["$val"]);
1930         } else {
1931           $data= $this->$val = $_POST["$val"];
1932         }
1933         if ($this->$val != $data){
1934           $this->is_modified= TRUE;
1935         }
1936     
1937         /* IE post fix */
1938         if(isset($data[0]) && $data[0] == chr(194)) {
1939           $data = "";  
1940         }
1941         $this->$val= $data;
1942       }
1943     }
1944   }
1947   /*! \brief  Returns all attributes of this plugin, 
1948                to be able to detect multiple used attributes 
1949                in multi_plugg::detect_multiple_used_attributes().
1950       @return array Attributes required for intialization of multi_plug
1951    */
1952   public function get_multi_init_values()
1953   {
1954     $attrs = $this->attrs;
1955     return($attrs);
1956   }
1959   /*! \brief  Check given values in multiple edit
1960       @return array Error messages
1961    */
1962   function multiple_check()
1963   {
1964     $message = plugin::check();
1965     return($message);
1966   }
1969   /*! \brief  Returns the snapshot header part for "Actions" menu in management dialogs 
1970       @param  $layer_menu  
1971    */   
1972   function get_snapshot_header($base,$category)
1973   {
1974     $str = "";
1975     $ui = get_userinfo();
1976     if($this->snapshotEnabled() && $ui->allow_snapshot_restore($base,$category)){
1978       $ok = false;
1979       foreach($this->get_used_snapshot_bases() as $base){
1980         $ok |= count($this->getAllDeletedSnapshots($base)) >= 1 ;
1981       }
1983       if($ok){
1984         $str = "..|<img class='center' src='images/lists/restore.png' ".
1985           "alt='"._("Restore")."'>&nbsp;"._("Restore").                       "|RestoreDeletedSnapShot|\n";
1986       }else{
1987         $str = "..|<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;"._("Restore")."||\n";
1988       }
1989     }
1990     return($str);
1991   }
1994   function get_snapshot_action($base,$category)
1995   {
1996     $str= ""; 
1997     $ui = get_userinfo();
1998     if($this->snapshotEnabled()){
1999       if ($ui->allow_snapshot_restore($base,$category)){
2001         if(count($this->Available_SnapsShots($base))){
2002           $str.= "<input class='center' type='image' src='images/lists/restore.png'
2003             alt='"._("Restore snapshot")."' name='RestoreSnapShotDialog_".base64_encode($base)."' title='"._("Restore snapshot")."'>&nbsp;";
2004         } else {
2005           $str = "<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;";
2006         }
2007       }
2008       if($ui->allow_snapshot_create($base,$category)){
2009         $str.= "<input class='center' type='image' src='images/snapshot.png'
2010           alt='"._("Create snapshot")."' name='CreateSnapShotDialog_".base64_encode($base)."' 
2011           title='"._("Create a new snapshot from this object")."'>&nbsp;";
2012       }else{
2013         $str = "<img class='center' src='images/empty.png' alt=' '>&nbsp;";
2014       }
2015     }
2017     return($str);
2018   }
2021   function get_copypaste_action($base,$category,$class,$copy = TRUE, $cut = TRUE)
2022   {
2023     $ui = get_userinfo();
2024     $action = "";
2025     if($this->CopyPasteHandler){
2026       if($cut){
2027         if($ui->is_cutable($base,$category,$class)){
2028           $action .= "<input class='center' type='image'
2029             src='images/lists/cut.png' alt='"._("cut")."' name='cut_%KEY%' title='"._("Cut this entry")."'>&nbsp;";
2030         }else{
2031           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
2032         }
2033       }
2034       if($copy){
2035         if($ui->is_copyable($base,$category,$class)){
2036           $action.= "<input class='center' type='image'
2037             src='images/lists/copy.png' alt='"._("copy")."' name='copy_%KEY%' title='"._("Copy this entry")."'>&nbsp;";
2038         }else{
2039           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
2040         }
2041       }
2042     }
2044     return($action); 
2045   }
2048   function get_copypaste_header($base,$category,$copy = TRUE, $cut = TRUE)
2049   {
2050     $s = "";
2051     $ui =get_userinfo();
2053     if(!is_array($category)){
2054       $category = array($category);
2055     }
2057     /* Check permissions for each category, if there is at least one category which 
2058         support read or paste permissions for the given base, then display the specific actions.
2059      */
2060     $readable = $pasteable = false;
2061     foreach($category as $cat){
2062       $readable= $readable || preg_match('/r/', $ui->get_category_permissions($base, $cat));
2063       $pasteable= $pasteable || $ui->is_pasteable($base, $cat) == 1;
2064     }
2065   
2066     if(($cut || $copy) && isset($this->CopyPasteHandler) && is_object($this->CopyPasteHandler)){
2067       if($readable){
2068         $s.= "..|---|\n";
2069         if($copy){
2070           $s.= "..|<img src='images/lists/copy.png' alt='' border='0' class='center'>".
2071             "&nbsp;"._("Copy")."|"."multiple_copy_systems|\n";
2072         }
2073         if($cut){
2074           $s.= "..|<img src='images/lists/cut.png' alt='' border='0' class='center'>".
2075             "&nbsp;"._("Cut")."|"."multiple_cut_systems|\n";
2076         }
2077       }
2079       if($pasteable){
2080         if($this->CopyPasteHandler->entries_queued()){
2081           $img = "<img border='0' class='center' src='images/lists/paste.png' alt=''>";
2082           $s.="..|".$img."&nbsp;"._("Paste")."|editPaste|\n";
2083         }else{
2084           $img = "<img border='0' class='center' src='images/lists/paste-grey.png' alt=''>";
2085           $s.="..|".$img."&nbsp;"._("Paste")."\n";
2086         }
2087       }
2088     }
2089     return($s);
2090   }
2093   function get_used_snapshot_bases()
2094   {
2095      return(array());
2096   }
2098   function is_modal_dialog()
2099   {
2100     return(isset($this->dialog) && $this->dialog);
2101   }
2104 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2105 ?>