Code

Detect type of LDAP server (Sun LDAP and OpenLDAP for now) on login
[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     if ($this->config->comma_escape_style == "comma" ||
961         $this->config->comma_escape_style == "unknown") {
962       $src_dn=LDAP::fix($src_dn);
963     } else {
964       $src_dn=str_replace('\\,', '\\2C', LDAP::fix($src_dn));
965     }
966     foreach($ogroups as $ogroup){
967       if(isset($ogroup['member'])){
969         /* Reset class object, this will be initialized with class_ogroup on demand 
970          */
971         $o_ogroup = NULL; 
972         for($i = 0 ; $i < $ogroup['member']['count'] ; $i ++){
974           $c_mem = $ogroup['member'][$i];
975   
976           if(preg_match("/".preg_quote($src_dn, '/')."$/i",$c_mem)){
977  
978             $d_mem = preg_replace("/".preg_quote($src_dn, '/')."$/i",$dst_dn,$ogroup['member'][$i]);
980             if($o_ogroup == NULL){
981               $o_ogroup = new ogroup($this->config,$ogroup['dn']);
982             }              
984             /* Members are stored with their converted names, so convert $c_mem as well
985                to have it match in case of special characters in its name. */
986             unset($o_ogroup->member[LDAP::convert($c_mem)]);
987             $o_ogroup->member[$d_mem]= $d_mem;
988           }
989         }
990        
991         /* Save object group if there were changes made on the membership */ 
992         if($o_ogroup != NULL){
993           $o_ogroup->save();
994         }
995       }
996     }
997  
998     /* Check if there are gosa departments moved. 
999        If there were deps moved, the force reload of config->deps.
1000      */
1001     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
1002           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
1003   
1004     if(count($leaf_deps)){
1005       $this->config->get_departments();
1006       $this->config->make_idepartments();
1007       session::global_set("config",$this->config);
1008       $ui =get_userinfo();
1009       $ui->reset_acl_cache();
1010     }
1012     return(TRUE); 
1013   }
1016  
1017   function move($src_dn, $dst_dn)
1018   {
1019     /* Do not copy if only upper- lowercase has changed */
1020     if(strtolower($src_dn) == strtolower($dst_dn)){
1021       return(TRUE);
1022     }
1024     
1025     /* Try to move the entry instead of copy & delete
1026      */
1027     if(TRUE){
1029       /* Try to move with ldap routines, if this was not successfull
1030           fall back to the old style copy & remove method 
1031        */
1032       if($this->rename($src_dn, $dst_dn)){
1033         return(TRUE);
1034       }else{
1035         // See code below.
1036       }
1037     }
1039     /* Copy source to destination */
1040     if (!$this->copy($src_dn, $dst_dn)){
1041       return (FALSE);
1042     }
1044     /* Delete source */
1045     $ldap= $this->config->get_ldap_link();
1046     $ldap->rmdir_recursive($src_dn);
1047     if (!$ldap->success()){
1048       trigger_error("Trying to delete $src_dn failed.",
1049           E_USER_WARNING);
1050       return (FALSE);
1051     }
1053     return (TRUE);
1054   }
1057   /* \brief Move/Rename complete trees */
1058   function recursive_move($src_dn, $dst_dn)
1059   {
1060     /* Check if the destination entry exists */
1061     $ldap= $this->config->get_ldap_link();
1063     /* Check if destination exists - abort */
1064     $ldap->cat($dst_dn, array('dn'));
1065     if ($ldap->fetch()){
1066       trigger_error("recursive_move $dst_dn already exists.",
1067           E_USER_WARNING);
1068       return (FALSE);
1069     }
1071     $this->copy($src_dn, $dst_dn);
1073     /* Remove src_dn */
1074     $ldap->cd($src_dn);
1075     $ldap->recursive_remove($src_dn);
1076     return (TRUE);
1077   }
1080   function handle_post_events($mode, $add_attrs= array())
1081   {
1082     switch ($mode){
1083       case "add":
1084         $this->postcreate($add_attrs);
1085       break;
1087       case "modify":
1088         $this->postmodify($add_attrs);
1089       break;
1091       case "remove":
1092         $this->postremove($add_attrs);
1093       break;
1094     }
1095   }
1098   function saveCopyDialog(){
1099   }
1102   function getCopyDialog(){
1103     return(array("string"=>"","status"=>""));
1104   }
1107   /*! \brief Prepare for Copy & Paste */
1108   function PrepareForCopyPaste($source)
1109   {
1110     $todo = $this->attributes;
1111     if(isset($this->CopyPasteVars)){
1112       $todo = array_merge($todo,$this->CopyPasteVars);
1113     }
1115     if(count($this->objectclasses)){
1116       $this->is_account = TRUE;
1117       foreach($this->objectclasses as $class){
1118         if(!in_array($class,$source['objectClass'])){
1119           $this->is_account = FALSE;
1120         }
1121       }
1122     }
1124     foreach($todo as $var){
1125       if (isset($source[$var])){
1126         if(isset($source[$var]['count'])){
1127           if($source[$var]['count'] > 1){
1128             $this->$var = array();
1129             $tmp = array();
1130             for($i = 0 ; $i < $source[$var]['count']; $i++){
1131               $tmp = $source[$var][$i];
1132             }
1133             $this->$var = $tmp;
1134           }else{
1135             $this->$var = $source[$var][0];
1136           }
1137         }else{
1138           $this->$var= $source[$var];
1139         }
1140       }
1141     }
1142   }
1144   /*! \brief Get gosaUnitTag for the given DN */
1145   function get_gosaUnitTag($dn = "")
1146   {
1147     if ($dn == "") {
1148         $dn = $this->dn;
1149     }
1151     $len = strlen($dn);
1152     @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1153      $relevant= array();
1154         foreach ($this->config->adepartments as $key => $ntag){
1156           /* This one is bigger than our dn, its not relevant... */
1157           if ($len < strlen($key)){
1158             continue;
1159           }
1161           /* This one matches with the latter part. Break and don't fix this entry */
1162           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
1163             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1164             $relevant[strlen($key)]= $ntag;
1165             continue;
1166           }
1168         }
1170         /* If we've some relevant tags to set, just get the longest one */
1171         if (count($relevant)){
1172           ksort($relevant);
1173           $tmp= array_keys($relevant);
1174           $idx= end($tmp);
1175           $tag= $relevant[$idx];
1176           return $tag;
1177         }
1179   }
1181   /*! \brief Add unit tag */ 
1182   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1183   {
1184     /* Skip tagging? 
1185        If this is called from departmentGeneric, we have to skip this
1186         tagging procedure. 
1187      */
1188     if($this->skipTagging){
1189       return;
1190     }
1192     /* No dn? Self-operation... */
1193     if ($dn == ""){
1194       $dn= $this->dn;
1196       /* No tag? Find it yourself... */
1197       if ($tag == ""){
1198           $tag = $this->get_gosaUnitTag();
1199       }
1200     }
1201   
1202     /* Remove tags that may already be here... */
1203     remove_objectClass("gosaAdministrativeUnitTag", $at);
1204     if (isset($at['gosaUnitTag'])){
1205         unset($at['gosaUnitTag']);
1206     }
1208     /* Set tag? */
1209     if ($tag != ""){
1210       add_objectClass("gosaAdministrativeUnitTag", $at);
1211       $at['gosaUnitTag']= $tag;
1212     }
1214     /* Initially this object was tagged. 
1215        - But now, it is no longer inside a tagged department. 
1216        So force the remove of the tag.
1217        (objectClass was already removed obove)
1218      */
1219     if($tag == "" && $this->gosaUnitTag){
1220       $at['gosaUnitTag'] = array();
1221     }
1222   }
1225   /*! \brief Test for removability of the object
1226    *
1227    * Allows testing of conditions for removal of object. If removal should be aborted
1228    * the function needs to remove an error message.
1229    * */
1230   function allow_remove()
1231   {
1232     $reason= "";
1233     return $reason;
1234   }
1237   /*! \brief Create a snapshot of the current object */
1238   function create_snapshot($type= "snapshot", $description= array())
1239   {
1241     /* Check if snapshot functionality is enabled */
1242     if(!$this->snapshotEnabled()){
1243       return;
1244     }
1246     /* Get configuration from gosa.conf */
1247     $config = $this->config;
1249     /* Create lokal ldap connection */
1250     $ldap= $this->config->get_ldap_link();
1251     $ldap->cd($this->config->current['BASE']);
1253     /* check if there are special server configurations for snapshots */
1254     if($config->get_cfg_value("snapshotURI") == ""){
1256       /* Source and destination server are both the same, just copy source to dest obj */
1257       $ldap_to      = $ldap;
1258       $snapldapbase = $this->config->current['BASE'];
1260     }else{
1261       $server         = $config->get_cfg_value("snapshotURI");
1262       $user           = $config->get_cfg_value("snapshotAdminDn");
1263       $password       = $config->get_cfg_value("snapshotAdminPassword");
1264       $snapldapbase   = $config->get_cfg_value("snapshotBase");
1266       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1267       $ldap_to -> cd($snapldapbase);
1269       if (!$ldap_to->success()){
1270         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1271       }
1273     }
1275     /* check if the dn exists */ 
1276     if ($ldap->dn_exists($this->dn)){
1278       /* Extract seconds & mysecs, they are used as entry index */
1279       list($usec, $sec)= explode(" ", microtime());
1281       /* Collect some infos */
1282       $base           = $this->config->current['BASE'];
1283       $snap_base      = $config->get_cfg_value("snapshotBase");
1284       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1285       $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1287       /* Create object */
1288 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1289       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1290       $newName          = str_replace(".", "", $sec."-".$usec);
1291       $target= array();
1292       $target['objectClass']            = array("top", "gosaSnapshotObject");
1293       $target['gosaSnapshotData']       = gzcompress($data, 6);
1294       $target['gosaSnapshotType']       = $type;
1295       $target['gosaSnapshotDN']         = $this->dn;
1296       $target['description']            = $description;
1297       $target['gosaSnapshotTimestamp']  = $newName;
1299       /* Insert the new snapshot 
1300          But we have to check first, if the given gosaSnapshotTimestamp
1301          is already used, in this case we should increment this value till there is 
1302          an unused value. */ 
1303       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1304       $ldap_to->cat($new_dn);
1305       while($ldap_to->count()){
1306         $ldap_to->cat($new_dn);
1307         $newName = str_replace(".", "", $sec."-".($usec++));
1308         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1309         $target['gosaSnapshotTimestamp']  = $newName;
1310       } 
1312       /* Inset this new snapshot */
1313       $ldap_to->cd($snapldapbase);
1314       $ldap_to->create_missing_trees($snapldapbase);
1315       $ldap_to->create_missing_trees($new_base);
1316       $ldap_to->cd($new_dn);
1317       $ldap_to->add($target);
1318       if (!$ldap_to->success()){
1319         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $new_dn, LDAP_ADD, get_class()));
1320       }
1322       if (!$ldap->success()){
1323         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $new_base, "", get_class()));
1324       }
1326     }
1327   }
1329   /*! \brief Remove a snapshot */
1330   function remove_snapshot($dn)
1331   {
1332     $ui       = get_userinfo();
1333     $old_dn   = $this->dn; 
1334     $this->dn = $dn;
1335     $ldap = $this->config->get_ldap_link();
1336     $ldap->cd($this->config->current['BASE']);
1337     $ldap->rmdir_recursive($this->dn);
1338     if(!$ldap->success()){
1339       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn));
1340     }
1341     $this->dn = $old_dn;
1342   }
1345   /*! \brief Test if snapshotting is enabled
1346    *
1347    * Test weither snapshotting is enabled or not. There will also be some errors posted,
1348    * if the configuration failed 
1349    * \return TRUE if snapshots are enabled, and FALSE if it is disabled
1350    */
1351   function snapshotEnabled()
1352   {
1353     $config = $this->config;
1354     if($config->get_cfg_value("enableSnapshots") == "true"){
1355             /* Check if the snapshot_base is defined */
1356             if ($config->get_cfg_value("snapshotBase") == ""){
1357                     msg_dialog::display(_("Configuration error"), sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."),"snapshotBase"), ERROR_DIALOG);
1358                     return(FALSE);
1359             }
1361             /* check if there are special server configurations for snapshots */
1362             if ($config->get_cfg_value("snapshotURI") != ""){
1364                     /* check if all required vars are available to create a new ldap connection */
1365                     $missing = "";
1366                     foreach(array("snapshotURI","snapshotAdminDn","snapshotAdminPassword","snapshotBase") as $var){
1367                             if($config->get_cfg_value($var) == ""){
1368                                     $missing .= $var." ";
1369                                     msg_dialog::display(_("Configuration error"), sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."), $missing), ERROR_DIALOG);
1370                                     return(FALSE);
1371                             }
1372                     }
1373             }
1374             return(TRUE);
1375     }
1376     return(FALSE);
1377   }
1380   /* \brief Return available snapshots for the given base */
1381   function Available_SnapsShots($dn,$raw = false)
1382   {
1383     if(!$this->snapshotEnabled()) return(array());
1385     /* Create an additional ldap object which
1386        points to our ldap snapshot server */
1387     $ldap= $this->config->get_ldap_link();
1388     $ldap->cd($this->config->current['BASE']);
1389     $cfg= &$this->config->current;
1391     /* check if there are special server configurations for snapshots */
1392     if($this->config->get_cfg_value("snapshotURI") == ""){
1393       $ldap_to      = $ldap;
1394     }else{
1395       $server         = $this->config->get_cfg_value("snapshotURI");
1396       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1397       $password       = $this->config->get_cfg_value("snapshotAdminPassword");
1398       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1399       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1400       $ldap_to -> cd($snapldapbase);
1401       if (!$ldap_to->success()){
1402         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1403       }
1404     }
1406     /* Prepare bases and some other infos */
1407     $base           = $this->config->current['BASE'];
1408     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1409     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1410     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1411     $tmp            = array(); 
1413     /* Fetch all objects with  gosaSnapshotDN=$dn */
1414     $ldap_to->cd($new_base);
1415     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1416         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1418     /* Put results into a list and add description if missing */
1419     while($entry = $ldap_to->fetch()){ 
1420       if(!isset($entry['description'][0])){
1421         $entry['description'][0]  = "";
1422       }
1423       $tmp[] = $entry; 
1424     }
1426     /* Return the raw array, or format the result */
1427     if($raw){
1428       return($tmp);
1429     }else{  
1430       $tmp2 = array();
1431       foreach($tmp as $entry){
1432         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1433       }
1434     }
1435     return($tmp2);
1436   }
1439   function getAllDeletedSnapshots($base_of_object,$raw = false)
1440   {
1441     if(!$this->snapshotEnabled()) return(array());
1443     /* Create an additional ldap object which
1444        points to our ldap snapshot server */
1445     $ldap= $this->config->get_ldap_link();
1446     $ldap->cd($this->config->current['BASE']);
1447     $cfg= &$this->config->current;
1449     /* check if there are special server configurations for snapshots */
1450     if($this->config->get_cfg_value("snapshotURI") == ""){
1451       $ldap_to      = $ldap;
1452     }else{
1453       $server         = $this->config->get_cfg_value("snapshotURI");
1454       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1455       $password       = $this->config->get_cfg_value("snapshotAdminPassword");
1456       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1457       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1458       $ldap_to -> cd($snapldapbase);
1459       if (!$ldap_to->success()){
1460         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1461       }
1462     }
1464     /* Prepare bases */ 
1465     $base           = $this->config->current['BASE'];
1466     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1467     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1469     /* Fetch all objects and check if they do not exist anymore */
1470     $ui = get_userinfo();
1471     $tmp = array();
1472     $ldap_to->cd($new_base);
1473     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1474     while($entry = $ldap_to->fetch()){
1476       $chk =  str_replace($new_base,"",$entry['dn']);
1477       if(preg_match("/,ou=/",$chk)) continue;
1479       if(!isset($entry['description'][0])){
1480         $entry['description'][0]  = "";
1481       }
1482       $tmp[] = $entry; 
1483     }
1485     /* Check if entry still exists */
1486     foreach($tmp as $key => $entry){
1487       $ldap->cat($entry['gosaSnapshotDN'][0]);
1488       if($ldap->count()){
1489         unset($tmp[$key]);
1490       }
1491     }
1493     /* Format result as requested */
1494     if($raw) {
1495       return($tmp);
1496     }else{
1497       $tmp2 = array();
1498       foreach($tmp as $key => $entry){
1499         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1500       }
1501     }
1502     return($tmp2);
1503   } 
1506   /* \brief Restore selected snapshot */
1507   function restore_snapshot($dn)
1508   {
1509     if(!$this->snapshotEnabled()) return(array());
1511     $ldap= $this->config->get_ldap_link();
1512     $ldap->cd($this->config->current['BASE']);
1513     $cfg= &$this->config->current;
1515     /* check if there are special server configurations for snapshots */
1516     if($this->config->get_cfg_value("snapshotURI") == ""){
1517       $ldap_to      = $ldap;
1518     }else{
1519       $server         = $this->config->get_cfg_value("snapshotURI");
1520       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1521       $password       = $this->config->get_cfg_value("snapshotAdminPassword");
1522       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1523       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1524       $ldap_to -> cd($snapldapbase);
1525       if (!$ldap_to->success()){
1526         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1527       }
1528     }
1530     /* Get the snapshot */ 
1531     $ldap_to->cat($dn);
1532     $restoreObject = $ldap_to->fetch();
1534     /* Prepare import string */
1535     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1537     /* Import the given data */
1538     $err = "";
1539     $ldap->import_complete_ldif($data,$err,false,false);
1540     if (!$ldap->success()){
1541       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, "", get_class()));
1542     }
1543   }
1546   function showSnapshotDialog($base,$baseSuffixe,&$parent)
1547   {
1548     $once = true;
1549     $ui = get_userinfo();
1550     $this->parent = $parent;
1552     foreach($_POST as $name => $value){
1554       /* Create a new snapshot, display a dialog */
1555       if(preg_match("/^CreateSnapShotDialog_[^_]*_[xy]$/",$name) && $once){
1557                           $entry = base64_decode(preg_replace("/^CreateSnapShotDialog_([^_]*)_[xy]$/","\\1",$name));
1558         $once = false;
1559         $entry = preg_replace("/^CreateSnapShotDialog_/","",$entry);
1561         if(!empty($entry) && $ui->allow_snapshot_create($entry,$this->parent->acl_module)){
1562           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1563         }else{
1564           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to create a snapshot for %s."),$entry),ERROR_DIALOG);
1565         }
1566       }  
1567   
1568       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1569       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1570         $once = false;
1571         $entry = base64_decode(preg_replace("/^RestoreSnapShotDialog_([^_]*)_[xy]$/i","\\1",$name));
1572         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1573           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1574           $this->snapDialog->display_restore_dialog = true;
1575         }else{
1576           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1577         }
1578       }
1580       /* Restore one of the already deleted objects */
1581       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1582           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1583         $once = false;
1585         if($ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1586           $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1587           $this->snapDialog->set_snapshot_bases($baseSuffixe);
1588           $this->snapDialog->display_restore_dialog      = true;
1589           $this->snapDialog->display_all_removed_objects  = true;
1590         }else{
1591           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$base),ERROR_DIALOG);
1592         }
1593       }
1595       /* Restore selected snapshot */
1596       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1597         $once = false;
1598         $entry = base64_decode(preg_replace("/^RestoreSnapShot_([^_]*)_[xy]$/i","\\1",$name));
1600         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1601           $this->restore_snapshot($entry);
1602           $this->snapDialog = NULL;
1603         }else{
1604           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1605         }
1606       }
1607     }
1609     /* Create a new snapshot requested, check
1610        the given attributes and create the snapshot*/
1611     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1612       $this->snapDialog->save_object();
1613       $msgs = $this->snapDialog->check();
1614       if(count($msgs)){
1615         foreach($msgs as $msg){
1616           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
1617         }
1618       }else{
1619         $this->dn =  $this->snapDialog->dn;
1620         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1621         $this->snapDialog = NULL;
1622       }
1623     }
1625     /* Restore is requested, restore the object with the posted dn .*/
1626     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1627     }
1629     if(isset($_POST['CancelSnapshot'])){
1630       $this->snapDialog = NULL;
1631     }
1633     if(is_object($this->snapDialog )){
1634       $this->snapDialog->save_object();
1635       return($this->snapDialog->execute());
1636     }
1637   }
1640   /*! \brief Return plugin informations for acl handling */
1641   static function plInfo()
1642   {
1643     return array();
1644   }
1647   function set_acl_base($base)
1648   {
1649     $this->acl_base= $base;
1650   }
1653   function set_acl_category($category)
1654   {
1655     $this->acl_category= "$category/";
1656   }
1659   function acl_is_writeable($attribute,$skip_write = FALSE)
1660   {
1661     if($this->read_only) return(FALSE);
1662     $ui= get_userinfo();
1663     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1664   }
1667   function acl_is_readable($attribute)
1668   {
1669     $ui= get_userinfo();
1670     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1671   }
1674   function acl_is_createable($base ="")
1675   {
1676     if($this->read_only) return(FALSE);
1677     $ui= get_userinfo();
1678     if($base == "") $base = $this->acl_base;
1679     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1680   }
1683   function acl_is_removeable($base ="")
1684   {
1685     if($this->read_only) return(FALSE);
1686     $ui= get_userinfo();
1687     if($base == "") $base = $this->acl_base;
1688     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1689   }
1692   function acl_is_moveable($base = "")
1693   {
1694     if($this->read_only) return(FALSE);
1695     $ui= get_userinfo();
1696     if($base == "") $base = $this->acl_base;
1697     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1698   }
1701   function acl_have_any_permissions()
1702   {
1703   }
1706   function getacl($attribute,$skip_write= FALSE)
1707   {
1708     $ui= get_userinfo();
1709     $skip_write |= $this->read_only;
1710     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1711   }
1714   /*! \brief Returns a list of all available departments for this object.
1715    * 
1716    * If this object is new, all departments we are allowed to create a new user in
1717    * are returned. If this is an existing object, return all deps. 
1718    * We are allowed to move tis object too.
1719    * \return array [dn] => "..name"  // All deps. we are allowed to act on.
1720   */
1721   function get_allowed_bases()
1722   {
1723     $ui = get_userinfo();
1724     $deps = array();
1726     /* Is this a new object ? Or just an edited existing object */
1727     if(!$this->initially_was_account && $this->is_account){
1728       $new = true;
1729     }else{
1730       $new = false;
1731     }
1733     foreach($this->config->idepartments as $dn => $name){
1734       if($new && $this->acl_is_createable($dn)){
1735         $deps[$dn] = $name;
1736       }elseif(!$new && $this->acl_is_moveable($dn)){
1737         $deps[$dn] = $name;
1738       }
1739     }
1741     /* Add current base */      
1742     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1743       $deps[$this->base] = $this->config->idepartments[$this->base];
1744     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1746     }else{
1747       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1748     }
1749     return($deps);
1750   }
1753   /* This function updates ACL settings if $old_dn was used.
1754    *  \param string 'old_dn' specifies the actually used dn
1755    *  \param string 'new_dn' specifies the destiantion dn
1756    */
1757   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1758   {
1759     /* Check if old_dn is empty. This should never happen */
1760     if(empty($old_dn) || empty($new_dn)){
1761       trigger_error("Failed to check acl dependencies, wrong dn given.");
1762       return;
1763     }
1765     /* Update userinfo if necessary */
1766     $ui = session::global_get('ui');
1767     if($ui->dn == $old_dn){
1768       $ui->dn = $new_dn;
1769       session::global_set('ui',$ui);
1770       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1771     }
1773     /* Object was moved, ensure that all acls will be moved too */
1774     if($new_dn != $old_dn && $old_dn != "new"){
1776       /* get_ldap configuration */
1777       $update = array();
1778       $ldap = $this->config->get_ldap_link();
1779       $ldap->cd ($this->config->current['BASE']);
1780       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1781       while($attrs = $ldap->fetch()){
1782         $acls = array();
1783         $found = false;
1784         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1785           $acl_parts = split(":",$attrs['gosaAclEntry'][$i]);
1787           /* Roles uses antoher data storage order, members are stored int the third part, 
1788              while the members in direct ACL assignments are stored in the second part.
1789            */
1790           $id = ($acl_parts[1] == "role") ? 3 : 2;
1792           /* Update member entries to use $new_dn instead of old_dn
1793            */
1794           $members = explode(",",$acl_parts[$id]);
1795           foreach($members as $key => $member){
1796             $member = base64_decode($member);
1797             if($member == $old_dn){
1798               $members[$key] = base64_encode($new_dn);
1799               $found = TRUE;
1800             }
1801           } 
1803           /* Check if the selected role has to updated
1804            */
1805           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1806             $acl_parts[2] = base64_encode($new_dn);
1807             $found = TRUE;
1808           }
1810           /* Build new acl string */ 
1811           $acl_parts[$id] = implode($members,",");
1812           $acls[] = implode($acl_parts,":");
1813         }
1815         /* Acls for this object must be adjusted */
1816         if($found){
1818           $debug_info=  _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1819             $old_dn."</b><br>&nbsp;-"._("to")."&nbsp;<b>".$new_dn."</b><br>";
1820           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1822           $update[$attrs['dn']] =array();
1823           foreach($acls as $acl){
1824             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1825           }
1826         }
1827       }
1829       /* Write updated acls */
1830       foreach($update as $dn => $attrs){
1831         $ldap->cd($dn);
1832         $ldap->modify($attrs);
1833       }
1834     }
1835   }
1837   
1839   /*! \brief Enable the Serial ID check
1840    *
1841    * This function enables the entry Serial ID check.  If an entry was edited while
1842    * we have edited the entry too, an error message will be shown. 
1843    * To configure this check correctly read the FAQ.
1844    */    
1845   function enable_CSN_check()
1846   {
1847     $this->CSN_check_active =TRUE;
1848     $this->entryCSN = getEntryCSN($this->dn);
1849   }
1852   /*! \brief  Prepares the plugin to be used for multiple edit
1853    *          Update plugin attributes with given array of attribtues.
1854    *  \param  array   Array with attributes that must be updated.
1855    */
1856   function init_multiple_support($attrs,$all)
1857   {
1858     $ldap= $this->config->get_ldap_link();
1859     $this->multi_attrs    = $attrs;
1860     $this->multi_attrs_all= $all;
1862     /* Copy needed attributes */
1863     foreach ($this->attributes as $val){
1864       $found= array_key_ics($val, $this->multi_attrs);
1865       if ($found != ""){
1866         if(isset($this->multi_attrs["$found"][0])){
1867           $this->$val= $this->multi_attrs["$found"][0];
1868         }
1869       }
1870     }
1871   }
1873  
1874   /*! \brief  Enables multiple support for this plugin
1875    */
1876   function enable_multiple_support()
1877   {
1878     $this->ignore_account = TRUE;
1879     $this->multiple_support_active = TRUE;
1880   }
1883   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1884       \return array Cotaining all modified values. 
1885    */
1886   function get_multi_edit_values()
1887   {
1888     $ret = array();
1889     foreach($this->attributes as $attr){
1890       if(in_array($attr,$this->multi_boxes)){
1891         $ret[$attr] = $this->$attr;
1892       }
1893     }
1894     return($ret);
1895   }
1897   
1898   /*! \brief  Update class variables with values collected by multiple edit.
1899    */
1900   function set_multi_edit_values($attrs)
1901   {
1902     foreach($attrs as $name => $value){
1903       $this->$name = $value;
1904     }
1905   }
1908   /*! \brief Generates the html output for this node for multi edit*/
1909   function multiple_execute()
1910   {
1911     /* This one is empty currently. Fabian - please fill in the docu code */
1912     session::global_set('current_class_for_help',get_class($this));
1914     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1915     session::set('LOCK_VARS_TO_USE',array());
1916     session::set('LOCK_VARS_USED',array());
1917     
1918     return("Multiple edit is currently not implemented for this plugin.");
1919   }
1922   /*! \brief Save HTML posted data to object for multiple edit
1923    */
1924   function multiple_save_object()
1925   {
1926     if(empty($this->entryCSN) && $this->CSN_check_active){
1927       $this->entryCSN = getEntryCSN($this->dn);
1928     }
1930     /* Save values to object */
1931     $this->multi_boxes = array();
1932     foreach ($this->attributes as $val){
1933   
1934       /* Get selected checkboxes from multiple edit */
1935       if(isset($_POST["use_".$val])){
1936         $this->multi_boxes[] = $val;
1937       }
1939       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
1941         /* Check for modifications */
1942         if (get_magic_quotes_gpc()) {
1943           $data= stripcslashes($_POST["$val"]);
1944         } else {
1945           $data= $this->$val = $_POST["$val"];
1946         }
1947         if ($this->$val != $data){
1948           $this->is_modified= TRUE;
1949         }
1950     
1951         /* IE post fix */
1952         if(isset($data[0]) && $data[0] == chr(194)) {
1953           $data = "";  
1954         }
1955         $this->$val= $data;
1956       }
1957     }
1958   }
1961   /*! \brief Returns all attributes of this plugin, 
1962                to be able to detect multiple used attributes 
1963                in multi_plugg::detect_multiple_used_attributes().
1964       @return array Attributes required for intialization of multi_plug
1965    */
1966   public function get_multi_init_values()
1967   {
1968     $attrs = $this->attrs;
1969     return($attrs);
1970   }
1973   /*! \brief  Check given values in multiple edit
1974       \return array Error messages
1975    */
1976   function multiple_check()
1977   {
1978     $message = plugin::check();
1979     return($message);
1980   }
1983   /*! \brief  Returns the snapshot header part for "Actions" menu in management dialogs 
1984       \param  $layer_menu  
1985    */   
1986   function get_snapshot_header($base,$category)
1987   {
1988     $str = "";
1989     $ui = get_userinfo();
1990     if($this->snapshotEnabled() && $ui->allow_snapshot_restore($base,$category)){
1992       $ok = false;
1993       foreach($this->get_used_snapshot_bases() as $base){
1994         $ok |= count($this->getAllDeletedSnapshots($base)) >= 1 ;
1995       }
1997       if($ok){
1998         $str = "..|<img class='center' src='images/lists/restore.png' ".
1999           "alt='"._("Restore")."'>&nbsp;"._("Restore").                       "|RestoreDeletedSnapShot|\n";
2000       }else{
2001         $str = "..|<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;"._("Restore")."||\n";
2002       }
2003     }
2004     return($str);
2005   }
2008   function get_snapshot_action($base,$category)
2009   {
2010     $str= ""; 
2011     $ui = get_userinfo();
2012     if($this->snapshotEnabled()){
2013       if ($ui->allow_snapshot_restore($base,$category)){
2015         if(count($this->Available_SnapsShots($base))){
2016           $str.= "<input class='center' type='image' src='images/lists/restore.png'
2017             alt='"._("Restore snapshot")."' name='RestoreSnapShotDialog_".base64_encode($base)."' title='"._("Restore snapshot")."'>&nbsp;";
2018         } else {
2019           $str = "<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;";
2020         }
2021       }
2022       if($ui->allow_snapshot_create($base,$category)){
2023         $str.= "<input class='center' type='image' src='images/snapshot.png'
2024           alt='"._("Create snapshot")."' name='CreateSnapShotDialog_".base64_encode($base)."' 
2025           title='"._("Create a new snapshot from this object")."'>&nbsp;";
2026       }else{
2027         $str = "<img class='center' src='images/empty.png' alt=' '>&nbsp;";
2028       }
2029     }
2031     return($str);
2032   }
2035   function get_copypaste_action($base,$category,$class,$copy = TRUE, $cut = TRUE)
2036   {
2037     $ui = get_userinfo();
2038     $action = "";
2039     if($this->CopyPasteHandler){
2040       if($cut){
2041         if($ui->is_cutable($base,$category,$class)){
2042           $action .= "<input class='center' type='image'
2043             src='images/lists/cut.png' alt='"._("cut")."' name='cut_%KEY%' title='"._("Cut this entry")."'>&nbsp;";
2044         }else{
2045           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
2046         }
2047       }
2048       if($copy){
2049         if($ui->is_copyable($base,$category,$class)){
2050           $action.= "<input class='center' type='image'
2051             src='images/lists/copy.png' alt='"._("copy")."' name='copy_%KEY%' title='"._("Copy this entry")."'>&nbsp;";
2052         }else{
2053           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
2054         }
2055       }
2056     }
2058     return($action); 
2059   }
2062   function get_copypaste_header($base,$category,$copy = TRUE, $cut = TRUE)
2063   {
2064     $s = "";
2065     $ui =get_userinfo();
2067     if(!is_array($category)){
2068       $category = array($category);
2069     }
2071     /* Check permissions for each category, if there is at least one category which 
2072         support read or paste permissions for the given base, then display the specific actions.
2073      */
2074     $readable = $pasteable = TRUE;
2075     foreach($category as $cat){
2076       $readable |= $ui->get_category_permissions($base,$cat);
2077       $pasteable|= $ui->is_pasteable($base,$cat);
2078     }
2079   
2080     if(($cut || $copy) && isset($this->CopyPasteHandler) && is_object($this->CopyPasteHandler)){
2081       if($readable){
2082         $s.= "..|---|\n";
2083         if($copy){
2084           $s.= "..|<img src='images/lists/copy.png' alt='' border='0' class='center'>".
2085             "&nbsp;"._("Copy")."|"."multiple_copy_systems|\n";
2086         }
2087         if($cut){
2088           $s.= "..|<img src='images/lists/cut.png' alt='' border='0' class='center'>".
2089             "&nbsp;"._("Cut")."|"."multiple_cut_systems|\n";
2090         }
2091       }
2093       if($pasteable){
2094         if($this->CopyPasteHandler->entries_queued()){
2095           $img = "<img border='0' class='center' src='images/lists/paste.png' alt=''>";
2096           $s.="..|".$img."&nbsp;"._("Paste")."|editPaste|\n";
2097         }else{
2098           $img = "<img border='0' class='center' src='images/lists/paste-grey.png' alt=''>";
2099           $s.="..|".$img."&nbsp;"._("Paste")."\n";
2100         }
2101       }
2102     }
2103     return($s);
2104   }
2107   function get_used_snapshot_bases()
2108   {
2109      return(array());
2110   }
2112   function is_modal_dialog()
2113   {
2114     return(isset($this->dialog) && $this->dialog);
2115   }
2117 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2118 ?>