Code

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