Code

fixed property
[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->search(get_class($this), "CHECK", array('menu', 'tabs'));
471     if ($command != ""){
473       if (!check_command($command)){
474         $message[]= msgPool::cmdnotfound("CHECK", get_class($this));
475       } else {
477         /* Generate "ldif" for check hook */
478         $ldif= "dn: $this->dn\n";
479         
480         /* ... objectClasses */
481         foreach ($this->objectclasses as $oc){
482           $ldif.= "objectClass: $oc\n";
483         }
484         
485         /* ... attributes */
486         foreach ($this->attributes as $attr){
487           if ($this->$attr == ""){
488             continue;
489           }
490           if (is_array($this->$attr)){
491             foreach ($this->$attr as $val){
492               $ldif.= "$attr: $val\n";
493             }
494           } else {
495               $ldif.= "$attr: ".$this->$attr."\n";
496           }
497         }
499         /* Append empty line */
500         $ldif.= "\n";
502         /* Feed "ldif" into hook and retrieve result*/
503         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
504         $fh= proc_open($command, $descriptorspec, $pipes);
505         if (is_resource($fh)) {
506           fwrite ($pipes[0], $ldif);
507           fclose($pipes[0]);
508           
509           $result= stream_get_contents($pipes[1]);
510           if ($result != ""){
511             $message[]= $result;
512           }
513           
514           fclose($pipes[1]);
515           fclose($pipes[2]);
516           proc_close($fh);
517         }
518       }
520     }
522     /* Check entryCSN */
523     if($this->CSN_check_active){
524       $current_csn = getEntryCSN($this->dn);
525       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
526         $this->entryCSN = $current_csn;
527         $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!");
528       }
529     }
530     return ($message);
531   }
533   /* Adapt from template, using 'dn' */
534   function adapt_from_template($dn, $skip= array())
535   {
536     /* Include global link_info */
537     $ldap= $this->config->get_ldap_link();
539     /* Load requested 'dn' to 'attrs' */
540     $ldap->cat ($dn);
541     $this->attrs= $ldap->fetch();
543     /* Walk through attributes */
544     foreach ($this->attributes as $val){
546       /* Skip the ones in skip list */
547       if (in_array($val, $skip)){
548         continue;
549       }
551       if (isset($this->attrs["$val"][0])){
553         /* If attribute is set, replace dynamic parts: 
554            %sn, %givenName and %uid. Fill these in our local variables. */
555         $value= $this->attrs["$val"][0];
557         foreach (array("sn", "givenName", "uid") as $repl){
558           if (preg_match("/%$repl/i", $value)){
559             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
560           }
561         }
562         $this->$val= $value;
563       }
564     }
566     /* Is Account? */
567     $found= TRUE;
568     foreach ($this->objectclasses as $obj){
569       if (preg_match('/top/i', $obj)){
570         continue;
571       }
572       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
573         $found= FALSE;
574         break;
575       }
576     }
577     if ($found){
578       $this->is_account= TRUE;
579     }
580   }
582   /* \brief Indicate whether a password change is needed or not */
583   function password_change_needed()
584   {
585     return FALSE;
586   }
589   /*! \brief Show header message for tab dialogs */
590   function show_enable_header($button_text, $text, $disabled= FALSE)
591   {
592     if (($disabled == TRUE) || (!$this->acl_is_createable())){
593       $state= "disabled";
594     } else {
595       $state= "";
596     }
597     $display = "<div class='plugin-enable-header'>\n";
598     $display.= "<p>$text</p>\n";
599     $display.= "<button type='submit' name=\"modify_state\" ".$state.">$button_text</button>\n";
600     $display.= "</div>\n";
602     return($display);
603   }
606   /*! \brief Show header message for tab dialogs */
607   function show_disable_header($button_text, $text, $disabled= FALSE)
608   {
609     if (($disabled == TRUE) || !$this->acl_is_removeable()){
610       $state= "disabled";
611     } else {
612       $state= "";
613     }
614     $display = "<div class='plugin-disable-header'>\n";
615     $display.= "<p>$text</p>\n";
616     $display.= "<button type='submit' name=\"modify_state\" ".$state.">$button_text</button>\n";
617     $display.= "</div>\n";
618     return($display);
619   }
623   /* Create unique DN */
624   function create_unique_dn2($data, $base)
625   {
626     $ldap= $this->config->get_ldap_link();
627     $base= preg_replace("/^,*/", "", $base);
629     /* Try to use plain entry first */
630     $dn= "$data,$base";
631     $attribute= preg_replace('/=.*$/', '', $data);
632     $ldap->cat ($dn, array('dn'));
633     if (!$ldap->fetch()){
634       return ($dn);
635     }
637     /* Look for additional attributes */
638     foreach ($this->attributes as $attr){
639       if ($attr == $attribute || $this->$attr == ""){
640         continue;
641       }
643       $dn= "$data+$attr=".$this->$attr.",$base";
644       $ldap->cat ($dn, array('dn'));
645       if (!$ldap->fetch()){
646         return ($dn);
647       }
648     }
650     /* None found */
651     return ("none");
652   }
655   /*! \brief Create unique DN */
656   function create_unique_dn($attribute, $base)
657   {
658     $ldap= $this->config->get_ldap_link();
659     $base= preg_replace("/^,*/", "", $base);
661     /* Try to use plain entry first */
662     $dn= "$attribute=".$this->$attribute.",$base";
663     $ldap->cat ($dn, array('dn'));
664     if (!$ldap->fetch()){
665       return ($dn);
666     }
668     /* Look for additional attributes */
669     foreach ($this->attributes as $attr){
670       if ($attr == $attribute || $this->$attr == ""){
671         continue;
672       }
674       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
675       $ldap->cat ($dn, array('dn'));
676       if (!$ldap->fetch()){
677         return ($dn);
678       }
679     }
681     /* None found */
682     return ("none");
683   }
686   function rebind($ldap, $referral)
687   {
688     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
689     if (ldap_bind($ldap, $credentials['ADMIN'], $this->config->get_credentials($credentials['PASSWORD']))) {
690       $this->error = "Success";
691       $this->hascon=true;
692       $this->reconnect= true;
693       return (0);
694     } else {
695       $this->error = "Could not bind to " . $credentials['ADMIN'];
696       return NULL;
697     }
698   }
701   /* Recursively copy ldap object */
702   function _copy($src_dn,$dst_dn)
703   {
704     $ldap=$this->config->get_ldap_link();
705     $ldap->cat($src_dn);
706     $attrs= $ldap->fetch();
708     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
709     $ds= ldap_connect($this->config->current['SERVER']);
710     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
711     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
712       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
713     }
715     $pwd = $this->config->get_credentials($this->config->current['ADMINPASSWORD']);
716     $r=ldap_bind($ds,$this->config->current['ADMINDN'], $pwd);
717     $sr=ldap_read($ds, LDAP::fix($src_dn), "objectClass=*");
719     /* Fill data from LDAP */
720     $new= array();
721     if ($sr) {
722       $ei=ldap_first_entry($ds, $sr);
723       if ($ei) {
724         foreach($attrs as $attr => $val){
725           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
726             for ($i= 0; $i<$info['count']; $i++){
727               if ($info['count'] == 1){
728                 $new[$attr]= $info[$i];
729               } else {
730                 $new[$attr][]= $info[$i];
731               }
732             }
733           }
734         }
735       }
736     }
738     /* close conncetion */
739     ldap_unbind($ds);
741     /* Adapt naming attribute */
742     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
743     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
744     $new[$dst_name]= LDAP::fix($dst_val);
746     /* Check if this is a department.
747      * If it is a dep. && there is a , override in his ou 
748      *  change \2C to , again, else this entry can't be saved ...
749      */
750     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
751       $new['ou'] = str_replace("\\\\,",",",$new['ou']);
752     }
754     /* Save copy */
755     $ldap->connect();
756     $ldap->cd($this->config->current['BASE']);
757     
758     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
760     /* FAIvariable=.../..., cn=.. 
761         could not be saved, because the attribute FAIvariable was different to 
762         the dn FAIvariable=..., cn=... */
764     if(!is_array($new['objectClass'])) $new['objectClass'] = array($new['objectClass']);
766     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
767       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
768     }
769     $ldap->cd($dst_dn);
770     $ldap->add($new);
772     if (!$ldap->success()){
773       trigger_error("Trying to save $dst_dn failed.",
774           E_USER_WARNING);
775       return(FALSE);
776     }
777     return(TRUE);
778   }
781   /* This is a workaround function. */
782   function copy($src_dn, $dst_dn)
783   {
784     /* Rename dn in possible object groups */
785     $ldap= $this->config->get_ldap_link();
786     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::prepare4filter($src_dn).'))',
787         array('cn'));
788     while ($attrs= $ldap->fetch()){
789       $og= new ogroup($this->config, $ldap->getDN());
790       unset($og->member[$src_dn]);
791       $og->member[$dst_dn]= $dst_dn;
792       $og->save ();
793     }
795     $ldap->cat($dst_dn);
796     $attrs= $ldap->fetch();
797     if (count($attrs)){
798       trigger_error("Trying to overwrite ".LDAP::fix($dst_dn).", which already exists.",
799           E_USER_WARNING);
800       return (FALSE);
801     }
803     $ldap->cat($src_dn);
804     $attrs= $ldap->fetch();
805     if (!count($attrs)){
806       trigger_error("Trying to move ".LDAP::fix($src_dn).", which does not seem to exist.",
807           E_USER_WARNING);
808       return (FALSE);
809     }
811     $ldap->cd($src_dn);
812     $ldap->search("objectClass=*",array("dn"));
813     while($attrs = $ldap->fetch()){
814       $src = $attrs['dn'];
815       $dst = preg_replace("/".preg_quote($src_dn, '/')."$/",$dst_dn,$attrs['dn']);
816       $this->_copy($src,$dst);
817     }
818     return (TRUE);
819   }
823   /*! \brief  Rename/Move a given src_dn to the given dest_dn
824    *
825    * Move a given ldap object indentified by $src_dn to the
826    * given destination $dst_dn
827    *
828    * - Ensure that all references are updated (ogroups)
829    * - Update ACLs   
830    * - Update accessTo
831    *
832    * \param  string  'src_dn' the source DN.
833    * \param  string  'dst_dn' the destination DN.
834    * \return boolean TRUE on success else FALSE.
835    */
836   function rename($src_dn, $dst_dn)
837   {
838     $start = microtime(1);
840     /* Try to move the source entry to the destination position */
841     $ldap = $this->config->get_ldap_link();
842     $ldap->cd($this->config->current['BASE']);
843     $ldap->create_missing_trees(preg_replace("/^[^,]+,/","",$dst_dn));
844     if (!$ldap->rename_dn($src_dn,$dst_dn)){
845       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());
846       @DEBUG(DEBUG_LDAP,__LINE__,__FUNCTION__,__FILE__,"Rename failed FROM: $src_dn  -- TO:  $dst_dn", 
847           "Ldap Protocol v3 implementation error, falling back to maunal method.");
848       return(FALSE);
849     }
851     /* Get list of users,groups and roles within this tree,
852         maybe we have to update ACL references.
853      */
854     $leaf_objs = get_list("(|(objectClass=posixGroup)(objectClass=gosaAccount)(objectClass=gosaRole))",array("all"),$dst_dn,
855           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
856     foreach($leaf_objs as $obj){
857       $new_dn = $obj['dn'];
858       $old_dn = preg_replace("/".preg_quote(LDAP::convert($dst_dn), '/')."$/i",$src_dn,LDAP::convert($new_dn));
859       $this->update_acls($old_dn,$new_dn); 
860     }
862     // Migrate objectgroups if needed
863     $ogroups = get_sub_list("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter(LDAP::fix($src_dn))."))",
864       "ogroups", array(get_ou("ogroupRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
866     // Walk through all objectGroups
867     foreach($ogroups as $ogroup){
868       // Migrate old to new dn
869       $o_ogroup= new ogroup($this->config,$ogroup['dn']);
870       if (isset($o_ogroup->member[$src_dn])) {
871         unset($o_ogroup->member[$src_dn]);
872       }
873       $o_ogroup->member[$dst_dn]= $dst_dn;
874       
875       // Save object group
876       $o_ogroup->save();
877     }
879     // Migrate rfc groups if needed
880     $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);
882     // Walk through all POSIX groups
883     foreach($groups as $group){
885       // Migrate old to new dn
886       $o_group= new group($this->config,$group['dn']);
887       $o_group->save();
888     }
890     /* Update roles to use the new entry dn */
891     $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);
893     // Walk through all roles
894     foreach($roles as $role){
895       $role = new roleGeneric($this->config,$role['dn']);
896       $key= array_search($src_dn, $role->roleOccupant);      
897       if($key !== FALSE){
898         $role->roleOccupant[$key] = $dst_dn;
899         $role->save();
900       }
901     }
903     // Update 'manager' attributes from gosaDepartment and inetOrgPerson 
904     $filter = "(&(objectClass=inetOrgPerson)(manager=".LDAP::prepare4filter(LDAP::fix($src_dn))."))";
905     $ocs = $ldap->get_objectclasses();
906     if(isset($ocs['gosaDepartment']['MAY']) && in_array('manager', $ocs['gosaDepartment']['MAY'])){
907       $filter = "(|".$filter."(&(objectClass=gosaDepartment)(manager=".LDAP::prepare4filter(LDAP::fix($src_dn)).")))";
908     }
909     $leaf_deps=  get_list($filter,array("all"),$this->config->current['BASE'], 
910         array("manager","dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
911     foreach($leaf_deps as $entry){
912       $update = array('manager' => $dst_dn);
913       $ldap->cd($entry['dn']);
914       $ldap->modify($update);
915       if(!$ldap->success()){
916         trigger_error(sprintf("Failed to update manager for %s: %s", bold($entry['dn']), $ldap->get_error()));
917       }
918     }
919  
920     /* Check if there are gosa departments moved. 
921        If there were deps moved, the force reload of config->deps.
922      */
923     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
924           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
925   
926     if(count($leaf_deps)){
927       $this->config->get_departments();
928       $this->config->make_idepartments();
929       session::global_set("config",$this->config);
930       $ui =get_userinfo();
931       $ui->reset_acl_cache();
932     }
934     return(TRUE); 
935   }
938  
939   function move($src_dn, $dst_dn)
940   {
941     /* Do not copy if only upper- lowercase has changed */
942     if(strtolower($src_dn) == strtolower($dst_dn)){
943       return(TRUE);
944     }
946     
947     /* Try to move the entry instead of copy & delete
948      */
949     if(TRUE){
951       /* Try to move with ldap routines, if this was not successfull
952           fall back to the old style copy & remove method 
953        */
954       if($this->rename($src_dn, $dst_dn)){
955         return(TRUE);
956       }else{
957         // See code below.
958       }
959     }
961     /* Copy source to destination */
962     if (!$this->copy($src_dn, $dst_dn)){
963       return (FALSE);
964     }
966     /* Delete source */
967     $ldap= $this->config->get_ldap_link();
968     $ldap->rmdir_recursive($src_dn);
969     if (!$ldap->success()){
970       trigger_error("Trying to delete $src_dn failed.",
971           E_USER_WARNING);
972       return (FALSE);
973     }
975     return (TRUE);
976   }
979   /* \brief Move/Rename complete trees */
980   function recursive_move($src_dn, $dst_dn)
981   {
982     /* Check if the destination entry exists */
983     $ldap= $this->config->get_ldap_link();
985     /* Check if destination exists - abort */
986     $ldap->cat($dst_dn, array('dn'));
987     if ($ldap->fetch()){
988       trigger_error("recursive_move $dst_dn already exists.",
989           E_USER_WARNING);
990       return (FALSE);
991     }
993     $this->copy($src_dn, $dst_dn);
995     /* Remove src_dn */
996     $ldap->cd($src_dn);
997     $ldap->recursive_remove($src_dn);
998     return (TRUE);
999   }
1002   function saveCopyDialog(){
1003   }
1006   function getCopyDialog(){
1007     return(array("string"=>"","status"=>""));
1008   }
1011   /*! \brief Prepare for Copy & Paste */
1012   function PrepareForCopyPaste($source)
1013   {
1014     $todo = $this->attributes;
1015     if(isset($this->CopyPasteVars)){
1016       $todo = array_merge($todo,$this->CopyPasteVars);
1017     }
1019     if(count($this->objectclasses)){
1020       $this->is_account = TRUE;
1021       foreach($this->objectclasses as $class){
1022         if(!in_array($class,$source['objectClass'])){
1023           $this->is_account = FALSE;
1024         }
1025       }
1026     }
1028     foreach($todo as $var){
1029       if (isset($source[$var])){
1030         if(isset($source[$var]['count'])){
1031           if($source[$var]['count'] > 1){
1032             $tmp= $source[$var];
1033             unset($tmp['count']);
1034             $this->$var = $tmp;
1035           }else{
1036             $this->$var = $source[$var][0];
1037           }
1038         }else{
1039           $this->$var= $source[$var];
1040         }
1041       }
1042     }
1043   }
1045   /*! \brief Get gosaUnitTag for the given DN
1046        If this is called from departmentGeneric, we have to skip this
1047         tagging procedure. 
1048     */
1049   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1050   {
1051     /* Skip tagging? */
1052     if($this->skipTagging){
1053       return;
1054     }
1056     /* No dn? Self-operation... */
1057     if ($dn == ""){
1058       $dn= $this->dn;
1060       /* No tag? Find it yourself... */
1061       if ($tag == ""){
1062         $len= strlen($dn);
1064         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1065         $relevant= array();
1066         foreach ($this->config->adepartments as $key => $ntag){
1068           /* This one is bigger than our dn, its not relevant... */
1069           if ($len < strlen($key)){
1070             continue;
1071           }
1073           /* This one matches with the latter part. Break and don't fix this entry */
1074           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
1075             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1076             $relevant[strlen($key)]= $ntag;
1077             continue;
1078           }
1080         }
1082         /* If we've some relevant tags to set, just get the longest one */
1083         if (count($relevant)){
1084           ksort($relevant);
1085           $tmp= array_keys($relevant);
1086           $idx= end($tmp);
1087           $tag= $relevant[$idx];
1088           $this->gosaUnitTag= $tag;
1089         }
1090       }
1091     }
1093   /*! \brief Add unit tag */ 
1094     /* Remove tags that may already be here... */
1095     remove_objectClass("gosaAdministrativeUnitTag", $at);
1096     if (isset($at['gosaUnitTag'])){
1097         unset($at['gosaUnitTag']);
1098     }
1100     /* Set tag? */
1101     if ($tag != ""){
1102       add_objectClass("gosaAdministrativeUnitTag", $at);
1103       $at['gosaUnitTag']= $tag;
1104     }
1106     /* Initially this object was tagged. 
1107        - But now, it is no longer inside a tagged department. 
1108        So force the remove of the tag.
1109        (objectClass was already removed obove)
1110      */
1111     if($tag == "" && $this->gosaUnitTag){
1112       $at['gosaUnitTag'] = array();
1113     }
1114   }
1117   /*! \brief Test for removability of the object
1118    *
1119    * Allows testing of conditions for removal of object. If removal should be aborted
1120    * the function needs to remove an error message.
1121    * */
1122   function allow_remove()
1123   {
1124     $reason= "";
1125     return $reason;
1126   }
1129   /*! \brief Test if snapshotting is enabled
1130    *
1131    * Test weither snapshotting is enabled or not. There will also be some errors posted,
1132    * if the configuration failed 
1133    * \return TRUE if snapshots are enabled, and FALSE if it is disabled
1134    */
1135   function snapshotEnabled()
1136   {
1137       return $this->config->snapshotEnabled();
1138   }
1141   /*! \brief Return plugin informations for acl handling */
1142   static function plInfo()
1143   {
1144     return array();
1145   }
1148   function set_acl_base($base)
1149   {
1150     @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,"<b>".$base."</b>","<b>ACL-Base:</b> ");
1151     $this->acl_base= $base;
1152   }
1155   function set_acl_category($category)
1156   {
1157     @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,"<b>".$category."</b>(/".get_class($this).")","<b>ACL-Category:</b> ");
1158     $this->acl_category= "$category/";
1159   }
1162   function acl_is_writeable($attribute,$skip_write = FALSE)
1163   {
1164     if($this->read_only) return(FALSE);
1165     $ui= get_userinfo();
1166     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1167   }
1170   function acl_is_readable($attribute)
1171   {
1172     $ui= get_userinfo();
1173     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1174   }
1177   function acl_is_createable($base ="")
1178   {
1179     if($this->read_only) return(FALSE);
1180     $ui= get_userinfo();
1181     if($base == "") $base = $this->acl_base;
1182     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1183   }
1186   function acl_is_removeable($base ="")
1187   {
1188     if($this->read_only) return(FALSE);
1189     $ui= get_userinfo();
1190     if($base == "") $base = $this->acl_base;
1191     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1192   }
1195   function acl_is_moveable($base = "")
1196   {
1197     if($this->read_only) return(FALSE);
1198     $ui= get_userinfo();
1199     if($base == "") $base = $this->acl_base;
1200     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1201   }
1204   function acl_have_any_permissions()
1205   {
1206   }
1209   function getacl($attribute,$skip_write= FALSE)
1210   {
1211     $ui= get_userinfo();
1212     $skip_write |= $this->read_only;
1213     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1214   }
1217   /*! \brief Returns a list of all available departments for this object.
1218    * 
1219    * If this object is new, all departments we are allowed to create a new user in
1220    * are returned. If this is an existing object, return all deps. 
1221    * We are allowed to move tis object too.
1222    * \return array [dn] => "..name"  // All deps. we are allowed to act on.
1223   */
1224   function get_allowed_bases()
1225   {
1226     $ui = get_userinfo();
1227     $deps = array();
1229     /* Is this a new object ? Or just an edited existing object */
1230     if(!$this->initially_was_account && $this->is_account){
1231       $new = true;
1232     }else{
1233       $new = false;
1234     }
1236     foreach($this->config->idepartments as $dn => $name){
1237       if($new && $this->acl_is_createable($dn)){
1238         $deps[$dn] = $name;
1239       }elseif(!$new && $this->acl_is_moveable($dn)){
1240         $deps[$dn] = $name;
1241       }
1242     }
1244     /* Add current base */      
1245     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1246       $deps[$this->base] = $this->config->idepartments[$this->base];
1247     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1249     }else{
1250       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1251     }
1252     return($deps);
1253   }
1256   /* This function updates ACL settings if $old_dn was used.
1257    *  \param string 'old_dn' specifies the actually used dn
1258    *  \param string 'new_dn' specifies the destiantion dn
1259    */
1260   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1261   {
1262     /* Check if old_dn is empty. This should never happen */
1263     if(empty($old_dn) || empty($new_dn)){
1264       trigger_error("Failed to check acl dependencies, wrong dn given.");
1265       return;
1266     }
1268     /* Update userinfo if necessary */
1269     $ui = session::global_get('ui');
1270     if($ui->dn == $old_dn){
1271       $ui->dn = $new_dn;
1272       session::global_set('ui',$ui);
1273       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1274     }
1276     /* Object was moved, ensure that all acls will be moved too */
1277     if($new_dn != $old_dn && $old_dn != "new"){
1279       /* get_ldap configuration */
1280       $update = array();
1281       $ldap = $this->config->get_ldap_link();
1282       $ldap->cd ($this->config->current['BASE']);
1283       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1284       while($attrs = $ldap->fetch()){
1285         $acls = array();
1286         $found = false;
1287         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1288           $acl_parts = explode(":",$attrs['gosaAclEntry'][$i]);
1290           /* Roles uses antoher data storage order, members are stored int the third part, 
1291              while the members in direct ACL assignments are stored in the second part.
1292            */
1293           $id = ($acl_parts[1] == "role") ? 3 : 2;
1295           /* Update member entries to use $new_dn instead of old_dn
1296            */
1297           $members = explode(",",$acl_parts[$id]);
1298           foreach($members as $key => $member){
1299             $member = base64_decode($member);
1300             if($member == $old_dn){
1301               $members[$key] = base64_encode($new_dn);
1302               $found = TRUE;
1303             }
1304           } 
1306           /* Check if the selected role has to updated
1307            */
1308           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1309             $acl_parts[2] = base64_encode($new_dn);
1310             $found = TRUE;
1311           }
1313           /* Build new acl string */ 
1314           $acl_parts[$id] = implode($members,",");
1315           $acls[] = implode($acl_parts,":");
1316         }
1318         /* Acls for this object must be adjusted */
1319         if($found){
1321           $debug_info= sprintf(_("Changing ACL DN from %s to %s"), bold($old_dn), bold($new_dn));
1322           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1324           $update[$attrs['dn']] =array();
1325           foreach($acls as $acl){
1326             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1327           }
1328         }
1329       }
1331       /* Write updated acls */
1332       foreach($update as $dn => $attrs){
1333         $ldap->cd($dn);
1334         $ldap->modify($attrs);
1335       }
1336     }
1337   }
1339   
1341   /*! \brief Enable the Serial ID check
1342    *
1343    * This function enables the entry Serial ID check.  If an entry was edited while
1344    * we have edited the entry too, an error message will be shown. 
1345    * To configure this check correctly read the FAQ.
1346    */    
1347   function enable_CSN_check()
1348   {
1349     $this->CSN_check_active =TRUE;
1350     $this->entryCSN = getEntryCSN($this->dn);
1351   }
1354   /*! \brief  Prepares the plugin to be used for multiple edit
1355    *          Update plugin attributes with given array of attribtues.
1356    *  \param  array   Array with attributes that must be updated.
1357    */
1358   function init_multiple_support($attrs,$all)
1359   {
1360     $ldap= $this->config->get_ldap_link();
1361     $this->multi_attrs    = $attrs;
1362     $this->multi_attrs_all= $all;
1364     /* Copy needed attributes */
1365     foreach ($this->attributes as $val){
1366       $found= array_key_ics($val, $this->multi_attrs);
1367  
1368       if ($found != ""){
1369         if(isset($this->multi_attrs["$val"][0])){
1370           $this->$val= $this->multi_attrs["$val"][0];
1371         }
1372       }
1373     }
1374   }
1376  
1377   /*! \brief  Enables multiple support for this plugin
1378    */
1379   function enable_multiple_support()
1380   {
1381     $this->ignore_account = TRUE;
1382     $this->multiple_support_active = TRUE;
1383   }
1386   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1387       \return array Cotaining all modified values. 
1388    */
1389   function get_multi_edit_values()
1390   {
1391     $ret = array();
1392     foreach($this->attributes as $attr){
1393       if(in_array($attr,$this->multi_boxes)){
1394         $ret[$attr] = $this->$attr;
1395       }
1396     }
1397     return($ret);
1398   }
1400   
1401   /*! \brief  Update class variables with values collected by multiple edit.
1402    */
1403   function set_multi_edit_values($attrs)
1404   {
1405     foreach($attrs as $name => $value){
1406       $this->$name = $value;
1407     }
1408   }
1411   /*! \brief Generates the html output for this node for multi edit*/
1412   function multiple_execute()
1413   {
1414     /* This one is empty currently. Fabian - please fill in the docu code */
1415     session::global_set('current_class_for_help',get_class($this));
1417     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1418     session::set('LOCK_VARS_TO_USE',array());
1419     session::set('LOCK_VARS_USED_GET',array());
1420     session::set('LOCK_VARS_USED_POST',array());
1421     session::set('LOCK_VARS_USED_REQUEST',array());
1422     
1423     return("Multiple edit is currently not implemented for this plugin.");
1424   }
1427   /*! \brief Save HTML posted data to object for multiple edit
1428    */
1429   function multiple_save_object()
1430   {
1431     if(empty($this->entryCSN) && $this->CSN_check_active){
1432       $this->entryCSN = getEntryCSN($this->dn);
1433     }
1435     /* Save values to object */
1436     $this->multi_boxes = array();
1437     foreach ($this->attributes as $val){
1438   
1439       /* Get selected checkboxes from multiple edit */
1440       if(isset($_POST["use_".$val])){
1441         $this->multi_boxes[] = $val;
1442       }
1444       if (isset ($_POST["$val"]) && $this->acl_is_writeable($val)){
1446         /* Check for modifications */
1447         if (get_magic_quotes_gpc()) {
1448           $data= stripcslashes($_POST["$val"]);
1449         } else {
1450           $data= $this->$val = $_POST["$val"];
1451         }
1452         if ($this->$val != $data){
1453           $this->is_modified= TRUE;
1454         }
1455     
1456         /* IE post fix */
1457         if(isset($data[0]) && $data[0] == chr(194)) {
1458           $data = "";  
1459         }
1460         $this->$val= $data;
1461       }
1462     }
1463   }
1466   /*! \brief Returns all attributes of this plugin, 
1467                to be able to detect multiple used attributes 
1468                in multi_plugg::detect_multiple_used_attributes().
1469       @return array Attributes required for intialization of multi_plug
1470    */
1471   public function get_multi_init_values()
1472   {
1473     $attrs = $this->attrs;
1474     return($attrs);
1475   }
1478   /*! \brief  Check given values in multiple edit
1479       \return array Error messages
1480    */
1481   function multiple_check()
1482   {
1483     $message = plugin::check();
1484     return($message);
1485   }
1487   function get_used_snapshot_bases()
1488   {
1489      return(array());
1490   }
1492   function is_modal_dialog()
1493   {
1494     return(isset($this->dialog) && $this->dialog);
1495   }
1498   /*! \brief    Forward command execution requests
1499    *             to the hook execution method. 
1500    */
1501   function handle_post_events($mode, $addAttrs= array())
1502   {
1503     if(!in_array($mode, array('add','remove','modify'))){
1504       trigger_error(sprintf("Invalid post event type given %s! Valid types are [add,modify,remove].", bold($mode)));
1505       return;
1506     }
1507     switch ($mode){
1508       case "add":
1509         plugin::callHook($this,"POSTCREATE", $addAttrs);
1510       break;
1512       case "modify":
1513         plugin::callHook($this,"POSTMODIFY", $addAttrs);
1514       break;
1516       case "remove":
1517         plugin::callHook($this,"POSTREMOVE", $addAttrs);
1518       break;
1519     }
1520   }
1523   /*! \brief    Calls external hooks which are defined for this plugin (gosa.conf)
1524    *            Replaces placeholder by class values of this plugin instance.
1525    *  @param    Allows to a add special replacements.
1526    */
1527   static function callHook($plugin, $cmd, $addAttrs= array())
1528   {
1529     global $config;
1530     $command= $config->search(get_class($plugin), $cmd,array('menu','tabs'));
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 ?>