Code

Updated plugin::move
[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   /*! \brief    The title shown in path menu while this plugin is visible.
36    */
37   var $pathTitle = "";
39   /*!
40     \brief Reference to parent object
42     This variable is used when the plugin is included in tabs
43     and keeps reference to the tab class. Communication to other
44     tabs is possible by 'name'. So the 'fax' plugin can ask the
45     'userinfo' plugin for the fax number.
47     \sa tab
48    */
49   var $parent= NULL;
51   /*!
52     \brief Configuration container
54     Access to global configuration
55    */
56   var $config= NULL;
58   /*!
59     \brief Mark plugin as account
61     Defines whether this plugin is defined as an account or not.
62     This has consequences for the plugin to be saved from tab
63     mode. If it is set to 'FALSE' the tab will call the delete
64     function, else the save function. Should be set to 'TRUE' if
65     the construtor detects a valid LDAP object.
67     \sa plugin::plugin()
68    */
69   var $is_account= FALSE;
70   var $initially_was_account= FALSE;
72   /*!
73     \brief Mark plugin as template
75     Defines whether we are creating a template or a normal object.
76     Has conseqences on the way execute() shows the formular and how
77     save() puts the data to LDAP.
79     \sa plugin::save() plugin::execute()
80    */
81   var $is_template= FALSE;
82   var $ignore_account= FALSE;
83   var $is_modified= FALSE;
85   /*!
86     \brief Represent temporary LDAP data
88     This is only used internally.
89    */
90   var $attrs= array();
92   /* Keep set of conflicting plugins */
93   var $conflicts= array();
95   /* Save unit tags */
96   var $gosaUnitTag= "";
97   var $skipTagging= FALSE;
99   /*!
100     \brief Used standard values
102     dn
103    */
104   var $dn= "";
105   var $uid= "";
106   var $sn= "";
107   var $givenName= "";
108   var $acl= "*none*";
109   var $dialog= FALSE;
110   var $snapDialog = NULL;
112   /* attribute list for save action */
113   var $attributes= array();
114   var $objectclasses= array();
115   var $is_new= TRUE;
116   var $saved_attributes= array();
118   var $acl_base= "";
119   var $acl_category= "";
120   var $read_only = FALSE; // Used when the entry is opened as "readonly" due to locks.
122   /* This can be set to render the tabulators in another stylesheet */
123   var $pl_notify= FALSE;
125   /* Object entry CSN */
126   var $entryCSN         = "";
127   var $CSN_check_active = FALSE;
129   /* This variable indicates that this class can handle multiple dns at once. */
130   var $multiple_support = FALSE;
131   var $multi_attrs      = array();
132   var $multi_attrs_all  = array(); 
134   /* This aviable indicates, that we are currently in multiple edit handle */
135   var $multiple_support_active = FALSE; 
136   var $selected_edit_values = array();
137   var $multi_boxes = array();
139   /*! \brief plugin constructor
141     If 'dn' is set, the node loads the given 'dn' from LDAP
143     \param dn Distinguished name to initialize plugin from
144     \sa plugin()
145    */
146   function plugin (&$config, $dn= NULL, $object= NULL)
147   {
148     /* Configuration is fine, allways */
149     $this->config= &$config;    
150     $this->dn= $dn;
152     // Ensure that we've a valid acl_category set.
153     if(empty($this->acl_category)){
154       $tmp = $this->plInfo();
155       if (isset($tmp['plCategory'])) {
156         $c = key($tmp['plCategory']);
157         if(is_numeric($c)){
158           $c = $tmp['plCategory'][0];
159         }
160         $this->acl_category = $c."/";
161       }
162     }
164     /* Handle new accounts, don't read information from LDAP */
165     if ($dn == "new"){
166       return;
167     }
169     /* Check if this entry was opened in read only mode */
170     if(isset($_POST['open_readonly'])){
171       if(session::global_is_set("LOCK_CACHE")){
172         $cache = &session::get("LOCK_CACHE");
173         if(isset($cache['READ_ONLY'][$this->dn])){
174           $this->read_only = TRUE;
175         }
176       }
177     }
179     /* Save current dn as acl_base */
180     $this->acl_base= $dn;
182     /* Get LDAP descriptor */
183     if ($dn !== NULL){
185       /* Load data to 'attrs' and save 'dn' */
186       if ($object !== NULL){
187         $this->attrs= $object->attrs;
188       } else {
189         $ldap= $this->config->get_ldap_link();
190         $ldap->cat ($dn);
191         $this->attrs= $ldap->fetch();
192       }
194       /* Copy needed attributes */
195       foreach ($this->attributes as $val){
196         $found= array_key_ics($val, $this->attrs);
197         if ($found != ""){
198           $this->$val= $found[0];
199         }
200       }
202       /* gosaUnitTag loading... */
203       if (isset($this->attrs['gosaUnitTag'][0])){
204         $this->gosaUnitTag= $this->attrs['gosaUnitTag'][0];
205       }
207       /* Set the template flag according to the existence of objectClass
208          gosaUserTemplate */
209       if (isset($this->attrs['objectClass'])){
210         if (in_array_ics ("gosaUserTemplate", $this->attrs['objectClass'])){
211           $this->is_template= TRUE;
212           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
213               "found", "Template check");
214         }
215       }
217       /* Is Account? */
218       $found= TRUE;
219       foreach ($this->objectclasses as $obj){
220         if (preg_match('/top/i', $obj)){
221           continue;
222         }
223         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
224           $found= FALSE;
225           break;
226         }
227       }
228       if ($found){
229         $this->is_account= TRUE;
230         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
231             "found", "Object check");
232       }
234       /* Prepare saved attributes */
235       $this->saved_attributes= $this->attrs;
236       foreach ($this->saved_attributes as $index => $value){
237         if (is_numeric($index)){
238           unset($this->saved_attributes[$index]);
239           continue;
240         }
242         if (!in_array_ics($index, $this->attributes) && strcasecmp('objectClass', $index)){
243           unset($this->saved_attributes[$index]);
244           continue;
245         }
247         if (isset($this->saved_attributes[$index][0])){
248           if(!isset($this->saved_attributes[$index]["count"])){
249             $this->saved_attributes[$index]["count"] = count($this->saved_attributes[$index]);
250           }
251           if($this->saved_attributes[$index]["count"] == 1){
252             $tmp= $this->saved_attributes[$index][0];
253             unset($this->saved_attributes[$index]);
254             $this->saved_attributes[$index]= $tmp;
255             continue;
256           }
257         }
258         unset($this->saved_attributes["$index"]["count"]);
259       }
261       if(isset($this->attrs['gosaUnitTag'])){
262         $this->saved_attributes['gosaUnitTag'] = $this->attrs['gosaUnitTag'][0];
263       }
264     }
266     /* Save initial account state */
267     $this->initially_was_account= $this->is_account;
268   }
271   /*! \brief Generates the html output for this node
272    */
273   function execute()
274   {
275     /* This one is empty currently. Fabian - please fill in the docu code */
276     session::global_set('current_class_for_help',get_class($this));
278     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
279     session::set('LOCK_VARS_TO_USE',array());
280     session::set('LOCK_VARS_USED_GET',array());
281     session::set('LOCK_VARS_USED_POST',array());
282     session::set('LOCK_VARS_USED_REQUEST',array());
284     pathNavigator::registerPlugin($this);
285   }
287   /*! \brief Removes object from parent
288    */
289   function remove_from_parent()
290   {
291     /* include global link_info */
292     $ldap= $this->config->get_ldap_link();
294     /* Get current objectClasses in order to add the required ones */
295     $ldap->cat($this->dn);
296     $tmp= $ldap->fetch ();
297     $oc= array();
298     if (isset($tmp['objectClass'])){
299       $oc= $tmp['objectClass'];
300       unset($oc['count']);
301     }
303     /* Remove objectClasses from entry */
304     $ldap->cd($this->dn);
305     $this->attrs= array();
306     $this->attrs['objectClass']= array_remove_entries_ics($this->objectclasses,$oc);
308     /* Unset attributes from entry */
309     foreach ($this->attributes as $val){
310       $this->attrs["$val"]= array();
311     }
313     /* Unset account info */
314     $this->is_account= FALSE;
316     /* Do not write in plugin base class, this must be done by
317        children, since there are normally additional attribs,
318        lists, etc. */
319     /*
320        $ldap->modify($this->attrs);
321      */
322   }
325   /*! \brief Save HTML posted data to object 
326    */
327   function save_object()
328   {
329     /* Update entry CSN if it is empty. */
330     if(empty($this->entryCSN) && $this->CSN_check_active){
331       $this->entryCSN = getEntryCSN($this->dn);
332     }
334     /* Save values to object */
335     foreach ($this->attributes as $val){
336       if (isset ($_POST["$val"]) && $this->acl_is_writeable($val)){
337         /* Check for modifications */
338         if (get_magic_quotes_gpc()) {
339           $data= stripcslashes($_POST["$val"]);
340         } else {
341           $data= $this->$val = $_POST["$val"];
342         }
343         if ($this->$val != $data){
344           $this->is_modified= TRUE;
345         }
346     
347         /* Okay, how can I explain this fix ... 
348          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
349          * So IE posts these 'unselectable' option, with value = chr(194) 
350          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
351          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
352          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
353          */
354         if(isset($data[0]) && $data[0] == chr(194)) {
355           $data = "";  
356         }
357         $this->$val= $data;
358       }
359     }
360   }
363   /*! \brief Save data to LDAP, depending on is_account we save or delete */
364   function save()
365   {
366     /* include global link_info */
367     $ldap= $this->config->get_ldap_link();
369     /* Save all plugins */
370     $this->entryCSN = "";
372     /* Start with empty array */
373     $this->attrs= array();
375     /* Get current objectClasses in order to add the required ones */
376     $ldap->cat($this->dn);
377     
378     $tmp= $ldap->fetch ();
380     $oc= array();
381     if (isset($tmp['objectClass'])){
382       $oc= $tmp["objectClass"];
383       $this->is_new= FALSE;
384       unset($oc['count']);
385     } else {
386       $this->is_new= TRUE;
387     }
389     /* Load (minimum) attributes, add missing ones */
390     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
392     /* Copy standard attributes */
393     foreach ($this->attributes as $val){
394       if ($this->$val != ""){
395         $this->attrs["$val"]= $this->$val;
396       } elseif (!$this->is_new) {
397         $this->attrs["$val"]= array();
398       }
399     }
401     /* Handle tagging */
402     $this->tag_attrs($this->attrs);
403   }
406   function cleanup()
407   {
408     foreach ($this->attrs as $index => $value){
409       
410       /* Convert arrays with one element to non arrays, if the saved
411          attributes are no array, too */
412       if (is_array($this->attrs[$index]) && 
413           count ($this->attrs[$index]) == 1 &&
414           isset($this->saved_attributes[$index]) &&
415           !is_array($this->saved_attributes[$index])){
416           
417         $tmp= $this->attrs[$index][0];
418         $this->attrs[$index]= $tmp;
419       }
421       /* Remove emtpy arrays if they do not differ */
422       if (is_array($this->attrs[$index]) &&
423           count($this->attrs[$index]) == 0 &&
424           !isset($this->saved_attributes[$index])){
425           
426         unset ($this->attrs[$index]);
427         continue;
428       }
430       /* Remove single attributes that do not differ */
431       if (!is_array($this->attrs[$index]) &&
432           isset($this->saved_attributes[$index]) &&
433           !is_array($this->saved_attributes[$index]) &&
434           $this->attrs[$index] == $this->saved_attributes[$index]){
436         unset ($this->attrs[$index]);
437         continue;
438       }
440       /* Remove arrays that do not differ */
441       if (is_array($this->attrs[$index]) && 
442           isset($this->saved_attributes[$index]) &&
443           is_array($this->saved_attributes[$index])){
444           
445         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
446           unset ($this->attrs[$index]);
447           continue;
448         }
449       }
450     }
452     /* Update saved attributes and ensure that next cleanups will be successful too */
453     foreach($this->attrs as $name => $value){
454       $this->saved_attributes[$name] = $value;
455     }
456   }
458   /*! \brief Check formular input */
459   function check()
460   {
461     $message= array();
463     /* Skip if we've no config object */
464     if (!isset($this->config) || !is_object($this->config)){
465       return $message;
466     }
468     /* Find hooks entries for this class */
469     $command = $this->config->configRegistry->getPropertyValue(get_class($this),"check");
470     if ($command != ""){
472       if (!check_command($command)){
473         $message[]= msgPool::cmdnotfound("CHECK", get_class($this));
474       } else {
476         /* Generate "ldif" for check hook */
477         $ldif= "dn: $this->dn\n";
478         
479         /* ... objectClasses */
480         foreach ($this->objectclasses as $oc){
481           $ldif.= "objectClass: $oc\n";
482         }
483         
484         /* ... attributes */
485         foreach ($this->attributes as $attr){
486           if ($this->$attr == ""){
487             continue;
488           }
489           if (is_array($this->$attr)){
490             foreach ($this->$attr as $val){
491               $ldif.= "$attr: $val\n";
492             }
493           } else {
494               $ldif.= "$attr: ".$this->$attr."\n";
495           }
496         }
498         /* Append empty line */
499         $ldif.= "\n";
501         /* Feed "ldif" into hook and retrieve result*/
502         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
503         $fh= proc_open($command, $descriptorspec, $pipes);
504         if (is_resource($fh)) {
505           fwrite ($pipes[0], $ldif);
506           fclose($pipes[0]);
507           
508           $result= stream_get_contents($pipes[1]);
509           if ($result != ""){
510             $message[]= $result;
511           }
512           
513           fclose($pipes[1]);
514           fclose($pipes[2]);
515           proc_close($fh);
516         }
517       }
519     }
521     /* Check entryCSN */
522     if($this->CSN_check_active){
523       $current_csn = getEntryCSN($this->dn);
524       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
525         $this->entryCSN = $current_csn;
526         $message[] = _("The current object has been altered while beeing edited. If you save this entry, changes that have been made by others will be discarded!");
527       }
528     }
529     return ($message);
530   }
532   /* Adapt from template, using 'dn' */
533   function adapt_from_template($dn, $skip= array())
534   {
535     /* Include global link_info */
536     $ldap= $this->config->get_ldap_link();
538     /* Load requested 'dn' to 'attrs' */
539     $ldap->cat ($dn);
540     $this->attrs= $ldap->fetch();
542     /* Walk through attributes */
543     foreach ($this->attributes as $val){
545       /* Skip the ones in skip list */
546       if (in_array($val, $skip)){
547         continue;
548       }
550       if (isset($this->attrs["$val"][0])){
552         /* If attribute is set, replace dynamic parts: 
553            %sn, %givenName and %uid. Fill these in our local variables. */
554         $value= $this->attrs["$val"][0];
556         foreach (array("sn", "givenName", "uid") as $repl){
557           if (preg_match("/%$repl/i", $value)){
558             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
559           }
560         }
561         $this->$val= $value;
562       }
563     }
565     /* Is Account? */
566     $found= TRUE;
567     foreach ($this->objectclasses as $obj){
568       if (preg_match('/top/i', $obj)){
569         continue;
570       }
571       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
572         $found= FALSE;
573         break;
574       }
575     }
576     if ($found){
577       $this->is_account= TRUE;
578     }
579   }
581   /* \brief Indicate whether a password change is needed or not */
582   function password_change_needed()
583   {
584     return FALSE;
585   }
588   /*! \brief Show header message for tab dialogs */
589   function show_enable_header($button_text, $text, $disabled= FALSE)
590   {
591     if (($disabled == TRUE) || (!$this->acl_is_createable())){
592       $state= "disabled";
593     } else {
594       $state= "";
595     }
596     $display = "<div class='plugin-enable-header'>\n";
597     $display.= "<p>$text</p>\n";
598     $display.= "<button type='submit' name=\"modify_state\" ".$state.">$button_text</button>\n";
599     $display.= "</div>\n";
601     return($display);
602   }
605   /*! \brief Show header message for tab dialogs */
606   function show_disable_header($button_text, $text, $disabled= FALSE)
607   {
608     if (($disabled == TRUE) || !$this->acl_is_removeable()){
609       $state= "disabled";
610     } else {
611       $state= "";
612     }
613     $display = "<div class='plugin-disable-header'>\n";
614     $display.= "<p>$text</p>\n";
615     $display.= "<button type='submit' name=\"modify_state\" ".$state.">$button_text</button>\n";
616     $display.= "</div>\n";
617     return($display);
618   }
622   /* Create unique DN */
623   function create_unique_dn2($data, $base)
624   {
625     $ldap= $this->config->get_ldap_link();
626     $base= preg_replace("/^,*/", "", $base);
628     /* Try to use plain entry first */
629     $dn= "$data,$base";
630     $attribute= preg_replace('/=.*$/', '', $data);
631     $ldap->cat ($dn, array('dn'));
632     if (!$ldap->fetch()){
633       return ($dn);
634     }
636     /* Look for additional attributes */
637     foreach ($this->attributes as $attr){
638       if ($attr == $attribute || $this->$attr == ""){
639         continue;
640       }
642       $dn= "$data+$attr=".$this->$attr.",$base";
643       $ldap->cat ($dn, array('dn'));
644       if (!$ldap->fetch()){
645         return ($dn);
646       }
647     }
649     /* None found */
650     return ("none");
651   }
654   /*! \brief Create unique DN */
655   function create_unique_dn($attribute, $base)
656   {
657     $ldap= $this->config->get_ldap_link();
658     $base= preg_replace("/^,*/", "", $base);
660     /* Try to use plain entry first */
661     $dn= "$attribute=".$this->$attribute.",$base";
662     $ldap->cat ($dn, array('dn'));
663     if (!$ldap->fetch()){
664       return ($dn);
665     }
667     /* Look for additional attributes */
668     foreach ($this->attributes as $attr){
669       if ($attr == $attribute || $this->$attr == ""){
670         continue;
671       }
673       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
674       $ldap->cat ($dn, array('dn'));
675       if (!$ldap->fetch()){
676         return ($dn);
677       }
678     }
680     /* None found */
681     return ("none");
682   }
685   function rebind($ldap, $referral)
686   {
687     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
688     if (ldap_bind($ldap, $credentials['ADMIN'], $this->config->get_credentials($credentials['PASSWORD']))) {
689       $this->error = "Success";
690       $this->hascon=true;
691       $this->reconnect= true;
692       return (0);
693     } else {
694       $this->error = "Could not bind to " . $credentials['ADMIN'];
695       return NULL;
696     }
697   }
700   /* Recursively copy ldap object */
701   function _copy($src_dn,$dst_dn)
702   {
703     $ldap=$this->config->get_ldap_link();
704     $ldap->cat($src_dn);
705     $attrs= $ldap->fetch();
707     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
708     $ds= ldap_connect($this->config->current['SERVER']);
709     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
710     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
711       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
712     }
714     $pwd = $this->config->get_credentials($this->config->current['ADMINPASSWORD']);
715     $r=ldap_bind($ds,$this->config->current['ADMINDN'], $pwd);
716     $sr=ldap_read($ds, LDAP::fix($src_dn), "objectClass=*");
718     /* Fill data from LDAP */
719     $new= array();
720     if ($sr) {
721       $ei=ldap_first_entry($ds, $sr);
722       if ($ei) {
723         foreach($attrs as $attr => $val){
724           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
725             for ($i= 0; $i<$info['count']; $i++){
726               if ($info['count'] == 1){
727                 $new[$attr]= $info[$i];
728               } else {
729                 $new[$attr][]= $info[$i];
730               }
731             }
732           }
733         }
734       }
735     }
737     /* close conncetion */
738     ldap_unbind($ds);
740     /* Adapt naming attribute */
741     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
742     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
743     $new[$dst_name]= LDAP::fix($dst_val);
745     /* Check if this is a department.
746      * If it is a dep. && there is a , override in his ou 
747      *  change \2C to , again, else this entry can't be saved ...
748      */
749     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
750       $new['ou'] = str_replace("\\\\,",",",$new['ou']);
751     }
753     /* Save copy */
754     $ldap->connect();
755     $ldap->cd($this->config->current['BASE']);
756     
757     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
759     /* FAIvariable=.../..., cn=.. 
760         could not be saved, because the attribute FAIvariable was different to 
761         the dn FAIvariable=..., cn=... */
763     if(!is_array($new['objectClass'])) $new['objectClass'] = array($new['objectClass']);
765     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
766       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
767     }
768     $ldap->cd($dst_dn);
769     $ldap->add($new);
771     if (!$ldap->success()){
772       trigger_error("Trying to save $dst_dn failed.",
773           E_USER_WARNING);
774       return(FALSE);
775     }
776     return(TRUE);
777   }
780   /* This is a workaround function. */
781   function copy($src_dn, $dst_dn)
782   {
783     /* Rename dn in possible object groups */
784     $ldap= $this->config->get_ldap_link();
785     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::prepare4filter($src_dn).'))',
786         array('cn'));
787     while ($attrs= $ldap->fetch()){
788       $og= new ogroup($this->config, $ldap->getDN());
789       unset($og->member[$src_dn]);
790       $og->member[$dst_dn]= $dst_dn;
791       $og->save ();
792     }
794     $ldap->cat($dst_dn);
795     $attrs= $ldap->fetch();
796     if (count($attrs)){
797       trigger_error("Trying to overwrite ".LDAP::fix($dst_dn).", which already exists.",
798           E_USER_WARNING);
799       return (FALSE);
800     }
802     $ldap->cat($src_dn);
803     $attrs= $ldap->fetch();
804     if (!count($attrs)){
805       trigger_error("Trying to move ".LDAP::fix($src_dn).", which does not seem to exist.",
806           E_USER_WARNING);
807       return (FALSE);
808     }
810     $ldap->cd($src_dn);
811     $ldap->search("objectClass=*",array("dn"));
812     while($attrs = $ldap->fetch()){
813       $src = $attrs['dn'];
814       $dst = preg_replace("/".preg_quote($src_dn, '/')."$/",$dst_dn,$attrs['dn']);
815       $this->_copy($src,$dst);
816     }
817     return (TRUE);
818   }
822   /*! \brief  Rename/Move a given src_dn to the given dest_dn
823    *
824    * Move a given ldap object indentified by $src_dn to the
825    * given destination $dst_dn
826    *
827    * - Ensure that all references are updated (ogroups)
828    * - Update ACLs   
829    * - Update accessTo
830    *
831    * \param  string  'src_dn' the source DN.
832    * \param  string  'dst_dn' the destination DN.
833    * \return boolean TRUE on success else FALSE.
834    */
835   function rename($src_dn, $dst_dn)
836   {
837     $start = microtime(1);
839     /* Try to move the source entry to the destination position */
840     $ldap = $this->config->get_ldap_link();
841     $ldap->cd($this->config->current['BASE']);
842     $ldap->create_missing_trees(preg_replace("/^[^,]+,/","",$dst_dn));
843     if (!$ldap->rename_dn($src_dn,$dst_dn)){
844       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());
845       @DEBUG(DEBUG_LDAP,__LINE__,__FUNCTION__,__FILE__,"Rename failed FROM: $src_dn  -- TO:  $dst_dn", 
846           "Ldap Protocol v3 implementation error, falling back to maunal method.");
847       return(FALSE);
848     }
850     /* Get list of users,groups and roles within this tree,
851         maybe we have to update ACL references.
852      */
853     $leaf_objs = get_list("(|(objectClass=posixGroup)(objectClass=gosaAccount)(objectClass=gosaRole))",array("all"),$dst_dn,
854           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
855     foreach($leaf_objs as $obj){
856       $new_dn = $obj['dn'];
857       $old_dn = preg_replace("/".preg_quote(LDAP::convert($dst_dn), '/')."$/i",$src_dn,LDAP::convert($new_dn));
858       $this->update_acls($old_dn,$new_dn); 
859     }
861     // Migrate objectgroups if needed
862     $ogroups = get_sub_list("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter(LDAP::fix($src_dn))."))",
863       "ogroups", array(get_ou("group", "ogroupRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
865     // Walk through all objectGroups
866     foreach($ogroups as $ogroup){
867       // Migrate old to new dn
868       $o_ogroup= new ogroup($this->config,$ogroup['dn']);
869       if (isset($o_ogroup->member[$src_dn])) {
870         unset($o_ogroup->member[$src_dn]);
871       }
872       $o_ogroup->member[$dst_dn]= $dst_dn;
873       
874       // Save object group
875       $o_ogroup->save();
876     }
878     // Migrate rfc groups if needed
879     $groups = get_sub_list("(&(objectClass=posixGroup)(member=".LDAP::prepare4filter(LDAP::fix($src_dn))."))","groups", array(get_ou("core", "groupRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
881     // Walk through all POSIX groups
882     foreach($groups as $group){
884       // Migrate old to new dn
885       $o_group= new group($this->config,$group['dn']);
886       $o_group->save();
887     }
889     /* Update roles to use the new entry dn */
890     $roles = get_sub_list("(&(objectClass=organizationalRole)(roleOccupant=".LDAP::prepare4filter(LDAP::fix($src_dn))."))","roles", array(get_ou("roleGeneric", "roleRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
892     // Walk through all roles
893     foreach($roles as $role){
894       $role = new roleGeneric($this->config,$role['dn']);
895       $key= array_search($src_dn, $role->roleOccupant);      
896       if($key !== FALSE){
897         $role->roleOccupant[$key] = $dst_dn;
898         $role->save();
899       }
900     }
902     // Update 'manager' attributes from gosaDepartment and inetOrgPerson 
903     $filter = "(&(objectClass=inetOrgPerson)(manager=".LDAP::prepare4filter(LDAP::fix($src_dn))."))";
904     $ocs = $ldap->get_objectclasses();
905     if(isset($ocs['gosaDepartment']['MAY']) && in_array('manager', $ocs['gosaDepartment']['MAY'])){
906       $filter = "(|".$filter."(&(objectClass=gosaDepartment)(manager=".LDAP::prepare4filter(LDAP::fix($src_dn)).")))";
907     }
908     $leaf_deps=  get_list($filter,array("all"),$this->config->current['BASE'], 
909         array("manager","dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
910     foreach($leaf_deps as $entry){
911       $update = array('manager' => $dst_dn);
912       $ldap->cd($entry['dn']);
913       $ldap->modify($update);
914       if(!$ldap->success()){
915         trigger_error(sprintf("Failed to update manager for %s: %s", bold($entry['dn']), $ldap->get_error()));
916       }
917     }
919     // Migrate 'dyn-groups' here. labeledURIObject
920     if(class_available('DynamicLdapGroup')) {
921         DynamicLdapGroup::moveDynGroup($this->config,$src_dn,$dst_dn);
922     }
923  
924     /* Check if there are gosa departments moved. 
925        If there were deps moved, the force reload of config->deps.
926      */
927     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
928           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
929   
930     if(count($leaf_deps)){
931       $this->config->get_departments();
932       $this->config->make_idepartments();
933       session::global_set("config",$this->config);
934       $ui =get_userinfo();
935       $ui->reset_acl_cache();
936     }
938     return(TRUE); 
939   }
942  
943   function move($src_dn, $dst_dn)
944   {
945     /* Do not copy if only upper- lowercase has changed */
946     if(strtolower($src_dn) == strtolower($dst_dn)){
947       return(TRUE);
948     }
950     
951     /* Try to move the entry instead of copy & delete
952      */
953     if(TRUE){
955       /* Try to move with ldap routines, if this was not successfull
956           fall back to the old style copy & remove method 
957        */
958       if($this->rename($src_dn, $dst_dn)){
959         return(TRUE);
960       }else{
961         // See code below.
962       }
963     }
965     /* Copy source to destination */
966     if (!$this->copy($src_dn, $dst_dn)){
967       return (FALSE);
968     }
970     /* Delete source */
971     $ldap= $this->config->get_ldap_link();
972     $ldap->rmdir_recursive($src_dn);
973     if (!$ldap->success()){
974       trigger_error("Trying to delete $src_dn failed.",
975           E_USER_WARNING);
976       return (FALSE);
977     }
979     return (TRUE);
980   }
983   /* \brief Move/Rename complete trees */
984   function recursive_move($src_dn, $dst_dn)
985   {
986     /* Check if the destination entry exists */
987     $ldap= $this->config->get_ldap_link();
989     /* Check if destination exists - abort */
990     $ldap->cat($dst_dn, array('dn'));
991     if ($ldap->fetch()){
992       trigger_error("recursive_move $dst_dn already exists.",
993           E_USER_WARNING);
994       return (FALSE);
995     }
997     $this->copy($src_dn, $dst_dn);
999     /* Remove src_dn */
1000     $ldap->cd($src_dn);
1001     $ldap->recursive_remove($src_dn);
1002     return (TRUE);
1003   }
1006   function saveCopyDialog(){
1007   }
1010   function getCopyDialog(){
1011     return(array("string"=>"","status"=>""));
1012   }
1015   /*! \brief Prepare for Copy & Paste */
1016   function PrepareForCopyPaste($source)
1017   {
1018     $todo = $this->attributes;
1019     if(isset($this->CopyPasteVars)){
1020       $todo = array_merge($todo,$this->CopyPasteVars);
1021     }
1023     if(count($this->objectclasses)){
1024       $this->is_account = TRUE;
1025       foreach($this->objectclasses as $class){
1026         if(!in_array($class,$source['objectClass'])){
1027           $this->is_account = FALSE;
1028         }
1029       }
1030     }
1032     foreach($todo as $var){
1033       if (isset($source[$var])){
1034         if(isset($source[$var]['count'])){
1035           if($source[$var]['count'] > 1){
1036             $tmp= $source[$var];
1037             unset($tmp['count']);
1038             $this->$var = $tmp;
1039           }else{
1040             $this->$var = $source[$var][0];
1041           }
1042         }else{
1043           $this->$var= $source[$var];
1044         }
1045       }
1046     }
1047   }
1049   /*! \brief Get gosaUnitTag for the given DN
1050        If this is called from departmentGeneric, we have to skip this
1051         tagging procedure. 
1052     */
1053   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1054   {
1055     /* Skip tagging? */
1056     if($this->skipTagging){
1057       return;
1058     }
1060     /* No dn? Self-operation... */
1061     if ($dn == ""){
1062       $dn= $this->dn;
1064       /* No tag? Find it yourself... */
1065       if ($tag == ""){
1066         $len= strlen($dn);
1068         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1069         $relevant= array();
1070         foreach ($this->config->adepartments as $key => $ntag){
1072           /* This one is bigger than our dn, its not relevant... */
1073           if ($len < strlen($key)){
1074             continue;
1075           }
1077           /* This one matches with the latter part. Break and don't fix this entry */
1078           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
1079             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1080             $relevant[strlen($key)]= $ntag;
1081             continue;
1082           }
1084         }
1086         /* If we've some relevant tags to set, just get the longest one */
1087         if (count($relevant)){
1088           ksort($relevant);
1089           $tmp= array_keys($relevant);
1090           $idx= end($tmp);
1091           $tag= $relevant[$idx];
1092           $this->gosaUnitTag= $tag;
1093         }
1094       }
1095     }
1097   /*! \brief Add unit tag */ 
1098     /* Remove tags that may already be here... */
1099     remove_objectClass("gosaAdministrativeUnitTag", $at);
1100     if (isset($at['gosaUnitTag'])){
1101         unset($at['gosaUnitTag']);
1102     }
1104     /* Set tag? */
1105     if ($tag != ""){
1106       add_objectClass("gosaAdministrativeUnitTag", $at);
1107       $at['gosaUnitTag']= $tag;
1108     }
1110     /* Initially this object was tagged. 
1111        - But now, it is no longer inside a tagged department. 
1112        So force the remove of the tag.
1113        (objectClass was already removed obove)
1114      */
1115     if($tag == "" && $this->gosaUnitTag){
1116       $at['gosaUnitTag'] = array();
1117     }
1118   }
1121   /*! \brief Test for removability of the object
1122    *
1123    * Allows testing of conditions for removal of object. If removal should be aborted
1124    * the function needs to remove an error message.
1125    * */
1126   function allow_remove()
1127   {
1128     $reason= "";
1129     return $reason;
1130   }
1133   /*! \brief Test if snapshotting is enabled
1134    *
1135    * Test weither snapshotting is enabled or not. There will also be some errors posted,
1136    * if the configuration failed 
1137    * \return TRUE if snapshots are enabled, and FALSE if it is disabled
1138    */
1139   function snapshotEnabled()
1140   {
1141       return $this->config->snapshotEnabled();
1142   }
1145   /*! \brief Return plugin informations for acl handling */
1146   static function plInfo()
1147   {
1148     return array();
1149   }
1152   function set_acl_base($base)
1153   {
1154     @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,"<b>".$base."</b>","<b>ACL-Base:</b> ");
1155     $this->acl_base= $base;
1156   }
1159   function set_acl_category($category)
1160   {
1161     @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,"<b>".$category."</b>(/".get_class($this).")","<b>ACL-Category:</b> ");
1162     $this->acl_category= "$category/";
1163   }
1166   function acl_is_writeable($attribute,$skip_write = FALSE)
1167   {
1168     if($this->read_only) return(FALSE);
1169     $ui= get_userinfo();
1170     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1171   }
1174   function acl_is_readable($attribute)
1175   {
1176     $ui= get_userinfo();
1177     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1178   }
1181   function acl_is_createable($base ="")
1182   {
1183     if($this->read_only) return(FALSE);
1184     $ui= get_userinfo();
1185     if($base == "") $base = $this->acl_base;
1186     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1187   }
1190   function acl_is_removeable($base ="")
1191   {
1192     if($this->read_only) return(FALSE);
1193     $ui= get_userinfo();
1194     if($base == "") $base = $this->acl_base;
1195     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1196   }
1199   function acl_is_moveable($base = "")
1200   {
1201     if($this->read_only) return(FALSE);
1202     $ui= get_userinfo();
1203     if($base == "") $base = $this->acl_base;
1204     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1205   }
1208   function acl_have_any_permissions()
1209   {
1210   }
1213   function getacl($attribute,$skip_write= FALSE)
1214   {
1215     $ui= get_userinfo();
1216     $skip_write |= $this->read_only;
1217     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1218   }
1221   /*! \brief Returns a list of all available departments for this object.
1222    * 
1223    * If this object is new, all departments we are allowed to create a new user in
1224    * are returned. If this is an existing object, return all deps. 
1225    * We are allowed to move tis object too.
1226    * \return array [dn] => "..name"  // All deps. we are allowed to act on.
1227   */
1228   function get_allowed_bases()
1229   {
1230     $ui = get_userinfo();
1231     $deps = array();
1233     /* Is this a new object ? Or just an edited existing object */
1234     if(!$this->initially_was_account && $this->is_account){
1235       $new = true;
1236     }else{
1237       $new = false;
1238     }
1240     foreach($this->config->idepartments as $dn => $name){
1241       if($new && $this->acl_is_createable($dn)){
1242         $deps[$dn] = $name;
1243       }elseif(!$new && $this->acl_is_moveable($dn)){
1244         $deps[$dn] = $name;
1245       }
1246     }
1248     /* Add current base */      
1249     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1250       $deps[$this->base] = $this->config->idepartments[$this->base];
1251     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1253     }else{
1254       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1255     }
1256     return($deps);
1257   }
1260   /* This function updates ACL settings if $old_dn was used.
1261    *  \param string 'old_dn' specifies the actually used dn
1262    *  \param string 'new_dn' specifies the destiantion dn
1263    */
1264   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1265   {
1266     /* Check if old_dn is empty. This should never happen */
1267     if(empty($old_dn) || empty($new_dn)){
1268       trigger_error("Failed to check acl dependencies, wrong dn given.");
1269       return;
1270     }
1272     /* Update userinfo if necessary */
1273     $ui = session::global_get('ui');
1274     if($ui->dn == $old_dn){
1275       $ui->dn = $new_dn;
1276       session::global_set('ui',$ui);
1277       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1278     }
1280     /* Object was moved, ensure that all acls will be moved too */
1281     if($new_dn != $old_dn && $old_dn != "new"){
1283       /* get_ldap configuration */
1284       $update = array();
1285       $ldap = $this->config->get_ldap_link();
1286       $ldap->cd ($this->config->current['BASE']);
1287       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1288       while($attrs = $ldap->fetch()){
1289         $acls = array();
1290         $found = false;
1291         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1292           $acl_parts = explode(":",$attrs['gosaAclEntry'][$i]);
1294           /* Roles uses antoher data storage order, members are stored int the third part, 
1295              while the members in direct ACL assignments are stored in the second part.
1296            */
1297           $id = ($acl_parts[1] == "role") ? 3 : 2;
1299           /* Update member entries to use $new_dn instead of old_dn
1300            */
1301           $members = explode(",",$acl_parts[$id]);
1302           foreach($members as $key => $member){
1303             $member = base64_decode($member);
1304             if($member == $old_dn){
1305               $members[$key] = base64_encode($new_dn);
1306               $found = TRUE;
1307             }
1308           } 
1310           /* Check if the selected role has to updated
1311            */
1312           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1313             $acl_parts[2] = base64_encode($new_dn);
1314             $found = TRUE;
1315           }
1317           /* Build new acl string */ 
1318           $acl_parts[$id] = implode($members,",");
1319           $acls[] = implode($acl_parts,":");
1320         }
1322         /* Acls for this object must be adjusted */
1323         if($found){
1325           $debug_info= sprintf(_("Changing ACL DN from %s to %s"), bold($old_dn), bold($new_dn));
1326           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1328           $update[$attrs['dn']] =array();
1329           foreach($acls as $acl){
1330             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1331           }
1332         }
1333       }
1335       /* Write updated acls */
1336       foreach($update as $dn => $attrs){
1337         $ldap->cd($dn);
1338         $ldap->modify($attrs);
1339       }
1340     }
1341   }
1343   
1345   /*! \brief Enable the Serial ID check
1346    *
1347    * This function enables the entry Serial ID check.  If an entry was edited while
1348    * we have edited the entry too, an error message will be shown. 
1349    * To configure this check correctly read the FAQ.
1350    */    
1351   function enable_CSN_check()
1352   {
1353     $this->CSN_check_active =TRUE;
1354     $this->entryCSN = getEntryCSN($this->dn);
1355   }
1358   /*! \brief  Prepares the plugin to be used for multiple edit
1359    *          Update plugin attributes with given array of attribtues.
1360    *  \param  array   Array with attributes that must be updated.
1361    */
1362   function init_multiple_support($attrs,$all)
1363   {
1364     $ldap= $this->config->get_ldap_link();
1365     $this->multi_attrs    = $attrs;
1366     $this->multi_attrs_all= $all;
1368     /* Copy needed attributes */
1369     foreach ($this->attributes as $val){
1370       $found= array_key_ics($val, $this->multi_attrs);
1371  
1372       if ($found != ""){
1373         if(isset($this->multi_attrs["$val"][0])){
1374           $this->$val= $this->multi_attrs["$val"][0];
1375         }
1376       }
1377     }
1378   }
1380  
1381   /*! \brief  Enables multiple support for this plugin
1382    */
1383   function enable_multiple_support()
1384   {
1385     $this->ignore_account = TRUE;
1386     $this->multiple_support_active = TRUE;
1387   }
1390   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1391       \return array Cotaining all modified values. 
1392    */
1393   function get_multi_edit_values()
1394   {
1395     $ret = array();
1396     foreach($this->attributes as $attr){
1397       if(in_array($attr,$this->multi_boxes)){
1398         $ret[$attr] = $this->$attr;
1399       }
1400     }
1401     return($ret);
1402   }
1404   
1405   /*! \brief  Update class variables with values collected by multiple edit.
1406    */
1407   function set_multi_edit_values($attrs)
1408   {
1409     foreach($attrs as $name => $value){
1410       $this->$name = $value;
1411     }
1412   }
1415   /*! \brief Generates the html output for this node for multi edit*/
1416   function multiple_execute()
1417   {
1418     /* This one is empty currently. Fabian - please fill in the docu code */
1419     session::global_set('current_class_for_help',get_class($this));
1421     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1422     session::set('LOCK_VARS_TO_USE',array());
1423     session::set('LOCK_VARS_USED_GET',array());
1424     session::set('LOCK_VARS_USED_POST',array());
1425     session::set('LOCK_VARS_USED_REQUEST',array());
1426     
1427     return("Multiple edit is currently not implemented for this plugin.");
1428   }
1431   /*! \brief Save HTML posted data to object for multiple edit
1432    */
1433   function multiple_save_object()
1434   {
1435     if(empty($this->entryCSN) && $this->CSN_check_active){
1436       $this->entryCSN = getEntryCSN($this->dn);
1437     }
1439     /* Save values to object */
1440     $this->multi_boxes = array();
1441     foreach ($this->attributes as $val){
1442   
1443       /* Get selected checkboxes from multiple edit */
1444       if(isset($_POST["use_".$val])){
1445         $this->multi_boxes[] = $val;
1446       }
1448       if (isset ($_POST["$val"]) && $this->acl_is_writeable($val)){
1450         /* Check for modifications */
1451         if (get_magic_quotes_gpc()) {
1452           $data= stripcslashes($_POST["$val"]);
1453         } else {
1454           $data= $this->$val = $_POST["$val"];
1455         }
1456         if ($this->$val != $data){
1457           $this->is_modified= TRUE;
1458         }
1459     
1460         /* IE post fix */
1461         if(isset($data[0]) && $data[0] == chr(194)) {
1462           $data = "";  
1463         }
1464         $this->$val= $data;
1465       }
1466     }
1467   }
1470   /*! \brief Returns all attributes of this plugin, 
1471                to be able to detect multiple used attributes 
1472                in multi_plugg::detect_multiple_used_attributes().
1473       @return array Attributes required for intialization of multi_plug
1474    */
1475   public function get_multi_init_values()
1476   {
1477     $attrs = $this->attrs;
1478     return($attrs);
1479   }
1482   /*! \brief  Check given values in multiple edit
1483       \return array Error messages
1484    */
1485   function multiple_check()
1486   {
1487     $message = plugin::check();
1488     return($message);
1489   }
1491   function get_used_snapshot_bases()
1492   {
1493      return(array());
1494   }
1496   function is_modal_dialog()
1497   {
1498     return(isset($this->dialog) && $this->dialog);
1499   }
1502   /*! \brief    Forward command execution requests
1503    *             to the hook execution method. 
1504    */
1505   function handle_post_events($mode, $addAttrs= array())
1506   {
1507     if(!in_array($mode, array('add','remove','modify'))){
1508       trigger_error(sprintf("Invalid post event type given %s! Valid types are [add,modify,remove].", bold($mode)));
1509       return;
1510     }
1511     switch ($mode){
1512       case "add":
1513         plugin::callHook($this,"POSTCREATE", $addAttrs);
1514       break;
1516       case "modify":
1517         plugin::callHook($this,"POSTMODIFY", $addAttrs);
1518       break;
1520       case "remove":
1521         plugin::callHook($this,"POSTREMOVE", $addAttrs);
1522       break;
1523     }
1524   }
1527   /*! \brief    Calls external hooks which are defined for this plugin (gosa.conf)
1528    *            Replaces placeholder by class values of this plugin instance.
1529    *  @param    Allows to a add special replacements.
1530    */
1531   static function callHook($plugin, $cmd, $addAttrs= array())
1532   {
1533     global $config;
1534     $command = $config->configRegistry->getPropertyValue(get_class($plugin),$cmd);
1535     
1536     if ($command != ""){
1538       // Walk trough attributes list and add the plugins attributes. 
1539       foreach ($plugin->attributes as $attr){
1540         if (!is_array($plugin->$attr)){
1541           $addAttrs[$attr] = $plugin->$attr;
1542         }
1543       }
1544       $ui = get_userinfo();
1545       $addAttrs['callerDN']=$ui->dn;
1546       $addAttrs['dn']=$plugin->dn;
1548       // Sort attributes by length, ensures correct replacement
1549       $tmp = array();
1550       foreach($addAttrs as $name => $value){
1551         $tmp[$name] =  strlen($name);
1552       }
1553       arsort($tmp);
1555       // Now replace the placeholder 
1556       foreach ($tmp as $name => $len){
1557         $value = $addAttrs[$name];
1558         $command= str_replace("%$name", "$value", $command);
1559       }
1561       // If there are still some %.. in our command, try to fill these with some other class vars 
1562       if(preg_match("/%/",$command)){
1563         $attrs = get_object_vars($plugin);
1564         foreach($attrs as $name => $value){
1565           if(is_array($value)){
1566             $s = "";
1567             foreach($value as $val){
1568               if(is_string($val) || is_int($val) || is_float($val) || is_bool($val)){
1569                 $s .= '"'.$val.'",'; 
1570               }
1571             }
1572             $value = '['.trim($s,',').']';
1573           }
1574           if(!is_string($value) && !is_int($value) && !is_float($value) && !is_bool($value)){
1575             continue;
1576           }
1577           $command= preg_replace("/%$name/", $value, $command);
1578         }
1579       }
1581       if (check_command($command)){
1582         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,$command,"Execute");
1583         exec($command,$arr);
1584         if(is_array($arr)){
1585           $str = implode("\n",$arr);
1586           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Result: ".$str);
1587         }
1588       } else {
1589         $message= msgPool::cmdnotfound("POSTCREATE", get_class($plugin));
1590         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
1591       }
1592     }
1593   }
1596 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1597 ?>