Code

Added pathNavigator
[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     // Ensure that we've a valid acl_category set.
149     if(empty($this->acl_category)){
150       $tmp = $this->plInfo();
151       if (isset($tmp['plCategory'])) {
152         $c = key($tmp['plCategory']);
153         if(is_numeric($c)){
154           $c = $tmp['plCategory'][0];
155         }
156         $this->acl_category = $c."/";
157       }
158     }
160     /* Handle new accounts, don't read information from LDAP */
161     if ($dn == "new"){
162       return;
163     }
165     /* Check if this entry was opened in read only mode */
166     if(isset($_POST['open_readonly'])){
167       if(session::global_is_set("LOCK_CACHE")){
168         $cache = &session::get("LOCK_CACHE");
169         if(isset($cache['READ_ONLY'][$this->dn])){
170           $this->read_only = TRUE;
171         }
172       }
173     }
175     /* Save current dn as acl_base */
176     $this->acl_base= $dn;
178     /* Get LDAP descriptor */
179     if ($dn !== NULL){
181       /* Load data to 'attrs' and save 'dn' */
182       if ($object !== NULL){
183         $this->attrs= $object->attrs;
184       } else {
185         $ldap= $this->config->get_ldap_link();
186         $ldap->cat ($dn);
187         $this->attrs= $ldap->fetch();
188       }
190       /* Copy needed attributes */
191       foreach ($this->attributes as $val){
192         $found= array_key_ics($val, $this->attrs);
193         if ($found != ""){
194           $this->$val= $found[0];
195         }
196       }
198       /* gosaUnitTag loading... */
199       if (isset($this->attrs['gosaUnitTag'][0])){
200         $this->gosaUnitTag= $this->attrs['gosaUnitTag'][0];
201       }
203       /* Set the template flag according to the existence of objectClass
204          gosaUserTemplate */
205       if (isset($this->attrs['objectClass'])){
206         if (in_array_ics ("gosaUserTemplate", $this->attrs['objectClass'])){
207           $this->is_template= TRUE;
208           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
209               "found", "Template check");
210         }
211       }
213       /* Is Account? */
214       $found= TRUE;
215       foreach ($this->objectclasses as $obj){
216         if (preg_match('/top/i', $obj)){
217           continue;
218         }
219         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
220           $found= FALSE;
221           break;
222         }
223       }
224       if ($found){
225         $this->is_account= TRUE;
226         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
227             "found", "Object check");
228       }
230       /* Prepare saved attributes */
231       $this->saved_attributes= $this->attrs;
232       foreach ($this->saved_attributes as $index => $value){
233         if (is_numeric($index)){
234           unset($this->saved_attributes[$index]);
235           continue;
236         }
238         if (!in_array_ics($index, $this->attributes) && strcasecmp('objectClass', $index)){
239           unset($this->saved_attributes[$index]);
240           continue;
241         }
243         if (isset($this->saved_attributes[$index][0])){
244           if(!isset($this->saved_attributes[$index]["count"])){
245             $this->saved_attributes[$index]["count"] = count($this->saved_attributes[$index]);
246           }
247           if($this->saved_attributes[$index]["count"] == 1){
248             $tmp= $this->saved_attributes[$index][0];
249             unset($this->saved_attributes[$index]);
250             $this->saved_attributes[$index]= $tmp;
251             continue;
252           }
253         }
254         unset($this->saved_attributes["$index"]["count"]);
255       }
257       if(isset($this->attrs['gosaUnitTag'])){
258         $this->saved_attributes['gosaUnitTag'] = $this->attrs['gosaUnitTag'][0];
259       }
260     }
262     /* Save initial account state */
263     $this->initially_was_account= $this->is_account;
264   }
267   /*! \brief Generates the html output for this node
268    */
269   function execute()
270   {
271     /* This one is empty currently. Fabian - please fill in the docu code */
272     session::global_set('current_class_for_help',get_class($this));
274     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
275     session::set('LOCK_VARS_TO_USE',array());
276     session::set('LOCK_VARS_USED_GET',array());
277     session::set('LOCK_VARS_USED_POST',array());
278     session::set('LOCK_VARS_USED_REQUEST',array());
280     pathNavigator::registerPlugin($this);
281   }
283   /*! \brief Removes object from parent
284    */
285   function remove_from_parent()
286   {
287     /* include global link_info */
288     $ldap= $this->config->get_ldap_link();
290     /* Get current objectClasses in order to add the required ones */
291     $ldap->cat($this->dn);
292     $tmp= $ldap->fetch ();
293     $oc= array();
294     if (isset($tmp['objectClass'])){
295       $oc= $tmp['objectClass'];
296       unset($oc['count']);
297     }
299     /* Remove objectClasses from entry */
300     $ldap->cd($this->dn);
301     $this->attrs= array();
302     $this->attrs['objectClass']= array_remove_entries_ics($this->objectclasses,$oc);
304     /* Unset attributes from entry */
305     foreach ($this->attributes as $val){
306       $this->attrs["$val"]= array();
307     }
309     /* Unset account info */
310     $this->is_account= FALSE;
312     /* Do not write in plugin base class, this must be done by
313        children, since there are normally additional attribs,
314        lists, etc. */
315     /*
316        $ldap->modify($this->attrs);
317      */
318   }
321   /*! \brief Save HTML posted data to object 
322    */
323   function save_object()
324   {
325     /* Update entry CSN if it is empty. */
326     if(empty($this->entryCSN) && $this->CSN_check_active){
327       $this->entryCSN = getEntryCSN($this->dn);
328     }
330     /* Save values to object */
331     foreach ($this->attributes as $val){
332       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
333         /* Check for modifications */
334         if (get_magic_quotes_gpc()) {
335           $data= stripcslashes($_POST["$val"]);
336         } else {
337           $data= $this->$val = $_POST["$val"];
338         }
339         if ($this->$val != $data){
340           $this->is_modified= TRUE;
341         }
342     
343         /* Okay, how can I explain this fix ... 
344          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
345          * So IE posts these 'unselectable' option, with value = chr(194) 
346          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
347          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
348          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
349          */
350         if(isset($data[0]) && $data[0] == chr(194)) {
351           $data = "";  
352         }
353         $this->$val= $data;
354       }
355     }
356   }
359   /*! \brief Save data to LDAP, depending on is_account we save or delete */
360   function save()
361   {
362     /* include global link_info */
363     $ldap= $this->config->get_ldap_link();
365     /* Save all plugins */
366     $this->entryCSN = "";
368     /* Start with empty array */
369     $this->attrs= array();
371     /* Get current objectClasses in order to add the required ones */
372     $ldap->cat($this->dn);
373     
374     $tmp= $ldap->fetch ();
376     $oc= array();
377     if (isset($tmp['objectClass'])){
378       $oc= $tmp["objectClass"];
379       $this->is_new= FALSE;
380       unset($oc['count']);
381     } else {
382       $this->is_new= TRUE;
383     }
385     /* Load (minimum) attributes, add missing ones */
386     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
388     /* Copy standard attributes */
389     foreach ($this->attributes as $val){
390       if ($this->$val != ""){
391         $this->attrs["$val"]= $this->$val;
392       } elseif (!$this->is_new) {
393         $this->attrs["$val"]= array();
394       }
395     }
397     /* Handle tagging */
398     $this->tag_attrs($this->attrs);
399   }
402   function cleanup()
403   {
404     foreach ($this->attrs as $index => $value){
405       
406       /* Convert arrays with one element to non arrays, if the saved
407          attributes are no array, too */
408       if (is_array($this->attrs[$index]) && 
409           count ($this->attrs[$index]) == 1 &&
410           isset($this->saved_attributes[$index]) &&
411           !is_array($this->saved_attributes[$index])){
412           
413         $tmp= $this->attrs[$index][0];
414         $this->attrs[$index]= $tmp;
415       }
417       /* Remove emtpy arrays if they do not differ */
418       if (is_array($this->attrs[$index]) &&
419           count($this->attrs[$index]) == 0 &&
420           !isset($this->saved_attributes[$index])){
421           
422         unset ($this->attrs[$index]);
423         continue;
424       }
426       /* Remove single attributes that do not differ */
427       if (!is_array($this->attrs[$index]) &&
428           isset($this->saved_attributes[$index]) &&
429           !is_array($this->saved_attributes[$index]) &&
430           $this->attrs[$index] == $this->saved_attributes[$index]){
432         unset ($this->attrs[$index]);
433         continue;
434       }
436       /* Remove arrays that do not differ */
437       if (is_array($this->attrs[$index]) && 
438           isset($this->saved_attributes[$index]) &&
439           is_array($this->saved_attributes[$index])){
440           
441         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
442           unset ($this->attrs[$index]);
443           continue;
444         }
445       }
446     }
448     /* Update saved attributes and ensure that next cleanups will be successful too */
449     foreach($this->attrs as $name => $value){
450       $this->saved_attributes[$name] = $value;
451     }
452   }
454   /*! \brief Check formular input */
455   function check()
456   {
457     $message= array();
459     /* Skip if we've no config object */
460     if (!isset($this->config) || !is_object($this->config)){
461       return $message;
462     }
464     /* Find hooks entries for this class */
465     $command= $this->config->search(get_class($this), "CHECK", array('menu', 'tabs'));
467     if ($command != ""){
469       if (!check_command($command)){
470         $message[]= msgPool::cmdnotfound("CHECK", get_class($this));
471       } else {
473         /* Generate "ldif" for check hook */
474         $ldif= "dn: $this->dn\n";
475         
476         /* ... objectClasses */
477         foreach ($this->objectclasses as $oc){
478           $ldif.= "objectClass: $oc\n";
479         }
480         
481         /* ... attributes */
482         foreach ($this->attributes as $attr){
483           if ($this->$attr == ""){
484             continue;
485           }
486           if (is_array($this->$attr)){
487             foreach ($this->$attr as $val){
488               $ldif.= "$attr: $val\n";
489             }
490           } else {
491               $ldif.= "$attr: ".$this->$attr."\n";
492           }
493         }
495         /* Append empty line */
496         $ldif.= "\n";
498         /* Feed "ldif" into hook and retrieve result*/
499         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
500         $fh= proc_open($command, $descriptorspec, $pipes);
501         if (is_resource($fh)) {
502           fwrite ($pipes[0], $ldif);
503           fclose($pipes[0]);
504           
505           $result= stream_get_contents($pipes[1]);
506           if ($result != ""){
507             $message[]= $result;
508           }
509           
510           fclose($pipes[1]);
511           fclose($pipes[2]);
512           proc_close($fh);
513         }
514       }
516     }
518     /* Check entryCSN */
519     if($this->CSN_check_active){
520       $current_csn = getEntryCSN($this->dn);
521       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
522         $this->entryCSN = $current_csn;
523         $message[] = _("The object has changed since opened in GOsa. All changes that may be done by others get lost if you save this entry!");
524       }
525     }
526     return ($message);
527   }
529   /* Adapt from template, using 'dn' */
530   function adapt_from_template($dn, $skip= array())
531   {
532     /* Include global link_info */
533     $ldap= $this->config->get_ldap_link();
535     /* Load requested 'dn' to 'attrs' */
536     $ldap->cat ($dn);
537     $this->attrs= $ldap->fetch();
539     /* Walk through attributes */
540     foreach ($this->attributes as $val){
542       /* Skip the ones in skip list */
543       if (in_array($val, $skip)){
544         continue;
545       }
547       if (isset($this->attrs["$val"][0])){
549         /* If attribute is set, replace dynamic parts: 
550            %sn, %givenName and %uid. Fill these in our local variables. */
551         $value= $this->attrs["$val"][0];
553         foreach (array("sn", "givenName", "uid") as $repl){
554           if (preg_match("/%$repl/i", $value)){
555             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
556           }
557         }
558         $this->$val= $value;
559       }
560     }
562     /* Is Account? */
563     $found= TRUE;
564     foreach ($this->objectclasses as $obj){
565       if (preg_match('/top/i', $obj)){
566         continue;
567       }
568       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
569         $found= FALSE;
570         break;
571       }
572     }
573     if ($found){
574       $this->is_account= TRUE;
575     }
576   }
578   /* \brief Indicate whether a password change is needed or not */
579   function password_change_needed()
580   {
581     return FALSE;
582   }
585   /*! \brief Show header message for tab dialogs */
586   function show_enable_header($button_text, $text, $disabled= FALSE)
587   {
588     if (($disabled == TRUE) || (!$this->acl_is_createable())){
589       $state= "disabled";
590     } else {
591       $state= "";
592     }
593     $display = "<div class='plugin-enable-header'>\n";
594     $display.= "<p>$text</p>\n";
595     $display.= "<button type='submit' name=\"modify_state\" ".$state.">$button_text</button>\n";
596     $display.= "</div>\n";
598     return($display);
599   }
602   /*! \brief Show header message for tab dialogs */
603   function show_disable_header($button_text, $text, $disabled= FALSE)
604   {
605     if (($disabled == TRUE) || !$this->acl_is_removeable()){
606       $state= "disabled";
607     } else {
608       $state= "";
609     }
610     $display = "<div class='plugin-disable-header'>\n";
611     $display.= "<p>$text</p>\n";
612     $display.= "<button type='submit' name=\"modify_state\" ".$state.">$button_text</button>\n";
613     $display.= "</div>\n";
614     return($display);
615   }
619   /* Create unique DN */
620   function create_unique_dn2($data, $base)
621   {
622     $ldap= $this->config->get_ldap_link();
623     $base= preg_replace("/^,*/", "", $base);
625     /* Try to use plain entry first */
626     $dn= "$data,$base";
627     $attribute= preg_replace('/=.*$/', '', $data);
628     $ldap->cat ($dn, array('dn'));
629     if (!$ldap->fetch()){
630       return ($dn);
631     }
633     /* Look for additional attributes */
634     foreach ($this->attributes as $attr){
635       if ($attr == $attribute || $this->$attr == ""){
636         continue;
637       }
639       $dn= "$data+$attr=".$this->$attr.",$base";
640       $ldap->cat ($dn, array('dn'));
641       if (!$ldap->fetch()){
642         return ($dn);
643       }
644     }
646     /* None found */
647     return ("none");
648   }
651   /*! \brief Create unique DN */
652   function create_unique_dn($attribute, $base)
653   {
654     $ldap= $this->config->get_ldap_link();
655     $base= preg_replace("/^,*/", "", $base);
657     /* Try to use plain entry first */
658     $dn= "$attribute=".$this->$attribute.",$base";
659     $ldap->cat ($dn, array('dn'));
660     if (!$ldap->fetch()){
661       return ($dn);
662     }
664     /* Look for additional attributes */
665     foreach ($this->attributes as $attr){
666       if ($attr == $attribute || $this->$attr == ""){
667         continue;
668       }
670       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
671       $ldap->cat ($dn, array('dn'));
672       if (!$ldap->fetch()){
673         return ($dn);
674       }
675     }
677     /* None found */
678     return ("none");
679   }
682   function rebind($ldap, $referral)
683   {
684     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
685     if (ldap_bind($ldap, $credentials['ADMIN'], $this->config->get_credentials($credentials['PASSWORD']))) {
686       $this->error = "Success";
687       $this->hascon=true;
688       $this->reconnect= true;
689       return (0);
690     } else {
691       $this->error = "Could not bind to " . $credentials['ADMIN'];
692       return NULL;
693     }
694   }
697   /* Recursively copy ldap object */
698   function _copy($src_dn,$dst_dn)
699   {
700     $ldap=$this->config->get_ldap_link();
701     $ldap->cat($src_dn);
702     $attrs= $ldap->fetch();
704     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
705     $ds= ldap_connect($this->config->current['SERVER']);
706     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
707     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
708       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
709     }
711     $pwd = $this->config->get_credentials($this->config->current['ADMINPASSWORD']);
712     $r=ldap_bind($ds,$this->config->current['ADMINDN'], $pwd);
713     $sr=ldap_read($ds, LDAP::fix($src_dn), "objectClass=*");
715     /* Fill data from LDAP */
716     $new= array();
717     if ($sr) {
718       $ei=ldap_first_entry($ds, $sr);
719       if ($ei) {
720         foreach($attrs as $attr => $val){
721           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
722             for ($i= 0; $i<$info['count']; $i++){
723               if ($info['count'] == 1){
724                 $new[$attr]= $info[$i];
725               } else {
726                 $new[$attr][]= $info[$i];
727               }
728             }
729           }
730         }
731       }
732     }
734     /* close conncetion */
735     ldap_unbind($ds);
737     /* Adapt naming attribute */
738     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
739     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
740     $new[$dst_name]= LDAP::fix($dst_val);
742     /* Check if this is a department.
743      * If it is a dep. && there is a , override in his ou 
744      *  change \2C to , again, else this entry can't be saved ...
745      */
746     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
747       $new['ou'] = str_replace("\\\\,",",",$new['ou']);
748     }
750     /* Save copy */
751     $ldap->connect();
752     $ldap->cd($this->config->current['BASE']);
753     
754     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
756     /* FAIvariable=.../..., cn=.. 
757         could not be saved, because the attribute FAIvariable was different to 
758         the dn FAIvariable=..., cn=... */
760     if(!is_array($new['objectClass'])) $new['objectClass'] = array($new['objectClass']);
762     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
763       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
764     }
765     $ldap->cd($dst_dn);
766     $ldap->add($new);
768     if (!$ldap->success()){
769       trigger_error("Trying to save $dst_dn failed.",
770           E_USER_WARNING);
771       return(FALSE);
772     }
773     return(TRUE);
774   }
777   /* This is a workaround function. */
778   function copy($src_dn, $dst_dn)
779   {
780     /* Rename dn in possible object groups */
781     $ldap= $this->config->get_ldap_link();
782     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::prepare4filter($src_dn).'))',
783         array('cn'));
784     while ($attrs= $ldap->fetch()){
785       $og= new ogroup($this->config, $ldap->getDN());
786       unset($og->member[$src_dn]);
787       $og->member[$dst_dn]= $dst_dn;
788       $og->save ();
789     }
791     $ldap->cat($dst_dn);
792     $attrs= $ldap->fetch();
793     if (count($attrs)){
794       trigger_error("Trying to overwrite ".LDAP::fix($dst_dn).", which already exists.",
795           E_USER_WARNING);
796       return (FALSE);
797     }
799     $ldap->cat($src_dn);
800     $attrs= $ldap->fetch();
801     if (!count($attrs)){
802       trigger_error("Trying to move ".LDAP::fix($src_dn).", which does not seem to exist.",
803           E_USER_WARNING);
804       return (FALSE);
805     }
807     $ldap->cd($src_dn);
808     $ldap->search("objectClass=*",array("dn"));
809     while($attrs = $ldap->fetch()){
810       $src = $attrs['dn'];
811       $dst = preg_replace("/".preg_quote($src_dn, '/')."$/",$dst_dn,$attrs['dn']);
812       $this->_copy($src,$dst);
813     }
814     return (TRUE);
815   }
819   /*! \brief  Rename/Move a given src_dn to the given dest_dn
820    *
821    * Move a given ldap object indentified by $src_dn to the
822    * given destination $dst_dn
823    *
824    * - Ensure that all references are updated (ogroups)
825    * - Update ACLs   
826    * - Update accessTo
827    *
828    * \param  string  'src_dn' the source DN.
829    * \param  string  'dst_dn' the destination DN.
830    * \return boolean TRUE on success else FALSE.
831    */
832   function rename($src_dn, $dst_dn)
833   {
834     $start = microtime(1);
836     /* Try to move the source entry to the destination position */
837     $ldap = $this->config->get_ldap_link();
838     $ldap->cd($this->config->current['BASE']);
839     $ldap->create_missing_trees(preg_replace("/^[^,]+,/","",$dst_dn));
840     if (!$ldap->rename_dn($src_dn,$dst_dn)){
841 #      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $src_dn, "", get_class()));
842       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());
843       @DEBUG(DEBUG_LDAP,__LINE__,__FUNCTION__,__FILE__,"Rename failed FROM: $src_dn  -- TO:  $dst_dn", 
844           "Ldap Protocol v3 implementation error, falling back to maunal method.");
845       return(FALSE);
846     }
848     /* Get list of users,groups and roles within this tree,
849         maybe we have to update ACL references.
850      */
851     $leaf_objs = get_list("(|(objectClass=posixGroup)(objectClass=gosaAccount)(objectClass=gosaRole))",array("all"),$dst_dn,
852           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
853     foreach($leaf_objs as $obj){
854       $new_dn = $obj['dn'];
855       $old_dn = preg_replace("/".preg_quote(LDAP::convert($dst_dn), '/')."$/i",$src_dn,LDAP::convert($new_dn));
856       $this->update_acls($old_dn,$new_dn); 
857     }
859     // Migrate objectgroups if needed
860     $ogroups = get_sub_list("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter(LDAP::fix($src_dn))."))",
861       "ogroups", array(get_ou("ogroupRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
863     // Walk through all objectGroups
864     foreach($ogroups as $ogroup){
865       // Migrate old to new dn
866       $o_ogroup= new ogroup($this->config,$ogroup['dn']);
867       if (isset($o_ogroup->member[$src_dn])) {
868         unset($o_ogroup->member[$src_dn]);
869       }
870       $o_ogroup->member[$dst_dn]= $dst_dn;
871       
872       // Save object group
873       $o_ogroup->save();
874     }
876     // Migrate rfc groups if needed
877     $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);
879     // Walk through all POSIX groups
880     foreach($groups as $group){
882       // Migrate old to new dn
883       $o_group= new group($this->config,$group['dn']);
884       $o_group->save();
885     }
887     /* Update roles to use the new entry dn */
888     $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);
890     // Walk through all roles
891     foreach($roles as $role){
892       $role = new roleGeneric($this->config,$role['dn']);
893       $key= array_search($src_dn, $role->roleOccupant);      
894       if($key !== FALSE){
895         $role->roleOccupant[$key] = $dst_dn;
896         $role->save();
897       }
898     }
900     // Update 'manager' attributes from gosaDepartment and inetOrgPerson 
901     $filter = "(&(objectClass=inetOrgPerson)(manager=".LDAP::prepare4filter(LDAP::fix($src_dn))."))";
902     $ocs = $ldap->get_objectclasses();
903     if(isset($ocs['gosaDepartment']['MAY']) && in_array('manager', $ocs['gosaDepartment']['MAY'])){
904       $filter = "(|".$filter."(&(objectClass=gosaDepartment)(manager=".LDAP::prepare4filter(LDAP::fix($src_dn)).")))";
905     }
906     $leaf_deps=  get_list($filter,array("all"),$this->config->current['BASE'], 
907         array("manager","dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
908     foreach($leaf_deps as $entry){
909       $update = array('manager' => $dst_dn);
910       $ldap->cd($entry['dn']);
911       $ldap->modify($update);
912       if(!$ldap->success()){
913         trigger_error(sprintf("Failed to update manager for '%s', error was '%s'", $entry['dn'], $ldap->get_error()));
914       }
915     }
916  
917     /* Check if there are gosa departments moved. 
918        If there were deps moved, the force reload of config->deps.
919      */
920     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
921           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
922   
923     if(count($leaf_deps)){
924       $this->config->get_departments();
925       $this->config->make_idepartments();
926       session::global_set("config",$this->config);
927       $ui =get_userinfo();
928       $ui->reset_acl_cache();
929     }
931     return(TRUE); 
932   }
935  
936   function move($src_dn, $dst_dn)
937   {
938     /* Do not copy if only upper- lowercase has changed */
939     if(strtolower($src_dn) == strtolower($dst_dn)){
940       return(TRUE);
941     }
943     
944     /* Try to move the entry instead of copy & delete
945      */
946     if(TRUE){
948       /* Try to move with ldap routines, if this was not successfull
949           fall back to the old style copy & remove method 
950        */
951       if($this->rename($src_dn, $dst_dn)){
952         return(TRUE);
953       }else{
954         // See code below.
955       }
956     }
958     /* Copy source to destination */
959     if (!$this->copy($src_dn, $dst_dn)){
960       return (FALSE);
961     }
963     /* Delete source */
964     $ldap= $this->config->get_ldap_link();
965     $ldap->rmdir_recursive($src_dn);
966     if (!$ldap->success()){
967       trigger_error("Trying to delete $src_dn failed.",
968           E_USER_WARNING);
969       return (FALSE);
970     }
972     return (TRUE);
973   }
976   /* \brief Move/Rename complete trees */
977   function recursive_move($src_dn, $dst_dn)
978   {
979     /* Check if the destination entry exists */
980     $ldap= $this->config->get_ldap_link();
982     /* Check if destination exists - abort */
983     $ldap->cat($dst_dn, array('dn'));
984     if ($ldap->fetch()){
985       trigger_error("recursive_move $dst_dn already exists.",
986           E_USER_WARNING);
987       return (FALSE);
988     }
990     $this->copy($src_dn, $dst_dn);
992     /* Remove src_dn */
993     $ldap->cd($src_dn);
994     $ldap->recursive_remove($src_dn);
995     return (TRUE);
996   }
999   function saveCopyDialog(){
1000   }
1003   function getCopyDialog(){
1004     return(array("string"=>"","status"=>""));
1005   }
1008   /*! \brief Prepare for Copy & Paste */
1009   function PrepareForCopyPaste($source)
1010   {
1011     $todo = $this->attributes;
1012     if(isset($this->CopyPasteVars)){
1013       $todo = array_merge($todo,$this->CopyPasteVars);
1014     }
1016     if(count($this->objectclasses)){
1017       $this->is_account = TRUE;
1018       foreach($this->objectclasses as $class){
1019         if(!in_array($class,$source['objectClass'])){
1020           $this->is_account = FALSE;
1021         }
1022       }
1023     }
1025     foreach($todo as $var){
1026       if (isset($source[$var])){
1027         if(isset($source[$var]['count'])){
1028           if($source[$var]['count'] > 1){
1029             $tmp= $source[$var];
1030             unset($tmp['count']);
1031             $this->$var = $tmp;
1032           }else{
1033             $this->$var = $source[$var][0];
1034           }
1035         }else{
1036           $this->$var= $source[$var];
1037         }
1038       }
1039     }
1040   }
1042   /*! \brief Get gosaUnitTag for the given DN
1043        If this is called from departmentGeneric, we have to skip this
1044         tagging procedure. 
1045     */
1046   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1047   {
1048     /* Skip tagging? */
1049     if($this->skipTagging){
1050       return;
1051     }
1053     /* No dn? Self-operation... */
1054     if ($dn == ""){
1055       $dn= $this->dn;
1057       /* No tag? Find it yourself... */
1058       if ($tag == ""){
1059         $len= strlen($dn);
1061         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1062         $relevant= array();
1063         foreach ($this->config->adepartments as $key => $ntag){
1065           /* This one is bigger than our dn, its not relevant... */
1066           if ($len < strlen($key)){
1067             continue;
1068           }
1070           /* This one matches with the latter part. Break and don't fix this entry */
1071           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
1072             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1073             $relevant[strlen($key)]= $ntag;
1074             continue;
1075           }
1077         }
1079         /* If we've some relevant tags to set, just get the longest one */
1080         if (count($relevant)){
1081           ksort($relevant);
1082           $tmp= array_keys($relevant);
1083           $idx= end($tmp);
1084           $tag= $relevant[$idx];
1085           $this->gosaUnitTag= $tag;
1086         }
1087       }
1088     }
1090   /*! \brief Add unit tag */ 
1091     /* Remove tags that may already be here... */
1092     remove_objectClass("gosaAdministrativeUnitTag", $at);
1093     if (isset($at['gosaUnitTag'])){
1094         unset($at['gosaUnitTag']);
1095     }
1097     /* Set tag? */
1098     if ($tag != ""){
1099       add_objectClass("gosaAdministrativeUnitTag", $at);
1100       $at['gosaUnitTag']= $tag;
1101     }
1103     /* Initially this object was tagged. 
1104        - But now, it is no longer inside a tagged department. 
1105        So force the remove of the tag.
1106        (objectClass was already removed obove)
1107      */
1108     if($tag == "" && $this->gosaUnitTag){
1109       $at['gosaUnitTag'] = array();
1110     }
1111   }
1114   /*! \brief Test for removability of the object
1115    *
1116    * Allows testing of conditions for removal of object. If removal should be aborted
1117    * the function needs to remove an error message.
1118    * */
1119   function allow_remove()
1120   {
1121     $reason= "";
1122     return $reason;
1123   }
1126   /*! \brief Create a snapshot of the current object */
1127   function create_snapshot($type= "snapshot", $description= array())
1128   {
1130     /* Check if snapshot functionality is enabled */
1131     if(!$this->snapshotEnabled()){
1132       return;
1133     }
1135     /* Get configuration from gosa.conf */
1136     $config = $this->config;
1138     /* Create lokal ldap connection */
1139     $ldap= $this->config->get_ldap_link();
1140     $ldap->cd($this->config->current['BASE']);
1142     /* check if there are special server configurations for snapshots */
1143     if($config->get_cfg_value("snapshotURI") == ""){
1145       /* Source and destination server are both the same, just copy source to dest obj */
1146       $ldap_to      = $ldap;
1147       $snapldapbase = $this->config->current['BASE'];
1149     }else{
1150       $server         = $config->get_cfg_value("snapshotURI");
1151       $user           = $config->get_cfg_value("snapshotAdminDn");
1152       $password       = $this->config->get_credentials($config->get_cfg_value("snapshotAdminPassword"));
1153       $snapldapbase   = $config->get_cfg_value("snapshotBase");
1155       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1156       $ldap_to -> cd($snapldapbase);
1158       if (!$ldap_to->success()){
1159         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1160       }
1162     }
1164     /* check if the dn exists */ 
1165     if ($ldap->dn_exists($this->dn)){
1167       /* Extract seconds & mysecs, they are used as entry index */
1168       list($usec, $sec)= explode(" ", microtime());
1170       /* Collect some infos */
1171       $base           = $this->config->current['BASE'];
1172       $snap_base      = $config->get_cfg_value("snapshotBase");
1173       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1174       $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1176       /* Create object */
1177 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1178       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1179       $newName          = str_replace(".", "", $sec."-".$usec);
1180       $target= array();
1181       $target['objectClass']            = array("top", "gosaSnapshotObject");
1182       $target['gosaSnapshotData']       = gzcompress($data, 6);
1183       $target['gosaSnapshotType']       = $type;
1184       $target['gosaSnapshotDN']         = $this->dn;
1185       $target['description']            = $description;
1186       $target['gosaSnapshotTimestamp']  = $newName;
1188       /* Insert the new snapshot 
1189          But we have to check first, if the given gosaSnapshotTimestamp
1190          is already used, in this case we should increment this value till there is 
1191          an unused value. */ 
1192       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1193       $ldap_to->cat($new_dn);
1194       while($ldap_to->count()){
1195         $ldap_to->cat($new_dn);
1196         $newName = str_replace(".", "", $sec."-".($usec++));
1197         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1198         $target['gosaSnapshotTimestamp']  = $newName;
1199       } 
1201       /* Inset this new snapshot */
1202       $ldap_to->cd($snapldapbase);
1203       $ldap_to->create_missing_trees($snapldapbase);
1204       $ldap_to->create_missing_trees($new_base);
1205       $ldap_to->cd($new_dn);
1206       $ldap_to->add($target);
1207       if (!$ldap_to->success()){
1208         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $new_dn, LDAP_ADD, get_class()));
1209       }
1211       if (!$ldap->success()){
1212         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $new_base, "", get_class()));
1213       }
1215     }
1216   }
1218   /*! \brief Remove a snapshot */
1219   function remove_snapshot($dn)
1220   {
1221     $ui       = get_userinfo();
1222     $old_dn   = $this->dn; 
1223     $this->dn = $dn;
1224     $ldap = $this->config->get_ldap_link();
1225     $ldap->cd($this->config->current['BASE']);
1226     $ldap->rmdir_recursive($this->dn);
1227     if(!$ldap->success()){
1228       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn));
1229     }
1230     $this->dn = $old_dn;
1231   }
1234   /*! \brief Test if snapshotting is enabled
1235    *
1236    * Test weither snapshotting is enabled or not. There will also be some errors posted,
1237    * if the configuration failed 
1238    * \return TRUE if snapshots are enabled, and FALSE if it is disabled
1239    */
1240   function snapshotEnabled()
1241   {
1242     return $this->config->snapshotEnabled();
1243   }
1246   /* \brief Return available snapshots for the given base */
1247   function Available_SnapsShots($dn,$raw = false)
1248   {
1249     if(!$this->snapshotEnabled()) return(array());
1251     /* Create an additional ldap object which
1252        points to our ldap snapshot server */
1253     $ldap= $this->config->get_ldap_link();
1254     $ldap->cd($this->config->current['BASE']);
1255     $cfg= &$this->config->current;
1257     /* check if there are special server configurations for snapshots */
1258     if($this->config->get_cfg_value("snapshotURI") == ""){
1259       $ldap_to      = $ldap;
1260     }else{
1261       $server         = $this->config->get_cfg_value("snapshotURI");
1262       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1263       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1264       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1265       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1266       $ldap_to -> cd($snapldapbase);
1267       if (!$ldap_to->success()){
1268         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1269       }
1270     }
1272     /* Prepare bases and some other infos */
1273     $base           = $this->config->current['BASE'];
1274     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1275     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1276     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1277     $tmp            = array(); 
1279     /* Fetch all objects with  gosaSnapshotDN=$dn */
1280     $ldap_to->cd($new_base);
1281     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1282         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1284     /* Put results into a list and add description if missing */
1285     while($entry = $ldap_to->fetch()){ 
1286       if(!isset($entry['description'][0])){
1287         $entry['description'][0]  = "";
1288       }
1289       $tmp[] = $entry; 
1290     }
1292     /* Return the raw array, or format the result */
1293     if($raw){
1294       return($tmp);
1295     }else{  
1296       $tmp2 = array();
1297       foreach($tmp as $entry){
1298         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1299       }
1300     }
1301     return($tmp2);
1302   }
1305   function getAllDeletedSnapshots($base_of_object,$raw = false)
1306   {
1307     if(!$this->snapshotEnabled()) return(array());
1309     /* Create an additional ldap object which
1310        points to our ldap snapshot server */
1311     $ldap= $this->config->get_ldap_link();
1312     $ldap->cd($this->config->current['BASE']);
1313     $cfg= &$this->config->current;
1315     /* check if there are special server configurations for snapshots */
1316     if($this->config->get_cfg_value("snapshotURI") == ""){
1317       $ldap_to      = $ldap;
1318     }else{
1319       $server         = $this->config->get_cfg_value("snapshotURI");
1320       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1321       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1322       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1323       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1324       $ldap_to -> cd($snapldapbase);
1325       if (!$ldap_to->success()){
1326         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1327       }
1328     }
1330     /* Prepare bases */ 
1331     $base           = $this->config->current['BASE'];
1332     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1333     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1335     /* Fetch all objects and check if they do not exist anymore */
1336     $ui = get_userinfo();
1337     $tmp = array();
1338     $ldap_to->cd($new_base);
1339     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1340     while($entry = $ldap_to->fetch()){
1342       $chk =  str_replace($new_base,"",$entry['dn']);
1343       if(preg_match("/,ou=/",$chk)) continue;
1345       if(!isset($entry['description'][0])){
1346         $entry['description'][0]  = "";
1347       }
1348       $tmp[] = $entry; 
1349     }
1351     /* Check if entry still exists */
1352     foreach($tmp as $key => $entry){
1353       $ldap->cat($entry['gosaSnapshotDN'][0]);
1354       if($ldap->count()){
1355         unset($tmp[$key]);
1356       }
1357     }
1359     /* Format result as requested */
1360     if($raw) {
1361       return($tmp);
1362     }else{
1363       $tmp2 = array();
1364       foreach($tmp as $key => $entry){
1365         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1366       }
1367     }
1368     return($tmp2);
1369   } 
1372   /* \brief Restore selected snapshot */
1373   function restore_snapshot($dn)
1374   {
1375     if(!$this->snapshotEnabled()) return(array());
1377     $ldap= $this->config->get_ldap_link();
1378     $ldap->cd($this->config->current['BASE']);
1379     $cfg= &$this->config->current;
1381     /* check if there are special server configurations for snapshots */
1382     if($this->config->get_cfg_value("snapshotURI") == ""){
1383       $ldap_to      = $ldap;
1384     }else{
1385       $server         = $this->config->get_cfg_value("snapshotURI");
1386       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1387       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1388       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1389       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1390       $ldap_to -> cd($snapldapbase);
1391       if (!$ldap_to->success()){
1392         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1393       }
1394     }
1396     /* Get the snapshot */ 
1397     $ldap_to->cat($dn);
1398     $restoreObject = $ldap_to->fetch();
1400     /* Prepare import string */
1401     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1403     /* Import the given data */
1404     $err = "";
1405     $ldap->import_complete_ldif($data,$err,false,false);
1406     if (!$ldap->success()){
1407       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, "", get_class()));
1408     }
1409   }
1412   function showSnapshotDialog($base,$baseSuffixe,&$parent)
1413   {
1414     $once = true;
1415     $ui = get_userinfo();
1416     $this->parent = $parent;
1418     foreach($_POST as $name => $value){
1420       /* Create a new snapshot, display a dialog */
1421       if(preg_match("/^CreateSnapShotDialog_[^_]*_[xy]$/",$name) && $once){
1423                           $entry = base64_decode(preg_replace("/^CreateSnapShotDialog_([^_]*)_[xy]$/","\\1",$name));
1424         $once = false;
1425         $entry = preg_replace("/^CreateSnapShotDialog_/","",$entry);
1427         if(!empty($entry) && $ui->allow_snapshot_create($entry,$this->parent->acl_module)){
1428           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1429         }else{
1430           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to create a snapshot for %s."),$entry),ERROR_DIALOG);
1431         }
1432       }  
1433   
1434       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1435       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1436         $once = false;
1437         $entry = base64_decode(preg_replace("/^RestoreSnapShotDialog_([^_]*)_[xy]$/i","\\1",$name));
1438         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1439           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1440           $this->snapDialog->display_restore_dialog = true;
1441         }else{
1442           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1443         }
1444       }
1446       /* Restore one of the already deleted objects */
1447       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1448           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1449         $once = false;
1451         if($ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1452           $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1453           $this->snapDialog->set_snapshot_bases($baseSuffixe);
1454           $this->snapDialog->display_restore_dialog      = true;
1455           $this->snapDialog->display_all_removed_objects  = true;
1456         }else{
1457           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$base),ERROR_DIALOG);
1458         }
1459       }
1461       /* Restore selected snapshot */
1462       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1463         $once = false;
1464         $entry = base64_decode(preg_replace("/^RestoreSnapShot_([^_]*)_[xy]$/i","\\1",$name));
1466         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1467           $this->restore_snapshot($entry);
1468           $this->snapDialog = NULL;
1469         }else{
1470           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1471         }
1472       }
1473     }
1475     /* Create a new snapshot requested, check
1476        the given attributes and create the snapshot*/
1477     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1478       $this->snapDialog->save_object();
1479       $msgs = $this->snapDialog->check();
1480       if(count($msgs)){
1481         foreach($msgs as $msg){
1482           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
1483         }
1484       }else{
1485         $this->dn =  $this->snapDialog->dn;
1486         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1487         $this->snapDialog = NULL;
1488       }
1489     }
1491     /* Restore is requested, restore the object with the posted dn .*/
1492     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1493     }
1495     if(isset($_POST['CancelSnapshot'])){
1496       $this->snapDialog = NULL;
1497     }
1499     if(is_object($this->snapDialog )){
1500       $this->snapDialog->save_object();
1501       return($this->snapDialog->execute());
1502     }
1503   }
1506   /*! \brief Return plugin informations for acl handling */
1507   static function plInfo()
1508   {
1509     return array();
1510   }
1513   function set_acl_base($base)
1514   {
1515     $this->acl_base= $base;
1516   }
1519   function set_acl_category($category)
1520   {
1521     $this->acl_category= "$category/";
1522   }
1525   function acl_is_writeable($attribute,$skip_write = FALSE)
1526   {
1527     if($this->read_only) return(FALSE);
1528     $ui= get_userinfo();
1529     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1530   }
1533   function acl_is_readable($attribute)
1534   {
1535     $ui= get_userinfo();
1536     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1537   }
1540   function acl_is_createable($base ="")
1541   {
1542     if($this->read_only) return(FALSE);
1543     $ui= get_userinfo();
1544     if($base == "") $base = $this->acl_base;
1545     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1546   }
1549   function acl_is_removeable($base ="")
1550   {
1551     if($this->read_only) return(FALSE);
1552     $ui= get_userinfo();
1553     if($base == "") $base = $this->acl_base;
1554     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1555   }
1558   function acl_is_moveable($base = "")
1559   {
1560     if($this->read_only) return(FALSE);
1561     $ui= get_userinfo();
1562     if($base == "") $base = $this->acl_base;
1563     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1564   }
1567   function acl_have_any_permissions()
1568   {
1569   }
1572   function getacl($attribute,$skip_write= FALSE)
1573   {
1574     $ui= get_userinfo();
1575     $skip_write |= $this->read_only;
1576     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1577   }
1580   /*! \brief Returns a list of all available departments for this object.
1581    * 
1582    * If this object is new, all departments we are allowed to create a new user in
1583    * are returned. If this is an existing object, return all deps. 
1584    * We are allowed to move tis object too.
1585    * \return array [dn] => "..name"  // All deps. we are allowed to act on.
1586   */
1587   function get_allowed_bases()
1588   {
1589     $ui = get_userinfo();
1590     $deps = array();
1592     /* Is this a new object ? Or just an edited existing object */
1593     if(!$this->initially_was_account && $this->is_account){
1594       $new = true;
1595     }else{
1596       $new = false;
1597     }
1599     foreach($this->config->idepartments as $dn => $name){
1600       if($new && $this->acl_is_createable($dn)){
1601         $deps[$dn] = $name;
1602       }elseif(!$new && $this->acl_is_moveable($dn)){
1603         $deps[$dn] = $name;
1604       }
1605     }
1607     /* Add current base */      
1608     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1609       $deps[$this->base] = $this->config->idepartments[$this->base];
1610     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1612     }else{
1613       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1614     }
1615     return($deps);
1616   }
1619   /* This function updates ACL settings if $old_dn was used.
1620    *  \param string 'old_dn' specifies the actually used dn
1621    *  \param string 'new_dn' specifies the destiantion dn
1622    */
1623   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1624   {
1625     /* Check if old_dn is empty. This should never happen */
1626     if(empty($old_dn) || empty($new_dn)){
1627       trigger_error("Failed to check acl dependencies, wrong dn given.");
1628       return;
1629     }
1631     /* Update userinfo if necessary */
1632     $ui = session::global_get('ui');
1633     if($ui->dn == $old_dn){
1634       $ui->dn = $new_dn;
1635       session::global_set('ui',$ui);
1636       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1637     }
1639     /* Object was moved, ensure that all acls will be moved too */
1640     if($new_dn != $old_dn && $old_dn != "new"){
1642       /* get_ldap configuration */
1643       $update = array();
1644       $ldap = $this->config->get_ldap_link();
1645       $ldap->cd ($this->config->current['BASE']);
1646       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1647       while($attrs = $ldap->fetch()){
1648         $acls = array();
1649         $found = false;
1650         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1651           $acl_parts = explode(":",$attrs['gosaAclEntry'][$i]);
1653           /* Roles uses antoher data storage order, members are stored int the third part, 
1654              while the members in direct ACL assignments are stored in the second part.
1655            */
1656           $id = ($acl_parts[1] == "role") ? 3 : 2;
1658           /* Update member entries to use $new_dn instead of old_dn
1659            */
1660           $members = explode(",",$acl_parts[$id]);
1661           foreach($members as $key => $member){
1662             $member = base64_decode($member);
1663             if($member == $old_dn){
1664               $members[$key] = base64_encode($new_dn);
1665               $found = TRUE;
1666             }
1667           } 
1669           /* Check if the selected role has to updated
1670            */
1671           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1672             $acl_parts[2] = base64_encode($new_dn);
1673             $found = TRUE;
1674           }
1676           /* Build new acl string */ 
1677           $acl_parts[$id] = implode($members,",");
1678           $acls[] = implode($acl_parts,":");
1679         }
1681         /* Acls for this object must be adjusted */
1682         if($found){
1684           $debug_info=  _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1685             $old_dn."</b><br>&nbsp;-"._("to")."&nbsp;<b>".$new_dn."</b><br>";
1686           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1688           $update[$attrs['dn']] =array();
1689           foreach($acls as $acl){
1690             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1691           }
1692         }
1693       }
1695       /* Write updated acls */
1696       foreach($update as $dn => $attrs){
1697         $ldap->cd($dn);
1698         $ldap->modify($attrs);
1699       }
1700     }
1701   }
1703   
1705   /*! \brief Enable the Serial ID check
1706    *
1707    * This function enables the entry Serial ID check.  If an entry was edited while
1708    * we have edited the entry too, an error message will be shown. 
1709    * To configure this check correctly read the FAQ.
1710    */    
1711   function enable_CSN_check()
1712   {
1713     $this->CSN_check_active =TRUE;
1714     $this->entryCSN = getEntryCSN($this->dn);
1715   }
1718   /*! \brief  Prepares the plugin to be used for multiple edit
1719    *          Update plugin attributes with given array of attribtues.
1720    *  \param  array   Array with attributes that must be updated.
1721    */
1722   function init_multiple_support($attrs,$all)
1723   {
1724     $ldap= $this->config->get_ldap_link();
1725     $this->multi_attrs    = $attrs;
1726     $this->multi_attrs_all= $all;
1728     /* Copy needed attributes */
1729     foreach ($this->attributes as $val){
1730       $found= array_key_ics($val, $this->multi_attrs);
1731  
1732       if ($found != ""){
1733         if(isset($this->multi_attrs["$val"][0])){
1734           $this->$val= $this->multi_attrs["$val"][0];
1735         }
1736       }
1737     }
1738   }
1740  
1741   /*! \brief  Enables multiple support for this plugin
1742    */
1743   function enable_multiple_support()
1744   {
1745     $this->ignore_account = TRUE;
1746     $this->multiple_support_active = TRUE;
1747   }
1750   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1751       \return array Cotaining all modified values. 
1752    */
1753   function get_multi_edit_values()
1754   {
1755     $ret = array();
1756     foreach($this->attributes as $attr){
1757       if(in_array($attr,$this->multi_boxes)){
1758         $ret[$attr] = $this->$attr;
1759       }
1760     }
1761     return($ret);
1762   }
1764   
1765   /*! \brief  Update class variables with values collected by multiple edit.
1766    */
1767   function set_multi_edit_values($attrs)
1768   {
1769     foreach($attrs as $name => $value){
1770       $this->$name = $value;
1771     }
1772   }
1775   /*! \brief Generates the html output for this node for multi edit*/
1776   function multiple_execute()
1777   {
1778     /* This one is empty currently. Fabian - please fill in the docu code */
1779     session::global_set('current_class_for_help',get_class($this));
1781     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1782     session::set('LOCK_VARS_TO_USE',array());
1783     session::set('LOCK_VARS_USED_GET',array());
1784     session::set('LOCK_VARS_USED_POST',array());
1785     session::set('LOCK_VARS_USED_REQUEST',array());
1786     
1787     return("Multiple edit is currently not implemented for this plugin.");
1788   }
1791   /*! \brief Save HTML posted data to object for multiple edit
1792    */
1793   function multiple_save_object()
1794   {
1795     if(empty($this->entryCSN) && $this->CSN_check_active){
1796       $this->entryCSN = getEntryCSN($this->dn);
1797     }
1799     /* Save values to object */
1800     $this->multi_boxes = array();
1801     foreach ($this->attributes as $val){
1802   
1803       /* Get selected checkboxes from multiple edit */
1804       if(isset($_POST["use_".$val])){
1805         $this->multi_boxes[] = $val;
1806       }
1808       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
1810         /* Check for modifications */
1811         if (get_magic_quotes_gpc()) {
1812           $data= stripcslashes($_POST["$val"]);
1813         } else {
1814           $data= $this->$val = $_POST["$val"];
1815         }
1816         if ($this->$val != $data){
1817           $this->is_modified= TRUE;
1818         }
1819     
1820         /* IE post fix */
1821         if(isset($data[0]) && $data[0] == chr(194)) {
1822           $data = "";  
1823         }
1824         $this->$val= $data;
1825       }
1826     }
1827   }
1830   /*! \brief Returns all attributes of this plugin, 
1831                to be able to detect multiple used attributes 
1832                in multi_plugg::detect_multiple_used_attributes().
1833       @return array Attributes required for intialization of multi_plug
1834    */
1835   public function get_multi_init_values()
1836   {
1837     $attrs = $this->attrs;
1838     return($attrs);
1839   }
1842   /*! \brief  Check given values in multiple edit
1843       \return array Error messages
1844    */
1845   function multiple_check()
1846   {
1847     $message = plugin::check();
1848     return($message);
1849   }
1852   /*! \brief  Returns the snapshot header part for "Actions" menu in management dialogs 
1853       \param  $layer_menu  
1854    */   
1855   function get_snapshot_header($base,$category)
1856   {
1857     $str = "";
1858     $ui = get_userinfo();
1859     if($this->snapshotEnabled() && $ui->allow_snapshot_restore($base,$category)){
1861       $ok = false;
1862       foreach($this->get_used_snapshot_bases() as $base){
1863         $ok |= count($this->getAllDeletedSnapshots($base)) >= 1 ;
1864       }
1866       if($ok){
1867         $str = "..|<img class='center' src='images/lists/restore.png' ".
1868           "alt='"._("Restore")."'>&nbsp;"._("Restore").                       "|RestoreDeletedSnapShot|\n";
1869       }else{
1870         $str = "..|<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;"._("Restore")."||\n";
1871       }
1872     }
1873     return($str);
1874   }
1877   function get_snapshot_action($base,$category)
1878   {
1879     $str= ""; 
1880     $ui = get_userinfo();
1881     if($this->snapshotEnabled()){
1882       if ($ui->allow_snapshot_restore($base,$category)){
1884         if(count($this->Available_SnapsShots($base))){
1885           $str.= "<input class='center' type='image' src='images/lists/restore.png'
1886             alt='"._("Restore snapshot")."' name='RestoreSnapShotDialog_".base64_encode($base)."' title='"._("Restore snapshot")."'>&nbsp;";
1887         } else {
1888           $str = "<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;";
1889         }
1890       }
1891       if($ui->allow_snapshot_create($base,$category)){
1892         $str.= "<input class='center' type='image' src='images/snapshot.png'
1893           alt='"._("Create snapshot")."' name='CreateSnapShotDialog_".base64_encode($base)."' 
1894           title='"._("Create a new snapshot from this object")."'>&nbsp;";
1895       }else{
1896         $str = "<img class='center' src='images/empty.png' alt=' '>&nbsp;";
1897       }
1898     }
1900     return($str);
1901   }
1904   function get_copypaste_action($base,$category,$class,$copy = TRUE, $cut = TRUE)
1905   {
1906     $ui = get_userinfo();
1907     $action = "";
1908     if($this->CopyPasteHandler){
1909       if($cut){
1910         if($ui->is_cutable($base,$category,$class)){
1911           $action .= "<input class='center' type='image'
1912             src='images/lists/cut.png' alt='"._("cut")."' name='cut_%KEY%' title='"._("Cut this entry")."'>&nbsp;";
1913         }else{
1914           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
1915         }
1916       }
1917       if($copy){
1918         if($ui->is_copyable($base,$category,$class)){
1919           $action.= "<input class='center' type='image'
1920             src='images/lists/copy.png' alt='"._("copy")."' name='copy_%KEY%' title='"._("Copy this entry")."'>&nbsp;";
1921         }else{
1922           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
1923         }
1924       }
1925     }
1927     return($action); 
1928   }
1931   function get_copypaste_header($base,$category,$copy = TRUE, $cut = TRUE)
1932   {
1933     $s = "";
1934     $ui =get_userinfo();
1936     if(!is_array($category)){
1937       $category = array($category);
1938     }
1940     /* Check permissions for each category, if there is at least one category which 
1941         support read or paste permissions for the given base, then display the specific actions.
1942      */
1943     $readable = $pasteable = false;
1944     foreach($category as $cat){
1945       $readable= $readable || preg_match('/r/', $ui->get_category_permissions($base, $cat));
1946       $pasteable= $pasteable || $ui->is_pasteable($base, $cat) == 1;
1947     }
1948   
1949     if(($cut || $copy) && isset($this->CopyPasteHandler) && is_object($this->CopyPasteHandler)){
1950       if($readable){
1951         $s.= "..|---|\n";
1952         if($copy){
1953           $s.= "..|<img src='images/lists/copy.png' alt='' border='0' class='center'>".
1954             "&nbsp;"._("Copy")."|"."multiple_copy_systems|\n";
1955         }
1956         if($cut){
1957           $s.= "..|<img src='images/lists/cut.png' alt='' border='0' class='center'>".
1958             "&nbsp;"._("Cut")."|"."multiple_cut_systems|\n";
1959         }
1960       }
1962       if($pasteable){
1963         if($this->CopyPasteHandler->entries_queued()){
1964           $img = "<img border='0' class='center' src='images/lists/paste.png' alt=''>";
1965           $s.="..|".$img."&nbsp;"._("Paste")."|editPaste|\n";
1966         }else{
1967           $img = "<img border='0' class='center' src='images/lists/paste-grey.png' alt=''>";
1968           $s.="..|".$img."&nbsp;"._("Paste")."\n";
1969         }
1970       }
1971     }
1972     return($s);
1973   }
1976   function get_used_snapshot_bases()
1977   {
1978      return(array());
1979   }
1981   function is_modal_dialog()
1982   {
1983     return(isset($this->dialog) && $this->dialog);
1984   }
1987   /*! \brief    Forward command execution requests
1988    *             to the hook execution method. 
1989    */
1990   function handle_post_events($mode, $addAttrs= array())
1991   {
1992     if(!in_array($mode, array('add','remove','modify'))){
1993       trigger_error(sprintf("Invalid post event type given '%s'! Valid types are [add,modify,remove].", $mode));
1994       return;
1995     }
1996     switch ($mode){
1997       case "add":
1998         plugin::callHook($this,"POSTCREATE", $addAttrs);
1999       break;
2001       case "modify":
2002         plugin::callHook($this,"POSTMODIFY", $addAttrs);
2003       break;
2005       case "remove":
2006         plugin::callHook($this,"POSTREMOVE", $addAttrs);
2007       break;
2008     }
2009   }
2012   /*! \brief    Calls external hooks which are defined for this plugin (gosa.conf)
2013    *            Replaces placeholder by class values of this plugin instance.
2014    *  @param    Allows to a add special replacements.
2015    */
2016   static function callHook($plugin, $cmd, $addAttrs= array())
2017   {
2018     global $config;
2019     $command= $config->search(get_class($plugin), $cmd,array('menu','tabs'));
2020     if ($command != ""){
2022       // Walk trough attributes list and add the plugins attributes. 
2023       foreach ($plugin->attributes as $attr){
2024         if (!is_array($plugin->$attr)){
2025           $addAttrs[$attr] = $plugin->$attr;
2026         }
2027       }
2028       $ui = get_userinfo();
2029       $addAttrs['callerDN']=$ui->dn;
2030       $addAttrs['dn']=$plugin->dn;
2032       // Sort attributes by length, ensures correct replacement
2033       $tmp = array();
2034       foreach($addAttrs as $name => $value){
2035         $tmp[$name] =  strlen($name);
2036       }
2037       arsort($tmp);
2039       // Now replace the placeholder 
2040       foreach ($tmp as $name => $len){
2041         $value = $addAttrs[$name];
2042         $command= str_replace("%$name", "$value", $command);
2043       }
2045       // If there are still some %.. in our command, try to fill these with some other class vars 
2046       if(preg_match("/%/",$command)){
2047         $attrs = get_object_vars($plugin);
2048         foreach($attrs as $name => $value){
2049           if(is_array($value)){
2050             $s = "";
2051             foreach($value as $val){
2052               if(is_string($val) || is_int($val) || is_float($val) || is_bool($val)){
2053                 $s .= '"'.$val.'",'; 
2054               }
2055             }
2056             $value = '['.trim($s,',').']';
2057           }
2058           if(!is_string($value) && !is_int($value) && !is_float($value) && !is_bool($value)){
2059             continue;
2060           }
2061           $command= preg_replace("/%$name/", $value, $command);
2062         }
2063       }
2065       if (check_command($command)){
2066         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,$command,"Execute");
2067         exec($command,$arr);
2068         if(is_array($arr)){
2069           $str = implode("\n",$arr);
2070           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Result: ".$str);
2071         }
2072       } else {
2073         $message= msgPool::cmdnotfound("POSTCREATE", get_class($plugin));
2074         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
2075       }
2076     }
2077   }
2080 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2081 ?>