Code

PHP5 flush
[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 __construct(&$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=... */
891     if(!is_array($new['objectClass'])) $new['objectClass'] = array($new['objectClass']);
893     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
894       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
895     }
896     $ldap->cd($dst_dn);
897     $ldap->add($new);
899     if (!$ldap->success()){
900       trigger_error("Trying to save $dst_dn failed.",
901           E_USER_WARNING);
902       return(FALSE);
903     }
904     return(TRUE);
905   }
908   /* This is a workaround function. */
909   function copy($src_dn, $dst_dn)
910   {
911     /* Rename dn in possible object groups */
912     $ldap= $this->config->get_ldap_link();
913     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::prepare4filter($src_dn).'))',
914         array('cn'));
915     while ($attrs= $ldap->fetch()){
916       $og= new ogroup($this->config, $ldap->getDN());
917       unset($og->member[$src_dn]);
918       $og->member[$dst_dn]= $dst_dn;
919       $og->save ();
920     }
922     $ldap->cat($dst_dn);
923     $attrs= $ldap->fetch();
924     if (count($attrs)){
925       trigger_error("Trying to overwrite ".LDAP::fix($dst_dn).", which already exists.",
926           E_USER_WARNING);
927       return (FALSE);
928     }
930     $ldap->cat($src_dn);
931     $attrs= $ldap->fetch();
932     if (!count($attrs)){
933       trigger_error("Trying to move ".LDAP::fix($src_dn).", which does not seem to exist.",
934           E_USER_WARNING);
935       return (FALSE);
936     }
938     $ldap->cd($src_dn);
939     $ldap->search("objectClass=*",array("dn"));
940     while($attrs = $ldap->fetch()){
941       $src = $attrs['dn'];
942       $dst = preg_replace("/".preg_quote($src_dn, '/')."$/",$dst_dn,$attrs['dn']);
943       $this->_copy($src,$dst);
944     }
945     return (TRUE);
946   }
950   /*! \brief  Move a given ldap object indentified by $src_dn   \
951                to the given destination $dst_dn   \
952               * Ensure that all references are updated (ogroups) \
953               * Update ACLs   \
954               * Update accessTo   \
955       @param  String  The source dn.
956       @param  String  The destination dn.
957       @return Boolean TRUE on success else FALSE.
958    */
959   function rename($src_dn, $dst_dn)
960   {
961     $start = microtime(1);
963     /* Try to move the source entry to the destination position */
964     $ldap = $this->config->get_ldap_link();
965     $ldap->cd($this->config->current['BASE']);
966     $ldap->create_missing_trees(preg_replace("/^[^,]+,/","",$dst_dn));
967     if (!$ldap->rename_dn($src_dn,$dst_dn)){
968 #      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $src_dn, "", get_class()));
969       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());
970       @DEBUG(DEBUG_LDAP,__LINE__,__FUNCTION__,__FILE__,"Rename failed FROM: $src_dn  -- TO:  $dst_dn", 
971           "Ldap Protocol v3 implementation error, falling back to maunal method.");
972       return(FALSE);
973     }
975     /* Get list of users,groups and roles within this tree,
976         maybe we have to update ACL references.
977      */
978     $leaf_objs = get_list("(|(objectClass=posixGroup)(objectClass=gosaAccount)(objectClass=gosaRole))",array("all"),$dst_dn,
979           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
980     foreach($leaf_objs as $obj){
981       $new_dn = $obj['dn'];
982       $old_dn = preg_replace("/".preg_quote(LDAP::convert($dst_dn), '/')."$/i",$src_dn,LDAP::convert($new_dn));
983       $this->update_acls($old_dn,$new_dn); 
984     }
986     // Migrate objectgroups if needed
987     $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);
989     // Walk through all objectGroups
990     foreach($ogroups as $ogroup){
991       // Migrate old to new dn
992       $o_ogroup= new ogroup($this->config,$ogroup['dn']);
993       if (isset($o_group->member[$src_dn])) {
994         unset($o_ogroup->member[$src_dn]);
995       }
996       $o_ogroup->member[$dst_dn]= $dst_dn;
997       
998       // Save object group
999       $o_ogroup->save();
1000     }
1002     // Migrate rfc groups if needed
1003     $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);
1005     // Walk through all POSIX groups
1006     foreach($groups as $group){
1008       // Migrate old to new dn
1009       $o_group= new group($this->config,$group['dn']);
1010       $o_group->save();
1011     }
1013     /* Update roles to use the new entry dn */
1014     $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);
1016     // Walk through all roles
1017     foreach($roles as $role){
1018       $role = new roleGeneric($this->config,$role['dn']);
1019       $key= array_search($src_dn, $role->roleOccupant);      
1020       if($key !== FALSE){
1021         $role->roleOccupant[$key] = $dst_dn;
1022         $role->save();
1023       }
1024     }
1025  
1026     /* Check if there are gosa departments moved. 
1027        If there were deps moved, the force reload of config->deps.
1028      */
1029     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
1030           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
1031   
1032     if(count($leaf_deps)){
1033       $this->config->get_departments();
1034       $this->config->make_idepartments();
1035       session::global_set("config",$this->config);
1036       $ui =get_userinfo();
1037       $ui->reset_acl_cache();
1038     }
1040     return(TRUE); 
1041   }
1045   function move($src_dn, $dst_dn)
1046   {
1047     /* Do not copy if only upper- lowercase has changed */
1048     if(strtolower($src_dn) == strtolower($dst_dn)){
1049       return(TRUE);
1050     }
1052     
1053     /* Try to move the entry instead of copy & delete
1054      */
1055     if(TRUE){
1057       /* Try to move with ldap routines, if this was not successfull
1058           fall back to the old style copy & remove method 
1059        */
1060       if($this->rename($src_dn, $dst_dn)){
1061         return(TRUE);
1062       }else{
1063         // See code below.
1064       }
1065     }
1067     /* Copy source to destination */
1068     if (!$this->copy($src_dn, $dst_dn)){
1069       return (FALSE);
1070     }
1072     /* Delete source */
1073     $ldap= $this->config->get_ldap_link();
1074     $ldap->rmdir_recursive($src_dn);
1075     if (!$ldap->success()){
1076       trigger_error("Trying to delete $src_dn failed.",
1077           E_USER_WARNING);
1078       return (FALSE);
1079     }
1081     return (TRUE);
1082   }
1085   /* Move/Rename complete trees */
1086   function recursive_move($src_dn, $dst_dn)
1087   {
1088     /* Check if the destination entry exists */
1089     $ldap= $this->config->get_ldap_link();
1091     /* Check if destination exists - abort */
1092     $ldap->cat($dst_dn, array('dn'));
1093     if ($ldap->fetch()){
1094       trigger_error("recursive_move $dst_dn already exists.",
1095           E_USER_WARNING);
1096       return (FALSE);
1097     }
1099     $this->copy($src_dn, $dst_dn);
1101     /* Remove src_dn */
1102     $ldap->cd($src_dn);
1103     $ldap->recursive_remove($src_dn);
1104     return (TRUE);
1105   }
1108   function handle_post_events($mode, $add_attrs= array())
1109   {
1110     switch ($mode){
1111       case "add":
1112         $this->postcreate($add_attrs);
1113       break;
1115       case "modify":
1116         $this->postmodify($add_attrs);
1117       break;
1119       case "remove":
1120         $this->postremove($add_attrs);
1121       break;
1122     }
1123   }
1126   function saveCopyDialog(){
1127   }
1130   function getCopyDialog(){
1131     return(array("string"=>"","status"=>""));
1132   }
1135   function PrepareForCopyPaste($source)
1136   {
1137     $todo = $this->attributes;
1138     if(isset($this->CopyPasteVars)){
1139       $todo = array_merge($todo,$this->CopyPasteVars);
1140     }
1142     if(count($this->objectclasses)){
1143       $this->is_account = TRUE;
1144       foreach($this->objectclasses as $class){
1145         if(!in_array($class,$source['objectClass'])){
1146           $this->is_account = FALSE;
1147         }
1148       }
1149     }
1151     foreach($todo as $var){
1152       if (isset($source[$var])){
1153         if(isset($source[$var]['count'])){
1154           if($source[$var]['count'] > 1){
1155             $tmp= $source[$var];
1156             unset($tmp['count']);
1157             $this->$var = $tmp;
1158           }else{
1159             $this->$var = $source[$var][0];
1160           }
1161         }else{
1162           $this->$var= $source[$var];
1163         }
1164       }
1165     }
1166   }
1168   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1169   {
1170     /* Skip tagging? 
1171        If this is called from departmentGeneric, we have to skip this
1172         tagging procedure. 
1173      */
1174     if($this->skipTagging){
1175       return;
1176     }
1178     /* No dn? Self-operation... */
1179     if ($dn == ""){
1180       $dn= $this->dn;
1182       /* No tag? Find it yourself... */
1183       if ($tag == ""){
1184         $len= strlen($dn);
1186         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1187         $relevant= array();
1188         foreach ($this->config->adepartments as $key => $ntag){
1190           /* This one is bigger than our dn, its not relevant... */
1191           if ($len < strlen($key)){
1192             continue;
1193           }
1195           /* This one matches with the latter part. Break and don't fix this entry */
1196           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
1197             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1198             $relevant[strlen($key)]= $ntag;
1199             continue;
1200           }
1202         }
1204         /* If we've some relevant tags to set, just get the longest one */
1205         if (count($relevant)){
1206           ksort($relevant);
1207           $tmp= array_keys($relevant);
1208           $idx= end($tmp);
1209           $tag= $relevant[$idx];
1210           $this->gosaUnitTag= $tag;
1211         }
1212       }
1213     }
1214   
1215     /* Remove tags that may already be here... */
1216     remove_objectClass("gosaAdministrativeUnitTag", $at);
1217     if (isset($at['gosaUnitTag'])){
1218         unset($at['gosaUnitTag']);
1219     }
1221     /* Set tag? */
1222     if ($tag != ""){
1223       add_objectClass("gosaAdministrativeUnitTag", $at);
1224       $at['gosaUnitTag']= $tag;
1225     }
1227     /* Initially this object was tagged. 
1228        - But now, it is no longer inside a tagged department. 
1229        So force the remove of the tag.
1230        (objectClass was already removed obove)
1231      */
1232     if($tag == "" && $this->gosaUnitTag){
1233       $at['gosaUnitTag'] = array();
1234     }
1235   }
1238   /* Add possibility to stop remove process */
1239   function allow_remove()
1240   {
1241     $reason= "";
1242     return $reason;
1243   }
1246   /* Create a snapshot of the current object */
1247   function create_snapshot($type= "snapshot", $description= array())
1248   {
1250     /* Check if snapshot functionality is enabled */
1251     if(!$this->snapshotEnabled()){
1252       return;
1253     }
1255     /* Get configuration from gosa.conf */
1256     $config = $this->config;
1258     /* Create lokal ldap connection */
1259     $ldap= $this->config->get_ldap_link();
1260     $ldap->cd($this->config->current['BASE']);
1262     /* check if there are special server configurations for snapshots */
1263     if($config->get_cfg_value("snapshotURI") == ""){
1265       /* Source and destination server are both the same, just copy source to dest obj */
1266       $ldap_to      = $ldap;
1267       $snapldapbase = $this->config->current['BASE'];
1269     }else{
1270       $server         = $config->get_cfg_value("snapshotURI");
1271       $user           = $config->get_cfg_value("snapshotAdminDn");
1272       $password       = $this->config->get_credentials($config->get_cfg_value("snapshotAdminPassword"));
1273       $snapldapbase   = $config->get_cfg_value("snapshotBase");
1275       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1276       $ldap_to -> cd($snapldapbase);
1278       if (!$ldap_to->success()){
1279         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1280       }
1282     }
1284     /* check if the dn exists */ 
1285     if ($ldap->dn_exists($this->dn)){
1287       /* Extract seconds & mysecs, they are used as entry index */
1288       list($usec, $sec)= explode(" ", microtime());
1290       /* Collect some infos */
1291       $base           = $this->config->current['BASE'];
1292       $snap_base      = $config->get_cfg_value("snapshotBase");
1293       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1294       $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1296       /* Create object */
1297 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1298       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1299       $newName          = str_replace(".", "", $sec."-".$usec);
1300       $target= array();
1301       $target['objectClass']            = array("top", "gosaSnapshotObject");
1302       $target['gosaSnapshotData']       = gzcompress($data, 6);
1303       $target['gosaSnapshotType']       = $type;
1304       $target['gosaSnapshotDN']         = $this->dn;
1305       $target['description']            = $description;
1306       $target['gosaSnapshotTimestamp']  = $newName;
1308       /* Insert the new snapshot 
1309          But we have to check first, if the given gosaSnapshotTimestamp
1310          is already used, in this case we should increment this value till there is 
1311          an unused value. */ 
1312       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1313       $ldap_to->cat($new_dn);
1314       while($ldap_to->count()){
1315         $ldap_to->cat($new_dn);
1316         $newName = str_replace(".", "", $sec."-".($usec++));
1317         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1318         $target['gosaSnapshotTimestamp']  = $newName;
1319       } 
1321       /* Inset this new snapshot */
1322       $ldap_to->cd($snapldapbase);
1323       $ldap_to->create_missing_trees($snapldapbase);
1324       $ldap_to->create_missing_trees($new_base);
1325       $ldap_to->cd($new_dn);
1326       $ldap_to->add($target);
1327       if (!$ldap_to->success()){
1328         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $new_dn, LDAP_ADD, get_class()));
1329       }
1331       if (!$ldap->success()){
1332         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $new_base, "", get_class()));
1333       }
1335     }
1336   }
1338   function remove_snapshot($dn)
1339   {
1340     $ui       = get_userinfo();
1341     $old_dn   = $this->dn; 
1342     $this->dn = $dn;
1343     $ldap = $this->config->get_ldap_link();
1344     $ldap->cd($this->config->current['BASE']);
1345     $ldap->rmdir_recursive($this->dn);
1346     if(!$ldap->success()){
1347       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn));
1348     }
1349     $this->dn = $old_dn;
1350   }
1353   /* returns true if snapshots are enabled, and false if it is disalbed
1354      There will also be some errors psoted, if the configuration failed */
1355   function snapshotEnabled()
1356   {
1357     return $this->config->snapshotEnabled();
1358   }
1361   /* Return available snapshots for the given base 
1362    */
1363   function Available_SnapsShots($dn,$raw = false)
1364   {
1365     if(!$this->snapshotEnabled()) return(array());
1367     /* Create an additional ldap object which
1368        points to our ldap snapshot server */
1369     $ldap= $this->config->get_ldap_link();
1370     $ldap->cd($this->config->current['BASE']);
1371     $cfg= &$this->config->current;
1373     /* check if there are special server configurations for snapshots */
1374     if($this->config->get_cfg_value("snapshotURI") == ""){
1375       $ldap_to      = $ldap;
1376     }else{
1377       $server         = $this->config->get_cfg_value("snapshotURI");
1378       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1379       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1380       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1381       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1382       $ldap_to -> cd($snapldapbase);
1383       if (!$ldap_to->success()){
1384         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1385       }
1386     }
1388     /* Prepare bases and some other infos */
1389     $base           = $this->config->current['BASE'];
1390     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1391     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1392     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1393     $tmp            = array(); 
1395     /* Fetch all objects with  gosaSnapshotDN=$dn */
1396     $ldap_to->cd($new_base);
1397     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1398         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1400     /* Put results into a list and add description if missing */
1401     while($entry = $ldap_to->fetch()){ 
1402       if(!isset($entry['description'][0])){
1403         $entry['description'][0]  = "";
1404       }
1405       $tmp[] = $entry; 
1406     }
1408     /* Return the raw array, or format the result */
1409     if($raw){
1410       return($tmp);
1411     }else{  
1412       $tmp2 = array();
1413       foreach($tmp as $entry){
1414         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1415       }
1416     }
1417     return($tmp2);
1418   }
1421   function getAllDeletedSnapshots($base_of_object,$raw = false)
1422   {
1423     if(!$this->snapshotEnabled()) return(array());
1425     /* Create an additional ldap object which
1426        points to our ldap snapshot server */
1427     $ldap= $this->config->get_ldap_link();
1428     $ldap->cd($this->config->current['BASE']);
1429     $cfg= &$this->config->current;
1431     /* check if there are special server configurations for snapshots */
1432     if($this->config->get_cfg_value("snapshotURI") == ""){
1433       $ldap_to      = $ldap;
1434     }else{
1435       $server         = $this->config->get_cfg_value("snapshotURI");
1436       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1437       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1438       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1439       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1440       $ldap_to -> cd($snapldapbase);
1441       if (!$ldap_to->success()){
1442         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1443       }
1444     }
1446     /* Prepare bases */ 
1447     $base           = $this->config->current['BASE'];
1448     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1449     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1451     /* Fetch all objects and check if they do not exist anymore */
1452     $ui = get_userinfo();
1453     $tmp = array();
1454     $ldap_to->cd($new_base);
1455     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1456     while($entry = $ldap_to->fetch()){
1458       $chk =  str_replace($new_base,"",$entry['dn']);
1459       if(preg_match("/,ou=/",$chk)) continue;
1461       if(!isset($entry['description'][0])){
1462         $entry['description'][0]  = "";
1463       }
1464       $tmp[] = $entry; 
1465     }
1467     /* Check if entry still exists */
1468     foreach($tmp as $key => $entry){
1469       $ldap->cat($entry['gosaSnapshotDN'][0]);
1470       if($ldap->count()){
1471         unset($tmp[$key]);
1472       }
1473     }
1475     /* Format result as requested */
1476     if($raw) {
1477       return($tmp);
1478     }else{
1479       $tmp2 = array();
1480       foreach($tmp as $key => $entry){
1481         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1482       }
1483     }
1484     return($tmp2);
1485   } 
1488   /* Restore selected snapshot */
1489   function restore_snapshot($dn)
1490   {
1491     if(!$this->snapshotEnabled()) return(array());
1493     $ldap= $this->config->get_ldap_link();
1494     $ldap->cd($this->config->current['BASE']);
1495     $cfg= &$this->config->current;
1497     /* check if there are special server configurations for snapshots */
1498     if($this->config->get_cfg_value("snapshotURI") == ""){
1499       $ldap_to      = $ldap;
1500     }else{
1501       $server         = $this->config->get_cfg_value("snapshotURI");
1502       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1503       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1504       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1505       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1506       $ldap_to -> cd($snapldapbase);
1507       if (!$ldap_to->success()){
1508         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1509       }
1510     }
1512     /* Get the snapshot */ 
1513     $ldap_to->cat($dn);
1514     $restoreObject = $ldap_to->fetch();
1516     /* Prepare import string */
1517     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1519     /* Import the given data */
1520     $err = "";
1521     $ldap->import_complete_ldif($data,$err,false,false);
1522     if (!$ldap->success()){
1523       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, "", get_class()));
1524     }
1525   }
1528   function showSnapshotDialog($base,$baseSuffixe,&$parent)
1529   {
1530     $once = true;
1531     $ui = get_userinfo();
1532     $this->parent = $parent;
1534     foreach($_POST as $name => $value){
1536       /* Create a new snapshot, display a dialog */
1537       if(preg_match("/^CreateSnapShotDialog_[^_]*_[xy]$/",$name) && $once){
1539                           $entry = base64_decode(preg_replace("/^CreateSnapShotDialog_([^_]*)_[xy]$/","\\1",$name));
1540         $once = false;
1541         $entry = preg_replace("/^CreateSnapShotDialog_/","",$entry);
1543         if(!empty($entry) && $ui->allow_snapshot_create($entry,$this->parent->acl_module)){
1544           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1545         }else{
1546           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to create a snapshot for %s."),$entry),ERROR_DIALOG);
1547         }
1548       }  
1549   
1550       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1551       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1552         $once = false;
1553         $entry = base64_decode(preg_replace("/^RestoreSnapShotDialog_([^_]*)_[xy]$/i","\\1",$name));
1554         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1555           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1556           $this->snapDialog->display_restore_dialog = true;
1557         }else{
1558           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1559         }
1560       }
1562       /* Restore one of the already deleted objects */
1563       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1564           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1565         $once = false;
1567         if($ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1568           $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1569           $this->snapDialog->set_snapshot_bases($baseSuffixe);
1570           $this->snapDialog->display_restore_dialog      = true;
1571           $this->snapDialog->display_all_removed_objects  = true;
1572         }else{
1573           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$base),ERROR_DIALOG);
1574         }
1575       }
1577       /* Restore selected snapshot */
1578       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1579         $once = false;
1580         $entry = base64_decode(preg_replace("/^RestoreSnapShot_([^_]*)_[xy]$/i","\\1",$name));
1582         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1583           $this->restore_snapshot($entry);
1584           $this->snapDialog = NULL;
1585         }else{
1586           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1587         }
1588       }
1589     }
1591     /* Create a new snapshot requested, check
1592        the given attributes and create the snapshot*/
1593     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1594       $this->snapDialog->save_object();
1595       $msgs = $this->snapDialog->check();
1596       if(count($msgs)){
1597         foreach($msgs as $msg){
1598           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
1599         }
1600       }else{
1601         $this->dn =  $this->snapDialog->dn;
1602         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1603         $this->snapDialog = NULL;
1604       }
1605     }
1607     /* Restore is requested, restore the object with the posted dn .*/
1608     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1609     }
1611     if(isset($_POST['CancelSnapshot'])){
1612       $this->snapDialog = NULL;
1613     }
1615     if(is_object($this->snapDialog )){
1616       $this->snapDialog->save_object();
1617       return($this->snapDialog->execute());
1618     }
1619   }
1622   static function plInfo()
1623   {
1624     return array();
1625   }
1628   function set_acl_base($base)
1629   {
1630     $this->acl_base= $base;
1631   }
1634   function set_acl_category($category)
1635   {
1636     $this->acl_category= "$category/";
1637   }
1640   function acl_is_writeable($attribute,$skip_write = FALSE)
1641   {
1642     if($this->read_only) return(FALSE);
1643     $ui= get_userinfo();
1644     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1645   }
1648   function acl_is_readable($attribute)
1649   {
1650     $ui= get_userinfo();
1651     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1652   }
1655   function acl_is_createable($base ="")
1656   {
1657     if($this->read_only) return(FALSE);
1658     $ui= get_userinfo();
1659     if($base == "") $base = $this->acl_base;
1660     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1661   }
1664   function acl_is_removeable($base ="")
1665   {
1666     if($this->read_only) return(FALSE);
1667     $ui= get_userinfo();
1668     if($base == "") $base = $this->acl_base;
1669     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1670   }
1673   function acl_is_moveable($base = "")
1674   {
1675     if($this->read_only) return(FALSE);
1676     $ui= get_userinfo();
1677     if($base == "") $base = $this->acl_base;
1678     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1679   }
1682   function acl_have_any_permissions()
1683   {
1684   }
1687   function getacl($attribute,$skip_write= FALSE)
1688   {
1689     $ui= get_userinfo();
1690     $skip_write |= $this->read_only;
1691     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1692   }
1695   /*! \brief    Returns a list of all available departments for this object.  
1696                 If this object is new, all departments we are allowed to create a new user in are returned.
1697                 If this is an existing object, return all deps. we are allowed to move tis object too.
1699       @return   Array [dn] => "..name"  // All deps. we are allowed to act on.
1700   */
1701   function get_allowed_bases()
1702   {
1703     $ui = get_userinfo();
1704     $deps = array();
1706     /* Is this a new object ? Or just an edited existing object */
1707     if(!$this->initially_was_account && $this->is_account){
1708       $new = true;
1709     }else{
1710       $new = false;
1711     }
1713     foreach($this->config->idepartments as $dn => $name){
1714       if($new && $this->acl_is_createable($dn)){
1715         $deps[$dn] = $name;
1716       }elseif(!$new && $this->acl_is_moveable($dn)){
1717         $deps[$dn] = $name;
1718       }
1719     }
1721     /* Add current base */      
1722     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1723       $deps[$this->base] = $this->config->idepartments[$this->base];
1724     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1726     }else{
1727       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1728     }
1729     return($deps);
1730   }
1733   /* This function updates ACL settings if $old_dn was used.
1734    *  $old_dn   specifies the actually used dn
1735    *  $new_dn   specifies the destiantion dn
1736    */
1737   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1738   {
1739     /* Check if old_dn is empty. This should never happen */
1740     if(empty($old_dn) || empty($new_dn)){
1741       trigger_error("Failed to check acl dependencies, wrong dn given.");
1742       return;
1743     }
1745     /* Update userinfo if necessary */
1746     $ui = session::global_get('ui');
1747     if($ui->dn == $old_dn){
1748       $ui->dn = $new_dn;
1749       session::global_set('ui',$ui);
1750       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1751     }
1753     /* Object was moved, ensure that all acls will be moved too */
1754     if($new_dn != $old_dn && $old_dn != "new"){
1756       /* get_ldap configuration */
1757       $update = array();
1758       $ldap = $this->config->get_ldap_link();
1759       $ldap->cd ($this->config->current['BASE']);
1760       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1761       while($attrs = $ldap->fetch()){
1762         $acls = array();
1763         $found = false;
1764         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1765           $acl_parts = explode(":",$attrs['gosaAclEntry'][$i]);
1767           /* Roles uses antoher data storage order, members are stored int the third part, 
1768              while the members in direct ACL assignments are stored in the second part.
1769            */
1770           $id = ($acl_parts[1] == "role") ? 3 : 2;
1772           /* Update member entries to use $new_dn instead of old_dn
1773            */
1774           $members = explode(",",$acl_parts[$id]);
1775           foreach($members as $key => $member){
1776             $member = base64_decode($member);
1777             if($member == $old_dn){
1778               $members[$key] = base64_encode($new_dn);
1779               $found = TRUE;
1780             }
1781           } 
1783           /* Check if the selected role has to updated
1784            */
1785           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1786             $acl_parts[2] = base64_encode($new_dn);
1787             $found = TRUE;
1788           }
1790           /* Build new acl string */ 
1791           $acl_parts[$id] = implode($members,",");
1792           $acls[] = implode($acl_parts,":");
1793         }
1795         /* Acls for this object must be adjusted */
1796         if($found){
1798           $debug_info=  _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1799             $old_dn."</b><br>&nbsp;-"._("to")."&nbsp;<b>".$new_dn."</b><br>";
1800           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1802           $update[$attrs['dn']] =array();
1803           foreach($acls as $acl){
1804             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1805           }
1806         }
1807       }
1809       /* Write updated acls */
1810       foreach($update as $dn => $attrs){
1811         $ldap->cd($dn);
1812         $ldap->modify($attrs);
1813       }
1814     }
1815   }
1817   
1819   /* This function enables the entry Serial ID check.
1820    * If an entry was edited while we have edited the entry too,
1821    *  an error message will be shown. 
1822    * To configure this check correctly read the FAQ.
1823    */    
1824   function enable_CSN_check()
1825   {
1826     $this->CSN_check_active =TRUE;
1827     $this->entryCSN = getEntryCSN($this->dn);
1828   }
1831   /*! \brief  Prepares the plugin to be used for multiple edit
1832    *          Update plugin attributes with given array of attribtues.
1833    *  @param  array   Array with attributes that must be updated.
1834    */
1835   function init_multiple_support($attrs,$all)
1836   {
1837     $ldap= $this->config->get_ldap_link();
1838     $this->multi_attrs    = $attrs;
1839     $this->multi_attrs_all= $all;
1841     /* Copy needed attributes */
1842     foreach ($this->attributes as $val){
1843       $found= array_key_ics($val, $this->multi_attrs);
1844  
1845       if ($found != ""){
1846         if(isset($this->multi_attrs["$val"][0])){
1847           $this->$val= $this->multi_attrs["$val"][0];
1848         }
1849       }
1850     }
1851   }
1853  
1854   /*! \brief  Enables multiple support for this plugin
1855    */
1856   function enable_multiple_support()
1857   {
1858     $this->ignore_account = TRUE;
1859     $this->multiple_support_active = TRUE;
1860   }
1863   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1864       @return array Cotaining all mdofied values. 
1865    */
1866   function get_multi_edit_values()
1867   {
1868     $ret = array();
1869     foreach($this->attributes as $attr){
1870       if(in_array($attr,$this->multi_boxes)){
1871         $ret[$attr] = $this->$attr;
1872       }
1873     }
1874     return($ret);
1875   }
1877   
1878   /*! \brief  Update class variables with values collected by multiple edit.
1879    */
1880   function set_multi_edit_values($attrs)
1881   {
1882     foreach($attrs as $name => $value){
1883       $this->$name = $value;
1884     }
1885   }
1888   /*! \brief execute plugin
1890     Generates the html output for this node
1891    */
1892   function multiple_execute()
1893   {
1894     /* This one is empty currently. Fabian - please fill in the docu code */
1895     session::global_set('current_class_for_help',get_class($this));
1897     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1898     session::set('LOCK_VARS_TO_USE',array());
1899     session::set('LOCK_VARS_USED_GET',array());
1900     session::set('LOCK_VARS_USED_POST',array());
1901     session::set('LOCK_VARS_USED_REQUEST',array());
1902     
1903     return("Multiple edit is currently not implemented for this plugin.");
1904   }
1907   /*! \brief   Save HTML posted data to object for multiple edit
1908    */
1909   function multiple_save_object()
1910   {
1911     if(empty($this->entryCSN) && $this->CSN_check_active){
1912       $this->entryCSN = getEntryCSN($this->dn);
1913     }
1915     /* Save values to object */
1916     $this->multi_boxes = array();
1917     foreach ($this->attributes as $val){
1918   
1919       /* Get selected checkboxes from multiple edit */
1920       if(isset($_POST["use_".$val])){
1921         $this->multi_boxes[] = $val;
1922       }
1924       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
1926         /* Check for modifications */
1927         if (get_magic_quotes_gpc()) {
1928           $data= stripcslashes($_POST["$val"]);
1929         } else {
1930           $data= $this->$val = $_POST["$val"];
1931         }
1932         if ($this->$val != $data){
1933           $this->is_modified= TRUE;
1934         }
1935     
1936         /* IE post fix */
1937         if(isset($data[0]) && $data[0] == chr(194)) {
1938           $data = "";  
1939         }
1940         $this->$val= $data;
1941       }
1942     }
1943   }
1946   /*! \brief  Returns all attributes of this plugin, 
1947                to be able to detect multiple used attributes 
1948                in multi_plugg::detect_multiple_used_attributes().
1949       @return array Attributes required for intialization of multi_plug
1950    */
1951   public function get_multi_init_values()
1952   {
1953     $attrs = $this->attrs;
1954     return($attrs);
1955   }
1958   /*! \brief  Check given values in multiple edit
1959       @return array Error messages
1960    */
1961   function multiple_check()
1962   {
1963     $message = plugin::check();
1964     return($message);
1965   }
1968   /*! \brief  Returns the snapshot header part for "Actions" menu in management dialogs 
1969       @param  $layer_menu  
1970    */   
1971   function get_snapshot_header($base,$category)
1972   {
1973     $str = "";
1974     $ui = get_userinfo();
1975     if($this->snapshotEnabled() && $ui->allow_snapshot_restore($base,$category)){
1977       $ok = false;
1978       foreach($this->get_used_snapshot_bases() as $base){
1979         $ok |= count($this->getAllDeletedSnapshots($base)) >= 1 ;
1980       }
1982       if($ok){
1983         $str = "..|<img class='center' src='images/lists/restore.png' ".
1984           "alt='"._("Restore")."'>&nbsp;"._("Restore").                       "|RestoreDeletedSnapShot|\n";
1985       }else{
1986         $str = "..|<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;"._("Restore")."||\n";
1987       }
1988     }
1989     return($str);
1990   }
1993   function get_snapshot_action($base,$category)
1994   {
1995     $str= ""; 
1996     $ui = get_userinfo();
1997     if($this->snapshotEnabled()){
1998       if ($ui->allow_snapshot_restore($base,$category)){
2000         if(count($this->Available_SnapsShots($base))){
2001           $str.= "<input class='center' type='image' src='images/lists/restore.png'
2002             alt='"._("Restore snapshot")."' name='RestoreSnapShotDialog_".base64_encode($base)."' title='"._("Restore snapshot")."'>&nbsp;";
2003         } else {
2004           $str = "<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;";
2005         }
2006       }
2007       if($ui->allow_snapshot_create($base,$category)){
2008         $str.= "<input class='center' type='image' src='images/snapshot.png'
2009           alt='"._("Create snapshot")."' name='CreateSnapShotDialog_".base64_encode($base)."' 
2010           title='"._("Create a new snapshot from this object")."'>&nbsp;";
2011       }else{
2012         $str = "<img class='center' src='images/empty.png' alt=' '>&nbsp;";
2013       }
2014     }
2016     return($str);
2017   }
2020   function get_copypaste_action($base,$category,$class,$copy = TRUE, $cut = TRUE)
2021   {
2022     $ui = get_userinfo();
2023     $action = "";
2024     if($this->CopyPasteHandler){
2025       if($cut){
2026         if($ui->is_cutable($base,$category,$class)){
2027           $action .= "<input class='center' type='image'
2028             src='images/lists/cut.png' alt='"._("cut")."' name='cut_%KEY%' title='"._("Cut this entry")."'>&nbsp;";
2029         }else{
2030           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
2031         }
2032       }
2033       if($copy){
2034         if($ui->is_copyable($base,$category,$class)){
2035           $action.= "<input class='center' type='image'
2036             src='images/lists/copy.png' alt='"._("copy")."' name='copy_%KEY%' title='"._("Copy this entry")."'>&nbsp;";
2037         }else{
2038           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
2039         }
2040       }
2041     }
2043     return($action); 
2044   }
2047   function get_copypaste_header($base,$category,$copy = TRUE, $cut = TRUE)
2048   {
2049     $s = "";
2050     $ui =get_userinfo();
2052     if(!is_array($category)){
2053       $category = array($category);
2054     }
2056     /* Check permissions for each category, if there is at least one category which 
2057         support read or paste permissions for the given base, then display the specific actions.
2058      */
2059     $readable = $pasteable = false;
2060     foreach($category as $cat){
2061       $readable= $readable || preg_match('/r/', $ui->get_category_permissions($base, $cat));
2062       $pasteable= $pasteable || $ui->is_pasteable($base, $cat) == 1;
2063     }
2064   
2065     if(($cut || $copy) && isset($this->CopyPasteHandler) && is_object($this->CopyPasteHandler)){
2066       if($readable){
2067         $s.= "..|---|\n";
2068         if($copy){
2069           $s.= "..|<img src='images/lists/copy.png' alt='' border='0' class='center'>".
2070             "&nbsp;"._("Copy")."|"."multiple_copy_systems|\n";
2071         }
2072         if($cut){
2073           $s.= "..|<img src='images/lists/cut.png' alt='' border='0' class='center'>".
2074             "&nbsp;"._("Cut")."|"."multiple_cut_systems|\n";
2075         }
2076       }
2078       if($pasteable){
2079         if($this->CopyPasteHandler->entries_queued()){
2080           $img = "<img border='0' class='center' src='images/lists/paste.png' alt=''>";
2081           $s.="..|".$img."&nbsp;"._("Paste")."|editPaste|\n";
2082         }else{
2083           $img = "<img border='0' class='center' src='images/lists/paste-grey.png' alt=''>";
2084           $s.="..|".$img."&nbsp;"._("Paste")."\n";
2085         }
2086       }
2087     }
2088     return($s);
2089   }
2092   function get_used_snapshot_bases()
2093   {
2094      return(array());
2095   }
2097   function is_modal_dialog()
2098   {
2099     return(isset($this->dialog) && $this->dialog);
2100   }
2103 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2104 ?>