Code

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