Code

Implemented groupware tab in dynamic tab handling of ogroups
[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   {
149     $this->initTime = microtime(TRUE);
151     /* Configuration is fine, allways */
152     $this->config= &$config;    
153     $this->dn= $dn;
155     // Ensure that we've a valid acl_category set.
156     if(empty($this->acl_category)){
157       $tmp = $this->plInfo();
158       if (isset($tmp['plCategory'])) {
159         $c = key($tmp['plCategory']);
160         if(is_numeric($c)){
161           $c = $tmp['plCategory'][0];
162         }
163         $this->acl_category = $c."/";
164       }
165     }
167     // Create statistic table entry 
168     stats::log('plugin', $class = get_class($this), $category = array($this->acl_category),  $action = 'open', 
169         $amount = 1, $duration = (microtime(TRUE) - $this->initTime));
171     /* Handle new accounts, don't read information from LDAP */
172     if ($dn == "new"){
173       return;
174     }
176     /* Check if this entry was opened in read only mode */
177     if(isset($_POST['open_readonly'])){
178       if(session::global_is_set("LOCK_CACHE")){
179         $cache = &session::get("LOCK_CACHE");
180         if(isset($cache['READ_ONLY'][$this->dn])){
181           $this->read_only = TRUE;
182         }
183       }
184     }
186     /* Save current dn as acl_base */
187     $this->acl_base= $dn;
189     /* Get LDAP descriptor */
190     if ($dn !== NULL){
192       /* Load data to 'attrs' and save 'dn' */
193       if ($object !== NULL){
194         $this->attrs= $object->attrs;
195       } else {
196         $ldap= $this->config->get_ldap_link();
197         $ldap->cat ($dn);
198         $this->attrs= $ldap->fetch();
199       }
201       /* Copy needed attributes */
202       foreach ($this->attributes as $val){
203         $found= array_key_ics($val, $this->attrs);
204         if ($found != ""){
205           $this->$val= $found[0];
206         }
207       }
209       /* gosaUnitTag loading... */
210       if (isset($this->attrs['gosaUnitTag'][0])){
211         $this->gosaUnitTag= $this->attrs['gosaUnitTag'][0];
212       }
214       /* Set the template flag according to the existence of objectClass
215          gosaUserTemplate */
216       if (isset($this->attrs['objectClass'])){
217         if (in_array_ics ("gosaUserTemplate", $this->attrs['objectClass'])){
218           $this->is_template= TRUE;
219           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
220               "found", "Template check");
221         }
222       }
224       /* Is Account? */
225       $found= TRUE;
226       foreach ($this->objectclasses as $obj){
227         if (preg_match('/top/i', $obj)){
228           continue;
229         }
230         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
231           $found= FALSE;
232           break;
233         }
234       }
235       if ($found){
236         $this->is_account= TRUE;
237         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
238             "found", "Object check");
239       }
241       /* Prepare saved attributes */
242       $this->saved_attributes= $this->attrs;
243       foreach ($this->saved_attributes as $index => $value){
244         if (is_numeric($index)){
245           unset($this->saved_attributes[$index]);
246           continue;
247         }
249         if (!in_array_ics($index, $this->attributes) && strcasecmp('objectClass', $index)){
250           unset($this->saved_attributes[$index]);
251           continue;
252         }
254         if (isset($this->saved_attributes[$index][0])){
255           if(!isset($this->saved_attributes[$index]["count"])){
256             $this->saved_attributes[$index]["count"] = count($this->saved_attributes[$index]);
257           }
258           if($this->saved_attributes[$index]["count"] == 1){
259             $tmp= $this->saved_attributes[$index][0];
260             unset($this->saved_attributes[$index]);
261             $this->saved_attributes[$index]= $tmp;
262             continue;
263           }
264         }
265         unset($this->saved_attributes["$index"]["count"]);
266       }
268       if(isset($this->attrs['gosaUnitTag'])){
269         $this->saved_attributes['gosaUnitTag'] = $this->attrs['gosaUnitTag'][0];
270       }
271     }
273     /* Save initial account state */
274     $this->initially_was_account= $this->is_account;
275   }
278   /*! \brief Generates the html output for this node
279    */
280   function execute()
281   {
282     /* This one is empty currently. Fabian - please fill in the docu code */
283     session::global_set('current_class_for_help',get_class($this));
285     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
286     session::set('LOCK_VARS_TO_USE',array());
287     session::set('LOCK_VARS_USED_GET',array());
288     session::set('LOCK_VARS_USED_POST',array());
289     session::set('LOCK_VARS_USED_REQUEST',array());
291     pathNavigator::registerPlugin($this);
293     // Create statistic table entry 
294     stats::log('plugin', $class = get_class($this), $category = array($this->acl_category),  $action = 'view', 
295         $amount = 1, $duration = (microtime(TRUE) - $this->initTime));
296   }
298   /*! \brief Removes object from parent
299    */
300   function remove_from_parent()
301   {
302     /* include global link_info */
303     $ldap= $this->config->get_ldap_link();
305     /* Get current objectClasses in order to add the required ones */
306     $ldap->cat($this->dn);
307     $tmp= $ldap->fetch ();
308     $oc= array();
309     if (isset($tmp['objectClass'])){
310       $oc= $tmp['objectClass'];
311       unset($oc['count']);
312     }
314     /* Remove objectClasses from entry */
315     $ldap->cd($this->dn);
316     $this->attrs= array();
317     $this->attrs['objectClass']= array_remove_entries_ics($this->objectclasses,$oc);
319     /* Unset attributes from entry */
320     foreach ($this->attributes as $val){
321       $this->attrs["$val"]= array();
322     }
324     /* Unset account info */
325     $this->is_account= FALSE;
327     /* Do not write in plugin base class, this must be done by
328        children, since there are normally additional attribs,
329        lists, etc. */
330     /*
331        $ldap->modify($this->attrs);
332      */
333     if($this->initially_was_account){
334         $this->handle_pre_events('remove');
336         // Create statistic table entry 
337         stats::log('plugin', $class = get_class($this), $category = array($this->acl_category),  $action = 'remove', 
338                 $amount = 1, $duration = (microtime(TRUE) - $this->initTime));
339     }
340   }
343   /*! \brief Save HTML posted data to object 
344    */
345   function save_object()
346   {
347     /* Update entry CSN if it is empty. */
348     if(empty($this->entryCSN) && $this->CSN_check_active){
349       $this->entryCSN = getEntryCSN($this->dn);
350     }
352     /* Save values to object */
353     foreach ($this->attributes as $val){
354       if (isset ($_POST["$val"]) && $this->acl_is_writeable($val)){
355   
356         /* Check for modifications */
357         $data= get_post($val);
358         if ($this->$val != $data){
359           $this->is_modified= TRUE;
360         }
361         $this->$val = $data;
362     
363         /* Okay, how can I explain this fix ... 
364          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
365          * So IE posts these 'unselectable' option, with value = chr(194) 
366          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
367          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
368          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
369          */
370         if(isset($data[0]) && $data[0] == chr(194)) {
371           $data = "";  
372         }
373         $this->$val= $data;
374       }
375     }
376   }
379   /*! \brief Save data to LDAP, depending on is_account we save or delete */
380   function save()
381   {
382     /* include global link_info */
383     $ldap= $this->config->get_ldap_link();
385     /* Save all plugins */
386     $this->entryCSN = "";
388     /* Start with empty array */
389     $this->attrs= array();
391     /* Get current objectClasses in order to add the required ones */
392     $ldap->cat($this->dn);
393     
394     $tmp= $ldap->fetch ();
396     $oc= array();
397     if (isset($tmp['objectClass'])){
398       $oc= $tmp["objectClass"];
399       $this->is_new= FALSE;
400       unset($oc['count']);
401     } else {
402       $this->is_new= TRUE;
403     }
405     /* Load (minimum) attributes, add missing ones */
406     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
408     /* Copy standard attributes */
409     foreach ($this->attributes as $val){
410       if ($this->$val != ""){
411         $this->attrs["$val"]= $this->$val;
412       } elseif (!$this->is_new) {
413         $this->attrs["$val"]= array();
414       }
415     }
417     /* Handle tagging */
418     $this->tag_attrs($this->attrs);
420     if($this->is_new){
421         $this->handle_pre_events('add');
423         // Create statistic table entry 
424         stats::log('plugin', $class = get_class($this), $category = array($this->acl_category),  $action = 'create', 
425                 $amount = 1, $duration = (microtime(TRUE) - $this->initTime));
426     }else{
427         $this->handle_pre_events('modify');
429         // Create statistic table entry 
430         stats::log('plugin', $class = get_class($this), $category = array($this->acl_category),  $action = 'modify', 
431                 $amount = 1, $duration = (microtime(TRUE) - $this->initTime));
432     }
433   }
436   /*! \brief    Forward command execution requests
437    *             to the hook execution method.
438    */
439   function handle_pre_events($mode, $addAttrs= array())
440   {
441     if(!in_array($mode, array('add','remove','modify'))){
442       trigger_error(sprintf("Invalid pre event type given %s! Valid types are [add,modify,remove].", $mode));
443       return;
444     }
445     switch ($mode){
446       case "add":
447         plugin::callHook($this,"PRECREATE", $addAttrs);
448       break;
450       case "modify":
451         plugin::callHook($this,"PREMODIFY", $addAttrs);
452       break;
454       case "remove":
455         plugin::callHook($this,"PREREMOVE", $addAttrs);
456       break;
457     }
458   }
461   function cleanup()
462   {
463     foreach ($this->attrs as $index => $value){
464       
465       /* Convert arrays with one element to non arrays, if the saved
466          attributes are no array, too */
467       if (is_array($this->attrs[$index]) && 
468           count ($this->attrs[$index]) == 1 &&
469           isset($this->saved_attributes[$index]) &&
470           !is_array($this->saved_attributes[$index])){
471           
472         $tmp= $this->attrs[$index][0];
473         $this->attrs[$index]= $tmp;
474       }
476       /* Remove emtpy arrays if they do not differ */
477       if (is_array($this->attrs[$index]) &&
478           count($this->attrs[$index]) == 0 &&
479           !isset($this->saved_attributes[$index])){
480           
481         unset ($this->attrs[$index]);
482         continue;
483       }
485       /* Remove single attributes that do not differ */
486       if (!is_array($this->attrs[$index]) &&
487           isset($this->saved_attributes[$index]) &&
488           !is_array($this->saved_attributes[$index]) &&
489           $this->attrs[$index] == $this->saved_attributes[$index]){
491         unset ($this->attrs[$index]);
492         continue;
493       }
495       /* Remove arrays that do not differ */
496       if (is_array($this->attrs[$index]) && 
497           isset($this->saved_attributes[$index]) &&
498           is_array($this->saved_attributes[$index])){
499           
500         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
501           unset ($this->attrs[$index]);
502           continue;
503         }
504       }
505     }
507     /* Update saved attributes and ensure that next cleanups will be successful too */
508     foreach($this->attrs as $name => $value){
509       $this->saved_attributes[$name] = $value;
510     }
511   }
513   /*! \brief Check formular input */
514   function check()
515   {
516     $message= array();
518     /* Skip if we've no config object */
519     if (!isset($this->config) || !is_object($this->config)){
520       return $message;
521     }
523     /* Find hooks entries for this class */
524     $command = $this->config->configRegistry->getPropertyValue(get_class($this),"check");
525     if ($command != ""){
527       if (!check_command($command)){
528         $message[]= msgPool::cmdnotfound("CHECK", get_class($this));
529       } else {
531         /* Generate "ldif" for check hook */
532         $ldif= "dn: $this->dn\n";
533         
534         /* ... objectClasses */
535         foreach ($this->objectclasses as $oc){
536           $ldif.= "objectClass: $oc\n";
537         }
538         
539         /* ... attributes */
540         foreach ($this->attributes as $attr){
541           if ($this->$attr == ""){
542             continue;
543           }
544           if (is_array($this->$attr)){
545             foreach ($this->$attr as $val){
546               $ldif.= "$attr: $val\n";
547             }
548           } else {
549               $ldif.= "$attr: ".$this->$attr."\n";
550           }
551         }
553         /* Append empty line */
554         $ldif.= "\n";
556         /* Feed "ldif" into hook and retrieve result*/
557         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
558         $fh= proc_open($command, $descriptorspec, $pipes);
559         if (is_resource($fh)) {
560           fwrite ($pipes[0], $ldif);
561           fclose($pipes[0]);
562           
563           $result= stream_get_contents($pipes[1]);
564           if ($result != ""){
565             $message[]= $result;
566           }
567           
568           fclose($pipes[1]);
569           fclose($pipes[2]);
570           proc_close($fh);
571         }
572       }
574     }
576     /* Check entryCSN */
577     if($this->CSN_check_active){
578       $current_csn = getEntryCSN($this->dn);
579       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
580         $this->entryCSN = $current_csn;
581         $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!");
582       }
583     }
584     return ($message);
585   }
587   /* Adapt from template, using 'dn' */
588   function adapt_from_template($dn, $skip= array())
589   {
590     /* Include global link_info */
591     $ldap= $this->config->get_ldap_link();
593     /* Load requested 'dn' to 'attrs' */
594     $ldap->cat ($dn);
595     $this->attrs= $ldap->fetch();
597     $values = array();
598     foreach($this->attributes as $name){
599         if(isset($this->parent->$name)){
600             $value = $this->parent->$name;
601             if(is_numeric($name)) continue;
602             if(is_string($value))  $values[$name] = $value;
603             if(is_array($value) && isset($value[0]))  $values[$name] = $value[0];
604         }
605     }
607     foreach($this->attributes as $name){
609         // Skip the ones in skip list 
610         if (in_array($name, $skip)) continue;
611         if (!isset($this->attrs[$name]['count'])) continue;
613         $value= $this->attrs[$name][0];
615         if($this->attrs[$name]['count'] == 1){
616             $value = fillReplacements($this->attrs[$name][0], $values);
617         }else{
618             $value = array();
619             for($i=0;$i<$this->attrs[$name]['count'];$i++){
620                 $value[] = fillReplacements($this->attrs[$name][$i], $values);
621             }
622         }
623         $this->$name = $value; 
624     }
626     /* Is Account? */
627     $found= TRUE;
628     foreach ($this->objectclasses as $obj){
629       if (preg_match('/top/i', $obj)) continue;
630       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
631         $found= FALSE;
632         break;
633       }
634     }
635     $this->is_account = $found;
636   }
638   /* \brief Indicate whether a password change is needed or not */
639   function password_change_needed()
640   {
641     return FALSE;
642   }
645   /*! \brief Show header message for tab dialogs */
646   function show_enable_header($button_text, $text, $disabled= FALSE)
647   {
648     if (($disabled == TRUE) || (!$this->acl_is_createable())){
649       $state= "disabled";
650     } else {
651       $state= "";
652     }
653     $display = "<div class='plugin-enable-header'>\n";
654     $display.= "<p>$text</p>\n";
655     $display.= "<button type='submit' name=\"modify_state\" ".$state.">$button_text</button>\n";
656     $display.= "</div>\n";
658     return($display);
659   }
662   /*! \brief Show header message for tab dialogs */
663   function show_disable_header($button_text, $text, $disabled= FALSE)
664   {
665     if (($disabled == TRUE) || !$this->acl_is_removeable()){
666       $state= "disabled";
667     } else {
668       $state= "";
669     }
670     $display = "<div class='plugin-disable-header'>\n";
671     $display.= "<p>$text</p>\n";
672     $display.= "<button type='submit' name=\"modify_state\" ".$state.">$button_text</button>\n";
673     $display.= "</div>\n";
674     return($display);
675   }
679   /* Create unique DN */
680   function create_unique_dn2($data, $base)
681   {
682     $ldap= $this->config->get_ldap_link();
683     $base= preg_replace("/^,*/", "", $base);
685     /* Try to use plain entry first */
686     $dn= "$data,$base";
687     $attribute= preg_replace('/=.*$/', '', $data);
688     $ldap->cat ($dn, array('dn'));
689     if (!$ldap->fetch()){
690       return ($dn);
691     }
693     /* Look for additional attributes */
694     foreach ($this->attributes as $attr){
695       if ($attr == $attribute || $this->$attr == ""){
696         continue;
697       }
699       $dn= "$data+$attr=".$this->$attr.",$base";
700       $ldap->cat ($dn, array('dn'));
701       if (!$ldap->fetch()){
702         return ($dn);
703       }
704     }
706     /* None found */
707     return ("none");
708   }
711   /*! \brief Create unique DN */
712   function create_unique_dn($attribute, $base)
713   {
714     $ldap= $this->config->get_ldap_link();
715     $base= preg_replace("/^,*/", "", $base);
717     /* Try to use plain entry first */
718     $dn= "$attribute=".$this->$attribute.",$base";
719     $ldap->cat ($dn, array('dn'));
720     if (!$ldap->fetch()){
721       return ($dn);
722     }
724     /* Look for additional attributes */
725     foreach ($this->attributes as $attr){
726       if ($attr == $attribute || $this->$attr == ""){
727         continue;
728       }
730       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
731       $ldap->cat ($dn, array('dn'));
732       if (!$ldap->fetch()){
733         return ($dn);
734       }
735     }
737     /* None found */
738     return ("none");
739   }
742   function rebind($ldap, $referral)
743   {
744     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
745     if (ldap_bind($ldap, $credentials['ADMIN'], $this->config->get_credentials($credentials['PASSWORD']))) {
746       $this->error = "Success";
747       $this->hascon=true;
748       $this->reconnect= true;
749       return (0);
750     } else {
751       $this->error = "Could not bind to " . $credentials['ADMIN'];
752       return NULL;
753     }
754   }
757   /* Recursively copy ldap object */
758   function _copy($src_dn,$dst_dn)
759   {
760     $ldap=$this->config->get_ldap_link();
761     $ldap->cat($src_dn);
762     $attrs= $ldap->fetch();
764     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
765     $ds= ldap_connect($this->config->current['SERVER']);
766     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
767     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
768       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
769     }
771     $pwd = $this->config->get_credentials($this->config->current['ADMINPASSWORD']);
772     $r=ldap_bind($ds,$this->config->current['ADMINDN'], $pwd);
773     $sr=ldap_read($ds, LDAP::fix($src_dn), "objectClass=*");
775     /* Fill data from LDAP */
776     $new= array();
777     if ($sr) {
778       $ei=ldap_first_entry($ds, $sr);
779       if ($ei) {
780         foreach($attrs as $attr => $val){
781           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
782             for ($i= 0; $i<$info['count']; $i++){
783               if ($info['count'] == 1){
784                 $new[$attr]= $info[$i];
785               } else {
786                 $new[$attr][]= $info[$i];
787               }
788             }
789           }
790         }
791       }
792     }
794     /* close conncetion */
795     ldap_unbind($ds);
797     /* Adapt naming attribute */
798     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
799     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
800     $new[$dst_name]= LDAP::fix($dst_val);
802     /* Check if this is a department.
803      * If it is a dep. && there is a , override in his ou 
804      *  change \2C to , again, else this entry can't be saved ...
805      */
806     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
807       $new['ou'] = str_replace("\\\\,",",",$new['ou']);
808     }
810     /* Save copy */
811     $ldap->connect();
812     $ldap->cd($this->config->current['BASE']);
813     
814     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
816     /* FAIvariable=.../..., cn=.. 
817         could not be saved, because the attribute FAIvariable was different to 
818         the dn FAIvariable=..., cn=... */
820     if(!is_array($new['objectClass'])) $new['objectClass'] = array($new['objectClass']);
822     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
823       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
824     }
825     $ldap->cd($dst_dn);
826     $ldap->add($new);
828     if (!$ldap->success()){
829       trigger_error("Trying to save $dst_dn failed.",
830           E_USER_WARNING);
831       return(FALSE);
832     }
833     return(TRUE);
834   }
837   /* This is a workaround function. */
838   function copy($src_dn, $dst_dn)
839   {
840     /* Rename dn in possible object groups */
841     $ldap= $this->config->get_ldap_link();
842     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::prepare4filter($src_dn).'))',
843         array('cn'));
844     while ($attrs= $ldap->fetch()){
845       $og= new ogroup($this->config, $ldap->getDN());
846       unset($og->member[$src_dn]);
847       $og->member[$dst_dn]= $dst_dn;
848       $og->save ();
849     }
851     $ldap->cat($dst_dn);
852     $attrs= $ldap->fetch();
853     if (count($attrs)){
854       trigger_error("Trying to overwrite ".LDAP::fix($dst_dn).", which already exists.",
855           E_USER_WARNING);
856       return (FALSE);
857     }
859     $ldap->cat($src_dn);
860     $attrs= $ldap->fetch();
861     if (!count($attrs)){
862       trigger_error("Trying to move ".LDAP::fix($src_dn).", which does not seem to exist.",
863           E_USER_WARNING);
864       return (FALSE);
865     }
867     $ldap->cd($src_dn);
868     $ldap->search("objectClass=*",array("dn"));
869     while($attrs = $ldap->fetch()){
870       $src = $attrs['dn'];
871       $dst = preg_replace("/".preg_quote($src_dn, '/')."$/",$dst_dn,$attrs['dn']);
872       $this->_copy($src,$dst);
873     }
874     return (TRUE);
875   }
879   /*! \brief  Rename/Move a given src_dn to the given dest_dn
880    *
881    * Move a given ldap object indentified by $src_dn to the
882    * given destination $dst_dn
883    *
884    * - Ensure that all references are updated (ogroups)
885    * - Update ACLs   
886    * - Update accessTo
887    *
888    * \param  string  'src_dn' the source DN.
889    * \param  string  'dst_dn' the destination DN.
890    * \return boolean TRUE on success else FALSE.
891    */
892   function rename($src_dn, $dst_dn)
893   {
894     $start = microtime(1);
896     /* Try to move the source entry to the destination position */
897     $ldap = $this->config->get_ldap_link();
898     $ldap->cd($this->config->current['BASE']);
899     $ldap->create_missing_trees(preg_replace("/^[^,]+,/","",$dst_dn));
900     if (!$ldap->rename_dn($src_dn,$dst_dn)){
901       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());
902       @DEBUG(DEBUG_LDAP,__LINE__,__FUNCTION__,__FILE__,"Rename failed FROM: $src_dn  -- TO:  $dst_dn", 
903           "Ldap Protocol v3 implementation error, falling back to maunal method.");
904       return(FALSE);
905     }
907     /* Get list of users,groups and roles within this tree,
908         maybe we have to update ACL references.
909      */
910     $leaf_objs = get_list("(|(objectClass=posixGroup)(objectClass=gosaAccount)(objectClass=gosaRole))",array("all"),$dst_dn,
911           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
912     foreach($leaf_objs as $obj){
913       $new_dn = $obj['dn'];
914       $old_dn = preg_replace("/".preg_quote(LDAP::convert($dst_dn), '/')."$/i",$src_dn,LDAP::convert($new_dn));
915       $this->update_acls($old_dn,$new_dn); 
916     }
918     // Migrate objectgroups if needed
919     $ogroups = get_sub_list("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter(LDAP::fix($src_dn))."))",
920       "ogroups", array(get_ou("group", "ogroupRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
922     // Walk through all objectGroups
923     foreach($ogroups as $ogroup){
924       // Migrate old to new dn
925       $o_ogroup= new ogroup($this->config,$ogroup['dn']);
926       if (isset($o_ogroup->member[$src_dn])) {
927         unset($o_ogroup->member[$src_dn]);
928       }
929       $o_ogroup->member[$dst_dn]= $dst_dn;
930       
931       // Save object group
932       $o_ogroup->save();
933     }
935     // Migrate objectgroups if needed
936     $objects = get_sub_list("(&(objectClass=gotoEnvironment)(gotoHotplugDeviceDN=".LDAP::prepare4filter(LDAP::fix($src_dn))."))",
937             "users",array(get_ou("core","userRDN"), get_ou("core","groupRDN")),
938             $this->config->current['BASE'],array("dn", "gotoHotplugDeviceDN"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
939     $ldap = $this->config->get_ldap_link();
940     foreach($objects as $obj){
941         $deviceDNS = array();
942         for($i=0; $i < $obj["gotoHotplugDeviceDN"]['count']; $i++){
943             $odn = $obj["gotoHotplugDeviceDN"][$i];
944             if($odn == $src_dn){
945                 $odn = $dst_dn;
946             }
947             $deviceDNS[] = $odn;
948         }
949         $ldap->cd($obj['dn']);
950         $ldap->modify(array('gotoHotplugDeviceDN'=>$deviceDNS));
951         if(!$ldap->success()){
952             trigger_error(sprintf("Failed to update gotoHotplugDeviceDN for %s: %s", bold($obj['dn']), $ldap->get_error()));
953         }
954     }
956     // Migrate rfc groups if needed
957     $groups = get_sub_list("(&(objectClass=posixGroup)(member=".LDAP::prepare4filter(LDAP::fix($src_dn))."))","groups", array(get_ou("core", "groupRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
959     // Walk through all POSIX groups
960     foreach($groups as $group){
962       // Migrate old to new dn
963       $o_group= new group($this->config,$group['dn']);
964       $o_group->save();
965     }
967     /* Update roles to use the new entry dn */
968     $roles = get_sub_list("(&(objectClass=organizationalRole)(roleOccupant=".LDAP::prepare4filter(LDAP::fix($src_dn))."))","roles", array(get_ou("roleGeneric", "roleRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
970     // Walk through all roles
971     foreach($roles as $role){
972       $role = new roleGeneric($this->config,$role['dn']);
973       $key= array_search($src_dn, $role->roleOccupant);      
974       if($key !== FALSE){
975         $role->roleOccupant[$key] = $dst_dn;
976         $role->save();
977       }
978     }
980     // Update 'manager' attributes from gosaDepartment and inetOrgPerson 
981     $filter = "(&(objectClass=inetOrgPerson)(manager=".LDAP::prepare4filter(LDAP::fix($src_dn))."))";
982     $ocs = $ldap->get_objectclasses();
983     if(isset($ocs['gosaDepartment']['MAY']) && in_array('manager', $ocs['gosaDepartment']['MAY'])){
984       $filter = "(|".$filter."(&(objectClass=gosaDepartment)(manager=".LDAP::prepare4filter(LDAP::fix($src_dn)).")))";
985     }
986     $leaf_deps=  get_list($filter,array("all"),$this->config->current['BASE'], 
987         array("manager","dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
988     foreach($leaf_deps as $entry){
989       $update = array('manager' => $dst_dn);
990       $ldap->cd($entry['dn']);
991       $ldap->modify($update);
992       if(!$ldap->success()){
993         trigger_error(sprintf("Failed to update manager for %s: %s", bold($entry['dn']), $ldap->get_error()));
994       }
995     }
997     // Migrate 'dyn-groups' here. labeledURIObject
998     if(class_available('DynamicLdapGroup')) {
999         DynamicLdapGroup::moveDynGroup($this->config,$src_dn,$dst_dn);
1000     }
1001  
1002     /* Check if there are gosa departments moved. 
1003        If there were deps moved, the force reload of config->deps.
1004      */
1005     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
1006           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
1007   
1008     if(count($leaf_deps)){
1009       $this->config->get_departments();
1010       $this->config->make_idepartments();
1011       session::global_set("config",$this->config);
1012       $ui =get_userinfo();
1013       $ui->reset_acl_cache();
1014     }
1016     return(TRUE); 
1017   }
1020  
1021   function move($src_dn, $dst_dn)
1022   {
1023     /* Do not copy if only upper- lowercase has changed */
1024     if(strtolower($src_dn) == strtolower($dst_dn)){
1025       return(TRUE);
1026     }
1028     // Create statistic table entry 
1029     stats::log('plugin', $class = get_class($this), $category = array($this->acl_category),  $action = 'move', 
1030             $amount = 1, $duration = (microtime(TRUE) - $this->initTime));
1032     /* Try to move the entry instead of copy & delete
1033      */
1034     if(TRUE){
1036       /* Try to move with ldap routines, if this was not successfull
1037           fall back to the old style copy & remove method 
1038        */
1039       if($this->rename($src_dn, $dst_dn)){
1040         return(TRUE);
1041       }else{
1042         // See code below.
1043       }
1044     }
1046     /* Copy source to destination */
1047     if (!$this->copy($src_dn, $dst_dn)){
1048       return (FALSE);
1049     }
1051     /* Delete source */
1052     $ldap= $this->config->get_ldap_link();
1053     $ldap->rmdir_recursive($src_dn);
1054     if (!$ldap->success()){
1055       trigger_error("Trying to delete $src_dn failed.",
1056           E_USER_WARNING);
1057       return (FALSE);
1058     }
1060     return (TRUE);
1061   }
1064   /* \brief Move/Rename complete trees */
1065   function recursive_move($src_dn, $dst_dn)
1066   {
1067     /* Check if the destination entry exists */
1068     $ldap= $this->config->get_ldap_link();
1070     /* Check if destination exists - abort */
1071     $ldap->cat($dst_dn, array('dn'));
1072     if ($ldap->fetch()){
1073       trigger_error("recursive_move $dst_dn already exists.",
1074           E_USER_WARNING);
1075       return (FALSE);
1076     }
1078     $this->copy($src_dn, $dst_dn);
1080     /* Remove src_dn */
1081     $ldap->cd($src_dn);
1082     $ldap->recursive_remove($src_dn);
1083     return (TRUE);
1084   }
1087   function saveCopyDialog(){
1088   }
1091   function getCopyDialog(){
1092     return(array("string"=>"","status"=>""));
1093   }
1096   /*! \brief Prepare for Copy & Paste */
1097   function PrepareForCopyPaste($source)
1098   {
1099     $todo = $this->attributes;
1100     if(isset($this->CopyPasteVars)){
1101       $todo = array_merge($todo,$this->CopyPasteVars);
1102     }
1104     if(count($this->objectclasses)){
1105       $this->is_account = TRUE;
1106       foreach($this->objectclasses as $class){
1107         if(!in_array($class,$source['objectClass'])){
1108           $this->is_account = FALSE;
1109         }
1110       }
1111     }
1113     foreach($todo as $var){
1114       if (isset($source[$var])){
1115         if(isset($source[$var]['count'])){
1116           if($source[$var]['count'] > 1){
1117             $tmp= $source[$var];
1118             unset($tmp['count']);
1119             $this->$var = $tmp;
1120           }else{
1121             $this->$var = $source[$var][0];
1122           }
1123         }else{
1124           $this->$var= $source[$var];
1125         }
1126       }
1127     }
1128   }
1130   /*! \brief Get gosaUnitTag for the given DN
1131        If this is called from departmentGeneric, we have to skip this
1132         tagging procedure. 
1133     */
1134   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1135   {
1136     /* Skip tagging? */
1137     if($this->skipTagging){
1138       return;
1139     }
1141     /* No dn? Self-operation... */
1142     if ($dn == ""){
1143       $dn= $this->dn;
1145       /* No tag? Find it yourself... */
1146       if ($tag == ""){
1147         $len= strlen($dn);
1149         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1150         $relevant= array();
1151         foreach ($this->config->adepartments as $key => $ntag){
1153           /* This one is bigger than our dn, its not relevant... */
1154           if ($len < strlen($key)){
1155             continue;
1156           }
1158           /* This one matches with the latter part. Break and don't fix this entry */
1159           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
1160             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1161             $relevant[strlen($key)]= $ntag;
1162             continue;
1163           }
1165         }
1167         /* If we've some relevant tags to set, just get the longest one */
1168         if (count($relevant)){
1169           ksort($relevant);
1170           $tmp= array_keys($relevant);
1171           $idx= end($tmp);
1172           $tag= $relevant[$idx];
1173           $this->gosaUnitTag= $tag;
1174         }
1175       }
1176     }
1178   /*! \brief Add unit tag */ 
1179     /* Remove tags that may already be here... */
1180     remove_objectClass("gosaAdministrativeUnitTag", $at);
1181     if (isset($at['gosaUnitTag'])){
1182         unset($at['gosaUnitTag']);
1183     }
1185     /* Set tag? */
1186     if ($tag != ""){
1187       add_objectClass("gosaAdministrativeUnitTag", $at);
1188       $at['gosaUnitTag']= $tag;
1189     }
1191     /* Initially this object was tagged. 
1192        - But now, it is no longer inside a tagged department. 
1193        So force the remove of the tag.
1194        (objectClass was already removed obove)
1195      */
1196     if($tag == "" && $this->gosaUnitTag){
1197       $at['gosaUnitTag'] = array();
1198     }
1199   }
1202   /*! \brief Test for removability of the object
1203    *
1204    * Allows testing of conditions for removal of object. If removal should be aborted
1205    * the function needs to remove an error message.
1206    * */
1207   function allow_remove()
1208   {
1209     $reason= "";
1210     return $reason;
1211   }
1214   /*! \brief Test if snapshotting is enabled
1215    *
1216    * Test weither snapshotting is enabled or not. There will also be some errors posted,
1217    * if the configuration failed 
1218    * \return TRUE if snapshots are enabled, and FALSE if it is disabled
1219    */
1220   function snapshotEnabled()
1221   {
1222       return $this->config->snapshotEnabled();
1223   }
1226   /*! \brief Return plugin informations for acl handling 
1227    *         See class_core.inc for examples.
1228    */
1229   static function plInfo()
1230   {
1231     return array();
1232   }
1235   function set_acl_base($base)
1236   {
1237     @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,"<b>".$base."</b>","<b>ACL-Base:</b> ");
1238     $this->acl_base= $base;
1239   }
1242   function set_acl_category($category)
1243   {
1244     @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,"<b>".$category."</b>(/".get_class($this).")","<b>ACL-Category:</b> ");
1245     $this->acl_category= "$category/";
1246   }
1249   function acl_is_writeable($attribute,$skip_write = FALSE)
1250   {
1251     if($this->read_only) return(FALSE);
1252     $ui= get_userinfo();
1253     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1254   }
1257   function acl_is_readable($attribute)
1258   {
1259     $ui= get_userinfo();
1260     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1261   }
1264   function acl_is_createable($base ="")
1265   {
1266     if($this->read_only) return(FALSE);
1267     $ui= get_userinfo();
1268     if($base == "") $base = $this->acl_base;
1269     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1270   }
1273   function acl_is_removeable($base ="")
1274   {
1275     if($this->read_only) return(FALSE);
1276     $ui= get_userinfo();
1277     if($base == "") $base = $this->acl_base;
1278     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1279   }
1282   function acl_is_moveable($base = "")
1283   {
1284     if($this->read_only) return(FALSE);
1285     $ui= get_userinfo();
1286     if($base == "") $base = $this->acl_base;
1287     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1288   }
1291   function acl_have_any_permissions()
1292   {
1293   }
1296   function getacl($attribute,$skip_write= FALSE)
1297   {
1298     $ui= get_userinfo();
1299     $skip_write |= $this->read_only;
1300     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1301   }
1304   /*! \brief Returns a list of all available departments for this object.
1305    * 
1306    * If this object is new, all departments we are allowed to create a new user in
1307    * are returned. If this is an existing object, return all deps. 
1308    * We are allowed to move tis object too.
1309    * \return array [dn] => "..name"  // All deps. we are allowed to act on.
1310   */
1311   function get_allowed_bases()
1312   {
1313     $ui = get_userinfo();
1314     $deps = array();
1316     /* Is this a new object ? Or just an edited existing object */
1317     if(!$this->initially_was_account && $this->is_account){
1318       $new = true;
1319     }else{
1320       $new = false;
1321     }
1323     foreach($this->config->idepartments as $dn => $name){
1324       if($new && $this->acl_is_createable($dn)){
1325         $deps[$dn] = $name;
1326       }elseif(!$new && $this->acl_is_moveable($dn)){
1327         $deps[$dn] = $name;
1328       }
1329     }
1331     /* Add current base */      
1332     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1333       $deps[$this->base] = $this->config->idepartments[$this->base];
1334     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1336     }else{
1337       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1338     }
1339     return($deps);
1340   }
1343   /* This function updates ACL settings if $old_dn was used.
1344    *  \param string 'old_dn' specifies the actually used dn
1345    *  \param string 'new_dn' specifies the destiantion dn
1346    */
1347   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1348   {
1349     /* Check if old_dn is empty. This should never happen */
1350     if(empty($old_dn) || empty($new_dn)){
1351       trigger_error("Failed to check acl dependencies, wrong dn given.");
1352       return;
1353     }
1355     /* Update userinfo if necessary */
1356     $ui = session::global_get('ui');
1357     if($ui->dn == $old_dn){
1358       $ui->dn = $new_dn;
1359       $ui->loadACL();
1360       session::global_set('ui',$ui);
1361       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1362     }
1364     /* Object was moved, ensure that all acls will be moved too */
1365     if($new_dn != $old_dn && $old_dn != "new"){
1367       /* get_ldap configuration */
1368       $update = array();
1369       $ldap = $this->config->get_ldap_link();
1370       $ldap->cd ($this->config->current['BASE']);
1371       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1372       while($attrs = $ldap->fetch()){
1373         $acls = array();
1374         $found = false;
1375         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1376           $acl_parts = explode(":",$attrs['gosaAclEntry'][$i]);
1378           /* Roles uses antoher data storage order, members are stored int the third part, 
1379              while the members in direct ACL assignments are stored in the second part.
1380            */
1381           $id = ($acl_parts[1] == "role") ? 3 : 2;
1383           /* Update member entries to use $new_dn instead of old_dn
1384            */
1385           $members = explode(",",$acl_parts[$id]);
1386           foreach($members as $key => $member){
1387             $member = base64_decode($member);
1388             if($member == $old_dn){
1389               $members[$key] = base64_encode($new_dn);
1390               $found = TRUE;
1391             }
1392           } 
1394           /* Check if the selected role has to updated
1395            */
1396           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1397             $acl_parts[2] = base64_encode($new_dn);
1398             $found = TRUE;
1399           }
1401           /* Build new acl string */ 
1402           $acl_parts[$id] = implode($members,",");
1403           $acls[] = implode($acl_parts,":");
1404         }
1406         /* Acls for this object must be adjusted */
1407         if($found){
1409           $debug_info= sprintf(_("Changing ACL DN from %s to %s"), bold($old_dn), bold($new_dn));
1410           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1412           $update[$attrs['dn']] =array();
1413           foreach($acls as $acl){
1414             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1415           }
1416         }
1417       }
1419       /* Write updated acls */
1420       foreach($update as $dn => $attrs){
1421         $ldap->cd($dn);
1422         $ldap->modify($attrs);
1423       }
1424     }
1425   }
1427   
1429   /*! \brief Enable the Serial ID check
1430    *
1431    * This function enables the entry Serial ID check.  If an entry was edited while
1432    * we have edited the entry too, an error message will be shown. 
1433    * To configure this check correctly read the FAQ.
1434    */    
1435   function enable_CSN_check()
1436   {
1437     $this->CSN_check_active =TRUE;
1438     $this->entryCSN = getEntryCSN($this->dn);
1439   }
1442   /*! \brief  Prepares the plugin to be used for multiple edit
1443    *          Update plugin attributes with given array of attribtues.
1444    *  \param  array   Array with attributes that must be updated.
1445    */
1446   function init_multiple_support($attrs,$all)
1447   {
1448     $ldap= $this->config->get_ldap_link();
1449     $this->multi_attrs    = $attrs;
1450     $this->multi_attrs_all= $all;
1452     /* Copy needed attributes */
1453     foreach ($this->attributes as $val){
1454       $found= array_key_ics($val, $this->multi_attrs);
1455  
1456       if ($found != ""){
1457         if(isset($this->multi_attrs["$val"][0])){
1458           $this->$val= $this->multi_attrs["$val"][0];
1459         }
1460       }
1461     }
1462   }
1464  
1465   /*! \brief  Enables multiple support for this plugin
1466    */
1467   function enable_multiple_support()
1468   {
1469     $this->ignore_account = TRUE;
1470     $this->multiple_support_active = TRUE;
1471   }
1474   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1475       \return array Cotaining all modified values. 
1476    */
1477   function get_multi_edit_values()
1478   {
1479     $ret = array();
1480     foreach($this->attributes as $attr){
1481       if(in_array($attr,$this->multi_boxes)){
1482         $ret[$attr] = $this->$attr;
1483       }
1484     }
1485     return($ret);
1486   }
1488   
1489   /*! \brief  Update class variables with values collected by multiple edit.
1490    */
1491   function set_multi_edit_values($attrs)
1492   {
1493     foreach($attrs as $name => $value){
1494       $this->$name = $value;
1495     }
1496   }
1499   /*! \brief Generates the html output for this node for multi edit*/
1500   function multiple_execute()
1501   {
1502     /* This one is empty currently. Fabian - please fill in the docu code */
1503     session::global_set('current_class_for_help',get_class($this));
1505     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1506     session::set('LOCK_VARS_TO_USE',array());
1507     session::set('LOCK_VARS_USED_GET',array());
1508     session::set('LOCK_VARS_USED_POST',array());
1509     session::set('LOCK_VARS_USED_REQUEST',array());
1510     
1511     return("Multiple edit is currently not implemented for this plugin.");
1512   }
1515   /*! \brief Save HTML posted data to object for multiple edit
1516    */
1517   function multiple_save_object()
1518   {
1519     if(empty($this->entryCSN) && $this->CSN_check_active){
1520       $this->entryCSN = getEntryCSN($this->dn);
1521     }
1523     /* Save values to object */
1524     $this->multi_boxes = array();
1525     foreach ($this->attributes as $val){
1526   
1527       /* Get selected checkboxes from multiple edit */
1528       if(isset($_POST["use_".$val])){
1529         $this->multi_boxes[] = $val;
1530       }
1532       if (isset ($_POST["$val"]) && $this->acl_is_writeable($val)){
1534         $data= $this->$val = get_post($val);
1535         if ($this->$val != $data){
1536           $this->is_modified= TRUE;
1537         }
1538     
1539         /* IE post fix */
1540         if(isset($data[0]) && $data[0] == chr(194)) {
1541           $data = "";  
1542         }
1543         $this->$val= $data;
1544       }
1545     }
1546   }
1549   /*! \brief Returns all attributes of this plugin, 
1550                to be able to detect multiple used attributes 
1551                in multi_plugg::detect_multiple_used_attributes().
1552       @return array Attributes required for intialization of multi_plug
1553    */
1554   public function get_multi_init_values()
1555   {
1556     $attrs = $this->attrs;
1557     return($attrs);
1558   }
1561   /*! \brief  Check given values in multiple edit
1562       \return array Error messages
1563    */
1564   function multiple_check()
1565   {
1566     $message = plugin::check();
1567     return($message);
1568   }
1570   function get_used_snapshot_bases()
1571   {
1572      return(array());
1573   }
1575   function is_modal_dialog()
1576   {
1577     return(isset($this->dialog) && $this->dialog);
1578   }
1581   /*! \brief    Forward command execution requests
1582    *             to the hook execution method. 
1583    */
1584   function handle_post_events($mode, $addAttrs= array())
1585   {
1586     if(!in_array($mode, array('add','remove','modify'))){
1587       trigger_error(sprintf("Invalid post event type given %s! Valid types are [add,modify,remove].", bold($mode)));
1588       return;
1589     }
1590     switch ($mode){
1591       case "add":
1592         plugin::callHook($this,"POSTCREATE", $addAttrs);
1593       break;
1595       case "modify":
1596         plugin::callHook($this,"POSTMODIFY", $addAttrs);
1597       break;
1599       case "remove":
1600         plugin::callHook($this,"POSTREMOVE", $addAttrs);
1601       break;
1602     }
1603   }
1606   /*! \brief    Calls external hooks which are defined for this plugin (gosa.conf)
1607    *            Replaces placeholder by class values of this plugin instance.
1608    *  @param    Allows to a add special replacements.
1609    */
1610   static function callHook($plugin, $cmd, $addAttrs= array(), &$returnOutput = array(), 
1611           &$returnCode = NULL, &$errorOutput = array(), $displayErrors = TRUE)
1612   {
1613       global $config;
1614       $command = $config->configRegistry->getPropertyValue(get_class($plugin),$cmd);
1616       $returnCode = 0; // Simulate a return code to tell the caller that everythin is fine.
1617       $returnOutput = array();
1618       $arr = array();
1620       if (!empty($command)){
1622           // Walk trough attributes list and add the plugins attributes. 
1623           foreach ($plugin->attributes as $attr){
1624               if (!is_array($plugin->$attr)){
1625                   $addAttrs[$attr] = $plugin->$attr;
1626               }
1627           }
1628           $ui = get_userinfo();
1629           $addAttrs['callerDN']=$ui->dn;
1630           $addAttrs['dn']=$plugin->dn;
1631           $addAttrs['location']=$config->current['NAME'];
1633           // Sort attributes by length, ensures correct replacement
1634           $tmp = array();
1635           foreach($addAttrs as $name => $value){
1636               $tmp[$name] =  strlen($name);
1637           }
1638           arsort($tmp);
1640           // Now replace the placeholder 
1641           $command = fillReplacements($command, $addAttrs, TRUE);
1643           // If there are still some %.. in our command, try to fill these with some other class vars 
1644           if(preg_match("/%/",$command)){
1645               $attrs = get_object_vars($plugin);
1646               foreach($attrs as $name => $value){
1647                   if(is_array($value)){
1648                       $s = "";
1649                       foreach($value as $val){
1650                           if(is_string($val) || is_int($val) || is_float($val) || is_bool($val)){
1651                               $s .= '"'.$val.'",'; 
1652                           }
1653                       }
1654                       $value = '['.trim($s,',').']';
1655                   }
1656                   if(!is_string($value) && !is_int($value) && !is_float($value) && !is_bool($value)){
1657                       continue;
1658                   }
1659                   $command= preg_replace("/%$name/", escapeshellarg($value), $command);
1660               }
1661           }
1663           if (check_command($command)){
1665               // Create list of process pipes
1666               $descriptorspec = array(
1667                       0 => array("pipe", "r"),  // stdin
1668                       1 => array("pipe", "w"),  // stdout
1669                       2 => array("pipe", "w")); // stderr
1671               // Try to open the process
1672               @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,$command,"Execute");
1673               $process = proc_open($command, $descriptorspec, $pipes);
1674               if (is_resource($process)) {
1676                   // Write the password to stdin
1677                   // fwrite($pipes[0], $pwd); 
1678                   fclose($pipes[0]);
1680                   // Get results from stdout and stderr
1681                   $arr = stream_get_contents($pipes[1]);
1682                   $err = stream_get_contents($pipes[2]);
1683                   fclose($pipes[1]);
1685                   // Close the process and check its return value
1686                   $returnCode = proc_close($process);
1687                   $returnOutput = preg_split("/\n/", $arr,0,PREG_SPLIT_NO_EMPTY);
1688                   $errorOutput = preg_split("/\n/",$err,0,PREG_SPLIT_NO_EMPTY);
1689               }
1691               if($returnCode != 0){
1692                   @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execution failed code: ".$returnCode);
1693                   @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Result: ".$err);
1694                   if($displayErrors){
1695                       $message= msgPool::cmdexecfailed($cmd,$command, get_class($plugin));
1696                       msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
1697                   }
1698               }elseif(is_array($arr)){
1699                   @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Result: ".$arr);
1700               }
1701           } elseif($displayErrors) {
1702               $message= msgPool::cmdinvalid($cmd,$command, get_class($plugin));
1703               msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
1704           }
1705       }
1706   }
1709 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1710 ?>