Code

-Little performance improvement. class_userinfo.inc get_module_departments
[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= "";
117   /* This can be set to render the tabulators in another stylesheet */
118   var $pl_notify= FALSE;
120   /* Object entry CSN */
121   var $entryCSN         = "";
122   var $CSN_check_active = FALSE;
124   /* This variable indicates that this class can handle multiple dns at once. */
125   var $multiple_support = FALSE;
126   var $multi_attrs      = array();
127   var $multi_attrs_all  = array(); 
129   /* This aviable indicates, that we are currently in multiple edit handle */
130   var $multiple_support_active = FALSE; 
131   var $selected_edit_values = array();
132   var $multi_boxes = array();
134   /*! \brief plugin constructor
136     If 'dn' is set, the node loads the given 'dn' from LDAP
138     \param dn Distinguished name to initialize plugin from
139     \sa plugin()
140    */
141   function plugin (&$config, $dn= NULL, $parent= NULL)
142   {
143     /* Configuration is fine, allways */
144     $this->config= &$config;    
145     $this->dn= $dn;
147     /* Handle new accounts, don't read information from LDAP */
148     if ($dn == "new"){
149       return;
150     }
152     /* Save current dn as acl_base */
153     $this->acl_base= $dn;
155     /* Get LDAP descriptor */
156     if ($dn !== NULL){
158       /* Load data to 'attrs' and save 'dn' */
159       if ($parent !== NULL){
160         $this->attrs= $parent->attrs;
161       } else {
162         $ldap= $this->config->get_ldap_link();
163         $ldap->cat ($dn);
164         $this->attrs= $ldap->fetch();
165       }
167       /* Copy needed attributes */
168       foreach ($this->attributes as $val){
169         $found= array_key_ics($val, $this->attrs);
170         if ($found != ""){
171           $this->$val= $found[0];
172         }
173       }
175       /* gosaUnitTag loading... */
176       if (isset($this->attrs['gosaUnitTag'][0])){
177         $this->gosaUnitTag= $this->attrs['gosaUnitTag'][0];
178       }
180       /* Set the template flag according to the existence of objectClass
181          gosaUserTemplate */
182       if (isset($this->attrs['objectClass'])){
183         if (in_array_ics ("gosaUserTemplate", $this->attrs['objectClass'])){
184           $this->is_template= TRUE;
185           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
186               "found", "Template check");
187         }
188       }
190       /* Is Account? */
191       $found= TRUE;
192       foreach ($this->objectclasses as $obj){
193         if (preg_match('/top/i', $obj)){
194           continue;
195         }
196         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
197           $found= FALSE;
198           break;
199         }
200       }
201       if ($found){
202         $this->is_account= TRUE;
203         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
204             "found", "Object check");
205       }
207       /* Prepare saved attributes */
208       $this->saved_attributes= $this->attrs;
209       foreach ($this->saved_attributes as $index => $value){
210         if (is_numeric($index)){
211           unset($this->saved_attributes[$index]);
212           continue;
213         }
215         if (!in_array_ics($index, $this->attributes) && strcasecmp('objectClass', $index)){
216           unset($this->saved_attributes[$index]);
217           continue;
218         }
220         if (isset($this->saved_attributes[$index][0])){
221           if(!isset($this->saved_attributes[$index]["count"])){
222             $this->saved_attributes[$index]["count"] = count($this->saved_attributes[$index]);
223           }
224           if($this->saved_attributes[$index]["count"] == 1){
225             $tmp= $this->saved_attributes[$index][0];
226             unset($this->saved_attributes[$index]);
227             $this->saved_attributes[$index]= $tmp;
228             continue;
229           }
230         }
231         unset($this->saved_attributes["$index"]["count"]);
232       }
234       if(isset($this->attrs['gosaUnitTag'])){
235         $this->saved_attributes['gosaUnitTag'] = $this->attrs['gosaUnitTag'][0];
236       }
237     }
239     /* Save initial account state */
240     $this->initially_was_account= $this->is_account;
241   }
244   /*! \brief execute plugin
246     Generates the html output for this node
247    */
248   function execute()
249   {
250     /* This one is empty currently. Fabian - please fill in the docu code */
251     session::set('current_class_for_help',get_class($this));
253     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
254     session::set('LOCK_VARS_TO_USE',array());
255     session::set('LOCK_VARS_USED',array());
256   }
258   /*! \brief execute plugin
259      Removes object from parent
260    */
261   function remove_from_parent()
262   {
263     /* include global link_info */
264     $ldap= $this->config->get_ldap_link();
266     /* Get current objectClasses in order to add the required ones */
267     $ldap->cat($this->dn);
268     $tmp= $ldap->fetch ();
269     $oc= array();
270     if (isset($tmp['objectClass'])){
271       $oc= $tmp['objectClass'];
272       unset($oc['count']);
273     }
275     /* Remove objectClasses from entry */
276     $ldap->cd($this->dn);
277     $this->attrs= array();
278     $this->attrs['objectClass']= array_remove_entries_ics($this->objectclasses,$oc);
280     /* Unset attributes from entry */
281     foreach ($this->attributes as $val){
282       $this->attrs["$val"]= array();
283     }
285     /* Unset account info */
286     $this->is_account= FALSE;
288     /* Do not write in plugin base class, this must be done by
289        children, since there are normally additional attribs,
290        lists, etc. */
291     /*
292        $ldap->modify($this->attrs);
293      */
294   }
297   /*! \brief   Save HTML posted data to object 
298    */
299   function save_object()
300   {
301     /* Update entry CSN if it is empty. */
302     if(empty($this->entryCSN) && $this->CSN_check_active){
303       $this->entryCSN = getEntryCSN($this->dn);
304     }
306     /* Save values to object */
307     foreach ($this->attributes as $val){
308       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
309         /* Check for modifications */
310         if (get_magic_quotes_gpc()) {
311           $data= stripcslashes($_POST["$val"]);
312         } else {
313           $data= $this->$val = $_POST["$val"];
314         }
315         if ($this->$val != $data){
316           $this->is_modified= TRUE;
317         }
318     
319         /* Okay, how can I explain this fix ... 
320          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
321          * So IE posts these 'unselectable' option, with value = chr(194) 
322          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
323          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
324          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
325          */
326         if(isset($data[0]) && $data[0] == chr(194)) {
327           $data = "";  
328         }
329         $this->$val= $data;
330       }
331     }
332   }
335   /* Save data to LDAP, depending on is_account we save or delete */
336   function save()
337   {
338     /* include global link_info */
339     $ldap= $this->config->get_ldap_link();
341     /* Save all plugins */
342     $this->entryCSN = "";
344     /* Start with empty array */
345     $this->attrs= array();
347     /* Get current objectClasses in order to add the required ones */
348     $ldap->cat($this->dn);
349     
350     $tmp= $ldap->fetch ();
352     $oc= array();
353     if (isset($tmp['objectClass'])){
354       $oc= $tmp["objectClass"];
355       $this->is_new= FALSE;
356       unset($oc['count']);
357     } else {
358       $this->is_new= TRUE;
359     }
361     /* Load (minimum) attributes, add missing ones */
362     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
364     /* Copy standard attributes */
365     foreach ($this->attributes as $val){
366       if ($this->$val != ""){
367         $this->attrs["$val"]= $this->$val;
368       } elseif (!$this->is_new) {
369         $this->attrs["$val"]= array();
370       }
371     }
373     /* Handle tagging */
374     $this->tag_attrs($this->attrs);
375   }
378   function cleanup()
379   {
380     foreach ($this->attrs as $index => $value){
381       
382       /* Convert arrays with one element to non arrays, if the saved
383          attributes are no array, too */
384       if (is_array($this->attrs[$index]) && 
385           count ($this->attrs[$index]) == 1 &&
386           isset($this->saved_attributes[$index]) &&
387           !is_array($this->saved_attributes[$index])){
388           
389         $tmp= $this->attrs[$index][0];
390         $this->attrs[$index]= $tmp;
391       }
393       /* Remove emtpy arrays if they do not differ */
394       if (is_array($this->attrs[$index]) &&
395           count($this->attrs[$index]) == 0 &&
396           !isset($this->saved_attributes[$index])){
397           
398         unset ($this->attrs[$index]);
399         continue;
400       }
402       /* Remove single attributes that do not differ */
403       if (!is_array($this->attrs[$index]) &&
404           isset($this->saved_attributes[$index]) &&
405           !is_array($this->saved_attributes[$index]) &&
406           $this->attrs[$index] == $this->saved_attributes[$index]){
408         unset ($this->attrs[$index]);
409         continue;
410       }
412       /* Remove arrays that do not differ */
413       if (is_array($this->attrs[$index]) && 
414           isset($this->saved_attributes[$index]) &&
415           is_array($this->saved_attributes[$index])){
416           
417         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
418           unset ($this->attrs[$index]);
419           continue;
420         }
421       }
422     }
424     /* Update saved attributes and ensure that next cleanups will be successful too */
425     foreach($this->attrs as $name => $value){
426       $this->saved_attributes[$name] = $value;
427     }
428   }
430   /* Check formular input */
431   function check()
432   {
433     $message= array();
435     /* Skip if we've no config object */
436     if (!isset($this->config) || !is_object($this->config)){
437       return $message;
438     }
440     /* Find hooks entries for this class */
441     $command= $this->config->search(get_class($this), "CHECK", array('menu', 'tabs'));
443     if ($command != ""){
445       if (!check_command($command)){
446         $message[]= msgPool::cmdnotfound("CHECK", get_class($this));
447       } else {
449         /* Generate "ldif" for check hook */
450         $ldif= "dn: $this->dn\n";
451         
452         /* ... objectClasses */
453         foreach ($this->objectclasses as $oc){
454           $ldif.= "objectClass: $oc\n";
455         }
456         
457         /* ... attributes */
458         foreach ($this->attributes as $attr){
459           if ($this->$attr == ""){
460             continue;
461           }
462           if (is_array($this->$attr)){
463             foreach ($this->$attr as $val){
464               $ldif.= "$attr: $val\n";
465             }
466           } else {
467               $ldif.= "$attr: ".$this->$attr."\n";
468           }
469         }
471         /* Append empty line */
472         $ldif.= "\n";
474         /* Feed "ldif" into hook and retrieve result*/
475         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
476         $fh= proc_open($command, $descriptorspec, $pipes);
477         if (is_resource($fh)) {
478           fwrite ($pipes[0], $ldif);
479           fclose($pipes[0]);
480           
481           $result= stream_get_contents($pipes[1]);
482           if ($result != ""){
483             $message[]= $result;
484           }
485           
486           fclose($pipes[1]);
487           fclose($pipes[2]);
488           proc_close($fh);
489         }
490       }
492     }
494     /* Check entryCSN */
495     if($this->CSN_check_active){
496       $current_csn = getEntryCSN($this->dn);
497       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
498         $this->entryCSN = $current_csn;
499         $message[] = _("The object has changed since opened in GOsa. All changes that may be done by others get lost if you save this entry!");
500       }
501     }
502     return ($message);
503   }
505   /* Adapt from template, using 'dn' */
506   function adapt_from_template($dn, $skip= array())
507   {
508     /* Include global link_info */
509     $ldap= $this->config->get_ldap_link();
511     /* Load requested 'dn' to 'attrs' */
512     $ldap->cat ($dn);
513     $this->attrs= $ldap->fetch();
515     /* Walk through attributes */
516     foreach ($this->attributes as $val){
518       /* Skip the ones in skip list */
519       if (in_array($val, $skip)){
520         continue;
521       }
523       if (isset($this->attrs["$val"][0])){
525         /* If attribute is set, replace dynamic parts: 
526            %sn, %givenName and %uid. Fill these in our local variables. */
527         $value= $this->attrs["$val"][0];
529         foreach (array("sn", "givenName", "uid") as $repl){
530           if (preg_match("/%$repl/i", $value)){
531             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
532           }
533         }
534         $this->$val= $value;
535       }
536     }
538     /* Is Account? */
539     $found= TRUE;
540     foreach ($this->objectclasses as $obj){
541       if (preg_match('/top/i', $obj)){
542         continue;
543       }
544       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
545         $found= FALSE;
546         break;
547       }
548     }
549     if ($found){
550       $this->is_account= TRUE;
551     }
552   }
554   /* Indicate whether a password change is needed or not */
555   function password_change_needed()
556   {
557     return FALSE;
558   }
561   /* Show header message for tab dialogs */
562   function show_enable_header($button_text, $text, $disabled= FALSE)
563   {
564     if (($disabled == TRUE) || (!$this->acl_is_createable())){
565       $state= "disabled";
566     } else {
567       $state= "";
568     }
569     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
570     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
571       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
573     return($display);
574   }
577   /* Show header message for tab dialogs */
578   function show_disable_header($button_text, $text, $disabled= FALSE)
579   {
580     if (($disabled == TRUE) || !$this->acl_is_removeable()){
581       $state= "disabled";
582     } else {
583       $state= "";
584     }
585     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
586     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
587       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
589     return($display);
590   }
593   /* Show header message for tab dialogs */
594   function show_header($button_text, $text, $disabled= FALSE)
595   {
596     echo "FIXME: show_header should be replaced by show_disable_header and show_enable_header<br>";
597     if ($disabled == TRUE){
598       $state= "disabled";
599     } else {
600       $state= "";
601     }
602     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
603     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
604       ($this->acl_is_createable()?'':'disabled')." ".$state.
605       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
607     return($display);
608   }
611   function postcreate($add_attrs= array())
612   {
613     /* Find postcreate entries for this class */
614     $command= $this->config->search(get_class($this), "POSTCREATE",array('menu', 'tabs'));
616     if ($command != ""){
618       /* Walk through attribute list */
619       foreach ($this->attributes as $attr){
620         if (!is_array($this->$attr)){
621           $add_attrs[$attr] = $this->$attr;
622         }
623       }
624       $add_attrs['dn']=$this->dn;
626       $tmp = array();
627       foreach($add_attrs as $name => $value){
628         $tmp[$name] =  strlen($name);
629       }
630       arsort($tmp);
631       
632       /* Additional attributes */
633       foreach ($tmp as $name => $len){
634         $value = $add_attrs[$name];
635         $command= str_replace("%$name", "$value", $command);
636       }
638       if (check_command($command)){
639         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
640             $command, "Execute");
641         exec($command,$arr);
642         foreach($arr as $str){
643           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
644             $command, "Result: ".$str);
645         }
646       } else {
647         $message= msgPool::cmdnotfound("POSTCREATE", get_class($this));
648         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
649       }
650     }
651   }
653   function postmodify($add_attrs= array())
654   {
655     /* Find postcreate entries for this class */
656     $command= $this->config->search(get_class($this), "POSTMODIFY",array('menu','tabs'));
658     if ($command != ""){
660       /* Walk through attribute list */
661       foreach ($this->attributes as $attr){
662         if (!is_array($this->$attr)){
663           $add_attrs[$attr] = $this->$attr;
664         }
665       }
666       $add_attrs['dn']=$this->dn;
668       $tmp = array();
669       foreach($add_attrs as $name => $value){
670         $tmp[$name] =  strlen($name);
671       }
672       arsort($tmp);
673       
674       /* Additional attributes */
675       foreach ($tmp as $name => $len){
676         $value = $add_attrs[$name];
677         $command= str_replace("%$name", "$value", $command);
678       }
680       if (check_command($command)){
681         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,$command, "Execute");
682         exec($command,$arr);
683         foreach($arr as $str){
684           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
685             $command, "Result: ".$str);
686         }
687       } else {
688         $message= msgPool::cmdnotfound("POSTMODIFY", get_class($this));
689         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
690       }
691     }
692   }
694   function postremove($add_attrs= array())
695   {
696     /* Find postremove entries for this class */
697     $command= $this->config->search(get_class($this), "POSTREMOVE",array('menu','tabs'));
698     if ($command != ""){
700       /* Walk through attribute list */
701       foreach ($this->attributes as $attr){
702         if (!is_array($this->$attr)){
703           $add_attrs[$attr] = $this->$attr;
704         }
705       }
706       $add_attrs['dn']=$this->dn;
708       $tmp = array();
709       foreach($add_attrs as $name => $value){
710         $tmp[$name] =  strlen($name);
711       }
712       arsort($tmp);
713       
714       /* Additional attributes */
715       foreach ($tmp as $name => $len){
716         $value = $add_attrs[$name];
717         $command= str_replace("%$name", "$value", $command);
718       }
720       if (check_command($command)){
721         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
722             $command, "Execute");
724         exec($command,$arr);
725         foreach($arr as $str){
726           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
727             $command, "Result: ".$str);
728         }
729       } else {
730         $message= msgPool::cmdnotfound("POSTREMOVE", get_class($this));
731         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
732       }
733     }
734   }
736   /* Create unique DN */
737   function create_unique_dn($attribute, $base)
738   {
739     $ldap= $this->config->get_ldap_link();
740     $base= preg_replace("/^,*/", "", $base);
742     /* Try to use plain entry first */
743     $dn= "$attribute=".$this->$attribute.",$base";
744     $ldap->cat ($dn, array('dn'));
745     if (!$ldap->fetch()){
746       return ($dn);
747     }
749     /* Look for additional attributes */
750     foreach ($this->attributes as $attr){
751       if ($attr == $attribute || $this->$attr == ""){
752         continue;
753       }
755       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
756       $ldap->cat ($dn, array('dn'));
757       if (!$ldap->fetch()){
758         return ($dn);
759       }
760     }
762     /* None found */
763     return ("none");
764   }
766   function rebind($ldap, $referral)
767   {
768     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
769     if (ldap_bind($ldap, $credentials['ADMIN'], $this->config->get_credentials($credentials['PASSWORD']))) {
770       $this->error = "Success";
771       $this->hascon=true;
772       $this->reconnect= true;
773       return (0);
774     } else {
775       $this->error = "Could not bind to " . $credentials['ADMIN'];
776       return NULL;
777     }
778   }
781   /* Recursively copy ldap object */
782   function _copy($src_dn,$dst_dn)
783   {
784     $ldap=$this->config->get_ldap_link();
785     $ldap->cat($src_dn);
786     $attrs= $ldap->fetch();
788     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
789     $ds= ldap_connect($this->config->current['SERVER']);
790     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
791     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
792       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
793     }
795     $r=ldap_bind($ds,$this->config->current['ADMINDN'], $this->config->current['ADMINPASSWORD']);
796     $sr=ldap_read($ds, LDAP::fix($src_dn), "objectClass=*");
798     /* Fill data from LDAP */
799     $new= array();
800     if ($sr) {
801       $ei=ldap_first_entry($ds, $sr);
802       if ($ei) {
803         foreach($attrs as $attr => $val){
804           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
805             for ($i= 0; $i<$info['count']; $i++){
806               if ($info['count'] == 1){
807                 $new[$attr]= $info[$i];
808               } else {
809                 $new[$attr][]= $info[$i];
810               }
811             }
812           }
813         }
814       }
815     }
817     /* close conncetion */
818     ldap_unbind($ds);
820     /* Adapt naming attribute */
821     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
822     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
823     $new[$dst_name]= LDAP::fix($dst_val);
825     /* Check if this is a department.
826      * If it is a dep. && there is a , override in his ou 
827      *  change \2C to , again, else this entry can't be saved ...
828      */
829     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
830       $new['ou'] = str_replace("\\\\,",",",$new['ou']);
831     }
833     /* Save copy */
834     $ldap->connect();
835     $ldap->cd($this->config->current['BASE']);
836     
837     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
839     /* FAIvariable=.../..., cn=.. 
840         could not be saved, because the attribute FAIvariable was different to 
841         the dn FAIvariable=..., cn=... */
842     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
843       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
844     }
845     $ldap->cd($dst_dn);
846     $ldap->add($new);
848     if (!$ldap->success()){
849       trigger_error("Trying to save $dst_dn failed.",
850           E_USER_WARNING);
851       return(FALSE);
852     }
853     return(TRUE);
854   }
857   /* This is a workaround function. */
858   function copy($src_dn, $dst_dn)
859   {
860     /* Rename dn in possible object groups */
861     $ldap= $this->config->get_ldap_link();
862     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::prepare4filter($src_dn).'))',
863         array('cn'));
864     while ($attrs= $ldap->fetch()){
865       $og= new ogroup($this->config, $ldap->getDN());
866       unset($og->member[$src_dn]);
867       $og->member[$dst_dn]= $dst_dn;
868       $og->save ();
869     }
871     $ldap->cat($dst_dn);
872     $attrs= $ldap->fetch();
873     if (count($attrs)){
874       trigger_error("Trying to overwrite ".LDAP::fix($dst_dn).", which already exists.",
875           E_USER_WARNING);
876       return (FALSE);
877     }
879     $ldap->cat($src_dn);
880     $attrs= $ldap->fetch();
881     if (!count($attrs)){
882       trigger_error("Trying to move ".LDAP::fix($src_dn).", which does not seem to exist.",
883           E_USER_WARNING);
884       return (FALSE);
885     }
887     $ldap->cd($src_dn);
888     $ldap->search("objectClass=*",array("dn"));
889     while($attrs = $ldap->fetch()){
890       $src = $attrs['dn'];
891       $dst = preg_replace("/".preg_quote($src_dn, '/')."$/",$dst_dn,$attrs['dn']);
892       $this->_copy($src,$dst);
893     }
894     return (TRUE);
895   }
899   /*! \brief  Move a given ldap object indentified by $src_dn   \
900                to the given destination $dst_dn   \
901               * Ensure that all references are updated (ogroups) \
902               * Update ACLs   \
903               * Update accessTo   \
904       @param  String  The source dn.
905       @param  String  The destination dn.
906       @return Boolean TRUE on success else FALSE.
907    */
908   function rename($src_dn, $dst_dn)
909   {
910     $start = microtime(1);
912     /* Try to move the source entry to the destination position */
913     $ldap = $this->config->get_ldap_link();
914     $ldap->cd($this->config->current['BASE']);
915     $ldap->create_missing_trees(preg_replace("/^[^,]+,/","",$dst_dn));
916     if (!$ldap->rename_dn($src_dn,$dst_dn)){
917       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $src_dn, "", get_class()));
918       return(FALSE);
919     }
921     /* Get list of users,groups and roles within this tree,
922         maybe we have to update ACL references.
923      */
924     $leaf_objs = get_list("(|(objectClass=posixGroup)(objectClass=gosaAccount)(objectClass=gosaRole))",array("all"),$dst_dn,
925           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
926     foreach($leaf_objs as $obj){
927       $new_dn = $obj['dn'];
928       $old_dn = preg_replace("/".preg_quote($dst_dn, '/')."$/i",$src_dn,$new_dn);
929       $this->update_acls($old_dn,$new_dn); 
930     }
932     /* Get all objectGroups defined in this database. 
933         and check if there is an entry matching the source dn,
934         if this is the case, then update this objectgroup to use the new dn.
935      */
936     $ogroups = get_sub_list("(&(objectClass=gosaGroupOfNames)(member=*))","ogroups",
937         array(get_ou("ogroupRDN")),$this->config->current['BASE'],array("member"),
938         GL_SUBSEARCH | GL_NO_ACL_CHECK) ;
940     /* Walk through all objectGroups and check if there are 
941         members matching the source dn 
942      */
943     foreach($ogroups as $ogroup){
944       if(isset($ogroup['member'])){
946         /* Reset class object, this will be initialized with class_ogroup on demand 
947          */
948         $o_ogroup = NULL; 
949         for($i = 0 ; $i < $ogroup['member']['count'] ; $i ++){
951           $c_mem = $ogroup['member'][$i];
952   
953           if(preg_match("/".preg_quote($src_dn, '/')."$/i",$c_mem)){
954  
955             $d_mem = preg_replace("/".preg_quote($src_dn, '/')."$/i",$dst_dn,$ogroup['member'][$i]);
957             if($o_ogroup == NULL){
958               $o_ogroup = new ogroup($this->config,$ogroup['dn']);
959             }              
961             unset($o_ogroup->member[$c_mem]);
962             $o_ogroup->member[$d_mem]= $d_mem;
963           }
964         }
965        
966         /* Save object group if there were changes made on the membership */ 
967         if($o_ogroup != NULL){
968           $o_ogroup->save();
969         }
970       }
971     }
972  
973     /* Check if there are gosa departments moved. 
974        If there were deps moved, the force reload of config->deps.
975      */
976     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
977           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
978   
979     if(count($leaf_deps)){
980       $this->config->get_departments();
981       $this->config->make_idepartments();
982       session::set("config",$this->config);
983       $ui =get_userinfo();
984       $ui->reset_acl_cache();
985     }
987     return(TRUE); 
988   }
992   function move($src_dn, $dst_dn)
993   {
994     /* Do not copy if only upper- lowercase has changed */
995     if(strtolower($src_dn) == strtolower($dst_dn)){
996       return(TRUE);
997     }
999     
1000     /* Try to move the entry instead of copy & delete
1001      */
1002     if(TRUE){
1004       /* Try to move with ldap routines, if this was not successfull
1005           fall back to the old style copy & remove method 
1006        */
1007       if($this->rename($src_dn, $dst_dn)){
1008         return(TRUE);
1009       }else{
1010         // See code below.
1011       }
1012     }
1014     /* Copy source to destination */
1015     if (!$this->copy($src_dn, $dst_dn)){
1016       return (FALSE);
1017     }
1019     /* Delete source */
1020     $ldap= $this->config->get_ldap_link();
1021     $ldap->rmdir_recursive($src_dn);
1022     if (!$ldap->success()){
1023       trigger_error("Trying to delete $src_dn failed.",
1024           E_USER_WARNING);
1025       return (FALSE);
1026     }
1028     return (TRUE);
1029   }
1032   /* Move/Rename complete trees */
1033   function recursive_move($src_dn, $dst_dn)
1034   {
1035     /* Check if the destination entry exists */
1036     $ldap= $this->config->get_ldap_link();
1038     /* Check if destination exists - abort */
1039     $ldap->cat($dst_dn, array('dn'));
1040     if ($ldap->fetch()){
1041       trigger_error("recursive_move $dst_dn already exists.",
1042           E_USER_WARNING);
1043       return (FALSE);
1044     }
1046     $this->copy($src_dn, $dst_dn);
1048     /* Remove src_dn */
1049     $ldap->cd($src_dn);
1050     $ldap->recursive_remove($src_dn);
1051     return (TRUE);
1052   }
1055   function handle_post_events($mode, $add_attrs= array())
1056   {
1057     switch ($mode){
1058       case "add":
1059         $this->postcreate($add_attrs);
1060       break;
1062       case "modify":
1063         $this->postmodify($add_attrs);
1064       break;
1066       case "remove":
1067         $this->postremove($add_attrs);
1068       break;
1069     }
1070   }
1073   function saveCopyDialog(){
1074   }
1077   function getCopyDialog(){
1078     return(array("string"=>"","status"=>""));
1079   }
1082   function PrepareForCopyPaste($source)
1083   {
1084     $todo = $this->attributes;
1085     if(isset($this->CopyPasteVars)){
1086       $todo = array_merge($todo,$this->CopyPasteVars);
1087     }
1089     if(count($this->objectclasses)){
1090       $this->is_account = TRUE;
1091       foreach($this->objectclasses as $class){
1092         if(!in_array($class,$source['objectClass'])){
1093           $this->is_account = FALSE;
1094         }
1095       }
1096     }
1098     foreach($todo as $var){
1099       if (isset($source[$var])){
1100         if(isset($source[$var]['count'])){
1101           if($source[$var]['count'] > 1){
1102             $this->$var = array();
1103             $tmp = array();
1104             for($i = 0 ; $i < $source[$var]['count']; $i++){
1105               $tmp = $source[$var][$i];
1106             }
1107             $this->$var = $tmp;
1108           }else{
1109             $this->$var = $source[$var][0];
1110           }
1111         }else{
1112           $this->$var= $source[$var];
1113         }
1114       }
1115     }
1116   }
1118   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1119   {
1120     /* Skip tagging? 
1121        If this is called from departmentGeneric, we have to skip this
1122         tagging procedure. 
1123      */
1124     if($this->skipTagging){
1125       return;
1126     }
1128     /* No dn? Self-operation... */
1129     if ($dn == ""){
1130       $dn= $this->dn;
1132       /* No tag? Find it yourself... */
1133       if ($tag == ""){
1134         $len= strlen($dn);
1136         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1137         $relevant= array();
1138         foreach ($this->config->adepartments as $key => $ntag){
1140           /* This one is bigger than our dn, its not relevant... */
1141           if ($len < strlen($key)){
1142             continue;
1143           }
1145           /* This one matches with the latter part. Break and don't fix this entry */
1146           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
1147             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1148             $relevant[strlen($key)]= $ntag;
1149             continue;
1150           }
1152         }
1154         /* If we've some relevant tags to set, just get the longest one */
1155         if (count($relevant)){
1156           ksort($relevant);
1157           $tmp= array_keys($relevant);
1158           $idx= end($tmp);
1159           $tag= $relevant[$idx];
1160           $this->gosaUnitTag= $tag;
1161         }
1162       }
1163     }
1164   
1165     /* Remove tags that may already be here... */
1166     remove_objectClass("gosaAdministrativeUnitTag", $at);
1167     if (isset($at['gosaUnitTag'])){
1168         unset($at['gosaUnitTag']);
1169     }
1171     /* Set tag? */
1172     if ($tag != ""){
1173       add_objectClass("gosaAdministrativeUnitTag", $at);
1174       $at['gosaUnitTag']= $tag;
1175     }
1177     /* Initially this object was tagged. 
1178        - But now, it is no longer inside a tagged department. 
1179        So force the remove of the tag.
1180        (objectClass was already removed obove)
1181      */
1182     if($tag == "" && $this->gosaUnitTag){
1183       $at['gosaUnitTag'] = array();
1184     }
1185   }
1188   /* Add possibility to stop remove process */
1189   function allow_remove()
1190   {
1191     $reason= "";
1192     return $reason;
1193   }
1196   /* Create a snapshot of the current object */
1197   function create_snapshot($type= "snapshot", $description= array())
1198   {
1200     /* Check if snapshot functionality is enabled */
1201     if(!$this->snapshotEnabled()){
1202       return;
1203     }
1205     /* Get configuration from gosa.conf */
1206     $config = $this->config;
1208     /* Create lokal ldap connection */
1209     $ldap= $this->config->get_ldap_link();
1210     $ldap->cd($this->config->current['BASE']);
1212     /* check if there are special server configurations for snapshots */
1213     if($config->get_cfg_value("snapshotURI") == ""){
1215       /* Source and destination server are both the same, just copy source to dest obj */
1216       $ldap_to      = $ldap;
1217       $snapldapbase = $this->config->current['BASE'];
1219     }else{
1220       $server         = $config->get_cfg_value("snapshotURI");
1221       $user           = $config->get_cfg_value("snapshotAdminDn");
1222       $password       = $config->get_cfg_value("snapshotAdminPassword");
1223       $snapldapbase   = $config->get_cfg_value("snapshotBase");
1225       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1226       $ldap_to -> cd($snapldapbase);
1228       if (!$ldap_to->success()){
1229         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1230       }
1232     }
1234     /* check if the dn exists */ 
1235     if ($ldap->dn_exists($this->dn)){
1237       /* Extract seconds & mysecs, they are used as entry index */
1238       list($usec, $sec)= explode(" ", microtime());
1240       /* Collect some infos */
1241       $base           = $this->config->current['BASE'];
1242       $snap_base      = $config->get_cfg_value("snapshotBase");
1243       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1244       $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1246       /* Create object */
1247 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1248       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1249       $newName          = str_replace(".", "", $sec."-".$usec);
1250       $target= array();
1251       $target['objectClass']            = array("top", "gosaSnapshotObject");
1252       $target['gosaSnapshotData']       = gzcompress($data, 6);
1253       $target['gosaSnapshotType']       = $type;
1254       $target['gosaSnapshotDN']         = $this->dn;
1255       $target['description']            = $description;
1256       $target['gosaSnapshotTimestamp']  = $newName;
1258       /* Insert the new snapshot 
1259          But we have to check first, if the given gosaSnapshotTimestamp
1260          is already used, in this case we should increment this value till there is 
1261          an unused value. */ 
1262       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1263       $ldap_to->cat($new_dn);
1264       while($ldap_to->count()){
1265         $ldap_to->cat($new_dn);
1266         $newName = str_replace(".", "", $sec."-".($usec++));
1267         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1268         $target['gosaSnapshotTimestamp']  = $newName;
1269       } 
1271       /* Inset this new snapshot */
1272       $ldap_to->cd($snapldapbase);
1273       $ldap_to->create_missing_trees($snapldapbase);
1274       $ldap_to->create_missing_trees($new_base);
1275       $ldap_to->cd($new_dn);
1276       $ldap_to->add($target);
1277       if (!$ldap_to->success()){
1278         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $new_dn, LDAP_ADD, get_class()));
1279       }
1281       if (!$ldap->success()){
1282         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $new_base, "", get_class()));
1283       }
1285     }
1286   }
1288   function remove_snapshot($dn)
1289   {
1290     $ui       = get_userinfo();
1291     $old_dn   = $this->dn; 
1292     $this->dn = $dn;
1293     $ldap = $this->config->get_ldap_link();
1294     $ldap->cd($this->config->current['BASE']);
1295     $ldap->rmdir_recursive($dn);
1296     $this->dn = $old_dn;
1297   }
1300   /* returns true if snapshots are enabled, and false if it is disalbed
1301      There will also be some errors psoted, if the configuration failed */
1302   function snapshotEnabled()
1303   {
1304     $config = $this->config;
1305     if($config->get_cfg_value("enableSnapshots") == "true"){
1306             /* Check if the snapshot_base is defined */
1307             if ($config->get_cfg_value("snapshotBase") == ""){
1308                     msg_dialog::display(_("Configuration error"), sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."),"snapshotBase"), ERROR_DIALOG);
1309                     return(FALSE);
1310             }
1312             /* check if there are special server configurations for snapshots */
1313             if ($config->get_cfg_value("snapshotURI") != ""){
1315                     /* check if all required vars are available to create a new ldap connection */
1316                     $missing = "";
1317                     foreach(array("snapshotURI","snapshotAdminDn","snapshotAdminPassword","snapshotBase") as $var){
1318                             if($config->get_cfg_value($var) == ""){
1319                                     $missing .= $var." ";
1320                                     msg_dialog::display(_("Configuration error"), sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."), $missing), ERROR_DIALOG);
1321                                     return(FALSE);
1322                             }
1323                     }
1324             }
1325             return(TRUE);
1326     }
1327     return(FALSE);
1328   }
1331   /* Return available snapshots for the given base 
1332    */
1333   function Available_SnapsShots($dn,$raw = false)
1334   {
1335     if(!$this->snapshotEnabled()) return(array());
1337     /* Create an additional ldap object which
1338        points to our ldap snapshot server */
1339     $ldap= $this->config->get_ldap_link();
1340     $ldap->cd($this->config->current['BASE']);
1341     $cfg= &$this->config->current;
1343     /* check if there are special server configurations for snapshots */
1344     if($this->config->get_cfg_value("snapshotURI") == ""){
1345       $ldap_to      = $ldap;
1346     }else{
1347       $server         = $this->config->get_cfg_value("snapshotURI");
1348       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1349       $password       = $this->config->get_cfg_value("snapshotAdminPassword");
1350       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1351       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1352       $ldap_to -> cd($snapldapbase);
1353       if (!$ldap_to->success()){
1354         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1355       }
1356     }
1358     /* Prepare bases and some other infos */
1359     $base           = $this->config->current['BASE'];
1360     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1361     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1362     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1363     $tmp            = array(); 
1365     /* Fetch all objects with  gosaSnapshotDN=$dn */
1366     $ldap_to->cd($new_base);
1367     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1368         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1370     /* Put results into a list and add description if missing */
1371     while($entry = $ldap_to->fetch()){ 
1372       if(!isset($entry['description'][0])){
1373         $entry['description'][0]  = "";
1374       }
1375       $tmp[] = $entry; 
1376     }
1378     /* Return the raw array, or format the result */
1379     if($raw){
1380       return($tmp);
1381     }else{  
1382       $tmp2 = array();
1383       foreach($tmp as $entry){
1384         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1385       }
1386     }
1387     return($tmp2);
1388   }
1391   function getAllDeletedSnapshots($base_of_object,$raw = false)
1392   {
1393     if(!$this->snapshotEnabled()) return(array());
1395     /* Create an additional ldap object which
1396        points to our ldap snapshot server */
1397     $ldap= $this->config->get_ldap_link();
1398     $ldap->cd($this->config->current['BASE']);
1399     $cfg= &$this->config->current;
1401     /* check if there are special server configurations for snapshots */
1402     if($this->config->get_cfg_value("snapshotURI") == ""){
1403       $ldap_to      = $ldap;
1404     }else{
1405       $server         = $this->config->get_cfg_value("snapshotURI");
1406       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1407       $password       = $this->config->get_cfg_value("snapshotAdminPassword");
1408       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1409       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1410       $ldap_to -> cd($snapldapbase);
1411       if (!$ldap_to->success()){
1412         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1413       }
1414     }
1416     /* Prepare bases */ 
1417     $base           = $this->config->current['BASE'];
1418     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1419     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1421     /* Fetch all objects and check if they do not exist anymore */
1422     $ui = get_userinfo();
1423     $tmp = array();
1424     $ldap_to->cd($new_base);
1425     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1426     while($entry = $ldap_to->fetch()){
1428       $chk =  str_replace($new_base,"",$entry['dn']);
1429       if(preg_match("/,ou=/",$chk)) continue;
1431       if(!isset($entry['description'][0])){
1432         $entry['description'][0]  = "";
1433       }
1434       $tmp[] = $entry; 
1435     }
1437     /* Check if entry still exists */
1438     foreach($tmp as $key => $entry){
1439       $ldap->cat($entry['gosaSnapshotDN'][0]);
1440       if($ldap->count()){
1441         unset($tmp[$key]);
1442       }
1443     }
1445     /* Format result as requested */
1446     if($raw) {
1447       return($tmp);
1448     }else{
1449       $tmp2 = array();
1450       foreach($tmp as $key => $entry){
1451         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1452       }
1453     }
1454     return($tmp2);
1455   } 
1458   /* Restore selected snapshot */
1459   function restore_snapshot($dn)
1460   {
1461     if(!$this->snapshotEnabled()) return(array());
1463     $ldap= $this->config->get_ldap_link();
1464     $ldap->cd($this->config->current['BASE']);
1465     $cfg= &$this->config->current;
1467     /* check if there are special server configurations for snapshots */
1468     if($this->config->get_cfg_value("snapshotURI") == ""){
1469       $ldap_to      = $ldap;
1470     }else{
1471       $server         = $this->config->get_cfg_value("snapshotURI");
1472       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1473       $password       = $this->config->get_cfg_value("snapshotAdminPassword");
1474       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1475       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1476       $ldap_to -> cd($snapldapbase);
1477       if (!$ldap_to->success()){
1478         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1479       }
1480     }
1482     /* Get the snapshot */ 
1483     $ldap_to->cat($dn);
1484     $restoreObject = $ldap_to->fetch();
1486     /* Prepare import string */
1487     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1489     /* Import the given data */
1490     $err = "";
1491     $ldap->import_complete_ldif($data,$err,false,false);
1492     if (!$ldap->success()){
1493       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, "", get_class()));
1494     }
1495   }
1498   function showSnapshotDialog($base,$baseSuffixe,&$parent)
1499   {
1500     $once = true;
1501     $ui = get_userinfo();
1502     $this->parent = $parent;
1504     foreach($_POST as $name => $value){
1505                         $entry = base64_decode(preg_replace("/_[xy]$/","",$name));
1507       /* Create a new snapshot, display a dialog */
1508       if(preg_match("/^CreateSnapShotDialog_/",$name) && $once){
1509         $once = false;
1510         $entry = preg_replace("/^CreateSnapShotDialog_/","",$entry);
1512         if(!empty($entry) && $ui->allow_snapshot_create($entry,$this->parent->acl_module)){
1513           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1514         }else{
1515           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to create a snapshot for %s."),$entry),ERROR_DIALOG);
1516         }
1517       }  
1518   
1519       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1520       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1521         $once = false;
1522         $entry = preg_replace("/^RestoreSnapShotDialog_/","",$entry);
1523         if(!empty($entry) && $ui->allow_snapshot_restore($entry,$this->parent->acl_module)){
1524           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1525           $this->snapDialog->display_restore_dialog = true;
1526         }else{
1527           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1528         }
1529       }
1531       /* Restore one of the already deleted objects */
1532       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1533           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1534         $once = false;
1536         if($ui->allow_snapshot_restore($base,$this->parent->acl_module)){
1537           $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1538           $this->snapDialog->set_snapshot_bases($baseSuffixe);
1539           $this->snapDialog->display_restore_dialog      = true;
1540           $this->snapDialog->display_all_removed_objects  = true;
1541         }else{
1542           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$base),ERROR_DIALOG);
1543         }
1544       }
1546       /* Restore selected snapshot */
1547       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1548         $once = false;
1549         $entry = preg_replace("/^RestoreSnapShot_/","",$entry);
1550         if(!empty($entry) && $ui->allow_snapshot_restore($entry,$this->parent->acl_module)){
1551           $this->restore_snapshot($entry);
1552           $this->snapDialog = NULL;
1553         }else{
1554           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1555         }
1556       }
1557     }
1559     /* Create a new snapshot requested, check
1560        the given attributes and create the snapshot*/
1561     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1562       $this->snapDialog->save_object();
1563       $msgs = $this->snapDialog->check();
1564       if(count($msgs)){
1565         foreach($msgs as $msg){
1566           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
1567         }
1568       }else{
1569         $this->dn =  $this->snapDialog->dn;
1570         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1571         $this->snapDialog = NULL;
1572       }
1573     }
1575     /* Restore is requested, restore the object with the posted dn .*/
1576     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1577     }
1579     if(isset($_POST['CancelSnapshot'])){
1580       $this->snapDialog = NULL;
1581     }
1583     if(is_object($this->snapDialog )){
1584       $this->snapDialog->save_object();
1585       return($this->snapDialog->execute());
1586     }
1587   }
1590   static function plInfo()
1591   {
1592     return array();
1593   }
1596   function set_acl_base($base)
1597   {
1598     $this->acl_base= $base;
1599   }
1602   function set_acl_category($category)
1603   {
1604     $this->acl_category= "$category/";
1605   }
1608   function acl_is_writeable($attribute,$skip_write = FALSE)
1609   {
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     $ui= get_userinfo();
1625     if($base == "") $base = $this->acl_base;
1626     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1627   }
1630   function acl_is_removeable($base ="")
1631   {
1632     $ui= get_userinfo();
1633     if($base == "") $base = $this->acl_base;
1634     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1635   }
1638   function acl_is_moveable($base = "")
1639   {
1640     $ui= get_userinfo();
1641     if($base == "") $base = $this->acl_base;
1642     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1643   }
1646   function acl_have_any_permissions()
1647   {
1648   }
1651   function getacl($attribute,$skip_write= FALSE)
1652   {
1653     $ui= get_userinfo();
1654     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1655   }
1658   /*! \brief    Returns a list of all available departments for this object.  
1659                 If this object is new, all departments we are allowed to create a new user in are returned.
1660                 If this is an existing object, return all deps. we are allowed to move tis object too.
1662       @return   Array [dn] => "..name"  // All deps. we are allowed to act on.
1663   */
1664   function get_allowed_bases()
1665   {
1666     $ui = get_userinfo();
1667     $deps = array();
1669     /* Is this a new object ? Or just an edited existing object */
1670     if(!$this->initially_was_account && $this->is_account){
1671       $new = true;
1672     }else{
1673       $new = false;
1674     }
1676     foreach($this->config->idepartments as $dn => $name){
1677       if($new && $this->acl_is_createable($dn)){
1678         $deps[$dn] = $name;
1679       }elseif(!$new && $this->acl_is_moveable($dn)){
1680         $deps[$dn] = $name;
1681       }
1682     }
1684     /* Add current base */      
1685     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1686       $deps[$this->base] = $this->config->idepartments[$this->base];
1687     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1689     }else{
1690       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1691     }
1692     return($deps);
1693   }
1696   /* This function updates ACL settings if $old_dn was used.
1697    *  $old_dn   specifies the actually used dn
1698    *  $new_dn   specifies the destiantion dn
1699    */
1700   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1701   {
1702     /* Check if old_dn is empty. This should never happen */
1703     if(empty($old_dn) || empty($new_dn)){
1704       trigger_error("Failed to check acl dependencies, wrong dn given.");
1705       return;
1706     }
1708     /* Update userinfo if necessary */
1709     $ui = session::get('ui');
1710     if($ui->dn == $old_dn){
1711       $ui->dn = $new_dn;
1712       session::set('ui',$ui);
1713       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1714     }
1716     /* Object was moved, ensure that all acls will be moved too */
1717     if($new_dn != $old_dn && $old_dn != "new"){
1719       /* get_ldap configuration */
1720       $update = array();
1721       $ldap = $this->config->get_ldap_link();
1722       $ldap->cd ($this->config->current['BASE']);
1723       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1724       while($attrs = $ldap->fetch()){
1725         $acls = array();
1726         $found = false;
1727         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1728           $acl_parts = split(":",$attrs['gosaAclEntry'][$i]);
1730           /* Roles uses antoher data storage order, members are stored int the third part, 
1731              while the members in direct ACL assignments are stored in the second part.
1732            */
1733           $id = ($acl_parts[1] == "role") ? 3 : 2;
1735           /* Update member entries to use $new_dn instead of old_dn
1736            */
1737           $members = explode(",",$acl_parts[$id]);
1738           foreach($members as $key => $member){
1739             $member = base64_decode($member);
1740             if($member == $old_dn){
1741               $members[$key] = base64_encode($new_dn);
1742               $found = TRUE;
1743             }
1744           } 
1746           /* Check if the selected role has to updated
1747            */
1748           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1749             $acl_parts[2] = base64_encode($new_dn);
1750             $found = TRUE;
1751           }
1753           /* Build new acl string */ 
1754           $acl_parts[$id] = implode($members,",");
1755           $acls[] = implode($acl_parts,":");
1756         }
1758         /* Acls for this object must be adjusted */
1759         if($found){
1761           $debug_info=  _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1762             $old_dn."</b><br>&nbsp;-"._("to")."&nbsp;<b>".$new_dn."</b><br>";
1763           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1765           $update[$attrs['dn']] =array();
1766           foreach($acls as $acl){
1767             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1768           }
1769         }
1770       }
1772       /* Write updated acls */
1773       foreach($update as $dn => $attrs){
1774         $ldap->cd($dn);
1775         $ldap->modify($attrs);
1776       }
1777     }
1778   }
1780   
1782   /* This function enables the entry Serial ID check.
1783    * If an entry was edited while we have edited the entry too,
1784    *  an error message will be shown. 
1785    * To configure this check correctly read the FAQ.
1786    */    
1787   function enable_CSN_check()
1788   {
1789     $this->CSN_check_active =TRUE;
1790     $this->entryCSN = getEntryCSN($this->dn);
1791   }
1794   /*! \brief  Prepares the plugin to be used for multiple edit
1795    *          Update plugin attributes with given array of attribtues.
1796    *  @param  array   Array with attributes that must be updated.
1797    */
1798   function init_multiple_support($attrs,$all)
1799   {
1800     $ldap= $this->config->get_ldap_link();
1801     $this->multi_attrs    = $attrs;
1802     $this->multi_attrs_all= $all;
1804     /* Copy needed attributes */
1805     foreach ($this->attributes as $val){
1806       $found= array_key_ics($val, $this->multi_attrs);
1807       if ($found != ""){
1808         if(isset($this->multi_attrs["$found"][0])){
1809           $this->$val= $this->multi_attrs["$found"][0];
1810         }
1811       }
1812     }
1813   }
1815  
1816   /*! \brief  Enables multiple support for this plugin
1817    */
1818   function enable_multiple_support()
1819   {
1820     $this->ignore_account = TRUE;
1821     $this->multiple_support_active = TRUE;
1822   }
1825   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1826       @return array Cotaining all mdofied values. 
1827    */
1828   function get_multi_edit_values()
1829   {
1830     $ret = array();
1831     foreach($this->attributes as $attr){
1832       if(in_array($attr,$this->multi_boxes)){
1833         $ret[$attr] = $this->$attr;
1834       }
1835     }
1836     return($ret);
1837   }
1839   
1840   /*! \brief  Update class variables with values collected by multiple edit.
1841    */
1842   function set_multi_edit_values($attrs)
1843   {
1844     foreach($attrs as $name => $value){
1845       $this->$name = $value;
1846     }
1847   }
1850   /*! \brief execute plugin
1852     Generates the html output for this node
1853    */
1854   function multiple_execute()
1855   {
1856     /* This one is empty currently. Fabian - please fill in the docu code */
1857     session::set('current_class_for_help',get_class($this));
1859     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1860     session::set('LOCK_VARS_TO_USE',array());
1861     session::set('LOCK_VARS_USED',array());
1862     
1863     return("Multiple edit is currently not implemented for this plugin.");
1864   }
1867   /*! \brief   Save HTML posted data to object for multiple edit
1868    */
1869   function multiple_save_object()
1870   {
1871     if(empty($this->entryCSN) && $this->CSN_check_active){
1872       $this->entryCSN = getEntryCSN($this->dn);
1873     }
1875     /* Save values to object */
1876     $this->multi_boxes = array();
1877     foreach ($this->attributes as $val){
1878   
1879       /* Get selected checkboxes from multiple edit */
1880       if(isset($_POST["use_".$val])){
1881         $this->multi_boxes[] = $val;
1882       }
1884       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
1886         /* Check for modifications */
1887         if (get_magic_quotes_gpc()) {
1888           $data= stripcslashes($_POST["$val"]);
1889         } else {
1890           $data= $this->$val = $_POST["$val"];
1891         }
1892         if ($this->$val != $data){
1893           $this->is_modified= TRUE;
1894         }
1895     
1896         /* IE post fix */
1897         if(isset($data[0]) && $data[0] == chr(194)) {
1898           $data = "";  
1899         }
1900         $this->$val= $data;
1901       }
1902     }
1903   }
1906   /*! \brief  Returns all attributes of this plugin, 
1907                to be able to detect multiple used attributes 
1908                in multi_plugg::detect_multiple_used_attributes().
1909       @return array Attributes required for intialization of multi_plug
1910    */
1911   public function get_multi_init_values()
1912   {
1913     $attrs = $this->attrs;
1914     return($attrs);
1915   }
1918   /*! \brief  Check given values in multiple edit
1919       @return array Error messages
1920    */
1921   function multiple_check()
1922   {
1923     $message = plugin::check();
1924     return($message);
1925   }
1928   /*! \brief  Returns the snapshot header part for "Actions" menu in management dialogs 
1929       @param  $layer_menu  
1930    */   
1931   function get_snapshot_header($base,$category)
1932   {
1933     $str = "";
1934     $ui = get_userinfo();
1935     if($this->snapshotEnabled() && $ui->allow_snapshot_restore($base,$category)){
1937       $ok = false;
1938       foreach($this->get_used_snapshot_bases() as $base){
1939         $ok |= count($this->getAllDeletedSnapshots($base)) >= 1 ;
1940       }
1942       if($ok){
1943         $str = "..|<img class='center' src='images/lists/restore.png' ".
1944           "alt='"._("Restore")."'>&nbsp;"._("Restore").                       "|RestoreDeletedSnapShot|\n";
1945       }else{
1946         $str = "..|<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;"._("Restore")."||\n";
1947       }
1948     }
1949     return($str);
1950   }
1953   function get_snapshot_action($base,$category)
1954   {
1955     $str= ""; 
1956     $ui = get_userinfo();
1957     if($this->snapshotEnabled()){
1958       if ($ui->allow_snapshot_restore($base,$category)){
1960         if(count($this->Available_SnapsShots($base))){
1961           $str.= "<input class='center' type='image' src='images/lists/restore.png'
1962             alt='"._("Restore snapshot")."' name='RestoreSnapShotDialog_".base64_encode($base)."' title='"._("Restore snapshot")."'>&nbsp;";
1963         } else {
1964           $str = "<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;";
1965         }
1966       }
1967       if($ui->allow_snapshot_create($base,$category)){
1968         $str.= "<input class='center' type='image' src='images/snapshot.png'
1969           alt='"._("Create snapshot")."' name='CreateSnapShotDialog_".base64_encode($base)."' 
1970           title='"._("Create a new snapshot from this object")."'>&nbsp;";
1971       }else{
1972         $str = "<img class='center' src='images/empty.png' alt=' '>&nbsp;";
1973       }
1974     }
1976     return($str);
1977   }
1980   function get_copypaste_action($base,$category,$class,$copy = TRUE, $cut = TRUE)
1981   {
1982     $ui = get_userinfo();
1983     $action = "";
1984     if($this->CopyPasteHandler){
1985       if($cut){
1986         if($ui->is_cutable($base,$category,$class)){
1987           $action .= "<input class='center' type='image'
1988             src='images/lists/cut.png' alt='"._("cut")."' name='cut_%KEY%' title='"._("Cut this entry")."'>&nbsp;";
1989         }else{
1990           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
1991         }
1992       }
1993       if($copy){
1994         if($ui->is_copyable($base,$category,$class)){
1995           $action.= "<input class='center' type='image'
1996             src='images/lists/copy.png' alt='"._("copy")."' name='copy_%KEY%' title='"._("Copy this entry")."'>&nbsp;";
1997         }else{
1998           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
1999         }
2000       }
2001     }
2003     return($action); 
2004   }
2007   function get_copypaste_header($base,$category,$copy = TRUE, $cut = TRUE)
2008   {
2009     $s = "";
2010     $ui =get_userinfo();
2012     if(!is_array($category)){
2013       $category = array($category);
2014     }
2016     /* Check permissions for each category, if there is at least one category which 
2017         support read or paste permissions for the given base, then display the specific actions.
2018      */
2019     $readable = $pasteable = TRUE;
2020     foreach($category as $cat){
2021       $readable |= $ui->get_category_permissions($base,$cat);
2022       $pasteable|= $ui->is_pasteable($base,$cat);
2023     }
2024   
2025     if(($cut || $copy) && isset($this->CopyPasteHandler) && is_object($this->CopyPasteHandler)){
2026       if($readable){
2027         $s.= "..|---|\n";
2028         if($copy){
2029           $s.= "..|<img src='images/lists/copy.png' alt='' border='0' class='center'>".
2030             "&nbsp;"._("Copy")."|"."multiple_copy_systems|\n";
2031         }
2032         if($cut){
2033           $s.= "..|<img src='images/lists/cut.png' alt='' border='0' class='center'>".
2034             "&nbsp;"._("Cut")."|"."multiple_cut_systems|\n";
2035         }
2036       }
2038       if($pasteable){
2039         if($this->CopyPasteHandler->entries_queued()){
2040           $img = "<img border='0' class='center' src='images/lists/paste.png' alt=''>";
2041           $s.="..|".$img."&nbsp;"._("Paste")."|editPaste|\n";
2042         }else{
2043           $img = "<img border='0' class='center' src='images/lists/paste-grey.png' alt=''>";
2044           $s.="..|".$img."&nbsp;"._("Paste")."\n";
2045         }
2046       }
2047     }
2048     return($s);
2049   }
2052   function get_used_snapshot_bases()
2053   {
2054      return(array());
2055   }
2058 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2059 ?>