Code

closes #411
[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         }
218         if (isset($this->saved_attributes[$index][0]) && $this->saved_attributes[$index]["count"] == 1){
219           $tmp= $this->saved_attributes[$index][0];
220           unset($this->saved_attributes[$index]);
221           $this->saved_attributes[$index]= $tmp;
222           continue;
223         }
225         unset($this->saved_attributes["$index"]["count"]);
226       }
227       if(isset($this->attrs['gosaUnitTag'])){
228         $this->saved_attributes['gosaUnitTag'] = $this->attrs['gosaUnitTag'][0];
229       }
230     }
232     /* Save initial account state */
233     $this->initially_was_account= $this->is_account;
234   }
237   /*! \brief execute plugin
239     Generates the html output for this node
240    */
241   function execute()
242   {
243     /* This one is empty currently. Fabian - please fill in the docu code */
244     session::set('current_class_for_help',get_class($this));
246     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
247     session::set('LOCK_VARS_TO_USE',array());
248     session::set('LOCK_VARS_USED',array());
249   }
251   /*! \brief execute plugin
252      Removes object from parent
253    */
254   function remove_from_parent()
255   {
256     /* include global link_info */
257     $ldap= $this->config->get_ldap_link();
259     /* Get current objectClasses in order to add the required ones */
260     $ldap->cat($this->dn);
261     $tmp= $ldap->fetch ();
262     $oc= array();
263     if (isset($tmp['objectClass'])){
264       $oc= $tmp['objectClass'];
265       unset($oc['count']);
266     }
268     /* Remove objectClasses from entry */
269     $ldap->cd($this->dn);
270     $this->attrs= array();
271     $this->attrs['objectClass']= array_remove_entries($this->objectclasses,$oc);
273     /* Unset attributes from entry */
274     foreach ($this->attributes as $val){
275       $this->attrs["$val"]= array();
276     }
278     /* Unset account info */
279     $this->is_account= FALSE;
281     /* Do not write in plugin base class, this must be done by
282        children, since there are normally additional attribs,
283        lists, etc. */
284     /*
285        $ldap->modify($this->attrs);
286      */
287   }
290   /*! \brief   Save HTML posted data to object 
291    */
292   function save_object()
293   {
294     /* Update entry CSN if it is empty. */
295     if(empty($this->entryCSN) && $this->CSN_check_active){
296       $this->entryCSN = getEntryCSN($this->dn);
297     }
299     /* Save values to object */
300     foreach ($this->attributes as $val){
301       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
302         /* Check for modifications */
303         if (get_magic_quotes_gpc()) {
304           $data= stripcslashes($_POST["$val"]);
305         } else {
306           $data= $this->$val = $_POST["$val"];
307         }
308         if ($this->$val != $data){
309           $this->is_modified= TRUE;
310         }
311     
312         /* Okay, how can I explain this fix ... 
313          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
314          * So IE posts these 'unselectable' option, with value = chr(194) 
315          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
316          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
317          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
318          */
319         if(isset($data[0]) && $data[0] == chr(194)) {
320           $data = "";  
321         }
322         $this->$val= $data;
323       }
324     }
325   }
328   /* Save data to LDAP, depending on is_account we save or delete */
329   function save()
330   {
331     /* include global link_info */
332     $ldap= $this->config->get_ldap_link();
334     /* Save all plugins */
335     $this->entryCSN = "";
337     /* Start with empty array */
338     $this->attrs= array();
340     /* Get current objectClasses in order to add the required ones */
341     $ldap->cat($this->dn);
342     
343     $tmp= $ldap->fetch ();
345     $oc= array();
346     if (isset($tmp['objectClass'])){
347       $oc= $tmp["objectClass"];
348       $this->is_new= FALSE;
349       unset($oc['count']);
350     } else {
351       $this->is_new= TRUE;
352     }
354     /* Load (minimum) attributes, add missing ones */
355     $this->attrs['objectClass']= gosa_array_merge($oc,$this->objectclasses);
357     /* Copy standard attributes */
358     foreach ($this->attributes as $val){
359       if ($this->$val != ""){
360         $this->attrs["$val"]= $this->$val;
361       } elseif (!$this->is_new) {
362         $this->attrs["$val"]= array();
363       }
364     }
366     /* Handle tagging */
367     $this->tag_attrs($this->attrs);
368   }
371   function cleanup()
372   {
373     foreach ($this->attrs as $index => $value){
374       
375       /* Convert arrays with one element to non arrays, if the saved
376          attributes are no array, too */
377       if (is_array($this->attrs[$index]) && 
378           count ($this->attrs[$index]) == 1 &&
379           isset($this->saved_attributes[$index]) &&
380           !is_array($this->saved_attributes[$index])){
381           
382         $tmp= $this->attrs[$index][0];
383         $this->attrs[$index]= $tmp;
384       }
386       /* Remove emtpy arrays if they do not differ */
387       if (is_array($this->attrs[$index]) &&
388           count($this->attrs[$index]) == 0 &&
389           !isset($this->saved_attributes[$index])){
390           
391         unset ($this->attrs[$index]);
392         continue;
393       }
395       /* Remove single attributes that do not differ */
396       if (!is_array($this->attrs[$index]) &&
397           isset($this->saved_attributes[$index]) &&
398           !is_array($this->saved_attributes[$index]) &&
399           $this->attrs[$index] == $this->saved_attributes[$index]){
401         unset ($this->attrs[$index]);
402         continue;
403       }
405       /* Remove arrays that do not differ */
406       if (is_array($this->attrs[$index]) && 
407           isset($this->saved_attributes[$index]) &&
408           is_array($this->saved_attributes[$index])){
409           
410         if (!array_differs($this->attrs[$index],$this->saved_attributes[$index])){
411           unset ($this->attrs[$index]);
412           continue;
413         }
414       }
415     }
417     /* Update saved attributes and ensure that next cleanups will be successful too */
418     foreach($this->attrs as $name => $value){
419       $this->saved_attributes[$name] = $value;
420     }
421   }
423   /* Check formular input */
424   function check()
425   {
426     $message= array();
428     /* Skip if we've no config object */
429     if (!isset($this->config) || !is_object($this->config)){
430       return $message;
431     }
433     /* Find hooks entries for this class */
434     $command= $this->config->search(get_class($this), "CHECK", array('menu', 'tabs'));
436     if ($command != ""){
438       if (!check_command($command)){
439         $message[]= msgPool::cmdnotfound("CHECK", get_class($this));
440       } else {
442         /* Generate "ldif" for check hook */
443         $ldif= "dn: $this->dn\n";
444         
445         /* ... objectClasses */
446         foreach ($this->objectclasses as $oc){
447           $ldif.= "objectClass: $oc\n";
448         }
449         
450         /* ... attributes */
451         foreach ($this->attributes as $attr){
452           if ($this->$attr == ""){
453             continue;
454           }
455           if (is_array($this->$attr)){
456             foreach ($this->$attr as $val){
457               $ldif.= "$attr: $val\n";
458             }
459           } else {
460               $ldif.= "$attr: ".$this->$attr."\n";
461           }
462         }
464         /* Append empty line */
465         $ldif.= "\n";
467         /* Feed "ldif" into hook and retrieve result*/
468         $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
469         $fh= proc_open($command, $descriptorspec, $pipes);
470         if (is_resource($fh)) {
471           fwrite ($pipes[0], $ldif);
472           fclose($pipes[0]);
473           
474           $result= stream_get_contents($pipes[1]);
475           if ($result != ""){
476             $message[]= $result;
477           }
478           
479           fclose($pipes[1]);
480           fclose($pipes[2]);
481           proc_close($fh);
482         }
483       }
485     }
487     /* Check entryCSN */
488     if($this->CSN_check_active){
489       $current_csn = getEntryCSN($this->dn);
490       if($current_csn != $this->entryCSN && !empty($this->entryCSN) && !empty($current_csn)){
491         $this->entryCSN = $current_csn;
492         $message[] = _("The object has changed since opened in GOsa. All changes that may be done by others get lost if you save this entry!");
493       }
494     }
495     return ($message);
496   }
498   /* Adapt from template, using 'dn' */
499   function adapt_from_template($dn, $skip= array())
500   {
501     /* Include global link_info */
502     $ldap= $this->config->get_ldap_link();
504     /* Load requested 'dn' to 'attrs' */
505     $ldap->cat ($dn);
506     $this->attrs= $ldap->fetch();
508     /* Walk through attributes */
509     foreach ($this->attributes as $val){
511       /* Skip the ones in skip list */
512       if (in_array($val, $skip)){
513         continue;
514       }
516       if (isset($this->attrs["$val"][0])){
518         /* If attribute is set, replace dynamic parts: 
519            %sn, %givenName and %uid. Fill these in our local variables. */
520         $value= $this->attrs["$val"][0];
522         foreach (array("sn", "givenName", "uid") as $repl){
523           if (preg_match("/%$repl/i", $value)){
524             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
525           }
526         }
527         $this->$val= $value;
528       }
529     }
531     /* Is Account? */
532     $found= TRUE;
533     foreach ($this->objectclasses as $obj){
534       if (preg_match('/top/i', $obj)){
535         continue;
536       }
537       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
538         $found= FALSE;
539         break;
540       }
541     }
542     if ($found){
543       $this->is_account= TRUE;
544     }
545   }
547   /* Indicate whether a password change is needed or not */
548   function password_change_needed()
549   {
550     return FALSE;
551   }
554   /* Show header message for tab dialogs */
555   function show_enable_header($button_text, $text, $disabled= FALSE)
556   {
557     if (($disabled == TRUE) || (!$this->acl_is_createable())){
558       $state= "disabled";
559     } else {
560       $state= "";
561     }
562     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
563     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
564       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
566     return($display);
567   }
570   /* Show header message for tab dialogs */
571   function show_disable_header($button_text, $text, $disabled= FALSE)
572   {
573     if (($disabled == TRUE) || !$this->acl_is_removeable()){
574       $state= "disabled";
575     } else {
576       $state= "";
577     }
578     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
579     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".$state.
580       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
582     return($display);
583   }
586   /* Show header message for tab dialogs */
587   function show_header($button_text, $text, $disabled= FALSE)
588   {
589     echo "FIXME: show_header should be replaced by show_disable_header and show_enable_header<br>";
590     if ($disabled == TRUE){
591       $state= "disabled";
592     } else {
593       $state= "";
594     }
595     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
596     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
597       ($this->acl_is_createable()?'':'disabled')." ".$state.
598       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
600     return($display);
601   }
604   function postcreate($add_attrs= array())
605   {
606     /* Find postcreate entries for this class */
607     $command= $this->config->search(get_class($this), "POSTCREATE",array('menu', 'tabs'));
609     if ($command != ""){
611       /* Walk through attribute list */
612       foreach ($this->attributes as $attr){
613         if (!is_array($this->$attr)){
614           $add_attrs[$attr] = $this->$attr;
615         }
616       }
617       $add_attrs['dn']=$this->dn;
619       $tmp = array();
620       foreach($add_attrs as $name => $value){
621         $tmp[$name] =  strlen($name);
622       }
623       arsort($tmp);
624       
625       /* Additional attributes */
626       foreach ($tmp as $name => $len){
627         $value = $add_attrs[$name];
628         $command= preg_replace("/%$name/", "$value ", $command);
629       }
631       if (check_command($command)){
632         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
633             $command, "Execute");
635         exec($command);
636       } else {
637         $message[]= msgPool::cmdnotfound("POSTCREATE", get_class($this));
638         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
639       }
640     }
641   }
643   function postmodify($add_attrs= array())
644   {
645     /* Find postcreate entries for this class */
646     $command= $this->config->search(get_class($this), "POSTMODIFY",array('menu','tabs'));
648     if ($command != ""){
650       /* Walk through attribute list */
651       foreach ($this->attributes as $attr){
652         if (!is_array($this->$attr)){
653           $add_attrs[$attr] = $this->$attr;
654         }
655       }
656       $add_attrs['dn']=$this->dn;
658       $tmp = array();
659       foreach($add_attrs as $name => $value){
660         $tmp[$name] =  strlen($name);
661       }
662       arsort($tmp);
663       
664       /* Additional attributes */
665       foreach ($tmp as $name => $len){
666         $value = $add_attrs[$name];
667         $command= preg_replace("/%$name/", "$value ", $command);
668       }
670       if (check_command($command)){
671         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,$command, "Execute");
672         exec($command);
673       } else {
674         $message[]= msgPool::cmdnotfound("POSTMODIFY", get_class($this));
675         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
676       }
677     }
678   }
680   function postremove($add_attrs= array())
681   {
682     /* Find postremove entries for this class */
683     $command= $this->config->search(get_class($this), "POSTREMOVE",array('menu','tabs'));
684     if ($command != ""){
686       /* Walk through attribute list */
687       foreach ($this->attributes as $attr){
688         if (!is_array($this->$attr)){
689           $add_attrs[$attr] = $this->$attr;
690         }
691       }
692       $add_attrs['dn']=$this->dn;
694       $tmp = array();
695       foreach($add_attrs as $name => $value){
696         $tmp[$name] =  strlen($name);
697       }
698       arsort($tmp);
699       
700       /* Additional attributes */
701       foreach ($tmp as $name => $len){
702         $value = $add_attrs[$name];
703         $command= preg_replace("/%$name/", "$value ", $command);
704       }
706       if (check_command($command)){
707         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
708             $command, "Execute");
710         exec($command);
711       } else {
712         $message[]= msgPool::cmdnotfound("POSTREMOVE", get_class($this));
713         msg_dialog::display(_("Error"), $message, ERROR_DIALOG);
714       }
715     }
716   }
718   /* Create unique DN */
719   function create_unique_dn($attribute, $base)
720   {
721     $ldap= $this->config->get_ldap_link();
722     $base= preg_replace("/^,*/", "", $base);
724     /* Try to use plain entry first */
725     $dn= "$attribute=".$this->$attribute.",$base";
726     $ldap->cat ($dn, array('dn'));
727     if (!$ldap->fetch()){
728       return ($dn);
729     }
731     /* Look for additional attributes */
732     foreach ($this->attributes as $attr){
733       if ($attr == $attribute || $this->$attr == ""){
734         continue;
735       }
737       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
738       $ldap->cat ($dn, array('dn'));
739       if (!$ldap->fetch()){
740         return ($dn);
741       }
742     }
744     /* None found */
745     return ("none");
746   }
748   function rebind($ldap, $referral)
749   {
750     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
751     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
752       $this->error = "Success";
753       $this->hascon=true;
754       $this->reconnect= true;
755       return (0);
756     } else {
757       $this->error = "Could not bind to " . $credentials['ADMIN'];
758       return NULL;
759     }
760   }
763   /* Recursively copy ldap object */
764   function _copy($src_dn,$dst_dn)
765   {
766     $ldap=$this->config->get_ldap_link();
767     $ldap->cat($src_dn);
768     $attrs= $ldap->fetch();
770     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
771     $ds= ldap_connect($this->config->current['SERVER']);
772     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
773     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
774       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
775     }
777     $r=ldap_bind($ds,$this->config->current['ADMIN'], $this->config->current['PASSWORD']);
778     $sr=ldap_read($ds, @LDAP::fix($src_dn), "objectClass=*");
780     /* Fill data from LDAP */
781     $new= array();
782     if ($sr) {
783       $ei=ldap_first_entry($ds, $sr);
784       if ($ei) {
785         foreach($attrs as $attr => $val){
786           if ($info = @ldap_get_values_len($ds, $ei, $attr)){
787             for ($i= 0; $i<$info['count']; $i++){
788               if ($info['count'] == 1){
789                 $new[$attr]= $info[$i];
790               } else {
791                 $new[$attr][]= $info[$i];
792               }
793             }
794           }
795         }
796       }
797     }
799     /* close conncetion */
800     ldap_unbind($ds);
802     /* Adapt naming attribute */
803     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
804     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
805     $new[$dst_name]= @LDAP::fix($dst_val);
807     /* Check if this is a department.
808      * If it is a dep. && there is a , override in his ou 
809      *  change \2C to , again, else this entry can't be saved ...
810      */
811     if((isset($new['ou'])) &&( preg_match("/\\,/",$new['ou']))){
812       $new['ou'] = preg_replace("/\\\\,/",",",$new['ou']);
813     }
815     /* Save copy */
816     $ldap->connect();
817     $ldap->cd($this->config->current['BASE']);
818     
819     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
821     /* FAIvariable=.../..., cn=.. 
822         could not be saved, because the attribute FAIvariable was different to 
823         the dn FAIvariable=..., cn=... */
824     if(in_array_ics("FAIdebconfInfo",$new['objectClass'])){
825       $new['FAIvariable'] = $ldap->fix($new['FAIvariable']);
826     }
827     $ldap->cd($dst_dn);
828     $ldap->add($new);
830     if (!$ldap->success()){
831       trigger_error("Trying to save $dst_dn failed.",
832           E_USER_WARNING);
833       return(FALSE);
834     }
835     return(TRUE);
836   }
839   /* This is a workaround function. */
840   function copy($src_dn, $dst_dn)
841   {
842     /* Rename dn in possible object groups */
843     $ldap= $this->config->get_ldap_link();
844     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.@LDAP::prepare4filter($src_dn).'))',
845         array('cn'));
846     while ($attrs= $ldap->fetch()){
847       $og= new ogroup($this->config, $ldap->getDN());
848       unset($og->member[$src_dn]);
849       $og->member[$dst_dn]= $dst_dn;
850       $og->save ();
851     }
853     $ldap->cat($dst_dn);
854     $attrs= $ldap->fetch();
855     if (count($attrs)){
856       trigger_error("Trying to overwrite ".@LDAP::fix($dst_dn).", which already exists.",
857           E_USER_WARNING);
858       return (FALSE);
859     }
861     $ldap->cat($src_dn);
862     $attrs= $ldap->fetch();
863     if (!count($attrs)){
864       trigger_error("Trying to move ".@LDAP::fix($src_dn).", which does not seem to exist.",
865           E_USER_WARNING);
866       return (FALSE);
867     }
869     $ldap->cd($src_dn);
870     $ldap->search("objectClass=*",array("dn"));
871     while($attrs = $ldap->fetch()){
872       $src = $attrs['dn'];
873       $dst = preg_replace("/".normalizePreg($src_dn)."$/",$dst_dn,$attrs['dn']);
874       $this->_copy($src,$dst);
875     }
876     return (TRUE);
877   }
880   function move($src_dn, $dst_dn)
881   {
882     /* Do not copy if only upper- lowercase has changed */
883     if(strtolower($src_dn) == strtolower($dst_dn)){
884       return(TRUE);
885     }
887     /* Copy source to destination */
888     if (!$this->copy($src_dn, $dst_dn)){
889       return (FALSE);
890     }
892     /* Delete source */
893     $ldap= $this->config->get_ldap_link();
894     $ldap->rmdir_recursive($src_dn);
895     if (!$ldap->success()){
896       trigger_error("Trying to delete $src_dn failed.",
897           E_USER_WARNING);
898       return (FALSE);
899     }
901     return (TRUE);
902   }
905   /* Move/Rename complete trees */
906   function recursive_move($src_dn, $dst_dn)
907   {
908     /* Check if the destination entry exists */
909     $ldap= $this->config->get_ldap_link();
911     /* Check if destination exists - abort */
912     $ldap->cat($dst_dn, array('dn'));
913     if ($ldap->fetch()){
914       trigger_error("recursive_move $dst_dn already exists.",
915           E_USER_WARNING);
916       return (FALSE);
917     }
919     $this->copy($src_dn, $dst_dn);
921     /* Remove src_dn */
922     $ldap->cd($src_dn);
923     $ldap->recursive_remove($src_dn);
924     return (TRUE);
925   }
928   function handle_post_events($mode, $add_attrs= array())
929   {
930     switch ($mode){
931       case "add":
932         $this->postcreate($add_attrs);
933       break;
935       case "modify":
936         $this->postmodify($add_attrs);
937       break;
939       case "remove":
940         $this->postremove($add_attrs);
941       break;
942     }
943   }
946   function saveCopyDialog(){
947   }
950   function getCopyDialog(){
951     return(array("string"=>"","status"=>""));
952   }
955   function PrepareForCopyPaste($source)
956   {
957     $todo = $this->attributes;
958     if(isset($this->CopyPasteVars)){
959       $todo = array_merge($todo,$this->CopyPasteVars);
960     }
962     if(count($this->objectclasses)){
963       $this->is_account = TRUE;
964       foreach($this->objectclasses as $class){
965         if(!in_array($class,$source['objectClass'])){
966           $this->is_account = FALSE;
967         }
968       }
969     }
971     foreach($todo as $var){
972       if (isset($source[$var])){
973         if(isset($source[$var]['count'])){
974           if($source[$var]['count'] > 1){
975             $this->$var = array();
976             $tmp = array();
977             for($i = 0 ; $i < $source[$var]['count']; $i++){
978               $tmp = $source[$var][$i];
979             }
980             $this->$var = $tmp;
981           }else{
982             $this->$var = $source[$var][0];
983           }
984         }else{
985           $this->$var= $source[$var];
986         }
987       }
988     }
989   }
991   function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
992   {
993     /* Skip tagging? 
994        If this is called from departmentGeneric, we have to skip this
995         tagging procedure. 
996      */
997     if($this->skipTagging){
998       return;
999     }
1001     /* No dn? Self-operation... */
1002     if ($dn == ""){
1003       $dn= $this->dn;
1005       /* No tag? Find it yourself... */
1006       if ($tag == ""){
1007         $len= strlen($dn);
1009         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
1010         $relevant= array();
1011         foreach ($this->config->adepartments as $key => $ntag){
1013           /* This one is bigger than our dn, its not relevant... */
1014           if ($len <= strlen($key)){
1015             continue;
1016           }
1018           /* This one matches with the latter part. Break and don't fix this entry */
1019           if (preg_match('/(^|,)'.normalizePreg($key).'$/', $dn)){
1020             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
1021             $relevant[strlen($key)]= $ntag;
1022             continue;
1023           }
1025         }
1027         /* If we've some relevant tags to set, just get the longest one */
1028         if (count($relevant)){
1029           ksort($relevant);
1030           $tmp= array_keys($relevant);
1031           $idx= end($tmp);
1032           $tag= $relevant[$idx];
1033           $this->gosaUnitTag= $tag;
1034         }
1035       }
1036     }
1037   
1038     /* Remove tags that may already be here... */
1039     remove_objectClass("gosaAdministrativeUnitTag", $at);
1040     if (isset($at['gosaUnitTag'])){
1041         unset($at['gosaUnitTag']);
1042     }
1044     /* Set tag? */
1045     if ($tag != ""){
1046       add_objectClass("gosaAdministrativeUnitTag", $at);
1047       $at['gosaUnitTag']= $tag;
1048     }
1050     /* Initially this object was tagged. 
1051        - But now, it is no longer inside a tagged department. 
1052        So force the remove of the tag.
1053        (objectClass was already removed obove)
1054      */
1055     if($tag == "" && $this->gosaUnitTag){
1056       $at['gosaUnitTag'] = array();
1057     }
1058   }
1061   /* Add possibility to stop remove process */
1062   function allow_remove()
1063   {
1064     $reason= "";
1065     return $reason;
1066   }
1069   /* Create a snapshot of the current object */
1070   function create_snapshot($type= "snapshot", $description= array())
1071   {
1073     /* Check if snapshot functionality is enabled */
1074     if(!$this->snapshotEnabled()){
1075       return;
1076     }
1078     /* Get configuration from gosa.conf */
1079     $tmp = $this->config->current;
1081     /* Create lokal ldap connection */
1082     $ldap= $this->config->get_ldap_link();
1083     $ldap->cd($this->config->current['BASE']);
1085     /* check if there are special server configurations for snapshots */
1086     if(!isset($tmp['SNAPSHOT_SERVER'])){
1088       /* Source and destination server are both the same, just copy source to dest obj */
1089       $ldap_to      = $ldap;
1090       $snapldapbase = $this->config->current['BASE'];
1092     }else{
1093       $server         = $tmp['SNAPSHOT_SERVER'];
1094       $user           = $tmp['SNAPSHOT_USER'];
1095       $password       = $tmp['SNAPSHOT_PASSWORD'];
1096       $snapldapbase   = $tmp['SNAPSHOT_BASE'];
1098       $ldap_to        = new ldapMultiplexer(new LDAP($user,$password, $server));
1099       $ldap_to -> cd($snapldapbase);
1101       if (!$ldap_to->success()){
1102         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1103       }
1105     }
1107     /* check if the dn exists */ 
1108     if ($ldap->dn_exists($this->dn)){
1110       /* Extract seconds & mysecs, they are used as entry index */
1111       list($usec, $sec)= explode(" ", microtime());
1113       /* Collect some infos */
1114       $base           = $this->config->current['BASE'];
1115       $snap_base      = $tmp['SNAPSHOT_BASE'];
1116       $base_of_object = preg_replace ('/^[^,]+,/i', '', $this->dn);
1117       $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1119       /* Create object */
1120 #$data             = preg_replace('/^dn:.*\n/', '', $ldap->gen_ldif($this->dn,"(!(objectClass=gosaDepartment))"));
1121       $data             = $ldap->gen_ldif($this->dn,"(&(!(objectClass=gosaDepartment))(!(objectClass=FAIclass)))");
1122       $newName          = preg_replace("/\./", "", $sec."-".$usec);
1123       $target= array();
1124       $target['objectClass']            = array("top", "gosaSnapshotObject");
1125       $target['gosaSnapshotData']       = gzcompress($data, 6);
1126       $target['gosaSnapshotType']       = $type;
1127       $target['gosaSnapshotDN']         = $this->dn;
1128       $target['description']            = $description;
1129       $target['gosaSnapshotTimestamp']  = $newName;
1131       /* Insert the new snapshot 
1132          But we have to check first, if the given gosaSnapshotTimestamp
1133          is already used, in this case we should increment this value till there is 
1134          an unused value. */ 
1135       $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1136       $ldap_to->cat($new_dn);
1137       while($ldap_to->count()){
1138         $ldap_to->cat($new_dn);
1139         $newName = preg_replace("/\./", "", $sec."-".($usec++));
1140         $new_dn                           = "gosaSnapshotTimestamp=".$newName.",".$new_base;
1141         $target['gosaSnapshotTimestamp']  = $newName;
1142       } 
1144       /* Inset this new snapshot */
1145       $ldap_to->cd($snapldapbase);
1146       $ldap_to->create_missing_trees($snapldapbase);
1147       $ldap_to->create_missing_trees($new_base);
1148       $ldap_to->cd($new_dn);
1149       $ldap_to->add($target);
1150       if (!$ldap_to->success()){
1151         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $new_dn, LDAP_ADD, get_class()));
1152       }
1154       if (!$ldap->success()){
1155         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $new_base, "", get_class()));
1156       }
1158     }
1159   }
1161   function remove_snapshot($dn)
1162   {
1163     $ui       = get_userinfo();
1164     $old_dn   = $this->dn; 
1165     $this->dn = $dn;
1166     $ldap = $this->config->get_ldap_link();
1167     $ldap->cd($this->config->current['BASE']);
1168     $ldap->rmdir_recursive($dn);
1169     $this->dn = $old_dn;
1170   }
1173   /* returns true if snapshots are enabled, and false if it is disalbed
1174      There will also be some errors psoted, if the configuration failed */
1175   function snapshotEnabled()
1176   {
1177     $tmp = $this->config->current;
1178     if(isset($tmp['ENABLE_SNAPSHOT'])){
1179       if (preg_match("/^true$/i", $tmp['ENABLE_SNAPSHOT']) || preg_match("/yes/i", $tmp['ENABLE_SNAPSHOT'])){
1181         /* Check if the snapshot_base is defined */
1182         if(!isset($tmp['SNAPSHOT_BASE'])){
1183           msg_dialog::display(_("Configuration error"), sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."),"SNAPSHOT_BASE"), ERROR_DIALOG);
1184           return(FALSE);
1185         }
1187         /* check if there are special server configurations for snapshots */
1188         if(isset($tmp['SNAPSHOT_SERVER'])){
1190           /* check if all required vars are available to create a new ldap connection */
1191           $missing = "";
1192           foreach(array("SNAPSHOT_SERVER","SNAPSHOT_USER","SNAPSHOT_PASSWORD","SNAPSHOT_BASE") as $var){
1193             if(!isset($tmp[$var])){
1194               $missing .= $var." ";
1195               msg_dialog::display(_("Configuration error"), sprintf(_("The snapshot functionality is enabled, but the required variable '%s' is not set."), $missing), ERROR_DIALOG);
1196               return(FALSE);
1197             }
1198           }
1199         }
1200         return(TRUE);
1201       }
1202     }
1203     return(FALSE);
1204   }
1207   /* Return available snapshots for the given base 
1208    */
1209   function Available_SnapsShots($dn,$raw = false)
1210   {
1211     if(!$this->snapshotEnabled()) return(array());
1213     /* Create an additional ldap object which
1214        points to our ldap snapshot server */
1215     $ldap= $this->config->get_ldap_link();
1216     $ldap->cd($this->config->current['BASE']);
1217     $cfg= &$this->config->current;
1219     /* check if there are special server configurations for snapshots */
1221     if(isset($cfg['SERVER']) && isset($cfg['SNAPSHOT_SERVER']) && $cfg['SERVER'] == $cfg['SNAPSHOT_SERVER']){
1222       $ldap_to    = $ldap;
1223     }elseif(isset($cfg['SNAPSHOT_SERVER'])){
1224       $server       = $cfg['SNAPSHOT_SERVER'];
1225       $user         = $cfg['SNAPSHOT_USER'];
1226       $password     = $cfg['SNAPSHOT_PASSWORD'];
1227       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1229       $ldap_to      = new ldapMultiplexer(new LDAP($user,$password, $server));
1230       $ldap_to -> cd ($snapldapbase);
1231       if (!$ldap_to->success()){
1232         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1233       }
1234     }else{
1235       $ldap_to    = $ldap;
1236     }
1238     /* Prepare bases and some other infos */
1239     $base           = $this->config->current['BASE'];
1240     $snap_base      = $cfg['SNAPSHOT_BASE'];
1241     $base_of_object = preg_replace ('/^[^,]+,/i', '', $dn);
1242     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1243     $tmp            = array(); 
1245     /* Fetch all objects with  gosaSnapshotDN=$dn */
1246     $ldap_to->cd($new_base);
1247     $ldap_to->ls("(&(objectClass=gosaSnapshotObject)(gosaSnapshotDN=".$dn."))",$new_base,
1248         array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description")); 
1250     /* Put results into a list and add description if missing */
1251     while($entry = $ldap_to->fetch()){ 
1252       if(!isset($entry['description'][0])){
1253         $entry['description'][0]  = "";
1254       }
1255       $tmp[] = $entry; 
1256     }
1258     /* Return the raw array, or format the result */
1259     if($raw){
1260       return($tmp);
1261     }else{  
1262       $tmp2 = array();
1263       foreach($tmp as $entry){
1264         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1265       }
1266     }
1267     return($tmp2);
1268   }
1271   function getAllDeletedSnapshots($base_of_object,$raw = false)
1272   {
1273     if(!$this->snapshotEnabled()) return(array());
1275     /* Create an additional ldap object which
1276        points to our ldap snapshot server */
1277     $ldap= $this->config->get_ldap_link();
1278     $ldap->cd($this->config->current['BASE']);
1279     $cfg= &$this->config->current;
1281     /* check if there are special server configurations for snapshots */
1282     if(isset($cfg['SNAPSHOT_SERVER'])){
1283       $server       = $cfg['SNAPSHOT_SERVER'];
1284       $user         = $cfg['SNAPSHOT_USER'];
1285       $password     = $cfg['SNAPSHOT_PASSWORD'];
1286       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1287       $ldap_to      = new ldapMultiplexer(new LDAP($user,$password, $server));
1288       $ldap_to->cd ($snapldapbase);
1289       if (!$ldap_to->success()){
1290         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1291       }
1292     }else{
1293       $ldap_to    = $ldap;
1294     }
1296     /* Prepare bases */ 
1297     $base           = $this->config->current['BASE'];
1298     $snap_base      = $cfg['SNAPSHOT_BASE'];
1299     $new_base       = preg_replace("/".normalizePreg($base)."$/","",$base_of_object).$snap_base;
1301     /* Fetch all objects and check if they do not exist anymore */
1302     $ui = get_userinfo();
1303     $tmp = array();
1304     $ldap_to->cd($new_base);
1305     $ldap_to->ls("(objectClass=gosaSnapshotObject)",$new_base,array("gosaSnapshotType","gosaSnapshotTimestamp","gosaSnapshotDN","description"));
1306     while($entry = $ldap_to->fetch()){
1308       $chk =  str_replace($new_base,"",$entry['dn']);
1309       if(preg_match("/,ou=/",$chk)) continue;
1311       if(!isset($entry['description'][0])){
1312         $entry['description'][0]  = "";
1313       }
1314       $tmp[] = $entry; 
1315     }
1317     /* Check if entry still exists */
1318     foreach($tmp as $key => $entry){
1319       $ldap->cat($entry['gosaSnapshotDN'][0]);
1320       if($ldap->count()){
1321         unset($tmp[$key]);
1322       }
1323     }
1325     /* Format result as requested */
1326     if($raw) {
1327       return($tmp);
1328     }else{
1329       $tmp2 = array();
1330       foreach($tmp as $key => $entry){
1331         $tmp2[base64_encode($entry['dn'])] = $entry['description'][0]; 
1332       }
1333     }
1334     return($tmp2);
1335   } 
1338   /* Restore selected snapshot */
1339   function restore_snapshot($dn)
1340   {
1341     if(!$this->snapshotEnabled()) return(array());
1343     $ldap= $this->config->get_ldap_link();
1344     $ldap->cd($this->config->current['BASE']);
1345     $cfg= &$this->config->current;
1347     /* check if there are special server configurations for snapshots */
1348     if(isset($cfg['SNAPSHOT_SERVER'])){
1349       $server       = $cfg['SNAPSHOT_SERVER'];
1350       $user         = $cfg['SNAPSHOT_USER'];
1351       $password     = $cfg['SNAPSHOT_PASSWORD'];
1352       $snapldapbase = $cfg['SNAPSHOT_BASE'];
1353       $ldap_to      = new ldapMultiplexer(new LDAP($user,$password, $server));
1354       $ldap_to->cd ($snapldapbase);
1355       if (!$ldap_to->success()){
1356         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap_to->get_error(), $snapldapbase, "", get_class()));
1357       }
1358     }else{
1359       $ldap_to    = $ldap;
1360     }
1362     /* Get the snapshot */ 
1363     $ldap_to->cat($dn);
1364     $restoreObject = $ldap_to->fetch();
1366     /* Prepare import string */
1367     $data  = gzuncompress($ldap_to->get_attribute($dn,'gosaSnapshotData'));
1369     /* Import the given data */
1370     $err = "";
1371     $ldap->import_complete_ldif($data,$err,false,false);
1372     if (!$ldap->success()){
1373       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, "", get_class()));
1374     }
1375   }
1378   function showSnapshotDialog($base,$baseSuffixe)
1379   {
1380     $once = true;
1381     foreach($_POST as $name => $value){
1383       /* Create a new snapshot, display a dialog */
1384       if(preg_match("/^CreateSnapShotDialog_/",$name) && $once){
1385         $once = false;
1386         $entry = preg_replace("/^CreateSnapShotDialog_/","",$name);
1387         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1388         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1389       }
1391       /* Restore a snapshot, display a dialog with all snapshots of the current object */
1392       if(preg_match("/^RestoreSnapShotDialog_/",$name) && $once){
1393         $once = false;
1394         $entry = preg_replace("/^RestoreSnapShotDialog_/","",$name);
1395         $entry = base64_decode(preg_replace("/_[xy]$/","",$entry));
1396         $this->snapDialog = new SnapShotDialog($this->config,$entry,$this);
1397         $this->snapDialog->display_restore_dialog = true;
1398       }
1400       /* Restore one of the already deleted objects */
1401       if(((isset($_POST['menu_action']) && $_POST['menu_action'] == "RestoreDeletedSnapShot") 
1402           || preg_match("/^RestoreDeletedSnapShot_/",$name)) && $once){
1403         $once = false;
1404         $this->snapDialog = new SnapShotDialog($this->config,"",$this);
1405         $this->snapDialog->set_snapshot_bases($baseSuffixe);
1406         $this->snapDialog->display_restore_dialog      = true;
1407         $this->snapDialog->display_all_removed_objects  = true;
1408       }
1410       /* Restore selected snapshot */
1411       if(preg_match("/^RestoreSnapShot_/",$name) && $once){
1412         $once = false;
1413         $entry = preg_replace("/^RestoreSnapShot_/","",$name);
1414         $entry = base64_decode(trim(preg_replace("/_[xy]$/","",$entry)));
1415         if(!empty($entry)){
1416           $this->restore_snapshot($entry);
1417           $this->snapDialog = NULL;
1418         }
1419       }
1420     }
1422     /* Create a new snapshot requested, check
1423        the given attributes and create the snapshot*/
1424     if(isset($_POST['CreateSnapshot']) && is_object($this->snapDialog)){
1425       $this->snapDialog->save_object();
1426       $msgs = $this->snapDialog->check();
1427       if(count($msgs)){
1428         foreach($msgs as $msg){
1429           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
1430         }
1431       }else{
1432         $this->dn =  $this->snapDialog->dn;
1433         $this->create_snapshot("snapshot",$this->snapDialog->CurrentDescription);
1434         $this->snapDialog = NULL;
1435       }
1436     }
1438     /* Restore is requested, restore the object with the posted dn .*/
1439     if((isset($_POST['RestoreSnapshot'])) && (isset($_POST['SnapShot']))){
1440     }
1442     if(isset($_POST['CancelSnapshot'])){
1443       $this->snapDialog = NULL;
1444     }
1446     if(is_object($this->snapDialog )){
1447       $this->snapDialog->save_object();
1448       return($this->snapDialog->execute());
1449     }
1450   }
1453   static function plInfo()
1454   {
1455     return array();
1456   }
1459   function set_acl_base($base)
1460   {
1461     $this->acl_base= $base;
1462   }
1465   function set_acl_category($category)
1466   {
1467     $this->acl_category= "$category/";
1468   }
1471   function acl_is_writeable($attribute,$skip_write = FALSE)
1472   {
1473     $ui= get_userinfo();
1474     return preg_match('/w/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute, $skip_write));
1475   }
1478   function acl_is_readable($attribute)
1479   {
1480     $ui= get_userinfo();
1481     return preg_match('/r/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute));
1482   }
1485   function acl_is_createable()
1486   {
1487     $ui= get_userinfo();
1488     return preg_match('/c/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1489   }
1492   function acl_is_removeable()
1493   {
1494     $ui= get_userinfo();
1495     return preg_match('/d/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1496   }
1499   function acl_is_moveable()
1500   {
1501     $ui= get_userinfo();
1502     return preg_match('/m/', $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), '0'));
1503   }
1506   function acl_have_any_permissions()
1507   {
1508   }
1511   function getacl($attribute,$skip_write= FALSE)
1512   {
1513     $ui= get_userinfo();
1514     return  $ui->get_permissions($this->acl_base, $this->acl_category.get_class($this), $attribute,$skip_write);
1515   }
1517   /* Get all allowed bases to move an object to or to create a new object.
1518      Idepartments also contains all base departments which lead to the allowed bases */
1519   function get_allowed_bases($category = "")
1520   {
1521     $ui = get_userinfo();
1522     $deps = array();
1524     /* Set category */ 
1525     if(empty($category)){
1526       $category = $this->acl_category.get_class($this);
1527     }
1529     /* Is this a new object ? Or just an edited existing object */
1530     if(!$this->initially_was_account && $this->is_account){
1531       $new = true;
1532     }else{
1533       $new = false;
1534     }
1536     $cat_bases = $ui->get_module_departments(preg_replace("/\/.*$/","",$category));
1537     foreach($this->config->idepartments as $dn => $name){
1538       
1539       if(!in_array_ics($dn,$cat_bases)){
1540         continue;
1541       }
1542       
1543       $acl = $ui->get_permissions($dn,$category);
1544       if($new && preg_match("/c/",$acl)){
1545         $deps[$dn] = $name;
1546       }elseif(!$new && preg_match("/m/",$acl)){
1547         $deps[$dn] = $name;
1548       }
1549     }
1551     /* Add current base */      
1552     if(isset($this->base) && isset($this->config->idepartments[$this->base])){
1553       $deps[$this->base] = $this->config->idepartments[$this->base];
1554     }else{
1555       trigger_error("No default base found in class ".get_class($this).". ".$this->base);
1556     }
1557     return($deps);
1558   }
1561   /* This function modifies object acls too, if an object is moved.
1562    *  $old_dn   specifies the actually used dn
1563    *  $new_dn   specifies the destiantion dn
1564    */
1565   function update_acls($old_dn,$new_dn,$output_changes = FALSE)
1566   {
1567     /* Check if old_dn is empty. This should never happen */
1568     if(empty($old_dn) || empty($new_dn)){
1569       trigger_error("Failed to check acl dependencies, wrong dn given.");
1570       return;
1571     }
1573     /* Update userinfo if necessary */
1574     $ui = session::get('ui');
1575     if($ui->dn == $old_dn){
1576       $ui->dn = $new_dn;
1577       session::set('ui',$ui);
1578       new log("view","acl/".get_class($this),$this->dn,array(),"Updated current user dn from '".$old_dn."' to '".$new_dn."'");
1579     }
1581     /* Object was moved, ensure that all acls will be moved too */
1582     if($new_dn != $old_dn && $old_dn != "new"){
1584       /* get_ldap configuration */
1585       $update = array();
1586       $ldap = $this->config->get_ldap_link();
1587       $ldap->cd ($this->config->current['BASE']);
1588       $ldap->search("(&(objectClass=gosaAcl)(gosaAclEntry=*))",array("cn","gosaAclEntry"));
1589       while($attrs = $ldap->fetch()){
1591         $acls = array();
1593         /* Walk through acls */
1594         for($i = 0 ; $i <  $attrs['gosaAclEntry']['count'] ; $i ++ ){
1596           /* Reset vars */
1597           $found = false;
1599           /* Get Acl parts */
1600           $acl_parts = split(":",$attrs['gosaAclEntry'][$i]);
1602           /* Get every single member for this acl */  
1603           $members = array();  
1604           if(preg_match("/,/",$acl_parts[2])){
1605             $members = split(",",$acl_parts[2]);
1606           }else{
1607             $members = array($acl_parts[2]);
1608           } 
1609       
1610           /* Check if member match current dn */
1611           foreach($members as $key => $member){
1612             $member = base64_decode($member);
1613             if($member == $old_dn){
1614               $found = true;
1615               $members[$key] = base64_encode($new_dn);
1616             }
1617           } 
1618          
1619           /* Create new member string */ 
1620           $new_members = "";
1621           foreach($members as $member){
1622             $new_members .= $member.",";
1623           }
1624           $new_members = preg_replace("/,$/","",$new_members);
1625           $acl_parts[2] = $new_members;
1626         
1627           /* Reconstruckt acl entry */
1628           $acl_str  ="";
1629           foreach($acl_parts as $t){
1630            $acl_str .= $t.":";
1631           }
1632           $acl_str = preg_replace("/:$/","",$acl_str);
1633        }
1635        /* Acls for this object must be adjusted */
1636        if($found){
1638           $debug_info=  _("Changing ACL dn")."&nbsp;:&nbsp;<br>&nbsp;-"._("from")."&nbsp;<b>&nbsp;".
1639                   $old_dn."</b><br>&nbsp;-"._("to")."&nbsp;<b>".$new_dn."</b><br>";
1640           @DEBUG (DEBUG_ACL, __LINE__, __FUNCTION__, __FILE__,$debug_info,"ACL");
1642           $update[$attrs['dn']] =array();
1643           foreach($acls as $acl){
1644             $update[$attrs['dn']]['gosaAclEntry'][] = $acl;
1645           }
1646         }
1647       }
1649       /* Write updated acls */
1650       foreach($update as $dn => $attrs){
1651         $ldap->cd($dn);
1652         $ldap->modify($attrs);
1653       }
1654     }
1655   }
1657   
1659   /* This function enables the entry Serial ID check.
1660    * If an entry was edited while we have edited the entry too,
1661    *  an error message will be shown. 
1662    * To configure this check correctly read the FAQ.
1663    */    
1664   function enable_CSN_check()
1665   {
1666     $this->CSN_check_active =TRUE;
1667     $this->entryCSN = getEntryCSN($this->dn);
1668   }
1671   /*! \brief  Prepares the plugin to be used for multiple edit
1672    *          Update plugin attributes with given array of attribtues.
1673    *  @param  array   Array with attributes that must be updated.
1674    */
1675   function init_multiple_support($attrs,$all)
1676   {
1677     $ldap= $this->config->get_ldap_link();
1678     $this->multi_attrs    = $attrs;
1679     $this->multi_attrs_all= $all;
1681     /* Copy needed attributes */
1682     foreach ($this->attributes as $val){
1683       $found= array_key_ics($val, $this->multi_attrs);
1684       if ($found != ""){
1685         if(isset($this->multi_attrs["$found"][0])){
1686           $this->$val= $this->multi_attrs["$found"][0];
1687         }
1688       }
1689     }
1690   }
1692  
1693   /*! \brief  Enables multiple support for this plugin
1694    */
1695   function enable_multiple_support()
1696   {
1697     $this->ignore_account = TRUE;
1698     $this->multiple_support_active = TRUE;
1699   }
1702   /*! \brief  Returns all values that have been modfied in multiple edit mode.
1703       @return array Cotaining all mdofied values. 
1704    */
1705   function get_multi_edit_values()
1706   {
1707     $ret = array();
1708     foreach($this->attributes as $attr){
1709       if(in_array($attr,$this->multi_boxes)){
1710         $ret[$attr] = $this->$attr;
1711       }
1712     }
1713     return($ret);
1714   }
1716   
1717   /*! \brief  Update class variables with values collected by multiple edit.
1718    */
1719   function set_multi_edit_values($attrs)
1720   {
1721     foreach($attrs as $name => $value){
1722       $this->$name = $value;
1723     }
1724   }
1727   /*! \brief execute plugin
1729     Generates the html output for this node
1730    */
1731   function multiple_execute()
1732   {
1733     /* This one is empty currently. Fabian - please fill in the docu code */
1734     session::set('current_class_for_help',get_class($this));
1736     /* Reset Lock message POST/GET check array, to prevent perg_match errors*/
1737     session::set('LOCK_VARS_TO_USE',array());
1738     session::set('LOCK_VARS_USED',array());
1739     
1740     return("Multiple edit is currently not implemented for this plugin.");
1741   }
1744   /*! \brief   Save HTML posted data to object for multiple edit
1745    */
1746   function multiple_save_object()
1747   {
1748     if(empty($this->entryCSN) && $this->CSN_check_active){
1749       $this->entryCSN = getEntryCSN($this->dn);
1750     }
1752     /* Save values to object */
1753     $this->multi_boxes = array();
1754     foreach ($this->attributes as $val){
1755   
1756       /* Get selected checkboxes from multiple edit */
1757       if(isset($_POST["use_".$val])){
1758         $this->multi_boxes[] = $val;
1759       }
1761       if ($this->acl_is_writeable($val) && isset ($_POST["$val"])){
1763         /* Check for modifications */
1764         if (get_magic_quotes_gpc()) {
1765           $data= stripcslashes($_POST["$val"]);
1766         } else {
1767           $data= $this->$val = $_POST["$val"];
1768         }
1769         if ($this->$val != $data){
1770           $this->is_modified= TRUE;
1771         }
1772     
1773         /* IE post fix */
1774         if(isset($data[0]) && $data[0] == chr(194)) {
1775           $data = "";  
1776         }
1777         $this->$val= $data;
1778       }
1779     }
1780   }
1783   /*! \brief  Returns all attributes of this plugin, 
1784                to be able to detect multiple used attributes 
1785                in multi_plugg::detect_multiple_used_attributes().
1786       @return array Attributes required for intialization of multi_plug
1787    */
1788   public function get_multi_init_values()
1789   {
1790     $attrs = $this->attrs;
1791     return($attrs);
1792   }
1795   /*! \brief  Check given values in multiple edit
1796       @return array Error messages
1797    */
1798   function multiple_check()
1799   {
1800     $message = plugin::check();
1801     return($message);
1802   }
1805 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1806 ?>