Code

ac449d59fd60bd5ee5bcbe84d1d1894f0554c608
[gosa.git] / include / class_plugin.inc
1 <?php
2 /*
3    This code is part of GOsa (https://gosa.gonicus.de)
4    Copyright (C) 2003  Cajus Pollmeier
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
21 /*! \brief   The plugin base class
22   \author  Cajus Pollmeier <pollmeier@gonicus.de>
23   \version 2.00
24   \date    24.07.2003
26   This is the base class for all plugins. It can be used standalone or
27   can be included by the tabs class. All management should be done 
28   within this class. Extend your plugins from this class.
29  */
31 class plugin
32 {
33   /*!
34     \brief Reference to parent object
36     This variable is used when the plugin is included in tabs
37     and keeps reference to the tab class. Communication to other
38     tabs is possible by 'name'. So the 'fax' plugin can ask the
39     'userinfo' plugin for the fax number.
41     \sa tab
42    */
43   var $parent= NULL;
45   /*!
46     \brief Configuration container
48     Access to global configuration
49    */
50   var $config= NULL;
52   /*!
53     \brief Mark plugin as account
55     Defines whether this plugin is defined as an account or not.
56     This has consequences for the plugin to be saved from tab
57     mode. If it is set to 'FALSE' the tab will call the delete
58     function, else the save function. Should be set to 'TRUE' if
59     the construtor detects a valid LDAP object.
61     \sa plugin::plugin()
62    */
63   var $is_account= FALSE;
64   var $initially_was_account= FALSE;
66   /*!
67     \brief Mark plugin as template
69     Defines whether we are creating a template or a normal object.
70     Has conseqences on the way execute() shows the formular and how
71     save() puts the data to LDAP.
73     \sa plugin::save() plugin::execute()
74    */
75   var $is_template= FALSE;
76   var $ignore_account= FALSE;
77   var $is_modified= FALSE;
79   /*!
80     \brief Represent temporary LDAP data
82     This is only used internally.
83    */
84   var $attrs= array();
87   /*!
88     \brief Used standard values
90     dn
91    */
92   var $dn= "";
93   var $uid= "";
94   var $sn= "";
95   var $givenName= "";
96   var $acl= "*none*";
97   var $dialog= FALSE;
99   /* attribute list for save action */
100   var $attributes= array();
101   var $objectclasses= array();
102   var $new= TRUE;
103   var $saved_attributes= array();
105   /*! \brief plugin constructor
107     If 'dn' is set, the node loads the given 'dn' from LDAP
109     \param dn Distinguished name to initialize plugin from
110     \sa plugin()
111    */
112   function plugin ($config, $dn= NULL)
113   {
114     /* Configuration is fine, allways */
115     $this->config= $config;     
116     $this->dn= $dn;
118     /* Handle new accounts, don't read information from LDAP */
119     if ($dn == "new"){
120       return;
121     }
123     /* Get LDAP descriptor */
124     $ldap= $this->config->get_ldap_link();
125     if ($dn != NULL){
127       /* Load data to 'attrs' and save 'dn' */
128       $ldap->cat ($dn);
129       $this->attrs= $ldap->fetch();
131       /* Copy needed attributes */
132       foreach ($this->attributes as $val){
133         #if (isset($this->attrs["$val"][0])){
134         $found= array_key_ics($val, $this->attrs);
135         if ($found != ""){
136           $this->$val= $this->attrs["$found"][0];
137         }
138       }
140       /* Set the template flag according to the existence of objectClass
141          gosaUserTemplate */
142       if (isset($this->attrs['objectClass'])){
143         if (in_array ("gosaUserTemplate", $this->attrs['objectClass'])){
144           $this->is_template= TRUE;
145           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
146               "found", "Template check");
147         }
148       }
150       /* Is Account? */
151       error_reporting(0);
152       $found= TRUE;
153       foreach ($this->objectclasses as $obj){
154         if (preg_match('/top/i', $obj)){
155           continue;
156         }
157         if (!isset($this->attrs['objectClass']) || !in_array_ics ($obj, $this->attrs['objectClass'])){
158           $found= FALSE;
159           break;
160         }
161       }
162       error_reporting(E_ALL);
163       if ($found){
164         $this->is_account= TRUE;
165         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
166             "found", "Object check");
167       }
169       /* Prepare saved attributes */
170       $this->saved_attributes= $this->attrs;
171       foreach ($this->saved_attributes as $index => $value){
172         if (preg_match('/^[0-9]+$/', $index)){
173           unset($this->saved_attributes[$index]);
174           continue;
175         }
176         if (!in_array($index, $this->attributes) && $index != "objectClass"){
177           unset($this->saved_attributes[$index]);
178           continue;
179         }
180         if ($this->saved_attributes[$index]["count"] == 1){
181           $tmp= $this->saved_attributes[$index][0];
182           unset($this->saved_attributes[$index]);
183           $this->saved_attributes[$index]= $tmp;
184           continue;
185         }
187         unset($this->saved_attributes["$index"]["count"]);
188       }
189     }
191     /* Save initial account state */
192     $this->initially_was_account= $this->is_account;
193   }
195   /*! \brief execute plugin
197     Generates the html output for this node
198    */
199   function execute()
200   {
201     # This one is empty currently. Fabian - please fill in the docu code
202     $_SESSION['current_class_for_help'] = get_class($this);
203   }
205   /* remove object from parent */
206   function remove_from_parent()
207   {
208     /* include global link_info */
209     $ldap= $this->config->get_ldap_link();
211     /* Get current objectClasses in order to add the required ones */
212     $ldap->cat($this->dn);
213     $tmp= $ldap->fetch ();
214     if (isset($tmp['objectClass'])){
215       $oc= $tmp['objectClass'];
216     } else {
217       $oc= array("count" => 0);
218     }
220     /* Remove objectClasses from entry */
221     $ldap->cd($this->dn);
222     $this->attrs= array();
223     $this->attrs['objectClass']= array();
224     for ($i= 0; $i<$oc["count"]; $i++){
225       if (!in_array_ics($oc[$i], $this->objectclasses)){
226         $this->attrs['objectClass'][]= $oc[$i];
227       }
228     }
230     /* Unset attributes from entry */
231     foreach ($this->attributes as $val){
232       $this->attrs["$val"]= array();
233     }
235     /* Unset account info */
236     $this->is_account= FALSE;
238     /* Do not write in plugin base class, this must be done by
239        children, since there are normally additional attribs,
240        lists, etc. */
241     /*
242        $ldap->modify($this->attrs);
243      */
244   }
247   /* Save data to object */
248   function save_object()
249   {
250     /* Save values to object */
251     foreach ($this->attributes as $val){
252       if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
253         /* Check for modifications */
254         if (get_magic_quotes_gpc()) {
255           $data= stripcslashes($_POST["$val"]);
256         } else {
257           $data= $this->$val = $_POST["$val"];
258         }
259         if ($this->$val != $data){
260           $this->is_modified= TRUE;
261         }
262     
263         /* Okay, how can I explain this fix ... 
264          * In firefox, disabled option fields aren't selectable ... but in IE you can select these fileds. 
265          * So IE posts these 'unselectable' option, with value = chr(194) 
266          * chr(194) seems to be the &nbsp; in between the ...option>&nbsp;</option.. because there is no value=".." specified in these option fields  
267          * This &nbsp; was added for W3c compliance, but now causes these ... ldap errors ... 
268          * So we set these Fields to ""; a normal empty string, and we can check these values in plugin::check() again ...
269          */
270         if(isset($data[0]) && $data[0] == chr(194)) {
271           $data = "";  
272         }
273         $this->$val= $data;
274       }
275     }
276   }
279   /* Save data to LDAP, depending on is_account we save or delete */
280   function save()
281   {
282     /* include global link_info */
283     $ldap= $this->config->get_ldap_link();
285     /* Start with empty array */
286     $this->attrs= array();
288     /* Get current objectClasses in order to add the required ones */
289     $ldap->cat($this->dn);
290     
291     $tmp= $ldap->fetch ();
292     
293     if (isset($tmp['objectClass'])){
294       $oc= $tmp["objectClass"];
295       $this->new= FALSE;
296     } else {
297       $oc= array("count" => 0);
298       $this->new= TRUE;
299     }
301     /* Load (minimum) attributes, add missing ones */
302     $this->attrs['objectClass']= $this->objectclasses;
303     for ($i= 0; $i<$oc["count"]; $i++){
304       if (!in_array_ics($oc[$i], $this->objectclasses)){
305         $this->attrs['objectClass'][]= $oc[$i];
306       }
307     }
309     /* Copy standard attributes */
310     foreach ($this->attributes as $val){
311       if ($this->$val != ""){
312         $this->attrs["$val"]= $this->$val;
313       } elseif (!$this->new) {
314         $this->attrs["$val"]= array();
315       }
316     }
318   }
320   function cleanup()
321   {
322     /* Clean up */
323     foreach ($this->attrs as $index => $value){
324       if (is_array($this->attrs[$index]) && count($this->attrs[$index]) == 0 && !isset($this->saved_attributes[$index])){
325         unset ($this->attrs[$index]);
326         continue;
327       }
329       if (!is_array($this->attrs[$index]) && isset($this->saved_attributes[$index])
330           && !is_array($this->saved_attributes[$index]) && $value == $this->saved_attributes[$index]){
331         unset ($this->attrs[$index]);
332         continue;
333       }
335       /* Array checks */
336       if(is_array($this->attrs[$index]) && isset($this->saved_attributes[$index]) && is_array($this->saved_attributes[$index])){
338           /* Different number of elements, so this attribute has changed 
339              We must do this, because array_diff only shows differnces between 
340               array1 -> array2 
341             and not 
342               array2 -> array1  
343            */
344           if(count($this->attrs[$index])!= count($this->saved_attributes[$index])){
345             continue; 
346           }elseif(
348           /* Same number of elements, so we must check if all elements contain the same value 
349            */
350             count(
351               array_diff(
352                 array_change_key_case(
353                   array_flip(
354                     $this->attrs[$index]),
355                   CASE_UPPER),
356                 array_change_key_case(
357                   array_flip(
358                     $this->saved_attributes[$index]),
359                   CASE_UPPER)
360                 )
361               ) ==0 
362             ){
363           unset ($this->attrs[$index]);
364           continue;
365           }
366       }
367     
368       /* Check for this combination, one value is an array and one is string.
369          Both contain the same value (nothing changed). 
370       
371         Example : check for
372           $this->attrs['name']= "test";
373           $this->saved_attributes['name'][0]= "test";
374       
375         noting changed, but one is string and one is array;
376       */ 
377       if(is_array($this->attrs[$index])&&  count($this->attrs[$index])==1 && isset($this->saved_attributes[$index]) && (!is_array($this->saved_attributes[$index])) && $this->attrs[$index][0] == $this->saved_attributes[$index]){
378         unset ($this->attrs[$index]);
379       }
380     }
382     #######################################################
383     ; echo "--- DEBUG: changes ---<b>".get_class($this)."</b><br>"                   ;
384     ; print_a ($this->attrs)                              ;
385     ; if (count($this->attrs)==0)echo "<b>Skipped</b><br>";
386     #######################################################
387   }
389   /* Check formular input */
390   function check()
391   {
392     $message= array();
393     return ($message);
394   }
396   /* Adapt from template, using 'dn' */
397   function adapt_from_template($dn)
398   {
399     /* Include global link_info */
400     $ldap= $this->config->get_ldap_link();
402     /* Load requested 'dn' to 'attrs' */
403     $ldap->cat ($dn);
404     $this->attrs= $ldap->fetch();
406     /* Walk through attributes */
407     foreach ($this->attributes as $val){
409       if (isset($this->attrs["$val"][0])){
411         /* If attribute is set, replace dynamic parts: 
412            %sn, %givenName and %uid. Fill these in our local variables. */
413         $value= $this->attrs["$val"][0];
415         foreach (array("sn", "givenName", "uid") as $repl){
416           if (preg_match("/%$repl/i", $value)){
417             $value= preg_replace ("/%$repl/i", $this->parent->$repl, $value);
418           }
419         }
420         $this->$val= $value;
421       }
422     }
424     /* Is Account? */
425     $found= TRUE;
426     foreach ($this->objectclasses as $obj){
427       if (preg_match('/top/i', $obj)){
428         continue;
429       }
430       if (!in_array_ics ($obj, $this->attrs['objectClass'])){
431         $found= FALSE;
432         break;
433       }
434     }
435     if ($found){
436       $this->is_account= TRUE;
437     }
438   }
440   /* Indicate whether a password change is needed or not */
441   function password_change_needed()
442   {
443     return FALSE;
444   }
446   /* Show header message for tab dialogs */
447   function show_header($button_text, $text, $disabled= FALSE)
448   {
449     if ($disabled == TRUE){
450       $state= "disabled";
451     } else {
452       $state= "";
453     }
454     $display= "<table summary=\"\" width=\"100%\"><tr>\n<td colspan=2><p><b>$text</b></p>\n";
455     $display.= "<input type=submit value=\"$button_text\" name=\"modify_state\" ".
456       chkacl($this->acl, "all")." ".$state.
457       "><p class=\"seperator\">&nbsp;</p></td></tr></table>";
459     return($display);
460   }
462   function postcreate()
463   {
464     /* Find postcreate entries for this class */
465     $command= search_config($this->config->data['MENU'], get_class($this), "POSTCREATE");
466     if ($command == "" && isset($this->config->data['TABS'])){
467       $command= search_config($this->config->data['TABS'], get_class($this), "POSTCREATE");
468     }
470     if ($command != ""){
471       /* Walk through attribute list */
472       foreach ($this->attributes as $attr){
473         if (!is_array($this->$attr)){
474           $command= preg_replace("/%$attr/", $this->$attr, $command);
475         }
476       }
477       $command= preg_replace("/%dn/", $this->dn, $command);
478       if (check_command($command)){
479         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
480             $command, "Execute");
482         exec($command);
483       } else {
484         $message= sprintf(_("Command '%s', specified as POSTCREATE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
485         print_red ($message);
486       }
487     }
488   }
490   function postmodify()
491   {
492     /* Find postcreate entries for this class */
493     $command= search_config($this->config->data['MENU'], get_class($this), "POSTMODIFY");
494     if ($command == "" && isset($this->config->data['TABS'])){
495       $command= search_config($this->config->data['TABS'], get_class($this), "POSTMODIFY");
496     }
498     if ($command != ""){
499       /* Walk through attribute list */
500       foreach ($this->attributes as $attr){
501         if (!is_array($this->$attr)){
502           $command= preg_replace("/%$attr/", $this->$attr, $command);
503         }
504       }
505       $command= preg_replace("/%dn/", $this->dn, $command);
506       if (check_command($command)){
507         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
508             $command, "Execute");
510         exec($command);
511       } else {
512         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, get_class($this));
513         print_red ($message);
514       }
515     }
516   }
518   function postremove()
519   {
520     /* Find postremove entries for this class */
521     $command= search_config($this->config->data['MENU'], get_class($this), "POSTREMOVE");
522     if ($command == "" && isset($this->config->data['TABS'])){
523       $command= search_config($this->config->data['TABS'], get_class($this), "POSTREMOVE");
524     }
526     if ($command != ""){
527       /* Walk through attribute list */
528       foreach ($this->attributes as $attr){
529         if (!is_array($this->$attr)){
530           $command= preg_replace("/%$attr/", $this->$attr, $command);
531         }
532       }
533       $command= preg_replace("/%dn/", $this->dn, $command);
534       if (check_command($command)){
535         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
536             $command, "Execute");
538         exec($command);
539       } else {
540         $message= sprintf(_("Command '%s', specified as POSTREMOVE for plugin '%s' doesn't seem to exist."), $command, get_class($this));
541         print_red ($message);
542       }
543     }
544   }
546   /* Create unique DN */
547   function create_unique_dn($attribute, $base)
548   {
549     $ldap= $this->config->get_ldap_link();
550     $base= preg_replace("/^,*/", "", $base);
552     /* Try to use plain entry first */
553     $dn= "$attribute=".$this->$attribute.",$base";
554     $ldap->cat ($dn);
555     if (!$ldap->fetch()){
556       return ($dn);
557     }
559     /* Look for additional attributes */
560     foreach ($this->attributes as $attr){
561       if ($attr == $attribute || $this->$attr == ""){
562         continue;
563       }
565       $dn= "$attribute=".$this->$attribute."+$attr=".$this->$attr.",$base";
566       $ldap->cat ($dn);
567       if (!$ldap->fetch()){
568         return ($dn);
569       }
570     }
572     /* None found */
573     return ("none");
574   }
576   function rebind($ldap, $referral)
577   {
578     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
579     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
580       $this->error = "Success";
581       $this->hascon=true;
582       $this->reconnect= true;
583       return (0);
584     } else {
585       $this->error = "Could not bind to " . $credentials['ADMIN'];
586       return NULL;
587     }
588   }
590   /* This is a workaround function. */
591   function copy($src_dn, $dst_dn)
592   {
593     /* Rename dn in possible object groups */
594     $ldap= $this->config->get_ldap_link();
595     $ldap->search('(&(objectClass=gosaGroupOfNames)(member='.$src_dn.'))',
596         array('cn'));
597     while ($attrs= $ldap->fetch()){
598       $og= new ogroup($this->config, $ldap->getDN());
599       unset($og->member[$src_dn]);
600       $og->member[$dst_dn]= $dst_dn;
601       $og->save ();
602     }
604     $ldap->cat($dst_dn);
605     $attrs= $ldap->fetch();
606     if (count($attrs)){
607       trigger_error("Trying to overwrite $dst_dn, which already exists.",
608           E_USER_WARNING);
609       return (FALSE);
610     }
612     $ldap->cat($src_dn);
613     $attrs= array();
614     $attrs= $ldap->fetch();
615     if (!count($attrs)){
616       trigger_error("Trying to move $src_dn, which does not seem to exist.",
617           E_USER_WARNING);
618       return (FALSE);
619     }
621     /* Grummble. This really sucks. PHP ldap doesn't support rdn stuff. */
622     $ds= ldap_connect($this->config->current['SERVER']);
623     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
624     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['REFERRAL'])) {
625       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
626     }
628     $r=ldap_bind($ds,$this->config->current['ADMIN'], $this->config->current['PASSWORD']);
629     error_reporting (0);
630     $sr=ldap_read($ds, $src_dn, "objectClass=*");
632     /* Fill data from LDAP */
633     $new= array();
634     if ($sr) {
635       $ei=ldap_first_entry($ds, $sr);
636       if ($ei) {
637         foreach($attrs as $attr => $val){
638           if ($info = ldap_get_values_len($ds, $ei, $attr)){
639             for ($i= 0; $i<$info['count']; $i++){
640               if ($info['count'] == 1){
641                 $new[$attr]= $info[$i];
642               } else {
643                 $new[$attr][]= $info[$i];
644               }
645             }
646           }
647         }
648       }
649     }
651     /* close conncetion */
652     error_reporting (E_ALL);
653     ldap_unbind($ds);
655     /* Adapt naming attribute */
656     $dst_name= preg_replace("/^([^=]+)=.*$/", "\\1", $dst_dn);
657     $dst_val = preg_replace("/^[^=]+=([^,+]+).*,.*$/", "\\1", $dst_dn);
658     $new[$dst_name]= $dst_val;
660     /* Save copy */
661     $ldap->connect();
662     $ldap->cd($this->config->current['BASE']);
663     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dst_dn));
664     $ldap->cd($dst_dn);
665     $ldap->add($new);
667     if ($ldap->error != "Success"){
668       trigger_error("Trying to save $dst_dn failed.",
669           E_USER_WARNING);
670       return(FALSE);
671     }
673     return (TRUE);
674   }
677   function move($src_dn, $dst_dn)
678   {
679     /* Copy source to destination */
680     if (!$this->copy($src_dn, $dst_dn)){
681       return (FALSE);
682     }
684     /* Delete source */
685     $ldap= $this->config->get_ldap_link();
686     $ldap->rmdir($src_dn);
687     if ($ldap->error != "Success"){
688       trigger_error("Trying to delete $src_dn failed.",
689           E_USER_WARNING);
690       return (FALSE);
691     }
693     return (TRUE);
694   }
697   /* Move/Rename complete trees */
698   function recursive_move($src_dn, $dst_dn)
699   {
700     /* Check if the destination entry exists */
701     $ldap= $this->config->get_ldap_link();
703     /* Check if destination exists - abort */
704     $ldap->cat($dst_dn);
705     if ($ldap->fetch()){
706       trigger_error("recursive_move $dst_dn already exists.",
707           E_USER_WARNING);
708       return (FALSE);
709     }
711     /* Perform a search for all objects to be moved */
712     $objects= array();
713     $ldap->cd($src_dn);
714     $ldap->search("(objectClass=*)", array("dn"));
715     while($attrs= $ldap->fetch()){
716       $dn= $attrs['dn'];
717       $objects[$dn]= strlen($dn);
718     }
720     /* Sort objects by indent level */
721     asort($objects);
722     reset($objects);
724     /* Copy objects from small to big indent levels by replacing src_dn by dst_dn */
725     foreach ($objects as $object => $len){
726       $src= $object;
727       $dst= preg_replace("/$src_dn$/", "$dst_dn", $object);
728       if (!$this->copy($src, $dst)){
729         return (FALSE);
730       }
731     }
733     /* Remove src_dn */
734     $ldap->cd($src_dn);
735     $ldap->recursive_remove();
736     return (TRUE);
737   }
740   function handle_post_events($mode)
741   {
742     switch ($mode){
743       case "add":
744         $this->postcreate();
745       break;
747       case "modify":
748         $this->postmodify();
749       break;
751       case "remove":
752         $this->postremove();
753       break;
754     }
755   }
759 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
760 ?>