Code

Fixed dialog ignore account state
[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 object has changed since opened in GOsa. All changes that may be done by others get lost if you save this entry!");
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 #      msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $src_dn, "", get_class()));
846       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());
847       @DEBUG(DEBUG_LDAP,__LINE__,__FUNCTION__,__FILE__,"Rename failed FROM: $src_dn  -- TO:  $dst_dn", 
848           "Ldap Protocol v3 implementation error, falling back to maunal method.");
849       return(FALSE);
850     }
852     /* Get list of users,groups and roles within this tree,
853         maybe we have to update ACL references.
854      */
855     $leaf_objs = get_list("(|(objectClass=posixGroup)(objectClass=gosaAccount)(objectClass=gosaRole))",array("all"),$dst_dn,
856           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
857     foreach($leaf_objs as $obj){
858       $new_dn = $obj['dn'];
859       $old_dn = preg_replace("/".preg_quote(LDAP::convert($dst_dn), '/')."$/i",$src_dn,LDAP::convert($new_dn));
860       $this->update_acls($old_dn,$new_dn); 
861     }
863     // Migrate objectgroups if needed
864     $ogroups = get_sub_list("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter(LDAP::fix($src_dn))."))",
865       "ogroups", array(get_ou("ogroupRDN")),$this->config->current['BASE'],array("dn"), GL_SUBSEARCH | GL_NO_ACL_CHECK);
867     // Walk through all objectGroups
868     foreach($ogroups as $ogroup){
869       // Migrate old to new dn
870       $o_ogroup= new ogroup($this->config,$ogroup['dn']);
871       if (isset($o_ogroup->member[$src_dn])) {
872         unset($o_ogroup->member[$src_dn]);
873       }
874       $o_ogroup->member[$dst_dn]= $dst_dn;
875       
876       // Save object group
877       $o_ogroup->save();
878     }
880     // Migrate rfc groups if needed
881     $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);
883     // Walk through all POSIX groups
884     foreach($groups as $group){
886       // Migrate old to new dn
887       $o_group= new group($this->config,$group['dn']);
888       $o_group->save();
889     }
891     /* Update roles to use the new entry dn */
892     $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);
894     // Walk through all roles
895     foreach($roles as $role){
896       $role = new roleGeneric($this->config,$role['dn']);
897       $key= array_search($src_dn, $role->roleOccupant);      
898       if($key !== FALSE){
899         $role->roleOccupant[$key] = $dst_dn;
900         $role->save();
901       }
902     }
904     // Update 'manager' attributes from gosaDepartment and inetOrgPerson 
905     $filter = "(&(objectClass=inetOrgPerson)(manager=".LDAP::prepare4filter(LDAP::fix($src_dn))."))";
906     $ocs = $ldap->get_objectclasses();
907     if(isset($ocs['gosaDepartment']['MAY']) && in_array('manager', $ocs['gosaDepartment']['MAY'])){
908       $filter = "(|".$filter."(&(objectClass=gosaDepartment)(manager=".LDAP::prepare4filter(LDAP::fix($src_dn)).")))";
909     }
910     $leaf_deps=  get_list($filter,array("all"),$this->config->current['BASE'], 
911         array("manager","dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
912     foreach($leaf_deps as $entry){
913       $update = array('manager' => $dst_dn);
914       $ldap->cd($entry['dn']);
915       $ldap->modify($update);
916       if(!$ldap->success()){
917         trigger_error(sprintf("Failed to update manager for '%s', error was '%s'", $entry['dn'], $ldap->get_error()));
918       }
919     }
920  
921     /* Check if there are gosa departments moved. 
922        If there were deps moved, the force reload of config->deps.
923      */
924     $leaf_deps=  get_list("(objectClass=gosaDepartment)",array("all"),$dst_dn,
925           array("dn","objectClass"),GL_SUBSEARCH | GL_NO_ACL_CHECK);
926   
927     if(count($leaf_deps)){
928       $this->config->get_departments();
929       $this->config->make_idepartments();
930       session::global_set("config",$this->config);
931       $ui =get_userinfo();
932       $ui->reset_acl_cache();
933     }
935     return(TRUE); 
936   }
939  
940   function move($src_dn, $dst_dn)
941   {
942     /* Do not copy if only upper- lowercase has changed */
943     if(strtolower($src_dn) == strtolower($dst_dn)){
944       return(TRUE);
945     }
947     
948     /* Try to move the entry instead of copy & delete
949      */
950     if(TRUE){
952       /* Try to move with ldap routines, if this was not successfull
953           fall back to the old style copy & remove method 
954        */
955       if($this->rename($src_dn, $dst_dn)){
956         return(TRUE);
957       }else{
958         // See code below.
959       }
960     }
962     /* Copy source to destination */
963     if (!$this->copy($src_dn, $dst_dn)){
964       return (FALSE);
965     }
967     /* Delete source */
968     $ldap= $this->config->get_ldap_link();
969     $ldap->rmdir_recursive($src_dn);
970     if (!$ldap->success()){
971       trigger_error("Trying to delete $src_dn failed.",
972           E_USER_WARNING);
973       return (FALSE);
974     }
976     return (TRUE);
977   }
980   /* \brief Move/Rename complete trees */
981   function recursive_move($src_dn, $dst_dn)
982   {
983     /* Check if the destination entry exists */
984     $ldap= $this->config->get_ldap_link();
986     /* Check if destination exists - abort */
987     $ldap->cat($dst_dn, array('dn'));
988     if ($ldap->fetch()){
989       trigger_error("recursive_move $dst_dn already exists.",
990           E_USER_WARNING);
991       return (FALSE);
992     }
994     $this->copy($src_dn, $dst_dn);
996     /* Remove src_dn */
997     $ldap->cd($src_dn);
998     $ldap->recursive_remove($src_dn);
999     return (TRUE);
1000   }
1003   function saveCopyDialog(){
1004   }
1007   function getCopyDialog(){
1008     return(array("string"=>"","status"=>""));
1009   }
1012   /*! \brief Prepare for Copy & Paste */
1013   function PrepareForCopyPaste($source)
1014   {
1015     $todo = $this->attributes;
1016     if(isset($this->CopyPasteVars)){
1017       $todo = array_merge($todo,$this->CopyPasteVars);
1018     }
1020     if(count($this->objectclasses)){
1021       $this->is_account = TRUE;
1022       foreach($this->objectclasses as $class){
1023         if(!in_array($class,$source['objectClass'])){
1024           $this->is_account = FALSE;
1025         }
1026       }
1027     }
1029     foreach($todo as $var){
1030       if (isset($source[$var])){
1031         if(isset($source[$var]['count'])){
1032           if($source[$var]['count'] > 1){
1033             $tmp= $source[$var];
1034             unset($tmp['count']);
1035             $this->$var = $tmp;
1036           }else{
1037             $this->$var = $source[$var][0];
1038           }
1039         }else{
1040           $this->$var= $source[$var];
1041         }
1042       }
1043     }
1044   }
1046   /*! \brief Get gosaUnitTag for the given DN
1047        If this is called from departmentGeneric, we have to skip this
1048         tagging procedure. 
1049     */
1050   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1051   {
1052     /* Skip tagging? */
1053     if($this->skipTagging){
1054       return;
1055     }
1057     /* No dn? Self-operation... */
1058     if ($dn == ""){
1059       $dn= $this->dn;
1061       /* No tag? Find it yourself... */
1062       if ($tag == ""){
1063         $len= strlen($dn);
1065         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1066         $relevant= array();
1067         foreach ($this->config->adepartments as $key => $ntag){
1069           /* This one is bigger than our dn, its not relevant... */
1070           if ($len < strlen($key)){
1071             continue;
1072           }
1074           /* This one matches with the latter part. Break and don't fix this entry */
1075           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
1076             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1077             $relevant[strlen($key)]= $ntag;
1078             continue;
1079           }
1081         }
1083         /* If we've some relevant tags to set, just get the longest one */
1084         if (count($relevant)){
1085           ksort($relevant);
1086           $tmp= array_keys($relevant);
1087           $idx= end($tmp);
1088           $tag= $relevant[$idx];
1089           $this->gosaUnitTag= $tag;
1090         }
1091       }
1092     }
1094   /*! \brief Add unit tag */ 
1095     /* Remove tags that may already be here... */
1096     remove_objectClass("gosaAdministrativeUnitTag", $at);
1097     if (isset($at['gosaUnitTag'])){
1098         unset($at['gosaUnitTag']);
1099     }
1101     /* Set tag? */
1102     if ($tag != ""){
1103       add_objectClass("gosaAdministrativeUnitTag", $at);
1104       $at['gosaUnitTag']= $tag;
1105     }
1107     /* Initially this object was tagged. 
1108        - But now, it is no longer inside a tagged department. 
1109        So force the remove of the tag.
1110        (objectClass was already removed obove)
1111      */
1112     if($tag == "" && $this->gosaUnitTag){
1113       $at['gosaUnitTag'] = array();
1114     }
1115   }
1118   /*! \brief Test for removability of the object
1119    *
1120    * Allows testing of conditions for removal of object. If removal should be aborted
1121    * the function needs to remove an error message.
1122    * */
1123   function allow_remove()
1124   {
1125     $reason= "";
1126     return $reason;
1127   }
1130   /*! \brief Create a snapshot of the current object */
1131   function create_snapshot($type= "snapshot", $description= array())
1132   {
1134     /* Check if snapshot functionality is enabled */
1135     if(!$this->snapshotEnabled()){
1136       return;
1137     }
1139     /* Get configuration from gosa.conf */
1140     $config = $this->config;
1142     /* Create lokal ldap connection */
1143     $ldap= $this->config->get_ldap_link();
1144     $ldap->cd($this->config->current['BASE']);
1146     /* check if there are special server configurations for snapshots */
1147     if($config->get_cfg_value("snapshotURI") == ""){
1149       /* Source and destination server are both the same, just copy source to dest obj */
1150       $ldap_to      = $ldap;
1151       $snapldapbase = $this->config->current['BASE'];
1153     }else{
1154       $server         = $config->get_cfg_value("snapshotURI");
1155       $user           = $config->get_cfg_value("snapshotAdminDn");
1156       $password       = $this->config->get_credentials($config->get_cfg_value("snapshotAdminPassword"));
1157       $snapldapbase   = $config->get_cfg_value("snapshotBase");
1159       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1160       $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       }
1166     }
1168     /* check if the dn exists */ 
1169     if ($ldap->dn_exists($this->dn)){
1171       /* Extract seconds & mysecs, they are used as entry index */
1172       list($usec, $sec)= explode(" ", microtime());
1174       /* Collect some infos */
1175       $base           = $this->config->current['BASE'];
1176       $snap_base      = $config->get_cfg_value("snapshotBase");
1177       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1178       $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1180       /* Create object */
1181 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1182       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1183       $newName          = str_replace(".", "", $sec."-".$usec);
1184       $target= array();
1185       $target['objectClass']            = array("top", "gosaSnapshotObject");
1186       $target['gosaSnapshotData']       = gzcompress($data, 6);
1187       $target['gosaSnapshotType']       = $type;
1188       $target['gosaSnapshotDN']         = $this->dn;
1189       $target['description']            = $description;
1190       $target['gosaSnapshotTimestamp']  = $newName;
1192       /* Insert the new snapshot 
1193          But we have to check first, if the given gosaSnapshotTimestamp
1194          is already used, in this case we should increment this value till there is 
1195          an unused value. */ 
1196       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1197       $ldap_to->cat($new_dn);
1198       while($ldap_to->count()){
1199         $ldap_to->cat($new_dn);
1200         $newName = str_replace(".", "", $sec."-".($usec++));
1201         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1202         $target['gosaSnapshotTimestamp']  = $newName;
1203       } 
1205       /* Inset this new snapshot */
1206       $ldap_to->cd($snapldapbase);
1207       $ldap_to->create_missing_trees($snapldapbase);
1208       $ldap_to->create_missing_trees($new_base);
1209       $ldap_to->cd($new_dn);
1210       $ldap_to->add($target);
1211       if (!$ldap_to->success()){
1212         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $new_dn, LDAP_ADD, get_class()));
1213       }
1215       if (!$ldap->success()){
1216         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $new_base, "", get_class()));
1217       }
1219     }
1220   }
1222   /*! \brief Remove a snapshot */
1223   function remove_snapshot($dn)
1224   {
1225     $ui       = get_userinfo();
1226     $old_dn   = $this->dn; 
1227     $this->dn = $dn;
1228     $ldap = $this->config->get_ldap_link();
1229     $ldap->cd($this->config->current['BASE']);
1230     $ldap->rmdir_recursive($this->dn);
1231     if(!$ldap->success()){
1232       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn));
1233     }
1234     $this->dn = $old_dn;
1235   }
1238   /*! \brief Test if snapshotting is enabled
1239    *
1240    * Test weither snapshotting is enabled or not. There will also be some errors posted,
1241    * if the configuration failed 
1242    * \return TRUE if snapshots are enabled, and FALSE if it is disabled
1243    */
1244   function snapshotEnabled()
1245   {
1246     return $this->config->snapshotEnabled();
1247   }
1250   /* \brief Return available snapshots for the given base */
1251   function Available_SnapsShots($dn,$raw = false)
1252   {
1253     if(!$this->snapshotEnabled()) return(array());
1255     /* Create an additional ldap object which
1256        points to our ldap snapshot server */
1257     $ldap= $this->config->get_ldap_link();
1258     $ldap->cd($this->config->current['BASE']);
1259     $cfg= &$this->config->current;
1261     /* check if there are special server configurations for snapshots */
1262     if($this->config->get_cfg_value("snapshotURI") == ""){
1263       $ldap_to      = $ldap;
1264     }else{
1265       $server         = $this->config->get_cfg_value("snapshotURI");
1266       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1267       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1268       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1269       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1270       $ldap_to -> cd($snapldapbase);
1271       if (!$ldap_to->success()){
1272         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1273       }
1274     }
1276     /* Prepare bases and some other infos */
1277     $base           = $this->config->current['BASE'];
1278     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1279     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1280     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1281     $tmp            = array(); 
1283     /* Fetch all objects with  gosaSnapshotDN=$dn */
1284     $ldap_to->cd($new_base);
1285     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1286         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1288     /* Put results into a list and add description if missing */
1289     while($entry = $ldap_to->fetch()){ 
1290       if(!isset($entry['description'][0])){
1291         $entry['description'][0]  = "";
1292       }
1293       $tmp[] = $entry; 
1294     }
1296     /* Return the raw array, or format the result */
1297     if($raw){
1298       return($tmp);
1299     }else{  
1300       $tmp2 = array();
1301       foreach($tmp as $entry){
1302         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1303       }
1304     }
1305     return($tmp2);
1306   }
1309   function getAllDeletedSnapshots($base_of_object,$raw = false)
1310   {
1311     if(!$this->snapshotEnabled()) return(array());
1313     /* Create an additional ldap object which
1314        points to our ldap snapshot server */
1315     $ldap= $this->config->get_ldap_link();
1316     $ldap->cd($this->config->current['BASE']);
1317     $cfg= &$this->config->current;
1319     /* check if there are special server configurations for snapshots */
1320     if($this->config->get_cfg_value("snapshotURI") == ""){
1321       $ldap_to      = $ldap;
1322     }else{
1323       $server         = $this->config->get_cfg_value("snapshotURI");
1324       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1325       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1326       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1327       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1328       $ldap_to -> cd($snapldapbase);
1329       if (!$ldap_to->success()){
1330         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1331       }
1332     }
1334     /* Prepare bases */ 
1335     $base           = $this->config->current['BASE'];
1336     $snap_base      = $this->config->get_cfg_value("snapshotBase");
1337     $new_base       = preg_replace("/".preg_quote($base, '/')."$/","",$base_of_object).$snap_base;
1339     /* Fetch all objects and check if they do not exist anymore */
1340     $ui = get_userinfo();
1341     $tmp = array();
1342     $ldap_to->cd($new_base);
1343     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1344     while($entry = $ldap_to->fetch()){
1346       $chk =  str_replace($new_base,"",$entry['dn']);
1347       if(preg_match("/,ou=/",$chk)) continue;
1349       if(!isset($entry['description'][0])){
1350         $entry['description'][0]  = "";
1351       }
1352       $tmp[] = $entry; 
1353     }
1355     /* Check if entry still exists */
1356     foreach($tmp as $key => $entry){
1357       $ldap->cat($entry['gosaSnapshotDN'][0]);
1358       if($ldap->count()){
1359         unset($tmp[$key]);
1360       }
1361     }
1363     /* Format result as requested */
1364     if($raw) {
1365       return($tmp);
1366     }else{
1367       $tmp2 = array();
1368       foreach($tmp as $key => $entry){
1369         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1370       }
1371     }
1372     return($tmp2);
1373   } 
1376   /* \brief Restore selected snapshot */
1377   function restore_snapshot($dn)
1378   {
1379     if(!$this->snapshotEnabled()) return(array());
1381     $ldap= $this->config->get_ldap_link();
1382     $ldap->cd($this->config->current['BASE']);
1383     $cfg= &$this->config->current;
1385     /* check if there are special server configurations for snapshots */
1386     if($this->config->get_cfg_value("snapshotURI") == ""){
1387       $ldap_to      = $ldap;
1388     }else{
1389       $server         = $this->config->get_cfg_value("snapshotURI");
1390       $user           = $this->config->get_cfg_value("snapshotAdminDn");
1391       $password       = $this->config->get_credentials($this->config->get_cfg_value("snapshotAdminPassword"));
1392       $snapldapbase   = $this->config->get_cfg_value("snapshotBase");
1393       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1394       $ldap_to -> cd($snapldapbase);
1395       if (!$ldap_to->success()){
1396         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1397       }
1398     }
1400     /* Get the snapshot */ 
1401     $ldap_to->cat($dn);
1402     $restoreObject = $ldap_to->fetch();
1404     /* Prepare import string */
1405     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1407     /* Import the given data */
1408     $err = "";
1409     $ldap->import_complete_ldif($data,$err,false,false);
1410     if (!$ldap->success()){
1411       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, "", get_class()));
1412     }
1413   }
1416   function showSnapshotDialog($base,$baseSuffixe,&$parent)
1417   {
1418     $once = true;
1419     $ui = get_userinfo();
1420     $this->parent = $parent;
1422     foreach($_POST as $name => $value){
1424       /* Create a new snapshot, display a dialog */
1425       if(preg_match("/^CreateSnapShotDialog_[^_]*_[xy]$/",$name) && $once){
1427                           $entry = base64_decode(preg_replace("/^CreateSnapShotDialog_([^_]*)_[xy]$/","\\1",$name));
1428         $once = false;
1429         $entry = preg_replace("/^CreateSnapShotDialog_/","",$entry);
1431         if(!empty($entry) && $ui->allow_snapshot_create($entry,$this->parent->acl_module)){
1432           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1433         }else{
1434           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to create a snapshot for %s."),$entry),ERROR_DIALOG);
1435         }
1436       }  
1437   
1438       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1439       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1440         $once = false;
1441         $entry = base64_decode(preg_replace("/^RestoreSnapShotDialog_([^_]*)_[xy]$/i","\\1",$name));
1442         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1443           $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1444           $this->snapDialog->display_restore_dialog = true;
1445         }else{
1446           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1447         }
1448       }
1450       /* Restore one of the already deleted objects */
1451       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1452           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1453         $once = false;
1455         if($ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1456           $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1457           $this->snapDialog->set_snapshot_bases($baseSuffixe);
1458           $this->snapDialog->display_restore_dialog      = true;
1459           $this->snapDialog->display_all_removed_objects  = true;
1460         }else{
1461           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$base),ERROR_DIALOG);
1462         }
1463       }
1465       /* Restore selected snapshot */
1466       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1467         $once = false;
1468         $entry = base64_decode(preg_replace("/^RestoreSnapShot_(.*)$/i","\\1",$name));
1470         if(!empty($entry) && $ui->allow_snapshot_restore($this->dn,$this->parent->acl_module)){
1471           $this->restore_snapshot($entry);
1472           $this->snapDialog = NULL;
1473         }else{
1474           msg_dialog::display(_("Permission"),sprintf(_("You are not allowed to restore a snapshot for %s."),$entry),ERROR_DIALOG);
1475         }
1476       }
1477     }
1479     /* Create a new snapshot requested, check
1480        the given attributes and create the snapshot*/
1481     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1482       $this->snapDialog->save_object();
1483       $msgs = $this->snapDialog->check();
1484       if(count($msgs)){
1485         foreach($msgs as $msg){
1486           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
1487         }
1488       }else{
1489         $this->dn =  $this->snapDialog->dn;
1490         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1491         $this->snapDialog = NULL;
1492       }
1493     }
1495     /* Restore is requested, restore the object with the posted dn .*/
1496     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1497     }
1499     if(isset($_POST['CancelSnapshot'])){
1500       $this->snapDialog = NULL;
1501     }
1503     if(is_object($this->snapDialog )){
1504       $this->snapDialog->save_object();
1505       return($this->snapDialog->execute());
1506     }
1507   }
1510   /*! \brief Return plugin informations for acl handling */
1511   static function plInfo()
1512   {
1513     return array();
1514   }
1517   function set_acl_base($base)
1518   {
1519     @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,"<b>".$base."</b>","<b>ACL-Base:</b> ");
1520     $this->acl_base= $base;
1521   }
1524   function set_acl_category($category)
1525   {
1526     @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,"<b>".$category."</b>(/".get_class($this).")","<b>ACL-Category:</b> ");
1527     $this->acl_category= "$category/";
1528   }
1531   function acl_is_writeable($attribute,$skip_write = FALSE)
1532   {
1533     if($this->read_only) return(FALSE);
1534     $ui= get_userinfo();
1535     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1536   }
1539   function acl_is_readable($attribute)
1540   {
1541     $ui= get_userinfo();
1542     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1543   }
1546   function acl_is_createable($base ="")
1547   {
1548     if($this->read_only) return(FALSE);
1549     $ui= get_userinfo();
1550     if($base == "") $base = $this->acl_base;
1551     return preg_match('/c/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1552   }
1555   function acl_is_removeable($base ="")
1556   {
1557     if($this->read_only) return(FALSE);
1558     $ui= get_userinfo();
1559     if($base == "") $base = $this->acl_base;
1560     return preg_match('/d/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1561   }
1564   function acl_is_moveable($base = "")
1565   {
1566     if($this->read_only) return(FALSE);
1567     $ui= get_userinfo();
1568     if($base == "") $base = $this->acl_base;
1569     return preg_match('/m/', $ui->get_permissions($base, $this->acl_category.get_class($this), '0'));
1570   }
1573   function acl_have_any_permissions()
1574   {
1575   }
1578   function getacl($attribute,$skip_write= FALSE)
1579   {
1580     $ui= get_userinfo();
1581     $skip_write |= $this->read_only;
1582     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1583   }
1586   /*! \brief Returns a list of all available departments for this object.
1587    * 
1588    * If this object is new, all departments we are allowed to create a new user in
1589    * are returned. If this is an existing object, return all deps. 
1590    * We are allowed to move tis object too.
1591    * \return array [dn] => "..name"  // All deps. we are allowed to act on.
1592   */
1593   function get_allowed_bases()
1594   {
1595     $ui = get_userinfo();
1596     $deps = array();
1598     /* Is this a new object ? Or just an edited existing object */
1599     if(!$this->initially_was_account && $this->is_account){
1600       $new = true;
1601     }else{
1602       $new = false;
1603     }
1605     foreach($this->config->idepartments as $dn => $name){
1606       if($new && $this->acl_is_createable($dn)){
1607         $deps[$dn] = $name;
1608       }elseif(!$new && $this->acl_is_moveable($dn)){
1609         $deps[$dn] = $name;
1610       }
1611     }
1613     /* Add current base */      
1614     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1615       $deps[$this->base] = $this->config->idepartments[$this->base];
1616     }elseif(strtolower($this->dn) == strtolower($this->config->current['BASE'])){
1618     }else{
1619       trigger_error("Cannot return list of departments, no default base found in class ".get_class($this).". ".$this->base);
1620     }
1621     return($deps);
1622   }
1625   /* This function updates ACL settings if $old_dn was used.
1626    *  \param string 'old_dn' specifies the actually used dn
1627    *  \param string 'new_dn' specifies the destiantion dn
1628    */
1629   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1630   {
1631     /* Check if old_dn is empty. This should never happen */
1632     if(empty($old_dn) || empty($new_dn)){
1633       trigger_error("Failed to check acl dependencies, wrong dn given.");
1634       return;
1635     }
1637     /* Update userinfo if necessary */
1638     $ui = session::global_get('ui');
1639     if($ui->dn == $old_dn){
1640       $ui->dn = $new_dn;
1641       session::global_set('ui',$ui);
1642       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current object dn from '".$old_dn."' to '".$new_dn."'");
1643     }
1645     /* Object was moved, ensure that all acls will be moved too */
1646     if($new_dn != $old_dn && $old_dn != "new"){
1648       /* get_ldap configuration */
1649       $update = array();
1650       $ldap = $this->config->get_ldap_link();
1651       $ldap->cd ($this->config->current['BASE']);
1652       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*".base64_encode($old_dn)."*))",array("cn","gosaAclEntry"));
1653       while($attrs = $ldap->fetch()){
1654         $acls = array();
1655         $found = false;
1656         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1657           $acl_parts = explode(":",$attrs['gosaAclEntry'][$i]);
1659           /* Roles uses antoher data storage order, members are stored int the third part, 
1660              while the members in direct ACL assignments are stored in the second part.
1661            */
1662           $id = ($acl_parts[1] == "role") ? 3 : 2;
1664           /* Update member entries to use $new_dn instead of old_dn
1665            */
1666           $members = explode(",",$acl_parts[$id]);
1667           foreach($members as $key => $member){
1668             $member = base64_decode($member);
1669             if($member == $old_dn){
1670               $members[$key] = base64_encode($new_dn);
1671               $found = TRUE;
1672             }
1673           } 
1675           /* Check if the selected role has to updated
1676            */
1677           if($acl_parts[1] == "role" && $acl_parts[2] == base64_encode($old_dn)){
1678             $acl_parts[2] = base64_encode($new_dn);
1679             $found = TRUE;
1680           }
1682           /* Build new acl string */ 
1683           $acl_parts[$id] = implode($members,",");
1684           $acls[] = implode($acl_parts,":");
1685         }
1687         /* Acls for this object must be adjusted */
1688         if($found){
1690           $debug_info=  _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1691             $old_dn."</b><br>&nbsp;-"._("to")."&nbsp;<b>".$new_dn."</b><br>";
1692           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1694           $update[$attrs['dn']] =array();
1695           foreach($acls as $acl){
1696             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1697           }
1698         }
1699       }
1701       /* Write updated acls */
1702       foreach($update as $dn => $attrs){
1703         $ldap->cd($dn);
1704         $ldap->modify($attrs);
1705       }
1706     }
1707   }
1709   
1711   /*! \brief Enable the Serial ID check
1712    *
1713    * This function enables the entry Serial ID check.  If an entry was edited while
1714    * we have edited the entry too, an error message will be shown. 
1715    * To configure this check correctly read the FAQ.
1716    */    
1717   function enable_CSN_check()
1718   {
1719     $this->CSN_check_active =TRUE;
1720     $this->entryCSN = getEntryCSN($this->dn);
1721   }
1724   /*! \brief  Prepares the plugin to be used for multiple edit
1725    *          Update plugin attributes with given array of attribtues.
1726    *  \param  array   Array with attributes that must be updated.
1727    */
1728   function init_multiple_support($attrs,$all)
1729   {
1730     $ldap= $this->config->get_ldap_link();
1731     $this->multi_attrs    = $attrs;
1732     $this->multi_attrs_all= $all;
1734     /* Copy needed attributes */
1735     foreach ($this->attributes as $val){
1736       $found= array_key_ics($val, $this->multi_attrs);
1737  
1738       if ($found != ""){
1739         if(isset($this->multi_attrs["$val"][0])){
1740           $this->$val= $this->multi_attrs["$val"][0];
1741         }
1742       }
1743     }
1744   }
1746  
1747   /*! \brief  Enables multiple support for this plugin
1748    */
1749   function enable_multiple_support()
1750   {
1751     $this->ignore_account = TRUE;
1752     $this->multiple_support_active = TRUE;
1753   }
1756   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1757       \return array Cotaining all modified values. 
1758    */
1759   function get_multi_edit_values()
1760   {
1761     $ret = array();
1762     foreach($this->attributes as $attr){
1763       if(in_array($attr,$this->multi_boxes)){
1764         $ret[$attr] = $this->$attr;
1765       }
1766     }
1767     return($ret);
1768   }
1770   
1771   /*! \brief  Update class variables with values collected by multiple edit.
1772    */
1773   function set_multi_edit_values($attrs)
1774   {
1775     foreach($attrs as $name => $value){
1776       $this->$name = $value;
1777     }
1778   }
1781   /*! \brief Generates the html output for this node for multi edit*/
1782   function multiple_execute()
1783   {
1784     /* This one is empty currently. Fabian - please fill in the docu code */
1785     session::global_set('current_class_for_help',get_class($this));
1787     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1788     session::set('LOCK_VARS_TO_USE',array());
1789     session::set('LOCK_VARS_USED_GET',array());
1790     session::set('LOCK_VARS_USED_POST',array());
1791     session::set('LOCK_VARS_USED_REQUEST',array());
1792     
1793     return("Multiple edit is currently not implemented for this plugin.");
1794   }
1797   /*! \brief Save HTML posted data to object for multiple edit
1798    */
1799   function multiple_save_object()
1800   {
1801     if(empty($this->entryCSN) && $this->CSN_check_active){
1802       $this->entryCSN = getEntryCSN($this->dn);
1803     }
1805     /* Save values to object */
1806     $this->multi_boxes = array();
1807     foreach ($this->attributes as $val){
1808   
1809       /* Get selected checkboxes from multiple edit */
1810       if(isset($_POST["use_".$val])){
1811         $this->multi_boxes[] = $val;
1812       }
1814       if (isset ($_POST["$val"]) && $this->acl_is_writeable($val)){
1816         /* Check for modifications */
1817         if (get_magic_quotes_gpc()) {
1818           $data= stripcslashes($_POST["$val"]);
1819         } else {
1820           $data= $this->$val = $_POST["$val"];
1821         }
1822         if ($this->$val != $data){
1823           $this->is_modified= TRUE;
1824         }
1825     
1826         /* IE post fix */
1827         if(isset($data[0]) && $data[0] == chr(194)) {
1828           $data = "";  
1829         }
1830         $this->$val= $data;
1831       }
1832     }
1833   }
1836   /*! \brief Returns all attributes of this plugin, 
1837                to be able to detect multiple used attributes 
1838                in multi_plugg::detect_multiple_used_attributes().
1839       @return array Attributes required for intialization of multi_plug
1840    */
1841   public function get_multi_init_values()
1842   {
1843     $attrs = $this->attrs;
1844     return($attrs);
1845   }
1848   /*! \brief  Check given values in multiple edit
1849       \return array Error messages
1850    */
1851   function multiple_check()
1852   {
1853     $message = plugin::check();
1854     return($message);
1855   }
1858   /*! \brief  Returns the snapshot header part for "Actions" menu in management dialogs 
1859       \param  $layer_menu  
1860    */   
1861   function get_snapshot_header($base,$category)
1862   {
1863     $str = "";
1864     $ui = get_userinfo();
1865     if($this->snapshotEnabled() && $ui->allow_snapshot_restore($base,$category)){
1867       $ok = false;
1868       foreach($this->get_used_snapshot_bases() as $base){
1869         $ok |= count($this->getAllDeletedSnapshots($base)) >= 1 ;
1870       }
1872       if($ok){
1873         $str = "..|<img class='center' src='images/lists/restore.png' ".
1874           "alt='"._("Restore")."'>&nbsp;"._("Restore").                       "|RestoreDeletedSnapShot|\n";
1875       }else{
1876         $str = "..|<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;"._("Restore")."||\n";
1877       }
1878     }
1879     return($str);
1880   }
1883   function get_snapshot_action($base,$category)
1884   {
1885     $str= ""; 
1886     $ui = get_userinfo();
1887     if($this->snapshotEnabled()){
1888       if ($ui->allow_snapshot_restore($base,$category)){
1890         if(count($this->Available_SnapsShots($base))){
1891           $str.= "<input class='center' type='image' src='images/lists/restore.png'
1892             alt='"._("Restore snapshot")."' name='RestoreSnapShotDialog_".base64_encode($base)."' title='"._("Restore snapshot")."'>&nbsp;";
1893         } else {
1894           $str = "<img class='center' src='images/lists/restore_grey.png' alt=''>&nbsp;";
1895         }
1896       }
1897       if($ui->allow_snapshot_create($base,$category)){
1898         $str.= "<input class='center' type='image' src='images/snapshot.png'
1899           alt='"._("Create snapshot")."' name='CreateSnapShotDialog_".base64_encode($base)."' 
1900           title='"._("Create a new snapshot from this object")."'>&nbsp;";
1901       }else{
1902         $str = "<img class='center' src='images/empty.png' alt=' '>&nbsp;";
1903       }
1904     }
1906     return($str);
1907   }
1910   function get_copypaste_action($base,$category,$class,$copy = TRUE, $cut = TRUE)
1911   {
1912     $ui = get_userinfo();
1913     $action = "";
1914     if($this->CopyPasteHandler){
1915       if($cut){
1916         if($ui->is_cutable($base,$category,$class)){
1917           $action .= "<input class='center' type='image'
1918             src='images/lists/cut.png' alt='"._("cut")."' name='cut_%KEY%' title='"._("Cut this entry")."'>&nbsp;";
1919         }else{
1920           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
1921         }
1922       }
1923       if($copy){
1924         if($ui->is_copyable($base,$category,$class)){
1925           $action.= "<input class='center' type='image'
1926             src='images/lists/copy.png' alt='"._("copy")."' name='copy_%KEY%' title='"._("Copy this entry")."'>&nbsp;";
1927         }else{
1928           $action.="<img src='images/empty.png' alt=' ' class='center'>&nbsp;";
1929         }
1930       }
1931     }
1933     return($action); 
1934   }
1937   function get_copypaste_header($base,$category,$copy = TRUE, $cut = TRUE)
1938   {
1939     $s = "";
1940     $ui =get_userinfo();
1942     if(!is_array($category)){
1943       $category = array($category);
1944     }
1946     /* Check permissions for each category, if there is at least one category which 
1947         support read or paste permissions for the given base, then display the specific actions.
1948      */
1949     $readable = $pasteable = false;
1950     foreach($category as $cat){
1951       $readable= $readable || preg_match('/r/', $ui->get_category_permissions($base, $cat));
1952       $pasteable= $pasteable || $ui->is_pasteable($base, $cat) == 1;
1953     }
1954   
1955     if(($cut || $copy) && isset($this->CopyPasteHandler) && is_object($this->CopyPasteHandler)){
1956       if($readable){
1957         $s.= "..|---|\n";
1958         if($copy){
1959           $s.= "..|<img src='images/lists/copy.png' alt='' border='0' class='center'>".
1960             "&nbsp;"._("Copy")."|"."multiple_copy_systems|\n";
1961         }
1962         if($cut){
1963           $s.= "..|<img src='images/lists/cut.png' alt='' border='0' class='center'>".
1964             "&nbsp;"._("Cut")."|"."multiple_cut_systems|\n";
1965         }
1966       }
1968       if($pasteable){
1969         if($this->CopyPasteHandler->entries_queued()){
1970           $img = "<img border='0' class='center' src='images/lists/paste.png' alt=''>";
1971           $s.="..|".$img."&nbsp;"._("Paste")."|editPaste|\n";
1972         }else{
1973           $img = "<img border='0' class='center' src='images/lists/paste-grey.png' alt=''>";
1974           $s.="..|".$img."&nbsp;"._("Paste")."\n";
1975         }
1976       }
1977     }
1978     return($s);
1979   }
1982   function get_used_snapshot_bases()
1983   {
1984      return(array());
1985   }
1987   function is_modal_dialog()
1988   {
1989     return(isset($this->dialog) && $this->dialog);
1990   }
1993   /*! \brief    Forward command execution requests
1994    *             to the hook execution method. 
1995    */
1996   function handle_post_events($mode, $addAttrs= array())
1997   {
1998     if(!in_array($mode, array('add','remove','modify'))){
1999       trigger_error(sprintf("Invalid post event type given '%s'! Valid types are [add,modify,remove].", $mode));
2000       return;
2001     }
2002     switch ($mode){
2003       case "add":
2004         plugin::callHook($this,"POSTCREATE", $addAttrs);
2005       break;
2007       case "modify":
2008         plugin::callHook($this,"POSTMODIFY", $addAttrs);
2009       break;
2011       case "remove":
2012         plugin::callHook($this,"POSTREMOVE", $addAttrs);
2013       break;
2014     }
2015   }
2018   /*! \brief    Calls external hooks which are defined for this plugin (gosa.conf)
2019    *            Replaces placeholder by class values of this plugin instance.
2020    *  @param    Allows to a add special replacements.
2021    */
2022   static function callHook($plugin, $cmd, $addAttrs= array())
2023   {
2024     global $config;
2025     $command= $config->search(get_class($plugin), $cmd,array('menu','tabs'));
2026     if ($command != ""){
2028       // Walk trough attributes list and add the plugins attributes. 
2029       foreach ($plugin->attributes as $attr){
2030         if (!is_array($plugin->$attr)){
2031           $addAttrs[$attr] = $plugin->$attr;
2032         }
2033       }
2034       $ui = get_userinfo();
2035       $addAttrs['callerDN']=$ui->dn;
2036       $addAttrs['dn']=$plugin->dn;
2038       // Sort attributes by length, ensures correct replacement
2039       $tmp = array();
2040       foreach($addAttrs as $name => $value){
2041         $tmp[$name] =  strlen($name);
2042       }
2043       arsort($tmp);
2045       // Now replace the placeholder 
2046       foreach ($tmp as $name => $len){
2047         $value = $addAttrs[$name];
2048         $command= str_replace("%$name", "$value", $command);
2049       }
2051       // If there are still some %.. in our command, try to fill these with some other class vars 
2052       if(preg_match("/%/",$command)){
2053         $attrs = get_object_vars($plugin);
2054         foreach($attrs as $name => $value){
2055           if(is_array($value)){
2056             $s = "";
2057             foreach($value as $val){
2058               if(is_string($val) || is_int($val) || is_float($val) || is_bool($val)){
2059                 $s .= '"'.$val.'",'; 
2060               }
2061             }
2062             $value = '['.trim($s,',').']';
2063           }
2064           if(!is_string($value) && !is_int($value) && !is_float($value) && !is_bool($value)){
2065             continue;
2066           }
2067           $command= preg_replace("/%$name/", $value, $command);
2068         }
2069       }
2071       if (check_command($command)){
2072         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,$command,"Execute");
2073         exec($command,$arr);
2074         if(is_array($arr)){
2075           $str = implode("\n",$arr);
2076           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Result: ".$str);
2077         }
2078       } else {
2079         $message= msgPool::cmdnotfound("POSTCREATE", get_class($plugin));
2080         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
2081       }
2082     }
2083   }
2086 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
2087 ?>