Code

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