Code

634901a4d5134886d047c3e49dcdeaeca38fd0c7
[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", $this->$val);
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     return(false);
483         }
486         /* Tag objects to have the gosaAdministrativeUnitTag */
487         function tag_objects($OnlySetTagFlag = false)
488         {
489     if(!$OnlySetTagFlag){
490       $smarty= get_smarty();
491       /* Print out html introduction */
492       echo '  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
493         <html>
494         <head>
495         <title></title>
496         <style type="text/css">@import url("themes/default/style.css");</style>
497         <script language="javascript" src="include/focus.js" type="text/javascript"></script>
498         </head>
499         <body style="background: none; margin:4px;" id="body" >
500         ';
501       echo "<h3>".sprintf(_("Tagging '%s'."),"<i>".LDAP::fix($this->dn)."</i>")."</h3>";
502     }
504     $add= $this->is_administrational_unit;
505     $len= strlen($this->dn);
506     $ldap= $this->config->get_ldap_link();
507     $ldap->cd($this->dn);
508     if ($add){
509             $ldap->search('(!(&(objectClass=gosaAdministrativeUnitTag)(gosaUnitTag='.
510                                                     $this->gosaUnitTag.')))', array('dn'));
511     } else {
512             $ldap->search('objectClass=gosaAdministrativeUnitTag', array('dn'));
513     }
515     $objects = array();
516     while ($attrs= $ldap->fetch()){
517       $objects[] = $attrs;
518     }
519     foreach($objects as $attrs){
521             /* Skip self */
522             if ($attrs['dn'] == $this->dn){
523                     continue;
524             }
526             /* Check for confilicting administrative units */
527             $fix= true;
528             foreach ($this->config->adepartments as $key => $tag){
529                     /* This one is shorter than our dn, its not relevant... */
530                     if ($len >= strlen($key)){
531                             continue;
532                     }
534                     /* This one matches with the latter part. Break and don't fix this entry */
535                     if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $attrs['dn'])){
536                             $fix= false;
537                             break;
538                     }
539             }
541             /* Fix entry if needed */
542             if ($fix){
543                     if($OnlySetTagFlag){
544                             $this->must_be_tagged =true;
545                             return;
546                     }
547                     $this->handle_object_tagging($attrs['dn'], $this->gosaUnitTag, TRUE );
548         echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
549             }
550     }
551     
552     if(!$OnlySetTagFlag){
553       $this->must_be_tagged = FALSE;
554             echo '<p class="seperator">&nbsp;</p>';
555       echo "<div style='width:100%;text-align:right;'>".
556         "<form name='form' method='post' action='?plug=".$_GET['plug']."' target='_parent'>".
557         "<br>".
558         "<input type='submit' name='back' value='"._("Continue")."'>".
559         "<input type='hidden' name='php_c_check' value='1'>".
560         "</form>".
561         "</div>";
562       echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
563     }
564         }
567         /* Move/Rename complete trees */
568         function recursive_move($src_dn, $dst_dn,$force = false)
569         {
570     /* Print header to have styles included */
571     $smarty= get_smarty();
573     echo '  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
574       <html>
575       <head>
576       <title></title>
577       <style type="text/css">@import url("themes/default/style.css");</style>
578       <script language="javascript" src="include/focus.js" type="text/javascript"></script>
579       </head>
580       <body style="background: none; margin:4px;" id="body" >
581       ';
582     echo "<h3>".sprintf(_("Moving '%s' to '%s'"),"<i>".LDAP::fix($src_dn)."</i>","<i>".LDAP::fix($dst_dn)."</i>")."</h3>";
585     /* Check if the destination entry exists */
586     $ldap= $this->config->get_ldap_link();
588     /* Check if destination exists - abort */
589     $ldap->cat($dst_dn, array('dn'));
590     if ($ldap->fetch()){
591       trigger_error("Recursive_move ".LDAP::fix($dst_dn)." already exists.",
592           E_USER_WARNING);
593       echo sprintf("Recursive_move: '%s' already exists", LDAP::fix($dst_dn))."<br>"; 
594       return (FALSE);
595     }
597     /* Perform a search for all objects to be moved */
598     $objects= array();
599     $ldap->cd($src_dn);
600     $ldap->search("(objectClass=*)", array("dn"));
601     while($attrs= $ldap->fetch()){
602       $dn= $attrs['dn'];
603       $objects[$dn]= strlen($dn);
604     }
606     /* Sort objects by indent level */
607     asort($objects);
608     reset($objects);
610     /* Copy objects from small to big indent levels by replacing src_dn by dst_dn */
611     foreach ($objects as $object => $len){
614       $src= str_replace("\\","\\\\",$object);
615       $dst= preg_replace("/".str_replace("\\","\\\\",$src_dn)."$/", "$dst_dn", $object);
616       $dst= str_replace($src_dn,$dst_dn,$object);
618       echo "<b>"._("Object").":</b> ".LDAP::fix($src)."<br>";
620       $this->update_acls($object, $dst,TRUE);
622       if (!$this->copy($src, $dst)){
623         echo "<font color='#FF0000'><br>".sprintf(_("FAILED to copy %s, aborting operation"),LDAP::fix($src))."</font>";
624         return (FALSE);
625       }
626       echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
627       flush();
628     }
630     /* Remove src_dn */
631     $ldap->cd($src_dn);
632     $ldap->recursive_remove();
633     $this->orig_dn  = $this->dn = $dst_dn;
634     $this->orig_base= $this->base;     
635     $this->entryCSN = getEntryCSN($this->dn);
637     echo '<p class="seperator">&nbsp;</p>';
639     echo "<div style='width:100%;text-align:right;'><form name='form' method='post' action='?plug=".$_GET['plug']."' target='_parent'>
640       <br><input type='submit' name='back' value='"._("Continue")."'>
641       </form></div>";
643     echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
644     echo "</body></html>";
646     return (TRUE);
647   }
650   /* Return plugin informations for acl handling */ 
651   static function plInfo()
652   {
653     return (array("plShortName"   => _("Generic"),
654                   "plDescription" => _("Departments"),
655                   "plSelfModify"  => FALSE,
656                   "plPriority"    => 0,
657                   "plDepends"     => array(),
658                   "plSection"     => array("administration"),
659                   "plCategory"    => array("department" => array("objectClass" => "gosaDepartment", "description" => _("Departments"))),
660             
661                   "plProvidedAcls" => array(
662                     "ou"                => _("Department name"),
663                     "description"       => _("Description"),
664                     "businessCategory"  => _("Category"),
665                     "base"              => _("Base"),
667                     "st"                => _("State"),
668                     "l"                 => _("Location"),
669                     "postalAddress"     => _("Address"),
670                     "telephoneNumber"   => _("Telephone"),
671                     "facsimileTelephoneNumber" => _("Fax"),
672                     "manager" => _("Manager"),
674                     "gosaUnitTag"       => _("Administrative settings"))
675                   ));
676   }
678   function handle_object_tagging($dn= "", $tag= "", $show= false)
679   {
680     /* No dn? Self-operation... */
681     if ($dn == ""){
682       $dn= $this->dn;
684       /* No tag? Find it yourself... */
685       if ($tag == ""){
686         $len= strlen($dn);
688         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
689         $relevant= array();
690         foreach ($this->config->adepartments as $key => $ntag){
692           /* This one is bigger than our dn, its not relevant... */
693           if ($len <= strlen($key)){
694             continue;
695           }
697           /* This one matches with the latter part. Break and don't fix this entry */
698           if (preg_match('/(^|,)'.preg_quote($key, '/').'$/', $dn)){
699             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
700             $relevant[strlen($key)]= $ntag;
701             continue;
702           }
704         }
706         /* If we've some relevant tags to set, just get the longest one */
707         if (count($relevant)){
708           ksort($relevant);
709           $tmp= array_keys($relevant);
710           $idx= end($tmp);
711           $tag= $relevant[$idx];
712           $this->gosaUnitTag= $tag;
713         }
714       }
715     }
717     /* Set tag? */
718     if ($tag != ""){
719       /* Set objectclass and attribute */
720       $ldap= $this->config->get_ldap_link();
721       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
722       $attrs= $ldap->fetch();
723       if(isset($attrs['gosaUnitTag'][0]) && $attrs['gosaUnitTag'][0] == $tag){
724         if ($show) {
725           echo sprintf(_("Object '%s' is already tagged"), LDAP::fix($dn))."<br>";
726           flush();
727         }
728         return;
729       }
730       if (count($attrs)){
731         if ($show){
732           echo sprintf(_("Adding tag (%s) to object '%s'"), $tag, LDAP::fix($dn))."<br>";
733           flush();
734         }
735         $nattrs= array("gosaUnitTag" => $tag);
736         $nattrs['objectClass']= array();
737         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
738           $oc= $attrs['objectClass'][$i];
739           if ($oc != "gosaAdministrativeUnitTag"){
740             $nattrs['objectClass'][]= $oc;
741           }
742         }
743         $nattrs['objectClass'][]= "gosaAdministrativeUnitTag";
744         $ldap->cd($dn);
745         $ldap->modify($nattrs);
746         if (!$ldap->success()){
747           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, get_class()));
748         }
749       } else {
750         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not tagging ($tag) $dn - seems to have moved away", "Tagging");
751       }
753     } else {
754       /* Remove objectclass and attribute */
755       $ldap= $this->config->get_ldap_link();
756       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
757       $attrs= $ldap->fetch();
758       if (isset($attrs['objectClass']) && !in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass'])){
759         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "$dn is not tagged", "Tagging");
760         return;
761       }
762       if (count($attrs)){
763         if ($show){
764           echo sprintf(_("Removing tag from object '%s'"), LDAP::fix($dn))."<br>";
765           flush();
766         }
767         $nattrs= array("gosaUnitTag" => array());
768         $nattrs['objectClass']= array();
769         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
770           $oc= $attrs['objectClass'][$i];
771           if ($oc != "gosaAdministrativeUnitTag"){
772             $nattrs['objectClass'][]= $oc;
773           }
774         }
775         $ldap->cd($dn);
776         $ldap->modify($nattrs);
777         if (!$ldap->success()){
778           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, get_class()));
779         }
780       } else {
781         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not removing tag ($tag) $dn - seems to have moved away", "Tagging");
782       }
783     }
784   }
788 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
789 ?>