Code

f932dd3f23b44e789e7d5cdebc636aae649fb29f
[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     if(class_available('roleGeneric')){
969         $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);
971         // Walk through all roles
972         foreach($roles as $role){
973             $role = new roleGeneric($this->config,$role['dn']);
974             $key= array_search($src_dn, $role->roleOccupant);      
975             if($key !== FALSE){
976                 $role->roleOccupant[$key] = $dst_dn;
977                 $role->save();
978             }
979         }
980     }
982     // Update 'manager' attributes from gosaDepartment and inetOrgPerson 
983     $filter = "(&(objectClass=inetOrgPerson)(manager=".LDAP::prepare4filter(LDAP::fix($src_dn))."))";
984     $ocs = $ldap->get_objectclasses();
985     if(isset($ocs['gosaDepartment']['MAY']) && in_array('manager', $ocs['gosaDepartment']['MAY'])){
986       $filter = "(|".$filter."(&(objectClass=gosaDepartment)(manager=".LDAP::prepare4filter(LDAP::fix($src_dn)).")))";
987     }
988     $leaf_deps=  get_list($filter,array("all"),$this->config->current['BASE'], 
989         array("manager","dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
990     foreach($leaf_deps as $entry){
991       $update = array('manager' => $dst_dn);
992       $ldap->cd($entry['dn']);
993       $ldap->modify($update);
994       if(!$ldap->success()){
995         trigger_error(sprintf("Failed to update manager for %s: %s", bold($entry['dn']), $ldap->get_error()));
996       }
997     }
999     // Migrate 'dyn-groups' here. labeledURIObject
1000     if(class_available('DynamicLdapGroup')) {
1001         DynamicLdapGroup::moveDynGroup($this->config,$src_dn,$dst_dn);
1002     }
1003  
1004     /* Check if there are gosa departments moved. 
1005        If there were deps moved, the force reload of config->deps.
1006      */
1007     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
1008           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
1009   
1010     if(count($leaf_deps)){
1011       $this->config->get_departments();
1012       $this->config->make_idepartments();
1013       session::global_set("config",$this->config);
1014       $ui =get_userinfo();
1015       $ui->reset_acl_cache();
1016     }
1018     return(TRUE); 
1019   }
1022  
1023   function move($src_dn, $dst_dn)
1024   {
1025     /* Do not copy if only upper- lowercase has changed */
1026     if(strtolower($src_dn) == strtolower($dst_dn)){
1027       return(TRUE);
1028     }
1030     // Create statistic table entry 
1031     stats::log('plugin', $class = get_class($this), $category = array($this->acl_category),  $action = 'move', 
1032             $amount = 1, $duration = (microtime(TRUE) - $this->initTime));
1034     /* Try to move the entry instead of copy & delete
1035      */
1036     if(TRUE){
1038       /* Try to move with ldap routines, if this was not successfull
1039           fall back to the old style copy & remove method 
1040        */
1041       if($this->rename($src_dn, $dst_dn)){
1042         return(TRUE);
1043       }else{
1044         // See code below.
1045       }
1046     }
1048     /* Copy source to destination */
1049     if (!$this->copy($src_dn, $dst_dn)){
1050       return (FALSE);
1051     }
1053     /* Delete source */
1054     $ldap= $this->config->get_ldap_link();
1055     $ldap->rmdir_recursive($src_dn);
1056     if (!$ldap->success()){
1057       trigger_error("Trying to delete $src_dn failed.",
1058           E_USER_WARNING);
1059       return (FALSE);
1060     }
1062     return (TRUE);
1063   }
1066   /* \brief Move/Rename complete trees */
1067   function recursive_move($src_dn, $dst_dn)
1068   {
1069     /* Check if the destination entry exists */
1070     $ldap= $this->config->get_ldap_link();
1072     /* Check if destination exists - abort */
1073     $ldap->cat($dst_dn, array('dn'));
1074     if ($ldap->fetch()){
1075       trigger_error("recursive_move $dst_dn already exists.",
1076           E_USER_WARNING);
1077       return (FALSE);
1078     }
1080     $this->copy($src_dn, $dst_dn);
1082     /* Remove src_dn */
1083     $ldap->cd($src_dn);
1084     $ldap->recursive_remove($src_dn);
1085     return (TRUE);
1086   }
1089   function saveCopyDialog(){
1090   }
1093   function getCopyDialog(){
1094     return(array("string"=>"","status"=>""));
1095   }
1098   /*! \brief Prepare for Copy & Paste */
1099   function PrepareForCopyPaste($source)
1100   {
1101     $todo = $this->attributes;
1102     if(isset($this->CopyPasteVars)){
1103       $todo = array_merge($todo,$this->CopyPasteVars);
1104     }
1106     if(count($this->objectclasses)){
1107       $this->is_account = TRUE;
1108       foreach($this->objectclasses as $class){
1109         if(!in_array($class,$source['objectClass'])){
1110           $this->is_account = FALSE;
1111         }
1112       }
1113     }
1115     foreach($todo as $var){
1116       if (isset($source[$var])){
1117         if(isset($source[$var]['count'])){
1118           if($source[$var]['count'] > 1){
1119             $tmp= $source[$var];
1120             unset($tmp['count']);
1121             $this->$var = $tmp;
1122           }else{
1123             $this->$var = $source[$var][0];
1124           }
1125         }else{
1126           $this->$var= $source[$var];
1127         }
1128       }
1129     }
1130   }
1132   /*! \brief Get gosaUnitTag for the given DN
1133        If this is called from departmentGeneric, we have to skip this
1134         tagging procedure. 
1135     */
1136   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1137   {
1138     /* Skip tagging? */
1139     if($this->skipTagging){
1140       return;
1141     }
1143     /* No dn? Self-operation... */
1144     if ($dn == ""){
1145       $dn= $this->dn;
1147       /* No tag? Find it yourself... */
1148       if ($tag == ""){
1149         $len= strlen($dn);
1151         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1152         $relevant= array();
1153         foreach ($this->config->adepartments as $key => $ntag){
1155           /* This one is bigger than our dn, its not relevant... */
1156           if ($len < strlen($key)){
1157             continue;
1158           }
1160           /* This one matches with the latter part. Break and don't fix this entry */
1161           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
1162             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1163             $relevant[strlen($key)]= $ntag;
1164             continue;
1165           }
1167         }
1169         /* If we've some relevant tags to set, just get the longest one */
1170         if (count($relevant)){
1171           ksort($relevant);
1172           $tmp= array_keys($relevant);
1173           $idx= end($tmp);
1174           $tag= $relevant[$idx];
1175           $this->gosaUnitTag= $tag;
1176         }
1177       }
1178     }
1180   /*! \brief Add unit tag */ 
1181     /* Remove tags that may already be here... */
1182     remove_objectClass("gosaAdministrativeUnitTag", $at);
1183     if (isset($at['gosaUnitTag'])){
1184         unset($at['gosaUnitTag']);
1185     }
1187     /* Set tag? */
1188     if ($tag != ""){
1189       add_objectClass("gosaAdministrativeUnitTag", $at);
1190       $at['gosaUnitTag']= $tag;
1191     }
1193     /* Initially this object was tagged. 
1194        - But now, it is no longer inside a tagged department. 
1195        So force the remove of the tag.
1196        (objectClass was already removed obove)
1197      */
1198     if($tag == "" && $this->gosaUnitTag){
1199       $at['gosaUnitTag'] = array();
1200     }
1201   }
1204   /*! \brief Test for removability of the object
1205    *
1206    * Allows testing of conditions for removal of object. If removal should be aborted
1207    * the function needs to remove an error message.
1208    * */
1209   function allow_remove()
1210   {
1211     $reason= "";
1212     return $reason;
1213   }
1216   /*! \brief Test if snapshotting is enabled
1217    *
1218    * Test weither snapshotting is enabled or not. There will also be some errors posted,
1219    * if the configuration failed 
1220    * \return TRUE if snapshots are enabled, and FALSE if it is disabled
1221    */
1222   function snapshotEnabled()
1223   {
1224       return $this->config->snapshotEnabled();
1225   }
1228   /*! \brief Return plugin informations for acl handling 
1229    *         See class_core.inc for examples.
1230    */
1231   static function plInfo()
1232   {
1233     return array();
1234   }
1237   function set_acl_base($base)
1238   {
1239     @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,"<b>".$base."</b>","<b>ACL-Base:</b> ");
1240     $this->acl_base= $base;
1241   }
1244   function set_acl_category($category)
1245   {
1246     @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,"<b>".$category."</b>(/".get_class($this).")","<b>ACL-Category:</b> ");
1247     $this->acl_category= "$category/";
1248   }
1251   function acl_is_writeable($attribute,$skip_write = FALSE)
1252   {
1253     if($this->read_only) return(FALSE);
1254     $ui= get_userinfo();
1255     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1256   }
1259   function acl_is_readable($attribute)
1260   {
1261     $ui= get_userinfo();
1262     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1263   }
1266   function acl_is_createable($base ="")
1267   {
1268     if($this->read_only) return(FALSE);
1269     $ui= get_userinfo();
1270     if($base == "") $base = $this->acl_base;
1271     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1272   }
1275   function acl_is_removeable($base ="")
1276   {
1277     if($this->read_only) return(FALSE);
1278     $ui= get_userinfo();
1279     if($base == "") $base = $this->acl_base;
1280     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1281   }
1284   function acl_is_moveable($base = "")
1285   {
1286     if($this->read_only) return(FALSE);
1287     $ui= get_userinfo();
1288     if($base == "") $base = $this->acl_base;
1289     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1290   }
1293   function acl_have_any_permissions()
1294   {
1295   }
1298   function getacl($attribute,$skip_write= FALSE)
1299   {
1300     $ui= get_userinfo();
1301     $skip_write |= $this->read_only;
1302     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1303   }
1306   /*! \brief Returns a list of all available departments for this object.
1307    * 
1308    * If this object is new, all departments we are allowed to create a new user in
1309    * are returned. If this is an existing object, return all deps. 
1310    * We are allowed to move tis object too.
1311    * \return array [dn] => "..name"  // All deps. we are allowed to act on.
1312   */
1313   function get_allowed_bases()
1314   {
1315     $ui = get_userinfo();
1316     $deps = array();
1318     /* Is this a new object ? Or just an edited existing object */
1319     if(!$this->initially_was_account && $this->is_account){
1320       $new = true;
1321     }else{
1322       $new = false;
1323     }
1325     foreach($this->config->idepartments as $dn => $name){
1326       if($new && $this->acl_is_createable($dn)){
1327         $deps[$dn] = $name;
1328       }elseif(!$new && $this->acl_is_moveable($dn)){
1329         $deps[$dn] = $name;
1330       }
1331     }
1333     /* Add current base */      
1334     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1335       $deps[$this->base] = $this->config->idepartments[$this->base];
1336     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1338     }else{
1339       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1340     }
1341     return($deps);
1342   }
1345   /* This function updates ACL settings if $old_dn was used.
1346    *  \param string 'old_dn' specifies the actually used dn
1347    *  \param string 'new_dn' specifies the destiantion dn
1348    */
1349   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1350   {
1351     /* Check if old_dn is empty. This should never happen */
1352     if(empty($old_dn) || empty($new_dn)){
1353       trigger_error("Failed to check acl dependencies, wrong dn given.");
1354       return;
1355     }
1357     /* Update userinfo if necessary */
1358     $ui = session::global_get('ui');
1359     if($ui->dn == $old_dn){
1360       $ui->dn = $new_dn;
1361       $ui->loadACL();
1362       session::global_set('ui',$ui);
1363       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1364     }
1366     /* Object was moved, ensure that all acls will be moved too */
1367     if($new_dn != $old_dn && $old_dn != "new"){
1369       /* get_ldap configuration */
1370       $update = array();
1371       $ldap = $this->config->get_ldap_link();
1372       $ldap->cd ($this->config->current['BASE']);
1373       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1374       while($attrs = $ldap->fetch()){
1375         $acls = array();
1376         $found = false;
1377         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1378           $acl_parts = explode(":",$attrs['gosaAclEntry'][$i]);
1380           /* Roles uses antoher data storage order, members are stored int the third part, 
1381              while the members in direct ACL assignments are stored in the second part.
1382            */
1383           $id = ($acl_parts[1] == "role") ? 3 : 2;
1385           /* Update member entries to use $new_dn instead of old_dn
1386            */
1387           $members = explode(",",$acl_parts[$id]);
1388           foreach($members as $key => $member){
1389             $member = base64_decode($member);
1390             if($member == $old_dn){
1391               $members[$key] = base64_encode($new_dn);
1392               $found = TRUE;
1393             }
1394           } 
1396           /* Check if the selected role has to updated
1397            */
1398           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1399             $acl_parts[2] = base64_encode($new_dn);
1400             $found = TRUE;
1401           }
1403           /* Build new acl string */ 
1404           $acl_parts[$id] = implode($members,",");
1405           $acls[] = implode($acl_parts,":");
1406         }
1408         /* Acls for this object must be adjusted */
1409         if($found){
1411           $debug_info= sprintf(_("Changing ACL DN from %s to %s"), bold($old_dn), bold($new_dn));
1412           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1414           $update[$attrs['dn']] =array();
1415           foreach($acls as $acl){
1416             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1417           }
1418         }
1419       }
1421       /* Write updated acls */
1422       foreach($update as $dn => $attrs){
1423         $ldap->cd($dn);
1424         $ldap->modify($attrs);
1425       }
1426     }
1427   }
1429   
1431   /*! \brief Enable the Serial ID check
1432    *
1433    * This function enables the entry Serial ID check.  If an entry was edited while
1434    * we have edited the entry too, an error message will be shown. 
1435    * To configure this check correctly read the FAQ.
1436    */    
1437   function enable_CSN_check()
1438   {
1439     $this->CSN_check_active =TRUE;
1440     $this->entryCSN = getEntryCSN($this->dn);
1441   }
1444   /*! \brief  Prepares the plugin to be used for multiple edit
1445    *          Update plugin attributes with given array of attribtues.
1446    *  \param  array   Array with attributes that must be updated.
1447    */
1448   function init_multiple_support($attrs,$all)
1449   {
1450     $ldap= $this->config->get_ldap_link();
1451     $this->multi_attrs    = $attrs;
1452     $this->multi_attrs_all= $all;
1454     /* Copy needed attributes */
1455     foreach ($this->attributes as $val){
1456       $found= array_key_ics($val, $this->multi_attrs);
1457  
1458       if ($found != ""){
1459         if(isset($this->multi_attrs["$val"][0])){
1460           $this->$val= $this->multi_attrs["$val"][0];
1461         }
1462       }
1463     }
1464   }
1466  
1467   /*! \brief  Enables multiple support for this plugin
1468    */
1469   function enable_multiple_support()
1470   {
1471     $this->ignore_account = TRUE;
1472     $this->multiple_support_active = TRUE;
1473   }
1476   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1477       \return array Cotaining all modified values. 
1478    */
1479   function get_multi_edit_values()
1480   {
1481     $ret = array();
1482     foreach($this->attributes as $attr){
1483       if(in_array($attr,$this->multi_boxes)){
1484         $ret[$attr] = $this->$attr;
1485       }
1486     }
1487     return($ret);
1488   }
1490   
1491   /*! \brief  Update class variables with values collected by multiple edit.
1492    */
1493   function set_multi_edit_values($attrs)
1494   {
1495     foreach($attrs as $name => $value){
1496       $this->$name = $value;
1497     }
1498   }
1501   /*! \brief Generates the html output for this node for multi edit*/
1502   function multiple_execute()
1503   {
1504     /* This one is empty currently. Fabian - please fill in the docu code */
1505     session::global_set('current_class_for_help',get_class($this));
1507     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1508     session::set('LOCK_VARS_TO_USE',array());
1509     session::set('LOCK_VARS_USED_GET',array());
1510     session::set('LOCK_VARS_USED_POST',array());
1511     session::set('LOCK_VARS_USED_REQUEST',array());
1512     
1513     return("Multiple edit is currently not implemented for this plugin.");
1514   }
1517   /*! \brief Save HTML posted data to object for multiple edit
1518    */
1519   function multiple_save_object()
1520   {
1521     if(empty($this->entryCSN) && $this->CSN_check_active){
1522       $this->entryCSN = getEntryCSN($this->dn);
1523     }
1525     /* Save values to object */
1526     $this->multi_boxes = array();
1527     foreach ($this->attributes as $val){
1528   
1529       /* Get selected checkboxes from multiple edit */
1530       if(isset($_POST["use_".$val])){
1531         $this->multi_boxes[] = $val;
1532       }
1534       if (isset ($_POST["$val"]) && $this->acl_is_writeable($val)){
1536         $data= $this->$val = get_post($val);
1537         if ($this->$val != $data){
1538           $this->is_modified= TRUE;
1539         }
1540     
1541         /* IE post fix */
1542         if(isset($data[0]) && $data[0] == chr(194)) {
1543           $data = "";  
1544         }
1545         $this->$val= $data;
1546       }
1547     }
1548   }
1551   /*! \brief Returns all attributes of this plugin, 
1552                to be able to detect multiple used attributes 
1553                in multi_plugg::detect_multiple_used_attributes().
1554       @return array Attributes required for intialization of multi_plug
1555    */
1556   public function get_multi_init_values()
1557   {
1558     $attrs = $this->attrs;
1559     return($attrs);
1560   }
1563   /*! \brief  Check given values in multiple edit
1564       \return array Error messages
1565    */
1566   function multiple_check()
1567   {
1568     $message = plugin::check();
1569     return($message);
1570   }
1572   function get_used_snapshot_bases()
1573   {
1574      return(array());
1575   }
1577   function is_modal_dialog()
1578   {
1579     return(isset($this->dialog) && $this->dialog);
1580   }
1583   /*! \brief    Forward command execution requests
1584    *             to the hook execution method. 
1585    */
1586   function handle_post_events($mode, $addAttrs= array())
1587   {
1588     if(!in_array($mode, array('add','remove','modify'))){
1589       trigger_error(sprintf("Invalid post event type given %s! Valid types are [add,modify,remove].", bold($mode)));
1590       return;
1591     }
1592     switch ($mode){
1593       case "add":
1594         plugin::callHook($this,"POSTCREATE", $addAttrs);
1595       break;
1597       case "modify":
1598         plugin::callHook($this,"POSTMODIFY", $addAttrs);
1599       break;
1601       case "remove":
1602         plugin::callHook($this,"POSTREMOVE", $addAttrs);
1603       break;
1604     }
1605   }
1608   /*! \brief    Calls external hooks which are defined for this plugin (gosa.conf)
1609    *            Replaces placeholder by class values of this plugin instance.
1610    *  @param    Allows to a add special replacements.
1611    */
1612   static function callHook($plugin, $cmd, $addAttrs= array(), &$returnOutput = array(), 
1613           &$returnCode = NULL, &$errorOutput = array(), $displayErrors = TRUE)
1614   {
1615       global $config;
1616       $command = $config->configRegistry->getPropertyValue(get_class($plugin),$cmd);
1618       $returnCode = 0; // Simulate a return code to tell the caller that everythin is fine.
1619       $returnOutput = array();
1620       $arr = array();
1622       if (!empty($command)){
1624           // Walk trough attributes list and add the plugins attributes. 
1625           foreach ($plugin->attributes as $attr){
1626               if (!is_array($plugin->$attr)){
1627                   $addAttrs[$attr] = $plugin->$attr;
1628               }
1629           }
1630           $ui = get_userinfo();
1631           $addAttrs['callerDN']=$ui->dn;
1632           $addAttrs['dn']=$plugin->dn;
1633           $addAttrs['location']=$config->current['NAME'];
1635           // Sort attributes by length, ensures correct replacement
1636           $tmp = array();
1637           foreach($addAttrs as $name => $value){
1638               $tmp[$name] =  strlen($name);
1639           }
1640           arsort($tmp);
1642           // Now replace the placeholder 
1643           $command = fillReplacements($command, $addAttrs, TRUE);
1645           // If there are still some %.. in our command, try to fill these with some other class vars 
1646           if(preg_match("/%/",$command)){
1647               $attrs = get_object_vars($plugin);
1648               foreach($attrs as $name => $value){
1649                   if(is_array($value)){
1650                       $s = "";
1651                       foreach($value as $val){
1652                           if(is_string($val) || is_int($val) || is_float($val) || is_bool($val)){
1653                               $s .= '"'.$val.'",'; 
1654                           }
1655                       }
1656                       $value = '['.trim($s,',').']';
1657                   }
1658                   if(!is_string($value) && !is_int($value) && !is_float($value) && !is_bool($value)){
1659                       continue;
1660                   }
1661                   $command= preg_replace("/%$name/", escapeshellarg($value), $command);
1662               }
1663           }
1665           if (check_command($command)){
1667               // Create list of process pipes
1668               $descriptorspec = array(
1669                       0 => array("pipe", "r"),  // stdin
1670                       1 => array("pipe", "w"),  // stdout
1671                       2 => array("pipe", "w")); // stderr
1673               // Try to open the process
1674               @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,$command,"Execute");
1675               $process = proc_open($command, $descriptorspec, $pipes);
1676               if (is_resource($process)) {
1678                   // Write the password to stdin
1679                   // fwrite($pipes[0], $pwd); 
1680                   fclose($pipes[0]);
1682                   // Get results from stdout and stderr
1683                   $arr = stream_get_contents($pipes[1]);
1684                   $err = stream_get_contents($pipes[2]);
1685                   fclose($pipes[1]);
1687                   // Close the process and check its return value
1688                   $returnCode = proc_close($process);
1689                   $returnOutput = preg_split("/\n/", $arr,0,PREG_SPLIT_NO_EMPTY);
1690                   $errorOutput = preg_split("/\n/",$err,0,PREG_SPLIT_NO_EMPTY);
1691               }
1693               if($returnCode != 0){
1694                   @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execution failed code: ".$returnCode);
1695                   @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Result: ".$err);
1696                   if($displayErrors){
1697                       $message= msgPool::cmdexecfailed($cmd,$command, get_class($plugin));
1698                       msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
1699                   }
1700               }elseif(is_array($arr)){
1701                   @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Result: ".$arr);
1702               }
1703           } elseif($displayErrors) {
1704               $message= msgPool::cmdinvalid($cmd,$command, get_class($plugin));
1705               msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
1706           }
1707       }
1708   }
1711 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1712 ?>