Code

Check hook call
[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($plugin),"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("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("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("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     }
918  
919     /* Check if there are gosa departments moved. 
920        If there were deps moved, the force reload of config->deps.
921      */
922     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
923           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
924   
925     if(count($leaf_deps)){
926       $this->config->get_departments();
927       $this->config->make_idepartments();
928       session::global_set("config",$this->config);
929       $ui =get_userinfo();
930       $ui->reset_acl_cache();
931     }
933     return(TRUE); 
934   }
937  
938   function move($src_dn, $dst_dn)
939   {
940     /* Do not copy if only upper- lowercase has changed */
941     if(strtolower($src_dn) == strtolower($dst_dn)){
942       return(TRUE);
943     }
945     
946     /* Try to move the entry instead of copy & delete
947      */
948     if(TRUE){
950       /* Try to move with ldap routines, if this was not successfull
951           fall back to the old style copy & remove method 
952        */
953       if($this->rename($src_dn, $dst_dn)){
954         return(TRUE);
955       }else{
956         // See code below.
957       }
958     }
960     /* Copy source to destination */
961     if (!$this->copy($src_dn, $dst_dn)){
962       return (FALSE);
963     }
965     /* Delete source */
966     $ldap= $this->config->get_ldap_link();
967     $ldap->rmdir_recursive($src_dn);
968     if (!$ldap->success()){
969       trigger_error("Trying to delete $src_dn failed.",
970           E_USER_WARNING);
971       return (FALSE);
972     }
974     return (TRUE);
975   }
978   /* \brief Move/Rename complete trees */
979   function recursive_move($src_dn, $dst_dn)
980   {
981     /* Check if the destination entry exists */
982     $ldap= $this->config->get_ldap_link();
984     /* Check if destination exists - abort */
985     $ldap->cat($dst_dn, array('dn'));
986     if ($ldap->fetch()){
987       trigger_error("recursive_move $dst_dn already exists.",
988           E_USER_WARNING);
989       return (FALSE);
990     }
992     $this->copy($src_dn, $dst_dn);
994     /* Remove src_dn */
995     $ldap->cd($src_dn);
996     $ldap->recursive_remove($src_dn);
997     return (TRUE);
998   }
1001   function saveCopyDialog(){
1002   }
1005   function getCopyDialog(){
1006     return(array("string"=>"","status"=>""));
1007   }
1010   /*! \brief Prepare for Copy & Paste */
1011   function PrepareForCopyPaste($source)
1012   {
1013     $todo = $this->attributes;
1014     if(isset($this->CopyPasteVars)){
1015       $todo = array_merge($todo,$this->CopyPasteVars);
1016     }
1018     if(count($this->objectclasses)){
1019       $this->is_account = TRUE;
1020       foreach($this->objectclasses as $class){
1021         if(!in_array($class,$source['objectClass'])){
1022           $this->is_account = FALSE;
1023         }
1024       }
1025     }
1027     foreach($todo as $var){
1028       if (isset($source[$var])){
1029         if(isset($source[$var]['count'])){
1030           if($source[$var]['count'] > 1){
1031             $tmp= $source[$var];
1032             unset($tmp['count']);
1033             $this->$var = $tmp;
1034           }else{
1035             $this->$var = $source[$var][0];
1036           }
1037         }else{
1038           $this->$var= $source[$var];
1039         }
1040       }
1041     }
1042   }
1044   /*! \brief Get gosaUnitTag for the given DN
1045        If this is called from departmentGeneric, we have to skip this
1046         tagging procedure. 
1047     */
1048   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1049   {
1050     /* Skip tagging? */
1051     if($this->skipTagging){
1052       return;
1053     }
1055     /* No dn? Self-operation... */
1056     if ($dn == ""){
1057       $dn= $this->dn;
1059       /* No tag? Find it yourself... */
1060       if ($tag == ""){
1061         $len= strlen($dn);
1063         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1064         $relevant= array();
1065         foreach ($this->config->adepartments as $key => $ntag){
1067           /* This one is bigger than our dn, its not relevant... */
1068           if ($len < strlen($key)){
1069             continue;
1070           }
1072           /* This one matches with the latter part. Break and don't fix this entry */
1073           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
1074             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1075             $relevant[strlen($key)]= $ntag;
1076             continue;
1077           }
1079         }
1081         /* If we've some relevant tags to set, just get the longest one */
1082         if (count($relevant)){
1083           ksort($relevant);
1084           $tmp= array_keys($relevant);
1085           $idx= end($tmp);
1086           $tag= $relevant[$idx];
1087           $this->gosaUnitTag= $tag;
1088         }
1089       }
1090     }
1092   /*! \brief Add unit tag */ 
1093     /* Remove tags that may already be here... */
1094     remove_objectClass("gosaAdministrativeUnitTag", $at);
1095     if (isset($at['gosaUnitTag'])){
1096         unset($at['gosaUnitTag']);
1097     }
1099     /* Set tag? */
1100     if ($tag != ""){
1101       add_objectClass("gosaAdministrativeUnitTag", $at);
1102       $at['gosaUnitTag']= $tag;
1103     }
1105     /* Initially this object was tagged. 
1106        - But now, it is no longer inside a tagged department. 
1107        So force the remove of the tag.
1108        (objectClass was already removed obove)
1109      */
1110     if($tag == "" && $this->gosaUnitTag){
1111       $at['gosaUnitTag'] = array();
1112     }
1113   }
1116   /*! \brief Test for removability of the object
1117    *
1118    * Allows testing of conditions for removal of object. If removal should be aborted
1119    * the function needs to remove an error message.
1120    * */
1121   function allow_remove()
1122   {
1123     $reason= "";
1124     return $reason;
1125   }
1128   /*! \brief Test if snapshotting is enabled
1129    *
1130    * Test weither snapshotting is enabled or not. There will also be some errors posted,
1131    * if the configuration failed 
1132    * \return TRUE if snapshots are enabled, and FALSE if it is disabled
1133    */
1134   function snapshotEnabled()
1135   {
1136       return $this->config->snapshotEnabled();
1137   }
1140   /*! \brief Return plugin informations for acl handling */
1141   static function plInfo()
1142   {
1143     return array();
1144   }
1147   function set_acl_base($base)
1148   {
1149     @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,"<b>".$base."</b>","<b>ACL-Base:</b> ");
1150     $this->acl_base= $base;
1151   }
1154   function set_acl_category($category)
1155   {
1156     @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,"<b>".$category."</b>(/".get_class($this).")","<b>ACL-Category:</b> ");
1157     $this->acl_category= "$category/";
1158   }
1161   function acl_is_writeable($attribute,$skip_write = FALSE)
1162   {
1163     if($this->read_only) return(FALSE);
1164     $ui= get_userinfo();
1165     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1166   }
1169   function acl_is_readable($attribute)
1170   {
1171     $ui= get_userinfo();
1172     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1173   }
1176   function acl_is_createable($base ="")
1177   {
1178     if($this->read_only) return(FALSE);
1179     $ui= get_userinfo();
1180     if($base == "") $base = $this->acl_base;
1181     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1182   }
1185   function acl_is_removeable($base ="")
1186   {
1187     if($this->read_only) return(FALSE);
1188     $ui= get_userinfo();
1189     if($base == "") $base = $this->acl_base;
1190     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1191   }
1194   function acl_is_moveable($base = "")
1195   {
1196     if($this->read_only) return(FALSE);
1197     $ui= get_userinfo();
1198     if($base == "") $base = $this->acl_base;
1199     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1200   }
1203   function acl_have_any_permissions()
1204   {
1205   }
1208   function getacl($attribute,$skip_write= FALSE)
1209   {
1210     $ui= get_userinfo();
1211     $skip_write |= $this->read_only;
1212     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1213   }
1216   /*! \brief Returns a list of all available departments for this object.
1217    * 
1218    * If this object is new, all departments we are allowed to create a new user in
1219    * are returned. If this is an existing object, return all deps. 
1220    * We are allowed to move tis object too.
1221    * \return array [dn] => "..name"  // All deps. we are allowed to act on.
1222   */
1223   function get_allowed_bases()
1224   {
1225     $ui = get_userinfo();
1226     $deps = array();
1228     /* Is this a new object ? Or just an edited existing object */
1229     if(!$this->initially_was_account && $this->is_account){
1230       $new = true;
1231     }else{
1232       $new = false;
1233     }
1235     foreach($this->config->idepartments as $dn => $name){
1236       if($new && $this->acl_is_createable($dn)){
1237         $deps[$dn] = $name;
1238       }elseif(!$new && $this->acl_is_moveable($dn)){
1239         $deps[$dn] = $name;
1240       }
1241     }
1243     /* Add current base */      
1244     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1245       $deps[$this->base] = $this->config->idepartments[$this->base];
1246     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1248     }else{
1249       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1250     }
1251     return($deps);
1252   }
1255   /* This function updates ACL settings if $old_dn was used.
1256    *  \param string 'old_dn' specifies the actually used dn
1257    *  \param string 'new_dn' specifies the destiantion dn
1258    */
1259   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1260   {
1261     /* Check if old_dn is empty. This should never happen */
1262     if(empty($old_dn) || empty($new_dn)){
1263       trigger_error("Failed to check acl dependencies, wrong dn given.");
1264       return;
1265     }
1267     /* Update userinfo if necessary */
1268     $ui = session::global_get('ui');
1269     if($ui->dn == $old_dn){
1270       $ui->dn = $new_dn;
1271       session::global_set('ui',$ui);
1272       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1273     }
1275     /* Object was moved, ensure that all acls will be moved too */
1276     if($new_dn != $old_dn && $old_dn != "new"){
1278       /* get_ldap configuration */
1279       $update = array();
1280       $ldap = $this->config->get_ldap_link();
1281       $ldap->cd ($this->config->current['BASE']);
1282       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1283       while($attrs = $ldap->fetch()){
1284         $acls = array();
1285         $found = false;
1286         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1287           $acl_parts = explode(":",$attrs['gosaAclEntry'][$i]);
1289           /* Roles uses antoher data storage order, members are stored int the third part, 
1290              while the members in direct ACL assignments are stored in the second part.
1291            */
1292           $id = ($acl_parts[1] == "role") ? 3 : 2;
1294           /* Update member entries to use $new_dn instead of old_dn
1295            */
1296           $members = explode(",",$acl_parts[$id]);
1297           foreach($members as $key => $member){
1298             $member = base64_decode($member);
1299             if($member == $old_dn){
1300               $members[$key] = base64_encode($new_dn);
1301               $found = TRUE;
1302             }
1303           } 
1305           /* Check if the selected role has to updated
1306            */
1307           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1308             $acl_parts[2] = base64_encode($new_dn);
1309             $found = TRUE;
1310           }
1312           /* Build new acl string */ 
1313           $acl_parts[$id] = implode($members,",");
1314           $acls[] = implode($acl_parts,":");
1315         }
1317         /* Acls for this object must be adjusted */
1318         if($found){
1320           $debug_info= sprintf(_("Changing ACL DN from %s to %s"), bold($old_dn), bold($new_dn));
1321           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1323           $update[$attrs['dn']] =array();
1324           foreach($acls as $acl){
1325             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1326           }
1327         }
1328       }
1330       /* Write updated acls */
1331       foreach($update as $dn => $attrs){
1332         $ldap->cd($dn);
1333         $ldap->modify($attrs);
1334       }
1335     }
1336   }
1338   
1340   /*! \brief Enable the Serial ID check
1341    *
1342    * This function enables the entry Serial ID check.  If an entry was edited while
1343    * we have edited the entry too, an error message will be shown. 
1344    * To configure this check correctly read the FAQ.
1345    */    
1346   function enable_CSN_check()
1347   {
1348     $this->CSN_check_active =TRUE;
1349     $this->entryCSN = getEntryCSN($this->dn);
1350   }
1353   /*! \brief  Prepares the plugin to be used for multiple edit
1354    *          Update plugin attributes with given array of attribtues.
1355    *  \param  array   Array with attributes that must be updated.
1356    */
1357   function init_multiple_support($attrs,$all)
1358   {
1359     $ldap= $this->config->get_ldap_link();
1360     $this->multi_attrs    = $attrs;
1361     $this->multi_attrs_all= $all;
1363     /* Copy needed attributes */
1364     foreach ($this->attributes as $val){
1365       $found= array_key_ics($val, $this->multi_attrs);
1366  
1367       if ($found != ""){
1368         if(isset($this->multi_attrs["$val"][0])){
1369           $this->$val= $this->multi_attrs["$val"][0];
1370         }
1371       }
1372     }
1373   }
1375  
1376   /*! \brief  Enables multiple support for this plugin
1377    */
1378   function enable_multiple_support()
1379   {
1380     $this->ignore_account = TRUE;
1381     $this->multiple_support_active = TRUE;
1382   }
1385   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1386       \return array Cotaining all modified values. 
1387    */
1388   function get_multi_edit_values()
1389   {
1390     $ret = array();
1391     foreach($this->attributes as $attr){
1392       if(in_array($attr,$this->multi_boxes)){
1393         $ret[$attr] = $this->$attr;
1394       }
1395     }
1396     return($ret);
1397   }
1399   
1400   /*! \brief  Update class variables with values collected by multiple edit.
1401    */
1402   function set_multi_edit_values($attrs)
1403   {
1404     foreach($attrs as $name => $value){
1405       $this->$name = $value;
1406     }
1407   }
1410   /*! \brief Generates the html output for this node for multi edit*/
1411   function multiple_execute()
1412   {
1413     /* This one is empty currently. Fabian - please fill in the docu code */
1414     session::global_set('current_class_for_help',get_class($this));
1416     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1417     session::set('LOCK_VARS_TO_USE',array());
1418     session::set('LOCK_VARS_USED_GET',array());
1419     session::set('LOCK_VARS_USED_POST',array());
1420     session::set('LOCK_VARS_USED_REQUEST',array());
1421     
1422     return("Multiple edit is currently not implemented for this plugin.");
1423   }
1426   /*! \brief Save HTML posted data to object for multiple edit
1427    */
1428   function multiple_save_object()
1429   {
1430     if(empty($this->entryCSN) && $this->CSN_check_active){
1431       $this->entryCSN = getEntryCSN($this->dn);
1432     }
1434     /* Save values to object */
1435     $this->multi_boxes = array();
1436     foreach ($this->attributes as $val){
1437   
1438       /* Get selected checkboxes from multiple edit */
1439       if(isset($_POST["use_".$val])){
1440         $this->multi_boxes[] = $val;
1441       }
1443       if (isset ($_POST["$val"]) && $this->acl_is_writeable($val)){
1445         /* Check for modifications */
1446         if (get_magic_quotes_gpc()) {
1447           $data= stripcslashes($_POST["$val"]);
1448         } else {
1449           $data= $this->$val = $_POST["$val"];
1450         }
1451         if ($this->$val != $data){
1452           $this->is_modified= TRUE;
1453         }
1454     
1455         /* IE post fix */
1456         if(isset($data[0]) && $data[0] == chr(194)) {
1457           $data = "";  
1458         }
1459         $this->$val= $data;
1460       }
1461     }
1462   }
1465   /*! \brief Returns all attributes of this plugin, 
1466                to be able to detect multiple used attributes 
1467                in multi_plugg::detect_multiple_used_attributes().
1468       @return array Attributes required for intialization of multi_plug
1469    */
1470   public function get_multi_init_values()
1471   {
1472     $attrs = $this->attrs;
1473     return($attrs);
1474   }
1477   /*! \brief  Check given values in multiple edit
1478       \return array Error messages
1479    */
1480   function multiple_check()
1481   {
1482     $message = plugin::check();
1483     return($message);
1484   }
1486   function get_used_snapshot_bases()
1487   {
1488      return(array());
1489   }
1491   function is_modal_dialog()
1492   {
1493     return(isset($this->dialog) && $this->dialog);
1494   }
1497   /*! \brief    Forward command execution requests
1498    *             to the hook execution method. 
1499    */
1500   function handle_post_events($mode, $addAttrs= array())
1501   {
1502     if(!in_array($mode, array('add','remove','modify'))){
1503       trigger_error(sprintf("Invalid post event type given %s! Valid types are [add,modify,remove].", bold($mode)));
1504       return;
1505     }
1506     switch ($mode){
1507       case "add":
1508         plugin::callHook($this,"POSTCREATE", $addAttrs);
1509       break;
1511       case "modify":
1512         plugin::callHook($this,"POSTMODIFY", $addAttrs);
1513       break;
1515       case "remove":
1516         plugin::callHook($this,"POSTREMOVE", $addAttrs);
1517       break;
1518     }
1519   }
1522   /*! \brief    Calls external hooks which are defined for this plugin (gosa.conf)
1523    *            Replaces placeholder by class values of this plugin instance.
1524    *  @param    Allows to a add special replacements.
1525    */
1526   static function callHook($plugin, $cmd, $addAttrs= array())
1527   {
1528     global $config;
1529     $command = $config->configRegistry->getPropertyValue(get_class($plugin),$cmd);
1530     
1531     if ($command != ""){
1533       // Walk trough attributes list and add the plugins attributes. 
1534       foreach ($plugin->attributes as $attr){
1535         if (!is_array($plugin->$attr)){
1536           $addAttrs[$attr] = $plugin->$attr;
1537         }
1538       }
1539       $ui = get_userinfo();
1540       $addAttrs['callerDN']=$ui->dn;
1541       $addAttrs['dn']=$plugin->dn;
1543       // Sort attributes by length, ensures correct replacement
1544       $tmp = array();
1545       foreach($addAttrs as $name => $value){
1546         $tmp[$name] =  strlen($name);
1547       }
1548       arsort($tmp);
1550       // Now replace the placeholder 
1551       foreach ($tmp as $name => $len){
1552         $value = $addAttrs[$name];
1553         $command= str_replace("%$name", "$value", $command);
1554       }
1556       // If there are still some %.. in our command, try to fill these with some other class vars 
1557       if(preg_match("/%/",$command)){
1558         $attrs = get_object_vars($plugin);
1559         foreach($attrs as $name => $value){
1560           if(is_array($value)){
1561             $s = "";
1562             foreach($value as $val){
1563               if(is_string($val) || is_int($val) || is_float($val) || is_bool($val)){
1564                 $s .= '"'.$val.'",'; 
1565               }
1566             }
1567             $value = '['.trim($s,',').']';
1568           }
1569           if(!is_string($value) && !is_int($value) && !is_float($value) && !is_bool($value)){
1570             continue;
1571           }
1572           $command= preg_replace("/%$name/", $value, $command);
1573         }
1574       }
1576       if (check_command($command)){
1577         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,$command,"Execute");
1578         exec($command,$arr);
1579         if(is_array($arr)){
1580           $str = implode("\n",$arr);
1581           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Result: ".$str);
1582         }
1583       } else {
1584         $message= msgPool::cmdnotfound("POSTCREATE", get_class($plugin));
1585         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
1586       }
1587     }
1588   }
1591 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1592 ?>