Code

Updated utils/msgPool
[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 Generates the html output for this node
256    */
257   function execute()
258   {
259     /* This one is empty currently. Fabian - please fill in the docu code */
260     session::global_set('current_class_for_help',get_class($this));
262     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
263     session::set('LOCK_VARS_TO_USE',array());
264     session::set('LOCK_VARS_USED_GET',array());
265     session::set('LOCK_VARS_USED_POST',array());
266     session::set('LOCK_VARS_USED_REQUEST',array());
267   }
269   /*! \brief Removes object from parent
270    */
271   function remove_from_parent()
272   {
273     /* include global link_info */
274     $ldap= $this->config->get_ldap_link();
276     /* Get current objectClasses in order to add the required ones */
277     $ldap->cat($this->dn);
278     $tmp= $ldap->fetch ();
279     $oc= array();
280     if (isset($tmp['objectClass'])){
281       $oc= $tmp['objectClass'];
282       unset($oc['count']);
283     }
285     /* Remove objectClasses from entry */
286     $ldap->cd($this->dn);
287     $this->attrs= array();
288     $this->attrs['objectClass']= array_remove_entries_ics($this->objectclasses,$oc);
290     /* Unset attributes from entry */
291     foreach ($this->attributes as $val){
292       $this->attrs["$val"]= array();
293     }
295     /* Unset account info */
296     $this->is_account= FALSE;
298     /* Do not write in plugin base class, this must be done by
299        children, since there are normally additional attribs,
300        lists, etc. */
301     /*
302        $ldap->modify($this->attrs);
303      */
304   }
307   /*! \brief Save HTML posted data to object 
308    */
309   function save_object()
310   {
311     /* Update entry CSN if it is empty. */
312     if(empty($this->entryCSN) && $this->CSN_check_active){
313       $this->entryCSN = getEntryCSN($this->dn);
314     }
316     /* Save values to object */
317     foreach ($this->attributes as $val){
318       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
319         /* Check for modifications */
320         if (get_magic_quotes_gpc()) {
321           $data= stripcslashes($_POST["$val"]);
322         } else {
323           $data= $this->$val = $_POST["$val"];
324         }
325         if ($this->$val != $data){
326           $this->is_modified= TRUE;
327         }
328     
329         /* Okay, how can I explain this fix ... 
330          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
331          * So IE posts these 'unselectable' option, with value = chr(194) 
332          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
333          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
334          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
335          */
336         if(isset($data[0]) && $data[0] == chr(194)) {
337           $data = "";  
338         }
339         $this->$val= $data;
340       }
341     }
342   }
345   /*! \brief Save data to LDAP, depending on is_account we save or delete */
346   function save()
347   {
348     /* include global link_info */
349     $ldap= $this->config->get_ldap_link();
351     /* Save all plugins */
352     $this->entryCSN = "";
354     /* Start with empty array */
355     $this->attrs= array();
357     /* Get current objectClasses in order to add the required ones */
358     $ldap->cat($this->dn);
359     
360     $tmp= $ldap->fetch ();
362     $oc= array();
363     if (isset($tmp['objectClass'])){
364       $oc= $tmp["objectClass"];
365       $this->is_new= FALSE;
366       unset($oc['count']);
367     } else {
368       $this->is_new= TRUE;
369     }
371     /* Load (minimum) attributes, add missing ones */
372     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
374     /* Copy standard attributes */
375     foreach ($this->attributes as $val){
376       if ($this->$val != ""){
377         $this->attrs["$val"]= $this->$val;
378       } elseif (!$this->is_new) {
379         $this->attrs["$val"]= array();
380       }
381     }
383     /* Handle tagging */
384     $this->tag_attrs($this->attrs);
385   }
388   function cleanup()
389   {
390     foreach ($this->attrs as $index => $value){
391       
392       /* Convert arrays with one element to non arrays, if the saved
393          attributes are no array, too */
394       if (is_array($this->attrs[$index]) && 
395           count ($this->attrs[$index]) == 1 &&
396           isset($this->saved_attributes[$index]) &&
397           !is_array($this->saved_attributes[$index])){
398           
399         $tmp= $this->attrs[$index][0];
400         $this->attrs[$index]= $tmp;
401       }
403       /* Remove emtpy arrays if they do not differ */
404       if (is_array($this->attrs[$index]) &&
405           count($this->attrs[$index]) == 0 &&
406           !isset($this->saved_attributes[$index])){
407           
408         unset ($this->attrs[$index]);
409         continue;
410       }
412       /* Remove single attributes that do not differ */
413       if (!is_array($this->attrs[$index]) &&
414           isset($this->saved_attributes[$index]) &&
415           !is_array($this->saved_attributes[$index]) &&
416           $this->attrs[$index] == $this->saved_attributes[$index]){
418         unset ($this->attrs[$index]);
419         continue;
420       }
422       /* Remove arrays that do not differ */
423       if (is_array($this->attrs[$index]) && 
424           isset($this->saved_attributes[$index]) &&
425           is_array($this->saved_attributes[$index])){
426           
427         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
428           unset ($this->attrs[$index]);
429           continue;
430         }
431       }
432     }
434     /* Update saved attributes and ensure that next cleanups will be successful too */
435     foreach($this->attrs as $name => $value){
436       $this->saved_attributes[$name] = $value;
437     }
438   }
440   /*! \brief Check formular input */
441   function check()
442   {
443     $message= array();
445     /* Skip if we've no config object */
446     if (!isset($this->config) || !is_object($this->config)){
447       return $message;
448     }
450     /* Find hooks entries for this class */
451     $command= $this->config->search(get_class($this), "CHECK", array('menu', 'tabs'));
453     if ($command != ""){
455       if (!check_command($command)){
456         $message[]= msgPool::cmdnotfound("CHECK", get_class($this));
457       } else {
459         /* Generate "ldif" for check hook */
460         $ldif= "dn: $this->dn\n";
461         
462         /* ... objectClasses */
463         foreach ($this->objectclasses as $oc){
464           $ldif.= "objectClass: $oc\n";
465         }
466         
467         /* ... attributes */
468         foreach ($this->attributes as $attr){
469           if ($this->$attr == ""){
470             continue;
471           }
472           if (is_array($this->$attr)){
473             foreach ($this->$attr as $val){
474               $ldif.= "$attr: $val\n";
475             }
476           } else {
477               $ldif.= "$attr: ".$this->$attr."\n";
478           }
479         }
481         /* Append empty line */
482         $ldif.= "\n";
484         /* Feed "ldif" into hook and retrieve result*/
485         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
486         $fh= proc_open($command, $descriptorspec, $pipes);
487         if (is_resource($fh)) {
488           fwrite ($pipes[0], $ldif);
489           fclose($pipes[0]);
490           
491           $result= stream_get_contents($pipes[1]);
492           if ($result != ""){
493             $message[]= $result;
494           }
495           
496           fclose($pipes[1]);
497           fclose($pipes[2]);
498           proc_close($fh);
499         }
500       }
502     }
504     /* Check entryCSN */
505     if($this->CSN_check_active){
506       $current_csn = getEntryCSN($this->dn);
507       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
508         $this->entryCSN = $current_csn;
509         $message[] = _("The object has changed since opened in GOsa. All changes that may be done by others get lost if you save this entry!");
510       }
511     }
512     return ($message);
513   }
515   /* Adapt from template, using 'dn' */
516   function adapt_from_template($dn, $skip= array())
517   {
518     /* Include global link_info */
519     $ldap= $this->config->get_ldap_link();
521     /* Load requested 'dn' to 'attrs' */
522     $ldap->cat ($dn);
523     $this->attrs= $ldap->fetch();
525     /* Walk through attributes */
526     foreach ($this->attributes as $val){
528       /* Skip the ones in skip list */
529       if (in_array($val, $skip)){
530         continue;
531       }
533       if (isset($this->attrs["$val"][0])){
535         /* If attribute is set, replace dynamic parts: 
536            %sn, %givenName and %uid. Fill these in our local variables. */
537         $value= $this->attrs["$val"][0];
539         foreach (array("sn", "givenName", "uid") as $repl){
540           if (preg_match("/%$repl/i", $value)){
541             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
542           }
543         }
544         $this->$val= $value;
545       }
546     }
548     /* Is Account? */
549     $found= TRUE;
550     foreach ($this->objectclasses as $obj){
551       if (preg_match('/top/i', $obj)){
552         continue;
553       }
554       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
555         $found= FALSE;
556         break;
557       }
558     }
559     if ($found){
560       $this->is_account= TRUE;
561     }
562   }
564   /* \brief Indicate whether a password change is needed or not */
565   function password_change_needed()
566   {
567     return FALSE;
568   }
571   /*! \brief Show header message for tab dialogs */
572   function show_enable_header($button_text, $text, $disabled= FALSE)
573   {
574     if (($disabled == TRUE) || (!$this->acl_is_createable())){
575       $state= "disabled";
576     } else {
577       $state= "";
578     }
579     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
580     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
581       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
583     return($display);
584   }
587   /*! \brief Show header message for tab dialogs */
588   function show_disable_header($button_text, $text, $disabled= FALSE)
589   {
590     if (($disabled == TRUE) || !$this->acl_is_removeable()){
591       $state= "disabled";
592     } else {
593       $state= "";
594     }
595     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
596     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
597       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
599     return($display);
600   }
603   /*! \brief Show header message for tab dialogs */
604   function show_header($button_text, $text, $disabled= FALSE)
605   {
606     echo "FIXME: show_header should be replaced by show_disable_header and show_enable_header<br>";
607     if ($disabled == TRUE){
608       $state= "disabled";
609     } else {
610       $state= "";
611     }
612     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
613     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
614       ($this->acl_is_createable()?'':'disabled')." ".$state.
615       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
617     return($display);
618   }
620   /*! \brief Executes commands after an object has been created */
621   function postcreate($add_attrs= array())
622   {
623     /* Find postcreate entries for this class */
624     $command= $this->config->search(get_class($this), "POSTCREATE",array('menu', 'tabs'));
626     if ($command != ""){
628       /* Walk through attribute list */
629       foreach ($this->attributes as $attr){
630         if (!is_array($this->$attr)){
631           $add_attrs[$attr] = $this->$attr;
632         }
633       }
634       $add_attrs['dn']=$this->dn;
636       $tmp = array();
637       foreach($add_attrs as $name => $value){
638         $tmp[$name] =  strlen($name);
639       }
640       arsort($tmp);
641       
642       /* Additional attributes */
643       foreach ($tmp as $name => $len){
644         $value = $add_attrs[$name];
645         $command= str_replace("%$name", "$value", $command);
646       }
648       if (check_command($command)){
649         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
650             $command, "Execute");
651         exec($command,$arr);
652         foreach($arr as $str){
653           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
654             $command, "Result: ".$str);
655         }
656       } else {
657         $message= msgPool::cmdnotfound("POSTCREATE", get_class($this));
658         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
659       }
660     }
661   }
663   /*! \brief Execute commands after an object has been modified */
664   function postmodify($add_attrs= array())
665   {
666     /* Find postcreate entries for this class */
667     $command= $this->config->search(get_class($this), "POSTMODIFY",array('menu','tabs'));
669     if ($command != ""){
671       /* Walk through attribute list */
672       foreach ($this->attributes as $attr){
673         if (!is_array($this->$attr)){
674           $add_attrs[$attr] = $this->$attr;
675         }
676       }
677       $add_attrs['dn']=$this->dn;
679       $tmp = array();
680       foreach($add_attrs as $name => $value){
681         $tmp[$name] =  strlen($name);
682       }
683       arsort($tmp);
684       
685       /* Additional attributes */
686       foreach ($tmp as $name => $len){
687         $value = $add_attrs[$name];
688         $command= str_replace("%$name", "$value", $command);
689       }
691       if (check_command($command)){
692         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,$command, "Execute");
693         exec($command,$arr);
694         foreach($arr as $str){
695           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
696             $command, "Result: ".$str);
697         }
698       } else {
699         $message= msgPool::cmdnotfound("POSTMODIFY", get_class($this));
700         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
701       }
702     }
703   }
705   /*! \brief Executes a command after an object has been removed */
706   function postremove($add_attrs= array())
707   {
708     /* Find postremove entries for this class */
709     $command= $this->config->search(get_class($this), "POSTREMOVE",array('menu','tabs'));
710     if ($command != ""){
712       /* Walk through attribute list */
713       foreach ($this->attributes as $attr){
714         if (!is_array($this->$attr)){
715           $add_attrs[$attr] = $this->$attr;
716         }
717       }
718       $add_attrs['dn']=$this->dn;
720       $tmp = array();
721       foreach($add_attrs as $name => $value){
722         $tmp[$name] =  strlen($name);
723       }
724       arsort($tmp);
725       
726       /* Additional attributes */
727       foreach ($tmp as $name => $len){
728         $value = $add_attrs[$name];
729         $command= str_replace("%$name", "$value", $command);
730       }
732       if (check_command($command)){
733         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
734             $command, "Execute");
736         exec($command,$arr);
737         foreach($arr as $str){
738           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
739             $command, "Result: ".$str);
740         }
741       } else {
742         $message= msgPool::cmdnotfound("POSTREMOVE", get_class($this));
743         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
744       }
745     }
746   }
749   /* Create unique DN */
750   function create_unique_dn2($data, $base)
751   {
752     $ldap= $this->config->get_ldap_link();
753     $base= preg_replace("/^,*/", "", $base);
755     /* Try to use plain entry first */
756     $dn= "$data,$base";
757     $attribute= preg_replace('/=.*$/', '', $data);
758     $ldap->cat ($dn, array('dn'));
759     if (!$ldap->fetch()){
760       return ($dn);
761     }
763     /* Look for additional attributes */
764     foreach ($this->attributes as $attr){
765       if ($attr == $attribute || $this->$attr == ""){
766         continue;
767       }
769       $dn= "$data+$attr=".$this->$attr.",$base";
770       $ldap->cat ($dn, array('dn'));
771       if (!$ldap->fetch()){
772         return ($dn);
773       }
774     }
776     /* None found */
777     return ("none");
778   }
781   /*! \brief Create unique DN */
782   function create_unique_dn($attribute, $base)
783   {
784     $ldap= $this->config->get_ldap_link();
785     $base= preg_replace("/^,*/", "", $base);
787     /* Try to use plain entry first */
788     $dn= "$attribute=".$this->$attribute.",$base";
789     $ldap->cat ($dn, array('dn'));
790     if (!$ldap->fetch()){
791       return ($dn);
792     }
794     /* Look for additional attributes */
795     foreach ($this->attributes as $attr){
796       if ($attr == $attribute || $this->$attr == ""){
797         continue;
798       }
800       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
801       $ldap->cat ($dn, array('dn'));
802       if (!$ldap->fetch()){
803         return ($dn);
804       }
805     }
807     /* None found */
808     return ("none");
809   }
812   function rebind($ldap, $referral)
813   {
814     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
815     if (ldap_bind($ldap, $credentials['ADMIN'], $this->config->get_credentials($credentials['PASSWORD']))) {
816       $this->error = "Success";
817       $this->hascon=true;
818       $this->reconnect= true;
819       return (0);
820     } else {
821       $this->error = "Could not bind to " . $credentials['ADMIN'];
822       return NULL;
823     }
824   }
827   /* Recursively copy ldap object */
828   function _copy($src_dn,$dst_dn)
829   {
830     $ldap=$this->config->get_ldap_link();
831     $ldap->cat($src_dn);
832     $attrs= $ldap->fetch();
834     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
835     $ds= ldap_connect($this->config->current['SERVER']);
836     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
837     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
838       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
839     }
841     $pwd = $this->config->get_credentials($this->config->current['ADMINPASSWORD']);
842     $r=ldap_bind($ds,$this->config->current['ADMINDN'], $pwd);
843     $sr=ldap_read($ds, LDAP::fix($src_dn), "objectClass=*");
845     /* Fill data from LDAP */
846     $new= array();
847     if ($sr) {
848       $ei=ldap_first_entry($ds, $sr);
849       if ($ei) {
850         foreach($attrs as $attr => $val){
851           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
852             for ($i= 0; $i<$info['count']; $i++){
853               if ($info['count'] == 1){
854                 $new[$attr]= $info[$i];
855               } else {
856                 $new[$attr][]= $info[$i];
857               }
858             }
859           }
860         }
861       }
862     }
864     /* close conncetion */
865     ldap_unbind($ds);
867     /* Adapt naming attribute */
868     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
869     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
870     $new[$dst_name]= LDAP::fix($dst_val);
872     /* Check if this is a department.
873      * If it is a dep. && there is a , override in his ou 
874      *  change \2C to , again, else this entry can't be saved ...
875      */
876     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
877       $new['ou'] = str_replace("\\\\,",",",$new['ou']);
878     }
880     /* Save copy */
881     $ldap->connect();
882     $ldap->cd($this->config->current['BASE']);
883     
884     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
886     /* FAIvariable=.../..., cn=.. 
887         could not be saved, because the attribute FAIvariable was different to 
888         the dn FAIvariable=..., cn=... */
890     if(!is_array($new['objectClass'])) $new['objectClass'] = array($new['objectClass']);
892     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
893       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
894     }
895     $ldap->cd($dst_dn);
896     $ldap->add($new);
898     if (!$ldap->success()){
899       trigger_error("Trying to save $dst_dn failed.",
900           E_USER_WARNING);
901       return(FALSE);
902     }
903     return(TRUE);
904   }
907   /* This is a workaround function. */
908   function copy($src_dn, $dst_dn)
909   {
910     /* Rename dn in possible object groups */
911     $ldap= $this->config->get_ldap_link();
912     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::prepare4filter($src_dn).'))',
913         array('cn'));
914     while ($attrs= $ldap->fetch()){
915       $og= new ogroup($this->config, $ldap->getDN());
916       unset($og->member[$src_dn]);
917       $og->member[$dst_dn]= $dst_dn;
918       $og->save ();
919     }
921     $ldap->cat($dst_dn);
922     $attrs= $ldap->fetch();
923     if (count($attrs)){
924       trigger_error("Trying to overwrite ".LDAP::fix($dst_dn).", which already exists.",
925           E_USER_WARNING);
926       return (FALSE);
927     }
929     $ldap->cat($src_dn);
930     $attrs= $ldap->fetch();
931     if (!count($attrs)){
932       trigger_error("Trying to move ".LDAP::fix($src_dn).", which does not seem to exist.",
933           E_USER_WARNING);
934       return (FALSE);
935     }
937     $ldap->cd($src_dn);
938     $ldap->search("objectClass=*",array("dn"));
939     while($attrs = $ldap->fetch()){
940       $src = $attrs['dn'];
941       $dst = preg_replace("/".preg_quote($src_dn, '/')."$/",$dst_dn,$attrs['dn']);
942       $this->_copy($src,$dst);
943     }
944     return (TRUE);
945   }
949   /*! \brief  Rename/Move a given src_dn to the given dest_dn
950    *
951    * Move a given ldap object indentified by $src_dn to the
952    * given destination $dst_dn
953    *
954    * - Ensure that all references are updated (ogroups)
955    * - Update ACLs   
956    * - Update accessTo
957    *
958    * \param  string  'src_dn' the source DN.
959    * \param  string  'dst_dn' the destination DN.
960    * \return boolean TRUE on success else FALSE.
961    */
962   function rename($src_dn, $dst_dn)
963   {
964     $start = microtime(1);
966     /* Try to move the source entry to the destination position */
967     $ldap = $this->config->get_ldap_link();
968     $ldap->cd($this->config->current['BASE']);
969     $ldap->create_missing_trees(preg_replace("/^[^,]+,/","",$dst_dn));
970     if (!$ldap->rename_dn($src_dn,$dst_dn)){
971 #      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $src_dn, "", get_class()));
972       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());
973       @DEBUG(DEBUG_LDAP,__LINE__,__FUNCTION__,__FILE__,"Rename failed FROM: $src_dn  -- TO:  $dst_dn", 
974           "Ldap Protocol v3 implementation error, falling back to maunal method.");
975       return(FALSE);
976     }
978     /* Get list of users,groups and roles within this tree,
979         maybe we have to update ACL references.
980      */
981     $leaf_objs = get_list("(|(objectClass=posixGroup)(objectClass=gosaAccount)(objectClass=gosaRole))",array("all"),$dst_dn,
982           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
983     foreach($leaf_objs as $obj){
984       $new_dn = $obj['dn'];
985       $old_dn = preg_replace("/".preg_quote(LDAP::convert($dst_dn), '/')."$/i",$src_dn,LDAP::convert($new_dn));
986       $this->update_acls($old_dn,$new_dn); 
987     }
989     // Migrate objectgroups if needed
990     $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);
992     // Walk through all objectGroups
993     foreach($ogroups as $ogroup){
994       // Migrate old to new dn
995       $o_ogroup= new ogroup($this->config,$ogroup['dn']);
996       if (isset($o_group->member[$src_dn])) {
997         unset($o_ogroup->member[$src_dn]);
998       }
999       $o_ogroup->member[$dst_dn]= $dst_dn;
1000       
1001       // Save object group
1002       $o_ogroup->save();
1003     }
1005     // Migrate rfc groups if needed
1006     $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);
1008     // Walk through all POSIX groups
1009     foreach($groups as $group){
1011       // Migrate old to new dn
1012       $o_group= new group($this->config,$group['dn']);
1013       $o_group->save();
1014     }
1016     /* Update roles to use the new entry dn */
1017     $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);
1019     // Walk through all roles
1020     foreach($roles as $role){
1021       $role = new roleGeneric($this->config,$role['dn']);
1022       $key= array_search($src_dn, $role->roleOccupant);      
1023       if($key !== FALSE){
1024         $role->roleOccupant[$key] = $dst_dn;
1025         $role->save();
1026       }
1027     }
1028  
1029     /* Check if there are gosa departments moved. 
1030        If there were deps moved, the force reload of config->deps.
1031      */
1032     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
1033           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
1034   
1035     if(count($leaf_deps)){
1036       $this->config->get_departments();
1037       $this->config->make_idepartments();
1038       session::global_set("config",$this->config);
1039       $ui =get_userinfo();
1040       $ui->reset_acl_cache();
1041     }
1043     return(TRUE); 
1044   }
1047  
1048   function move($src_dn, $dst_dn)
1049   {
1050     /* Do not copy if only upper- lowercase has changed */
1051     if(strtolower($src_dn) == strtolower($dst_dn)){
1052       return(TRUE);
1053     }
1055     
1056     /* Try to move the entry instead of copy & delete
1057      */
1058     if(TRUE){
1060       /* Try to move with ldap routines, if this was not successfull
1061           fall back to the old style copy & remove method 
1062        */
1063       if($this->rename($src_dn, $dst_dn)){
1064         return(TRUE);
1065       }else{
1066         // See code below.
1067       }
1068     }
1070     /* Copy source to destination */
1071     if (!$this->copy($src_dn, $dst_dn)){
1072       return (FALSE);
1073     }
1075     /* Delete source */
1076     $ldap= $this->config->get_ldap_link();
1077     $ldap->rmdir_recursive($src_dn);
1078     if (!$ldap->success()){
1079       trigger_error("Trying to delete $src_dn failed.",
1080           E_USER_WARNING);
1081       return (FALSE);
1082     }
1084     return (TRUE);
1085   }
1088   /* \brief Move/Rename complete trees */
1089   function recursive_move($src_dn, $dst_dn)
1090   {
1091     /* Check if the destination entry exists */
1092     $ldap= $this->config->get_ldap_link();
1094     /* Check if destination exists - abort */
1095     $ldap->cat($dst_dn, array('dn'));
1096     if ($ldap->fetch()){
1097       trigger_error("recursive_move $dst_dn already exists.",
1098           E_USER_WARNING);
1099       return (FALSE);
1100     }
1102     $this->copy($src_dn, $dst_dn);
1104     /* Remove src_dn */
1105     $ldap->cd($src_dn);
1106     $ldap->recursive_remove($src_dn);
1107     return (TRUE);
1108   }
1111   function handle_post_events($mode, $add_attrs= array())
1112   {
1113     switch ($mode){
1114       case "add":
1115         $this->postcreate($add_attrs);
1116       break;
1118       case "modify":
1119         $this->postmodify($add_attrs);
1120       break;
1122       case "remove":
1123         $this->postremove($add_attrs);
1124       break;
1125     }
1126   }
1129   function saveCopyDialog(){
1130   }
1133   function getCopyDialog(){
1134     return(array("string"=>"","status"=>""));
1135   }
1138   /*! \brief Prepare for Copy & Paste */
1139   function PrepareForCopyPaste($source)
1140   {
1141     $todo = $this->attributes;
1142     if(isset($this->CopyPasteVars)){
1143       $todo = array_merge($todo,$this->CopyPasteVars);
1144     }
1146     if(count($this->objectclasses)){
1147       $this->is_account = TRUE;
1148       foreach($this->objectclasses as $class){
1149         if(!in_array($class,$source['objectClass'])){
1150           $this->is_account = FALSE;
1151         }
1152       }
1153     }
1155     foreach($todo as $var){
1156       if (isset($source[$var])){
1157         if(isset($source[$var]['count'])){
1158           if($source[$var]['count'] > 1){
1159             $tmp= $source[$var];
1160             unset($tmp['count']);
1161             $this->$var = $tmp;
1162           }else{
1163             $this->$var = $source[$var][0];
1164           }
1165         }else{
1166           $this->$var= $source[$var];
1167         }
1168       }
1169     }
1170   }
1172   /*! \brief Get gosaUnitTag for the given DN
1173        If this is called from departmentGeneric, we have to skip this
1174         tagging procedure. 
1175     */
1176   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1177   {
1178     /* Skip tagging? */
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     }
1220   /*! \brief Add unit tag */ 
1221     /* Remove tags that may already be here... */
1222     remove_objectClass("gosaAdministrativeUnitTag", $at);
1223     if (isset($at['gosaUnitTag'])){
1224         unset($at['gosaUnitTag']);
1225     }
1227     /* Set tag? */
1228     if ($tag != ""){
1229       add_objectClass("gosaAdministrativeUnitTag", $at);
1230       $at['gosaUnitTag']= $tag;
1231     }
1233     /* Initially this object was tagged. 
1234        - But now, it is no longer inside a tagged department. 
1235        So force the remove of the tag.
1236        (objectClass was already removed obove)
1237      */
1238     if($tag == "" && $this->gosaUnitTag){
1239       $at['gosaUnitTag'] = array();
1240     }
1241   }
1244   /*! \brief Test for removability of the object
1245    *
1246    * Allows testing of conditions for removal of object. If removal should be aborted
1247    * the function needs to remove an error message.
1248    * */
1249   function allow_remove()
1250   {
1251     $reason= "";
1252     return $reason;
1253   }
1256   /*! \brief Create a snapshot of the current object */
1257   function create_snapshot($type= "snapshot", $description= array())
1258   {
1260     /* Check if snapshot functionality is enabled */
1261     if(!$this->snapshotEnabled()){
1262       return;
1263     }
1265     /* Get configuration from gosa.conf */
1266     $config = $this->config;
1268     /* Create lokal ldap connection */
1269     $ldap= $this->config->get_ldap_link();
1270     $ldap->cd($this->config->current['BASE']);
1272     /* check if there are special server configurations for snapshots */
1273     if($config->get_cfg_value("snapshotURI") == ""){
1275       /* Source and destination server are both the same, just copy source to dest obj */
1276       $ldap_to      = $ldap;
1277       $snapldapbase = $this->config->current['BASE'];
1279     }else{
1280       $server         = $config->get_cfg_value("snapshotURI");
1281       $user           = $config->get_cfg_value("snapshotAdminDn");
1282       $password       = $this->config->get_credentials($config->get_cfg_value("snapshotAdminPassword"));
1283       $snapldapbase   = $config->get_cfg_value("snapshotBase");
1285       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1286       $ldap_to -> cd($snapldapbase);
1288       if (!$ldap_to->success()){
1289         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1290       }
1292     }
1294     /* check if the dn exists */ 
1295     if ($ldap->dn_exists($this->dn)){
1297       /* Extract seconds & mysecs, they are used as entry index */
1298       list($usec, $sec)= explode(" ", microtime());
1300       /* Collect some infos */
1301       $base           = $this->config->current['BASE'];
1302       $snap_base      = $config->get_cfg_value("snapshotBase");
1303       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1304       $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1306       /* Create object */
1307 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1308       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1309       $newName          = str_replace(".", "", $sec."-".$usec);
1310       $target= array();
1311       $target['objectClass']            = array("top", "gosaSnapshotObject");
1312       $target['gosaSnapshotData']       = gzcompress($data, 6);
1313       $target['gosaSnapshotType']       = $type;
1314       $target['gosaSnapshotDN']         = $this->dn;
1315       $target['description']            = $description;
1316       $target['gosaSnapshotTimestamp']  = $newName;
1318       /* Insert the new snapshot 
1319          But we have to check first, if the given gosaSnapshotTimestamp
1320          is already used, in this case we should increment this value till there is 
1321          an unused value. */ 
1322       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1323       $ldap_to->cat($new_dn);
1324       while($ldap_to->count()){
1325         $ldap_to->cat($new_dn);
1326         $newName = str_replace(".", "", $sec."-".($usec++));
1327         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1328         $target['gosaSnapshotTimestamp']  = $newName;
1329       } 
1331       /* Inset this new snapshot */
1332       $ldap_to->cd($snapldapbase);
1333       $ldap_to->create_missing_trees($snapldapbase);
1334       $ldap_to->create_missing_trees($new_base);
1335       $ldap_to->cd($new_dn);
1336       $ldap_to->add($target);
1337       if (!$ldap_to->success()){
1338         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $new_dn, LDAP_ADD, get_class()));
1339       }
1341       if (!$ldap->success()){
1342         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $new_base, "", get_class()));
1343       }
1345     }
1346   }
1348   /*! \brief Remove a snapshot */
1349   function remove_snapshot($dn)
1350   {
1351     $ui       = get_userinfo();
1352     $old_dn   = $this->dn; 
1353     $this->dn = $dn;
1354     $ldap = $this->config->get_ldap_link();
1355     $ldap->cd($this->config->current['BASE']);
1356     $ldap->rmdir_recursive($this->dn);
1357     if(!$ldap->success()){
1358       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn));
1359     }
1360     $this->dn = $old_dn;
1361   }
1364   /*! \brief Test if snapshotting is enabled
1365    *
1366    * Test weither snapshotting is enabled or not. There will also be some errors posted,
1367    * if the configuration failed 
1368    * \return TRUE if snapshots are enabled, and FALSE if it is disabled
1369    */
1370   function snapshotEnabled()
1371   {
1372     return $this->config->snapshotEnabled();
1373   }
1376   /* \brief Return available snapshots for the given base */
1377   function Available_SnapsShots($dn,$raw = false)
1378   {
1379     if(!$this->snapshotEnabled()) return(array());
1381     /* Create an additional ldap object which
1382        points to our ldap snapshot server */
1383     $ldap= $this->config->get_ldap_link();
1384     $ldap->cd($this->config->current['BASE']);
1385     $cfg= &$this->config->current;
1387     /* check if there are special server configurations for snapshots */
1388     if($this->config->get_cfg_value("snapshotURI") == ""){
1389       $ldap_to      = $ldap;
1390     }else{
1391       $server         = $this->config->get_cfg_value("snapshotURI");
1392       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1393       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1394       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1395       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1396       $ldap_to -> cd($snapldapbase);
1397       if (!$ldap_to->success()){
1398         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1399       }
1400     }
1402     /* Prepare bases and some other infos */
1403     $base           = $this->config->current['BASE'];
1404     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1405     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1406     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1407     $tmp            = array(); 
1409     /* Fetch all objects with  gosaSnapshotDN=$dn */
1410     $ldap_to->cd($new_base);
1411     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1412         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1414     /* Put results into a list and add description if missing */
1415     while($entry = $ldap_to->fetch()){ 
1416       if(!isset($entry['description'][0])){
1417         $entry['description'][0]  = "";
1418       }
1419       $tmp[] = $entry; 
1420     }
1422     /* Return the raw array, or format the result */
1423     if($raw){
1424       return($tmp);
1425     }else{  
1426       $tmp2 = array();
1427       foreach($tmp as $entry){
1428         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1429       }
1430     }
1431     return($tmp2);
1432   }
1435   function getAllDeletedSnapshots($base_of_object,$raw = false)
1436   {
1437     if(!$this->snapshotEnabled()) return(array());
1439     /* Create an additional ldap object which
1440        points to our ldap snapshot server */
1441     $ldap= $this->config->get_ldap_link();
1442     $ldap->cd($this->config->current['BASE']);
1443     $cfg= &$this->config->current;
1445     /* check if there are special server configurations for snapshots */
1446     if($this->config->get_cfg_value("snapshotURI") == ""){
1447       $ldap_to      = $ldap;
1448     }else{
1449       $server         = $this->config->get_cfg_value("snapshotURI");
1450       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1451       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1452       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1453       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1454       $ldap_to -> cd($snapldapbase);
1455       if (!$ldap_to->success()){
1456         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1457       }
1458     }
1460     /* Prepare bases */ 
1461     $base           = $this->config->current['BASE'];
1462     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1463     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1465     /* Fetch all objects and check if they do not exist anymore */
1466     $ui = get_userinfo();
1467     $tmp = array();
1468     $ldap_to->cd($new_base);
1469     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1470     while($entry = $ldap_to->fetch()){
1472       $chk =  str_replace($new_base,"",$entry['dn']);
1473       if(preg_match("/,ou=/",$chk)) continue;
1475       if(!isset($entry['description'][0])){
1476         $entry['description'][0]  = "";
1477       }
1478       $tmp[] = $entry; 
1479     }
1481     /* Check if entry still exists */
1482     foreach($tmp as $key => $entry){
1483       $ldap->cat($entry['gosaSnapshotDN'][0]);
1484       if($ldap->count()){
1485         unset($tmp[$key]);
1486       }
1487     }
1489     /* Format result as requested */
1490     if($raw) {
1491       return($tmp);
1492     }else{
1493       $tmp2 = array();
1494       foreach($tmp as $key => $entry){
1495         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1496       }
1497     }
1498     return($tmp2);
1499   } 
1502   /* \brief Restore selected snapshot */
1503   function restore_snapshot($dn)
1504   {
1505     if(!$this->snapshotEnabled()) return(array());
1507     $ldap= $this->config->get_ldap_link();
1508     $ldap->cd($this->config->current['BASE']);
1509     $cfg= &$this->config->current;
1511     /* check if there are special server configurations for snapshots */
1512     if($this->config->get_cfg_value("snapshotURI") == ""){
1513       $ldap_to      = $ldap;
1514     }else{
1515       $server         = $this->config->get_cfg_value("snapshotURI");
1516       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1517       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1518       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1519       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1520       $ldap_to -> cd($snapldapbase);
1521       if (!$ldap_to->success()){
1522         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1523       }
1524     }
1526     /* Get the snapshot */ 
1527     $ldap_to->cat($dn);
1528     $restoreObject = $ldap_to->fetch();
1530     /* Prepare import string */
1531     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1533     /* Import the given data */
1534     $err = "";
1535     $ldap->import_complete_ldif($data,$err,false,false);
1536     if (!$ldap->success()){
1537       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, "", get_class()));
1538     }
1539   }
1542   function showSnapshotDialog($base,$baseSuffixe,&$parent)
1543   {
1544     $once = true;
1545     $ui = get_userinfo();
1546     $this->parent = $parent;
1548     foreach($_POST as $name => $value){
1550       /* Create a new snapshot, display a dialog */
1551       if(preg_match("/^CreateSnapShotDialog_[^_]*_[xy]$/",$name) && $once){
1553                           $entry = base64_decode(preg_replace("/^CreateSnapShotDialog_([^_]*)_[xy]$/","\\1",$name));
1554         $once = false;
1555         $entry = preg_replace("/^CreateSnapShotDialog_/","",$entry);
1557         if(!empty($entry) && $ui->allow_snapshot_create($entry,$this->parent->acl_module)){
1558           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1559         }else{
1560           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to create a snapshot for %s."),$entry),ERROR_DIALOG);
1561         }
1562       }  
1563   
1564       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1565       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1566         $once = false;
1567         $entry = base64_decode(preg_replace("/^RestoreSnapShotDialog_([^_]*)_[xy]$/i","\\1",$name));
1568         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1569           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1570           $this->snapDialog->display_restore_dialog = true;
1571         }else{
1572           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1573         }
1574       }
1576       /* Restore one of the already deleted objects */
1577       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1578           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1579         $once = false;
1581         if($ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1582           $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1583           $this->snapDialog->set_snapshot_bases($baseSuffixe);
1584           $this->snapDialog->display_restore_dialog      = true;
1585           $this->snapDialog->display_all_removed_objects  = true;
1586         }else{
1587           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$base),ERROR_DIALOG);
1588         }
1589       }
1591       /* Restore selected snapshot */
1592       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1593         $once = false;
1594         $entry = base64_decode(preg_replace("/^RestoreSnapShot_([^_]*)_[xy]$/i","\\1",$name));
1596         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1597           $this->restore_snapshot($entry);
1598           $this->snapDialog = NULL;
1599         }else{
1600           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1601         }
1602       }
1603     }
1605     /* Create a new snapshot requested, check
1606        the given attributes and create the snapshot*/
1607     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1608       $this->snapDialog->save_object();
1609       $msgs = $this->snapDialog->check();
1610       if(count($msgs)){
1611         foreach($msgs as $msg){
1612           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
1613         }
1614       }else{
1615         $this->dn =  $this->snapDialog->dn;
1616         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1617         $this->snapDialog = NULL;
1618       }
1619     }
1621     /* Restore is requested, restore the object with the posted dn .*/
1622     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1623     }
1625     if(isset($_POST['CancelSnapshot'])){
1626       $this->snapDialog = NULL;
1627     }
1629     if(is_object($this->snapDialog )){
1630       $this->snapDialog->save_object();
1631       return($this->snapDialog->execute());
1632     }
1633   }
1636   /*! \brief Return plugin informations for acl handling */
1637   static function plInfo()
1638   {
1639     return array();
1640   }
1643   function set_acl_base($base)
1644   {
1645     $this->acl_base= $base;
1646   }
1649   function set_acl_category($category)
1650   {
1651     $this->acl_category= "$category/";
1652   }
1655   function acl_is_writeable($attribute,$skip_write = FALSE)
1656   {
1657     if($this->read_only) return(FALSE);
1658     $ui= get_userinfo();
1659     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1660   }
1663   function acl_is_readable($attribute)
1664   {
1665     $ui= get_userinfo();
1666     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1667   }
1670   function acl_is_createable($base ="")
1671   {
1672     if($this->read_only) return(FALSE);
1673     $ui= get_userinfo();
1674     if($base == "") $base = $this->acl_base;
1675     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1676   }
1679   function acl_is_removeable($base ="")
1680   {
1681     if($this->read_only) return(FALSE);
1682     $ui= get_userinfo();
1683     if($base == "") $base = $this->acl_base;
1684     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1685   }
1688   function acl_is_moveable($base = "")
1689   {
1690     if($this->read_only) return(FALSE);
1691     $ui= get_userinfo();
1692     if($base == "") $base = $this->acl_base;
1693     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1694   }
1697   function acl_have_any_permissions()
1698   {
1699   }
1702   function getacl($attribute,$skip_write= FALSE)
1703   {
1704     $ui= get_userinfo();
1705     $skip_write |= $this->read_only;
1706     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1707   }
1710   /*! \brief Returns a list of all available departments for this object.
1711    * 
1712    * If this object is new, all departments we are allowed to create a new user in
1713    * are returned. If this is an existing object, return all deps. 
1714    * We are allowed to move tis object too.
1715    * \return array [dn] => "..name"  // All deps. we are allowed to act on.
1716   */
1717   function get_allowed_bases()
1718   {
1719     $ui = get_userinfo();
1720     $deps = array();
1722     /* Is this a new object ? Or just an edited existing object */
1723     if(!$this->initially_was_account && $this->is_account){
1724       $new = true;
1725     }else{
1726       $new = false;
1727     }
1729     foreach($this->config->idepartments as $dn => $name){
1730       if($new && $this->acl_is_createable($dn)){
1731         $deps[$dn] = $name;
1732       }elseif(!$new && $this->acl_is_moveable($dn)){
1733         $deps[$dn] = $name;
1734       }
1735     }
1737     /* Add current base */      
1738     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1739       $deps[$this->base] = $this->config->idepartments[$this->base];
1740     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1742     }else{
1743       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1744     }
1745     return($deps);
1746   }
1749   /* This function updates ACL settings if $old_dn was used.
1750    *  \param string 'old_dn' specifies the actually used dn
1751    *  \param string 'new_dn' specifies the destiantion dn
1752    */
1753   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1754   {
1755     /* Check if old_dn is empty. This should never happen */
1756     if(empty($old_dn) || empty($new_dn)){
1757       trigger_error("Failed to check acl dependencies, wrong dn given.");
1758       return;
1759     }
1761     /* Update userinfo if necessary */
1762     $ui = session::global_get('ui');
1763     if($ui->dn == $old_dn){
1764       $ui->dn = $new_dn;
1765       session::global_set('ui',$ui);
1766       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1767     }
1769     /* Object was moved, ensure that all acls will be moved too */
1770     if($new_dn != $old_dn && $old_dn != "new"){
1772       /* get_ldap configuration */
1773       $update = array();
1774       $ldap = $this->config->get_ldap_link();
1775       $ldap->cd ($this->config->current['BASE']);
1776       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1777       while($attrs = $ldap->fetch()){
1778         $acls = array();
1779         $found = false;
1780         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1781           $acl_parts = explode(":",$attrs['gosaAclEntry'][$i]);
1783           /* Roles uses antoher data storage order, members are stored int the third part, 
1784              while the members in direct ACL assignments are stored in the second part.
1785            */
1786           $id = ($acl_parts[1] == "role") ? 3 : 2;
1788           /* Update member entries to use $new_dn instead of old_dn
1789            */
1790           $members = explode(",",$acl_parts[$id]);
1791           foreach($members as $key => $member){
1792             $member = base64_decode($member);
1793             if($member == $old_dn){
1794               $members[$key] = base64_encode($new_dn);
1795               $found = TRUE;
1796             }
1797           } 
1799           /* Check if the selected role has to updated
1800            */
1801           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1802             $acl_parts[2] = base64_encode($new_dn);
1803             $found = TRUE;
1804           }
1806           /* Build new acl string */ 
1807           $acl_parts[$id] = implode($members,",");
1808           $acls[] = implode($acl_parts,":");
1809         }
1811         /* Acls for this object must be adjusted */
1812         if($found){
1814           $debug_info=  _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1815             $old_dn."</b><br>&nbsp;-"._("to")."&nbsp;<b>".$new_dn."</b><br>";
1816           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1818           $update[$attrs['dn']] =array();
1819           foreach($acls as $acl){
1820             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1821           }
1822         }
1823       }
1825       /* Write updated acls */
1826       foreach($update as $dn => $attrs){
1827         $ldap->cd($dn);
1828         $ldap->modify($attrs);
1829       }
1830     }
1831   }
1833   
1835   /*! \brief Enable the Serial ID check
1836    *
1837    * This function enables the entry Serial ID check.  If an entry was edited while
1838    * we have edited the entry too, an error message will be shown. 
1839    * To configure this check correctly read the FAQ.
1840    */    
1841   function enable_CSN_check()
1842   {
1843     $this->CSN_check_active =TRUE;
1844     $this->entryCSN = getEntryCSN($this->dn);
1845   }
1848   /*! \brief  Prepares the plugin to be used for multiple edit
1849    *          Update plugin attributes with given array of attribtues.
1850    *  \param  array   Array with attributes that must be updated.
1851    */
1852   function init_multiple_support($attrs,$all)
1853   {
1854     $ldap= $this->config->get_ldap_link();
1855     $this->multi_attrs    = $attrs;
1856     $this->multi_attrs_all= $all;
1858     /* Copy needed attributes */
1859     foreach ($this->attributes as $val){
1860       $found= array_key_ics($val, $this->multi_attrs);
1861  
1862       if ($found != ""){
1863         if(isset($this->multi_attrs["$val"][0])){
1864           $this->$val= $this->multi_attrs["$val"][0];
1865         }
1866       }
1867     }
1868   }
1870  
1871   /*! \brief  Enables multiple support for this plugin
1872    */
1873   function enable_multiple_support()
1874   {
1875     $this->ignore_account = TRUE;
1876     $this->multiple_support_active = TRUE;
1877   }
1880   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1881       \return array Cotaining all modified values. 
1882    */
1883   function get_multi_edit_values()
1884   {
1885     $ret = array();
1886     foreach($this->attributes as $attr){
1887       if(in_array($attr,$this->multi_boxes)){
1888         $ret[$attr] = $this->$attr;
1889       }
1890     }
1891     return($ret);
1892   }
1894   
1895   /*! \brief  Update class variables with values collected by multiple edit.
1896    */
1897   function set_multi_edit_values($attrs)
1898   {
1899     foreach($attrs as $name => $value){
1900       $this->$name = $value;
1901     }
1902   }
1905   /*! \brief Generates the html output for this node for multi edit*/
1906   function multiple_execute()
1907   {
1908     /* This one is empty currently. Fabian - please fill in the docu code */
1909     session::global_set('current_class_for_help',get_class($this));
1911     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1912     session::set('LOCK_VARS_TO_USE',array());
1913     session::set('LOCK_VARS_USED_GET',array());
1914     session::set('LOCK_VARS_USED_POST',array());
1915     session::set('LOCK_VARS_USED_REQUEST',array());
1916     
1917     return("Multiple edit is currently not implemented for this plugin.");
1918   }
1921   /*! \brief Save HTML posted data to object for multiple edit
1922    */
1923   function multiple_save_object()
1924   {
1925     if(empty($this->entryCSN) && $this->CSN_check_active){
1926       $this->entryCSN = getEntryCSN($this->dn);
1927     }
1929     /* Save values to object */
1930     $this->multi_boxes = array();
1931     foreach ($this->attributes as $val){
1932   
1933       /* Get selected checkboxes from multiple edit */
1934       if(isset($_POST["use_".$val])){
1935         $this->multi_boxes[] = $val;
1936       }
1938       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
1940         /* Check for modifications */
1941         if (get_magic_quotes_gpc()) {
1942           $data= stripcslashes($_POST["$val"]);
1943         } else {
1944           $data= $this->$val = $_POST["$val"];
1945         }
1946         if ($this->$val != $data){
1947           $this->is_modified= TRUE;
1948         }
1949     
1950         /* IE post fix */
1951         if(isset($data[0]) && $data[0] == chr(194)) {
1952           $data = "";  
1953         }
1954         $this->$val= $data;
1955       }
1956     }
1957   }
1960   /*! \brief Returns all attributes of this plugin, 
1961                to be able to detect multiple used attributes 
1962                in multi_plugg::detect_multiple_used_attributes().
1963       @return array Attributes required for intialization of multi_plug
1964    */
1965   public function get_multi_init_values()
1966   {
1967     $attrs = $this->attrs;
1968     return($attrs);
1969   }
1972   /*! \brief  Check given values in multiple edit
1973       \return array Error messages
1974    */
1975   function multiple_check()
1976   {
1977     $message = plugin::check();
1978     return($message);
1979   }
1982   /*! \brief  Returns the snapshot header part for "Actions" menu in management dialogs 
1983       \param  $layer_menu  
1984    */   
1985   function get_snapshot_header($base,$category)
1986   {
1987     $str = "";
1988     $ui = get_userinfo();
1989     if($this->snapshotEnabled() && $ui->allow_snapshot_restore($base,$category)){
1991       $ok = false;
1992       foreach($this->get_used_snapshot_bases() as $base){
1993         $ok |= count($this->getAllDeletedSnapshots($base)) >= 1 ;
1994       }
1996       if($ok){
1997         $str = "..|<img class='center' src='images/lists/restore.png' ".
1998           "alt='"._("Restore")."'>&nbsp;"._("Restore").                       "|RestoreDeletedSnapShot|\n";
1999       }else{
2000         $str = "..|<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;"._("Restore")."||\n";
2001       }
2002     }
2003     return($str);
2004   }
2007   function get_snapshot_action($base,$category)
2008   {
2009     $str= ""; 
2010     $ui = get_userinfo();
2011     if($this->snapshotEnabled()){
2012       if ($ui->allow_snapshot_restore($base,$category)){
2014         if(count($this->Available_SnapsShots($base))){
2015           $str.= "<input class='center' type='image' src='images/lists/restore.png'
2016             alt='"._("Restore snapshot")."' name='RestoreSnapShotDialog_".base64_encode($base)."' title='"._("Restore snapshot")."'>&nbsp;";
2017         } else {
2018           $str = "<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;";
2019         }
2020       }
2021       if($ui->allow_snapshot_create($base,$category)){
2022         $str.= "<input class='center' type='image' src='images/snapshot.png'
2023           alt='"._("Create snapshot")."' name='CreateSnapShotDialog_".base64_encode($base)."' 
2024           title='"._("Create a new snapshot from this object")."'>&nbsp;";
2025       }else{
2026         $str = "<img class='center' src='images/empty.png' alt=' '>&nbsp;";
2027       }
2028     }
2030     return($str);
2031   }
2034   function get_copypaste_action($base,$category,$class,$copy = TRUE, $cut = TRUE)
2035   {
2036     $ui = get_userinfo();
2037     $action = "";
2038     if($this->CopyPasteHandler){
2039       if($cut){
2040         if($ui->is_cutable($base,$category,$class)){
2041           $action .= "<input class='center' type='image'
2042             src='images/lists/cut.png' alt='"._("cut")."' name='cut_%KEY%' title='"._("Cut this entry")."'>&nbsp;";
2043         }else{
2044           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
2045         }
2046       }
2047       if($copy){
2048         if($ui->is_copyable($base,$category,$class)){
2049           $action.= "<input class='center' type='image'
2050             src='images/lists/copy.png' alt='"._("copy")."' name='copy_%KEY%' title='"._("Copy this entry")."'>&nbsp;";
2051         }else{
2052           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
2053         }
2054       }
2055     }
2057     return($action); 
2058   }
2061   function get_copypaste_header($base,$category,$copy = TRUE, $cut = TRUE)
2062   {
2063     $s = "";
2064     $ui =get_userinfo();
2066     if(!is_array($category)){
2067       $category = array($category);
2068     }
2070     /* Check permissions for each category, if there is at least one category which 
2071         support read or paste permissions for the given base, then display the specific actions.
2072      */
2073     $readable = $pasteable = false;
2074     foreach($category as $cat){
2075       $readable= $readable || preg_match('/r/', $ui->get_category_permissions($base, $cat));
2076       $pasteable= $pasteable || $ui->is_pasteable($base, $cat) == 1;
2077     }
2078   
2079     if(($cut || $copy) && isset($this->CopyPasteHandler) && is_object($this->CopyPasteHandler)){
2080       if($readable){
2081         $s.= "..|---|\n";
2082         if($copy){
2083           $s.= "..|<img src='images/lists/copy.png' alt='' border='0' class='center'>".
2084             "&nbsp;"._("Copy")."|"."multiple_copy_systems|\n";
2085         }
2086         if($cut){
2087           $s.= "..|<img src='images/lists/cut.png' alt='' border='0' class='center'>".
2088             "&nbsp;"._("Cut")."|"."multiple_cut_systems|\n";
2089         }
2090       }
2092       if($pasteable){
2093         if($this->CopyPasteHandler->entries_queued()){
2094           $img = "<img border='0' class='center' src='images/lists/paste.png' alt=''>";
2095           $s.="..|".$img."&nbsp;"._("Paste")."|editPaste|\n";
2096         }else{
2097           $img = "<img border='0' class='center' src='images/lists/paste-grey.png' alt=''>";
2098           $s.="..|".$img."&nbsp;"._("Paste")."\n";
2099         }
2100       }
2101     }
2102     return($s);
2103   }
2106   function get_used_snapshot_bases()
2107   {
2108      return(array());
2109   }
2111   function is_modal_dialog()
2112   {
2113     return(isset($this->dialog) && $this->dialog);
2114   }
2117 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2118 ?>