Code

d517efd5bd5465425a3c7acc09b1f00a8c740f60
[gosa.git] / trunk / 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 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',array());
265   }
267   /*! \brief Removes object from parent
268    */
269   function remove_from_parent()
270   {
271     /* include global link_info */
272     $ldap= $this->config->get_ldap_link();
274     /* Get current objectClasses in order to add the required ones */
275     $ldap->cat($this->dn);
276     $tmp= $ldap->fetch ();
277     $oc= array();
278     if (isset($tmp['objectClass'])){
279       $oc= $tmp['objectClass'];
280       unset($oc['count']);
281     }
283     /* Remove objectClasses from entry */
284     $ldap->cd($this->dn);
285     $this->attrs= array();
286     $this->attrs['objectClass']= array_remove_entries_ics($this->objectclasses,$oc);
288     /* Unset attributes from entry */
289     foreach ($this->attributes as $val){
290       $this->attrs["$val"]= array();
291     }
293     /* Unset account info */
294     $this->is_account= FALSE;
296     /* Do not write in plugin base class, this must be done by
297        children, since there are normally additional attribs,
298        lists, etc. */
299     /*
300        $ldap->modify($this->attrs);
301      */
302   }
305   /*! \brief Save HTML posted data to object 
306    */
307   function save_object()
308   {
309     /* Update entry CSN if it is empty. */
310     if(empty($this->entryCSN) && $this->CSN_check_active){
311       $this->entryCSN = getEntryCSN($this->dn);
312     }
314     /* Save values to object */
315     foreach ($this->attributes as $val){
316       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
317         /* Check for modifications */
318         if (get_magic_quotes_gpc()) {
319           $data= stripcslashes($_POST["$val"]);
320         } else {
321           $data= $this->$val = $_POST["$val"];
322         }
323         if ($this->$val != $data){
324           $this->is_modified= TRUE;
325         }
326     
327         /* Okay, how can I explain this fix ... 
328          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
329          * So IE posts these 'unselectable' option, with value = chr(194) 
330          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
331          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
332          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
333          */
334         if(isset($data[0]) && $data[0] == chr(194)) {
335           $data = "";  
336         }
337         $this->$val= $data;
338       }
339     }
340   }
343   /*! \brief Save data to LDAP, depending on is_account we save or delete */
344   function save()
345   {
346     /* include global link_info */
347     $ldap= $this->config->get_ldap_link();
349     /* Save all plugins */
350     $this->entryCSN = "";
352     /* Start with empty array */
353     $this->attrs= array();
355     /* Get current objectClasses in order to add the required ones */
356     $ldap->cat($this->dn);
357     
358     $tmp= $ldap->fetch ();
360     $oc= array();
361     if (isset($tmp['objectClass'])){
362       $oc= $tmp["objectClass"];
363       $this->is_new= FALSE;
364       unset($oc['count']);
365     } else {
366       $this->is_new= TRUE;
367     }
369     /* Load (minimum) attributes, add missing ones */
370     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
372     /* Copy standard attributes */
373     foreach ($this->attributes as $val){
374       if ($this->$val != ""){
375         $this->attrs["$val"]= $this->$val;
376       } elseif (!$this->is_new) {
377         $this->attrs["$val"]= array();
378       }
379     }
381     /* Handle tagging */
382     $this->tag_attrs($this->attrs);
383   }
386   function cleanup()
387   {
388     foreach ($this->attrs as $index => $value){
389       
390       /* Convert arrays with one element to non arrays, if the saved
391          attributes are no array, too */
392       if (is_array($this->attrs[$index]) && 
393           count ($this->attrs[$index]) == 1 &&
394           isset($this->saved_attributes[$index]) &&
395           !is_array($this->saved_attributes[$index])){
396           
397         $tmp= $this->attrs[$index][0];
398         $this->attrs[$index]= $tmp;
399       }
401       /* Remove emtpy arrays if they do not differ */
402       if (is_array($this->attrs[$index]) &&
403           count($this->attrs[$index]) == 0 &&
404           !isset($this->saved_attributes[$index])){
405           
406         unset ($this->attrs[$index]);
407         continue;
408       }
410       /* Remove single attributes that do not differ */
411       if (!is_array($this->attrs[$index]) &&
412           isset($this->saved_attributes[$index]) &&
413           !is_array($this->saved_attributes[$index]) &&
414           $this->attrs[$index] == $this->saved_attributes[$index]){
416         unset ($this->attrs[$index]);
417         continue;
418       }
420       /* Remove arrays that do not differ */
421       if (is_array($this->attrs[$index]) && 
422           isset($this->saved_attributes[$index]) &&
423           is_array($this->saved_attributes[$index])){
424           
425         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
426           unset ($this->attrs[$index]);
427           continue;
428         }
429       }
430     }
432     /* Update saved attributes and ensure that next cleanups will be successful too */
433     foreach($this->attrs as $name => $value){
434       $this->saved_attributes[$name] = $value;
435     }
436   }
438   /*! \brief Check formular input */
439   function check()
440   {
441     $message= array();
443     /* Skip if we've no config object */
444     if (!isset($this->config) || !is_object($this->config)){
445       return $message;
446     }
448     /* Find hooks entries for this class */
449     $command= $this->config->search(get_class($this), "CHECK", array('menu', 'tabs'));
451     if ($command != ""){
453       if (!check_command($command)){
454         $message[]= msgPool::cmdnotfound("CHECK", get_class($this));
455       } else {
457         /* Generate "ldif" for check hook */
458         $ldif= "dn: $this->dn\n";
459         
460         /* ... objectClasses */
461         foreach ($this->objectclasses as $oc){
462           $ldif.= "objectClass: $oc\n";
463         }
464         
465         /* ... attributes */
466         foreach ($this->attributes as $attr){
467           if ($this->$attr == ""){
468             continue;
469           }
470           if (is_array($this->$attr)){
471             foreach ($this->$attr as $val){
472               $ldif.= "$attr: $val\n";
473             }
474           } else {
475               $ldif.= "$attr: ".$this->$attr."\n";
476           }
477         }
479         /* Append empty line */
480         $ldif.= "\n";
482         /* Feed "ldif" into hook and retrieve result*/
483         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
484         $fh= proc_open($command, $descriptorspec, $pipes);
485         if (is_resource($fh)) {
486           fwrite ($pipes[0], $ldif);
487           fclose($pipes[0]);
488           
489           $result= stream_get_contents($pipes[1]);
490           if ($result != ""){
491             $message[]= $result;
492           }
493           
494           fclose($pipes[1]);
495           fclose($pipes[2]);
496           proc_close($fh);
497         }
498       }
500     }
502     /* Check entryCSN */
503     if($this->CSN_check_active){
504       $current_csn = getEntryCSN($this->dn);
505       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
506         $this->entryCSN = $current_csn;
507         $message[] = _("The object has changed since opened in GOsa. All changes that may be done by others get lost if you save this entry!");
508       }
509     }
510     return ($message);
511   }
513   /* Adapt from template, using 'dn' */
514   function adapt_from_template($dn, $skip= array())
515   {
516     /* Include global link_info */
517     $ldap= $this->config->get_ldap_link();
519     /* Load requested 'dn' to 'attrs' */
520     $ldap->cat ($dn);
521     $this->attrs= $ldap->fetch();
523     /* Walk through attributes */
524     foreach ($this->attributes as $val){
526       /* Skip the ones in skip list */
527       if (in_array($val, $skip)){
528         continue;
529       }
531       if (isset($this->attrs["$val"][0])){
533         /* If attribute is set, replace dynamic parts: 
534            %sn, %givenName and %uid. Fill these in our local variables. */
535         $value= $this->attrs["$val"][0];
537         foreach (array("sn", "givenName", "uid") as $repl){
538           if (preg_match("/%$repl/i", $value)){
539             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
540           }
541         }
542         $this->$val= $value;
543       }
544     }
546     /* Is Account? */
547     $found= TRUE;
548     foreach ($this->objectclasses as $obj){
549       if (preg_match('/top/i', $obj)){
550         continue;
551       }
552       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
553         $found= FALSE;
554         break;
555       }
556     }
557     if ($found){
558       $this->is_account= TRUE;
559     }
560   }
562   /* \brief Indicate whether a password change is needed or not */
563   function password_change_needed()
564   {
565     return FALSE;
566   }
569   /*! \brief Show header message for tab dialogs */
570   function show_enable_header($button_text, $text, $disabled= FALSE)
571   {
572     if (($disabled == TRUE) || (!$this->acl_is_createable())){
573       $state= "disabled";
574     } else {
575       $state= "";
576     }
577     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
578     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
579       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
581     return($display);
582   }
585   /*! \brief Show header message for tab dialogs */
586   function show_disable_header($button_text, $text, $disabled= FALSE)
587   {
588     if (($disabled == TRUE) || !$this->acl_is_removeable()){
589       $state= "disabled";
590     } else {
591       $state= "";
592     }
593     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
594     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
595       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
597     return($display);
598   }
601   /*! \brief Show header message for tab dialogs */
602   function show_header($button_text, $text, $disabled= FALSE)
603   {
604     echo "FIXME: show_header should be replaced by show_disable_header and show_enable_header<br>";
605     if ($disabled == TRUE){
606       $state= "disabled";
607     } else {
608       $state= "";
609     }
610     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
611     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
612       ($this->acl_is_createable()?'':'disabled')." ".$state.
613       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
615     return($display);
616   }
618   /*! \brief Executes commands after an object has been created */
619   function postcreate($add_attrs= array())
620   {
621     /* Find postcreate entries for this class */
622     $command= $this->config->search(get_class($this), "POSTCREATE",array('menu', 'tabs'));
624     if ($command != ""){
626       /* Walk through attribute list */
627       foreach ($this->attributes as $attr){
628         if (!is_array($this->$attr)){
629           $add_attrs[$attr] = $this->$attr;
630         }
631       }
632       $add_attrs['dn']=$this->dn;
634       $tmp = array();
635       foreach($add_attrs as $name => $value){
636         $tmp[$name] =  strlen($name);
637       }
638       arsort($tmp);
639       
640       /* Additional attributes */
641       foreach ($tmp as $name => $len){
642         $value = $add_attrs[$name];
643         $command= str_replace("%$name", "$value", $command);
644       }
646       if (check_command($command)){
647         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
648             $command, "Execute");
649         exec($command,$arr);
650         foreach($arr as $str){
651           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
652             $command, "Result: ".$str);
653         }
654       } else {
655         $message= msgPool::cmdnotfound("POSTCREATE", get_class($this));
656         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
657       }
658     }
659   }
661   /*! \brief Execute commands after an object has been modified */
662   function postmodify($add_attrs= array())
663   {
664     /* Find postcreate entries for this class */
665     $command= $this->config->search(get_class($this), "POSTMODIFY",array('menu','tabs'));
667     if ($command != ""){
669       /* Walk through attribute list */
670       foreach ($this->attributes as $attr){
671         if (!is_array($this->$attr)){
672           $add_attrs[$attr] = $this->$attr;
673         }
674       }
675       $add_attrs['dn']=$this->dn;
677       $tmp = array();
678       foreach($add_attrs as $name => $value){
679         $tmp[$name] =  strlen($name);
680       }
681       arsort($tmp);
682       
683       /* Additional attributes */
684       foreach ($tmp as $name => $len){
685         $value = $add_attrs[$name];
686         $command= str_replace("%$name", "$value", $command);
687       }
689       if (check_command($command)){
690         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,$command, "Execute");
691         exec($command,$arr);
692         foreach($arr as $str){
693           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
694             $command, "Result: ".$str);
695         }
696       } else {
697         $message= msgPool::cmdnotfound("POSTMODIFY", get_class($this));
698         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
699       }
700     }
701   }
703   /*! \brief Executes a command after an object has been removed */
704   function postremove($add_attrs= array())
705   {
706     /* Find postremove entries for this class */
707     $command= $this->config->search(get_class($this), "POSTREMOVE",array('menu','tabs'));
708     if ($command != ""){
710       /* Walk through attribute list */
711       foreach ($this->attributes as $attr){
712         if (!is_array($this->$attr)){
713           $add_attrs[$attr] = $this->$attr;
714         }
715       }
716       $add_attrs['dn']=$this->dn;
718       $tmp = array();
719       foreach($add_attrs as $name => $value){
720         $tmp[$name] =  strlen($name);
721       }
722       arsort($tmp);
723       
724       /* Additional attributes */
725       foreach ($tmp as $name => $len){
726         $value = $add_attrs[$name];
727         $command= str_replace("%$name", "$value", $command);
728       }
730       if (check_command($command)){
731         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
732             $command, "Execute");
734         exec($command,$arr);
735         foreach($arr as $str){
736           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
737             $command, "Result: ".$str);
738         }
739       } else {
740         $message= msgPool::cmdnotfound("POSTREMOVE", get_class($this));
741         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
742       }
743     }
744   }
746   /*! \brief Create unique DN */
747   function create_unique_dn($attribute, $base)
748   {
749     $ldap= $this->config->get_ldap_link();
750     $base= preg_replace("/^,*/", "", $base);
752     /* Try to use plain entry first */
753     $dn= "$attribute=".$this->$attribute.",$base";
754     $ldap->cat ($dn, array('dn'));
755     if (!$ldap->fetch()){
756       return ($dn);
757     }
759     /* Look for additional attributes */
760     foreach ($this->attributes as $attr){
761       if ($attr == $attribute || $this->$attr == ""){
762         continue;
763       }
765       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
766       $ldap->cat ($dn, array('dn'));
767       if (!$ldap->fetch()){
768         return ($dn);
769       }
770     }
772     /* None found */
773     return ("none");
774   }
776   function rebind($ldap, $referral)
777   {
778     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
779     if (ldap_bind($ldap, $credentials['ADMIN'], $this->config->get_credentials($credentials['PASSWORD']))) {
780       $this->error = "Success";
781       $this->hascon=true;
782       $this->reconnect= true;
783       return (0);
784     } else {
785       $this->error = "Could not bind to " . $credentials['ADMIN'];
786       return NULL;
787     }
788   }
791   /* Recursively copy ldap object */
792   function _copy($src_dn,$dst_dn)
793   {
794     $ldap=$this->config->get_ldap_link();
795     $ldap->cat($src_dn);
796     $attrs= $ldap->fetch();
798     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
799     $ds= ldap_connect($this->config->current['SERVER']);
800     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
801     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
802       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
803     }
805     $r=ldap_bind($ds,$this->config->current['ADMINDN'], $this->config->current['ADMINPASSWORD']);
806     $sr=ldap_read($ds, LDAP::fix($src_dn), "objectClass=*");
808     /* Fill data from LDAP */
809     $new= array();
810     if ($sr) {
811       $ei=ldap_first_entry($ds, $sr);
812       if ($ei) {
813         foreach($attrs as $attr => $val){
814           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
815             for ($i= 0; $i<$info['count']; $i++){
816               if ($info['count'] == 1){
817                 $new[$attr]= $info[$i];
818               } else {
819                 $new[$attr][]= $info[$i];
820               }
821             }
822           }
823         }
824       }
825     }
827     /* close conncetion */
828     ldap_unbind($ds);
830     /* Adapt naming attribute */
831     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
832     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
833     $new[$dst_name]= LDAP::fix($dst_val);
835     /* Check if this is a department.
836      * If it is a dep. && there is a , override in his ou 
837      *  change \2C to , again, else this entry can't be saved ...
838      */
839     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
840       $new['ou'] = str_replace("\\\\,",",",$new['ou']);
841     }
843     /* Save copy */
844     $ldap->connect();
845     $ldap->cd($this->config->current['BASE']);
846     
847     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
849     /* FAIvariable=.../..., cn=.. 
850         could not be saved, because the attribute FAIvariable was different to 
851         the dn FAIvariable=..., cn=... */
852     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
853       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
854     }
855     $ldap->cd($dst_dn);
856     $ldap->add($new);
858     if (!$ldap->success()){
859       trigger_error("Trying to save $dst_dn failed.",
860           E_USER_WARNING);
861       return(FALSE);
862     }
863     return(TRUE);
864   }
867   /* This is a workaround function. */
868   function copy($src_dn, $dst_dn)
869   {
870     /* Rename dn in possible object groups */
871     $ldap= $this->config->get_ldap_link();
872     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::prepare4filter($src_dn).'))',
873         array('cn'));
874     while ($attrs= $ldap->fetch()){
875       $og= new ogroup($this->config, $ldap->getDN());
876       unset($og->member[$src_dn]);
877       $og->member[$dst_dn]= $dst_dn;
878       $og->save ();
879     }
881     $ldap->cat($dst_dn);
882     $attrs= $ldap->fetch();
883     if (count($attrs)){
884       trigger_error("Trying to overwrite ".LDAP::fix($dst_dn).", which already exists.",
885           E_USER_WARNING);
886       return (FALSE);
887     }
889     $ldap->cat($src_dn);
890     $attrs= $ldap->fetch();
891     if (!count($attrs)){
892       trigger_error("Trying to move ".LDAP::fix($src_dn).", which does not seem to exist.",
893           E_USER_WARNING);
894       return (FALSE);
895     }
897     $ldap->cd($src_dn);
898     $ldap->search("objectClass=*",array("dn"));
899     while($attrs = $ldap->fetch()){
900       $src = $attrs['dn'];
901       $dst = preg_replace("/".preg_quote($src_dn, '/')."$/",$dst_dn,$attrs['dn']);
902       $this->_copy($src,$dst);
903     }
904     return (TRUE);
905   }
909   /*! \brief  Rename/Move a given src_dn to the given dest_dn
910    *
911    * Move a given ldap object indentified by $src_dn to the
912    * given destination $dst_dn
913    *
914    * - Ensure that all references are updated (ogroups)
915    * - Update ACLs   
916    * - Update accessTo
917    *
918    * \param  string  'src_dn' the source DN.
919    * \param  string  'dst_dn' the destination DN.
920    * \return boolean TRUE on success else FALSE.
921    */
922   function rename($src_dn, $dst_dn)
923   {
924     $start = microtime(1);
926     /* Try to move the source entry to the destination position */
927     $ldap = $this->config->get_ldap_link();
928     $ldap->cd($this->config->current['BASE']);
929     $ldap->create_missing_trees(preg_replace("/^[^,]+,/","",$dst_dn));
930     if (!$ldap->rename_dn($src_dn,$dst_dn)){
931 #      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $src_dn, "", get_class()));
932       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());
933       @DEBUG(DEBUG_LDAP,__LINE__,__FUNCTION__,__FILE__,"Rename failed FROM: $src_dn  -- TO:  $dst_dn", 
934           "Ldap Protocol v3 implementation error, falling back to maunal method.");
935       return(FALSE);
936     }
938     /* Get list of users,groups and roles within this tree,
939         maybe we have to update ACL references.
940      */
941     $leaf_objs = get_list("(|(objectClass=posixGroup)(objectClass=gosaAccount)(objectClass=gosaRole))",array("all"),$dst_dn,
942           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
943     foreach($leaf_objs as $obj){
944       $new_dn = $obj['dn'];
945       $old_dn = preg_replace("/".preg_quote($dst_dn, '/')."$/i",$src_dn,$new_dn);
946       $this->update_acls($old_dn,$new_dn); 
947     }
949     /* Get all objectGroups defined in this database. 
950         and check if there is an entry matching the source dn,
951         if this is the case, then update this objectgroup to use the new dn.
952      */
953     $ogroups = get_sub_list("(&(objectClass=gosaGroupOfNames)(member=*))","ogroups",
954         array(get_ou("ogroupRDN")),$this->config->current['BASE'],array("member"),
955         GL_SUBSEARCH | GL_NO_ACL_CHECK) ;
957     /* Walk through all objectGroups and check if there are 
958         members matching the source dn 
959      */
960     $src_dn=str_replace('\\,', '\\2C', LDAP::fix($src_dn));
961     foreach($ogroups as $ogroup){
962       if(isset($ogroup['member'])){
964         /* Reset class object, this will be initialized with class_ogroup on demand 
965          */
966         $o_ogroup = NULL; 
967         for($i = 0 ; $i < $ogroup['member']['count'] ; $i ++){
969           $c_mem = $ogroup['member'][$i];
970   
971           if(preg_match("/".preg_quote($src_dn, '/')."$/i",$c_mem)){
972  
973             $d_mem = preg_replace("/".preg_quote($src_dn, '/')."$/i",$dst_dn,$ogroup['member'][$i]);
975             if($o_ogroup == NULL){
976               $o_ogroup = new ogroup($this->config,$ogroup['dn']);
977             }              
979             /* Members are stored with their converted names, so convert $c_mem as well
980                to have it match in case of special characters in its name. */
981             unset($o_ogroup->member[LDAP::convert($c_mem)]);
982             $o_ogroup->member[$d_mem]= $d_mem;
983           }
984         }
985        
986         /* Save object group if there were changes made on the membership */ 
987         if($o_ogroup != NULL){
988           $o_ogroup->save();
989         }
990       }
991     }
992  
993     /* Check if there are gosa departments moved. 
994        If there were deps moved, the force reload of config->deps.
995      */
996     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
997           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
998   
999     if(count($leaf_deps)){
1000       $this->config->get_departments();
1001       $this->config->make_idepartments();
1002       session::global_set("config",$this->config);
1003       $ui =get_userinfo();
1004       $ui->reset_acl_cache();
1005     }
1007     return(TRUE); 
1008   }
1011  
1012   function move($src_dn, $dst_dn)
1013   {
1014     /* Do not copy if only upper- lowercase has changed */
1015     if(strtolower($src_dn) == strtolower($dst_dn)){
1016       return(TRUE);
1017     }
1019     
1020     /* Try to move the entry instead of copy & delete
1021      */
1022     if(TRUE){
1024       /* Try to move with ldap routines, if this was not successfull
1025           fall back to the old style copy & remove method 
1026        */
1027       if($this->rename($src_dn, $dst_dn)){
1028         return(TRUE);
1029       }else{
1030         // See code below.
1031       }
1032     }
1034     /* Copy source to destination */
1035     if (!$this->copy($src_dn, $dst_dn)){
1036       return (FALSE);
1037     }
1039     /* Delete source */
1040     $ldap= $this->config->get_ldap_link();
1041     $ldap->rmdir_recursive($src_dn);
1042     if (!$ldap->success()){
1043       trigger_error("Trying to delete $src_dn failed.",
1044           E_USER_WARNING);
1045       return (FALSE);
1046     }
1048     return (TRUE);
1049   }
1052   /* \brief Move/Rename complete trees */
1053   function recursive_move($src_dn, $dst_dn)
1054   {
1055     /* Check if the destination entry exists */
1056     $ldap= $this->config->get_ldap_link();
1058     /* Check if destination exists - abort */
1059     $ldap->cat($dst_dn, array('dn'));
1060     if ($ldap->fetch()){
1061       trigger_error("recursive_move $dst_dn already exists.",
1062           E_USER_WARNING);
1063       return (FALSE);
1064     }
1066     $this->copy($src_dn, $dst_dn);
1068     /* Remove src_dn */
1069     $ldap->cd($src_dn);
1070     $ldap->recursive_remove($src_dn);
1071     return (TRUE);
1072   }
1075   function handle_post_events($mode, $add_attrs= array())
1076   {
1077     switch ($mode){
1078       case "add":
1079         $this->postcreate($add_attrs);
1080       break;
1082       case "modify":
1083         $this->postmodify($add_attrs);
1084       break;
1086       case "remove":
1087         $this->postremove($add_attrs);
1088       break;
1089     }
1090   }
1093   function saveCopyDialog(){
1094   }
1097   function getCopyDialog(){
1098     return(array("string"=>"","status"=>""));
1099   }
1102   /*! \brief Prepare for Copy & Paste */
1103   function PrepareForCopyPaste($source)
1104   {
1105     $todo = $this->attributes;
1106     if(isset($this->CopyPasteVars)){
1107       $todo = array_merge($todo,$this->CopyPasteVars);
1108     }
1110     if(count($this->objectclasses)){
1111       $this->is_account = TRUE;
1112       foreach($this->objectclasses as $class){
1113         if(!in_array($class,$source['objectClass'])){
1114           $this->is_account = FALSE;
1115         }
1116       }
1117     }
1119     foreach($todo as $var){
1120       if (isset($source[$var])){
1121         if(isset($source[$var]['count'])){
1122           if($source[$var]['count'] > 1){
1123             $this->$var = array();
1124             $tmp = array();
1125             for($i = 0 ; $i < $source[$var]['count']; $i++){
1126               $tmp = $source[$var][$i];
1127             }
1128             $this->$var = $tmp;
1129           }else{
1130             $this->$var = $source[$var][0];
1131           }
1132         }else{
1133           $this->$var= $source[$var];
1134         }
1135       }
1136     }
1137   }
1139   /*! \brief Get gosaUnitTag for the given DN */
1140   function get_gosaUnitTag($dn = "")
1141   {
1142     if ($dn == "") {
1143         $dn = $this->dn;
1144     }
1146     $len = strlen($dn);
1147     @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1148      $relevant= array();
1149         foreach ($this->config->adepartments as $key => $ntag){
1151           /* This one is bigger than our dn, its not relevant... */
1152           if ($len < strlen($key)){
1153             continue;
1154           }
1156           /* This one matches with the latter part. Break and don't fix this entry */
1157           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
1158             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1159             $relevant[strlen($key)]= $ntag;
1160             continue;
1161           }
1163         }
1165         /* If we've some relevant tags to set, just get the longest one */
1166         if (count($relevant)){
1167           ksort($relevant);
1168           $tmp= array_keys($relevant);
1169           $idx= end($tmp);
1170           $tag= $relevant[$idx];
1171           return $tag;
1172         }
1174   }
1176   /*! \brief Add unit tag */ 
1177   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1178   {
1179     /* Skip tagging? 
1180        If this is called from departmentGeneric, we have to skip this
1181         tagging procedure. 
1182      */
1183     if($this->skipTagging){
1184       return;
1185     }
1187     /* No dn? Self-operation... */
1188     if ($dn == ""){
1189       $dn= $this->dn;
1191       /* No tag? Find it yourself... */
1192       if ($tag == ""){
1193           $tag = $this->get_gosaUnitTag();
1194       }
1195     }
1196   
1197     /* Remove tags that may already be here... */
1198     remove_objectClass("gosaAdministrativeUnitTag", $at);
1199     if (isset($at['gosaUnitTag'])){
1200         unset($at['gosaUnitTag']);
1201     }
1203     /* Set tag? */
1204     if ($tag != ""){
1205       add_objectClass("gosaAdministrativeUnitTag", $at);
1206       $at['gosaUnitTag']= $tag;
1207     }
1209     /* Initially this object was tagged. 
1210        - But now, it is no longer inside a tagged department. 
1211        So force the remove of the tag.
1212        (objectClass was already removed obove)
1213      */
1214     if($tag == "" && $this->gosaUnitTag){
1215       $at['gosaUnitTag'] = array();
1216     }
1217   }
1220   /*! \brief Test for removability of the object
1221    *
1222    * Allows testing of conditions for removal of object. If removal should be aborted
1223    * the function needs to remove an error message.
1224    * */
1225   function allow_remove()
1226   {
1227     $reason= "";
1228     return $reason;
1229   }
1232   /*! \brief Create a snapshot of the current object */
1233   function create_snapshot($type= "snapshot", $description= array())
1234   {
1236     /* Check if snapshot functionality is enabled */
1237     if(!$this->snapshotEnabled()){
1238       return;
1239     }
1241     /* Get configuration from gosa.conf */
1242     $config = $this->config;
1244     /* Create lokal ldap connection */
1245     $ldap= $this->config->get_ldap_link();
1246     $ldap->cd($this->config->current['BASE']);
1248     /* check if there are special server configurations for snapshots */
1249     if($config->get_cfg_value("snapshotURI") == ""){
1251       /* Source and destination server are both the same, just copy source to dest obj */
1252       $ldap_to      = $ldap;
1253       $snapldapbase = $this->config->current['BASE'];
1255     }else{
1256       $server         = $config->get_cfg_value("snapshotURI");
1257       $user           = $config->get_cfg_value("snapshotAdminDn");
1258       $password       = $config->get_cfg_value("snapshotAdminPassword");
1259       $snapldapbase   = $config->get_cfg_value("snapshotBase");
1261       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1262       $ldap_to -> cd($snapldapbase);
1264       if (!$ldap_to->success()){
1265         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1266       }
1268     }
1270     /* check if the dn exists */ 
1271     if ($ldap->dn_exists($this->dn)){
1273       /* Extract seconds & mysecs, they are used as entry index */
1274       list($usec, $sec)= explode(" ", microtime());
1276       /* Collect some infos */
1277       $base           = $this->config->current['BASE'];
1278       $snap_base      = $config->get_cfg_value("snapshotBase");
1279       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1280       $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1282       /* Create object */
1283 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1284       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1285       $newName          = str_replace(".", "", $sec."-".$usec);
1286       $target= array();
1287       $target['objectClass']            = array("top", "gosaSnapshotObject");
1288       $target['gosaSnapshotData']       = gzcompress($data, 6);
1289       $target['gosaSnapshotType']       = $type;
1290       $target['gosaSnapshotDN']         = $this->dn;
1291       $target['description']            = $description;
1292       $target['gosaSnapshotTimestamp']  = $newName;
1294       /* Insert the new snapshot 
1295          But we have to check first, if the given gosaSnapshotTimestamp
1296          is already used, in this case we should increment this value till there is 
1297          an unused value. */ 
1298       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1299       $ldap_to->cat($new_dn);
1300       while($ldap_to->count()){
1301         $ldap_to->cat($new_dn);
1302         $newName = str_replace(".", "", $sec."-".($usec++));
1303         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1304         $target['gosaSnapshotTimestamp']  = $newName;
1305       } 
1307       /* Inset this new snapshot */
1308       $ldap_to->cd($snapldapbase);
1309       $ldap_to->create_missing_trees($snapldapbase);
1310       $ldap_to->create_missing_trees($new_base);
1311       $ldap_to->cd($new_dn);
1312       $ldap_to->add($target);
1313       if (!$ldap_to->success()){
1314         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $new_dn, LDAP_ADD, get_class()));
1315       }
1317       if (!$ldap->success()){
1318         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $new_base, "", get_class()));
1319       }
1321     }
1322   }
1324   /*! \brief Remove a snapshot */
1325   function remove_snapshot($dn)
1326   {
1327     $ui       = get_userinfo();
1328     $old_dn   = $this->dn; 
1329     $this->dn = $dn;
1330     $ldap = $this->config->get_ldap_link();
1331     $ldap->cd($this->config->current['BASE']);
1332     $ldap->rmdir_recursive($this->dn);
1333     if(!$ldap->success()){
1334       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn));
1335     }
1336     $this->dn = $old_dn;
1337   }
1340   /*! \brief Test if snapshotting is enabled
1341    *
1342    * Test weither snapshotting is enabled or not. There will also be some errors posted,
1343    * if the configuration failed 
1344    * \return TRUE if snapshots are enabled, and FALSE if it is disabled
1345    */
1346   function snapshotEnabled()
1347   {
1348     $config = $this->config;
1349     if($config->get_cfg_value("enableSnapshots") == "true"){
1350             /* Check if the snapshot_base is defined */
1351             if ($config->get_cfg_value("snapshotBase") == ""){
1352                     msg_dialog::display(_("Configuration error"), sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."),"snapshotBase"), ERROR_DIALOG);
1353                     return(FALSE);
1354             }
1356             /* check if there are special server configurations for snapshots */
1357             if ($config->get_cfg_value("snapshotURI") != ""){
1359                     /* check if all required vars are available to create a new ldap connection */
1360                     $missing = "";
1361                     foreach(array("snapshotURI","snapshotAdminDn","snapshotAdminPassword","snapshotBase") as $var){
1362                             if($config->get_cfg_value($var) == ""){
1363                                     $missing .= $var." ";
1364                                     msg_dialog::display(_("Configuration error"), sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."), $missing), ERROR_DIALOG);
1365                                     return(FALSE);
1366                             }
1367                     }
1368             }
1369             return(TRUE);
1370     }
1371     return(FALSE);
1372   }
1375   /* \brief Return available snapshots for the given base */
1376   function Available_SnapsShots($dn,$raw = false)
1377   {
1378     if(!$this->snapshotEnabled()) return(array());
1380     /* Create an additional ldap object which
1381        points to our ldap snapshot server */
1382     $ldap= $this->config->get_ldap_link();
1383     $ldap->cd($this->config->current['BASE']);
1384     $cfg= &$this->config->current;
1386     /* check if there are special server configurations for snapshots */
1387     if($this->config->get_cfg_value("snapshotURI") == ""){
1388       $ldap_to      = $ldap;
1389     }else{
1390       $server         = $this->config->get_cfg_value("snapshotURI");
1391       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1392       $password       = $this->config->get_cfg_value("snapshotAdminPassword");
1393       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1394       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1395       $ldap_to -> cd($snapldapbase);
1396       if (!$ldap_to->success()){
1397         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1398       }
1399     }
1401     /* Prepare bases and some other infos */
1402     $base           = $this->config->current['BASE'];
1403     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1404     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1405     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1406     $tmp            = array(); 
1408     /* Fetch all objects with  gosaSnapshotDN=$dn */
1409     $ldap_to->cd($new_base);
1410     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1411         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1413     /* Put results into a list and add description if missing */
1414     while($entry = $ldap_to->fetch()){ 
1415       if(!isset($entry['description'][0])){
1416         $entry['description'][0]  = "";
1417       }
1418       $tmp[] = $entry; 
1419     }
1421     /* Return the raw array, or format the result */
1422     if($raw){
1423       return($tmp);
1424     }else{  
1425       $tmp2 = array();
1426       foreach($tmp as $entry){
1427         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1428       }
1429     }
1430     return($tmp2);
1431   }
1434   function getAllDeletedSnapshots($base_of_object,$raw = false)
1435   {
1436     if(!$this->snapshotEnabled()) return(array());
1438     /* Create an additional ldap object which
1439        points to our ldap snapshot server */
1440     $ldap= $this->config->get_ldap_link();
1441     $ldap->cd($this->config->current['BASE']);
1442     $cfg= &$this->config->current;
1444     /* check if there are special server configurations for snapshots */
1445     if($this->config->get_cfg_value("snapshotURI") == ""){
1446       $ldap_to      = $ldap;
1447     }else{
1448       $server         = $this->config->get_cfg_value("snapshotURI");
1449       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1450       $password       = $this->config->get_cfg_value("snapshotAdminPassword");
1451       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1452       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1453       $ldap_to -> cd($snapldapbase);
1454       if (!$ldap_to->success()){
1455         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1456       }
1457     }
1459     /* Prepare bases */ 
1460     $base           = $this->config->current['BASE'];
1461     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1462     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1464     /* Fetch all objects and check if they do not exist anymore */
1465     $ui = get_userinfo();
1466     $tmp = array();
1467     $ldap_to->cd($new_base);
1468     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1469     while($entry = $ldap_to->fetch()){
1471       $chk =  str_replace($new_base,"",$entry['dn']);
1472       if(preg_match("/,ou=/",$chk)) continue;
1474       if(!isset($entry['description'][0])){
1475         $entry['description'][0]  = "";
1476       }
1477       $tmp[] = $entry; 
1478     }
1480     /* Check if entry still exists */
1481     foreach($tmp as $key => $entry){
1482       $ldap->cat($entry['gosaSnapshotDN'][0]);
1483       if($ldap->count()){
1484         unset($tmp[$key]);
1485       }
1486     }
1488     /* Format result as requested */
1489     if($raw) {
1490       return($tmp);
1491     }else{
1492       $tmp2 = array();
1493       foreach($tmp as $key => $entry){
1494         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1495       }
1496     }
1497     return($tmp2);
1498   } 
1501   /* \brief Restore selected snapshot */
1502   function restore_snapshot($dn)
1503   {
1504     if(!$this->snapshotEnabled()) return(array());
1506     $ldap= $this->config->get_ldap_link();
1507     $ldap->cd($this->config->current['BASE']);
1508     $cfg= &$this->config->current;
1510     /* check if there are special server configurations for snapshots */
1511     if($this->config->get_cfg_value("snapshotURI") == ""){
1512       $ldap_to      = $ldap;
1513     }else{
1514       $server         = $this->config->get_cfg_value("snapshotURI");
1515       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1516       $password       = $this->config->get_cfg_value("snapshotAdminPassword");
1517       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1518       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1519       $ldap_to -> cd($snapldapbase);
1520       if (!$ldap_to->success()){
1521         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1522       }
1523     }
1525     /* Get the snapshot */ 
1526     $ldap_to->cat($dn);
1527     $restoreObject = $ldap_to->fetch();
1529     /* Prepare import string */
1530     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1532     /* Import the given data */
1533     $err = "";
1534     $ldap->import_complete_ldif($data,$err,false,false);
1535     if (!$ldap->success()){
1536       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, "", get_class()));
1537     }
1538   }
1541   function showSnapshotDialog($base,$baseSuffixe,&$parent)
1542   {
1543     $once = true;
1544     $ui = get_userinfo();
1545     $this->parent = $parent;
1547     foreach($_POST as $name => $value){
1549       /* Create a new snapshot, display a dialog */
1550       if(preg_match("/^CreateSnapShotDialog_[^_]*_[xy]$/",$name) && $once){
1552                           $entry = base64_decode(preg_replace("/^CreateSnapShotDialog_([^_]*)_[xy]$/","\\1",$name));
1553         $once = false;
1554         $entry = preg_replace("/^CreateSnapShotDialog_/","",$entry);
1556         if(!empty($entry) && $ui->allow_snapshot_create($entry,$this->parent->acl_module)){
1557           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1558         }else{
1559           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to create a snapshot for %s."),$entry),ERROR_DIALOG);
1560         }
1561       }  
1562   
1563       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1564       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1565         $once = false;
1566         $entry = base64_decode(preg_replace("/^RestoreSnapShotDialog_([^_]*)_[xy]$/i","\\1",$name));
1567         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1568           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1569           $this->snapDialog->display_restore_dialog = true;
1570         }else{
1571           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1572         }
1573       }
1575       /* Restore one of the already deleted objects */
1576       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1577           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1578         $once = false;
1580         if($ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1581           $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1582           $this->snapDialog->set_snapshot_bases($baseSuffixe);
1583           $this->snapDialog->display_restore_dialog      = true;
1584           $this->snapDialog->display_all_removed_objects  = true;
1585         }else{
1586           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$base),ERROR_DIALOG);
1587         }
1588       }
1590       /* Restore selected snapshot */
1591       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1592         $once = false;
1593         $entry = base64_decode(preg_replace("/^RestoreSnapShot_([^_]*)_[xy]$/i","\\1",$name));
1595         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1596           $this->restore_snapshot($entry);
1597           $this->snapDialog = NULL;
1598         }else{
1599           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1600         }
1601       }
1602     }
1604     /* Create a new snapshot requested, check
1605        the given attributes and create the snapshot*/
1606     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1607       $this->snapDialog->save_object();
1608       $msgs = $this->snapDialog->check();
1609       if(count($msgs)){
1610         foreach($msgs as $msg){
1611           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
1612         }
1613       }else{
1614         $this->dn =  $this->snapDialog->dn;
1615         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1616         $this->snapDialog = NULL;
1617       }
1618     }
1620     /* Restore is requested, restore the object with the posted dn .*/
1621     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1622     }
1624     if(isset($_POST['CancelSnapshot'])){
1625       $this->snapDialog = NULL;
1626     }
1628     if(is_object($this->snapDialog )){
1629       $this->snapDialog->save_object();
1630       return($this->snapDialog->execute());
1631     }
1632   }
1635   /*! \brief Return plugin informations for acl handling */
1636   static function plInfo()
1637   {
1638     return array();
1639   }
1642   function set_acl_base($base)
1643   {
1644     $this->acl_base= $base;
1645   }
1648   function set_acl_category($category)
1649   {
1650     $this->acl_category= "$category/";
1651   }
1654   function acl_is_writeable($attribute,$skip_write = FALSE)
1655   {
1656     if($this->read_only) return(FALSE);
1657     $ui= get_userinfo();
1658     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1659   }
1662   function acl_is_readable($attribute)
1663   {
1664     $ui= get_userinfo();
1665     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1666   }
1669   function acl_is_createable($base ="")
1670   {
1671     if($this->read_only) return(FALSE);
1672     $ui= get_userinfo();
1673     if($base == "") $base = $this->acl_base;
1674     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1675   }
1678   function acl_is_removeable($base ="")
1679   {
1680     if($this->read_only) return(FALSE);
1681     $ui= get_userinfo();
1682     if($base == "") $base = $this->acl_base;
1683     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1684   }
1687   function acl_is_moveable($base = "")
1688   {
1689     if($this->read_only) return(FALSE);
1690     $ui= get_userinfo();
1691     if($base == "") $base = $this->acl_base;
1692     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1693   }
1696   function acl_have_any_permissions()
1697   {
1698   }
1701   function getacl($attribute,$skip_write= FALSE)
1702   {
1703     $ui= get_userinfo();
1704     $skip_write |= $this->read_only;
1705     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1706   }
1709   /*! \brief Returns a list of all available departments for this object.
1710    * 
1711    * If this object is new, all departments we are allowed to create a new user in
1712    * are returned. If this is an existing object, return all deps. 
1713    * We are allowed to move tis object too.
1714    * \return array [dn] => "..name"  // All deps. we are allowed to act on.
1715   */
1716   function get_allowed_bases()
1717   {
1718     $ui = get_userinfo();
1719     $deps = array();
1721     /* Is this a new object ? Or just an edited existing object */
1722     if(!$this->initially_was_account && $this->is_account){
1723       $new = true;
1724     }else{
1725       $new = false;
1726     }
1728     foreach($this->config->idepartments as $dn => $name){
1729       if($new && $this->acl_is_createable($dn)){
1730         $deps[$dn] = $name;
1731       }elseif(!$new && $this->acl_is_moveable($dn)){
1732         $deps[$dn] = $name;
1733       }
1734     }
1736     /* Add current base */      
1737     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1738       $deps[$this->base] = $this->config->idepartments[$this->base];
1739     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1741     }else{
1742       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1743     }
1744     return($deps);
1745   }
1748   /* This function updates ACL settings if $old_dn was used.
1749    *  \param string 'old_dn' specifies the actually used dn
1750    *  \param string 'new_dn' specifies the destiantion dn
1751    */
1752   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1753   {
1754     /* Check if old_dn is empty. This should never happen */
1755     if(empty($old_dn) || empty($new_dn)){
1756       trigger_error("Failed to check acl dependencies, wrong dn given.");
1757       return;
1758     }
1760     /* Update userinfo if necessary */
1761     $ui = session::global_get('ui');
1762     if($ui->dn == $old_dn){
1763       $ui->dn = $new_dn;
1764       session::global_set('ui',$ui);
1765       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1766     }
1768     /* Object was moved, ensure that all acls will be moved too */
1769     if($new_dn != $old_dn && $old_dn != "new"){
1771       /* get_ldap configuration */
1772       $update = array();
1773       $ldap = $this->config->get_ldap_link();
1774       $ldap->cd ($this->config->current['BASE']);
1775       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1776       while($attrs = $ldap->fetch()){
1777         $acls = array();
1778         $found = false;
1779         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1780           $acl_parts = split(":",$attrs['gosaAclEntry'][$i]);
1782           /* Roles uses antoher data storage order, members are stored int the third part, 
1783              while the members in direct ACL assignments are stored in the second part.
1784            */
1785           $id = ($acl_parts[1] == "role") ? 3 : 2;
1787           /* Update member entries to use $new_dn instead of old_dn
1788            */
1789           $members = explode(",",$acl_parts[$id]);
1790           foreach($members as $key => $member){
1791             $member = base64_decode($member);
1792             if($member == $old_dn){
1793               $members[$key] = base64_encode($new_dn);
1794               $found = TRUE;
1795             }
1796           } 
1798           /* Check if the selected role has to updated
1799            */
1800           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1801             $acl_parts[2] = base64_encode($new_dn);
1802             $found = TRUE;
1803           }
1805           /* Build new acl string */ 
1806           $acl_parts[$id] = implode($members,",");
1807           $acls[] = implode($acl_parts,":");
1808         }
1810         /* Acls for this object must be adjusted */
1811         if($found){
1813           $debug_info=  _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1814             $old_dn."</b><br>&nbsp;-"._("to")."&nbsp;<b>".$new_dn."</b><br>";
1815           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1817           $update[$attrs['dn']] =array();
1818           foreach($acls as $acl){
1819             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1820           }
1821         }
1822       }
1824       /* Write updated acls */
1825       foreach($update as $dn => $attrs){
1826         $ldap->cd($dn);
1827         $ldap->modify($attrs);
1828       }
1829     }
1830   }
1832   
1834   /*! \brief Enable the Serial ID check
1835    *
1836    * This function enables the entry Serial ID check.  If an entry was edited while
1837    * we have edited the entry too, an error message will be shown. 
1838    * To configure this check correctly read the FAQ.
1839    */    
1840   function enable_CSN_check()
1841   {
1842     $this->CSN_check_active =TRUE;
1843     $this->entryCSN = getEntryCSN($this->dn);
1844   }
1847   /*! \brief  Prepares the plugin to be used for multiple edit
1848    *          Update plugin attributes with given array of attribtues.
1849    *  \param  array   Array with attributes that must be updated.
1850    */
1851   function init_multiple_support($attrs,$all)
1852   {
1853     $ldap= $this->config->get_ldap_link();
1854     $this->multi_attrs    = $attrs;
1855     $this->multi_attrs_all= $all;
1857     /* Copy needed attributes */
1858     foreach ($this->attributes as $val){
1859       $found= array_key_ics($val, $this->multi_attrs);
1860       if ($found != ""){
1861         if(isset($this->multi_attrs["$found"][0])){
1862           $this->$val= $this->multi_attrs["$found"][0];
1863         }
1864       }
1865     }
1866   }
1868  
1869   /*! \brief  Enables multiple support for this plugin
1870    */
1871   function enable_multiple_support()
1872   {
1873     $this->ignore_account = TRUE;
1874     $this->multiple_support_active = TRUE;
1875   }
1878   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1879       \return array Cotaining all modified values. 
1880    */
1881   function get_multi_edit_values()
1882   {
1883     $ret = array();
1884     foreach($this->attributes as $attr){
1885       if(in_array($attr,$this->multi_boxes)){
1886         $ret[$attr] = $this->$attr;
1887       }
1888     }
1889     return($ret);
1890   }
1892   
1893   /*! \brief  Update class variables with values collected by multiple edit.
1894    */
1895   function set_multi_edit_values($attrs)
1896   {
1897     foreach($attrs as $name => $value){
1898       $this->$name = $value;
1899     }
1900   }
1903   /*! \brief Generates the html output for this node for multi edit*/
1904   function multiple_execute()
1905   {
1906     /* This one is empty currently. Fabian - please fill in the docu code */
1907     session::global_set('current_class_for_help',get_class($this));
1909     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1910     session::set('LOCK_VARS_TO_USE',array());
1911     session::set('LOCK_VARS_USED',array());
1912     
1913     return("Multiple edit is currently not implemented for this plugin.");
1914   }
1917   /*! \brief Save HTML posted data to object for multiple edit
1918    */
1919   function multiple_save_object()
1920   {
1921     if(empty($this->entryCSN) && $this->CSN_check_active){
1922       $this->entryCSN = getEntryCSN($this->dn);
1923     }
1925     /* Save values to object */
1926     $this->multi_boxes = array();
1927     foreach ($this->attributes as $val){
1928   
1929       /* Get selected checkboxes from multiple edit */
1930       if(isset($_POST["use_".$val])){
1931         $this->multi_boxes[] = $val;
1932       }
1934       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
1936         /* Check for modifications */
1937         if (get_magic_quotes_gpc()) {
1938           $data= stripcslashes($_POST["$val"]);
1939         } else {
1940           $data= $this->$val = $_POST["$val"];
1941         }
1942         if ($this->$val != $data){
1943           $this->is_modified= TRUE;
1944         }
1945     
1946         /* IE post fix */
1947         if(isset($data[0]) && $data[0] == chr(194)) {
1948           $data = "";  
1949         }
1950         $this->$val= $data;
1951       }
1952     }
1953   }
1956   /*! \brief Returns all attributes of this plugin, 
1957                to be able to detect multiple used attributes 
1958                in multi_plugg::detect_multiple_used_attributes().
1959       @return array Attributes required for intialization of multi_plug
1960    */
1961   public function get_multi_init_values()
1962   {
1963     $attrs = $this->attrs;
1964     return($attrs);
1965   }
1968   /*! \brief  Check given values in multiple edit
1969       \return array Error messages
1970    */
1971   function multiple_check()
1972   {
1973     $message = plugin::check();
1974     return($message);
1975   }
1978   /*! \brief  Returns the snapshot header part for "Actions" menu in management dialogs 
1979       \param  $layer_menu  
1980    */   
1981   function get_snapshot_header($base,$category)
1982   {
1983     $str = "";
1984     $ui = get_userinfo();
1985     if($this->snapshotEnabled() && $ui->allow_snapshot_restore($base,$category)){
1987       $ok = false;
1988       foreach($this->get_used_snapshot_bases() as $base){
1989         $ok |= count($this->getAllDeletedSnapshots($base)) >= 1 ;
1990       }
1992       if($ok){
1993         $str = "..|<img class='center' src='images/lists/restore.png' ".
1994           "alt='"._("Restore")."'>&nbsp;"._("Restore").                       "|RestoreDeletedSnapShot|\n";
1995       }else{
1996         $str = "..|<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;"._("Restore")."||\n";
1997       }
1998     }
1999     return($str);
2000   }
2003   function get_snapshot_action($base,$category)
2004   {
2005     $str= ""; 
2006     $ui = get_userinfo();
2007     if($this->snapshotEnabled()){
2008       if ($ui->allow_snapshot_restore($base,$category)){
2010         if(count($this->Available_SnapsShots($base))){
2011           $str.= "<input class='center' type='image' src='images/lists/restore.png'
2012             alt='"._("Restore snapshot")."' name='RestoreSnapShotDialog_".base64_encode($base)."' title='"._("Restore snapshot")."'>&nbsp;";
2013         } else {
2014           $str = "<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;";
2015         }
2016       }
2017       if($ui->allow_snapshot_create($base,$category)){
2018         $str.= "<input class='center' type='image' src='images/snapshot.png'
2019           alt='"._("Create snapshot")."' name='CreateSnapShotDialog_".base64_encode($base)."' 
2020           title='"._("Create a new snapshot from this object")."'>&nbsp;";
2021       }else{
2022         $str = "<img class='center' src='images/empty.png' alt=' '>&nbsp;";
2023       }
2024     }
2026     return($str);
2027   }
2030   function get_copypaste_action($base,$category,$class,$copy = TRUE, $cut = TRUE)
2031   {
2032     $ui = get_userinfo();
2033     $action = "";
2034     if($this->CopyPasteHandler){
2035       if($cut){
2036         if($ui->is_cutable($base,$category,$class)){
2037           $action .= "<input class='center' type='image'
2038             src='images/lists/cut.png' alt='"._("cut")."' name='cut_%KEY%' title='"._("Cut this entry")."'>&nbsp;";
2039         }else{
2040           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
2041         }
2042       }
2043       if($copy){
2044         if($ui->is_copyable($base,$category,$class)){
2045           $action.= "<input class='center' type='image'
2046             src='images/lists/copy.png' alt='"._("copy")."' name='copy_%KEY%' title='"._("Copy this entry")."'>&nbsp;";
2047         }else{
2048           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
2049         }
2050       }
2051     }
2053     return($action); 
2054   }
2057   function get_copypaste_header($base,$category,$copy = TRUE, $cut = TRUE)
2058   {
2059     $s = "";
2060     $ui =get_userinfo();
2062     if(!is_array($category)){
2063       $category = array($category);
2064     }
2066     /* Check permissions for each category, if there is at least one category which 
2067         support read or paste permissions for the given base, then display the specific actions.
2068      */
2069     $readable = $pasteable = TRUE;
2070     foreach($category as $cat){
2071       $readable |= $ui->get_category_permissions($base,$cat);
2072       $pasteable|= $ui->is_pasteable($base,$cat);
2073     }
2074   
2075     if(($cut || $copy) && isset($this->CopyPasteHandler) && is_object($this->CopyPasteHandler)){
2076       if($readable){
2077         $s.= "..|---|\n";
2078         if($copy){
2079           $s.= "..|<img src='images/lists/copy.png' alt='' border='0' class='center'>".
2080             "&nbsp;"._("Copy")."|"."multiple_copy_systems|\n";
2081         }
2082         if($cut){
2083           $s.= "..|<img src='images/lists/cut.png' alt='' border='0' class='center'>".
2084             "&nbsp;"._("Cut")."|"."multiple_cut_systems|\n";
2085         }
2086       }
2088       if($pasteable){
2089         if($this->CopyPasteHandler->entries_queued()){
2090           $img = "<img border='0' class='center' src='images/lists/paste.png' alt=''>";
2091           $s.="..|".$img."&nbsp;"._("Paste")."|editPaste|\n";
2092         }else{
2093           $img = "<img border='0' class='center' src='images/lists/paste-grey.png' alt=''>";
2094           $s.="..|".$img."&nbsp;"._("Paste")."\n";
2095         }
2096       }
2097     }
2098     return($s);
2099   }
2102   function get_used_snapshot_bases()
2103   {
2104      return(array());
2105   }
2107   function is_modal_dialog()
2108   {
2109     return(isset($this->dialog) && $this->dialog);
2110   }
2112 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2113 ?>