Code

Fixed typo
[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   /*!
36     \brief Reference to parent object
38     This variable is used when the plugin is included in tabs
39     and keeps reference to the tab class. Communication to other
40     tabs is possible by 'name'. So the 'fax' plugin can ask the
41     'userinfo' plugin for the fax number.
43     \sa tab
44    */
45   var $parent= NULL;
47   /*!
48     \brief Configuration container
50     Access to global configuration
51    */
52   var $config= NULL;
54   /*!
55     \brief Mark plugin as account
57     Defines whether this plugin is defined as an account or not.
58     This has consequences for the plugin to be saved from tab
59     mode. If it is set to 'FALSE' the tab will call the delete
60     function, else the save function. Should be set to 'TRUE' if
61     the construtor detects a valid LDAP object.
63     \sa plugin::plugin()
64    */
65   var $is_account= FALSE;
66   var $initially_was_account= FALSE;
68   /*!
69     \brief Mark plugin as template
71     Defines whether we are creating a template or a normal object.
72     Has conseqences on the way execute() shows the formular and how
73     save() puts the data to LDAP.
75     \sa plugin::save() plugin::execute()
76    */
77   var $is_template= FALSE;
78   var $ignore_account= FALSE;
79   var $is_modified= FALSE;
81   /*!
82     \brief Represent temporary LDAP data
84     This is only used internally.
85    */
86   var $attrs= array();
88   /* Keep set of conflicting plugins */
89   var $conflicts= array();
91   /* Save unit tags */
92   var $gosaUnitTag= "";
93   var $skipTagging= FALSE;
95   /*!
96     \brief Used standard values
98     dn
99    */
100   var $dn= "";
101   var $uid= "";
102   var $sn= "";
103   var $givenName= "";
104   var $acl= "*none*";
105   var $dialog= FALSE;
106   var $snapDialog = NULL;
108   /* attribute list for save action */
109   var $attributes= array();
110   var $objectclasses= array();
111   var $is_new= TRUE;
112   var $saved_attributes= array();
114   var $acl_base= "";
115   var $acl_category= "";
117   /* This can be set to render the tabulators in another stylesheet */
118   var $pl_notify= FALSE;
120   /* Object entry CSN */
121   var $entryCSN         = "";
122   var $CSN_check_active = FALSE;
124   /* This variable indicates that this class can handle multiple dns at once. */
125   var $multiple_support = FALSE;
126   var $multi_attrs      = array();
127   var $multi_attrs_all  = array(); 
129   /* This aviable indicates, that we are currently in multiple edit handle */
130   var $multiple_support_active = FALSE; 
131   var $selected_edit_values = array();
132   var $multi_boxes = array();
134   /*! \brief plugin constructor
136     If 'dn' is set, the node loads the given 'dn' from LDAP
138     \param dn Distinguished name to initialize plugin from
139     \sa plugin()
140    */
141   function plugin (&$config, $dn= NULL, $parent= NULL)
142   {
143     /* Configuration is fine, allways */
144     $this->config= &$config;    
145     $this->dn= $dn;
147     /* Handle new accounts, don't read information from LDAP */
148     if ($dn == "new"){
149       return;
150     }
152     /* Save current dn as acl_base */
153     $this->acl_base= $dn;
155     /* Get LDAP descriptor */
156     if ($dn !== NULL){
158       /* Load data to 'attrs' and save 'dn' */
159       if ($parent !== NULL){
160         $this->attrs= $parent->attrs;
161       } else {
162         $ldap= $this->config->get_ldap_link();
163         $ldap->cat ($dn);
164         $this->attrs= $ldap->fetch();
165       }
167       /* Copy needed attributes */
168       foreach ($this->attributes as $val){
169         $found= array_key_ics($val, $this->attrs);
170         if ($found != ""){
171           $this->$val= $this->attrs["$found"][0];
172         }
173       }
175       /* gosaUnitTag loading... */
176       if (isset($this->attrs['gosaUnitTag'][0])){
177         $this->gosaUnitTag= $this->attrs['gosaUnitTag'][0];
178       }
180       /* Set the template flag according to the existence of objectClass
181          gosaUserTemplate */
182       if (isset($this->attrs['objectClass'])){
183         if (in_array ("gosaUserTemplate", $this->attrs['objectClass'])){
184           $this->is_template= TRUE;
185           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
186               "found", "Template check");
187         }
188       }
190       /* Is Account? */
191       $found= TRUE;
192       foreach ($this->objectclasses as $obj){
193         if (preg_match('/top/i', $obj)){
194           continue;
195         }
196         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
197           $found= FALSE;
198           break;
199         }
200       }
201       if ($found){
202         $this->is_account= TRUE;
203         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
204             "found", "Object check");
205       }
207       /* Prepare saved attributes */
208       $this->saved_attributes= $this->attrs;
209       foreach ($this->saved_attributes as $index => $value){
210         if (preg_match('/^[0-9]+$/', $index)){
211           unset($this->saved_attributes[$index]);
212           continue;
213         }
214         if (!in_array($index, $this->attributes) && $index != "objectClass"){
215           unset($this->saved_attributes[$index]);
216           continue;
217         }
219         if (isset($this->saved_attributes[$index][0])){
220           if(!isset($this->saved_attributes[$index]["count"])){
221             $this->saved_attributes[$index]["count"] = count($this->saved_attributes[$index]);
222           }
223           if($this->saved_attributes[$index]["count"] == 1){
224             $tmp= $this->saved_attributes[$index][0];
225             unset($this->saved_attributes[$index]);
226             $this->saved_attributes[$index]= $tmp;
227             continue;
228           }
229         }
230         unset($this->saved_attributes["$index"]["count"]);
231       }
232       if(isset($this->attrs['gosaUnitTag'])){
233         $this->saved_attributes['gosaUnitTag'] = $this->attrs['gosaUnitTag'][0];
234       }
235     }
237     /* Save initial account state */
238     $this->initially_was_account= $this->is_account;
239   }
242   /*! \brief execute plugin
244     Generates the html output for this node
245    */
246   function execute()
247   {
248     /* This one is empty currently. Fabian - please fill in the docu code */
249     session::set('current_class_for_help',get_class($this));
251     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
252     session::set('LOCK_VARS_TO_USE',array());
253     session::set('LOCK_VARS_USED',array());
254   }
256   /*! \brief execute plugin
257      Removes object from parent
258    */
259   function remove_from_parent()
260   {
261     /* include global link_info */
262     $ldap= $this->config->get_ldap_link();
264     /* Get current objectClasses in order to add the required ones */
265     $ldap->cat($this->dn);
266     $tmp= $ldap->fetch ();
267     $oc= array();
268     if (isset($tmp['objectClass'])){
269       $oc= $tmp['objectClass'];
270       unset($oc['count']);
271     }
273     /* Remove objectClasses from entry */
274     $ldap->cd($this->dn);
275     $this->attrs= array();
276     $this->attrs['objectClass']= array_remove_entries($this->objectclasses,$oc);
278     /* Unset attributes from entry */
279     foreach ($this->attributes as $val){
280       $this->attrs["$val"]= array();
281     }
283     /* Unset account info */
284     $this->is_account= FALSE;
286     /* Do not write in plugin base class, this must be done by
287        children, since there are normally additional attribs,
288        lists, etc. */
289     /*
290        $ldap->modify($this->attrs);
291      */
292   }
295   /*! \brief   Save HTML posted data to object 
296    */
297   function save_object()
298   {
299     /* Update entry CSN if it is empty. */
300     if(empty($this->entryCSN) && $this->CSN_check_active){
301       $this->entryCSN = getEntryCSN($this->dn);
302     }
304     /* Save values to object */
305     foreach ($this->attributes as $val){
306       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
307         /* Check for modifications */
308         if (get_magic_quotes_gpc()) {
309           $data= stripcslashes($_POST["$val"]);
310         } else {
311           $data= $this->$val = $_POST["$val"];
312         }
313         if ($this->$val != $data){
314           $this->is_modified= TRUE;
315         }
316     
317         /* Okay, how can I explain this fix ... 
318          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
319          * So IE posts these 'unselectable' option, with value = chr(194) 
320          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
321          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
322          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
323          */
324         if(isset($data[0]) && $data[0] == chr(194)) {
325           $data = "";  
326         }
327         $this->$val= $data;
328       }
329     }
330   }
333   /* Save data to LDAP, depending on is_account we save or delete */
334   function save()
335   {
336     /* include global link_info */
337     $ldap= $this->config->get_ldap_link();
339     /* Save all plugins */
340     $this->entryCSN = "";
342     /* Start with empty array */
343     $this->attrs= array();
345     /* Get current objectClasses in order to add the required ones */
346     $ldap->cat($this->dn);
347     
348     $tmp= $ldap->fetch ();
350     $oc= array();
351     if (isset($tmp['objectClass'])){
352       $oc= $tmp["objectClass"];
353       $this->is_new= FALSE;
354       unset($oc['count']);
355     } else {
356       $this->is_new= TRUE;
357     }
359     /* Load (minimum) attributes, add missing ones */
360     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
362     /* Copy standard attributes */
363     foreach ($this->attributes as $val){
364       if ($this->$val != ""){
365         $this->attrs["$val"]= $this->$val;
366       } elseif (!$this->is_new) {
367         $this->attrs["$val"]= array();
368       }
369     }
371     /* Handle tagging */
372     $this->tag_attrs($this->attrs);
373   }
376   function cleanup()
377   {
378     foreach ($this->attrs as $index => $value){
379       
380       /* Convert arrays with one element to non arrays, if the saved
381          attributes are no array, too */
382       if (is_array($this->attrs[$index]) && 
383           count ($this->attrs[$index]) == 1 &&
384           isset($this->saved_attributes[$index]) &&
385           !is_array($this->saved_attributes[$index])){
386           
387         $tmp= $this->attrs[$index][0];
388         $this->attrs[$index]= $tmp;
389       }
391       /* Remove emtpy arrays if they do not differ */
392       if (is_array($this->attrs[$index]) &&
393           count($this->attrs[$index]) == 0 &&
394           !isset($this->saved_attributes[$index])){
395           
396         unset ($this->attrs[$index]);
397         continue;
398       }
400       /* Remove single attributes that do not differ */
401       if (!is_array($this->attrs[$index]) &&
402           isset($this->saved_attributes[$index]) &&
403           !is_array($this->saved_attributes[$index]) &&
404           $this->attrs[$index] == $this->saved_attributes[$index]){
406         unset ($this->attrs[$index]);
407         continue;
408       }
410       /* Remove arrays that do not differ */
411       if (is_array($this->attrs[$index]) && 
412           isset($this->saved_attributes[$index]) &&
413           is_array($this->saved_attributes[$index])){
414           
415         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
416           unset ($this->attrs[$index]);
417           continue;
418         }
419       }
420     }
422     /* Update saved attributes and ensure that next cleanups will be successful too */
423     foreach($this->attrs as $name => $value){
424       $this->saved_attributes[$name] = $value;
425     }
426   }
428   /* Check formular input */
429   function check()
430   {
431     $message= array();
433     /* Skip if we've no config object */
434     if (!isset($this->config) || !is_object($this->config)){
435       return $message;
436     }
438     /* Find hooks entries for this class */
439     $command= $this->config->search(get_class($this), "CHECK", array('menu', 'tabs'));
441     if ($command != ""){
443       if (!check_command($command)){
444         $message[]= msgPool::cmdnotfound("CHECK", get_class($this));
445       } else {
447         /* Generate "ldif" for check hook */
448         $ldif= "dn: $this->dn\n";
449         
450         /* ... objectClasses */
451         foreach ($this->objectclasses as $oc){
452           $ldif.= "objectClass: $oc\n";
453         }
454         
455         /* ... attributes */
456         foreach ($this->attributes as $attr){
457           if ($this->$attr == ""){
458             continue;
459           }
460           if (is_array($this->$attr)){
461             foreach ($this->$attr as $val){
462               $ldif.= "$attr: $val\n";
463             }
464           } else {
465               $ldif.= "$attr: ".$this->$attr."\n";
466           }
467         }
469         /* Append empty line */
470         $ldif.= "\n";
472         /* Feed "ldif" into hook and retrieve result*/
473         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
474         $fh= proc_open($command, $descriptorspec, $pipes);
475         if (is_resource($fh)) {
476           fwrite ($pipes[0], $ldif);
477           fclose($pipes[0]);
478           
479           $result= stream_get_contents($pipes[1]);
480           if ($result != ""){
481             $message[]= $result;
482           }
483           
484           fclose($pipes[1]);
485           fclose($pipes[2]);
486           proc_close($fh);
487         }
488       }
490     }
492     /* Check entryCSN */
493     if($this->CSN_check_active){
494       $current_csn = getEntryCSN($this->dn);
495       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
496         $this->entryCSN = $current_csn;
497         $message[] = _("The object has changed since opened in GOsa. All changes that may be done by others get lost if you save this entry!");
498       }
499     }
500     return ($message);
501   }
503   /* Adapt from template, using 'dn' */
504   function adapt_from_template($dn, $skip= array())
505   {
506     /* Include global link_info */
507     $ldap= $this->config->get_ldap_link();
509     /* Load requested 'dn' to 'attrs' */
510     $ldap->cat ($dn);
511     $this->attrs= $ldap->fetch();
513     /* Walk through attributes */
514     foreach ($this->attributes as $val){
516       /* Skip the ones in skip list */
517       if (in_array($val, $skip)){
518         continue;
519       }
521       if (isset($this->attrs["$val"][0])){
523         /* If attribute is set, replace dynamic parts: 
524            %sn, %givenName and %uid. Fill these in our local variables. */
525         $value= $this->attrs["$val"][0];
527         foreach (array("sn", "givenName", "uid") as $repl){
528           if (preg_match("/%$repl/i", $value)){
529             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
530           }
531         }
532         $this->$val= $value;
533       }
534     }
536     /* Is Account? */
537     $found= TRUE;
538     foreach ($this->objectclasses as $obj){
539       if (preg_match('/top/i', $obj)){
540         continue;
541       }
542       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
543         $found= FALSE;
544         break;
545       }
546     }
547     if ($found){
548       $this->is_account= TRUE;
549     }
550   }
552   /* Indicate whether a password change is needed or not */
553   function password_change_needed()
554   {
555     return FALSE;
556   }
559   /* Show header message for tab dialogs */
560   function show_enable_header($button_text, $text, $disabled= FALSE)
561   {
562     if (($disabled == TRUE) || (!$this->acl_is_createable())){
563       $state= "disabled";
564     } else {
565       $state= "";
566     }
567     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
568     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
569       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
571     return($display);
572   }
575   /* Show header message for tab dialogs */
576   function show_disable_header($button_text, $text, $disabled= FALSE)
577   {
578     if (($disabled == TRUE) || !$this->acl_is_removeable()){
579       $state= "disabled";
580     } else {
581       $state= "";
582     }
583     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
584     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
585       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
587     return($display);
588   }
591   /* Show header message for tab dialogs */
592   function show_header($button_text, $text, $disabled= FALSE)
593   {
594     echo "FIXME: show_header should be replaced by show_disable_header and show_enable_header<br>";
595     if ($disabled == TRUE){
596       $state= "disabled";
597     } else {
598       $state= "";
599     }
600     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
601     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
602       ($this->acl_is_createable()?'':'disabled')." ".$state.
603       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
605     return($display);
606   }
609   function postcreate($add_attrs= array())
610   {
611     /* Find postcreate entries for this class */
612     $command= $this->config->search(get_class($this), "POSTCREATE",array('menu', 'tabs'));
614     if ($command != ""){
616       /* Walk through attribute list */
617       foreach ($this->attributes as $attr){
618         if (!is_array($this->$attr)){
619           $add_attrs[$attr] = $this->$attr;
620         }
621       }
622       $add_attrs['dn']=$this->dn;
624       $tmp = array();
625       foreach($add_attrs as $name => $value){
626         $tmp[$name] =  strlen($name);
627       }
628       arsort($tmp);
629       
630       /* Additional attributes */
631       foreach ($tmp as $name => $len){
632         $value = $add_attrs[$name];
633         $command= preg_replace("/%$name/", "$value", $command);
634       }
636       if (check_command($command)){
637         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
638             $command, "Execute");
640         exec($command);
641       } else {
642         $message= msgPool::cmdnotfound("POSTCREATE", get_class($this));
643         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
644       }
645     }
646   }
648   function postmodify($add_attrs= array())
649   {
650     /* Find postcreate entries for this class */
651     $command= $this->config->search(get_class($this), "POSTMODIFY",array('menu','tabs'));
653     if ($command != ""){
655       /* Walk through attribute list */
656       foreach ($this->attributes as $attr){
657         if (!is_array($this->$attr)){
658           $add_attrs[$attr] = $this->$attr;
659         }
660       }
661       $add_attrs['dn']=$this->dn;
663       $tmp = array();
664       foreach($add_attrs as $name => $value){
665         $tmp[$name] =  strlen($name);
666       }
667       arsort($tmp);
668       
669       /* Additional attributes */
670       foreach ($tmp as $name => $len){
671         $value = $add_attrs[$name];
672         $command= preg_replace("/%$name/", "$value", $command);
673       }
675       if (check_command($command)){
676         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,$command, "Execute");
677         exec($command);
678       } else {
679         $message= msgPool::cmdnotfound("POSTMODIFY", get_class($this));
680         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
681       }
682     }
683   }
685   function postremove($add_attrs= array())
686   {
687     /* Find postremove entries for this class */
688     $command= $this->config->search(get_class($this), "POSTREMOVE",array('menu','tabs'));
689     if ($command != ""){
691       /* Walk through attribute list */
692       foreach ($this->attributes as $attr){
693         if (!is_array($this->$attr)){
694           $add_attrs[$attr] = $this->$attr;
695         }
696       }
697       $add_attrs['dn']=$this->dn;
699       $tmp = array();
700       foreach($add_attrs as $name => $value){
701         $tmp[$name] =  strlen($name);
702       }
703       arsort($tmp);
704       
705       /* Additional attributes */
706       foreach ($tmp as $name => $len){
707         $value = $add_attrs[$name];
708         $command= preg_replace("/%$name/", "$value", $command);
709       }
711       if (check_command($command)){
712         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
713             $command, "Execute");
715         exec($command);
716       } else {
717         $message= msgPool::cmdnotfound("POSTREMOVE", get_class($this));
718         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
719       }
720     }
721   }
723   /* Create unique DN */
724   function create_unique_dn($attribute, $base)
725   {
726     $ldap= $this->config->get_ldap_link();
727     $base= preg_replace("/^,*/", "", $base);
729     /* Try to use plain entry first */
730     $dn= "$attribute=".$this->$attribute.",$base";
731     $ldap->cat ($dn, array('dn'));
732     if (!$ldap->fetch()){
733       return ($dn);
734     }
736     /* Look for additional attributes */
737     foreach ($this->attributes as $attr){
738       if ($attr == $attribute || $this->$attr == ""){
739         continue;
740       }
742       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
743       $ldap->cat ($dn, array('dn'));
744       if (!$ldap->fetch()){
745         return ($dn);
746       }
747     }
749     /* None found */
750     return ("none");
751   }
753   function rebind($ldap, $referral)
754   {
755     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
756     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
757       $this->error = "Success";
758       $this->hascon=true;
759       $this->reconnect= true;
760       return (0);
761     } else {
762       $this->error = "Could not bind to " . $credentials['ADMIN'];
763       return NULL;
764     }
765   }
768   /* Recursively copy ldap object */
769   function _copy($src_dn,$dst_dn)
770   {
771     $ldap=$this->config->get_ldap_link();
772     $ldap->cat($src_dn);
773     $attrs= $ldap->fetch();
775     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
776     $ds= ldap_connect($this->config->current['SERVER']);
777     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
778     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
779       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
780     }
782     $r=ldap_bind($ds,$this->config->current['ADMIN'], $this->config->current['PASSWORD']);
783     $sr=ldap_read($ds, @LDAP::fix($src_dn), "objectClass=*");
785     /* Fill data from LDAP */
786     $new= array();
787     if ($sr) {
788       $ei=ldap_first_entry($ds, $sr);
789       if ($ei) {
790         foreach($attrs as $attr => $val){
791           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
792             for ($i= 0; $i<$info['count']; $i++){
793               if ($info['count'] == 1){
794                 $new[$attr]= $info[$i];
795               } else {
796                 $new[$attr][]= $info[$i];
797               }
798             }
799           }
800         }
801       }
802     }
804     /* close conncetion */
805     ldap_unbind($ds);
807     /* Adapt naming attribute */
808     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
809     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
810     $new[$dst_name]= @LDAP::fix($dst_val);
812     /* Check if this is a department.
813      * If it is a dep. && there is a , override in his ou 
814      *  change \2C to , again, else this entry can't be saved ...
815      */
816     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
817       $new['ou'] = preg_replace("/\\\\,/",",",$new['ou']);
818     }
820     /* Save copy */
821     $ldap->connect();
822     $ldap->cd($this->config->current['BASE']);
823     
824     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
826     /* FAIvariable=.../..., cn=.. 
827         could not be saved, because the attribute FAIvariable was different to 
828         the dn FAIvariable=..., cn=... */
829     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
830       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
831     }
832     $ldap->cd($dst_dn);
833     $ldap->add($new);
835     if (!$ldap->success()){
836       trigger_error("Trying to save $dst_dn failed.",
837           E_USER_WARNING);
838       return(FALSE);
839     }
840     return(TRUE);
841   }
844   /* This is a workaround function. */
845   function copy($src_dn, $dst_dn)
846   {
847     /* Rename dn in possible object groups */
848     $ldap= $this->config->get_ldap_link();
849     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::prepare4filter($src_dn).'))',
850         array('cn'));
851     while ($attrs= $ldap->fetch()){
852       $og= new ogroup($this->config, $ldap->getDN());
853       unset($og->member[$src_dn]);
854       $og->member[$dst_dn]= $dst_dn;
855       $og->save ();
856     }
858     $ldap->cat($dst_dn);
859     $attrs= $ldap->fetch();
860     if (count($attrs)){
861       trigger_error("Trying to overwrite ".@LDAP::fix($dst_dn).", which already exists.",
862           E_USER_WARNING);
863       return (FALSE);
864     }
866     $ldap->cat($src_dn);
867     $attrs= $ldap->fetch();
868     if (!count($attrs)){
869       trigger_error("Trying to move ".@LDAP::fix($src_dn).", which does not seem to exist.",
870           E_USER_WARNING);
871       return (FALSE);
872     }
874     $ldap->cd($src_dn);
875     $ldap->search("objectClass=*",array("dn"));
876     while($attrs = $ldap->fetch()){
877       $src = $attrs['dn'];
878       $dst = preg_replace("/".normalizePreg($src_dn)."$/",$dst_dn,$attrs['dn']);
879       $this->_copy($src,$dst);
880     }
881     return (TRUE);
882   }
885   function move($src_dn, $dst_dn)
886   {
887     /* Do not copy if only upper- lowercase has changed */
888     if(strtolower($src_dn) == strtolower($dst_dn)){
889       return(TRUE);
890     }
892     /* Copy source to destination */
893     if (!$this->copy($src_dn, $dst_dn)){
894       return (FALSE);
895     }
897     /* Delete source */
898     $ldap= $this->config->get_ldap_link();
899     $ldap->rmdir_recursive($src_dn);
900     if (!$ldap->success()){
901       trigger_error("Trying to delete $src_dn failed.",
902           E_USER_WARNING);
903       return (FALSE);
904     }
906     return (TRUE);
907   }
910   /* Move/Rename complete trees */
911   function recursive_move($src_dn, $dst_dn)
912   {
913     /* Check if the destination entry exists */
914     $ldap= $this->config->get_ldap_link();
916     /* Check if destination exists - abort */
917     $ldap->cat($dst_dn, array('dn'));
918     if ($ldap->fetch()){
919       trigger_error("recursive_move $dst_dn already exists.",
920           E_USER_WARNING);
921       return (FALSE);
922     }
924     $this->copy($src_dn, $dst_dn);
926     /* Remove src_dn */
927     $ldap->cd($src_dn);
928     $ldap->recursive_remove($src_dn);
929     return (TRUE);
930   }
933   function handle_post_events($mode, $add_attrs= array())
934   {
935     switch ($mode){
936       case "add":
937         $this->postcreate($add_attrs);
938       break;
940       case "modify":
941         $this->postmodify($add_attrs);
942       break;
944       case "remove":
945         $this->postremove($add_attrs);
946       break;
947     }
948   }
951   function saveCopyDialog(){
952   }
955   function getCopyDialog(){
956     return(array("string"=>"","status"=>""));
957   }
960   function PrepareForCopyPaste($source)
961   {
962     $todo = $this->attributes;
963     if(isset($this->CopyPasteVars)){
964       $todo = array_merge($todo,$this->CopyPasteVars);
965     }
967     if(count($this->objectclasses)){
968       $this->is_account = TRUE;
969       foreach($this->objectclasses as $class){
970         if(!in_array($class,$source['objectClass'])){
971           $this->is_account = FALSE;
972         }
973       }
974     }
976     foreach($todo as $var){
977       if (isset($source[$var])){
978         if(isset($source[$var]['count'])){
979           if($source[$var]['count'] > 1){
980             $this->$var = array();
981             $tmp = array();
982             for($i = 0 ; $i < $source[$var]['count']; $i++){
983               $tmp = $source[$var][$i];
984             }
985             $this->$var = $tmp;
986           }else{
987             $this->$var = $source[$var][0];
988           }
989         }else{
990           $this->$var= $source[$var];
991         }
992       }
993     }
994   }
996   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
997   {
998     /* Skip tagging? 
999        If this is called from departmentGeneric, we have to skip this
1000         tagging procedure. 
1001      */
1002     if($this->skipTagging){
1003       return;
1004     }
1006     /* No dn? Self-operation... */
1007     if ($dn == ""){
1008       $dn= $this->dn;
1010       /* No tag? Find it yourself... */
1011       if ($tag == ""){
1012         $len= strlen($dn);
1014         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1015         $relevant= array();
1016         foreach ($this->config->adepartments as $key => $ntag){
1018           /* This one is bigger than our dn, its not relevant... */
1019           if ($len < strlen($key)){
1020             continue;
1021           }
1023           /* This one matches with the latter part. Break and don't fix this entry */
1024           if (preg_match('/(^|,)'.normalizePreg($key).'$/', $dn)){
1025             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1026             $relevant[strlen($key)]= $ntag;
1027             continue;
1028           }
1030         }
1032         /* If we've some relevant tags to set, just get the longest one */
1033         if (count($relevant)){
1034           ksort($relevant);
1035           $tmp= array_keys($relevant);
1036           $idx= end($tmp);
1037           $tag= $relevant[$idx];
1038           $this->gosaUnitTag= $tag;
1039         }
1040       }
1041     }
1042   
1043     /* Remove tags that may already be here... */
1044     remove_objectClass("gosaAdministrativeUnitTag", $at);
1045     if (isset($at['gosaUnitTag'])){
1046         unset($at['gosaUnitTag']);
1047     }
1049     /* Set tag? */
1050     if ($tag != ""){
1051       add_objectClass("gosaAdministrativeUnitTag", $at);
1052       $at['gosaUnitTag']= $tag;
1053     }
1055     /* Initially this object was tagged. 
1056        - But now, it is no longer inside a tagged department. 
1057        So force the remove of the tag.
1058        (objectClass was already removed obove)
1059      */
1060     if($tag == "" && $this->gosaUnitTag){
1061       $at['gosaUnitTag'] = array();
1062     }
1063   }
1066   /* Add possibility to stop remove process */
1067   function allow_remove()
1068   {
1069     $reason= "";
1070     return $reason;
1071   }
1074   /* Create a snapshot of the current object */
1075   function create_snapshot($type= "snapshot", $description= array())
1076   {
1078     /* Check if snapshot functionality is enabled */
1079     if(!$this->snapshotEnabled()){
1080       return;
1081     }
1083     /* Get configuration from gosa.conf */
1084     $tmp = $this->config->current;
1086     /* Create lokal ldap connection */
1087     $ldap= $this->config->get_ldap_link();
1088     $ldap->cd($this->config->current['BASE']);
1090     /* check if there are special server configurations for snapshots */
1091     if(!isset($tmp['SNAPSHOT_SERVER'])){
1093       /* Source and destination server are both the same, just copy source to dest obj */
1094       $ldap_to      = $ldap;
1095       $snapldapbase = $this->config->current['BASE'];
1097     }else{
1098       $server         = $tmp['SNAPSHOT_SERVER'];
1099       $user           = $tmp['SNAPSHOT_USER'];
1100       $password       = $tmp['SNAPSHOT_PASSWORD'];
1101       $snapldapbase   = $tmp['SNAPSHOT_BASE'];
1103       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1104       $ldap_to -> cd($snapldapbase);
1106       if (!$ldap_to->success()){
1107         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1108       }
1110     }
1112     /* check if the dn exists */ 
1113     if ($ldap->dn_exists($this->dn)){
1115       /* Extract seconds & mysecs, they are used as entry index */
1116       list($usec, $sec)= explode(" ", microtime());
1118       /* Collect some infos */
1119       $base           = $this->config->current['BASE'];
1120       $snap_base      = $tmp['SNAPSHOT_BASE'];
1121       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1122       $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1124       /* Create object */
1125 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1126       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1127       $newName          = preg_replace("/\./", "", $sec."-".$usec);
1128       $target= array();
1129       $target['objectClass']            = array("top", "gosaSnapshotObject");
1130       $target['gosaSnapshotData']       = gzcompress($data, 6);
1131       $target['gosaSnapshotType']       = $type;
1132       $target['gosaSnapshotDN']         = $this->dn;
1133       $target['description']            = $description;
1134       $target['gosaSnapshotTimestamp']  = $newName;
1136       /* Insert the new snapshot 
1137          But we have to check first, if the given gosaSnapshotTimestamp
1138          is already used, in this case we should increment this value till there is 
1139          an unused value. */ 
1140       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1141       $ldap_to->cat($new_dn);
1142       while($ldap_to->count()){
1143         $ldap_to->cat($new_dn);
1144         $newName = preg_replace("/\./", "", $sec."-".($usec++));
1145         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1146         $target['gosaSnapshotTimestamp']  = $newName;
1147       } 
1149       /* Inset this new snapshot */
1150       $ldap_to->cd($snapldapbase);
1151       $ldap_to->create_missing_trees($snapldapbase);
1152       $ldap_to->create_missing_trees($new_base);
1153       $ldap_to->cd($new_dn);
1154       $ldap_to->add($target);
1155       if (!$ldap_to->success()){
1156         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $new_dn, LDAP_ADD, get_class()));
1157       }
1159       if (!$ldap->success()){
1160         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $new_base, "", get_class()));
1161       }
1163     }
1164   }
1166   function remove_snapshot($dn)
1167   {
1168     $ui       = get_userinfo();
1169     $old_dn   = $this->dn; 
1170     $this->dn = $dn;
1171     $ldap = $this->config->get_ldap_link();
1172     $ldap->cd($this->config->current['BASE']);
1173     $ldap->rmdir_recursive($dn);
1174     $this->dn = $old_dn;
1175   }
1178   /* returns true if snapshots are enabled, and false if it is disalbed
1179      There will also be some errors psoted, if the configuration failed */
1180   function snapshotEnabled()
1181   {
1182     $tmp = $this->config->current;
1183     if(isset($tmp['ENABLE_SNAPSHOT'])){
1184       if (preg_match("/^true$/i", $tmp['ENABLE_SNAPSHOT']) || preg_match("/yes/i", $tmp['ENABLE_SNAPSHOT'])){
1186         /* Check if the snapshot_base is defined */
1187         if(!isset($tmp['SNAPSHOT_BASE'])){
1188           msg_dialog::display(_("Configuration error"), sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."),"SNAPSHOT_BASE"), ERROR_DIALOG);
1189           return(FALSE);
1190         }
1192         /* check if there are special server configurations for snapshots */
1193         if(isset($tmp['SNAPSHOT_SERVER'])){
1195           /* check if all required vars are available to create a new ldap connection */
1196           $missing = "";
1197           foreach(array("SNAPSHOT_SERVER","SNAPSHOT_USER","SNAPSHOT_PASSWORD","SNAPSHOT_BASE") as $var){
1198             if(!isset($tmp[$var])){
1199               $missing .= $var." ";
1200               msg_dialog::display(_("Configuration error"), sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."), $missing), ERROR_DIALOG);
1201               return(FALSE);
1202             }
1203           }
1204         }
1205         return(TRUE);
1206       }
1207     }
1208     return(FALSE);
1209   }
1212   /* Return available snapshots for the given base 
1213    */
1214   function Available_SnapsShots($dn,$raw = false)
1215   {
1216     if(!$this->snapshotEnabled()) return(array());
1218     /* Create an additional ldap object which
1219        points to our ldap snapshot server */
1220     $ldap= $this->config->get_ldap_link();
1221     $ldap->cd($this->config->current['BASE']);
1222     $cfg= &$this->config->current;
1224     /* check if there are special server configurations for snapshots */
1226     if(isset($cfg['SERVER']) && isset($cfg['SNAPSHOT_SERVER']) && $cfg['SERVER'] == $cfg['SNAPSHOT_SERVER']){
1227       $ldap_to    = $ldap;
1228     }elseif(isset($cfg['SNAPSHOT_SERVER'])){
1229       $server       = $cfg['SNAPSHOT_SERVER'];
1230       $user         = $cfg['SNAPSHOT_USER'];
1231       $password     = $cfg['SNAPSHOT_PASSWORD'];
1232       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1234       $ldap_to      = new ldapMultiplexer(new LDAP($user,$password, $server));
1235       $ldap_to -> cd ($snapldapbase);
1236       if (!$ldap_to->success()){
1237         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1238       }
1239     }else{
1240       $ldap_to    = $ldap;
1241     }
1243     /* Prepare bases and some other infos */
1244     $base           = $this->config->current['BASE'];
1245     $snap_base      = $cfg['SNAPSHOT_BASE'];
1246     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1247     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1248     $tmp            = array(); 
1250     /* Fetch all objects with  gosaSnapshotDN=$dn */
1251     $ldap_to->cd($new_base);
1252     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1253         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1255     /* Put results into a list and add description if missing */
1256     while($entry = $ldap_to->fetch()){ 
1257       if(!isset($entry['description'][0])){
1258         $entry['description'][0]  = "";
1259       }
1260       $tmp[] = $entry; 
1261     }
1263     /* Return the raw array, or format the result */
1264     if($raw){
1265       return($tmp);
1266     }else{  
1267       $tmp2 = array();
1268       foreach($tmp as $entry){
1269         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1270       }
1271     }
1272     return($tmp2);
1273   }
1276   function getAllDeletedSnapshots($base_of_object,$raw = false)
1277   {
1278     if(!$this->snapshotEnabled()) return(array());
1280     /* Create an additional ldap object which
1281        points to our ldap snapshot server */
1282     $ldap= $this->config->get_ldap_link();
1283     $ldap->cd($this->config->current['BASE']);
1284     $cfg= &$this->config->current;
1286     /* check if there are special server configurations for snapshots */
1287     if(isset($cfg['SNAPSHOT_SERVER'])){
1288       $server       = $cfg['SNAPSHOT_SERVER'];
1289       $user         = $cfg['SNAPSHOT_USER'];
1290       $password     = $cfg['SNAPSHOT_PASSWORD'];
1291       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1292       $ldap_to      = new ldapMultiplexer(new LDAP($user,$password, $server));
1293       $ldap_to->cd ($snapldapbase);
1294       if (!$ldap_to->success()){
1295         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1296       }
1297     }else{
1298       $ldap_to    = $ldap;
1299     }
1301     /* Prepare bases */ 
1302     $base           = $this->config->current['BASE'];
1303     $snap_base      = $cfg['SNAPSHOT_BASE'];
1304     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1306     /* Fetch all objects and check if they do not exist anymore */
1307     $ui = get_userinfo();
1308     $tmp = array();
1309     $ldap_to->cd($new_base);
1310     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1311     while($entry = $ldap_to->fetch()){
1313       $chk =  str_replace($new_base,"",$entry['dn']);
1314       if(preg_match("/,ou=/",$chk)) continue;
1316       if(!isset($entry['description'][0])){
1317         $entry['description'][0]  = "";
1318       }
1319       $tmp[] = $entry; 
1320     }
1322     /* Check if entry still exists */
1323     foreach($tmp as $key => $entry){
1324       $ldap->cat($entry['gosaSnapshotDN'][0]);
1325       if($ldap->count()){
1326         unset($tmp[$key]);
1327       }
1328     }
1330     /* Format result as requested */
1331     if($raw) {
1332       return($tmp);
1333     }else{
1334       $tmp2 = array();
1335       foreach($tmp as $key => $entry){
1336         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1337       }
1338     }
1339     return($tmp2);
1340   } 
1343   /* Restore selected snapshot */
1344   function restore_snapshot($dn)
1345   {
1346     if(!$this->snapshotEnabled()) return(array());
1348     $ldap= $this->config->get_ldap_link();
1349     $ldap->cd($this->config->current['BASE']);
1350     $cfg= &$this->config->current;
1352     /* check if there are special server configurations for snapshots */
1353     if(isset($cfg['SNAPSHOT_SERVER'])){
1354       $server       = $cfg['SNAPSHOT_SERVER'];
1355       $user         = $cfg['SNAPSHOT_USER'];
1356       $password     = $cfg['SNAPSHOT_PASSWORD'];
1357       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1358       $ldap_to      = new ldapMultiplexer(new LDAP($user,$password, $server));
1359       $ldap_to->cd ($snapldapbase);
1360       if (!$ldap_to->success()){
1361         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1362       }
1363     }else{
1364       $ldap_to    = $ldap;
1365     }
1367     /* Get the snapshot */ 
1368     $ldap_to->cat($dn);
1369     $restoreObject = $ldap_to->fetch();
1371     /* Prepare import string */
1372     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1374     /* Import the given data */
1375     $err = "";
1376     $ldap->import_complete_ldif($data,$err,false,false);
1377     if (!$ldap->success()){
1378       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, "", get_class()));
1379     }
1380   }
1383   function showSnapshotDialog($base,$baseSuffixe)
1384   {
1385     $once = true;
1386     foreach($_POST as $name => $value){
1388       /* Create a new snapshot, display a dialog */
1389       if(preg_match("/^CreateSnapShotDialog_/",$name) && $once){
1390         $once = false;
1391         $entry = preg_replace("/^CreateSnapShotDialog_/","",$name);
1392         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1393         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1394       }
1396       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1397       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1398         $once = false;
1399         $entry = preg_replace("/^RestoreSnapShotDialog_/","",$name);
1400         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1401         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1402         $this->snapDialog->display_restore_dialog = true;
1403       }
1405       /* Restore one of the already deleted objects */
1406       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1407           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1408         $once = false;
1409         $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1410         $this->snapDialog->set_snapshot_bases($baseSuffixe);
1411         $this->snapDialog->display_restore_dialog      = true;
1412         $this->snapDialog->display_all_removed_objects  = true;
1413       }
1415       /* Restore selected snapshot */
1416       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1417         $once = false;
1418         $entry = preg_replace("/^RestoreSnapShot_/","",$name);
1419         $entry = base64_decode(trim(preg_replace("/_[xy]$/","",$entry)));
1420         if(!empty($entry)){
1421           $this->restore_snapshot($entry);
1422           $this->snapDialog = NULL;
1423         }
1424       }
1425     }
1427     /* Create a new snapshot requested, check
1428        the given attributes and create the snapshot*/
1429     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1430       $this->snapDialog->save_object();
1431       $msgs = $this->snapDialog->check();
1432       if(count($msgs)){
1433         foreach($msgs as $msg){
1434           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
1435         }
1436       }else{
1437         $this->dn =  $this->snapDialog->dn;
1438         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1439         $this->snapDialog = NULL;
1440       }
1441     }
1443     /* Restore is requested, restore the object with the posted dn .*/
1444     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1445     }
1447     if(isset($_POST['CancelSnapshot'])){
1448       $this->snapDialog = NULL;
1449     }
1451     if(is_object($this->snapDialog )){
1452       $this->snapDialog->save_object();
1453       return($this->snapDialog->execute());
1454     }
1455   }
1458   static function plInfo()
1459   {
1460     return array();
1461   }
1464   function set_acl_base($base)
1465   {
1466     $this->acl_base= $base;
1467   }
1470   function set_acl_category($category)
1471   {
1472     $this->acl_category= "$category/";
1473   }
1476   function acl_is_writeable($attribute,$skip_write = FALSE)
1477   {
1478     $ui= get_userinfo();
1479     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1480   }
1483   function acl_is_readable($attribute)
1484   {
1485     $ui= get_userinfo();
1486     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1487   }
1490   function acl_is_createable()
1491   {
1492     $ui= get_userinfo();
1493     return preg_match('/c/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1494   }
1497   function acl_is_removeable()
1498   {
1499     $ui= get_userinfo();
1500     return preg_match('/d/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1501   }
1504   function acl_is_moveable()
1505   {
1506     $ui= get_userinfo();
1507     return preg_match('/m/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1508   }
1511   function acl_have_any_permissions()
1512   {
1513   }
1516   function getacl($attribute,$skip_write= FALSE)
1517   {
1518     $ui= get_userinfo();
1519     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1520   }
1522   /* Get all allowed bases to move an object to or to create a new object.
1523      Idepartments also contains all base departments which lead to the allowed bases */
1524   function get_allowed_bases($category = "")
1525   {
1526     $ui = get_userinfo();
1527     $deps = array();
1529     /* Set category */ 
1530     if(empty($category)){
1531       $category = $this->acl_category.get_class($this);
1532     }
1534     /* Is this a new object ? Or just an edited existing object */
1535     if(!$this->initially_was_account && $this->is_account){
1536       $new = true;
1537     }else{
1538       $new = false;
1539     }
1541     $cat_bases = $ui->get_module_departments(preg_replace("/\/.*$/","",$category));
1542     foreach($this->config->idepartments as $dn => $name){
1543       
1544       if(!in_array_ics($dn,$cat_bases)){
1545         continue;
1546       }
1547       
1548       $acl = $ui->get_permissions($dn,$category);
1549       if($new && preg_match("/c/",$acl)){
1550         $deps[$dn] = $name;
1551       }elseif(!$new && preg_match("/m/",$acl)){
1552         $deps[$dn] = $name;
1553       }
1554     }
1556     /* Add current base */      
1557     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1558       $deps[$this->base] = $this->config->idepartments[$this->base];
1559     }else{
1560       trigger_error("No default base found in class ".get_class($this).". ".$this->base);
1561     }
1562     return($deps);
1563   }
1566   /* This function modifies object acls too, if an object is moved.
1567    *  $old_dn   specifies the actually used dn
1568    *  $new_dn   specifies the destiantion dn
1569    */
1570   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1571   {
1572     /* Check if old_dn is empty. This should never happen */
1573     if(empty($old_dn) || empty($new_dn)){
1574       trigger_error("Failed to check acl dependencies, wrong dn given.");
1575       return;
1576     }
1578     /* Update userinfo if necessary */
1579     $ui = session::get('ui');
1580     if($ui->dn == $old_dn){
1581       $ui->dn = $new_dn;
1582       session::set('ui',$ui);
1583       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current user dn from '".$old_dn."' to '".$new_dn."'");
1584     }
1586     /* Object was moved, ensure that all acls will be moved too */
1587     if($new_dn != $old_dn && $old_dn != "new"){
1589       /* get_ldap configuration */
1590       $update = array();
1591       $ldap = $this->config->get_ldap_link();
1592       $ldap->cd ($this->config->current['BASE']);
1593       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*))",array("cn","gosaAclEntry"));
1594       while($attrs = $ldap->fetch()){
1596         $acls = array();
1598         /* Walk through acls */
1599         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1601           /* Reset vars */
1602           $found = false;
1604           /* Get Acl parts */
1605           $acl_parts = split(":",$attrs['gosaAclEntry'][$i]);
1607           /* Get every single member for this acl */  
1608           $members = array();  
1609           if(preg_match("/,/",$acl_parts[2])){
1610             $members = split(",",$acl_parts[2]);
1611           }else{
1612             $members = array($acl_parts[2]);
1613           } 
1614       
1615           /* Check if member match current dn */
1616           foreach($members as $key => $member){
1617             $member = base64_decode($member);
1618             if($member == $old_dn){
1619               $found = true;
1620               $members[$key] = base64_encode($new_dn);
1621             }
1622           } 
1623          
1624           /* Create new member string */ 
1625           $new_members = "";
1626           foreach($members as $member){
1627             $new_members .= $member.",";
1628           }
1629           $new_members = preg_replace("/,$/","",$new_members);
1630           $acl_parts[2] = $new_members;
1631         
1632           /* Reconstruckt acl entry */
1633           $acl_str  ="";
1634           foreach($acl_parts as $t){
1635            $acl_str .= $t.":";
1636           }
1637           $acl_str = preg_replace("/:$/","",$acl_str);
1638        }
1640        /* Acls for this object must be adjusted */
1641        if($found){
1643           $debug_info=  _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1644                   $old_dn."</b><br>&nbsp;-"._("to")."&nbsp;<b>".$new_dn."</b><br>";
1645           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1647           $update[$attrs['dn']] =array();
1648           foreach($acls as $acl){
1649             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1650           }
1651         }
1652       }
1654       /* Write updated acls */
1655       foreach($update as $dn => $attrs){
1656         $ldap->cd($dn);
1657         $ldap->modify($attrs);
1658       }
1659     }
1660   }
1662   
1664   /* This function enables the entry Serial ID check.
1665    * If an entry was edited while we have edited the entry too,
1666    *  an error message will be shown. 
1667    * To configure this check correctly read the FAQ.
1668    */    
1669   function enable_CSN_check()
1670   {
1671     $this->CSN_check_active =TRUE;
1672     $this->entryCSN = getEntryCSN($this->dn);
1673   }
1676   /*! \brief  Prepares the plugin to be used for multiple edit
1677    *          Update plugin attributes with given array of attribtues.
1678    *  @param  array   Array with attributes that must be updated.
1679    */
1680   function init_multiple_support($attrs,$all)
1681   {
1682     $ldap= $this->config->get_ldap_link();
1683     $this->multi_attrs    = $attrs;
1684     $this->multi_attrs_all= $all;
1686     /* Copy needed attributes */
1687     foreach ($this->attributes as $val){
1688       $found= array_key_ics($val, $this->multi_attrs);
1689       if ($found != ""){
1690         if(isset($this->multi_attrs["$found"][0])){
1691           $this->$val= $this->multi_attrs["$found"][0];
1692         }
1693       }
1694     }
1695   }
1697  
1698   /*! \brief  Enables multiple support for this plugin
1699    */
1700   function enable_multiple_support()
1701   {
1702     $this->ignore_account = TRUE;
1703     $this->multiple_support_active = TRUE;
1704   }
1707   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1708       @return array Cotaining all mdofied values. 
1709    */
1710   function get_multi_edit_values()
1711   {
1712     $ret = array();
1713     foreach($this->attributes as $attr){
1714       if(in_array($attr,$this->multi_boxes)){
1715         $ret[$attr] = $this->$attr;
1716       }
1717     }
1718     return($ret);
1719   }
1721   
1722   /*! \brief  Update class variables with values collected by multiple edit.
1723    */
1724   function set_multi_edit_values($attrs)
1725   {
1726     foreach($attrs as $name => $value){
1727       $this->$name = $value;
1728     }
1729   }
1732   /*! \brief execute plugin
1734     Generates the html output for this node
1735    */
1736   function multiple_execute()
1737   {
1738     /* This one is empty currently. Fabian - please fill in the docu code */
1739     session::set('current_class_for_help',get_class($this));
1741     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1742     session::set('LOCK_VARS_TO_USE',array());
1743     session::set('LOCK_VARS_USED',array());
1744     
1745     return("Multiple edit is currently not implemented for this plugin.");
1746   }
1749   /*! \brief   Save HTML posted data to object for multiple edit
1750    */
1751   function multiple_save_object()
1752   {
1753     if(empty($this->entryCSN) && $this->CSN_check_active){
1754       $this->entryCSN = getEntryCSN($this->dn);
1755     }
1757     /* Save values to object */
1758     $this->multi_boxes = array();
1759     foreach ($this->attributes as $val){
1760   
1761       /* Get selected checkboxes from multiple edit */
1762       if(isset($_POST["use_".$val])){
1763         $this->multi_boxes[] = $val;
1764       }
1766       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
1768         /* Check for modifications */
1769         if (get_magic_quotes_gpc()) {
1770           $data= stripcslashes($_POST["$val"]);
1771         } else {
1772           $data= $this->$val = $_POST["$val"];
1773         }
1774         if ($this->$val != $data){
1775           $this->is_modified= TRUE;
1776         }
1777     
1778         /* IE post fix */
1779         if(isset($data[0]) && $data[0] == chr(194)) {
1780           $data = "";  
1781         }
1782         $this->$val= $data;
1783       }
1784     }
1785   }
1788   /*! \brief  Returns all attributes of this plugin, 
1789                to be able to detect multiple used attributes 
1790                in multi_plugg::detect_multiple_used_attributes().
1791       @return array Attributes required for intialization of multi_plug
1792    */
1793   public function get_multi_init_values()
1794   {
1795     $attrs = $this->attrs;
1796     return($attrs);
1797   }
1800   /*! \brief  Check given values in multiple edit
1801       @return array Error messages
1802    */
1803   function multiple_check()
1804   {
1805     $message = plugin::check();
1806     return($message);
1807   }
1810 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1811 ?>