Code

Updated ogroup.
[gosa.git] / gosa-core / plugins / admin / ogroups / class_ogroup.inc
1 <?php
4 /* Sort multidimensional arrays for key 'text' */
5 function sort_list($val1, $val2)
6 {
7   $v1= strtolower($val1['text']);
8   $v2= strtolower($val2['text']);
9   if ($v1 > $v2){
10     return 1;
11   }
12   if ($v1 < $v2){
13     return -1;
14   }
15   return 0;
16 }
19 class ogroup extends plugin
20 {
21   /* Variables */
22   var $cn= "";
23   var $description= "";
24   var $base= "";
25   var $gosaGroupObjects= "";
26   var $department= "";
27   var $objects= array();
28   var $objcache= array();
29   var $memberList= array();
30   var $member= array();
31   var $orig_dn= "";
32   var $group_dialog= FALSE;
33   var $view_logged = FALSE;
35   /* attribute list for save action */
36   var $attributes= array("cn", "description", "gosaGroupObjects","member");
37   var $objectclasses= array("top", "gosaGroupOfNames");
39   function ogroup (&$config, $dn= NULL)
40   {
41     plugin::plugin ($config, $dn);
42     $this->orig_dn= $dn;
44     $this->member = array();
46     /* Load member objects */
47     if (isset($this->attrs['member'])){
48       foreach ($this->attrs['member'] as $key => $value){
49         if ("$key" != "count"){
50           $value= @LDAP::convert($value);
51           $this->member["$value"]= "$value";
52         }
53       }
54     }
55     $this->is_account= TRUE;
57     /* Get global filter config */
58     if (!session::is_set("ogfilter")){
59       $ui= get_userinfo();
60       $base= get_base_from_people($ui->dn);
61       $ogfilter= array( "dselect"       => $base,
62           "regex"           => "*");
63       session::set("ogfilter", $ogfilter);
64     }
65     $ogfilter= session::get('ogfilter');
67     /* Adjust flags */
68     foreach( array(   "U" => "accounts",
69           "G" => "groups",
70           "A" => "applications",
71           "D" => "departments",
72           "S" => "servers",
73           "W" => "workstations",
74           "O" => "winstations",
75           "T" => "terminals",
76           "F" => "phones",
77           "_" => "subtrees",
78           "P" => "printers") as $key => $val){
80       if (preg_match("/$key/", $this->gosaGroupObjects)){
81         $ogfilter[$val]= "checked";
82       } else {
83         $ogfilter[$val]= "";
84       }
85     }
86     session::set("ogfilter", $ogfilter);
87   
88     if(session::is_set('CurrentMainBase')){
89      $this->base  = session::get('CurrentMainBase');
90     }
92     /* Set base */
93     if ($this->dn == "new"){
94       $this->base = session::get('CurrentMainBase');
95     } else {
96       $this->base= preg_replace("/^[^,]+,".normalizePreg(get_ou("ogroupou"))."/","",$this->dn);
97     }
99     /* Load member data */
100     $this->reload();
101   }
103   function AddDelMembership($NewMember = false){
105     if($NewMember){
107       /* Add member and force reload */
108       $this->member[$NewMember]= $NewMember;
109       $this->reload(); 
111       $this->memberList[$NewMember]= $this->objcache[$NewMember];
112       unset ($this->objects[$NewMember]);
113       uasort ($this->memberList, 'sort_list');
114       reset ($this->memberList);
115     }else{
116       /* Delete objects from group */
117       if (isset($_POST['delete_membership']) && isset($_POST['members'])){
118         foreach ($_POST['members'] as $value){
119           $this->objects["$value"]= $this->memberList[$value];
120           unset ($this->memberList["$value"]);
121           unset ($this->member["$value"]);
122           uasort ($this->objects, 'sort_list');
123           reset ($this->objects);
124         }
125         $this->reload();
126       }
128       /* Add objects to group */
129       if (isset($_POST['add_object_finish']) && isset($_POST['objects'])){
131         $tmp = "";
132         foreach($this->memberList as $obj){
133           $tmp .= $obj['type'];
134         }
135         $skipped = FALSE;
136         foreach ($_POST['objects'] as $value){
137           if(preg_match("/T/",$tmp) && $this->objects[$value]['type'] == "W"){
138             $skipped =TRUE;
139           }elseif(preg_match("/W/",$tmp) && $this->objects[$value]['type'] == "T"){
140             $skipped =TRUE;
141           }else{
142             $this->memberList["$value"]= $this->objects[$value];
143             $this->member["$value"]= $value;
144             unset ($this->objects[$value]);
145             uasort ($this->memberList, 'sort_list');
146             reset ($this->memberList);
147           }
148         }
149         if($skipped){
150           print_red(_("You can only have terminals or workstations in one group, but not both."));
151         }
152         $this->reload();
153       }
154     }
155   }
157   function execute()
158   {
159     /* Call parent execute */
160     plugin::execute();
162     if(!$this->view_logged){
163       $this->view_logged = TRUE;
164       new log("view","ogroups/".get_class($this),$this->dn);
165     }
168     /* Do we represent a valid group? */
169     if (!$this->is_account){
170       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
171         _("This 'dn' is no object group.")."</b>";
172       return ($display);
173     }
176     /* Load templating engine */
177     $smarty= get_smarty();
179     $tmp = $this->plInfo();
180     foreach($tmp['plProvidedAcls'] as $name => $translation){
181       $smarty->assign($name."ACL",$this->getacl($name));
182     }
184     /* Base select dialog */
185     $once = true;
186     foreach($_POST as $name => $value){
187       if(preg_match("/^chooseBase/",$name) && $once && $this->acl_is_moveable()){
188         $once = false;
189         $this->dialog = new baseSelectDialog($this->config,$this,$this->get_allowed_bases());
190         $this->dialog->setCurrentBase($this->base);
191       }
192     }
194     /* Dialog handling */
195     if(is_object($this->dialog) && $this->acl_is_moveable()){
196       /* Must be called before save_object */
197       $this->dialog->save_object();
199       if($this->dialog->isClosed()){
200         $this->dialog = false;
201       }elseif($this->dialog->isSelected()){
203         /* A new base was selected, check if it is a valid one */
204         $tmp = $this->get_allowed_bases();
205         if(isset($tmp[$this->dialog->isSelected()])){
206           $this->base = $this->dialog->isSelected();
207         }
208         $this->dialog= false;
209       }else{
210         return($this->dialog->execute());
211       }
212     }
214     /* Add objects? */
215     if (isset($_POST["edit_membership"])){
216       $this->group_dialog= TRUE;
217       $this->dialog= TRUE;
218     }
220     /* Add objects finished? */
221     if (isset($_POST["add_object_finish"]) || isset($_POST["add_object_cancel"])){
222       $this->group_dialog= FALSE;
223       $this->dialog= FALSE;
224     }
226     /* Manage object add dialog */
227     if ($this->group_dialog){
229       /* Save data */
230       $ogfilter= session::get("ogfilter");
231       foreach( array("dselect", "regex") as $type){
232         if (isset($_POST[$type])){
233           $ogfilter[$type]= $_POST[$type];
234         }
235       }
236       if (isset($_POST['dselect'])){
237         foreach( array("accounts", "groups", "applications", "departments",
238               "servers", "workstations", "winstations", "terminals", "printers","subtrees",
239               "phones") as $type){
241           if (isset($_POST[$type])) {
242             $ogfilter[$type]= "checked";
243           } else {
244             $ogfilter[$type]= "";
245           }
246         }
247       }
248       if (isset($_GET['search'])){
249         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
250         if ($s == "**"){
251           $s= "*";
252         }
253         $ogfilter['regex']= $s;
254       }
255       session::set("ogfilter", $ogfilter);
256       $this->reload();
258       /* Calculate actual groups */
259       $smarty->assign("objects", $this->convert_list($this->objects));
261       /* Show dialog */
262       $smarty->assign("search_image", get_template_path('images/search.png'));
263       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
264       $smarty->assign("tree_image", get_template_path('images/tree.png'));
265       $smarty->assign("deplist", $this->config->idepartments);
266       $smarty->assign("alphabet", generate_alphabet());
267       foreach( array("dselect", "regex", "accounts", "groups", "applications",
268             "departments", "servers", "workstations", "winstations", "terminals","subtrees",
269             "printers", "phones") as $type){
270         $smarty->assign("$type", $ogfilter[$type]);
271       }
272       $smarty->assign("hint", print_sizelimit_warning());
273       $smarty->assign("apply", apply_filter());
275       $display= $smarty->fetch (get_template_path('ogroup_objects.tpl', TRUE, dirname(__FILE__)));
276       return ($display);
277     }
279     /* Bases / Departments */
280       if ((isset($_POST['base'])) && ($this->acl_is_moveable())){
281         $this->base= $_POST['base'];
282       }
284     /* Assemble combine string */
285     if ($this->gosaGroupObjects == "[]"){
286       $smarty->assign("combinedObjects", _("none"));
287     } elseif (strlen($this->gosaGroupObjects) > 4){
288       $smarty->assign("combinedObjects", "<font color=red>"._("too many different objects!")."</font>");
289     } else {
290       $conv= array(   "U" => _("users"),
291           "G" => _("groups"),
292           "A" => _("applications"),
293           "D" => _("departments"),
294           "S" => _("servers"),
295           "W" => _("workstations"),
296           "O" => _("winstations"),
297           "T" => _("terminals"),
298           "F" => _("phones"),
299           "P" => _("printers"));
301       $type= preg_replace('/[\[\]]/', '', $this->gosaGroupObjects);
302       $p1= $conv[$type[0]];
303       error_reporting(0);
304       if (isset($type[1]) && preg_match('/[UGADSFOWTP]/', $type[1])){
305         $p2= $conv[$type[1]];
306         $smarty->assign("combinedObjects", "$p1 "._("and")." $p2");
307       } else {
308         $smarty->assign("combinedObjects", "$p1");
309       }
310       error_reporting(E_ALL | E_STRICT);
311     }
313     /* Assign variables */
314     $smarty->assign("bases", $this->get_allowed_bases());
315     $smarty->assign("base_select", $this->base);
316     $smarty->assign("department", $this->department);
317     $smarty->assign("members", $this->convert_list($this->memberList));
319     /* Objects have to be tuned... */
320     $smarty->assign("objects", $this->convert_list($this->objects));
322     /* Fields */
323     foreach ($this->attributes as $val){
324       $smarty->assign("$val", $this->$val);
325     }
327     return ($smarty->fetch (get_template_path('generic.tpl', TRUE)));
328   }
331   /* Save data to object */
332   function save_object()
333   {
334     /* Save additional values for possible next step */
335     if (isset($_POST['ogroupedit'])){
337       /* Create a base backup and reset the
338          base directly after calling plugin::save_object();
339          Base will be set seperatly a few lines below */
340       $base_tmp = $this->base;
341       plugin::save_object();
342       $this->base = $base_tmp;
344       /* Save base, since this is no LDAP attribute */
345       $tmp = $this->get_allowed_bases();
346       if(isset($_POST['base'])){
347         if(isset($tmp[$_POST['base']])){
348           $this->base= $_POST['base'];
349         }
350       }
351     }
352   }
355   /* (Re-)Load objects */
356   function reload()
357   {
358     /*###########
359       Variable initialisation 
360       ###########*/
362     $this->objects                = array();
363     $this->ui                     = get_userinfo();
364     $filter                       = "";
365     $objectClasses                = array();
366     
367     $ogfilter               = session::get("ogfilter");
368     $regex                  = $ogfilter['regex'];
370     $ldap= $this->config->get_ldap_link();
371     $ldap->cd ($ogfilter['dselect']);
374     /*###########
375       Generate Filter 
376       ###########*/
378     $p_f= array("accounts"        => array("CLASS"=>"gosaAccount"    ,"DN"=> get_people_ou()           ,"ACL" => "users"), 
379                 "groups"          => array("CLASS"=>"posixGroup"     ,"DN"=> get_groups_ou('ogroupou') ,"ACL" => "groups"), 
380                 "applications"    => array("CLASS"=>"gosaApplication","DN"=> get_ou('applicationou')   ,"ACL" => "application"), 
381                 "departments"     => array("CLASS"=>"gosaDepartment" ,"DN"=> ""                        ,"ACL" => "department"), 
382                 "servers"         => array("CLASS"=>"goServer"       ,"DN"=> get_ou('serverou')        ,"ACL" => "server"),
383                 "workstations"    => array("CLASS"=>"gotoWorkstation","DN"=> get_ou('workstationou')   ,"ACL" => "workstation"),
384                 "winstations"    => array("CLASS"=>"opsiClient",        "DN"=> get_ou('WINSTATIONS')     ,"ACL" => "winstation"),
385                 "terminals"       => array("CLASS"=>"gotoTerminal"   ,"DN"=> get_ou('terminalou')      ,"ACL" => "terminal"),
386                 "printers"        => array("CLASS"=>"gotoPrinter"    ,"DN"=> get_ou('printerou')       ,"ACL" => "printer"),
387                 "phones"          => array("CLASS"=>"goFonHardware"  ,"DN"=> get_ou('phoneou')         ,"ACL" => "phone"));
390     /*###########
391       Perform search for selected objectClasses & regex to fill list with objects   
392       ###########*/
394     $Get_list_flags = 0;
395     if($ogfilter['subtrees'] == "checked"){
396       $Get_list_flags |= GL_SUBSEARCH;
397     }    
399     foreach($p_f as $post_name => $data){
401       if($ogfilter[$post_name] == "checked"){
403         if($ogfilter['subtrees']){
404           $base =  $ogfilter['dselect'];
405         }else{
406           $base =  $data['DN'].$ogfilter['dselect'];
407         }
408     
409         $filter = "(&(objectClass=".$data['CLASS'].")(|(uid=$regex)(cn=$regex)(ou=$regex)))";
410         $res    = get_list($filter, $data['ACL']  , $base, 
411                     array("description", "objectClass", "sn", "givenName", "uid","ou","cn"),$Get_list_flags);
413         /* fetch results and append them to the list */
414         foreach($res as $attrs){
416           $type= $this->getObjectType($attrs);
417           $name= $this->getObjectName($attrs);
419           /* Fill array */
420           if (isset($attrs["description"][0])){
421             $this->objects[$attrs["dn"]]= array("text" => "$name [".$attrs["description"][0]."]", "type" => "$type");
422           } elseif (isset($attrs["uid"][0])) {
423             $this->objects[$attrs["dn"]]= array("text" => "$name [".$attrs["uid"][0]."]", "type" => "$type");
424           } else {
425             $this->objects[$attrs["dn"]]= array("text" => "$name", "type" => "$type");
426           }
427         }
428       }
429     }
430     uasort ($this->objects, 'sort_list');
431     reset ($this->objects);
433     
434     /*###########
435       Build member list and try to detect obsolete entries 
436       ###########*/
438     $this->memberList = array();
439   
440     /* Walk through all single member entry */
441     foreach($this->member as $dn){
443       /* The dn for the current member can't be resolved 
444          it seams that this entry was removed 
445        */ 
446       /* Try to resolv the entry again, if it still fails, display error msg */
447       $ldap->cat($dn, array("cn", "sn", "givenName", "ou", "description", "objectClass"));
449       /* It has failed, add entry with type flag I (Invalid)*/
450       if ($ldap->error != "Success"){
451         $this->memberList[$dn]= array('text' => _("Non existing dn:")." ".@LDAP::fix($dn),"type" => "I");
453       } else {
455         /* Append this entry to our all object list */
457         /* Fetch object */
458         $attrs= $ldap->fetch();
460         $type= $this->getObjectType($attrs);
461         $name= $this->getObjectName($attrs);
463         if (isset($attrs["description"][0])){
464           $this->objcache[$attrs["dn"]]= array("text" => "$name [".$attrs["description"][0]."]", "type" => "$type");
465         } elseif (isset($attrs["uid"][0])) {
466           $this->objcache[$attrs["dn"]]= array("text" => "$name [".$attrs["uid"][0]."]", "type" => "$type");
467         } else {
468           $this->objcache[$attrs["dn"]]= array("text" => "$name", "type" => "$type");
469         }
470         $this->objcache[$attrs["dn"]]['objectClass']  = $attrs['objectClass'];
471         if(isset($attrs['uid'])){
472           $this->objcache[$attrs["dn"]]['uid']          = $attrs['uid'];
473         }
475         /* Fill array */
476         if (isset($attrs["description"][0])){
477           $this->objects[$attrs["dn"]]= array("text" => "$name [".$attrs["description"][0]."]", "type" => "$type");
478         } else {
479           $this->objects[$attrs["dn"]]= array("text" => "$name", "type" => "$type");
480         }
482         $this->memberList[$dn]= $this->objects[$attrs["dn"]];
483       }
484     }
485     uasort ($this->memberList, 'sort_list');
486     reset ($this->memberList);
488     /* Assemble types of currently combined objects */
489     $objectTypes= "";
490     foreach ($this->memberList as $dn => $desc){
492       /* Invalid object? */
493       if ($desc['type'] == 'I'){
494         continue;
495       }
497       /* Fine. Add to list. */
498       if (!preg_match('/'.$desc['type'].'/', $objectTypes)){
499         $objectTypes.= $desc['type'];
500       }
501     }
502     $this->gosaGroupObjects= "[$objectTypes]";
503   }
506   function convert_list($input)
507   {
508     $temp= "";
509     $conv= array(  "U" => "select_user.png",
510         "G" => "select_groups.png",
511         "A" => "select_application.png",
512         "D" => "select_department.png",
513         "S" => "select_server.png",
514         "W" => "select_workstation.png",
515         "O" => "select_winstation.png",
516         "T" => "select_terminal.png",
517         "F" => "select_phone.png",
518         "I" => "flag.png",
519         "P" => "select_printer.png");
521     foreach ($input as $key => $value){
522       /* Generate output */
523       $temp.= "<option title='".addslashes( $key)."' value=\"$key\" class=\"select\" style=\"background-image:url('".get_template_path("images/".$conv[$value['type']])."');\">".$value['text']."</option>\n";
524     }
526     return ($temp);
527   }
530   function getObjectType($attrs)
531   {
532     $type= "I";
534     foreach(array(  "U" => "gosaAccount",
535           "G" => "posixGroup",
536           "A" => "gosaApplication",
537           "D" => "gosaDepartment",
538           "S" => "goServer",
539           "W" => "gotoWorkstation",
540           "O" => "opsiClient",
541           "T" => "gotoTerminal",
542           "F" => "goFonHardware",
543           "P" => "gotoPrinter") as $index => $class){
544       if (in_array($class, $attrs['objectClass'])){
545         $type= $index;
546         break;
547       }
548     }
550     return ($type);
551   }
554   function getObjectName($attrs)
555   {
556     /* Person? */
557     $name =""; 
558     if (in_array('gosaAccount', $attrs['objectClass'])){
559       if(isset($attrs['sn']) && isset($attrs['givenName'])){
560         $name= $attrs['sn'][0].", ".$attrs['givenName'][0];
561       } else {
562         $name= $attrs['uid'][0];
563       }
564     } else {
565       if(isset($attrs["cn"][0])) {
566         $name= $attrs['cn'][0];
567       } else {
568         $name= $attrs['ou'][0];
569       }
570     }
572     return ($name);
573   }
576   function check()
577   {
578     /* Call common method to give check the hook */
579     $message= plugin::check();
581     /* Permissions for that base? */
582     if ($this->base != ""){
583       $new_dn= 'cn='.$this->cn.','.get_ou('ogroupou').$this->base;
584     } else {
585       $new_dn= $this->dn;
586     }
589     $ldap = $this->config->get_ldap_link();
590     if($this->dn != $new_dn){
591       $ldap->cat ($new_dn, array('dn'));
592     }
593     
594     if($ldap->count() !=0){
595       $message[]= _("There is already an object with this cn.");
596     } 
598     /* Set new acl base */
599     if($this->dn == "new") {
600       $this->set_acl_base($this->base);
601     }
603     /* must: cn */
604     if ($this->cn == ""){
605       $message[]= "The required field 'Name' is not set.";
606     }
608     /* To many different object types? */
609     if (strlen($this->gosaGroupObjects) > 4){
610       $message[]= _("You can combine two different object types at maximum only!");
611     }
613     return ($message);
614   }
617   /* Save to LDAP */
618   function save()
619   {
620     plugin::save();
622     /* Move members to target array */
623     $this->attrs['member'] =array();
624     foreach ($this->member as $key => $desc){
625       $this->attrs['member'][]= @LDAP::fix($key);
626     }
628     $ldap= $this->config->get_ldap_link();
630     /* New accounts need proper 'dn', propagate it to remaining objects */
631     if ($this->dn == 'new'){
632       $this->dn= 'cn='.$this->cn.','.get_ou('ogroupou').$this->base;
633     }
635     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
636        new entries. So do a check first... */
637     $ldap->cat ($this->dn, array('dn'));
638     if ($ldap->fetch()){
639       /* Modify needs array() to remove values :-( */
640       if (!count ($this->member)){
641         $this->attrs['member']= array();
642       }
643       $mode= "modify";
645     } else {
646       $mode= "add";
647       $ldap->cd($this->config->current['BASE']);
648       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
649     }
651     /* Write back to ldap */
652     $ldap->cd($this->dn);
653     $this->cleanup();
654     $ldap->$mode($this->attrs);
656     if($mode == "add"){
657       new log("create","ogroups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
658     }else{
659       new log("modify","ogroups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
660     }
662     /* Trigger post signal */
663     $this->handle_post_events($mode);
665     $ret= 0;
666     if (show_ldap_error($ldap->get_error(), sprintf(_("Saving of object group/generic with dn '%s' failed."),$this->dn))){
667       $ret= 1;
668     }
670     return ($ret);
671   }
673   function remove_from_parent()
674   {
675     plugin::remove_from_parent();
677     $ldap= $this->config->get_ldap_link();
678     $ldap->rmdir($this->dn);
679     show_ldap_error($ldap->get_error(), sprintf(_("Removing of object group/generic with dn '%s' failed."),$this->dn));
681     new log("remove","ogroups/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
683     /* Trigger remove signal */
684     $this->handle_post_events("remove");
685   }
687   
688   function PrepareForCopyPaste($source)
689   {
690     /* Update available object types */
691     if(isset($source['gosaGroupObjects'][0])){
692       $this->gosaGroupObjects =  $source['gosaGroupObjects'][0];
693     }
695     /* Reload tabs */
696     $this->parent->reload($this->gosaGroupObjects );
697    
698     /* Reload plugins */ 
699     foreach($this->parent->by_object as $name => $class ){
700       if(get_class($this) != $name) {
701         $this->parent->by_object[$name]->PrepareForCopyPaste($source);
702       }
703     }
705     /* Load member objects */
706     if (isset($source['member'])){
707       foreach ($source['member'] as $key => $value){
708         if ("$key" != "count"){
709           $value= @LDAP::convert($value);
710           $this->member["$value"]= "$value";
711         }
712       }
713     }
715   }
718   function getCopyDialog()
719   {
720     $smarty = get_smarty();
721     $smarty->assign("cn",     $this->cn);
722     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
723     $ret = array();
724     $ret['string'] = $str;
725     $ret['status'] = "";
726     return($ret);
727   }
729   function saveCopyDialog()
730   {
731     if(isset($_POST['cn'])){
732       $this->cn = $_POST['cn'];
733     }
734   }
737   static function plInfo()
738   {
739     return (array(
740           "plShortName"   => _("Generic"),
741           "plDescription" => _("Object group generic"),
742           "plSelfModify"  => FALSE,
743           "plDepends"     => array(),
744           "plPriority"    => 1,
745           "plSection"     => array("administration"),
746           "plCategory"    => array("ogroups" => array("description"  => _("Object groups"),
747                                                       "objectClass"  => "gosaGroupOfNames")),
748           "plProvidedAcls"=> array(
749             "cn"                => _("Name"),
750             "base"              => _("Base"),
751             "description"       => _("Description"),
752             "member"            => _("Member"))
753           ));
754   }
757 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
758 ?>