Code

bdf658aab0de4f9ddbab1c229fd0c9ceac06d979
[gosa.git] / gosa-core / plugins / admin / departments / class_department.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 class department extends plugin
24 {
25   /* department attributes */
26   var $ou= "";
27   var $description= "";
28   var $base= "";
29   var $st= "";
30   var $l= "";
31   var $postalAddress= "";
32   var $businessCategory= "";
33   var $telephoneNumber= "";
34   var $facsimileTelephoneNumber= "";
35   var $is_administrational_unit= false;
36   var $gosaUnitTag= "";
37   var $view_logged = FALSE;
39   var $type ="organizationalUnit";
40   var $namingAttr = "ou";
42   /* Headpage attributes */
43   var $last_dep_sorting= "invalid";
44   var $departments= array();
45   var $must_be_tagged = false;
47   /* attribute list for save action */
48   var $attributes= array("ou", "description", "businessCategory", "st", "l", "postalAddress",
49                         "telephoneNumber", "facsimileTelephoneNumber", "gosaUnitTag", "manager");
51   /* Do not append the structural object classes here, they are added dynamically in the constructor */
52   var $objectclasses= array("top", "gosaDepartment");
53   var $structuralOC = array("organizationalUnit");
55   var $initially_was_tagged = false;
56   var $orig_base = "";
57   var $orig_ou = "";
58   var $baseSelector;
60   var $manager_enabled = FALSE;
61   var $manager_name ="";
62   var $manager ="";
64   function department (&$config, $dn)
65   {
66     /* Add the default structural obejct class 'locality' if this is a new entry
67      */
68     $ldap = $config->get_ldap_link();
69     $ldap->cd($config->current['BASE']);
70     if($dn == "" || $dn == "new" || !$ldap->dn_exists($dn)){
71       $this->objectclasses = array_merge($this->structuralOC,$this->objectclasses);
72     }else{
73       $ldap->cat($dn, array("structuralObjectClass"));
74       $attrs= $ldap->fetch();
75       if(isset($attrs['structuralObjectClass']['count'])){
76         for($i = 0 ; $i < $attrs['structuralObjectClass']['count'] ; $i++){
77           $this->objectclasses[] = $attrs['structuralObjectClass'][$i];
78         }
79       }else{
81         /* Could not detect structural object class for this object, fall back to the default 'locality'
82          */
83         $this->objectclasses = array_merge($this->structuralOC,$this->objectclasses);
84       }
85     }
86     $this->objectclasses = array_unique($this->objectclasses);
88     plugin::plugin($config, $dn);
89     $this->is_account= TRUE;
90     $this->ui= get_userinfo();
91     $this->dn= $dn;
92     $this->orig_dn= $dn;
94     /* Save current naming attribuet 
95      */
96     $nA      = $this->namingAttr;
97     $orig_nA = "orig_".$nA;
98     $this->$orig_nA = $this->$nA;
100     $this->config= $config;
102     /* Set base */
103     if ($this->dn == "new"){
104             $ui= get_userinfo();
105             if(session::is_set('CurrentMainBase')){
106                     $this->base = session::get('CurrentMainBase');
107             }else{
108                     $this->base= dn2base($ui->dn);
109             }
110     } else {
111             $this->base= preg_replace ("/^[^,]+,/", "", $this->dn);
112     }
114     $this->orig_base = $this->base;
116     /* Is administrational Unit? */
117     if ($dn != "new" && in_array_ics('gosaAdministrativeUnit', $this->attrs['objectClass'])){
118             $this->is_administrational_unit= true;
119             $this->initially_was_tagged = true;
120     }
122     /* Instanciate base selector */
123     $this->baseSelector= new baseSelector($this->get_allowed_bases(), $this->base);
124     $this->baseSelector->setSubmitButton(false);
125     $this->baseSelector->setHeight(300);
126     $this->baseSelector->update(true);
130     // If the 'manager' attribute is present in gosaDepartment allow to manage it.
131     $ldap = $this->config->get_ldap_link();
132     $ocs = $ldap->get_objectclasses();
133     if(isset($ocs['gosaDepartment']['MAY']) && in_array('manager', $ocs['gosaDepartment']['MAY'])){
134       $this->manager_enabled = TRUE;
136       // Detect the managers name
137       $this->manager_name = "";
138       $ldap = $this->config->get_ldap_link();
139       if(!empty($this->manager)){
140         $ldap->cat($this->manager, array('cn'));
141         if($ldap->count()){
142           $attrs = $ldap->fetch();
143           $this->manager_name = $attrs['cn'][0];
144         }else{
145           $this->manager_name = "("._("Unknown")."!): ".$this->manager;
146         }
147       }
148     }
149   }
151         function execute()
152         {
153                 /* Call parent execute */
154                 plugin::execute();
156     /* Log view */
157     if($this->is_account && !$this->view_logged){
158       $this->view_logged = TRUE;
159       new log("view","department/".get_class($this),$this->dn);
160     }
162                 /* Reload departments */
163                 $this->config->get_departments($this->dn);
164                 $this->config->make_idepartments();
165                 $smarty= get_smarty();
166     $smarty->assign("usePrototype", "true");
168     // Clear manager attribute if requested
169     if(preg_match("/ removeManager/i", " ".implode(array_keys($_POST),' ')." ")){
170       $this->manager = "";
171       $this->manager_name = "";
172     }
174     // Allow to manager manager attribute
175     if($this->manager_enabled){
177       // Allow to select a new inetOrgPersion:manager
178       if(preg_match("/ editManager/i", " ".implode(array_keys($_POST),' ')." ")){
179         $this->dialog = new singleUserSelect($this->config, get_userinfo());
180       }
181       if($this->dialog && count($this->dialog->detectPostActions())){
182         $users = $this->dialog->detectPostActions();
183         if(isset($users['targets']) && count($users['targets'])){
185           $headpage = $this->dialog->getHeadpage();
186           $dn = $users['targets'][0];
187           $attrs = $headpage->getEntry($dn);
188           $this->manager = $dn;
189           $this->manager_name = $attrs['cn'][0];
190           $this->dialog = NULL;
191         }
192       }
193       if(isset($_POST['add_users_cancel'])){
194         $this->dialog = NULL;
195       }
196       if($this->dialog) return($this->dialog->execute());
197     }
198     $smarty->assign("manager",$this->manager);
199     $smarty->assign("manager_name",$this->manager_name);
200     $smarty->assign("manager_enabled",$this->manager_enabled);
203     $tmp = $this->plInfo();
204     foreach($tmp['plProvidedAcls'] as $name => $translation){
205       $smarty->assign($name."ACL",$this->getacl($name));
206     }
208     /* Hide base selector, if this object represents the base itself 
209      */
210     $smarty->assign("is_root_dse", FALSE);
211     if($this->dn == $this->config->current['BASE']){
212       $smarty->assign("is_root_dse", TRUE);
213       $nA = $this->namingAttr."ACL";
214       $smarty->assign($nA,$this->getacl($this->namingAttr,TRUE));
215     }
217     /* Hide all departments, that are subtrees of this department */
218     $bases = $this->get_allowed_bases();
219     if(($this->dn == "new")||($this->dn == "")){
220             $tmp = $bases;
221     }else{
222             $tmp        = array();      
223             foreach($bases as $dn=>$base){
224                     /* Only attach departments which are not a subtree of this one */
225                     if(!preg_match("/".preg_quote($this->dn)."/",$dn)){
226                             $tmp[$dn]=$base;
227                     }
228             }
229     }
230     $this->baseSelector->setBases($tmp);
232     foreach ($this->attributes as $val){
233       $smarty->assign("$val", htmlentities($this->$val,ENT_COMPAT,'UTF-8'));
234     }
235     $smarty->assign("base", $this->baseSelector->render());
237     /* Set admin unit flag */
238     if ($this->is_administrational_unit) {
239       $smarty->assign("gosaUnitTag", "checked");
240     } else {
241       $smarty->assign("gosaUnitTag", "");
242     }
244     $smarty->assign("dep_type",$this->type);
245     
247     $dep_types = departmentManagement::get_support_departments();
248     $tpl ="";
249     foreach($dep_types as $key => $data){
250       if($data['OC'] == $this->type){
251         $tpl = $data['TPL'];
252         break;
253       }
254     }
255     if($tpl == "") {
256       trigger_error("No template specified for container type '".$this->type."', please update epartmentManagement::get_support_departments().");
257       $tpl = "generic.tpl";
258     }
259                 return($smarty->fetch (get_template_path($tpl, TRUE)));
260         }
262         function clear_fields()
263         {
264                 $this->dn   = "";
265                 $this->base = "";
267                 foreach ($this->attributes as $val){
268                         $this->$val= "";
269                 }
270         }
272         function remove_from_parent()
273         {
274                 $ldap= $this->config->get_ldap_link();
275                 $ldap->cd ($this->dn);
276                 $ldap->rmdir_recursive($this->dn);
277     new log("remove","department/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
278     if (!$ldap->success()){
279       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
280     }
282                 /* Optionally execute a command after we're done */
283                 $this->handle_post_events('remove');
284         }
286         function must_be_tagged()
287         {
288                 return $this->must_be_tagged;
289         }
291         /* Save data to object */
292         function save_object()
293         {       
294                 if (isset($_POST['dep_generic_posted'])){
296                         $nA = $this->namingAttr;
297                         $old_nA = $this->$nA;
301       /* Create a base backup and reset the
302          base directly after calling plugin::save_object();
303          Base will be set seperatly a few lines below */
304       $base_tmp = $this->base;
305       plugin::save_object();
306       $this->base = $base_tmp;
308                 /* Refresh base */
309                 if ($this->acl_is_moveable($this->base)){
310                         if (!$this->baseSelector->update()) {
311                                 msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
312                         }
313                         if ($this->base != $this->baseSelector->getBase()) {
314                                 $this->base= $this->baseSelector->getBase();
315                                 $this->is_modified= TRUE;
316                         }
317                 }
320       /* Save tagging flag */
321       if ($this->acl_is_writeable("gosaUnitTag")){
322         if (isset($_POST['is_administrational_unit'])){
323           $this->is_administrational_unit= true;
324         } else {
325           $this->is_administrational_unit= false;
326         }
327       }
329       /* If this is the root directory service entry then avoid
330          changing the naming attribute of this entry.
331        */
332       if($this->dn == $this->config->current['BASE']){
333         $this->$nA = $old_nA;
334       }
335     }
336         }
339         /* Check values */
340         function check()
341         {
342                 /* Call common method to give check the hook */
343                 $message= plugin::check();
345                 /* Check for presence of this department */
346                 $ldap= $this->config->get_ldap_link();
347     $ldap->ls ("(&(ou=".$this->ou.")(objectClass=organizationalUnit))", $this->base, array('dn'));
348     if ($this->orig_dn == "new" && $ldap->count()){
349                         $message[]= msgPool::duplicated(_("Name"));
350                 } elseif ($this->orig_dn != $this->dn && $ldap->count()){
351                         $message[]= msgPool::duplicated(_("Name"));
352                 }
354                 /* All required fields are set? */
355                 if ($this->ou == ""){
356                         $message[]= msgPool::required(_("Name"));
357                 }
358                 if ($this->description == ""){
359                         $message[]= msgPool::required(_("Description"));
360                 }
362     if(tests::is_department_name_reserved($this->ou,$this->base)){
363       $message[]= msgPool::reserved(_("Name"));
364     }
366                 if (preg_match ('/[#+:=>\\\\\/]/', $this->ou)){
367                         $message[]= msgPool::invalid(_("Name"), $this->ou, "/[^#+:=>\\\\\/]/");
368                 }
369                 if (!tests::is_phone_nr($this->telephoneNumber)){
370                         $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
371                 }
372                 if (!tests::is_phone_nr($this->facsimileTelephoneNumber)){
373                         $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
374                 }
376     // Check if a wrong base was supplied
377     if(!$this->baseSelector->checkLastBaseUpdate()){
378       $message[]= msgPool::check_base();;
379     }
381     /* Check if we are allowed to create or move this object
382      */
383     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
384       $message[] = msgPool::permCreate();
385     }elseif($this->orig_dn != "new" && $this->base != $this->orig_base && !$this->acl_is_moveable($this->base)){
386       $message[] = msgPool::permMove();
387     }
389     return $message;
390         }
393         /* Save to LDAP */
394         function save()
395         {
396                 $ldap= $this->config->get_ldap_link();
398     /* Ensure that ou is saved too, it is required by objectClass gosaDepartment 
399      */
400     $nA = $this->namingAttr;
401     $this->ou = $this->$nA;
403     /* Add tag objects if needed */
404     if ($this->is_administrational_unit){
406       /* If this wasn't tagged before add oc an reset unit tag */
407       if(!$this->initially_was_tagged){
408         $this->objectclasses[]= "gosaAdministrativeUnit";
409         $this->gosaUnitTag= "";
411         /* It seams that this method is called twice, 
412            set this to true. to avoid adding this oc twice */
413         $this->initially_was_tagged = true;
414       }
416       if ($this->gosaUnitTag == ""){
418         /* It's unlikely, but check if already used... */
419         $try= 5;
420         $ldap->cd($this->config->current['BASE']);
421         while ($try--){
423           /* Generate microtime stamp as tag */
424           list($usec, $sec)= explode(" ", microtime());
425           $time_stamp= preg_replace("/\./", "", $sec.$usec);
427           $ldap->search("(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$time_stamp))",array("gosaUnitTag"));
428           if ($ldap->count() == 0){
429             break;
430           }
431         }
432         if($try == 0) {
433           msg_dialog::display(_("Fatal error"), _("Cannot find an unused tag for this administrative unit!"), WARNING_DIALOG);
434           return;
435         }
436         $this->gosaUnitTag= preg_replace("/\./", "", $sec.$usec);
437       }
438     }
439     $this->skipTagging = TRUE;
440     plugin::save();
442     /* Remove tag information if needed */
443     if (!$this->is_administrational_unit && $this->initially_was_tagged){
444       $tmp= array();
446       /* Remove gosaAdministrativeUnit from this plugin */
447       foreach($this->attrs['objectClass'] as $oc){
448         if (preg_match("/^gosaAdministrativeUnitTag$/i", $oc)){
449           continue;
450         }
451         if (!preg_match("/^gosaAdministrativeUnit$/i", $oc)){
452           $tmp[]= $oc;
453         }
454       }
455       $this->attrs['objectClass']= $tmp;
456       $this->attrs['gosaUnitTag']= array();
457       $this->gosaUnitTag = "";
458     }
461                 /* Write back to ldap */
462                 $ldap->cat($this->dn, array('dn'));
463                 $ldap->cd($this->dn);
465                 if ($ldap->count()){
466                         $this->cleanup();
467                         $ldap->modify ($this->attrs); 
468       new log("modify","department/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
469                         $this->handle_post_events('modify');
470                 } else {
471                         $ldap->add($this->attrs);
472                         $this->handle_post_events('add');
473       new log("create","department/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
474                 }
475     if (!$ldap->success()){
476       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
477     }
479     /* The parameter forces only to set must_be_tagged, and don't touch any objects 
480        This will be done later */
481     $this->tag_objects(true);
482     
483     /* Optionally execute a command after we're done */
484                 $this->postcreate();
485     return(false);
486         }
489         /* Tag objects to have the gosaAdministrativeUnitTag */
490         function tag_objects($OnlySetTagFlag = false)
491         {
492     if(!$OnlySetTagFlag){
493       $smarty= get_smarty();
494       /* Print out html introduction */
495       echo '  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
496         <html>
497         <head>
498         <title></title>
499         <style type="text/css">@import url("themes/default/style.css");</style>
500         <script language="javascript" src="include/focus.js" type="text/javascript"></script>
501         </head>
502         <body style="background: none; margin:4px;" id="body" >
503         ';
504       echo "<h3>".sprintf(_("Tagging '%s'."),"<i>".LDAP::fix($this->dn)."</i>")."</h3>";
505     }
507     $add= $this->is_administrational_unit;
508     $len= strlen($this->dn);
509     $ldap= $this->config->get_ldap_link();
510     $ldap->cd($this->dn);
511     if ($add){
512             $ldap->search('(!(&(objectClass=gosaAdministrativeUnitTag)(gosaUnitTag='.
513                                                     $this->gosaUnitTag.')))', array('dn'));
514     } else {
515             $ldap->search('objectClass=gosaAdministrativeUnitTag', array('dn'));
516     }
518     $objects = array();
519     while ($attrs= $ldap->fetch()){
520       $objects[] = $attrs;
521     }
522     foreach($objects as $attrs){
524             /* Skip self */
525             if ($attrs['dn'] == $this->dn){
526                     continue;
527             }
529             /* Check for confilicting administrative units */
530             $fix= true;
531             foreach ($this->config->adepartments as $key => $tag){
532                     /* This one is shorter than our dn, its not relevant... */
533                     if ($len >= strlen($key)){
534                             continue;
535                     }
537                     /* This one matches with the latter part. Break and don't fix this entry */
538                     if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $attrs['dn'])){
539                             $fix= false;
540                             break;
541                     }
542             }
544             /* Fix entry if needed */
545             if ($fix){
546                     if($OnlySetTagFlag){
547                             $this->must_be_tagged =true;
548                             return;
549                     }
550                     $this->handle_object_tagging($attrs['dn'], $this->gosaUnitTag, TRUE );
551         echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
552             }
553     }
554     
555     if(!$OnlySetTagFlag){
556       $this->must_be_tagged = FALSE;
557             echo '<p class="seperator">&nbsp;</p>';
558       echo "<div style='width:100%;text-align:right;'>".
559         "<form name='form' method='post' action='?plug=".$_GET['plug']."' target='_parent'>".
560         "<br>".
561         "<input type='submit' name='back' value='"._("Continue")."'>".
562         "<input type='hidden' name='php_c_check' value='1'>".
563         "</form>".
564         "</div>";
565       echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
566     }
567         }
570         /* Move/Rename complete trees */
571         function recursive_move($src_dn, $dst_dn,$force = false)
572         {
573     /* Print header to have styles included */
574     $smarty= get_smarty();
576     echo '  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
577       <html>
578       <head>
579       <title></title>
580       <style type="text/css">@import url("themes/default/style.css");</style>
581       <script language="javascript" src="include/focus.js" type="text/javascript"></script>
582       </head>
583       <body style="background: none; margin:4px;" id="body" >
584       ';
585     echo "<h3>".sprintf(_("Moving '%s' to '%s'"),"<i>".LDAP::fix($src_dn)."</i>","<i>".LDAP::fix($dst_dn)."</i>")."</h3>";
588     /* Check if the destination entry exists */
589     $ldap= $this->config->get_ldap_link();
591     /* Check if destination exists - abort */
592     $ldap->cat($dst_dn, array('dn'));
593     if ($ldap->fetch()){
594       trigger_error("Recursive_move ".LDAP::fix($dst_dn)." already exists.",
595           E_USER_WARNING);
596       echo sprintf("Recursive_move: '%s' already exists", LDAP::fix($dst_dn))."<br>"; 
597       return (FALSE);
598     }
600     /* Perform a search for all objects to be moved */
601     $objects= array();
602     $ldap->cd($src_dn);
603     $ldap->search("(objectClass=*)", array("dn"));
604     while($attrs= $ldap->fetch()){
605       $dn= $attrs['dn'];
606       $objects[$dn]= strlen($dn);
607     }
609     /* Sort objects by indent level */
610     asort($objects);
611     reset($objects);
613     /* Copy objects from small to big indent levels by replacing src_dn by dst_dn */
614     foreach ($objects as $object => $len){
617       $src= str_replace("\\","\\\\",$object);
618       $dst= preg_replace("/".str_replace("\\","\\\\",$src_dn)."$/", "$dst_dn", $object);
619       $dst= str_replace($src_dn,$dst_dn,$object);
621       echo "<b>"._("Object").":</b> ".LDAP::fix($src)."<br>";
623       $this->update_acls($object, $dst,TRUE);
625       if (!$this->copy($src, $dst)){
626         echo "<font color='#FF0000'><br>".sprintf(_("FAILED to copy %s, aborting operation"),LDAP::fix($src))."</font>";
627         return (FALSE);
628       }
629       echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
630       flush();
631     }
633     /* Remove src_dn */
634     $ldap->cd($src_dn);
635     $ldap->recursive_remove();
636     $this->orig_dn  = $this->dn = $dst_dn;
637     $this->orig_base= $this->base;     
638     $this->entryCSN = getEntryCSN($this->dn);
640     echo '<p class="seperator">&nbsp;</p>';
642     echo "<div style='width:100%;text-align:right;'><form name='form' method='post' action='?plug=".$_GET['plug']."' target='_parent'>
643       <br><input type='submit' name='back' value='"._("Continue")."'>
644       </form></div>";
646     echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
647     echo "</body></html>";
649     return (TRUE);
650   }
653   /* Return plugin informations for acl handling */ 
654   static function plInfo()
655   {
656     return (array("plShortName"   => _("Generic"),
657                   "plDescription" => _("Departments"),
658                   "plSelfModify"  => FALSE,
659                   "plPriority"    => 0,
660                   "plDepends"     => array(),
661                   "plSection"     => array("administration"),
662                   "plCategory"    => array("department" => array("objectClass" => "gosaDepartment", "description" => _("Departments"))),
663             
664                   "plProvidedAcls" => array(
665                     "ou"                => _("Department name"),
666                     "description"       => _("Description"),
667                     "businessCategory"  => _("Category"),
668                     "base"              => _("Base"),
670                     "st"                => _("State"),
671                     "l"                 => _("Location"),
672                     "postalAddress"     => _("Address"),
673                     "telephoneNumber"   => _("Telephone"),
674                     "facsimileTelephoneNumber" => _("Fax"),
675                     "manager" => _("Manager"),
677                     "gosaUnitTag"       => _("Administrative settings"))
678                   ));
679   }
681   function handle_object_tagging($dn= "", $tag= "", $show= false)
682   {
683     /* No dn? Self-operation... */
684     if ($dn == ""){
685       $dn= $this->dn;
687       /* No tag? Find it yourself... */
688       if ($tag == ""){
689         $len= strlen($dn);
691         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
692         $relevant= array();
693         foreach ($this->config->adepartments as $key => $ntag){
695           /* This one is bigger than our dn, its not relevant... */
696           if ($len <= strlen($key)){
697             continue;
698           }
700           /* This one matches with the latter part. Break and don't fix this entry */
701           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
702             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
703             $relevant[strlen($key)]= $ntag;
704             continue;
705           }
707         }
709         /* If we've some relevant tags to set, just get the longest one */
710         if (count($relevant)){
711           ksort($relevant);
712           $tmp= array_keys($relevant);
713           $idx= end($tmp);
714           $tag= $relevant[$idx];
715           $this->gosaUnitTag= $tag;
716         }
717       }
718     }
720     /* Set tag? */
721     if ($tag != ""){
722       /* Set objectclass and attribute */
723       $ldap= $this->config->get_ldap_link();
724       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
725       $attrs= $ldap->fetch();
726       if(isset($attrs['gosaUnitTag'][0]) && $attrs['gosaUnitTag'][0] == $tag){
727         if ($show) {
728           echo sprintf(_("Object '%s' is already tagged"), LDAP::fix($dn))."<br>";
729           flush();
730         }
731         return;
732       }
733       if (count($attrs)){
734         if ($show){
735           echo sprintf(_("Adding tag (%s) to object '%s'"), $tag, LDAP::fix($dn))."<br>";
736           flush();
737         }
738         $nattrs= array("gosaUnitTag" => $tag);
739         $nattrs['objectClass']= array();
740         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
741           $oc= $attrs['objectClass'][$i];
742           if ($oc != "gosaAdministrativeUnitTag"){
743             $nattrs['objectClass'][]= $oc;
744           }
745         }
746         $nattrs['objectClass'][]= "gosaAdministrativeUnitTag";
747         $ldap->cd($dn);
748         $ldap->modify($nattrs);
749         if (!$ldap->success()){
750           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, get_class()));
751         }
752       } else {
753         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not tagging ($tag) $dn - seems to have moved away", "Tagging");
754       }
756     } else {
757       /* Remove objectclass and attribute */
758       $ldap= $this->config->get_ldap_link();
759       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
760       $attrs= $ldap->fetch();
761       if (isset($attrs['objectClass']) && !in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass'])){
762         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "$dn is not tagged", "Tagging");
763         return;
764       }
765       if (count($attrs)){
766         if ($show){
767           echo sprintf(_("Removing tag from object '%s'"), LDAP::fix($dn))."<br>";
768           flush();
769         }
770         $nattrs= array("gosaUnitTag" => array());
771         $nattrs['objectClass']= array();
772         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
773           $oc= $attrs['objectClass'][$i];
774           if ($oc != "gosaAdministrativeUnitTag"){
775             $nattrs['objectClass'][]= $oc;
776           }
777         }
778         $ldap->cd($dn);
779         $ldap->modify($nattrs);
780         if (!$ldap->success()){
781           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, get_class()));
782         }
783       } else {
784         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not removing tag ($tag) $dn - seems to have moved away", "Tagging");
785       }
786     }
787   }
791 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
792 ?>