Code

-Updated dep tagging
[gosa.git] / gosa-core / plugins / admin / departments / class_departmentGeneric.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 $orig_dn= "";
36         var $is_administrational_unit= false;
37         var $gosaUnitTag= "";
38   var $view_logged = FALSE;
40         /* Headpage attributes */
41         var $last_dep_sorting= "invalid";
42         var $departments= array();
43   var $must_be_tagged = false;
45         /* attribute list for save action */
46         var $attributes= array("ou", "description", "businessCategory", "st", "l", "postalAddress",
47                         "telephoneNumber", "facsimileTelephoneNumber", "gosaUnitTag");
48         var $objectclasses= array("top", "gosaDepartment", "organizationalUnit");
49   var $initially_was_tagged = false;
51   var $orig_base = "";
52   var $orig_ou = "";
54         function department (&$config, $dn)
55         {
57                 plugin::plugin($config, $dn);
58                 $this->is_account= TRUE;
59                 $this->ui= get_userinfo();
60                 $this->dn= $dn;
61                 $this->orig_dn= $dn;
62                 $this->orig_ou= $this->ou;
63                 $this->config= $config;
65                 /* Set base */
66                 if ($this->dn == "new"){
67                         $ui= get_userinfo();
68                         if(session::is_set('CurrentMainBase')){
69                                 $this->base = session::get('CurrentMainBase');
70                         }else{
71                                 $this->base= dn2base($ui->dn);
72                         }
73                 } else {
74                         $this->base= preg_replace ("/^[^,]+,/", "", $this->dn);
75                 }
77     $this->orig_base = $this->base;
79                 /* Is administrational Unit? */
80                 if ($dn != "new" && in_array_ics('gosaAdministrativeUnit', $this->attrs['objectClass'])){
81                         $this->is_administrational_unit= true;
82       $this->initially_was_tagged = true;
83                 }
84         }
86         function execute()
87         {
88                 /* Call parent execute */
89                 plugin::execute();
91     /* Log view */
92     if($this->is_account && !$this->view_logged){
93       $this->view_logged = TRUE;
94       new log("view","department/".get_class($this),$this->dn);
95     }
97                 /* Reload departments */
98                 $this->config->get_departments($this->dn);
99                 $this->config->make_idepartments();
100                 $smarty= get_smarty();
102     $tmp = $this->plInfo();
103     foreach($tmp['plProvidedAcls'] as $name => $translation){
104       $smarty->assign($name."ACL",$this->getacl($name));
105     }
107                 /* Base select dialog */
108                 $once = true;
109                 foreach($_POST as $name => $value){
110                         if((preg_match("/^chooseBase/",$name) && $once) && ($this->acl_is_moveable())){
111                                 $once = false;
112                                 $this->dialog = new baseSelectDialog($this->config,$this,$this->get_allowed_bases());
113                                 $this->dialog->setCurrentBase($this->base);
114                         }
115                 }
117                 /* Dialog handling */
118                 if(is_object($this->dialog)){
119                         /* Must be called before save_object */
120                         $this->dialog->save_object();
122                         if($this->dialog->isClosed()){
123                                 $this->dialog = false;
124                         }elseif($this->dialog->isSelected()){
126         /* A new base was selected, check if it is a valid one */
127         $tmp = $this->get_allowed_bases();
128         if(isset($tmp[$this->dialog->isSelected()])){
129           $this->base = $this->dialog->isSelected();
130         }
131   
132                                 $this->dialog= false;
133                         }else{
134                                 return($this->dialog->execute());
135                         }
136                 }
138                 /* Hide all departments, that are subtrees of this department */
139     $bases = $this->get_allowed_bases();
140                 if(($this->dn == "new")||($this->dn == "")){
141                         $tmp = $bases;
142                 }else{
143                         $tmp    = array();      
144                         foreach($bases as $dn=>$base){
145                                 $fixed = str_replace("/","\\",$this->dn);
146                                 /* Only attach departments which are not a subtree of this one */
147                                 if(!preg_match("/".$fixed."/",$dn)){
148                                         $tmp[$dn]=$base;
149                                 }
150                         }
151                 }
152                 $smarty->assign("bases", $tmp);
154                 foreach ($this->attributes as $val){
155                         $smarty->assign("$val", $this->$val);
156                 }
157                 $smarty->assign("base_select", $this->base);
159     /* Set admin unit flag */
160     if ($this->is_administrational_unit) {
161       $smarty->assign("unitTag", "checked");
162     } else {
163       $smarty->assign("unitTag", "");
164     }
166                 return($smarty->fetch (get_template_path('generic.tpl', TRUE)));
167         }
169         function clear_fields()
170         {
171                 $this->dn   = "";
172                 $this->base = "";
174                 foreach ($this->attributes as $val){
175                         $this->$val= "";
176                 }
177         }
179         function remove_from_parent()
180         {
181                 $ldap= $this->config->get_ldap_link();
182                 $ldap->cd ($this->dn);
183                 $ldap->recursive_remove();
184     new log("remove","department/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
185     if (!$ldap->success()){
186       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
187     }
189                 /* Optionally execute a command after we're done */
190                 $this->handle_post_events('remove');
191         }
193         function must_be_tagged()
194         {
195                 return $this->must_be_tagged;
196         }
198         /* Save data to object */
199         function save_object()
200         {
201                 if (isset($_POST['dep_generic_posted'])){
203       /* Create a base backup and reset the
204          base directly after calling plugin::save_object();
205          Base will be set seperatly a few lines below */
206       $base_tmp = $this->base;
207       plugin::save_object();
208       $this->base = $base_tmp;
210       /* Set new base if allowed */
211       $tmp = $this->get_allowed_bases();
212       if(isset($_POST['base'])){
213         if(isset($tmp[$_POST['base']])){
214           $this->base= $_POST['base'];
215         }
216       }
218       /* Save tagging flag */
219       if ($this->acl_is_writeable("unitTag")){
220         if (isset($_POST['unitTag'])){
221           $this->is_administrational_unit= true;
222         } else {
223           $this->is_administrational_unit= false;
224         }
225       }
226     }
227         }
230         /* Check values */
231         function check()
232         {
233                 /* Call common method to give check the hook */
234                 $message= plugin::check();
236                 /* Check for presence of this department */
237                 $ldap= $this->config->get_ldap_link();
238     $ldap->ls ("(&(ou=".$this->ou.")(objectClass=organizationalUnit))", $this->base, array('dn'));
239     if ($this->orig_dn == "new" && $ldap->count()){
240                         $message[]= msgPool::duplicated(_("Name"));
241                 } elseif ($this->orig_dn != $this->dn && $ldap->count()){
242                         $message[]= msgPool::duplicated(_("Name"));
243                 }
245                 /* All required fields are set? */
246                 if ($this->ou == ""){
247                         $message[]= _("Required field 'Name' is not set.");
248                         $message[]= msgPool::required(_("Name"));
249                 }
250                 if ($this->description == ""){
251                         $message[]= _("Required field 'Description' is not set.");
252                         $message[]= msgPool::required(_("Description"));
253                 }
255     if(tests::is_department_name_reserved($this->ou,$this->base)){
256       $message[]= msgPool::reserved(_("Name"));
257     }
259                 if (preg_match ('/[#+:=>\\\\\/]/', $this->ou)){
260                         $message[]= msgPool::invalid(_("Name"), $this->ou, "/[^#+:=>\\\\\/]/");
261                 }
262                 if (!tests::is_phone_nr($this->telephoneNumber)){
263                         $message[]= msgPool::invalid(_("Phone"), $this->telephoneNumber, "/[\/0-9 ()+*-]/");
264                 }
265                 if (!tests::is_phone_nr($this->facsimileTelephoneNumber)){
266                         $message[]= msgPool::invalid(_("Fax"), $this->facsimileTelephoneNumber, "/[\/0-9 ()+*-]/");
267                 }
269                 return $message;
270         }
273         /* Save to LDAP */
274         function save()
275         {
276                 $ldap= $this->config->get_ldap_link();
278     /* Add tag objects if needed */
279     if ($this->is_administrational_unit){
281       /* If this wasn't tagged before add oc an reset unit tag */
282       if(!$this->initially_was_tagged){
283         $this->objectclasses[]= "gosaAdministrativeUnit";
284         $this->gosaUnitTag= "";
286         /* It seams that this method is called twice, 
287            set this to true. to avoid adding this oc twice */
288         $this->initially_was_tagged = true;
289       }
291       if ($this->gosaUnitTag == ""){
293         /* It's unlikely, but check if already used... */
294         $try= 5;
295         $ldap->cd($this->config->current['BASE']);
296         while ($try--){
298           /* Generate microtime stamp as tag */
299           list($usec, $sec)= explode(" ", microtime());
300           $time_stamp= preg_replace("/\./", "", $sec.$usec);
302           $ldap->search("(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$time_stamp))",array("gosaUnitTag"));
303           if ($ldap->count() == 0){
304             break;
305           }
306         }
307         if($try == 0) {
308           msg_dialog::display(_("Fatal error"), _("Cannot find an unused tag for this administrative unit!"), WARNING_DIALOG);
309           return;
310         }
311         $this->gosaUnitTag= preg_replace("/\./", "", $sec.$usec);
312       }
313     }
314     $this->skipTagging = TRUE;
315     plugin::save();
317     /* Remove tag information if needed */
318     if (!$this->is_administrational_unit){
319       $tmp= array();
321       /* Remove gosaAdministrativeUnit from this plugin */
322       foreach($this->attrs['objectClass'] as $oc){
323         if (!preg_match("/^gosaAdministrativeUnit$/i", $oc)){
324           $tmp[]= $oc;
325         }
326       }
327       $this->attrs['objectClass']= $tmp;
328     }
330     /* Do we need to remove the tag itself? */
331     $has_unit_tag= false;
332     foreach($this->attrs['objectClass'] as $oc){
333       if (preg_match("/^gosaAdministrativeUnitTag$/i", $oc)){
334         $has_unit_tag= true;
335       }
336     }
337     if ($has_unit_tag == false && $this->is_administrational_unit == false){
338       $this->attrs['gosaUnitTag']= array();
339       $this->gosaUnitTag = "";
340     } else {
341       $this->attrs['gosaUnitTag']= $this->gosaUnitTag;
342     }
344                 /* Write back to ldap */
345                 $ldap->cat($this->dn, array('dn'));
346                 $ldap->cd($this->dn);
348                 if ($ldap->count()){
349                         $this->cleanup();
350                         $ldap->modify ($this->attrs); 
351       new log("modify","department/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
352                         $this->handle_post_events('modify');
353                 } else {
354                         $ldap->add($this->attrs);
355                         $this->handle_post_events('add');
356       new log("create","department/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
357                 }
358     if (!$ldap->success()){
359       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
360     }
362     /* The parameter forces only to set must_be_tagged, and don't touch any objects 
363        This will be done later */
364     $this->tag_objects(true);
365     
366     /* Optionally execute a command after we're done */
367                 $this->postcreate();
368     return(false);
369         }
372         /* Tag objects to have the gosaAdministrativeUnitTag */
373         function tag_objects($OnlySetTagFlag = false)
374         {
375     if(!$OnlySetTagFlag){
376       $smarty= get_smarty();
377       /* Print out html introduction */
378       echo '  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
379         <html>
380         <head>
381         <title></title>
382         <style type="text/css">@import url("themes/default/style.css");</style>
383         <script language="javascript" src="include/focus.js" type="text/javascript"></script>
384         </head>
385         <body style="background: none; margin:4px;" id="body" >
386         ';
387       echo "<h3>".sprintf(_("Tagging '%s'."),"<i>".@LDAP::fix($this->dn)."</i>")."</h3>";
388     }
390     $add= $this->is_administrational_unit;
391     $len= strlen($this->dn);
392     $ldap= $this->config->get_ldap_link();
393     $ldap->cd($this->dn);
394     if ($add){
395             $ldap->search('(!(&(objectClass=gosaAdministrativeUnitTag)(gosaUnitTag='.
396                                                     $this->gosaUnitTag.')))', array('dn'));
397     } else {
398             $ldap->search('objectClass=gosaAdministrativeUnitTag', array('dn'));
399     }
401     $objects = array();
402     while ($attrs= $ldap->fetch()){
403       $objects[] = $attrs;
404     }
405     foreach($objects as $attrs){
407             /* Skip self */
408             if ($attrs['dn'] == $this->dn){
409                     continue;
410             }
412             /* Check for confilicting administrative units */
413             $fix= true;
414             foreach ($this->config->adepartments as $key => $tag){
415                     /* This one is shorter than our dn, its not relevant... */
416                     if ($len >= strlen($key)){
417                             continue;
418                     }
420                     /* This one matches with the latter part. Break and don't fix this entry */
421                     if (preg_match('/(^|,)'.normalizePreg($key).'$/', $attrs['dn'])){
422                             $fix= false;
423                             break;
424                     }
425             }
427             /* Fix entry if needed */
428             if ($fix){
429                     if($OnlySetTagFlag){
430                             $this->must_be_tagged =true;
431                             return;
432                     }
433                     $this->handle_object_tagging($attrs['dn'], $this->gosaUnitTag, TRUE );
434         echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
435             }
436     }
437     
438     if(!$OnlySetTagFlag){
439       $this->must_be_tagged = FALSE;
440             echo '<p class="seperator">&nbsp;</p>';
441       echo "<div style='width:100%;text-align:right;'><form name='form' method='post' action='?plug=".$_GET['plug']."' target='_parent'>
442         <br><input type='submit' name='back' value='"._("Continue")."'>
443         </form></div>";
444       echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
445     }
446         }
449         /* Move/Rename complete trees */
450         function recursive_move($src_dn, $dst_dn,$force = false)
451         {
452     /* Print header to have styles included */
453     $smarty= get_smarty();
455     echo '  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
456       <html>
457       <head>
458       <title></title>
459       <style type="text/css">@import url("themes/default/style.css");</style>
460       <script language="javascript" src="include/focus.js" type="text/javascript"></script>
461       </head>
462       <body style="background: none; margin:4px;" id="body" >
463       ';
464     echo "<h3>".sprintf(_("Moving '%s' to '%s'"),"<i>".@LDAP::fix($src_dn)."</i>","<i>".@LDAP::fix($dst_dn)."</i>")."</h3>";
467     /* Check if the destination entry exists */
468     $ldap= $this->config->get_ldap_link();
470     /* Check if destination exists - abort */
471     $ldap->cat($dst_dn, array('dn'));
472     if ($ldap->fetch()){
473       trigger_error("Recursive_move ".@LDAP::fix($dst_dn)." already exists.",
474           E_USER_WARNING);
475       echo sprintf("Recursive_move: '%s' already exists", @LDAP::fix($dst_dn))."<br>"; 
476       return (FALSE);
477     }
479     /* Perform a search for all objects to be moved */
480     $objects= array();
481     $ldap->cd($src_dn);
482     $ldap->search("(objectClass=*)", array("dn"));
483     while($attrs= $ldap->fetch()){
484       $dn= $attrs['dn'];
485       $objects[$dn]= strlen($dn);
486     }
488     /* Sort objects by indent level */
489     asort($objects);
490     reset($objects);
492     /* Copy objects from small to big indent levels by replacing src_dn by dst_dn */
493     foreach ($objects as $object => $len){
496       $src= str_replace("\\","\\\\",$object);
497       $dst= preg_replace("/".str_replace("\\","\\\\",$src_dn)."$/", "$dst_dn", $object);
498       $dst= str_replace($src_dn,$dst_dn,$object);
500       echo "<b>"._("Object").":</b> ".@LDAP::fix($src)."<br>";
502       $this->update_acls($object, $dst,TRUE);
504       if (!$this->copy($src, $dst)){
505         echo "<font color='#FF0000'><br>".sprintf(_("FAILED to copy %s, aborting operation"),@LDAP::fix($src))."</font>";
506         return (FALSE);
507       }
508       echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
509       flush();
510     }
512     /* Remove src_dn */
513     $ldap->cd($src_dn);
514     $ldap->recursive_remove();
515     $this->orig_dn  = $this->dn = $dst_dn;
516     $this->orig_base= $this->base;     
517     $this->entryCSN = getEntryCSN($this->dn);
519     echo '<p class="seperator">&nbsp;</p>';
521     echo "<div style='width:100%;text-align:right;'><form name='form' method='post' action='?plug=".$_GET['plug']."' target='_parent'>
522       <br><input type='submit' name='back' value='"._("Continue")."'>
523       </form></div>";
525     echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
526     echo "</body></html>";
528     return (TRUE);
529   }
532   /* Return plugin informations for acl handling */ 
533   static function plInfo()
534   {
535     return (array("plShortName"   => _("Generic"),
536                   "plDescription" => _("Departments"),
537                   "plSelfModify"  => FALSE,
538                   "plPriority"    => 0,
539                   "plDepends"     => array(),
540                   "plSection"     => array("admin"),
541                   "plCategory"    => array("department" => array("objectClass" => "gosaDepartment", "description" => _("Departments"))),
542             
543                   "plProvidedAcls" => array(
544                     "description"       => _("Description"),
545                     "c"                 => _("Country"),
546                     "base"              => _("Base"),
547                     "l"                 => _("Location"),
548                     "telephoneNumber"   => _("Telephone"),
549                     "ou"                => _("Department name"),
550                     "businessCategory"  => _("Category"),
551                     "st"                => _("State"),
552                     "postalAddress"     => _("Address"),
553                     "gosaUnitTag"       => _("Administrative settings"),
554                     "facsimileTelephoneNumber" => _("Fax"))
555                   ));
556   }
558   function handle_object_tagging($dn= "", $tag= "", $show= false)
559   {
560     /* No dn? Self-operation... */
561     if ($dn == ""){
562       $dn= $this->dn;
564       /* No tag? Find it yourself... */
565       if ($tag == ""){
566         $len= strlen($dn);
568         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "No tag for $dn - looking for one...", "Tagging");
569         $relevant= array();
570         foreach ($this->config->adepartments as $key => $ntag){
572           /* This one is bigger than our dn, its not relevant... */
573           if ($len <= strlen($key)){
574             continue;
575           }
577           /* This one matches with the latter part. Break and don't fix this entry */
578           if (preg_match('/(^|,)'.normalizePreg($key).'$/', $dn)){
579             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "DEBUG: Possibly relevant: $key", "Tagging");
580             $relevant[strlen($key)]= $ntag;
581             continue;
582           }
584         }
586         /* If we've some relevant tags to set, just get the longest one */
587         if (count($relevant)){
588           ksort($relevant);
589           $tmp= array_keys($relevant);
590           $idx= end($tmp);
591           $tag= $relevant[$idx];
592           $this->gosaUnitTag= $tag;
593         }
594       }
595     }
597     /* Set tag? */
598     if ($tag != ""){
599       /* Set objectclass and attribute */
600       $ldap= $this->config->get_ldap_link();
601       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
602       $attrs= $ldap->fetch();
603       if(isset($attrs['gosaUnitTag'][0]) && $attrs['gosaUnitTag'][0] == $tag){
604         if ($show) {
605           echo sprintf(_("Object '%s' is already tagged"), @LDAP::fix($dn))."<br>";
606           flush();
607         }
608         return;
609       }
610       if (count($attrs)){
611         if ($show){
612           echo sprintf(_("Adding tag (%s) to object '%s'"), $tag, @LDAP::fix($dn))."<br>";
613           flush();
614         }
615         $nattrs= array("gosaUnitTag" => $tag);
616         $nattrs['objectClass']= array();
617         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
618           $oc= $attrs['objectClass'][$i];
619           if ($oc != "gosaAdministrativeUnitTag"){
620             $nattrs['objectClass'][]= $oc;
621           }
622         }
623         $nattrs['objectClass'][]= "gosaAdministrativeUnitTag";
624         $ldap->cd($dn);
625         $ldap->modify($nattrs);
626         if (!$ldap->success()){
627           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, get_class()));
628         }
629       } else {
630         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not tagging ($tag) $dn - seems to have moved away", "Tagging");
631       }
633     } else {
634       /* Remove objectclass and attribute */
635       $ldap= $this->config->get_ldap_link();
636       $ldap->cat($dn, array('gosaUnitTag', 'objectClass'));
637       $attrs= $ldap->fetch();
638       if (isset($attrs['objectClass']) && !in_array_ics("gosaAdministrativeUnitTag", $attrs['objectClass'])){
639         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "$dn is not tagged", "Tagging");
640         return;
641       }
642       if (count($attrs)){
643         if ($show){
644           echo sprintf(_("Removing tag from object '%s'"), @LDAP::fix($dn))."<br>";
645           flush();
646         }
647         $nattrs= array("gosaUnitTag" => array());
648         $nattrs['objectClass']= array();
649         for ($i= 0; $i<$attrs['objectClass']['count']; $i++){
650           $oc= $attrs['objectClass'][$i];
651           if ($oc != "gosaAdministrativeUnitTag"){
652             $nattrs['objectClass'][]= $oc;
653           }
654         }
655         $ldap->cd($dn);
656         $ldap->modify($nattrs);
657         if (!$ldap->success()){
658           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, get_class()));
659         }
660       } else {
661         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, "Not removing tag ($tag) $dn - seems to have moved away", "Tagging");
662       }
663     }
665   }
669 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
670 ?>