Code

Updated english strings
[gosa.git] / gosa-core / include / class_plugin.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 /*! \brief   The plugin base class
24   \author  Cajus Pollmeier <pollmeier@gonicus.de>
25   \version 2.00
26   \date    24.07.2003
28   This is the base class for all plugins. It can be used standalone or
29   can be included by the tabs class. All management should be done 
30   within this class. Extend your plugins from this class.
31  */
33 class plugin
34
35   /*! \brief    The title shown in path menu while this plugin is visible.
36    */
37   var $pathTitle = "";
39   /*!
40     \brief Reference to parent object
42     This variable is used when the plugin is included in tabs
43     and keeps reference to the tab class. Communication to other
44     tabs is possible by 'name'. So the 'fax' plugin can ask the
45     'userinfo' plugin for the fax number.
47     \sa tab
48    */
49   var $parent= NULL;
51   /*!
52     \brief Configuration container
54     Access to global configuration
55    */
56   var $config= NULL;
58   /*!
59     \brief Mark plugin as account
61     Defines whether this plugin is defined as an account or not.
62     This has consequences for the plugin to be saved from tab
63     mode. If it is set to 'FALSE' the tab will call the delete
64     function, else the save function. Should be set to 'TRUE' if
65     the construtor detects a valid LDAP object.
67     \sa plugin::plugin()
68    */
69   var $is_account= FALSE;
70   var $initially_was_account= FALSE;
72   /*!
73     \brief Mark plugin as template
75     Defines whether we are creating a template or a normal object.
76     Has conseqences on the way execute() shows the formular and how
77     save() puts the data to LDAP.
79     \sa plugin::save() plugin::execute()
80    */
81   var $is_template= FALSE;
82   var $ignore_account= FALSE;
83   var $is_modified= FALSE;
85   /*!
86     \brief Represent temporary LDAP data
88     This is only used internally.
89    */
90   var $attrs= array();
92   /* Keep set of conflicting plugins */
93   var $conflicts= array();
95   /* Save unit tags */
96   var $gosaUnitTag= "";
97   var $skipTagging= FALSE;
99   /*!
100     \brief Used standard values
102     dn
103    */
104   var $dn= "";
105   var $uid= "";
106   var $sn= "";
107   var $givenName= "";
108   var $acl= "*none*";
109   var $dialog= FALSE;
110   var $snapDialog = NULL;
112   /* attribute list for save action */
113   var $attributes= array();
114   var $objectclasses= array();
115   var $is_new= TRUE;
116   var $saved_attributes= array();
118   var $acl_base= "";
119   var $acl_category= "";
120   var $read_only = FALSE; // Used when the entry is opened as "readonly" due to locks.
122   /* This can be set to render the tabulators in another stylesheet */
123   var $pl_notify= FALSE;
125   /* Object entry CSN */
126   var $entryCSN         = "";
127   var $CSN_check_active = FALSE;
129   /* This variable indicates that this class can handle multiple dns at once. */
130   var $multiple_support = FALSE;
131   var $multi_attrs      = array();
132   var $multi_attrs_all  = array(); 
134   /* This aviable indicates, that we are currently in multiple edit handle */
135   var $multiple_support_active = FALSE; 
136   var $selected_edit_values = array();
137   var $multi_boxes = array();
139   /*! \brief plugin constructor
141     If 'dn' is set, the node loads the given 'dn' from LDAP
143     \param dn Distinguished name to initialize plugin from
144     \sa plugin()
145    */
146   function plugin (&$config, $dn= NULL, $object= NULL)
147   {
148     /* Configuration is fine, allways */
149     $this->config= &$config;    
150     $this->dn= $dn;
152     // Ensure that we've a valid acl_category set.
153     if(empty($this->acl_category)){
154       $tmp = $this->plInfo();
155       if (isset($tmp['plCategory'])) {
156         $c = key($tmp['plCategory']);
157         if(is_numeric($c)){
158           $c = $tmp['plCategory'][0];
159         }
160         $this->acl_category = $c."/";
161       }
162     }
164     /* Handle new accounts, don't read information from LDAP */
165     if ($dn == "new"){
166       return;
167     }
169     /* Check if this entry was opened in read only mode */
170     if(isset($_POST['open_readonly'])){
171       if(session::global_is_set("LOCK_CACHE")){
172         $cache = &session::get("LOCK_CACHE");
173         if(isset($cache['READ_ONLY'][$this->dn])){
174           $this->read_only = TRUE;
175         }
176       }
177     }
179     /* Save current dn as acl_base */
180     $this->acl_base= $dn;
182     /* Get LDAP descriptor */
183     if ($dn !== NULL){
185       /* Load data to 'attrs' and save 'dn' */
186       if ($object !== NULL){
187         $this->attrs= $object->attrs;
188       } else {
189         $ldap= $this->config->get_ldap_link();
190         $ldap->cat ($dn);
191         $this->attrs= $ldap->fetch();
192       }
194       /* Copy needed attributes */
195       foreach ($this->attributes as $val){
196         $found= array_key_ics($val, $this->attrs);
197         if ($found != ""){
198           $this->$val= $found[0];
199         }
200       }
202       /* gosaUnitTag loading... */
203       if (isset($this->attrs['gosaUnitTag'][0])){
204         $this->gosaUnitTag= $this->attrs['gosaUnitTag'][0];
205       }
207       /* Set the template flag according to the existence of objectClass
208          gosaUserTemplate */
209       if (isset($this->attrs['objectClass'])){
210         if (in_array_ics ("gosaUserTemplate", $this->attrs['objectClass'])){
211           $this->is_template= TRUE;
212           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
213               "found", "Template check");
214         }
215       }
217       /* Is Account? */
218       $found= TRUE;
219       foreach ($this->objectclasses as $obj){
220         if (preg_match('/top/i', $obj)){
221           continue;
222         }
223         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
224           $found= FALSE;
225           break;
226         }
227       }
228       if ($found){
229         $this->is_account= TRUE;
230         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
231             "found", "Object check");
232       }
234       /* Prepare saved attributes */
235       $this->saved_attributes= $this->attrs;
236       foreach ($this->saved_attributes as $index => $value){
237         if (is_numeric($index)){
238           unset($this->saved_attributes[$index]);
239           continue;
240         }
242         if (!in_array_ics($index, $this->attributes) && strcasecmp('objectClass', $index)){
243           unset($this->saved_attributes[$index]);
244           continue;
245         }
247         if (isset($this->saved_attributes[$index][0])){
248           if(!isset($this->saved_attributes[$index]["count"])){
249             $this->saved_attributes[$index]["count"] = count($this->saved_attributes[$index]);
250           }
251           if($this->saved_attributes[$index]["count"] == 1){
252             $tmp= $this->saved_attributes[$index][0];
253             unset($this->saved_attributes[$index]);
254             $this->saved_attributes[$index]= $tmp;
255             continue;
256           }
257         }
258         unset($this->saved_attributes["$index"]["count"]);
259       }
261       if(isset($this->attrs['gosaUnitTag'])){
262         $this->saved_attributes['gosaUnitTag'] = $this->attrs['gosaUnitTag'][0];
263       }
264     }
266     /* Save initial account state */
267     $this->initially_was_account= $this->is_account;
268   }
271   /*! \brief Generates the html output for this node
272    */
273   function execute()
274   {
275     /* This one is empty currently. Fabian - please fill in the docu code */
276     session::global_set('current_class_for_help',get_class($this));
278     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
279     session::set('LOCK_VARS_TO_USE',array());
280     session::set('LOCK_VARS_USED_GET',array());
281     session::set('LOCK_VARS_USED_POST',array());
282     session::set('LOCK_VARS_USED_REQUEST',array());
284     pathNavigator::registerPlugin($this);
285   }
287   /*! \brief Removes object from parent
288    */
289   function remove_from_parent()
290   {
291     /* include global link_info */
292     $ldap= $this->config->get_ldap_link();
294     /* Get current objectClasses in order to add the required ones */
295     $ldap->cat($this->dn);
296     $tmp= $ldap->fetch ();
297     $oc= array();
298     if (isset($tmp['objectClass'])){
299       $oc= $tmp['objectClass'];
300       unset($oc['count']);
301     }
303     /* Remove objectClasses from entry */
304     $ldap->cd($this->dn);
305     $this->attrs= array();
306     $this->attrs['objectClass']= array_remove_entries_ics($this->objectclasses,$oc);
308     /* Unset attributes from entry */
309     foreach ($this->attributes as $val){
310       $this->attrs["$val"]= array();
311     }
313     /* Unset account info */
314     $this->is_account= FALSE;
316     /* Do not write in plugin base class, this must be done by
317        children, since there are normally additional attribs,
318        lists, etc. */
319     /*
320        $ldap->modify($this->attrs);
321      */
322   }
325   /*! \brief Save HTML posted data to object 
326    */
327   function save_object()
328   {
329     /* Update entry CSN if it is empty. */
330     if(empty($this->entryCSN) && $this->CSN_check_active){
331       $this->entryCSN = getEntryCSN($this->dn);
332     }
334     /* Save values to object */
335     foreach ($this->attributes as $val){
336       if (isset ($_POST["$val"]) && $this->acl_is_writeable($val)){
337         /* Check for modifications */
338         if (get_magic_quotes_gpc()) {
339           $data= stripcslashes($_POST["$val"]);
340         } else {
341           $data= $this->$val = $_POST["$val"];
342         }
343         if ($this->$val != $data){
344           $this->is_modified= TRUE;
345         }
346     
347         /* Okay, how can I explain this fix ... 
348          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
349          * So IE posts these 'unselectable' option, with value = chr(194) 
350          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
351          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
352          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
353          */
354         if(isset($data[0]) && $data[0] == chr(194)) {
355           $data = "";  
356         }
357         $this->$val= $data;
358       }
359     }
360   }
363   /*! \brief Save data to LDAP, depending on is_account we save or delete */
364   function save()
365   {
366     /* include global link_info */
367     $ldap= $this->config->get_ldap_link();
369     /* Save all plugins */
370     $this->entryCSN = "";
372     /* Start with empty array */
373     $this->attrs= array();
375     /* Get current objectClasses in order to add the required ones */
376     $ldap->cat($this->dn);
377     
378     $tmp= $ldap->fetch ();
380     $oc= array();
381     if (isset($tmp['objectClass'])){
382       $oc= $tmp["objectClass"];
383       $this->is_new= FALSE;
384       unset($oc['count']);
385     } else {
386       $this->is_new= TRUE;
387     }
389     /* Load (minimum) attributes, add missing ones */
390     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
392     /* Copy standard attributes */
393     foreach ($this->attributes as $val){
394       if ($this->$val != ""){
395         $this->attrs["$val"]= $this->$val;
396       } elseif (!$this->is_new) {
397         $this->attrs["$val"]= array();
398       }
399     }
401     /* Handle tagging */
402     $this->tag_attrs($this->attrs);
403   }
406   function cleanup()
407   {
408     foreach ($this->attrs as $index => $value){
409       
410       /* Convert arrays with one element to non arrays, if the saved
411          attributes are no array, too */
412       if (is_array($this->attrs[$index]) && 
413           count ($this->attrs[$index]) == 1 &&
414           isset($this->saved_attributes[$index]) &&
415           !is_array($this->saved_attributes[$index])){
416           
417         $tmp= $this->attrs[$index][0];
418         $this->attrs[$index]= $tmp;
419       }
421       /* Remove emtpy arrays if they do not differ */
422       if (is_array($this->attrs[$index]) &&
423           count($this->attrs[$index]) == 0 &&
424           !isset($this->saved_attributes[$index])){
425           
426         unset ($this->attrs[$index]);
427         continue;
428       }
430       /* Remove single attributes that do not differ */
431       if (!is_array($this->attrs[$index]) &&
432           isset($this->saved_attributes[$index]) &&
433           !is_array($this->saved_attributes[$index]) &&
434           $this->attrs[$index] == $this->saved_attributes[$index]){
436         unset ($this->attrs[$index]);
437         continue;
438       }
440       /* Remove arrays that do not differ */
441       if (is_array($this->attrs[$index]) && 
442           isset($this->saved_attributes[$index]) &&
443           is_array($this->saved_attributes[$index])){
444           
445         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
446           unset ($this->attrs[$index]);
447           continue;
448         }
449       }
450     }
452     /* Update saved attributes and ensure that next cleanups will be successful too */
453     foreach($this->attrs as $name => $value){
454       $this->saved_attributes[$name] = $value;
455     }
456   }
458   /*! \brief Check formular input */
459   function check()
460   {
461     $message= array();
463     /* Skip if we've no config object */
464     if (!isset($this->config) || !is_object($this->config)){
465       return $message;
466     }
468     /* Find hooks entries for this class */
469     $command= $this->config->search(get_class($this), "CHECK", array('menu', 'tabs'));
471     if ($command != ""){
473       if (!check_command($command)){
474         $message[]= msgPool::cmdnotfound("CHECK", get_class($this));
475       } else {
477         /* Generate "ldif" for check hook */
478         $ldif= "dn: $this->dn\n";
479         
480         /* ... objectClasses */
481         foreach ($this->objectclasses as $oc){
482           $ldif.= "objectClass: $oc\n";
483         }
484         
485         /* ... attributes */
486         foreach ($this->attributes as $attr){
487           if ($this->$attr == ""){
488             continue;
489           }
490           if (is_array($this->$attr)){
491             foreach ($this->$attr as $val){
492               $ldif.= "$attr: $val\n";
493             }
494           } else {
495               $ldif.= "$attr: ".$this->$attr."\n";
496           }
497         }
499         /* Append empty line */
500         $ldif.= "\n";
502         /* Feed "ldif" into hook and retrieve result*/
503         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
504         $fh= proc_open($command, $descriptorspec, $pipes);
505         if (is_resource($fh)) {
506           fwrite ($pipes[0], $ldif);
507           fclose($pipes[0]);
508           
509           $result= stream_get_contents($pipes[1]);
510           if ($result != ""){
511             $message[]= $result;
512           }
513           
514           fclose($pipes[1]);
515           fclose($pipes[2]);
516           proc_close($fh);
517         }
518       }
520     }
522     /* Check entryCSN */
523     if($this->CSN_check_active){
524       $current_csn = getEntryCSN($this->dn);
525       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
526         $this->entryCSN = $current_csn;
527         $message[] = _("The current object has been altered while beeing edited. If you save this entry, changes that have been made by others will be discarded!");
528       }
529     }
530     return ($message);
531   }
533   /* Adapt from template, using 'dn' */
534   function adapt_from_template($dn, $skip= array())
535   {
536     /* Include global link_info */
537     $ldap= $this->config->get_ldap_link();
539     /* Load requested 'dn' to 'attrs' */
540     $ldap->cat ($dn);
541     $this->attrs= $ldap->fetch();
543     /* Walk through attributes */
544     foreach ($this->attributes as $val){
546       /* Skip the ones in skip list */
547       if (in_array($val, $skip)){
548         continue;
549       }
551       if (isset($this->attrs["$val"][0])){
553         /* If attribute is set, replace dynamic parts: 
554            %sn, %givenName and %uid. Fill these in our local variables. */
555         $value= $this->attrs["$val"][0];
557         foreach (array("sn", "givenName", "uid") as $repl){
558           if (preg_match("/%$repl/i", $value)){
559             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
560           }
561         }
562         $this->$val= $value;
563       }
564     }
566     /* Is Account? */
567     $found= TRUE;
568     foreach ($this->objectclasses as $obj){
569       if (preg_match('/top/i', $obj)){
570         continue;
571       }
572       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
573         $found= FALSE;
574         break;
575       }
576     }
577     if ($found){
578       $this->is_account= TRUE;
579     }
580   }
582   /* \brief Indicate whether a password change is needed or not */
583   function password_change_needed()
584   {
585     return FALSE;
586   }
589   /*! \brief Show header message for tab dialogs */
590   function show_enable_header($button_text, $text, $disabled= FALSE)
591   {
592     if (($disabled == TRUE) || (!$this->acl_is_createable())){
593       $state= "disabled";
594     } else {
595       $state= "";
596     }
597     $display = "<div class='plugin-enable-header'>\n";
598     $display.= "<p>$text</p>\n";
599     $display.= "<button type='submit' name=\"modify_state\" ".$state.">$button_text</button>\n";
600     $display.= "</div>\n";
602     return($display);
603   }
606   /*! \brief Show header message for tab dialogs */
607   function show_disable_header($button_text, $text, $disabled= FALSE)
608   {
609     if (($disabled == TRUE) || !$this->acl_is_removeable()){
610       $state= "disabled";
611     } else {
612       $state= "";
613     }
614     $display = "<div class='plugin-disable-header'>\n";
615     $display.= "<p>$text</p>\n";
616     $display.= "<button type='submit' name=\"modify_state\" ".$state.">$button_text</button>\n";
617     $display.= "</div>\n";
618     return($display);
619   }
623   /* Create unique DN */
624   function create_unique_dn2($data, $base)
625   {
626     $ldap= $this->config->get_ldap_link();
627     $base= preg_replace("/^,*/", "", $base);
629     /* Try to use plain entry first */
630     $dn= "$data,$base";
631     $attribute= preg_replace('/=.*$/', '', $data);
632     $ldap->cat ($dn, array('dn'));
633     if (!$ldap->fetch()){
634       return ($dn);
635     }
637     /* Look for additional attributes */
638     foreach ($this->attributes as $attr){
639       if ($attr == $attribute || $this->$attr == ""){
640         continue;
641       }
643       $dn= "$data+$attr=".$this->$attr.",$base";
644       $ldap->cat ($dn, array('dn'));
645       if (!$ldap->fetch()){
646         return ($dn);
647       }
648     }
650     /* None found */
651     return ("none");
652   }
655   /*! \brief Create unique DN */
656   function create_unique_dn($attribute, $base)
657   {
658     $ldap= $this->config->get_ldap_link();
659     $base= preg_replace("/^,*/", "", $base);
661     /* Try to use plain entry first */
662     $dn= "$attribute=".$this->$attribute.",$base";
663     $ldap->cat ($dn, array('dn'));
664     if (!$ldap->fetch()){
665       return ($dn);
666     }
668     /* Look for additional attributes */
669     foreach ($this->attributes as $attr){
670       if ($attr == $attribute || $this->$attr == ""){
671         continue;
672       }
674       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
675       $ldap->cat ($dn, array('dn'));
676       if (!$ldap->fetch()){
677         return ($dn);
678       }
679     }
681     /* None found */
682     return ("none");
683   }
686   function rebind($ldap, $referral)
687   {
688     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
689     if (ldap_bind($ldap, $credentials['ADMIN'], $this->config->get_credentials($credentials['PASSWORD']))) {
690       $this->error = "Success";
691       $this->hascon=true;
692       $this->reconnect= true;
693       return (0);
694     } else {
695       $this->error = "Could not bind to " . $credentials['ADMIN'];
696       return NULL;
697     }
698   }
701   /* Recursively copy ldap object */
702   function _copy($src_dn,$dst_dn)
703   {
704     $ldap=$this->config->get_ldap_link();
705     $ldap->cat($src_dn);
706     $attrs= $ldap->fetch();
708     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
709     $ds= ldap_connect($this->config->current['SERVER']);
710     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
711     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
712       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
713     }
715     $pwd = $this->config->get_credentials($this->config->current['ADMINPASSWORD']);
716     $r=ldap_bind($ds,$this->config->current['ADMINDN'], $pwd);
717     $sr=ldap_read($ds, LDAP::fix($src_dn), "objectClass=*");
719     /* Fill data from LDAP */
720     $new= array();
721     if ($sr) {
722       $ei=ldap_first_entry($ds, $sr);
723       if ($ei) {
724         foreach($attrs as $attr => $val){
725           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
726             for ($i= 0; $i<$info['count']; $i++){
727               if ($info['count'] == 1){
728                 $new[$attr]= $info[$i];
729               } else {
730                 $new[$attr][]= $info[$i];
731               }
732             }
733           }
734         }
735       }
736     }
738     /* close conncetion */
739     ldap_unbind($ds);
741     /* Adapt naming attribute */
742     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
743     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
744     $new[$dst_name]= LDAP::fix($dst_val);
746     /* Check if this is a department.
747      * If it is a dep. && there is a , override in his ou 
748      *  change \2C to , again, else this entry can't be saved ...
749      */
750     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
751       $new['ou'] = str_replace("\\\\,",",",$new['ou']);
752     }
754     /* Save copy */
755     $ldap->connect();
756     $ldap->cd($this->config->current['BASE']);
757     
758     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
760     /* FAIvariable=.../..., cn=.. 
761         could not be saved, because the attribute FAIvariable was different to 
762         the dn FAIvariable=..., cn=... */
764     if(!is_array($new['objectClass'])) $new['objectClass'] = array($new['objectClass']);
766     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
767       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
768     }
769     $ldap->cd($dst_dn);
770     $ldap->add($new);
772     if (!$ldap->success()){
773       trigger_error("Trying to save $dst_dn failed.",
774           E_USER_WARNING);
775       return(FALSE);
776     }
777     return(TRUE);
778   }
781   /* This is a workaround function. */
782   function copy($src_dn, $dst_dn)
783   {
784     /* Rename dn in possible object groups */
785     $ldap= $this->config->get_ldap_link();
786     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::prepare4filter($src_dn).'))',
787         array('cn'));
788     while ($attrs= $ldap->fetch()){
789       $og= new ogroup($this->config, $ldap->getDN());
790       unset($og->member[$src_dn]);
791       $og->member[$dst_dn]= $dst_dn;
792       $og->save ();
793     }
795     $ldap->cat($dst_dn);
796     $attrs= $ldap->fetch();
797     if (count($attrs)){
798       trigger_error("Trying to overwrite ".LDAP::fix($dst_dn).", which already exists.",
799           E_USER_WARNING);
800       return (FALSE);
801     }
803     $ldap->cat($src_dn);
804     $attrs= $ldap->fetch();
805     if (!count($attrs)){
806       trigger_error("Trying to move ".LDAP::fix($src_dn).", which does not seem to exist.",
807           E_USER_WARNING);
808       return (FALSE);
809     }
811     $ldap->cd($src_dn);
812     $ldap->search("objectClass=*",array("dn"));
813     while($attrs = $ldap->fetch()){
814       $src = $attrs['dn'];
815       $dst = preg_replace("/".preg_quote($src_dn, '/')."$/",$dst_dn,$attrs['dn']);
816       $this->_copy($src,$dst);
817     }
818     return (TRUE);
819   }
823   /*! \brief  Rename/Move a given src_dn to the given dest_dn
824    *
825    * Move a given ldap object indentified by $src_dn to the
826    * given destination $dst_dn
827    *
828    * - Ensure that all references are updated (ogroups)
829    * - Update ACLs   
830    * - Update accessTo
831    *
832    * \param  string  'src_dn' the source DN.
833    * \param  string  'dst_dn' the destination DN.
834    * \return boolean TRUE on success else FALSE.
835    */
836   function rename($src_dn, $dst_dn)
837   {
838     $start = microtime(1);
840     /* Try to move the source entry to the destination position */
841     $ldap = $this->config->get_ldap_link();
842     $ldap->cd($this->config->current['BASE']);
843     $ldap->create_missing_trees(preg_replace("/^[^,]+,/","",$dst_dn));
844     if (!$ldap->rename_dn($src_dn,$dst_dn)){
845       new log("debug","LDAP protocol v3 implementation error, ldap_rename failed, falling back to manual copy.","FROM: $src_dn  -- TO: $dst_dn",array(),$ldap->get_error());
846       @DEBUG(DEBUG_LDAP,__LINE__,__FUNCTION__,__FILE__,"Rename failed FROM: $src_dn  -- TO:  $dst_dn", 
847           "Ldap Protocol v3 implementation error, falling back to maunal method.");
848       return(FALSE);
849     }
851     /* Get list of users,groups and roles within this tree,
852         maybe we have to update ACL references.
853      */
854     $leaf_objs = get_list("(|(objectClass=posixGroup)(objectClass=gosaAccount)(objectClass=gosaRole))",array("all"),$dst_dn,
855           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
856     foreach($leaf_objs as $obj){
857       $new_dn = $obj['dn'];
858       $old_dn = preg_replace("/".preg_quote(LDAP::convert($dst_dn), '/')."$/i",$src_dn,LDAP::convert($new_dn));
859       $this->update_acls($old_dn,$new_dn); 
860     }
862     // Migrate objectgroups if needed
863     $ogroups = get_sub_list("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter(LDAP::fix($src_dn))."))",
864       "ogroups", array(get_ou("ogroupRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
866     // Walk through all objectGroups
867     foreach($ogroups as $ogroup){
868       // Migrate old to new dn
869       $o_ogroup= new ogroup($this->config,$ogroup['dn']);
870       if (isset($o_ogroup->member[$src_dn])) {
871         unset($o_ogroup->member[$src_dn]);
872       }
873       $o_ogroup->member[$dst_dn]= $dst_dn;
874       
875       // Save object group
876       $o_ogroup->save();
877     }
879     // Migrate rfc groups if needed
880     $groups = get_sub_list("(&(objectClass=posixGroup)(member=".LDAP::prepare4filter(LDAP::fix($src_dn))."))","groups", array(get_ou("groupRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
882     // Walk through all POSIX groups
883     foreach($groups as $group){
885       // Migrate old to new dn
886       $o_group= new group($this->config,$group['dn']);
887       $o_group->save();
888     }
890     /* Update roles to use the new entry dn */
891     $roles = get_sub_list("(&(objectClass=organizationalRole)(roleOccupant=".LDAP::prepare4filter(LDAP::fix($src_dn))."))","roles", array(get_ou("roleRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
893     // Walk through all roles
894     foreach($roles as $role){
895       $role = new roleGeneric($this->config,$role['dn']);
896       $key= array_search($src_dn, $role->roleOccupant);      
897       if($key !== FALSE){
898         $role->roleOccupant[$key] = $dst_dn;
899         $role->save();
900       }
901     }
903     // Update 'manager' attributes from gosaDepartment and inetOrgPerson 
904     $filter = "(&(objectClass=inetOrgPerson)(manager=".LDAP::prepare4filter(LDAP::fix($src_dn))."))";
905     $ocs = $ldap->get_objectclasses();
906     if(isset($ocs['gosaDepartment']['MAY']) && in_array('manager', $ocs['gosaDepartment']['MAY'])){
907       $filter = "(|".$filter."(&(objectClass=gosaDepartment)(manager=".LDAP::prepare4filter(LDAP::fix($src_dn)).")))";
908     }
909     $leaf_deps=  get_list($filter,array("all"),$this->config->current['BASE'], 
910         array("manager","dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
911     foreach($leaf_deps as $entry){
912       $update = array('manager' => $dst_dn);
913       $ldap->cd($entry['dn']);
914       $ldap->modify($update);
915       if(!$ldap->success()){
916         trigger_error(sprintf("Failed to update manager for %s: %s", bold($entry['dn']), $ldap->get_error()));
917       }
918     }
919  
920     /* Check if there are gosa departments moved. 
921        If there were deps moved, the force reload of config->deps.
922      */
923     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
924           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
925   
926     if(count($leaf_deps)){
927       $this->config->get_departments();
928       $this->config->make_idepartments();
929       session::global_set("config",$this->config);
930       $ui =get_userinfo();
931       $ui->reset_acl_cache();
932     }
934     return(TRUE); 
935   }
938  
939   function move($src_dn, $dst_dn)
940   {
941     /* Do not copy if only upper- lowercase has changed */
942     if(strtolower($src_dn) == strtolower($dst_dn)){
943       return(TRUE);
944     }
946     
947     /* Try to move the entry instead of copy & delete
948      */
949     if(TRUE){
951       /* Try to move with ldap routines, if this was not successfull
952           fall back to the old style copy & remove method 
953        */
954       if($this->rename($src_dn, $dst_dn)){
955         return(TRUE);
956       }else{
957         // See code below.
958       }
959     }
961     /* Copy source to destination */
962     if (!$this->copy($src_dn, $dst_dn)){
963       return (FALSE);
964     }
966     /* Delete source */
967     $ldap= $this->config->get_ldap_link();
968     $ldap->rmdir_recursive($src_dn);
969     if (!$ldap->success()){
970       trigger_error("Trying to delete $src_dn failed.",
971           E_USER_WARNING);
972       return (FALSE);
973     }
975     return (TRUE);
976   }
979   /* \brief Move/Rename complete trees */
980   function recursive_move($src_dn, $dst_dn)
981   {
982     /* Check if the destination entry exists */
983     $ldap= $this->config->get_ldap_link();
985     /* Check if destination exists - abort */
986     $ldap->cat($dst_dn, array('dn'));
987     if ($ldap->fetch()){
988       trigger_error("recursive_move $dst_dn already exists.",
989           E_USER_WARNING);
990       return (FALSE);
991     }
993     $this->copy($src_dn, $dst_dn);
995     /* Remove src_dn */
996     $ldap->cd($src_dn);
997     $ldap->recursive_remove($src_dn);
998     return (TRUE);
999   }
1002   function saveCopyDialog(){
1003   }
1006   function getCopyDialog(){
1007     return(array("string"=>"","status"=>""));
1008   }
1011   /*! \brief Prepare for Copy & Paste */
1012   function PrepareForCopyPaste($source)
1013   {
1014     $todo = $this->attributes;
1015     if(isset($this->CopyPasteVars)){
1016       $todo = array_merge($todo,$this->CopyPasteVars);
1017     }
1019     if(count($this->objectclasses)){
1020       $this->is_account = TRUE;
1021       foreach($this->objectclasses as $class){
1022         if(!in_array($class,$source['objectClass'])){
1023           $this->is_account = FALSE;
1024         }
1025       }
1026     }
1028     foreach($todo as $var){
1029       if (isset($source[$var])){
1030         if(isset($source[$var]['count'])){
1031           if($source[$var]['count'] > 1){
1032             $tmp= $source[$var];
1033             unset($tmp['count']);
1034             $this->$var = $tmp;
1035           }else{
1036             $this->$var = $source[$var][0];
1037           }
1038         }else{
1039           $this->$var= $source[$var];
1040         }
1041       }
1042     }
1043   }
1045   /*! \brief Get gosaUnitTag for the given DN
1046        If this is called from departmentGeneric, we have to skip this
1047         tagging procedure. 
1048     */
1049   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1050   {
1051     /* Skip tagging? */
1052     if($this->skipTagging){
1053       return;
1054     }
1056     /* No dn? Self-operation... */
1057     if ($dn == ""){
1058       $dn= $this->dn;
1060       /* No tag? Find it yourself... */
1061       if ($tag == ""){
1062         $len= strlen($dn);
1064         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1065         $relevant= array();
1066         foreach ($this->config->adepartments as $key => $ntag){
1068           /* This one is bigger than our dn, its not relevant... */
1069           if ($len < strlen($key)){
1070             continue;
1071           }
1073           /* This one matches with the latter part. Break and don't fix this entry */
1074           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
1075             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1076             $relevant[strlen($key)]= $ntag;
1077             continue;
1078           }
1080         }
1082         /* If we've some relevant tags to set, just get the longest one */
1083         if (count($relevant)){
1084           ksort($relevant);
1085           $tmp= array_keys($relevant);
1086           $idx= end($tmp);
1087           $tag= $relevant[$idx];
1088           $this->gosaUnitTag= $tag;
1089         }
1090       }
1091     }
1093   /*! \brief Add unit tag */ 
1094     /* Remove tags that may already be here... */
1095     remove_objectClass("gosaAdministrativeUnitTag", $at);
1096     if (isset($at['gosaUnitTag'])){
1097         unset($at['gosaUnitTag']);
1098     }
1100     /* Set tag? */
1101     if ($tag != ""){
1102       add_objectClass("gosaAdministrativeUnitTag", $at);
1103       $at['gosaUnitTag']= $tag;
1104     }
1106     /* Initially this object was tagged. 
1107        - But now, it is no longer inside a tagged department. 
1108        So force the remove of the tag.
1109        (objectClass was already removed obove)
1110      */
1111     if($tag == "" && $this->gosaUnitTag){
1112       $at['gosaUnitTag'] = array();
1113     }
1114   }
1117   /*! \brief Test for removability of the object
1118    *
1119    * Allows testing of conditions for removal of object. If removal should be aborted
1120    * the function needs to remove an error message.
1121    * */
1122   function allow_remove()
1123   {
1124     $reason= "";
1125     return $reason;
1126   }
1129   /*! \brief Test if snapshotting is enabled
1130    *
1131    * Test weither snapshotting is enabled or not. There will also be some errors posted,
1132    * if the configuration failed 
1133    * \return TRUE if snapshots are enabled, and FALSE if it is disabled
1134    */
1135   function snapshotEnabled()
1136   {
1137       return $this->config->snapshotEnabled();
1138   }
1141  /* \brief Return available snapshots for the given base */
1142  function Available_SnapsShots($dn,$raw = false)
1143  {
1144    if(!$this->snapshotEnabled()) return(array());
1146    /* Create an additional ldap object which
1147       points to our ldap snapshot server */
1148    $ldap= $this->config->get_ldap_link();
1149    $ldap->cd($this->config->current['BASE']);
1150    $cfg= &$this->config->current;
1152    /* check if there are special server configurations for snapshots */
1153    if($this->config->get_cfg_value("snapshotURI") == ""){
1154      $ldap_to      = $ldap;
1155    }else{
1156      $server         = $this->config->get_cfg_value("snapshotURI");
1157      $user           = $this->config->get_cfg_value("snapshotAdminDn");
1158      $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1159      $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1160      $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1161      $ldap_to -> cd($snapldapbase);
1162      if (!$ldap_to->success()){
1163        msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1164      }
1165    }
1167    /* Prepare bases and some other infos */
1168    $base           = $this->config->current['BASE'];
1169    $snap_base      = $this->config->get_cfg_value("snapshotBase");
1170    $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1171    $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1172    $tmp            = array(); 
1174    /* Fetch all objects with  gosaSnapshotDN=$dn */
1175    $ldap_to->cd($new_base);
1176    $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1177        array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1179    /* Put results into a list and add description if missing */
1180    while($entry = $ldap_to->fetch()){ 
1181      if(!isset($entry['description'][0])){
1182        $entry['description'][0]  = "";
1183      }
1184      $tmp[] = $entry; 
1185    }
1187    /* Return the raw array, or format the result */
1188    if($raw){
1189      return($tmp);
1190    }else{  
1191      $tmp2 = array();
1192      foreach($tmp as $entry){
1193        $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1194      }
1195    }
1196    return($tmp2);
1197  }
1199   /*! \brief Return plugin informations for acl handling */
1200   static function plInfo()
1201   {
1202     return array();
1203   }
1206   function set_acl_base($base)
1207   {
1208     @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,"<b>".$base."</b>","<b>ACL-Base:</b> ");
1209     $this->acl_base= $base;
1210   }
1213   function set_acl_category($category)
1214   {
1215     @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,"<b>".$category."</b>(/".get_class($this).")","<b>ACL-Category:</b> ");
1216     $this->acl_category= "$category/";
1217   }
1220   function acl_is_writeable($attribute,$skip_write = FALSE)
1221   {
1222     if($this->read_only) return(FALSE);
1223     $ui= get_userinfo();
1224     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1225   }
1228   function acl_is_readable($attribute)
1229   {
1230     $ui= get_userinfo();
1231     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1232   }
1235   function acl_is_createable($base ="")
1236   {
1237     if($this->read_only) return(FALSE);
1238     $ui= get_userinfo();
1239     if($base == "") $base = $this->acl_base;
1240     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1241   }
1244   function acl_is_removeable($base ="")
1245   {
1246     if($this->read_only) return(FALSE);
1247     $ui= get_userinfo();
1248     if($base == "") $base = $this->acl_base;
1249     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1250   }
1253   function acl_is_moveable($base = "")
1254   {
1255     if($this->read_only) return(FALSE);
1256     $ui= get_userinfo();
1257     if($base == "") $base = $this->acl_base;
1258     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1259   }
1262   function acl_have_any_permissions()
1263   {
1264   }
1267   function getacl($attribute,$skip_write= FALSE)
1268   {
1269     $ui= get_userinfo();
1270     $skip_write |= $this->read_only;
1271     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1272   }
1275   /*! \brief Returns a list of all available departments for this object.
1276    * 
1277    * If this object is new, all departments we are allowed to create a new user in
1278    * are returned. If this is an existing object, return all deps. 
1279    * We are allowed to move tis object too.
1280    * \return array [dn] => "..name"  // All deps. we are allowed to act on.
1281   */
1282   function get_allowed_bases()
1283   {
1284     $ui = get_userinfo();
1285     $deps = array();
1287     /* Is this a new object ? Or just an edited existing object */
1288     if(!$this->initially_was_account && $this->is_account){
1289       $new = true;
1290     }else{
1291       $new = false;
1292     }
1294     foreach($this->config->idepartments as $dn => $name){
1295       if($new && $this->acl_is_createable($dn)){
1296         $deps[$dn] = $name;
1297       }elseif(!$new && $this->acl_is_moveable($dn)){
1298         $deps[$dn] = $name;
1299       }
1300     }
1302     /* Add current base */      
1303     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1304       $deps[$this->base] = $this->config->idepartments[$this->base];
1305     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1307     }else{
1308       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1309     }
1310     return($deps);
1311   }
1314   /* This function updates ACL settings if $old_dn was used.
1315    *  \param string 'old_dn' specifies the actually used dn
1316    *  \param string 'new_dn' specifies the destiantion dn
1317    */
1318   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1319   {
1320     /* Check if old_dn is empty. This should never happen */
1321     if(empty($old_dn) || empty($new_dn)){
1322       trigger_error("Failed to check acl dependencies, wrong dn given.");
1323       return;
1324     }
1326     /* Update userinfo if necessary */
1327     $ui = session::global_get('ui');
1328     if($ui->dn == $old_dn){
1329       $ui->dn = $new_dn;
1330       session::global_set('ui',$ui);
1331       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1332     }
1334     /* Object was moved, ensure that all acls will be moved too */
1335     if($new_dn != $old_dn && $old_dn != "new"){
1337       /* get_ldap configuration */
1338       $update = array();
1339       $ldap = $this->config->get_ldap_link();
1340       $ldap->cd ($this->config->current['BASE']);
1341       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1342       while($attrs = $ldap->fetch()){
1343         $acls = array();
1344         $found = false;
1345         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1346           $acl_parts = explode(":",$attrs['gosaAclEntry'][$i]);
1348           /* Roles uses antoher data storage order, members are stored int the third part, 
1349              while the members in direct ACL assignments are stored in the second part.
1350            */
1351           $id = ($acl_parts[1] == "role") ? 3 : 2;
1353           /* Update member entries to use $new_dn instead of old_dn
1354            */
1355           $members = explode(",",$acl_parts[$id]);
1356           foreach($members as $key => $member){
1357             $member = base64_decode($member);
1358             if($member == $old_dn){
1359               $members[$key] = base64_encode($new_dn);
1360               $found = TRUE;
1361             }
1362           } 
1364           /* Check if the selected role has to updated
1365            */
1366           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1367             $acl_parts[2] = base64_encode($new_dn);
1368             $found = TRUE;
1369           }
1371           /* Build new acl string */ 
1372           $acl_parts[$id] = implode($members,",");
1373           $acls[] = implode($acl_parts,":");
1374         }
1376         /* Acls for this object must be adjusted */
1377         if($found){
1379           $debug_info= sprintf(_("Changing ACL DN from %s to %s"), bold($old_dn), bold($new_dn));
1380           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1382           $update[$attrs['dn']] =array();
1383           foreach($acls as $acl){
1384             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1385           }
1386         }
1387       }
1389       /* Write updated acls */
1390       foreach($update as $dn => $attrs){
1391         $ldap->cd($dn);
1392         $ldap->modify($attrs);
1393       }
1394     }
1395   }
1397   
1399   /*! \brief Enable the Serial ID check
1400    *
1401    * This function enables the entry Serial ID check.  If an entry was edited while
1402    * we have edited the entry too, an error message will be shown. 
1403    * To configure this check correctly read the FAQ.
1404    */    
1405   function enable_CSN_check()
1406   {
1407     $this->CSN_check_active =TRUE;
1408     $this->entryCSN = getEntryCSN($this->dn);
1409   }
1412   /*! \brief  Prepares the plugin to be used for multiple edit
1413    *          Update plugin attributes with given array of attribtues.
1414    *  \param  array   Array with attributes that must be updated.
1415    */
1416   function init_multiple_support($attrs,$all)
1417   {
1418     $ldap= $this->config->get_ldap_link();
1419     $this->multi_attrs    = $attrs;
1420     $this->multi_attrs_all= $all;
1422     /* Copy needed attributes */
1423     foreach ($this->attributes as $val){
1424       $found= array_key_ics($val, $this->multi_attrs);
1425  
1426       if ($found != ""){
1427         if(isset($this->multi_attrs["$val"][0])){
1428           $this->$val= $this->multi_attrs["$val"][0];
1429         }
1430       }
1431     }
1432   }
1434  
1435   /*! \brief  Enables multiple support for this plugin
1436    */
1437   function enable_multiple_support()
1438   {
1439     $this->ignore_account = TRUE;
1440     $this->multiple_support_active = TRUE;
1441   }
1444   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1445       \return array Cotaining all modified values. 
1446    */
1447   function get_multi_edit_values()
1448   {
1449     $ret = array();
1450     foreach($this->attributes as $attr){
1451       if(in_array($attr,$this->multi_boxes)){
1452         $ret[$attr] = $this->$attr;
1453       }
1454     }
1455     return($ret);
1456   }
1458   
1459   /*! \brief  Update class variables with values collected by multiple edit.
1460    */
1461   function set_multi_edit_values($attrs)
1462   {
1463     foreach($attrs as $name => $value){
1464       $this->$name = $value;
1465     }
1466   }
1469   /*! \brief Generates the html output for this node for multi edit*/
1470   function multiple_execute()
1471   {
1472     /* This one is empty currently. Fabian - please fill in the docu code */
1473     session::global_set('current_class_for_help',get_class($this));
1475     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1476     session::set('LOCK_VARS_TO_USE',array());
1477     session::set('LOCK_VARS_USED_GET',array());
1478     session::set('LOCK_VARS_USED_POST',array());
1479     session::set('LOCK_VARS_USED_REQUEST',array());
1480     
1481     return("Multiple edit is currently not implemented for this plugin.");
1482   }
1485   /*! \brief Save HTML posted data to object for multiple edit
1486    */
1487   function multiple_save_object()
1488   {
1489     if(empty($this->entryCSN) && $this->CSN_check_active){
1490       $this->entryCSN = getEntryCSN($this->dn);
1491     }
1493     /* Save values to object */
1494     $this->multi_boxes = array();
1495     foreach ($this->attributes as $val){
1496   
1497       /* Get selected checkboxes from multiple edit */
1498       if(isset($_POST["use_".$val])){
1499         $this->multi_boxes[] = $val;
1500       }
1502       if (isset ($_POST["$val"]) && $this->acl_is_writeable($val)){
1504         /* Check for modifications */
1505         if (get_magic_quotes_gpc()) {
1506           $data= stripcslashes($_POST["$val"]);
1507         } else {
1508           $data= $this->$val = $_POST["$val"];
1509         }
1510         if ($this->$val != $data){
1511           $this->is_modified= TRUE;
1512         }
1513     
1514         /* IE post fix */
1515         if(isset($data[0]) && $data[0] == chr(194)) {
1516           $data = "";  
1517         }
1518         $this->$val= $data;
1519       }
1520     }
1521   }
1524   /*! \brief Returns all attributes of this plugin, 
1525                to be able to detect multiple used attributes 
1526                in multi_plugg::detect_multiple_used_attributes().
1527       @return array Attributes required for intialization of multi_plug
1528    */
1529   public function get_multi_init_values()
1530   {
1531     $attrs = $this->attrs;
1532     return($attrs);
1533   }
1536   /*! \brief  Check given values in multiple edit
1537       \return array Error messages
1538    */
1539   function multiple_check()
1540   {
1541     $message = plugin::check();
1542     return($message);
1543   }
1546   /*! \brief  Returns the snapshot header part for "Actions" menu in management dialogs 
1547       \param  $layer_menu  
1548    */   
1549   function get_snapshot_header($base,$category)
1550   {
1551     $str = "";
1552     $ui = get_userinfo();
1553     if($this->snapshotEnabled() && $ui->allow_snapshot_restore($base,$category)){
1555       $ok = false;
1556       foreach($this->get_used_snapshot_bases() as $base){
1557         $ok |= count($this->getAllDeletedSnapshots($base)) >= 1 ;
1558       }
1560       if($ok){
1561         $str = "..|<img class='center' src='images/lists/restore.png' ".
1562           "alt='"._("Restore")."'>&nbsp;"._("Restore").                       "|RestoreDeletedSnapShot|\n";
1563       }else{
1564         $str = "..|<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;"._("Restore")."||\n";
1565       }
1566     }
1567     return($str);
1568   }
1571   function get_snapshot_action($base,$category)
1572   {
1573     $str= ""; 
1574     $ui = get_userinfo();
1575     if($this->snapshotEnabled()){
1576       if ($ui->allow_snapshot_restore($base,$category)){
1578         if(count($this->Available_SnapsShots($base))){
1579           $str.= "<input class='center' type='image' src='images/lists/restore.png'
1580             alt='"._("Restore snapshot")."' name='RestoreSnapShotDialog_".base64_encode($base)."' title='"._("Restore snapshot")."'>&nbsp;";
1581         } else {
1582           $str = "<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;";
1583         }
1584       }
1585       if($ui->allow_snapshot_create($base,$category)){
1586         $str.= "<input class='center' type='image' src='images/snapshot.png'
1587           alt='"._("Create snapshot")."' name='CreateSnapShotDialog_".base64_encode($base)."' 
1588           title='"._("Create new snapshot for this object")."'>&nbsp;";
1589       }else{
1590         $str = "<img class='center' src='images/empty.png' alt=' '>&nbsp;";
1591       }
1592     }
1594     return($str);
1595   }
1598   function get_copypaste_action($base,$category,$class,$copy = TRUE, $cut = TRUE)
1599   {
1600     $ui = get_userinfo();
1601     $action = "";
1602     if($this->CopyPasteHandler){
1603       if($cut){
1604         if($ui->is_cutable($base,$category,$class)){
1605           $action .= "<input class='center' type='image'
1606             src='images/lists/cut.png' alt='"._("Cut")."' name='cut_%KEY%' title='"._("Cut this entry")."'>&nbsp;";
1607         }else{
1608           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
1609         }
1610       }
1611       if($copy){
1612         if($ui->is_copyable($base,$category,$class)){
1613           $action.= "<input class='center' type='image'
1614             src='images/lists/copy.png' alt='"._("Copy")."' name='copy_%KEY%' title='"._("Copy this entry")."'>&nbsp;";
1615         }else{
1616           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
1617         }
1618       }
1619     }
1621     return($action); 
1622   }
1625   function get_copypaste_header($base,$category,$copy = TRUE, $cut = TRUE)
1626   {
1627     $s = "";
1628     $ui =get_userinfo();
1630     if(!is_array($category)){
1631       $category = array($category);
1632     }
1634     /* Check permissions for each category, if there is at least one category which 
1635         support read or paste permissions for the given base, then display the specific actions.
1636      */
1637     $readable = $pasteable = false;
1638     foreach($category as $cat){
1639       $readable= $readable || preg_match('/r/', $ui->get_category_permissions($base, $cat));
1640       $pasteable= $pasteable || $ui->is_pasteable($base, $cat) == 1;
1641     }
1642   
1643     if(($cut || $copy) && isset($this->CopyPasteHandler) && is_object($this->CopyPasteHandler)){
1644       if($readable){
1645         $s.= "..|---|\n";
1646         if($copy){
1647           $s.= "..|<img src='images/lists/copy.png' alt='' border='0' class='center'>".
1648             "&nbsp;"._("Copy")."|"."multiple_copy_systems|\n";
1649         }
1650         if($cut){
1651           $s.= "..|<img src='images/lists/cut.png' alt='' border='0' class='center'>".
1652             "&nbsp;"._("Cut")."|"."multiple_cut_systems|\n";
1653         }
1654       }
1656       if($pasteable){
1657         if($this->CopyPasteHandler->entries_queued()){
1658           $img = "<img border='0' class='center' src='images/lists/paste.png' alt=''>";
1659           $s.="..|".$img."&nbsp;"._("Paste")."|editPaste|\n";
1660         }else{
1661           $img = "<img border='0' class='center' src='images/lists/paste-grey.png' alt=''>";
1662           $s.="..|".$img."&nbsp;"._("Paste")."\n";
1663         }
1664       }
1665     }
1666     return($s);
1667   }
1670   function get_used_snapshot_bases()
1671   {
1672      return(array());
1673   }
1675   function is_modal_dialog()
1676   {
1677     return(isset($this->dialog) && $this->dialog);
1678   }
1681   /*! \brief    Forward command execution requests
1682    *             to the hook execution method. 
1683    */
1684   function handle_post_events($mode, $addAttrs= array())
1685   {
1686     if(!in_array($mode, array('add','remove','modify'))){
1687       trigger_error(sprintf("Invalid post event type given %s! Valid types are [add,modify,remove].", bold($mode)));
1688       return;
1689     }
1690     switch ($mode){
1691       case "add":
1692         plugin::callHook($this,"POSTCREATE", $addAttrs);
1693       break;
1695       case "modify":
1696         plugin::callHook($this,"POSTMODIFY", $addAttrs);
1697       break;
1699       case "remove":
1700         plugin::callHook($this,"POSTREMOVE", $addAttrs);
1701       break;
1702     }
1703   }
1706   /*! \brief    Calls external hooks which are defined for this plugin (gosa.conf)
1707    *            Replaces placeholder by class values of this plugin instance.
1708    *  @param    Allows to a add special replacements.
1709    */
1710   static function callHook($plugin, $cmd, $addAttrs= array())
1711   {
1712     global $config;
1713     $command= $config->search(get_class($plugin), $cmd,array('menu','tabs'));
1714     if ($command != ""){
1716       // Walk trough attributes list and add the plugins attributes. 
1717       foreach ($plugin->attributes as $attr){
1718         if (!is_array($plugin->$attr)){
1719           $addAttrs[$attr] = $plugin->$attr;
1720         }
1721       }
1722       $ui = get_userinfo();
1723       $addAttrs['callerDN']=$ui->dn;
1724       $addAttrs['dn']=$plugin->dn;
1726       // Sort attributes by length, ensures correct replacement
1727       $tmp = array();
1728       foreach($addAttrs as $name => $value){
1729         $tmp[$name] =  strlen($name);
1730       }
1731       arsort($tmp);
1733       // Now replace the placeholder 
1734       foreach ($tmp as $name => $len){
1735         $value = $addAttrs[$name];
1736         $command= str_replace("%$name", "$value", $command);
1737       }
1739       // If there are still some %.. in our command, try to fill these with some other class vars 
1740       if(preg_match("/%/",$command)){
1741         $attrs = get_object_vars($plugin);
1742         foreach($attrs as $name => $value){
1743           if(is_array($value)){
1744             $s = "";
1745             foreach($value as $val){
1746               if(is_string($val) || is_int($val) || is_float($val) || is_bool($val)){
1747                 $s .= '"'.$val.'",'; 
1748               }
1749             }
1750             $value = '['.trim($s,',').']';
1751           }
1752           if(!is_string($value) && !is_int($value) && !is_float($value) && !is_bool($value)){
1753             continue;
1754           }
1755           $command= preg_replace("/%$name/", $value, $command);
1756         }
1757       }
1759       if (check_command($command)){
1760         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,$command,"Execute");
1761         exec($command,$arr);
1762         if(is_array($arr)){
1763           $str = implode("\n",$arr);
1764           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Result: ".$str);
1765         }
1766       } else {
1767         $message= msgPool::cmdnotfound("POSTCREATE", get_class($plugin));
1768         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
1769       }
1770     }
1771   }
1774 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1775 ?>