Code

Fix issues with broken dn's
[gosa.git] / gosa-core / plugins / personal / posix / class_posixAccount.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 /*!
24   \brief   posixAccount plugin
25   \author  Cajus Pollmeier <pollmeier@gonicus.de>
26   \version 2.00
27   \date    24.07.2003
29   This class provides the functionality to read and write all attributes
30   relevant for posixAccounts and shadowAccounts from/to the LDAP. It
31   does syntax checking and displays the formulars required.
32  */
34 class posixAccount extends plugin
35 {
36   /* Definitions */
37   var $plHeadline= "UNIX";
38   var $plDescription= "Edit users POSIX settings";
40   /* Plugin specific values */
41   var $homeDirectory= "";
42   var $loginShell= "/bin/bash";
43   var $uidNumber= "";
44   var $gidNumber= "";
45   var $gecos= "";
46   var $shadowMin= "0";
47   var $shadowMax= "0";
48   var $shadowWarning= "0";
49   var $shadowLastChange= "0";
50   var $shadowInactive= "0";
51   var $shadowExpire= "";
52   var $gosaDefaultPrinter= "";
53   var $accessTo= array();
54   var $trustModel= "";
56   var $glist=array();
57   var $status= "";
58   var $loginShellList= array();
59   var $groupMembership= array();
60   var $savedGroupMembership= array();
61   var $savedUidNumber= "";
62   var $savedGidNumber= "";
63   var $activate_shadowMin= "0";
64   var $activate_shadowMax= "0";
65   var $activate_shadowWarning= "0";
66   var $activate_shadowInactive= "0";
67   var $activate_shadowExpire= "0";
68   var $mustchangepassword= "0";
69   var $force_ids= 0;
70   var $gotoLastSystemLogin= "";
71   var $group_dialog= FALSE;
72   var $show_ws_dialog= FALSE;
73   var $secondaryGroups= array();
74   var $primaryGroup= 0;
75   var $was_trust_account= FALSE;
76   var $memberGroup= array();
77   var $grouplist= array();
78   var $ui= array();
79   var $ssh= null;
80   var $sshAcl= "";
82   var $GroupRegex= "*";
83   var $GroupUserRegex= "*";
84   var $SubSearch= false;
86   var $view_logged= false;
88   /* attribute list for save action */
89   var $CopyPasteVars  = 
90       array("grouplist","groupMembership","activate_shadowMin",
91       "activate_shadowMax","activate_shadowWarning","activate_shadowInactive","activate_shadowExpire",
92       "must_change_password","printerList","grouplist","savedGidNumber","savedUidNumber");
94   var $attributes     = array("homeDirectory", "loginShell", "uidNumber", "gidNumber", "gecos",
95       "shadowMin", "shadowMax", "shadowWarning", "shadowInactive", "shadowLastChange",
96       "shadowExpire", "gosaDefaultPrinter", "uid","accessTo","trustModel", "gotoLastSystemLogin");
98   var $objectclasses= array("posixAccount", "shadowAccount");
100   var $uid= "";
101   var $multiple_support = TRUE;
102   var $groupMembership_some = array();
104   /* constructor, if 'dn' is set, the node loads the given
105      'dn' from LDAP */
106   function posixAccount (&$config, $dn= NULL)
107   {
108     global $class_mapping;
110     /* Configuration is fine, allways */
111     $this->config= $config;
113     /* Load bases attributes */
114     plugin::plugin($config, $dn);
116     /*  If gotoLastSystemLogin is available read it from ldap and create a readable
117         date time string, fallback to sambaLogonTime if available.
118      */
119     if(isset($this->attrs['gotoLastSystemLogin'][0]) && preg_match("/^[0-9]*$/",$this->attrs['gotoLastSystemLogin'][0])){
120       $this->gotoLastSystemLogin = date("d.m.Y H:i:s", strtotime($this->attrs['gotoLastSystemLogin'][0]));
121     } else if(isset($this->attrs['sambaLogonTime'][0]) && preg_match("/^[0-9]*$/",$this->attrs['sambaLogonTime'][0])){
122       $this->gotoLastSystemLogin = date("d.m.Y H:i:s", $this->attrs['sambaLogonTime'][0]);
123     }
125     /* Setting uid to default */
126     if(isset($this->attrs['uid'][0])){
127       $this->uid = $this->attrs['uid'][0];
128     }
130     $ldap= $this->config->get_ldap_link();
132     if ($dn !== NULL){
134       /* Correct is_account. shadowAccount is not required. */
135       if (isset($this->attrs['objectClass']) &&
136           in_array ('posixAccount', $this->attrs['objectClass'])){
138         $this->is_account= TRUE;
139       }
141       /* Is this account a trustAccount? */
142       if ($this->is_account && isset($this->attrs['trustModel'])){
143         $this->trustModel= $this->attrs['trustModel'][0];
144         $this->was_trust_account= TRUE;
145       } else {
146         $this->was_trust_account= FALSE;
147         $this->trustModel= "";
148       }
150       $this->accessTo = array(); 
151       if ($this->is_account && isset($this->attrs['accessTo'])){
152         for ($i= 0; $i<$this->attrs['accessTo']['count']; $i++){
153           $tmp= $this->attrs['accessTo'][$i];
154           $this->accessTo[$tmp]= $tmp;
155         }
156       }
157       $this->initially_was_account= $this->is_account;
159       /* Fill group */
160       $this->primaryGroup= $this->gidNumber;
162       /* Generate status text */
163       $current= date("U");
165       $current= floor($current / 60 /60 / 24);
167       if (($current >= $this->shadowExpire) && $this->shadowExpire){
168         $this->status= _("expired");
169         if (($current - $this->shadowExpire) < $this->shadowInactive){
170           $this->status.= ", "._("grace time active");
171         }
172       } elseif (($this->shadowLastChange + $this->shadowMin) >= $current){
173         $this->status= _("active").", "._("password not changeable");
174       } elseif (($this->shadowLastChange + $this->shadowMax) >= $current){
175         $this->status= _("active").", "._("password expired");
176       } else {
177         $this->status= _("active");
178       }
180       /* Get group membership */
181       $ldap->cd($this->config->current['BASE']);
182       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("cn", "description"));
184       while ($attrs= $ldap->fetch()){
185         if (!isset($attrs["description"][0])){
186           $entry= $attrs["cn"][0];
187         } else {
188           $entry= $attrs["cn"][0]." [".$attrs["description"][0]."]";
189         }
190         $this->groupMembership[$ldap->getDN()]= $entry;
191       }
192       asort($this->groupMembership);
193       reset($this->groupMembership);
194       $this->savedGroupMembership= $this->groupMembership;
195       $this->savedUidNumber= $this->uidNumber;
196       $this->savedGidNumber= $this->gidNumber;
198       // Instanciate SSH object if available
199       if (isset($class_mapping["sshPublicKey"])){
200         if (empty($this->acl_base)){
201           $this->acl_base= $config->current['BASE'];
202         }
204         $this->sshAcl= $this->getacl("sshPublicKey");
205         $this->ssh= new sshPublicKey($this->config, $this->dn, $this->sshAcl);
206       }
207     }
209     /* Adjust shadow checkboxes */
210     foreach (array("shadowMin", "shadowMax", "shadowWarning", "shadowInactive",
211           "shadowExpire") as $val){
213       if ($this->$val != 0){
214         $oval= "activate_".$val;
215         $this->$oval= "1";
216       }
217     }
219     /* Convert shadowExpire for usage */
220     if ($this->shadowExpire == 0){
221       $this->shadowExpire= "";
222     } else {
223       $this->shadowExpire= date('d.m.Y', $this->shadowExpire * 60 * 60 * 24);
224     }
227     /* Generate shell list from CONFIG_DIR./shells */
228     if (file_exists(CONFIG_DIR.'/shells')){
229       $shells = file (CONFIG_DIR.'/shells');
230       foreach ($shells as $line){
231         if (!preg_match ("/^#/", $line)){
232           $this->loginShellList[]= trim($line);
233         }
234       }
235     } else {
236       if ($this->loginShell == ""){
237         $this->loginShellList[]= _("unconfigured");
238       }
239     }
241     /* Insert possibly missing loginShell */
242     if ($this->loginShell != "" && !in_array($this->loginShell, $this->loginShellList)){
243       $this->loginShellList[]= $this->loginShell;
244     }
246     /* Generate group list */
247     $this->ui = get_userinfo(); 
248     $this->secondaryGroups[]= "- "._("automatic")." -";
249     $ldap->cd($this->config->current['BASE']);
250     $ldap->search("(objectClass=posixGroup)", array("cn", "gidNumber"));
251     while($attrs = $ldap->fetch()){
252       $this->secondaryGroups[$attrs['gidNumber'][0]]= $attrs['cn'][0];
253     }
254     asort ($this->secondaryGroups);
256     /* Get global filter config */
257     if (!session::is_set("sysfilter")){
258       $ui= get_userinfo();
259       $base= get_base_from_people($ui->dn);
260       $sysfilter= array( "depselect"       => $base,
261           "regex"           => "*");
262       session::set("sysfilter", $sysfilter);
263     }
264     $this->ui = get_userinfo();
265   }
268   /* execute generates the html output for this node */
269   function execute($isCopyPaste = false)
270   {
271     /* Call parent execute */
272     plugin::execute();
273     $display= "";
275     /* Log view */
276     if($this->is_account && !$this->view_logged){
277       $this->view_logged = TRUE;
278       new log("view","users/".get_class($this),$this->dn);
279     }
281     /* Department has changed? */
282     if(isset($_POST['depselect'])){
283       session::set('CurrentMainBase',validate($_POST['depselect']));
284     }
286     if($this->multiple_support_active){
287       $this->is_account = TRUE;
288     }
290     if(!$isCopyPaste && ! $this->multiple_support_active){
292       /* Do we need to flip is_account state? */
293       if(isset($_POST['modify_state'])){
294         if($this->is_account && $this->acl_is_removeable()){
295           $this->is_account= FALSE;
296         }elseif(!$this->is_account && $this->acl_is_createable()){
297           $this->is_account= TRUE;
298         }
299       }
301       /* Do we represent a valid posixAccount? */
302       if (!$this->is_account && $this->parent === NULL ){
303         $display= "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
304           msgPool::noValidExtension(_("POSIX"))."</b>";
305         $display.= back_to_main();
306         return ($display);
307       }
310       /* Show tab dialog headers */
311       if ($this->parent !== NULL){
312         if ($this->is_account){
313           if (isset($this->parent->by_object['sambaAccount'])){
314             $obj= $this->parent->by_object['sambaAccount'];
315           }
316           if (isset($obj) && $obj->is_account == TRUE &&
317               ((isset($this->parent->by_object['sambaAccount']))&&($this->parent->by_object['sambaAccount']->is_account))
318               ||(isset($this->parent->by_object['environment'] ))&&($this->parent->by_object['environment'] ->is_account)){
320             /* Samba3 dependency on posix accounts are enabled
321                in the moment, because I need to rely on unique
322                uidNumbers. There'll be a better solution later
323                on. */
324             $display= $this->show_disable_header(msgPool::removeFeaturesButton(_("POSIX")), msgPool::featuresEnabled(_("POSIX"), array(_("Samba"), _("Environment"))), TRUE);
325           } else {
326             $display= $this->show_disable_header(msgPool::removeFeaturesButton(_("POSIX")), msgPool::featuresEnabled(_("POSIX")));
327           }
328         } else {
329           $display= $this->show_enable_header(msgPool::addFeaturesButton(_("POSIX")), msgPool::featuresDisabled(_("POSIX")));
330           return($display);
331         }
332       }
333     }
335     /* Trigger group edit? */
336     if (isset($_POST['edit_groupmembership'])){
337       $this->group_dialog= TRUE;
338       $this->dialog= TRUE;
339     }
341     /* Cancel group edit? */
342     if (isset($_POST['add_groups_cancel']) ||
343         isset($_POST['add_groups_finish'])){
344       $this->group_dialog= FALSE;
345       $this->dialog= FALSE;
346     }
348     /* Add selected groups */
349     if (isset($_POST['add_groups_finish']) && isset($_POST['groups']) &&
350         count($_POST['groups'])){
352       $this->addGroup ($_POST['groups']);
353     }
355     /* Delete selected groups */
356     if (isset($_POST['delete_groupmembership']) && 
357         isset($_POST['group_list']) && count($_POST['group_list'])){
359       $this->delGroup ($_POST['group_list']);
360     }
362     /* Add user workstation? */
363     if (isset($_POST["add_ws"])){
364       $this->show_ws_dialog= TRUE;
365       $this->dialog= TRUE;
366     }
368     /* Add user workstation? */
369     if (isset($_POST["add_ws_finish"]) && isset($_POST['wslist'])){
370       foreach($_POST['wslist'] as $ws){
371         $this->accessTo[$ws]= $ws;
372       }
373       ksort($this->accessTo);
374       $this->is_modified= TRUE;
375     }
377     /* Remove user workstations? */
378     if (isset($_POST["delete_ws"]) && isset($_POST['workstation_list'])){
379       foreach($_POST['workstation_list'] as $name){
380         unset ($this->accessTo[$name]);
381       }
382       $this->is_modified= TRUE;
383     }
385     /* Add user workstation finished? */
386     if (isset($_POST["add_ws_finish"]) || isset($_POST["add_ws_cancel"])){
387       $this->show_ws_dialog= FALSE;
388       $this->dialog= FALSE;
389     }
391     /* Templates now! */
392     $smarty= get_smarty();
393     $smarty->assign("usePrototype", "true");
395     /* Show ws dialog */
396     if ($this->show_ws_dialog){
397       /* Save data */
398       $sysfilter= session::get("sysfilter");
399       foreach( array("depselect", "regex") as $type){
400         if (isset($_POST[$type])){
401           $sysfilter[$type]= $_POST[$type];
402         }
403       }
404       if (isset($_GET['search'])){
405         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
406         if ($s == "**"){
407           $s= "*";
408         }
409         $sysfilter['regex']= $s;
410       }
411       session::set("sysfilter", $sysfilter);
413       /* Get workstation list */
414       $exclude= "";
415       foreach($this->accessTo as $ws){
416         $exclude.= "(cn=$ws)";
417       }
418       if ($exclude != ""){
419         $exclude= "(!(|$exclude))";
420       }
421       $regex= $sysfilter['regex'];
423       $acls = array();
424       if(class_available("servgeneric")) $acls[] = "server";
425       if(class_available("workgeneric")) $acls[] = "worstation";
426       if(class_available("termgeneric")) $acls[] = "terminal";
428       $filter= "(&(|(objectClass=goServer)(objectClass=gotoWorkstation)(objectClass=gotoTerminal))$exclude(cn=*)(cn=$regex))";
430       $deps_a = array(get_ou("serverRDN"),
431                       get_ou("terminalRDN"),
432                       get_ou("workstationRDN")); 
434       $res= get_sub_list($filter, $acls, $deps_a, get_ou("systemRDN").$sysfilter['depselect'], array("cn"), GL_SUBSEARCH | GL_SIZELIMIT);
435       $wslist= array();
436       foreach ($res as $attrs){
437         $wslist[]= preg_replace('/\$/', '', $attrs['cn'][0]);
438       }
439       asort($wslist);
440       $smarty->assign("search_image", get_template_path('images/lists/search.png'));
441       $smarty->assign("launchimage", get_template_path('images/lists/action.png'));
442       $smarty->assign("tree_image", get_template_path('images/lists/search-subtree.png'));
443       $smarty->assign("deplist", $this->config->idepartments);
444       $smarty->assign("alphabet", generate_alphabet());
445       foreach( array("depselect", "regex") as $type){
446         $smarty->assign("$type", $sysfilter[$type]);
447       }
448       $smarty->assign("hint", print_sizelimit_warning());
449       $smarty->assign("wslist", $wslist);
450       $smarty->assign("apply", apply_filter());
451       $display= $smarty->fetch (get_template_path('trust_machines.tpl', TRUE, dirname(__FILE__)));
452       return ($display);
453     }
455     /* Manage group add dialog */
456     if ($this->group_dialog){
458       /* Get global filter config */
459       $this->reload();
461       /* remove already assigned groups */
462       $glist= array();
463       foreach ($this->grouplist as $key => $value){
464         if (!isset($this->groupMembership[$key]) && obj_is_writable($key,"groups/group","memberUid")){
465           $glist[$key]= $value;
466         }
467       }
469       if($this->SubSearch){
470         $smarty->assign("SubSearchCHK"," checked ");
471       }else{
472         $smarty->assign("SubSearchCHK","");
473       }
475       $smarty->assign("regex",$this->GroupRegex);
476       $smarty->assign("guser",$this->GroupUserRegex);
477       $smarty->assign("groups", $glist);
478       $smarty->assign("search_image", get_template_path('images/lists/search.png'));
479       $smarty->assign("launchimage", get_template_path('images/lists/action.png'));
480       $smarty->assign("tree_image", get_template_path('images/lists/search-subtree.png'));
481       $smarty->assign("deplist", $this->config->idepartments);
482       $smarty->assign("alphabet", generate_alphabet());
483       $smarty->assign("depselect", session::get('CurrentMainBase'));
484       $smarty->assign("hint", print_sizelimit_warning());
485       $smarty->assign("apply", apply_filter());
487       $display.= $smarty->fetch (get_template_path('posix_groups.tpl', TRUE, dirname(__FILE__)));
488       return ($display);
489     }
491     // Handle ssh dialog?
492     if ($this->ssh instanceOf sshPublicKey && preg_match('/[rw]/', $this->getacl("sshPublicKey"))) {
493         $smarty->assign("usePrototype", "false");
494        if ($result= $this->ssh->execute()) {
495          $this->dialog= true;
496          return $result;
497        }
498        $this->dialog= false;
499     }
502     /* Show main page */
503     $smarty= get_smarty();
505     /* In 'MyAccount' mode, we must remove write acls if we are not in editing mode. */ 
506     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
508     $smarty->assign("sshPublicKeyACL", $this->getacl("sshPublicKey", $SkipWrite));
510     /* Depending on pwmode, currently hardcoded because there are no other methods */
511     if ( 1 == 1 ){
512       $smarty->assign("pwmode", dirname(__FILE__)."/posix_shadow");
514       $shadowMinACL     =  $this->getacl("shadowMin",$SkipWrite);
515       $smarty->assign("shadowmins", sprintf(_("Password can't be changed up to %s days after last change"), 
516                                               "<input name=\"shadowMin\" size=3 maxlength=4 value=\"".$this->shadowMin."\">"));
518       $shadowMaxACL     =  $this->getacl("shadowMax",$SkipWrite);
519       $smarty->assign("shadowmaxs", sprintf(_("Password must be changed after %s days"), 
520                                               "<input name=\"shadowMax\" size=3 maxlength=4 value=\"".$this->shadowMax."\">"));
522       $shadowInactiveACL=  $this->getacl("shadowInactive",$SkipWrite);
523       $smarty->assign("shadowinactives", sprintf(_("Disable account after %s days of inactivity after password expiry"), 
524                                               "<input name=\"shadowInactive\" size=3 maxlength=4 value=\"".$this->shadowInactive."\">"));
526       $shadowWarningACL =  $this->getacl("shadowWarning",$SkipWrite);
527       $smarty->assign("shadowwarnings", sprintf(_("Warn user %s days before password expiry"), 
528                                               "<input name=\"shadowWarning\" size=3 maxlength=4 value=\"".$this->shadowWarning."\">"));
530       foreach( array("activate_shadowMin", "activate_shadowMax",
531                      "activate_shadowExpire", "activate_shadowInactive","activate_shadowWarning") as $val){
532         if ($this->$val == 1){
533           $smarty->assign("$val", "checked");
534         } else {
535           $smarty->assign("$val", "");
536         }
537         $smarty->assign("$val"."ACL", $this->getacl($val,$SkipWrite));
538       }
540       $smarty->assign("mustchangepasswordACL", $this->getacl("mustchangepassword",$SkipWrite));
541     }
543     // Set last system login
544     $smarty->assign("gotoLastSystemLogin",$this->gotoLastSystemLogin);
546     /* Fill arrays */
547     $smarty->assign("shells", $this->loginShellList);
548     $smarty->assign("secondaryGroups", $this->secondaryGroups);
549     $smarty->assign("primaryGroup", $this->primaryGroup);
550     if(!$this->multiple_support_active){
551       if (!count($this->groupMembership)){
552         $smarty->assign("groupMembership", array("&nbsp;"));
553       } else {
554         $smarty->assign("groupMembership", $this->groupMembership);
555       }
556     }else{
557       $smarty->assign("groupMembership", $this->groupMembership);
558       $smarty->assign("groupMembership_some", $this->groupMembership_some);
559     }
560     if (count($this->groupMembership) > 16){
561       $smarty->assign("groups", "too_many_for_nfs");
562     } else {
563       $smarty->assign("groups", "");
564     }
566     /* Avoid "Undefined index: forceMode" */
567     $smarty->assign("forceMode", "");
569     /* Checkboxes */
570     if ($this->force_ids == 1){
571       $smarty->assign("force_ids", "checked");
572       if (session::get('js')){
573         $smarty->assign("forceMode", "");
574       }
575     } else {
576       if (session::get('js')){
577         $smarty->assign("forceMode", "disabled");
578       }
579       $smarty->assign("force_ids", "");
580     }
582     /* Create onClick="" action string for the "Force UID/GID" option 
583      */
584     $onClickIDS ="";
585     if(preg_match("/w/",$this->getacl("uidNumber",$SkipWrite))){
586       $onClickIDS .= "changeState('uidNumber');";
587     }
588     if(preg_match("/w/",$this->getacl("gidNumber",$SkipWrite))){
589       $onClickIDS .= "changeState('gidNumber');";
590     }
591     $smarty->assign("onClickIDS", $onClickIDS);
592     $smarty->assign("force_idsACL", $this->getacl("uidNumber",$SkipWrite).$this->getacl("gidNumber",$SkipWrite));
594     foreach(array("primaryGroup","trustmode","activate_shadowWarning","activate_shadowInactive","activate_shadowMin","activate_shadowMax","activate_shadowExpire","mustchangepassword") as $val){
595       if(in_array($val,$this->multi_boxes)){
596         $smarty->assign("use_".$val,TRUE);
597       }else{
598         $smarty->assign("use_".$val,FALSE);
599       }
600     }
603     /* Load attributes and acl's */
604     foreach($this->attributes as $val){
605       if(in_array($val,$this->multi_boxes)){
606         $smarty->assign("use_".$val,TRUE);
607       }else{
608         $smarty->assign("use_".$val,FALSE);
609       }
611       if((session::get("js"))&&(($val=="uidNumber")||($val=="gidNumber")))
612       {
613         $smarty->assign("$val"."ACL",$this->getacl($val,$SkipWrite));
614         $smarty->assign("$val", $this->$val);
615         continue;
616       }
617       $smarty->assign("$val", $this->$val);
618       $smarty->assign("$val"."ACL", $this->getacl($val,$SkipWrite));
619     }
620     if($SkipWrite){
621       $smarty->assign("groupMembershipACL","r");
622     }else{
623       $smarty->assign("groupMembershipACL","rw");
624     }
625     $smarty->assign("status", $this->status);
627     /* Work on trust modes */
628     $smarty->assign("trusthide", " disabled ");
629     $smarty->assign("trustmodeACL",  $this->getacl("trustModel",$SkipWrite));
630     if ($this->trustModel == "fullaccess"){
631       $trustmode= 1;
632       // pervent double disable tag in html code, this will disturb our clean w3c html
633       $smarty->assign("trustmode",  $this->getacl("trustModel",$SkipWrite));
635     } elseif ($this->trustModel == "byhost"){
636       $trustmode= 2;
637       $smarty->assign("trusthide", "");
638     } else {
639       // pervent double disable tag in html code, this will disturb our clean w3c html
640       $smarty->assign("trustmode",  $this->getacl("trustModel",$SkipWrite));
641       $trustmode= 0;
642     }
643     $smarty->assign("trustmode", $trustmode);
644     $smarty->assign("trustmodes", array( 0 => _("disabled"), 1 => _("full access"),
645           2 => _("allow access to these hosts")));
649     if((count($this->accessTo))==0)
650       $smarty->assign("emptyArrAccess",true);
651     else
652       $smarty->assign("emptyArrAccess",false);
654       if($this->mustchangepassword){
655         $smarty->assign("mustchangepassword", " checked ");
656       } else {
657         $smarty->assign("mustchangepassword", "");
658       }
660     $smarty->assign("workstations", $this->accessTo);
662     // Add SSH button if available
663     $smarty->assign("sshPublicKey", $this->ssh?1:0);
665     $smarty->assign("apply", apply_filter());
666     $smarty->assign("multiple_support" , $this->multiple_support_active);
667     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
668     return($display);
669   }
672   /* remove object from parent */
673   function remove_from_parent()
674   {
675     /* Cancel if there's nothing to do here */
676     if ((!$this->initially_was_account) || (!$this->acl_is_removeable())){
677       return;
678     }
681     /* Remove and write to LDAP */
682     plugin::remove_from_parent();
684     /* Zero out array */
685     $this->attrs['gosaHostACL']= array();
687     /* Keep uid, because we need it for authentification! */
688     unset($this->attrs['uid']);
689     unset($this->attrs['trustModel']);
691     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
692     /* include global link_info */
693      $this->attributes, "Save");
694     $ldap= $this->config->get_ldap_link();
695     $ldap->cd($this->dn);
696     $this->cleanup();
697     $ldap->modify ($this->attrs); 
699     new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
701     if (!$ldap->success()){
702       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
703     }
705     /* Delete group only if cn is uid and there are no other
706        members inside */
707     $ldap->cd ($this->config->current['BASE']);
708     $ldap->search ("(&(objectClass=posixGroup)(gidNumber=".$this->gidNumber."))", array("cn", "memberUid"));
709     if ($ldap->count() != 0){
710       $attrs= $ldap->fetch();
711       if ($attrs['cn'][0] == $this->uid &&
712           !isset($this->attrs['memberUid'])){
714         $ldap->rmDir($ldap->getDN());
715       }
716     }
718     /* Optionally execute a command after we're done */
719     $this->handle_post_events("remove",array("uid" => $this->uid));
720   }
723   function save_object()
724   {
725     if (isset($_POST['posixTab'])){
726       /* Save values to object */
727       plugin::save_object();
730       /* Save force GID checkbox */
731       if($this->acl_is_writeable("gidNumber") || $this->acl_is_writeable("uidNumber")){
732         if (isset ($_POST['force_ids'])){
733           $data= 1;
734         } else {
735           $data= 0;
736         }
737         if ($this->force_ids != $data){
738           $this->is_modified= TRUE;
739         }
740         $this->force_ids= $data;
741       }
743       /*Save primary group settings */
744       if($this->acl_is_writeable("primaryGroup") && isset($_POST['primaryGroup'])){
745         $data= $_POST['primaryGroup'];
746         if ($this->primaryGroup != $data){
747           $this->is_modified= TRUE;
748         }
749         $this->primaryGroup= $_POST['primaryGroup'];
750       }
752       /* Get seelcted shadow checkboxes */
753       foreach(array("shadowMin","shadowMax","shadowExpire","shadowInactive","shadowWarning") as $var) {
754         if($this->acl_is_writeable($var)){
755           $activate_var = "activate_".$var;
756           if(isset($_POST['activate_'.$var])){
757             $this->$activate_var  = true;
758             $this->$var      = $_POST[$var];
759           }else{
760             $this->$activate_var  = false;
761             if ($var != "shadowExpire") {
762               $this->$var      = 0;
763             }
764           }
765         }
766       }
768       /* Force change password ? */
769       if(isset($_POST['mustchangepassword'])){
770         $this->mustchangepassword = TRUE;
771       }else{
772         $this->mustchangepassword = FALSE;
773       }
775       /* Trust mode - special handling */
776       if($this->acl_is_writeable("trustModel")){
777         if (isset($_POST['trustmode'])){
778           $saved= $this->trustModel;
779           if ($_POST['trustmode'] == "1"){
780             $this->trustModel= "fullaccess";
781           } elseif ($_POST['trustmode'] == "2"){
782             $this->trustModel= "byhost";
783           } else {
784             $this->trustModel= "";
785           }
786           if ($this->trustModel != $saved){
787             $this->is_modified= TRUE;
788           }
789         }
790       }
791     }
793     /* Get regex from alphabet */
794     if(isset($_GET['search'])){
795       $this->GroupRegex = $_GET['search']."*";
796     }
798     /* Check checkboxes and regexes */
799     if(isset($_POST["PosixGroupDialogPosted"])){
801       if(isset($_POST['SubSearch']) && ($_POST['SubSearch'])){
802         $this->SubSearch = true;
803       }else{
804         $this->SubSearch = false;
805       }
806       if(isset($_POST['guser'])){
807         $this->GroupUserRegex = $_POST['guser'];
808       }
809       if(isset($_POST['regex'])){
810         $this->GroupRegex = $_POST['regex'];
811       }
812     }
813     $this->GroupRegex = preg_replace("/\*\**/","*",$this->GroupRegex);
814     $this->GroupUserRegex = preg_replace("/\*\**/","*",$this->GroupUserRegex);
815   }
818   /* Save data to LDAP, depending on is_account we save or delete */
819   function save()
820   {
822     /* Adapt shadow values */
823     if (!$this->activate_shadowExpire){
824       $this->shadowExpire= "0";
825     } else {
826       /* Transform date to days since the beginning */
827       list($day, $month, $year)= split('\.', $this->shadowExpire, 3);
828       $this->shadowExpire= (int)(mktime(0, 0, 0, $month, $day, $year)/ (60 * 60 * 24)) ;
829     }
830     if (!$this->activate_shadowMax){
831       $this->shadowMax= "0";
832     }
833     if ($this->mustchangepassword){
834       $this->shadowLastChange= (int)(date("U") / 86400) - $this->shadowMax - 1;
835     } else {
836       $this->shadowLastChange= (int)(date("U") / 86400);
837     }
838     if (!$this->activate_shadowWarning){
839       $this->shadowWarning= "0";
840     }
842     /* Check what to do with ID's 
843         Nothing forced, so we may have to generate our own IDs, if not done already.
844      */
845     if ($this->force_ids == 0){
847       /* Handle uidNumber. 
848        * - use existing number if possible
849        * - if not, try to create a new uniqe one.
850        * */
851       if ($this->savedUidNumber != ""){
852         $this->uidNumber= $this->savedUidNumber;
853       } else {
855         /* Calculate new id's. We need to place a lock before calling get_next_id
856            to get real unique values. 
857          */
858         $wait= 10;
859         while (get_lock("uidnumber") != ""){
860           sleep (1);
862           /* Oups - timed out */
863           if ($wait-- == 0){
864             msg_dialog::display(_("Warning"), _("Timeout while waiting for lock. Ignoring lock!"), WARNING_DIALOG);
865             break;
866           }
867         }
868         add_lock ("uidnumber", "gosa");
869         $this->uidNumber= get_next_id("uidNumber", $this->dn);
870       }
871     }
874     /* Handle gidNumber 
875      * - If we do not have a primary group selected (automatic), we will check if there 
876      *    is already a group  with the same name and use this as primary.
877      * - .. if we couldn't find a group with the same name, we will create a new one, 
878      *    using the users uid as cn and a generated uniqe gidNumber. 
879      * */
880     if ($this->primaryGroup == 0 || $this->force_ids){
882       /* Search for existing group */
883       $ldap = $this->config->get_ldap_link();
884       $ldap->cd($this->config->current['BASE']);
886       /* Are we forced to use a special gidNumber? */ 
887       if($this->force_ids){
888         $ldap->search("(&(objectClass=posixGroup)(gidNumber=".$this->gidNumber."))", array("cn","gidNumber"));
889       }else{
890         $ldap->search("(&(objectClass=posixGroup)(gidNumber=*)(cn=".$this->uid."))", array("cn","gidNumber"));
891       }
893       /* No primary group found, create a new one */
894       if ($ldap->count() == 0){
896         $groupcn = $this->uid;
897         $groupdn= preg_replace ('/^'.preg_quote($this->config->get_cfg_value("accountPrimaryAttribute").'=[^,]+,'.get_people_ou(), '/').'/i',
898             'cn='.$groupcn.','.get_groups_ou(), $this->dn);
900         /* Request a new and uniqe gidNumber, if required */
901         if(!$this->force_ids){
902           $this->gidNumber= get_next_id("gidNumber", $this->dn);
903         }else{
905           /* If forced gidNumber could not be found, then check if the given group name already exists 
906               we do not want to modify the gidNumber of an existing group.
907            */
908           $cnt= 0; 
909           while($ldap->dn_exists($groupdn)){
910             $cnt ++;
911             $groupcn = $this->uid."_".$cnt;
912             $groupdn= preg_replace ('/^'.preg_quote($this->config->get_cfg_value("accountPrimaryAttribute").'=[^,]+,'.get_people_ou(), '/').'/i',
913             'cn='.$groupcn.','.get_groups_ou(), $this->dn);
914           }
915         }
917         /* Create new primary group and enforce the new gidNumber */
918         $g= new group($this->config, $groupdn);
919         $g->cn= $groupcn;
920         $g->force_gid= 1;
921         $g->gidNumber= $this->gidNumber;
922         $g->description= _("Group of user")." ".$this->givenName." ".$this->sn;
923         $g->save ();
925         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
926             sprintf("Primary group '%s' created, using gidNumber '%s'.",$groupcn,$this->gidNumber),"");
927       }else{
928         $attrs = $ldap->fetch();
929         $this->gidNumber = $attrs['gidNumber'][0];
930         @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
931             "Found and used: <i>".$attrs['dn']."</i>",
932             sprintf("Primary group '%s' exists, gidNumber is '%s'.",$this->uid,$this->gidNumber));
933       }
934     }else{
936       /* Primary group was selected by user
937        */
938       $this->gidNumber = $this->primaryGroup;
939       @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,
940           sprintf("Primary group '%s' for user '%s' manually selected.",$this->gidNumber,$this->uid),"");
941     }
943     if ($this->activate_shadowMin != "1" ) {
944       $this->shadowMin = "";
945     }
947     if (($this->activate_shadowMax != "1") && ($this->mustchangepassword != "1")) {
948       $this->shadowMax = "";
949     }
951     if ($this->activate_shadowWarning != "1" ) {
952       $this->shadowWarning = "";
953     }
955     if ($this->activate_shadowInactive != "1" ) {
956       $this->shadowInactive = "";
957     }
959     if ($this->activate_shadowExpire != "1" ) {
960       $this->shadowExpire = "";
961     }
963     /* Fill gecos */
964     if (isset($this->parent) && $this->parent !== NULL){
965       $this->gecos= rewrite($this->parent->by_object['user']->cn);
966       if (!preg_match('/^[a-z0-9 -]+$/i', $this->gecos)){
967         $this->gecos= "";
968       }
969     }
971     foreach(array("shadowMin","shadowMax","shadowWarning","shadowInactive","shadowExpire") as $attr){
972       $this->$attr = (int) $this->$attr;
973     }
974     /* Call parents save to prepare $this->attrs */
975     plugin::save();
977     /* Trust accounts */
978     $objectclasses= array();
979     foreach ($this->attrs['objectClass'] as $key => $class){
980       if (preg_match('/trustAccount/i', $class)){
981         continue;
982       }
983       $objectclasses[]= $this->attrs['objectClass'][$key];
984     }
985     $this->attrs['objectClass']= $objectclasses;
986     if ($this->trustModel != ""){
987       $this->attrs['objectClass'][]= "trustAccount";
988       $this->attrs['trustModel']= $this->trustModel;
989       $this->attrs['accessTo']= array();
990       if ($this->trustModel == "byhost"){
991         foreach ($this->accessTo as $host){
992           $this->attrs['accessTo'][]= $host;
993         }
994       }
995     } else {
996       if ($this->was_trust_account){
997         $this->attrs['accessTo']= array();
998         $this->attrs['trustModel']= array();
999       }
1000     }
1002     if(empty($this->attrs['gosaDefaultPrinter'])){
1003       $thid->attrs['gosaDefaultPrinter']=array();
1004     }
1007     /* include global link_info */
1008     $this->cleanup();
1009  
1010     /* This is just a test, we have had duplicated ids 
1011         in the past when copy & paste was used. 
1012        Normaly this should not happen.
1013      */ 
1014     if(isset($this->attrs['uidNumber']) && !$this->force_ids){
1015       $used = $this->get_used_uid_numbers();
1016       if(isset($used[$this->attrs['uidNumber']]) && $used[$this->attrs['uidNumber']] != $this->dn){
1017         msg_dialog::display(_("Warning"),_("A duplicated UID number was written for this user. If this was not intended please verify all used uidNumbers!"), WARNING_DIALOG);
1018       }
1019     }
1021     $ldap= $this->config->get_ldap_link();
1022     $ldap->cd($this->dn);
1023     unset($this->attrs['uid']);
1024     $ldap->modify ($this->attrs); 
1026     /* Log last action */ 
1027     if($this->initially_was_account){
1028       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1029     }else{
1030       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1031     }
1033     if (!$ldap->success()){
1034       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
1035     }
1037     /* Remove lock needed for unique id generation */
1038     del_lock ("uidnumber");
1040     // Save ssh stuff if needed
1041     if ($this->ssh) {
1042       $this->ssh->setDN($this->dn);
1043       $this->ssh->save();
1044     }
1046     /* Take care about groupMembership values: add to groups */
1047     foreach ($this->groupMembership as $key => $value){
1048       if (!isset($this->savedGroupMembership[$key])){
1049         $g= new grouptabs($this->config,$this->config->data['TABS']['GROUPTABS'], $key,"groups");
1050         $g->set_acl_base($key);
1051         $g->by_object['group']->addUser($this->uid);
1052         $g->save();
1053       }
1054     }
1056     /* Remove groups not listed in groupMembership */
1057     foreach ($this->savedGroupMembership as $key => $value){
1058       if (!isset($this->groupMembership[$key])){
1059         $g= new grouptabs($this->config,$this->config->data['TABS']['GROUPTABS'], $key,"groups");
1060         $g->set_acl_base($key);
1061         $g->by_object['group']->removeUser ($this->uid);
1062         $g->save();
1063       }
1064     }
1066     /* Optionally execute a command after we're done */
1067     if ($this->initially_was_account == $this->is_account){
1068       if ($this->is_modified){
1069         $this->handle_post_events("modify",array("uid" => $this->uid));
1070       }
1071     } else {
1072       $this->handle_post_events("add" ,array("uid"=> $this->uid));
1073     }
1074   }
1077   /* Check formular input */
1078   function check()
1079   {
1080     /* Include global link_info */
1081     $ldap= $this->config->get_ldap_link();
1083     /* Append groups as memberGroup: to check hook 
1084      */
1085     $tmp_attributes  = $this->attributes;    
1086     $this->attributes[] = "memberGroup";
1087     $this->memberGroup = array();
1088     foreach($this->groupMembership as $dn => $name){
1089       $this->memberGroup[] = $name;
1090     }
1092     /* Call common method to give check the hook */
1093     $message= plugin::check();
1094     $this->attributes = $tmp_attributes;
1096     /* must: homeDirectory */
1097     if ($this->homeDirectory == ""){
1098       $message[]= msgPool::required(_("Home directory"));
1099     }
1100     if (!tests::is_path($this->homeDirectory)){
1101       $message[]= msgPool::invalid(_("Home directory"), "", "", "/home/yourname" );
1102     }
1104     /* Check ID's if they are forced by user */
1105     if ($this->force_ids == "1"){
1107       /* Valid uid/gid? */
1108       if (!tests::is_id($this->uidNumber)){
1109         $message[]= msgPool::invalid(_("UID"), $this->uidNumber, "/[0-9]/");
1110       } else {
1111         if ($this->uidNumber < $this->config->get_cfg_value("minId")){
1112           $message[]= msgPool::toosmall(_("UID"), $this->config->get_cfg_value("minId"));
1113         }
1114       }
1115       if (!tests::is_id($this->gidNumber)){
1116         $message[]= msgPool::invalid(_("GID"), $this->gidNumber, "/[0-9]/");
1117       } else {
1118         if ($this->gidNumber < $this->config->get_cfg_value("minId")){
1119           $message[]= msgPool::toosmall(_("GID"), $this->config->get_cfg_value("minId"));
1120         }
1121       }
1122     }
1124     /* Check dates */
1125     if ($this->activate_shadowExpire && ($this->shadowExpire == "" || !tests::is_date($this->shadowExpire))){
1126       $message[]= msgPool::invalid("shadowExpire", $this->shadowExpire);
1127     }
1129     /* Check shadow settings, well I like spaghetties... */
1130     if ($this->activate_shadowMin){
1131       if (!tests::is_id($this->shadowMin)){
1132         $message[]= msgPool::invalid(_("shadowMin"), $this->shadowMin, "/[0-9]/");
1133       }
1134     }
1135     if ($this->activate_shadowMax){
1136       if (!tests::is_id($this->shadowMax)){
1137         $message[]= msgPool::invalid(_("shadowMax"), $this->shadowMax, "/[0-9]/");
1138       }
1139     }
1140     if ($this->activate_shadowWarning){
1141       if (!tests::is_id($this->shadowWarning)){
1142         $message[]= msgPool::invalid(_("shadowWarning"), $this->shadowWarning, "/[0-9]/");
1143       }
1144       if (!$this->activate_shadowMax){
1145         $message[]= msgPool::depends("shadowWarning", "shadowMax");
1146       }
1147       if ($this->shadowWarning > $this->shadowMax){
1148         $message[]= msgPool::toobig("shadowWarning", "shadowMax");
1149       }
1150       if ($this->activate_shadowMin && $this->shadowWarning < $this->shadowMin){
1151         $message[]= msgPool::toosmall("shadowWarning", "shadowMin");
1152       }
1153     }
1154     if ($this->activate_shadowInactive){
1155       if (!tests::is_id($this->shadowInactive)){
1156         $message[]= msgPool::invalid(_("shadowInactive"), $this->shadowInactive, "/[0-9]/");
1157       }
1158       if (!$this->activate_shadowMax){
1159         $message[]= msgPool::depends("shadowInactive", "shadowMax");
1160       }
1161     }
1162     if ($this->activate_shadowMin && $this->activate_shadowMax){
1163       if ($this->shadowMin > $this->shadowMax){
1164         $message[]= msgPool::toobig("shadowMin", "shadowMax");
1165       }
1166     }
1168     return ($message);
1169   }
1172   function multiple_check()
1173   {
1174     $message = plugin::multiple_check();
1175     if ($this->homeDirectory == "" && in_array("homeDirectory",$this->multi_boxes)){
1176       $message[]= msgPool::required(_("Home directory"));
1177     }
1178     if (!tests::is_path($this->homeDirectory) && in_array("homeDirectory",$this->multi_boxes)){
1179       $message[]= msgPool::invalid(_("Home directory"), "", "", "/home/yourname" );
1180     }
1182     /* Check shadow settings, well I like spaghetties... */
1183     if ($this->activate_shadowMin && in_array("activate_shadowMin",$this->multi_boxes)){
1184       if (!tests::is_id($this->shadowMin)){
1185         $message[]= msgPool::invalid(_("shadowMin"), $this->shadowMin, "/[0-9]/");
1186       }
1187     }
1188     if ($this->activate_shadowMax && in_array("activate_shadowMax",$this->multi_boxes)){
1189       if (!tests::is_id($this->shadowMax)){
1190         $message[]= msgPool::invalid(_("shadowMax"), $this->shadowMax, "/[0-9]/");
1191       }
1192     }
1193     if ($this->activate_shadowWarning && in_array("activate_shadowWarning",$this->multi_boxes)){
1194       if (!tests::is_id($this->shadowWarning)){
1195         $message[]= msgPool::invalid(_("shadowWarning"), $this->shadowWarning, "/[0-9]/");
1196       }
1197       if (!$this->activate_shadowMax && in_array("activate_shadowMax",$this->multi_boxes)){
1198         $message[]= msgPool::depends("shadowWarning", "shadowMax");
1199       }
1200       if ($this->shadowWarning > $this->shadowMax && in_array("activate_shadowWarning",$this->multi_boxes)){
1201         $message[]= msgPool::toobig("shadowWarning", "shadowMax");
1202       }
1203       if ($this->activate_shadowMin && $this->shadowWarning < $this->shadowMin && in_array("activate_shadowMin",$this->multi_boxes)){
1204         $message[]= msgPool::tosmall("shadowWarning", "shadowMin");
1205       }
1206     }
1207     if ($this->activate_shadowInactive && in_array("activate_shadowInactive",$this->multi_boxes)){
1208       if (!tests::is_id($this->shadowInactive)){
1209         $message[]= msgPool::invalid(_("shadowInactive"), $this->shadowInactive, "/[0-9]/");
1210       }
1211       if (!$this->activate_shadowMax && in_array("activate_shadowMax",$this->multi_boxes)){
1212         $message[]= msgPool::depends("shadowInactive", "shadowMax");
1213       }
1214     }
1215     if ($this->activate_shadowMin && $this->activate_shadowMax && in_array("activate_shadowMin",$this->multi_boxes)){
1216       if ($this->shadowMin > $this->shadowMax){
1217         $message[]= msgPool::toobig("shadowMin", "shadowMax");
1218       }
1219     }
1221     return($message);
1222   }
1225   function addGroup ($groups)
1226   {
1227     /* include global link_info */
1228     $ldap= $this->config->get_ldap_link();
1230     /* Walk through groups and add the descriptive entry if not exists */
1231     foreach ($groups as $value){
1233       if (!array_key_exists($value, $this->groupMembership)){
1234         $ldap->cat($value, array('cn', 'description', 'dn'));
1235         $attrs= $ldap->fetch();
1236         error_reporting (0);
1237         if (!isset($attrs['description'][0])){
1238           $entry= $attrs["cn"][0];
1239         } else {
1240           $dsc= preg_replace ('/^Group of user/', _("Group of user"), $attrs["description"][0]);
1241           $entry= $attrs["cn"][0]." [$dsc]";
1242         }
1243         error_reporting (E_ALL | E_STRICT);
1245         if(obj_is_writable($attrs['dn'],"groups/group","memberUid")){
1246           $this->groupMembership[$attrs['dn']]= $entry;
1247           if($this->multiple_support_active && isset($this->groupMembership_some[$attrs['dn']])){
1248             unset($this->groupMembership_some[$attrs['dn']]);
1249           }
1250         }
1251       }
1252     }
1254     /* Sort groups */
1255     asort ($this->groupMembership);
1256     reset ($this->groupMembership);
1257   }
1260   /* Del posix user from some groups */
1261   function delGroup ($groups)
1262   {
1263     $dest= array();
1264     foreach($groups as $dn_to_del){
1265       if(isset($this->groupMembership[$dn_to_del]) && obj_is_writable($dn_to_del,"groups/group","memberUid")){
1266         unset($this->groupMembership[$dn_to_del]);
1267       }
1268       if($this->multiple_support_active){
1269         if(isset($this->groupMembership_some[$dn_to_del]) && obj_is_writable($dn_to_del,"groups/group","memberUid")){
1270           unset($this->groupMembership_some[$dn_to_del]);
1271         }
1272       }
1273     }
1274   }
1277   /* Adapt from template, using 'dn' */
1278   function adapt_from_template($dn, $skip= array())
1279   {
1280     /* Include global link_info */
1281     $ldap= $this->config->get_ldap_link();
1283     plugin::adapt_from_template($dn, $skip);
1284     $template= $this->attrs['uid'][0];
1286     /* Adapt group membership */
1287     $ldap->cd($this->config->current['BASE']);
1288     $ldap->search("(&(objectClass=posixGroup)(memberUid=".$this->attrs["uid"][0]."))", array("description", "cn"));
1290     while ($this->attrs= $ldap->fetch()){
1291       if (!isset($this->attrs["description"][0])){
1292         $entry= $this->attrs["cn"][0];
1293       } else {
1294         $entry= $this->attrs["cn"][0]." [".$this->attrs["description"][0]."]";
1295       }
1296       $this->groupMembership[$ldap->getDN()]= $entry;
1297     }
1299     /* Fix primary group settings */
1300     $ldap->cd($this->config->current['BASE']);
1301     $ldap->search("(&(objectClass=posixGroup)(cn=$template)(gidNumber=".$this->gidNumber."))", array("cn"));
1302     if ($ldap->count() != 1){
1303       $this->primaryGroup= $this->gidNumber;
1304     }
1306     $ldap->cd($this->config->current['BASE']);
1307     $ldap->search("(&(objectClass=gosaUserTemplate)(uid=".$template.")(accessTo=*))", array("cn","accessTo"));
1308     while($attr = $ldap->fetch()){
1309       $tmp = $attr['accessTo'];
1310       unset ($tmp['count']);
1311       $this->accessTo = $tmp;   
1312     }
1314     /* Adjust shadow checkboxes */
1315     foreach (array("shadowMin", "shadowMax", "shadowWarning", "shadowInactive") as $val){
1316       if ($this->$val != 0){
1317         $oval= "activate_".$val;
1318         $this->$oval= "1";
1319       }
1320     }
1322     /* FIXME: NEED review of this section */
1323     /* Need to check shadowExpire separately */
1325     /* 
1326      * If shadowExpire is not enabled in the template, it's a UNIX timestamp - so don't convert it to seconds.
1327      * The check is a hack - if difference between timestamp generated above and here is max 1 day.
1328      */
1329     if(abs($this->shadowExpire - time())>86400) {
1330       $this->shadowExpire= $this->convertToSeconds($this->shadowExpire);
1331     }
1332     
1333     /* Only enable checkbox, if shadowExpire is in the future */
1334     if($this->shadowExpire > time()) {
1335       $this->activate_shadowExpire= "1";
1336     }
1337   }
1339   function convertToSeconds($val)
1340   {
1341     if ($val != 0){
1342       $val*= 60 * 60 * 24;
1343     } else {
1344       $date= getdate();
1345       $val= floor($date[0] / (60*60*24)) * 60 * 60 * 24;
1346     }
1347     return($val);
1348   }
1351   function get_used_uid_numbers()
1352   {
1353     $ids= array();
1354     $ldap= $this->config->get_ldap_link();
1356     $ldap->cd ($this->config->current['BASE']);
1357     $ldap->search ("(&(objectClass=posixAccount)(uidNumber=*))", array("uidNumber"));
1359     /* Get list of ids */
1360     while ($attrs= $ldap->fetch()){
1361       $ids[$attrs['uidNumber'][0]] = $attrs['dn'];
1362     }
1363     return($ids);
1364   }
1366   
1367   function reload()
1368   {
1369     /* Set base for all searches */
1370     $base      = session::get('CurrentMainBase');
1371     $base     = $base;
1372     $ldap     = $this->config->get_ldap_link();    
1373     $attrs    =  array("cn", "description", "gidNumber");
1374     $Flags    = GL_SIZELIMIT;
1376     /* Get groups */
1377     if ($this->GroupUserRegex == '*'){
1378       $filter = "(&(objectClass=posixGroup)(cn=".$this->GroupRegex."))";
1379     } else {
1380       $filter= "(&(objectClass=posixGroup)(cn=".$this->GroupRegex.")(memberUid=".$this->GroupUserRegex."))";
1381     }
1382     if($this->SubSearch){
1383       $Flags |= GL_SUBSEARCH;
1384     }else{
1385       $base = get_groups_ou().$base;
1386     }
1388     $res= get_list($filter, "groups", $base,$attrs, $Flags);
1389   
1390     /* check sizelimit */
1391     if (preg_match("/size limit/i", $ldap->get_error())){
1392       session::set('limit_exceeded',TRUE);
1393     }
1395     /* Create a list of users */
1396     $this->grouplist = array();
1397     foreach ($res as $value){
1398       $this->grouplist[$value['gidNumber'][0]]= $value;
1399     }
1401     $tmp=array();
1402     foreach($this->grouplist as $tkey => $val ){
1403       $tmp[strtolower($val['cn'][0]).$val['cn'][0]]=$val;
1404     }
1406     /* Sort index */
1407     ksort($tmp);
1409     /* Recreate index array[dn]=cn[description]*/
1410     $this->grouplist=array();
1411     foreach($tmp as $val){
1412       if(isset($val['description'])){
1413         $this->grouplist[$val['dn']]=$val['cn'][0]."&nbsp;[".$val['description'][0]."]";
1414       }else{
1415         $this->grouplist[$val['dn']]=$val['cn'][0];
1416       }
1417     }
1419     reset ($this->grouplist);
1420   }
1423   /* Get posts from copy & paste dialog */ 
1424   function saveCopyDialog()
1425   {
1426     if(isset($_POST['homeDirectory'])){
1427       $this->homeDirectory = $_POST['homeDirectory'];
1428       if (isset ($_POST['force_ids'])){
1429         $data= 1;
1430         $this->gidNumber = $_POST['gidNumber'];
1431         $this->uidNumber = $_POST['uidNumber'];
1432       } else {
1433         $data= 0;
1434       }
1435       if ($this->force_ids != $data){
1436         $this->is_modified= TRUE;
1437       }
1438       $this->force_ids= $data;
1439       $data= $_POST['primaryGroup'];
1440       if ($this->primaryGroup != $data){
1441         $this->is_modified= TRUE;
1442       }
1443       $this->primaryGroup= $_POST['primaryGroup'];
1444     }
1445   }
1446  
1448   /* Create the posix dialog part for copy & paste */
1449   function getCopyDialog()
1450   {
1451     /* Skip dialog creation if this is not a valid account*/
1452     if(!$this->is_account) return("");
1453     if ($this->force_ids == 1){
1454       $force_ids = "checked";
1455       if (session::get('js')){
1456         $forceMode = "";
1457       }
1458     } else {
1459       if (session::get('js')){
1460         if($this->acl != "#none#")
1461           $forceMode ="disabled";
1462       }
1463       $force_ids = "";
1464     }
1466     $sta = "";
1468     /* Open group add dialog */
1469     if(isset($_POST['edit_groupmembership'])){
1470       $this->group_dialog = TRUE;
1471       $sta = "SubDialog";
1472     }
1474     /* If the group-add dialog is closed, call execute 
1475        to ensure that the membership is updatd */
1476     if(isset($_POST['add_groups_finish']) || isset($_POST['add_groups_cancel'])){
1477       $this->execute();
1478       $this->group_dialog =FALSE;
1479     }
1481     if($this->group_dialog){
1482       $str = $this->execute(true);
1483       $ret = array();
1484       $ret['string'] = $str;
1485       $ret['status'] = $sta;
1486       return($ret);
1487     }
1489     /* If a group member should be deleted, simply call execute */
1490     if(isset($_POST['delete_groupmembership'])){
1491       $this->execute();
1492     }
1494     /* Assigned informations to smarty */
1495     $smarty = get_smarty();
1496     $smarty->assign("homeDirectory",$this->homeDirectory);
1497     $smarty->assign("secondaryGroups",$this->secondaryGroups);
1498     $smarty->assign("primaryGroup",$this->primaryGroup);
1499  
1500     $smarty->assign("uidNumber",$this->uidNumber);
1501     $smarty->assign("gidNumber",$this->gidNumber);
1502     $smarty->assign("forceMode",$forceMode);
1503     $smarty->assign("force_ids",$force_ids);
1504     if (!count($this->groupMembership)){
1505       $smarty->assign("groupMembership", array("&nbsp;"));
1506     } else {
1507       $smarty->assign("groupMembership", $this->groupMembership);
1508     }
1510     /* Display wars message if there are more than 16 group members */
1511     if (count($this->groupMembership) > 16){
1512       $smarty->assign("groups", "too_many_for_nfs");
1513     } else {
1514       $smarty->assign("groups", "");
1515     }
1516     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1518     $ret = array();
1519     $ret['string'] = $str;
1520     $ret['status'] = $sta;
1521     return($ret);
1522   }
1525   function PrepareForCopyPaste($source)
1526   {
1527     plugin::PrepareForCopyPaste($source);
1529     /* Avoid using the same gid/uid number as source user 
1530         empty numbers to enforce new ones. */
1531     $this->savedUidNumber = "";
1532     $this->savedGidNumber = "";
1534     /* Get group membership */
1535     $ldap = $this->config->get_ldap_link();
1536     $ldap->cd($this->config->current['BASE']);
1537     $ldap->search("(&(objectClass=posixGroup)(memberUid=".$source['uid'][0]."))", array("cn", "description"));
1539     while ($attrs= $ldap->fetch()){
1540       if (!isset($attrs["description"][0])){
1541         $entry= $attrs["cn"][0];
1542       } else {
1543         $entry= $attrs["cn"][0]." [".$attrs["description"][0]."]";
1544       }
1545       $this->groupMembership[$ldap->getDN()]= $entry;
1546     }
1547     asort($this->groupMembership);
1548     reset($this->groupMembership);
1550     /* Fill group */
1551     if(isset($source['gidNumber'][0])){
1552       $this->primaryGroup= $source['gidNumber'][0];
1553     }
1555   }
1558   function multiple_execute()
1559   {
1560     return($this->execute());
1561   }
1564   static function plInfo()
1565   {
1566     return (array(
1567           "plDescription"     => _("POSIX account"),
1568           "plSelfModify"      => TRUE,
1569           "plDepends"         => array("user"),
1570           "plPriority"        => 2,
1571           "plSection"         => array("personal" => _("My account")),
1572           "plCategory"        => array("users"),
1573           "plOptions"         => array(),
1575           "plProvidedAcls"  => array(
1577             "homeDirectory"       =>  _("Home directory"), 
1578             "loginShell"          =>  _("Shell"),
1579             "uidNumber"           =>  _("User ID"),
1580             "gidNumber"           =>  _("Group ID"),
1582             "mustchangepassword"=>  _("Force password change on login"),
1583             "shadowMin"           =>  _("Shadow min"),
1584             "shadowMax"           =>  _("Shadow max"),
1585             "shadowWarning"       =>  _("Shadow warning"),
1586             "shadowInactive"      =>  _("Shadow inactive"),
1587             "shadowExpire"        =>  _("Shadow expire"),
1588             "sshPublickey"        =>  _("Public SSH key"),
1589             "trustModel"          =>  _("System trust model")))
1590             );
1591   }
1594   /* Return selected values for multiple edit */
1595   function get_multi_edit_values()
1596   {
1597     $ret = plugin::get_multi_edit_values();
1598     $ret['groupMembership']     = $this->groupMembership;
1599     $ret['groupMembership_some']= $this->groupMembership_some;
1601     if(in_array("primaryGroup",$this->multi_boxes)){
1602       $ret['primaryGroup'] = $this->primaryGroup;
1603     }
1604     if(in_array("trustmode",$this->multi_boxes)){
1605       $ret['trustModel'] = $this->trustModel;
1606       $ret['accessTo'] = $this->accessTo;
1607     }
1608     foreach(array("shadowWarning","shadowInactive","shadowMin","shadowMax", "shadowExpire") as $entry){
1609       $active = "activate_".$entry;
1610       if(in_array($active,$this->multi_boxes)){
1611         $ret[$entry] = $this->$entry;
1612         $ret[$active] = $this->$active;
1613       }
1614     }
1615     if(in_array("mustchangepassword",$this->multi_boxes)){
1616       $ret['mustchangepassword'] = $this->mustchangepassword;
1617     }
1618     return($ret);
1619   }
1622   /* Save posts for multiple edit 
1623    */
1624   function multiple_save_object()
1625   {
1626     if(isset($_POST['posix_mulitple_edit'])){
1627  
1628       /* Backup expire value */ 
1629       $expire_tmp = $this->shadowExpire;
1630   
1631       /* Update all values */
1632       plugin::multiple_save_object();
1634       /* Get selected checkboxes */
1635       foreach(array("primaryGroup","trustmode","mustchangepassword","activate_shadowWarning","activate_shadowInactive","activate_shadowMin", "activate_shadowMax","activate_shadowExpire") as $val){
1636         if(isset($_POST["use_".$val])){
1637           $this->multi_boxes[] = $val;
1638         }
1639       }
1641       /* Update special values, checkboxes for posixShadow */
1642       foreach(array("shadowMin","shadowMax","shadowExpire","shadowInactive","shadowWarning") as $var) {
1643         if($this->acl_is_writeable($var)){
1644           $activate_var = "activate_".$var;
1645           if(in_array($activate_var, $this->multi_boxes)){
1646             if(isset($_POST['activate_'.$var])){
1647               $this->$activate_var  = true;
1648               $this->$var      = $_POST[$var];
1649             }else{
1650               $this->$activate_var  = false;
1651               $this->$var      = 0;
1652             }
1653           }
1654         }
1655       }
1657       /* Restore shadow value, if the shadow attribute isn't used */
1658       if(!in_array("activate_shadowExpire",$this->multi_boxes)){
1659         $this->shadowExpire = $expire_tmp;
1660       }
1662       /* Force change password ? */
1663       if(isset($_POST['mustchangepassword'])){
1664         $this->mustchangepassword = TRUE;
1665       }else{
1666         $this->mustchangepassword = FALSE;
1667       }
1669       /* Trust mode - special handling */
1670       if($this->acl_is_writeable("trustModel")){
1671         if (isset($_POST['trustmode'])){
1672           $saved= $this->trustModel;
1673           if ($_POST['trustmode'] == "1"){
1674             $this->trustModel= "fullaccess";
1675           } elseif ($_POST['trustmode'] == "2"){
1676             $this->trustModel= "byhost";
1677           } else {
1678             $this->trustModel= "";
1679           }
1680           if ($this->trustModel != $saved){
1681             $this->is_modified= TRUE;
1682           }
1683         }
1684       }
1686       /* Save primary group settings */
1687       if($this->acl_is_writeable("primaryGroup") && isset($_POST['primaryGroup'])){
1688         $data= $_POST['primaryGroup'];
1689         if ($this->primaryGroup != $data){
1690           $this->is_modified= TRUE;
1691         }
1692         $this->primaryGroup= $_POST['primaryGroup'];
1693       }
1694     }
1695   }
1697   
1698   /* Initialize plugin with given atribute arrays 
1699    */
1700   function init_multiple_support($attrs,$all)
1701   {
1702     plugin::init_multiple_support($attrs,$all);
1704     /* Some dummy values */
1705     $groups_some = array();
1706     $groups_all  = array();
1707     $groups_uid  = array();
1708     $uids        = array();
1709     $first       = TRUE;
1711     /* Get all groups used by currently edited users */
1712     $uid_filter="";  
1713     for($i =0; $i < $this->multi_attrs_all['uid']['count'] ; $i ++){
1714       $uid = $this->multi_attrs_all['uid'][$i];
1715       $uids[] = $uid;
1716       $uid_filter.= "(memberUid=".$uid.")"; 
1717     }
1718     $uid_filter = "(&(objectClass=posixGroup)(|".$uid_filter."))";
1719     $ldap = $this->config->get_ldap_link();
1720     $ldap->cd($this->config->current['BASE']);
1721     $ldap->search($uid_filter,array("dn","cn","memberUid"));
1722     while($group = $ldap->fetch()){
1723       $groups_some[$group['dn']] = $group['cn'][0];
1724       for($i = 0 ; $i < $group['memberUid']['count'] ; $i++){
1725         $groups_uid[$group['dn']][] = $group['memberUid'][$i];
1726       }
1727     }
1729     /* Create an array, containing all used groups */
1730     $groups_all = $groups_some;
1731     foreach($groups_all as $id => $group){
1732       foreach($uids as $uid){
1733         if(!in_array($uid,$groups_uid[$id])){
1734           unset($groups_all[$id]);
1735           break;
1736         }
1737       }
1738     }
1740     /* Assign group array */
1741     $this->groupMembership = $groups_all;
1743     /* Create an array of all grouops used by all users */
1744     foreach( $groups_all as $dn => $cn){
1745       if(isset($groups_some[$dn])){
1746         unset($groups_some[$dn]);
1747       }
1748     }
1749     $this->groupMembership_some = $groups_some;
1750     $this->primaryGroup = $this->gidNumber;
1752     /* Is this account a trustAccount? */
1753     if (isset($this->multi_attrs['trustModel'])){
1754       $this->trustModel= $this->multi_attrs['trustModel'][0];
1755       $this->was_trust_account= TRUE;
1756       $this->multi_boxes[] = "trustmode";
1757     } else {
1758       $this->was_trust_account= FALSE;
1759       $this->trustModel= "";
1760     }
1762     /* Create access informations */
1763     $this->accessTo = array();
1764     if (isset($this->multi_attrs['accessTo'])){
1765       for ($i= 0; $i<$this->multi_attrs['accessTo']['count']; $i++){
1766         $tmp= $this->multi_attrs['accessTo'][$i];
1767         $this->accessTo[$tmp]= $tmp;
1768       }
1769     }
1771     /* Adjust shadow checkboxes */
1772     foreach (array("shadowMin", "shadowMax", "shadowWarning", "shadowInactive",
1773           "shadowExpire") as $val){
1774       if ($this->$val != 0){
1775         $oval= "activate_".$val;
1776         $this->$oval= "1";
1777       }
1778     }
1780     /* Convert to seconds */
1781     if(isset($this->multi_attrs['shadowExpire'])){
1782       $this->shadowExpire = $this->convertToSeconds($this->multi_attrs['shadowExpire'][0]);
1783     }else{
1784       $this->activate_shadowExpire = FALSE;
1785     }
1786   }
1789   function set_multi_edit_values($attrs)
1790   {
1791     $groups = array();
1793     /* Update groupMembership, keep optinal group */
1794     foreach($attrs['groupMembership_some'] as $dn => $cn){
1795       if(isset($this->groupMembership[$dn])){
1796         $groups[$dn] = $cn;
1797       }
1798     }
1799     /* Update groupMembership, add forced groups */
1800     foreach($attrs['groupMembership'] as $dn => $cn){
1801       $groups[$dn] = $cn;
1802     }
1803     plugin::set_multi_edit_values($attrs);
1804     $this->groupMembership = $groups;
1805   }
1808 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1809 ?>