Code

Reverted last commit
[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, $object= 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 ($object !== NULL){
171         $this->attrs= $object->attrs;
172       } else {
173         $ldap= $this->config->get_ldap_link();
174         $ldap->cat ($dn);
175         $this->attrs= $ldap->fetch();
176       }
178       /* Copy needed attributes */
179       foreach ($this->attributes as $val){
180         $found= array_key_ics($val, $this->attrs);
181         if ($found != ""){
182           $this->$val= $found[0];
183         }
184       }
186       /* gosaUnitTag loading... */
187       if (isset($this->attrs['gosaUnitTag'][0])){
188         $this->gosaUnitTag= $this->attrs['gosaUnitTag'][0];
189       }
191       /* Set the template flag according to the existence of objectClass
192          gosaUserTemplate */
193       if (isset($this->attrs['objectClass'])){
194         if (in_array_ics ("gosaUserTemplate", $this->attrs['objectClass'])){
195           $this->is_template= TRUE;
196           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
197               "found", "Template check");
198         }
199       }
201       /* Is Account? */
202       $found= TRUE;
203       foreach ($this->objectclasses as $obj){
204         if (preg_match('/top/i', $obj)){
205           continue;
206         }
207         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
208           $found= FALSE;
209           break;
210         }
211       }
212       if ($found){
213         $this->is_account= TRUE;
214         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
215             "found", "Object check");
216       }
218       /* Prepare saved attributes */
219       $this->saved_attributes= $this->attrs;
220       foreach ($this->saved_attributes as $index => $value){
221         if (is_numeric($index)){
222           unset($this->saved_attributes[$index]);
223           continue;
224         }
226         if (!in_array_ics($index, $this->attributes) && strcasecmp('objectClass', $index)){
227           unset($this->saved_attributes[$index]);
228           continue;
229         }
231         if (isset($this->saved_attributes[$index][0])){
232           if(!isset($this->saved_attributes[$index]["count"])){
233             $this->saved_attributes[$index]["count"] = count($this->saved_attributes[$index]);
234           }
235           if($this->saved_attributes[$index]["count"] == 1){
236             $tmp= $this->saved_attributes[$index][0];
237             unset($this->saved_attributes[$index]);
238             $this->saved_attributes[$index]= $tmp;
239             continue;
240           }
241         }
242         unset($this->saved_attributes["$index"]["count"]);
243       }
245       if(isset($this->attrs['gosaUnitTag'])){
246         $this->saved_attributes['gosaUnitTag'] = $this->attrs['gosaUnitTag'][0];
247       }
248     }
250     /* Save initial account state */
251     $this->initially_was_account= $this->is_account;
252   }
255   /*! \brief execute plugin
257     Generates the html output for this node
258    */
259   function execute()
260   {
261     /* This one is empty currently. Fabian - please fill in the docu code */
262     session::global_set('current_class_for_help',get_class($this));
264     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
265     session::set('LOCK_VARS_TO_USE',array());
266     session::set('LOCK_VARS_USED_GET',array());
267     session::set('LOCK_VARS_USED_POST',array());
268     session::set('LOCK_VARS_USED_REQUEST',array());
269   }
271   /*! \brief execute plugin
272      Removes object from parent
273    */
274   function remove_from_parent()
275   {
276     /* include global link_info */
277     $ldap= $this->config->get_ldap_link();
279     /* Get current objectClasses in order to add the required ones */
280     $ldap->cat($this->dn);
281     $tmp= $ldap->fetch ();
282     $oc= array();
283     if (isset($tmp['objectClass'])){
284       $oc= $tmp['objectClass'];
285       unset($oc['count']);
286     }
288     /* Remove objectClasses from entry */
289     $ldap->cd($this->dn);
290     $this->attrs= array();
291     $this->attrs['objectClass']= array_remove_entries_ics($this->objectclasses,$oc);
293     /* Unset attributes from entry */
294     foreach ($this->attributes as $val){
295       $this->attrs["$val"]= array();
296     }
298     /* Unset account info */
299     $this->is_account= FALSE;
301     /* Do not write in plugin base class, this must be done by
302        children, since there are normally additional attribs,
303        lists, etc. */
304     /*
305        $ldap->modify($this->attrs);
306      */
307   }
310   /*! \brief   Save HTML posted data to object 
311    */
312   function save_object()
313   {
314     /* Update entry CSN if it is empty. */
315     if(empty($this->entryCSN) && $this->CSN_check_active){
316       $this->entryCSN = getEntryCSN($this->dn);
317     }
319     /* Save values to object */
320     foreach ($this->attributes as $val){
321       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
322         /* Check for modifications */
323         if (get_magic_quotes_gpc()) {
324           $data= stripcslashes($_POST["$val"]);
325         } else {
326           $data= $this->$val = $_POST["$val"];
327         }
328         if ($this->$val != $data){
329           $this->is_modified= TRUE;
330         }
331     
332         /* Okay, how can I explain this fix ... 
333          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
334          * So IE posts these 'unselectable' option, with value = chr(194) 
335          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
336          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
337          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
338          */
339         if(isset($data[0]) && $data[0] == chr(194)) {
340           $data = "";  
341         }
342         $this->$val= $data;
343       }
344     }
345   }
348   /* Save data to LDAP, depending on is_account we save or delete */
349   function save()
350   {
351     /* include global link_info */
352     $ldap= $this->config->get_ldap_link();
354     /* Save all plugins */
355     $this->entryCSN = "";
357     /* Start with empty array */
358     $this->attrs= array();
360     /* Get current objectClasses in order to add the required ones */
361     $ldap->cat($this->dn);
362     
363     $tmp= $ldap->fetch ();
365     $oc= array();
366     if (isset($tmp['objectClass'])){
367       $oc= $tmp["objectClass"];
368       $this->is_new= FALSE;
369       unset($oc['count']);
370     } else {
371       $this->is_new= TRUE;
372     }
374     /* Load (minimum) attributes, add missing ones */
375     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
377     /* Copy standard attributes */
378     foreach ($this->attributes as $val){
379       if ($this->$val != ""){
380         $this->attrs["$val"]= $this->$val;
381       } elseif (!$this->is_new) {
382         $this->attrs["$val"]= array();
383       }
384     }
386     /* Handle tagging */
387     $this->tag_attrs($this->attrs);
388   }
391   function cleanup()
392   {
393     foreach ($this->attrs as $index => $value){
394       
395       /* Convert arrays with one element to non arrays, if the saved
396          attributes are no array, too */
397       if (is_array($this->attrs[$index]) && 
398           count ($this->attrs[$index]) == 1 &&
399           isset($this->saved_attributes[$index]) &&
400           !is_array($this->saved_attributes[$index])){
401           
402         $tmp= $this->attrs[$index][0];
403         $this->attrs[$index]= $tmp;
404       }
406       /* Remove emtpy arrays if they do not differ */
407       if (is_array($this->attrs[$index]) &&
408           count($this->attrs[$index]) == 0 &&
409           !isset($this->saved_attributes[$index])){
410           
411         unset ($this->attrs[$index]);
412         continue;
413       }
415       /* Remove single attributes that do not differ */
416       if (!is_array($this->attrs[$index]) &&
417           isset($this->saved_attributes[$index]) &&
418           !is_array($this->saved_attributes[$index]) &&
419           $this->attrs[$index] == $this->saved_attributes[$index]){
421         unset ($this->attrs[$index]);
422         continue;
423       }
425       /* Remove arrays that do not differ */
426       if (is_array($this->attrs[$index]) && 
427           isset($this->saved_attributes[$index]) &&
428           is_array($this->saved_attributes[$index])){
429           
430         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
431           unset ($this->attrs[$index]);
432           continue;
433         }
434       }
435     }
437     /* Update saved attributes and ensure that next cleanups will be successful too */
438     foreach($this->attrs as $name => $value){
439       $this->saved_attributes[$name] = $value;
440     }
441   }
443   /* Check formular input */
444   function check()
445   {
446     $message= array();
448     /* Skip if we've no config object */
449     if (!isset($this->config) || !is_object($this->config)){
450       return $message;
451     }
453     /* Find hooks entries for this class */
454     $command= $this->config->search(get_class($this), "CHECK", array('menu', 'tabs'));
456     if ($command != ""){
458       if (!check_command($command)){
459         $message[]= msgPool::cmdnotfound("CHECK", get_class($this));
460       } else {
462         /* Generate "ldif" for check hook */
463         $ldif= "dn: $this->dn\n";
464         
465         /* ... objectClasses */
466         foreach ($this->objectclasses as $oc){
467           $ldif.= "objectClass: $oc\n";
468         }
469         
470         /* ... attributes */
471         foreach ($this->attributes as $attr){
472           if ($this->$attr == ""){
473             continue;
474           }
475           if (is_array($this->$attr)){
476             foreach ($this->$attr as $val){
477               $ldif.= "$attr: $val\n";
478             }
479           } else {
480               $ldif.= "$attr: ".$this->$attr."\n";
481           }
482         }
484         /* Append empty line */
485         $ldif.= "\n";
487         /* Feed "ldif" into hook and retrieve result*/
488         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
489         $fh= proc_open($command, $descriptorspec, $pipes);
490         if (is_resource($fh)) {
491           fwrite ($pipes[0], $ldif);
492           fclose($pipes[0]);
493           
494           $result= stream_get_contents($pipes[1]);
495           if ($result != ""){
496             $message[]= $result;
497           }
498           
499           fclose($pipes[1]);
500           fclose($pipes[2]);
501           proc_close($fh);
502         }
503       }
505     }
507     /* Check entryCSN */
508     if($this->CSN_check_active){
509       $current_csn = getEntryCSN($this->dn);
510       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
511         $this->entryCSN = $current_csn;
512         $message[] = _("The object has changed since opened in GOsa. All changes that may be done by others get lost if you save this entry!");
513       }
514     }
515     return ($message);
516   }
518   /* Adapt from template, using 'dn' */
519   function adapt_from_template($dn, $skip= array())
520   {
521     /* Include global link_info */
522     $ldap= $this->config->get_ldap_link();
524     /* Load requested 'dn' to 'attrs' */
525     $ldap->cat ($dn);
526     $this->attrs= $ldap->fetch();
528     /* Walk through attributes */
529     foreach ($this->attributes as $val){
531       /* Skip the ones in skip list */
532       if (in_array($val, $skip)){
533         continue;
534       }
536       if (isset($this->attrs["$val"][0])){
538         /* If attribute is set, replace dynamic parts: 
539            %sn, %givenName and %uid. Fill these in our local variables. */
540         $value= $this->attrs["$val"][0];
542         foreach (array("sn", "givenName", "uid") as $repl){
543           if (preg_match("/%$repl/i", $value)){
544             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
545           }
546         }
547         $this->$val= $value;
548       }
549     }
551     /* Is Account? */
552     $found= TRUE;
553     foreach ($this->objectclasses as $obj){
554       if (preg_match('/top/i', $obj)){
555         continue;
556       }
557       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
558         $found= FALSE;
559         break;
560       }
561     }
562     if ($found){
563       $this->is_account= TRUE;
564     }
565   }
567   /* Indicate whether a password change is needed or not */
568   function password_change_needed()
569   {
570     return FALSE;
571   }
574   /* Show header message for tab dialogs */
575   function show_enable_header($button_text, $text, $disabled= FALSE)
576   {
577     if (($disabled == TRUE) || (!$this->acl_is_createable())){
578       $state= "disabled";
579     } else {
580       $state= "";
581     }
582     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
583     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
584       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
586     return($display);
587   }
590   /* Show header message for tab dialogs */
591   function show_disable_header($button_text, $text, $disabled= FALSE)
592   {
593     if (($disabled == TRUE) || !$this->acl_is_removeable()){
594       $state= "disabled";
595     } else {
596       $state= "";
597     }
598     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
599     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
600       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
602     return($display);
603   }
606   /* Show header message for tab dialogs */
607   function show_header($button_text, $text, $disabled= FALSE)
608   {
609     echo "FIXME: show_header should be replaced by show_disable_header and show_enable_header<br>";
610     if ($disabled == TRUE){
611       $state= "disabled";
612     } else {
613       $state= "";
614     }
615     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
616     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
617       ($this->acl_is_createable()?'':'disabled')." ".$state.
618       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
620     return($display);
621   }
624   function postcreate($add_attrs= array())
625   {
626     /* Find postcreate entries for this class */
627     $command= $this->config->search(get_class($this), "POSTCREATE",array('menu', 'tabs'));
629     if ($command != ""){
631       /* Walk through attribute list */
632       foreach ($this->attributes as $attr){
633         if (!is_array($this->$attr)){
634           $add_attrs[$attr] = $this->$attr;
635         }
636       }
637       $add_attrs['dn']=$this->dn;
639       $tmp = array();
640       foreach($add_attrs as $name => $value){
641         $tmp[$name] =  strlen($name);
642       }
643       arsort($tmp);
644       
645       /* Additional attributes */
646       foreach ($tmp as $name => $len){
647         $value = $add_attrs[$name];
648         $command= str_replace("%$name", "$value", $command);
649       }
651       if (check_command($command)){
652         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
653             $command, "Execute");
654         exec($command,$arr);
655         foreach($arr as $str){
656           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
657             $command, "Result: ".$str);
658         }
659       } else {
660         $message= msgPool::cmdnotfound("POSTCREATE", get_class($this));
661         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
662       }
663     }
664   }
666   function postmodify($add_attrs= array())
667   {
668     /* Find postcreate entries for this class */
669     $command= $this->config->search(get_class($this), "POSTMODIFY",array('menu','tabs'));
671     if ($command != ""){
673       /* Walk through attribute list */
674       foreach ($this->attributes as $attr){
675         if (!is_array($this->$attr)){
676           $add_attrs[$attr] = $this->$attr;
677         }
678       }
679       $add_attrs['dn']=$this->dn;
681       $tmp = array();
682       foreach($add_attrs as $name => $value){
683         $tmp[$name] =  strlen($name);
684       }
685       arsort($tmp);
686       
687       /* Additional attributes */
688       foreach ($tmp as $name => $len){
689         $value = $add_attrs[$name];
690         $command= str_replace("%$name", "$value", $command);
691       }
693       if (check_command($command)){
694         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,$command, "Execute");
695         exec($command,$arr);
696         foreach($arr as $str){
697           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
698             $command, "Result: ".$str);
699         }
700       } else {
701         $message= msgPool::cmdnotfound("POSTMODIFY", get_class($this));
702         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
703       }
704     }
705   }
707   function postremove($add_attrs= array())
708   {
709     /* Find postremove entries for this class */
710     $command= $this->config->search(get_class($this), "POSTREMOVE",array('menu','tabs'));
711     if ($command != ""){
713       /* Walk through attribute list */
714       foreach ($this->attributes as $attr){
715         if (!is_array($this->$attr)){
716           $add_attrs[$attr] = $this->$attr;
717         }
718       }
719       $add_attrs['dn']=$this->dn;
721       $tmp = array();
722       foreach($add_attrs as $name => $value){
723         $tmp[$name] =  strlen($name);
724       }
725       arsort($tmp);
726       
727       /* Additional attributes */
728       foreach ($tmp as $name => $len){
729         $value = $add_attrs[$name];
730         $command= str_replace("%$name", "$value", $command);
731       }
733       if (check_command($command)){
734         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
735             $command, "Execute");
737         exec($command,$arr);
738         foreach($arr as $str){
739           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
740             $command, "Result: ".$str);
741         }
742       } else {
743         $message= msgPool::cmdnotfound("POSTREMOVE", get_class($this));
744         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
745       }
746     }
747   }
750   /* Create unique DN */
751   function create_unique_dn2($data, $base)
752   {
753     $ldap= $this->config->get_ldap_link();
754     $base= preg_replace("/^,*/", "", $base);
756     /* Try to use plain entry first */
757     $dn= "$data,$base";
758     $attribute= preg_replace('/=.*$/', '', $data);
759     $ldap->cat ($dn, array('dn'));
760     if (!$ldap->fetch()){
761       return ($dn);
762     }
764     /* Look for additional attributes */
765     foreach ($this->attributes as $attr){
766       if ($attr == $attribute || $this->$attr == ""){
767         continue;
768       }
770       $dn= "$data+$attr=".$this->$attr.",$base";
771       $ldap->cat ($dn, array('dn'));
772       if (!$ldap->fetch()){
773         return ($dn);
774       }
775     }
777     /* None found */
778     return ("none");
779   }
782   /* Create unique DN */
783   function create_unique_dn($attribute, $base)
784   {
785     $ldap= $this->config->get_ldap_link();
786     $base= preg_replace("/^,*/", "", $base);
788     /* Try to use plain entry first */
789     $dn= "$attribute=".$this->$attribute.",$base";
790     $ldap->cat ($dn, array('dn'));
791     if (!$ldap->fetch()){
792       return ($dn);
793     }
795     /* Look for additional attributes */
796     foreach ($this->attributes as $attr){
797       if ($attr == $attribute || $this->$attr == ""){
798         continue;
799       }
801       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
802       $ldap->cat ($dn, array('dn'));
803       if (!$ldap->fetch()){
804         return ($dn);
805       }
806     }
808     /* None found */
809     return ("none");
810   }
813   function rebind($ldap, $referral)
814   {
815     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
816     if (ldap_bind($ldap, $credentials['ADMIN'], $this->config->get_credentials($credentials['PASSWORD']))) {
817       $this->error = "Success";
818       $this->hascon=true;
819       $this->reconnect= true;
820       return (0);
821     } else {
822       $this->error = "Could not bind to " . $credentials['ADMIN'];
823       return NULL;
824     }
825   }
828   /* Recursively copy ldap object */
829   function _copy($src_dn,$dst_dn)
830   {
831     $ldap=$this->config->get_ldap_link();
832     $ldap->cat($src_dn);
833     $attrs= $ldap->fetch();
835     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
836     $ds= ldap_connect($this->config->current['SERVER']);
837     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
838     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
839       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
840     }
842     $pwd = $this->config->get_credentials($this->config->current['ADMINPASSWORD']);
843     $r=ldap_bind($ds,$this->config->current['ADMINDN'], $pwd);
844     $sr=ldap_read($ds, LDAP::fix($src_dn), "objectClass=*");
846     /* Fill data from LDAP */
847     $new= array();
848     if ($sr) {
849       $ei=ldap_first_entry($ds, $sr);
850       if ($ei) {
851         foreach($attrs as $attr => $val){
852           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
853             for ($i= 0; $i<$info['count']; $i++){
854               if ($info['count'] == 1){
855                 $new[$attr]= $info[$i];
856               } else {
857                 $new[$attr][]= $info[$i];
858               }
859             }
860           }
861         }
862       }
863     }
865     /* close conncetion */
866     ldap_unbind($ds);
868     /* Adapt naming attribute */
869     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
870     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
871     $new[$dst_name]= LDAP::fix($dst_val);
873     /* Check if this is a department.
874      * If it is a dep. && there is a , override in his ou 
875      *  change \2C to , again, else this entry can't be saved ...
876      */
877     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
878       $new['ou'] = str_replace("\\\\,",",",$new['ou']);
879     }
881     /* Save copy */
882     $ldap->connect();
883     $ldap->cd($this->config->current['BASE']);
884     
885     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
887     /* FAIvariable=.../..., cn=.. 
888         could not be saved, because the attribute FAIvariable was different to 
889         the dn FAIvariable=..., cn=... */
890     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
891       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
892     }
893     $ldap->cd($dst_dn);
894     $ldap->add($new);
896     if (!$ldap->success()){
897       trigger_error("Trying to save $dst_dn failed.",
898           E_USER_WARNING);
899       return(FALSE);
900     }
901     return(TRUE);
902   }
905   /* This is a workaround function. */
906   function copy($src_dn, $dst_dn)
907   {
908     /* Rename dn in possible object groups */
909     $ldap= $this->config->get_ldap_link();
910     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::prepare4filter($src_dn).'))',
911         array('cn'));
912     while ($attrs= $ldap->fetch()){
913       $og= new ogroup($this->config, $ldap->getDN());
914       unset($og->member[$src_dn]);
915       $og->member[$dst_dn]= $dst_dn;
916       $og->save ();
917     }
919     $ldap->cat($dst_dn);
920     $attrs= $ldap->fetch();
921     if (count($attrs)){
922       trigger_error("Trying to overwrite ".LDAP::fix($dst_dn).", which already exists.",
923           E_USER_WARNING);
924       return (FALSE);
925     }
927     $ldap->cat($src_dn);
928     $attrs= $ldap->fetch();
929     if (!count($attrs)){
930       trigger_error("Trying to move ".LDAP::fix($src_dn).", which does not seem to exist.",
931           E_USER_WARNING);
932       return (FALSE);
933     }
935     $ldap->cd($src_dn);
936     $ldap->search("objectClass=*",array("dn"));
937     while($attrs = $ldap->fetch()){
938       $src = $attrs['dn'];
939       $dst = preg_replace("/".preg_quote($src_dn, '/')."$/",$dst_dn,$attrs['dn']);
940       $this->_copy($src,$dst);
941     }
942     return (TRUE);
943   }
947   /*! \brief  Move a given ldap object indentified by $src_dn   \
948                to the given destination $dst_dn   \
949               * Ensure that all references are updated (ogroups) \
950               * Update ACLs   \
951               * Update accessTo   \
952       @param  String  The source dn.
953       @param  String  The destination dn.
954       @return Boolean TRUE on success else FALSE.
955    */
956   function rename($src_dn, $dst_dn)
957   {
958     $start = microtime(1);
960     /* Try to move the source entry to the destination position */
961     $ldap = $this->config->get_ldap_link();
962     $ldap->cd($this->config->current['BASE']);
963     $ldap->create_missing_trees(preg_replace("/^[^,]+,/","",$dst_dn));
964     if (!$ldap->rename_dn($src_dn,$dst_dn)){
965 #      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $src_dn, "", get_class()));
966       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());
967       @DEBUG(DEBUG_LDAP,__LINE__,__FUNCTION__,__FILE__,"Rename failed FROM: $src_dn  -- TO:  $dst_dn", 
968           "Ldap Protocol v3 implementation error, falling back to maunal method.");
969       return(FALSE);
970     }
972     /* Get list of users,groups and roles within this tree,
973         maybe we have to update ACL references.
974      */
975     $leaf_objs = get_list("(|(objectClass=posixGroup)(objectClass=gosaAccount)(objectClass=gosaRole))",array("all"),$dst_dn,
976           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
977     foreach($leaf_objs as $obj){
978       $new_dn = $obj['dn'];
979       $old_dn = preg_replace("/".preg_quote(LDAP::convert($dst_dn), '/')."$/i",$src_dn,LDAP::convert($new_dn));
980       $this->update_acls($old_dn,$new_dn); 
981     }
983     // Migrate objectgroups if needed
984     $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);
986     // Walk through all objectGroups
987     foreach($ogroups as $ogroup){
988       // Migrate old to new dn
989       $o_ogroup= new ogroup($this->config,$ogroup['dn']);
990       if (isset($o_group->member[$src_dn])) {
991         unset($o_ogroup->member[$src_dn]);
992       }
993       $o_ogroup->member[$dst_dn]= $dst_dn;
994       
995       // Save object group
996       $o_ogroup->save();
997     }
999     // Migrate rfc groups if needed
1000     $groups = get_sub_list("(&(objectClass=posixGroup)(member=".LDAP::prepare4filter(LDAP::fix($src_dn))."))","groups", array(get_ou("groupRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
1002     // Walk through all POSIX groups
1003     foreach($groups as $group){
1005       // Migrate old to new dn
1006       $o_group= new group($this->config,$group['dn']);
1007       $o_group->save();
1008     }
1010     /* Update roles to use the new entry dn */
1011     $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);
1013     // Walk through all roles
1014     foreach($roles as $role){
1015       $role = new roleGeneric($this->config,$role['dn']);
1016       $key= array_search($src_dn, $role->roleOccupant);      
1017       if($key !== FALSE){
1018         $role->roleOccupant[$key] = $dst_dn;
1019         $role->save();
1020       }
1021     }
1022  
1023     /* Check if there are gosa departments moved. 
1024        If there were deps moved, the force reload of config->deps.
1025      */
1026     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
1027           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
1028   
1029     if(count($leaf_deps)){
1030       $this->config->get_departments();
1031       $this->config->make_idepartments();
1032       session::global_set("config",$this->config);
1033       $ui =get_userinfo();
1034       $ui->reset_acl_cache();
1035     }
1037     return(TRUE); 
1038   }
1042   function move($src_dn, $dst_dn)
1043   {
1044     /* Do not copy if only upper- lowercase has changed */
1045     if(strtolower($src_dn) == strtolower($dst_dn)){
1046       return(TRUE);
1047     }
1049     
1050     /* Try to move the entry instead of copy & delete
1051      */
1052     if(TRUE){
1054       /* Try to move with ldap routines, if this was not successfull
1055           fall back to the old style copy & remove method 
1056        */
1057       if($this->rename($src_dn, $dst_dn)){
1058         return(TRUE);
1059       }else{
1060         // See code below.
1061       }
1062     }
1064     /* Copy source to destination */
1065     if (!$this->copy($src_dn, $dst_dn)){
1066       return (FALSE);
1067     }
1069     /* Delete source */
1070     $ldap= $this->config->get_ldap_link();
1071     $ldap->rmdir_recursive($src_dn);
1072     if (!$ldap->success()){
1073       trigger_error("Trying to delete $src_dn failed.",
1074           E_USER_WARNING);
1075       return (FALSE);
1076     }
1078     return (TRUE);
1079   }
1082   /* Move/Rename complete trees */
1083   function recursive_move($src_dn, $dst_dn)
1084   {
1085     /* Check if the destination entry exists */
1086     $ldap= $this->config->get_ldap_link();
1088     /* Check if destination exists - abort */
1089     $ldap->cat($dst_dn, array('dn'));
1090     if ($ldap->fetch()){
1091       trigger_error("recursive_move $dst_dn already exists.",
1092           E_USER_WARNING);
1093       return (FALSE);
1094     }
1096     $this->copy($src_dn, $dst_dn);
1098     /* Remove src_dn */
1099     $ldap->cd($src_dn);
1100     $ldap->recursive_remove($src_dn);
1101     return (TRUE);
1102   }
1105   function handle_post_events($mode, $add_attrs= array())
1106   {
1107     switch ($mode){
1108       case "add":
1109         $this->postcreate($add_attrs);
1110       break;
1112       case "modify":
1113         $this->postmodify($add_attrs);
1114       break;
1116       case "remove":
1117         $this->postremove($add_attrs);
1118       break;
1119     }
1120   }
1123   function saveCopyDialog(){
1124   }
1127   function getCopyDialog(){
1128     return(array("string"=>"","status"=>""));
1129   }
1132   function PrepareForCopyPaste($source)
1133   {
1134     $todo = $this->attributes;
1135     if(isset($this->CopyPasteVars)){
1136       $todo = array_merge($todo,$this->CopyPasteVars);
1137     }
1139     if(count($this->objectclasses)){
1140       $this->is_account = TRUE;
1141       foreach($this->objectclasses as $class){
1142         if(!in_array($class,$source['objectClass'])){
1143           $this->is_account = FALSE;
1144         }
1145       }
1146     }
1148     foreach($todo as $var){
1149       if (isset($source[$var])){
1150         if(isset($source[$var]['count'])){
1151           if($source[$var]['count'] > 1){
1152             $tmp= $source[$var];
1153             unset($tmp['count']);
1154             $this->$var = $tmp;
1155           }else{
1156             $this->$var = $source[$var][0];
1157           }
1158         }else{
1159           $this->$var= $source[$var];
1160         }
1161       }
1162     }
1163   }
1165   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1166   {
1167     /* Skip tagging? 
1168        If this is called from departmentGeneric, we have to skip this
1169         tagging procedure. 
1170      */
1171     if($this->skipTagging){
1172       return;
1173     }
1175     /* No dn? Self-operation... */
1176     if ($dn == ""){
1177       $dn= $this->dn;
1179       /* No tag? Find it yourself... */
1180       if ($tag == ""){
1181         $len= strlen($dn);
1183         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1184         $relevant= array();
1185         foreach ($this->config->adepartments as $key => $ntag){
1187           /* This one is bigger than our dn, its not relevant... */
1188           if ($len < strlen($key)){
1189             continue;
1190           }
1192           /* This one matches with the latter part. Break and don't fix this entry */
1193           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
1194             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1195             $relevant[strlen($key)]= $ntag;
1196             continue;
1197           }
1199         }
1201         /* If we've some relevant tags to set, just get the longest one */
1202         if (count($relevant)){
1203           ksort($relevant);
1204           $tmp= array_keys($relevant);
1205           $idx= end($tmp);
1206           $tag= $relevant[$idx];
1207           $this->gosaUnitTag= $tag;
1208         }
1209       }
1210     }
1211   
1212     /* Remove tags that may already be here... */
1213     remove_objectClass("gosaAdministrativeUnitTag", $at);
1214     if (isset($at['gosaUnitTag'])){
1215         unset($at['gosaUnitTag']);
1216     }
1218     /* Set tag? */
1219     if ($tag != ""){
1220       add_objectClass("gosaAdministrativeUnitTag", $at);
1221       $at['gosaUnitTag']= $tag;
1222     }
1224     /* Initially this object was tagged. 
1225        - But now, it is no longer inside a tagged department. 
1226        So force the remove of the tag.
1227        (objectClass was already removed obove)
1228      */
1229     if($tag == "" && $this->gosaUnitTag){
1230       $at['gosaUnitTag'] = array();
1231     }
1232   }
1235   /* Add possibility to stop remove process */
1236   function allow_remove()
1237   {
1238     $reason= "";
1239     return $reason;
1240   }
1243   /* Create a snapshot of the current object */
1244   function create_snapshot($type= "snapshot", $description= array())
1245   {
1247     /* Check if snapshot functionality is enabled */
1248     if(!$this->snapshotEnabled()){
1249       return;
1250     }
1252     /* Get configuration from gosa.conf */
1253     $config = $this->config;
1255     /* Create lokal ldap connection */
1256     $ldap= $this->config->get_ldap_link();
1257     $ldap->cd($this->config->current['BASE']);
1259     /* check if there are special server configurations for snapshots */
1260     if($config->get_cfg_value("snapshotURI") == ""){
1262       /* Source and destination server are both the same, just copy source to dest obj */
1263       $ldap_to      = $ldap;
1264       $snapldapbase = $this->config->current['BASE'];
1266     }else{
1267       $server         = $config->get_cfg_value("snapshotURI");
1268       $user           = $config->get_cfg_value("snapshotAdminDn");
1269       $password       = $this->config->get_credentials($config->get_cfg_value("snapshotAdminPassword"));
1270       $snapldapbase   = $config->get_cfg_value("snapshotBase");
1272       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1273       $ldap_to -> cd($snapldapbase);
1275       if (!$ldap_to->success()){
1276         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1277       }
1279     }
1281     /* check if the dn exists */ 
1282     if ($ldap->dn_exists($this->dn)){
1284       /* Extract seconds & mysecs, they are used as entry index */
1285       list($usec, $sec)= explode(" ", microtime());
1287       /* Collect some infos */
1288       $base           = $this->config->current['BASE'];
1289       $snap_base      = $config->get_cfg_value("snapshotBase");
1290       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1291       $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1293       /* Create object */
1294 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1295       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1296       $newName          = str_replace(".", "", $sec."-".$usec);
1297       $target= array();
1298       $target['objectClass']            = array("top", "gosaSnapshotObject");
1299       $target['gosaSnapshotData']       = gzcompress($data, 6);
1300       $target['gosaSnapshotType']       = $type;
1301       $target['gosaSnapshotDN']         = $this->dn;
1302       $target['description']            = $description;
1303       $target['gosaSnapshotTimestamp']  = $newName;
1305       /* Insert the new snapshot 
1306          But we have to check first, if the given gosaSnapshotTimestamp
1307          is already used, in this case we should increment this value till there is 
1308          an unused value. */ 
1309       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1310       $ldap_to->cat($new_dn);
1311       while($ldap_to->count()){
1312         $ldap_to->cat($new_dn);
1313         $newName = str_replace(".", "", $sec."-".($usec++));
1314         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1315         $target['gosaSnapshotTimestamp']  = $newName;
1316       } 
1318       /* Inset this new snapshot */
1319       $ldap_to->cd($snapldapbase);
1320       $ldap_to->create_missing_trees($snapldapbase);
1321       $ldap_to->create_missing_trees($new_base);
1322       $ldap_to->cd($new_dn);
1323       $ldap_to->add($target);
1324       if (!$ldap_to->success()){
1325         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $new_dn, LDAP_ADD, get_class()));
1326       }
1328       if (!$ldap->success()){
1329         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $new_base, "", get_class()));
1330       }
1332     }
1333   }
1335   function remove_snapshot($dn)
1336   {
1337     $ui       = get_userinfo();
1338     $old_dn   = $this->dn; 
1339     $this->dn = $dn;
1340     $ldap = $this->config->get_ldap_link();
1341     $ldap->cd($this->config->current['BASE']);
1342     $ldap->rmdir_recursive($this->dn);
1343     if(!$ldap->success()){
1344       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn));
1345     }
1346     $this->dn = $old_dn;
1347   }
1350   /* returns true if snapshots are enabled, and false if it is disalbed
1351      There will also be some errors psoted, if the configuration failed */
1352   function snapshotEnabled()
1353   {
1354     return $this->config->snapshotEnabled();
1355   }
1358   /* Return available snapshots for the given base 
1359    */
1360   function Available_SnapsShots($dn,$raw = false)
1361   {
1362     if(!$this->snapshotEnabled()) return(array());
1364     /* Create an additional ldap object which
1365        points to our ldap snapshot server */
1366     $ldap= $this->config->get_ldap_link();
1367     $ldap->cd($this->config->current['BASE']);
1368     $cfg= &$this->config->current;
1370     /* check if there are special server configurations for snapshots */
1371     if($this->config->get_cfg_value("snapshotURI") == ""){
1372       $ldap_to      = $ldap;
1373     }else{
1374       $server         = $this->config->get_cfg_value("snapshotURI");
1375       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1376       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1377       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1378       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1379       $ldap_to -> cd($snapldapbase);
1380       if (!$ldap_to->success()){
1381         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1382       }
1383     }
1385     /* Prepare bases and some other infos */
1386     $base           = $this->config->current['BASE'];
1387     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1388     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1389     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1390     $tmp            = array(); 
1392     /* Fetch all objects with  gosaSnapshotDN=$dn */
1393     $ldap_to->cd($new_base);
1394     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1395         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1397     /* Put results into a list and add description if missing */
1398     while($entry = $ldap_to->fetch()){ 
1399       if(!isset($entry['description'][0])){
1400         $entry['description'][0]  = "";
1401       }
1402       $tmp[] = $entry; 
1403     }
1405     /* Return the raw array, or format the result */
1406     if($raw){
1407       return($tmp);
1408     }else{  
1409       $tmp2 = array();
1410       foreach($tmp as $entry){
1411         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1412       }
1413     }
1414     return($tmp2);
1415   }
1418   function getAllDeletedSnapshots($base_of_object,$raw = false)
1419   {
1420     if(!$this->snapshotEnabled()) return(array());
1422     /* Create an additional ldap object which
1423        points to our ldap snapshot server */
1424     $ldap= $this->config->get_ldap_link();
1425     $ldap->cd($this->config->current['BASE']);
1426     $cfg= &$this->config->current;
1428     /* check if there are special server configurations for snapshots */
1429     if($this->config->get_cfg_value("snapshotURI") == ""){
1430       $ldap_to      = $ldap;
1431     }else{
1432       $server         = $this->config->get_cfg_value("snapshotURI");
1433       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1434       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1435       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1436       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1437       $ldap_to -> cd($snapldapbase);
1438       if (!$ldap_to->success()){
1439         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1440       }
1441     }
1443     /* Prepare bases */ 
1444     $base           = $this->config->current['BASE'];
1445     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1446     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1448     /* Fetch all objects and check if they do not exist anymore */
1449     $ui = get_userinfo();
1450     $tmp = array();
1451     $ldap_to->cd($new_base);
1452     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1453     while($entry = $ldap_to->fetch()){
1455       $chk =  str_replace($new_base,"",$entry['dn']);
1456       if(preg_match("/,ou=/",$chk)) continue;
1458       if(!isset($entry['description'][0])){
1459         $entry['description'][0]  = "";
1460       }
1461       $tmp[] = $entry; 
1462     }
1464     /* Check if entry still exists */
1465     foreach($tmp as $key => $entry){
1466       $ldap->cat($entry['gosaSnapshotDN'][0]);
1467       if($ldap->count()){
1468         unset($tmp[$key]);
1469       }
1470     }
1472     /* Format result as requested */
1473     if($raw) {
1474       return($tmp);
1475     }else{
1476       $tmp2 = array();
1477       foreach($tmp as $key => $entry){
1478         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1479       }
1480     }
1481     return($tmp2);
1482   } 
1485   /* Restore selected snapshot */
1486   function restore_snapshot($dn)
1487   {
1488     if(!$this->snapshotEnabled()) return(array());
1490     $ldap= $this->config->get_ldap_link();
1491     $ldap->cd($this->config->current['BASE']);
1492     $cfg= &$this->config->current;
1494     /* check if there are special server configurations for snapshots */
1495     if($this->config->get_cfg_value("snapshotURI") == ""){
1496       $ldap_to      = $ldap;
1497     }else{
1498       $server         = $this->config->get_cfg_value("snapshotURI");
1499       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1500       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1501       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1502       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1503       $ldap_to -> cd($snapldapbase);
1504       if (!$ldap_to->success()){
1505         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1506       }
1507     }
1509     /* Get the snapshot */ 
1510     $ldap_to->cat($dn);
1511     $restoreObject = $ldap_to->fetch();
1513     /* Prepare import string */
1514     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1516     /* Import the given data */
1517     $err = "";
1518     $ldap->import_complete_ldif($data,$err,false,false);
1519     if (!$ldap->success()){
1520       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, "", get_class()));
1521     }
1522   }
1525   function showSnapshotDialog($base,$baseSuffixe,&$parent)
1526   {
1527     $once = true;
1528     $ui = get_userinfo();
1529     $this->parent = $parent;
1531     foreach($_POST as $name => $value){
1533       /* Create a new snapshot, display a dialog */
1534       if(preg_match("/^CreateSnapShotDialog_[^_]*_[xy]$/",$name) && $once){
1536                           $entry = base64_decode(preg_replace("/^CreateSnapShotDialog_([^_]*)_[xy]$/","\\1",$name));
1537         $once = false;
1538         $entry = preg_replace("/^CreateSnapShotDialog_/","",$entry);
1540         if(!empty($entry) && $ui->allow_snapshot_create($entry,$this->parent->acl_module)){
1541           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1542         }else{
1543           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to create a snapshot for %s."),$entry),ERROR_DIALOG);
1544         }
1545       }  
1546   
1547       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1548       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1549         $once = false;
1550         $entry = base64_decode(preg_replace("/^RestoreSnapShotDialog_([^_]*)_[xy]$/i","\\1",$name));
1551         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1552           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1553           $this->snapDialog->display_restore_dialog = true;
1554         }else{
1555           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1556         }
1557       }
1559       /* Restore one of the already deleted objects */
1560       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1561           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1562         $once = false;
1564         if($ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1565           $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1566           $this->snapDialog->set_snapshot_bases($baseSuffixe);
1567           $this->snapDialog->display_restore_dialog      = true;
1568           $this->snapDialog->display_all_removed_objects  = true;
1569         }else{
1570           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$base),ERROR_DIALOG);
1571         }
1572       }
1574       /* Restore selected snapshot */
1575       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1576         $once = false;
1577         $entry = base64_decode(preg_replace("/^RestoreSnapShot_([^_]*)_[xy]$/i","\\1",$name));
1579         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1580           $this->restore_snapshot($entry);
1581           $this->snapDialog = NULL;
1582         }else{
1583           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1584         }
1585       }
1586     }
1588     /* Create a new snapshot requested, check
1589        the given attributes and create the snapshot*/
1590     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1591       $this->snapDialog->save_object();
1592       $msgs = $this->snapDialog->check();
1593       if(count($msgs)){
1594         foreach($msgs as $msg){
1595           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
1596         }
1597       }else{
1598         $this->dn =  $this->snapDialog->dn;
1599         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1600         $this->snapDialog = NULL;
1601       }
1602     }
1604     /* Restore is requested, restore the object with the posted dn .*/
1605     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1606     }
1608     if(isset($_POST['CancelSnapshot'])){
1609       $this->snapDialog = NULL;
1610     }
1612     if(is_object($this->snapDialog )){
1613       $this->snapDialog->save_object();
1614       return($this->snapDialog->execute());
1615     }
1616   }
1619   static function plInfo()
1620   {
1621     return array();
1622   }
1625   function set_acl_base($base)
1626   {
1627     $this->acl_base= $base;
1628   }
1631   function set_acl_category($category)
1632   {
1633     $this->acl_category= "$category/";
1634   }
1637   function acl_is_writeable($attribute,$skip_write = FALSE)
1638   {
1639     if($this->read_only) return(FALSE);
1640     $ui= get_userinfo();
1641     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1642   }
1645   function acl_is_readable($attribute)
1646   {
1647     $ui= get_userinfo();
1648     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1649   }
1652   function acl_is_createable($base ="")
1653   {
1654     if($this->read_only) return(FALSE);
1655     $ui= get_userinfo();
1656     if($base == "") $base = $this->acl_base;
1657     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1658   }
1661   function acl_is_removeable($base ="")
1662   {
1663     if($this->read_only) return(FALSE);
1664     $ui= get_userinfo();
1665     if($base == "") $base = $this->acl_base;
1666     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1667   }
1670   function acl_is_moveable($base = "")
1671   {
1672     if($this->read_only) return(FALSE);
1673     $ui= get_userinfo();
1674     if($base == "") $base = $this->acl_base;
1675     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1676   }
1679   function acl_have_any_permissions()
1680   {
1681   }
1684   function getacl($attribute,$skip_write= FALSE)
1685   {
1686     $ui= get_userinfo();
1687     $skip_write |= $this->read_only;
1688     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1689   }
1692   /*! \brief    Returns a list of all available departments for this object.  
1693                 If this object is new, all departments we are allowed to create a new user in are returned.
1694                 If this is an existing object, return all deps. we are allowed to move tis object too.
1696       @return   Array [dn] => "..name"  // All deps. we are allowed to act on.
1697   */
1698   function get_allowed_bases()
1699   {
1700     $ui = get_userinfo();
1701     $deps = array();
1703     /* Is this a new object ? Or just an edited existing object */
1704     if(!$this->initially_was_account && $this->is_account){
1705       $new = true;
1706     }else{
1707       $new = false;
1708     }
1710     foreach($this->config->idepartments as $dn => $name){
1711       if($new && $this->acl_is_createable($dn)){
1712         $deps[$dn] = $name;
1713       }elseif(!$new && $this->acl_is_moveable($dn)){
1714         $deps[$dn] = $name;
1715       }
1716     }
1718     /* Add current base */      
1719     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1720       $deps[$this->base] = $this->config->idepartments[$this->base];
1721     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1723     }else{
1724       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1725     }
1726     return($deps);
1727   }
1730   /* This function updates ACL settings if $old_dn was used.
1731    *  $old_dn   specifies the actually used dn
1732    *  $new_dn   specifies the destiantion dn
1733    */
1734   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1735   {
1736     /* Check if old_dn is empty. This should never happen */
1737     if(empty($old_dn) || empty($new_dn)){
1738       trigger_error("Failed to check acl dependencies, wrong dn given.");
1739       return;
1740     }
1742     /* Update userinfo if necessary */
1743     $ui = session::global_get('ui');
1744     if($ui->dn == $old_dn){
1745       $ui->dn = $new_dn;
1746       session::global_set('ui',$ui);
1747       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1748     }
1750     /* Object was moved, ensure that all acls will be moved too */
1751     if($new_dn != $old_dn && $old_dn != "new"){
1753       /* get_ldap configuration */
1754       $update = array();
1755       $ldap = $this->config->get_ldap_link();
1756       $ldap->cd ($this->config->current['BASE']);
1757       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1758       while($attrs = $ldap->fetch()){
1759         $acls = array();
1760         $found = false;
1761         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1762           $acl_parts = split(":",$attrs['gosaAclEntry'][$i]);
1764           /* Roles uses antoher data storage order, members are stored int the third part, 
1765              while the members in direct ACL assignments are stored in the second part.
1766            */
1767           $id = ($acl_parts[1] == "role") ? 3 : 2;
1769           /* Update member entries to use $new_dn instead of old_dn
1770            */
1771           $members = explode(",",$acl_parts[$id]);
1772           foreach($members as $key => $member){
1773             $member = base64_decode($member);
1774             if($member == $old_dn){
1775               $members[$key] = base64_encode($new_dn);
1776               $found = TRUE;
1777             }
1778           } 
1780           /* Check if the selected role has to updated
1781            */
1782           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1783             $acl_parts[2] = base64_encode($new_dn);
1784             $found = TRUE;
1785           }
1787           /* Build new acl string */ 
1788           $acl_parts[$id] = implode($members,",");
1789           $acls[] = implode($acl_parts,":");
1790         }
1792         /* Acls for this object must be adjusted */
1793         if($found){
1795           $debug_info=  _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1796             $old_dn."</b><br>&nbsp;-"._("to")."&nbsp;<b>".$new_dn."</b><br>";
1797           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1799           $update[$attrs['dn']] =array();
1800           foreach($acls as $acl){
1801             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1802           }
1803         }
1804       }
1806       /* Write updated acls */
1807       foreach($update as $dn => $attrs){
1808         $ldap->cd($dn);
1809         $ldap->modify($attrs);
1810       }
1811     }
1812   }
1814   
1816   /* This function enables the entry Serial ID check.
1817    * If an entry was edited while we have edited the entry too,
1818    *  an error message will be shown. 
1819    * To configure this check correctly read the FAQ.
1820    */    
1821   function enable_CSN_check()
1822   {
1823     $this->CSN_check_active =TRUE;
1824     $this->entryCSN = getEntryCSN($this->dn);
1825   }
1828   /*! \brief  Prepares the plugin to be used for multiple edit
1829    *          Update plugin attributes with given array of attribtues.
1830    *  @param  array   Array with attributes that must be updated.
1831    */
1832   function init_multiple_support($attrs,$all)
1833   {
1834     $ldap= $this->config->get_ldap_link();
1835     $this->multi_attrs    = $attrs;
1836     $this->multi_attrs_all= $all;
1838     /* Copy needed attributes */
1839     foreach ($this->attributes as $val){
1840       $found= array_key_ics($val, $this->multi_attrs);
1841  
1842       if ($found != ""){
1843         if(isset($this->multi_attrs["$val"][0])){
1844           $this->$val= $this->multi_attrs["$val"][0];
1845         }
1846       }
1847     }
1848   }
1850  
1851   /*! \brief  Enables multiple support for this plugin
1852    */
1853   function enable_multiple_support()
1854   {
1855     $this->ignore_account = TRUE;
1856     $this->multiple_support_active = TRUE;
1857   }
1860   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1861       @return array Cotaining all mdofied values. 
1862    */
1863   function get_multi_edit_values()
1864   {
1865     $ret = array();
1866     foreach($this->attributes as $attr){
1867       if(in_array($attr,$this->multi_boxes)){
1868         $ret[$attr] = $this->$attr;
1869       }
1870     }
1871     return($ret);
1872   }
1874   
1875   /*! \brief  Update class variables with values collected by multiple edit.
1876    */
1877   function set_multi_edit_values($attrs)
1878   {
1879     foreach($attrs as $name => $value){
1880       $this->$name = $value;
1881     }
1882   }
1885   /*! \brief execute plugin
1887     Generates the html output for this node
1888    */
1889   function multiple_execute()
1890   {
1891     /* This one is empty currently. Fabian - please fill in the docu code */
1892     session::global_set('current_class_for_help',get_class($this));
1894     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1895     session::set('LOCK_VARS_TO_USE',array());
1896     session::set('LOCK_VARS_USED_GET',array());
1897     session::set('LOCK_VARS_USED_POST',array());
1898     session::set('LOCK_VARS_USED_REQUEST',array());
1899     
1900     return("Multiple edit is currently not implemented for this plugin.");
1901   }
1904   /*! \brief   Save HTML posted data to object for multiple edit
1905    */
1906   function multiple_save_object()
1907   {
1908     if(empty($this->entryCSN) && $this->CSN_check_active){
1909       $this->entryCSN = getEntryCSN($this->dn);
1910     }
1912     /* Save values to object */
1913     $this->multi_boxes = array();
1914     foreach ($this->attributes as $val){
1915   
1916       /* Get selected checkboxes from multiple edit */
1917       if(isset($_POST["use_".$val])){
1918         $this->multi_boxes[] = $val;
1919       }
1921       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
1923         /* Check for modifications */
1924         if (get_magic_quotes_gpc()) {
1925           $data= stripcslashes($_POST["$val"]);
1926         } else {
1927           $data= $this->$val = $_POST["$val"];
1928         }
1929         if ($this->$val != $data){
1930           $this->is_modified= TRUE;
1931         }
1932     
1933         /* IE post fix */
1934         if(isset($data[0]) && $data[0] == chr(194)) {
1935           $data = "";  
1936         }
1937         $this->$val= $data;
1938       }
1939     }
1940   }
1943   /*! \brief  Returns all attributes of this plugin, 
1944                to be able to detect multiple used attributes 
1945                in multi_plugg::detect_multiple_used_attributes().
1946       @return array Attributes required for intialization of multi_plug
1947    */
1948   public function get_multi_init_values()
1949   {
1950     $attrs = $this->attrs;
1951     return($attrs);
1952   }
1955   /*! \brief  Check given values in multiple edit
1956       @return array Error messages
1957    */
1958   function multiple_check()
1959   {
1960     $message = plugin::check();
1961     return($message);
1962   }
1965   /*! \brief  Returns the snapshot header part for "Actions" menu in management dialogs 
1966       @param  $layer_menu  
1967    */   
1968   function get_snapshot_header($base,$category)
1969   {
1970     $str = "";
1971     $ui = get_userinfo();
1972     if($this->snapshotEnabled() && $ui->allow_snapshot_restore($base,$category)){
1974       $ok = false;
1975       foreach($this->get_used_snapshot_bases() as $base){
1976         $ok |= count($this->getAllDeletedSnapshots($base)) >= 1 ;
1977       }
1979       if($ok){
1980         $str = "..|<img class='center' src='images/lists/restore.png' ".
1981           "alt='"._("Restore")."'>&nbsp;"._("Restore").                       "|RestoreDeletedSnapShot|\n";
1982       }else{
1983         $str = "..|<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;"._("Restore")."||\n";
1984       }
1985     }
1986     return($str);
1987   }
1990   function get_snapshot_action($base,$category)
1991   {
1992     $str= ""; 
1993     $ui = get_userinfo();
1994     if($this->snapshotEnabled()){
1995       if ($ui->allow_snapshot_restore($base,$category)){
1997         if(count($this->Available_SnapsShots($base))){
1998           $str.= "<input class='center' type='image' src='images/lists/restore.png'
1999             alt='"._("Restore snapshot")."' name='RestoreSnapShotDialog_".base64_encode($base)."' title='"._("Restore snapshot")."'>&nbsp;";
2000         } else {
2001           $str = "<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;";
2002         }
2003       }
2004       if($ui->allow_snapshot_create($base,$category)){
2005         $str.= "<input class='center' type='image' src='images/snapshot.png'
2006           alt='"._("Create snapshot")."' name='CreateSnapShotDialog_".base64_encode($base)."' 
2007           title='"._("Create a new snapshot from this object")."'>&nbsp;";
2008       }else{
2009         $str = "<img class='center' src='images/empty.png' alt=' '>&nbsp;";
2010       }
2011     }
2013     return($str);
2014   }
2017   function get_copypaste_action($base,$category,$class,$copy = TRUE, $cut = TRUE)
2018   {
2019     $ui = get_userinfo();
2020     $action = "";
2021     if($this->CopyPasteHandler){
2022       if($cut){
2023         if($ui->is_cutable($base,$category,$class)){
2024           $action .= "<input class='center' type='image'
2025             src='images/lists/cut.png' alt='"._("cut")."' name='cut_%KEY%' title='"._("Cut this entry")."'>&nbsp;";
2026         }else{
2027           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
2028         }
2029       }
2030       if($copy){
2031         if($ui->is_copyable($base,$category,$class)){
2032           $action.= "<input class='center' type='image'
2033             src='images/lists/copy.png' alt='"._("copy")."' name='copy_%KEY%' title='"._("Copy this entry")."'>&nbsp;";
2034         }else{
2035           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
2036         }
2037       }
2038     }
2040     return($action); 
2041   }
2044   function get_copypaste_header($base,$category,$copy = TRUE, $cut = TRUE)
2045   {
2046     $s = "";
2047     $ui =get_userinfo();
2049     if(!is_array($category)){
2050       $category = array($category);
2051     }
2053     /* Check permissions for each category, if there is at least one category which 
2054         support read or paste permissions for the given base, then display the specific actions.
2055      */
2056     $readable = $pasteable = false;
2057     foreach($category as $cat){
2058       $readable= $readable || preg_match('/r/', $ui->get_category_permissions($base, $cat));
2059       $pasteable= $pasteable || $ui->is_pasteable($base, $cat) == 1;
2060     }
2061   
2062     if(($cut || $copy) && isset($this->CopyPasteHandler) && is_object($this->CopyPasteHandler)){
2063       if($readable){
2064         $s.= "..|---|\n";
2065         if($copy){
2066           $s.= "..|<img src='images/lists/copy.png' alt='' border='0' class='center'>".
2067             "&nbsp;"._("Copy")."|"."multiple_copy_systems|\n";
2068         }
2069         if($cut){
2070           $s.= "..|<img src='images/lists/cut.png' alt='' border='0' class='center'>".
2071             "&nbsp;"._("Cut")."|"."multiple_cut_systems|\n";
2072         }
2073       }
2075       if($pasteable){
2076         if($this->CopyPasteHandler->entries_queued()){
2077           $img = "<img border='0' class='center' src='images/lists/paste.png' alt=''>";
2078           $s.="..|".$img."&nbsp;"._("Paste")."|editPaste|\n";
2079         }else{
2080           $img = "<img border='0' class='center' src='images/lists/paste-grey.png' alt=''>";
2081           $s.="..|".$img."&nbsp;"._("Paste")."\n";
2082         }
2083       }
2084     }
2085     return($s);
2086   }
2089   function get_used_snapshot_bases()
2090   {
2091      return(array());
2092   }
2094   function is_modal_dialog()
2095   {
2096     return(isset($this->dialog) && $this->dialog);
2097   }
2100 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2101 ?>