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