Code

Added a first set of reference changes - nearly untested
[gosa.git] / plugins / personal / posix / class_posixAccount.inc
1 <?php
2 /*!
3   \brief   posixAccount plugin
4   \author  Cajus Pollmeier <pollmeier@gonicus.de>
5   \version 2.00
6   \date    24.07.2003
8   This class provides the functionality to read and write all attributes
9   relevant for posixAccounts and shadowAccounts from/to the LDAP. It
10   does syntax checking and displays the formulars required.
11  */
13 class posixAccount extends plugin
14 {
15   /* Definitions */
16   var $plHeadline= "UNIX";
17   var $plDescription= "This does something";
19   /* CLI vars */
20   var $cli_summary= "Manage users posix account";
21   var $cli_description= "Some longer text\nfor help";
22   var $cli_parameters= array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
24   /* Plugin specific values */
25   var $homeDirectory= "";
26   var $loginShell= "/bin/bash";
27   var $uidNumber= "";
28   var $gidNumber= "";
29   var $gecos= "";
30   var $shadowMin= "0";
31   var $shadowMax= "0";
32   var $shadowWarning= "0";
33   var $shadowLastChange= "0";
34   var $shadowInactive= "0";
35   var $shadowExpire= "0";
36   var $gosaDefaultPrinter= "";
37   var $accessTo= array();
38   var $trustModel= "";
40   var $glist=array();
41   var $status= "";
42   var $loginShellList= array();
43   var $groupMembership= array();
44   var $savedGroupMembership= array();
45   var $savedUidNumber= "";
46   var $savedGidNumber= "";
47   var $use_shadowMin= "0";
48   var $use_shadowMax= "0";
49   var $use_shadowWarning= "0";
50   var $use_shadowInactive= "0";
51   var $use_shadowExpire= "0";
52   var $mustchangepassword= "0";
53   var $force_ids= 0;
54   var $group_dialog= FALSE;
55   var $show_ws_dialog= FALSE;
56   var $secondaryGroups= array();
57   var $primaryGroup= 0;
58   var $was_trust_account= FALSE;
59   var $memberGroup = array();
60   var $grouplist  = array();
61   var $ui         = array();
63   var $GroupRegex       = "*";
64   var $GroupUserRegex   = "*";
65   var $SubSearch        = false;
67   var $view_logged = FALSE;
69   /* attribute list for save action */
70   var $CopyPasteVars  = 
71       array("grouplist","groupMembership","use_shadowMin",
72       "use_shadowMax","use_shadowWarning","use_shadowInactive","use_shadowExpire",
73       "must_change_password","printerList","grouplist","savedGidNumber","savedUidNumber");
75   var $attributes     = array("homeDirectory", "loginShell", "uidNumber", "gidNumber", "gecos",
76       "shadowMin", "shadowMax", "shadowWarning", "shadowInactive", "shadowLastChange",
77       "shadowExpire", "gosaDefaultPrinter", "uid","accessTo","trustModel");
79   var $objectclasses= array("posixAccount", "shadowAccount");
81   var $uid= "";
83   /* constructor, if 'dn' is set, the node loads the given
84      'dn' from LDAP */
85   function posixAccount (&$config, $dn= NULL)
86   {
87     /* Configuration is fine, allways */
88     $this->config= $config;
90     /* Load bases attributes */
91     plugin::plugin($config, $dn);
93     /* Setting uid to default */
94     if(isset($this->attrs['uid'][0])){
95       $this->uid = $this->attrs['uid'][0];
96     }
98     $ldap= $this->config->get_ldap_link();
100     if ($dn != NULL){
102       /* Correct is_account. shadowAccount is not required. */
103       if (isset($this->attrs['objectClass']) &&
104           in_array ('posixAccount', $this->attrs['objectClass'])){
106         $this->is_account= TRUE;
107       }
109       /* Is this account a trustAccount? */
110       if ($this->is_account && isset($this->attrs['trustModel'])){
111         $this->trustModel= $this->attrs['trustModel'][0];
112         $this->was_trust_account= TRUE;
113       } else {
114         $this->was_trust_account= FALSE;
115         $this->trustModel= "";
116       }
118       $this->accessTo = array(); 
119       if ($this->is_account && isset($this->attrs['accessTo'])){
120         for ($i= 0; $i<$this->attrs['accessTo']['count']; $i++){
121           $tmp= $this->attrs['accessTo'][$i];
122           $this->accessTo[$tmp]= $tmp;
123         }
124       }
125       $this->initially_was_account= $this->is_account;
127       /* Fill group */
128       $this->primaryGroup= $this->gidNumber;
130       /* Generate status text */
131       $current= date("U");
133       $current= floor($current / 60 /60 / 24);
135       if (($current >= $this->shadowExpire) && $this->shadowExpire){
136         $this->status= _("expired");
137         if (($current - $this->shadowExpire) < $this->shadowInactive){
138           $this->status.= ", "._("grace time active");
139         }
140       } elseif (($this->shadowLastChange + $this->shadowMin) >= $current){
141         $this->status= _("active, password not changable");
142       } elseif (($this->shadowLastChange + $this->shadowMax) >= $current){
143         $this->status= _("active, password expired");
144       } else {
145         $this->status= _("active");
146       }
148       /* Get group membership */
149       $ldap->cd($this->config->current['BASE']);
150       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("cn", "description"));
152       while ($this->attrs= $ldap->fetch()){
153         if (!isset($this->attrs["description"][0])){
154           $entry= $this->attrs["cn"][0];
155         } else {
156           $dsc= preg_replace ('/^Group of user/', _("Group of user"), $this->attrs["description"][0]);
157           $entry= $this->attrs["cn"][0]." [$dsc]";
158         }
159         $this->groupMembership[$ldap->getDN()]= $entry;
160       }
161       asort($this->groupMembership);
162       reset($this->groupMembership);
163       $this->savedGroupMembership= $this->groupMembership;
164       $this->savedUidNumber= $this->uidNumber;
165       $this->savedGidNumber= $this->gidNumber;
166     }
168     /* Adjust shadow checkboxes */
169     foreach (array("shadowMin", "shadowMax", "shadowWarning", "shadowInactive",
170           "shadowExpire") as $val){
172       if ($this->$val != 0){
173         $oval= "use_".$val;
174         $this->$oval= "1";
175       }
176     }
178     /* Convert to seconds */
179     $this->shadowExpire= $this->convertToSeconds($this->shadowExpire);
181     /* Generate shell list from CONFIG_DIR./shells */
182     if (file_exists(CONFIG_DIR.'/shells')){
183       $shells = file (CONFIG_DIR.'/shells');
184       foreach ($shells as $line){
185         if (!preg_match ("/^#/", $line)){
186           $this->loginShellList[]= trim($line);
187         }
188       }
189     } else {
190       if ($this->loginShell == ""){
191         $this->loginShellList[]= _("unconfigured");
192       }
193     }
195     /* Insert possibly missing loginShell */
196     if ($this->loginShell != "" && !in_array($this->loginShell, $this->loginShellList)){
197       $this->loginShellList[]= $this->loginShell;
198     }
200     /* Generate group list */
201     $this->ui = get_userinfo(); 
202     $this->secondaryGroups[]= "- "._("automatic")." -";
203     $ldap->cd($this->config->current['BASE']);
204     $ldap->search("(objectClass=posixGroup)", array("cn", "gidNumber"));
205     while($attrs = $ldap->fetch()){
206       $this->secondaryGroups[$attrs['gidNumber'][0]]= $attrs['cn'][0];
207     }
208     asort ($this->secondaryGroups);
210     /* Get global filter config */
211     if (!is_global("sysfilter")){
212       $ui= get_userinfo();
213       $base= get_base_from_people($ui->dn);
214       $sysfilter= array( "depselect"       => $base,
215           "regex"           => "*");
216       register_global("sysfilter", $sysfilter);
217     }
218     $this->ui = get_userinfo();
219   }
222   /* execute generates the html output for this node */
223   function execute($isCopyPaste = false)
224   {
225     /* Call parent execute */
226     plugin::execute();
227     $display= "";
229     /* Log view */
230     if($this->is_account && !$this->view_logged){
231       $this->view_logged = TRUE;
232       new log("view","users/".get_class($this),$this->dn);
233     }
235     /* Department has changed? */
236     if(isset($_POST['depselect'])){
237       $_SESSION['CurrentMainBase']= validate($_POST['depselect']);
238     }
240     if(!$isCopyPaste){
242       /* Do we need to flip is_account state? */
243       if(isset($_POST['modify_state'])){
244         if($this->is_account && $this->acl_is_removeable()){
245           $this->is_account= FALSE;
246         }elseif(!$this->is_account && $this->acl_is_createable()){
247           $this->is_account= TRUE;
248         }
249       }
251       /* Do we represent a valid posixAccount? */
252       if (!$this->is_account && $this->parent == NULL ){
253         $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
254           _("This account has no unix extensions.")."</b>";
255         $display.= back_to_main();
256         return ($display);
257       }
260       /* Show tab dialog headers */
261       if ($this->parent != NULL){
262         if ($this->is_account){
263           if (isset($this->parent->by_object['sambaAccount'])){
264             $obj= $this->parent->by_object['sambaAccount'];
265           }
266           if (isset($obj) && $obj->is_account == TRUE &&
267               ((isset($this->parent->by_object['sambaAccount']))&&($this->parent->by_object['sambaAccount']->is_account))
268               ||(isset($this->parent->by_object['environment'] ))&&($this->parent->by_object['environment'] ->is_account)){
270             /* Samba3 dependency on posix accounts are enabled
271                in the moment, because I need to rely on unique
272                uidNumbers. There'll be a better solution later
273                on. */
274             $display= $this->show_disable_header(_("Remove posix account"),
275                 _("This account has unix features enabled. To disable them, you'll need to remove the samba / environment account first."), TRUE);
276           } else {
277             $display= $this->show_disable_header(_("Remove posix account"),
278                 _("This account has posix features enabled. You can disable them by clicking below."));
279           }
280         } else {
281           $display= $this->show_enable_header(_("Create posix account"),
282               _("This account has posix features disabled. You can enable them by clicking below."));
283           return($display);
284         }
285       }
286     }
287     /* Trigger group edit? */
288     if (isset($_POST['edit_groupmembership'])){
289       $this->group_dialog= TRUE;
290       $this->dialog= TRUE;
291     }
293     /* Cancel group edit? */
294     if (isset($_POST['add_groups_cancel']) ||
295         isset($_POST['add_groups_finish'])){
296       $this->group_dialog= FALSE;
297       $this->dialog= FALSE;
298     }
300     /* Add selected groups */
301     if (isset($_POST['add_groups_finish']) && isset($_POST['groups']) &&
302         count($_POST['groups'])){
304       $this->addGroup ($_POST['groups']);
305     }
307     /* Delete selected groups */
308     if (isset($_POST['delete_groupmembership']) && 
309         isset($_POST['group_list']) && count($_POST['group_list'])){
311       $this->delGroup ($_POST['group_list']);
312     }
314     /* Add user workstation? */
315     if (isset($_POST["add_ws"])){
316       $this->show_ws_dialog= TRUE;
317       $this->dialog= TRUE;
318     }
320     /* Add user workstation? */
321     if (isset($_POST["add_ws_finish"]) && isset($_POST['wslist'])){
322       foreach($_POST['wslist'] as $ws){
323         $this->accessTo[$ws]= $ws;
324       }
325       ksort($this->accessTo);
326       $this->is_modified= TRUE;
327     }
329     /* Remove user workstations? */
330     if (isset($_POST["delete_ws"]) && isset($_POST['workstation_list'])){
331       foreach($_POST['workstation_list'] as $name){
332         unset ($this->accessTo[$name]);
333       }
334       $this->is_modified= TRUE;
335     }
337     /* Add user workstation finished? */
338     if (isset($_POST["add_ws_finish"]) || isset($_POST["add_ws_cancel"])){
339       $this->show_ws_dialog= FALSE;
340       $this->dialog= FALSE;
341     }
343     /* Templates now! */
344     $smarty= get_smarty();
346     /* Show ws dialog */
347     if ($this->show_ws_dialog){
348       /* Save data */
349       $sysfilter= get_global("sysfilter");
350       foreach( array("depselect", "regex") as $type){
351         if (isset($_POST[$type])){
352           $sysfilter[$type]= $_POST[$type];
353         }
354       }
355       if (isset($_GET['search'])){
356         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
357         if ($s == "**"){
358           $s= "*";
359         }
360         $sysfilter['regex']= $s;
361       }
362       register_global("sysfilter", $sysfilter);
364       /* Get workstation list */
365       $exclude= "";
366       foreach($this->accessTo as $ws){
367         $exclude.= "(cn=$ws)";
368       }
369       if ($exclude != ""){
370         $exclude= "(!(|$exclude))";
371       }
372       $regex= $sysfilter['regex'];
373       $filter= "(&(|(objectClass=goServer)(objectClass=gotoWorkstation)(objectClass=gotoTerminal))$exclude(cn=*)(cn=$regex))";
374       $res= get_list($filter, "groups", $sysfilter['depselect'], array("cn"), GL_SUBSEARCH | GL_SIZELIMIT);
375       $wslist= array();
376       foreach ($res as $attrs){
377         $wslist[]= preg_replace('/\$/', '', $attrs['cn'][0]);
378       }
379       asort($wslist);
380       $smarty->assign("search_image", get_template_path('images/search.png'));
381       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
382       $smarty->assign("tree_image", get_template_path('images/tree.png'));
383       $smarty->assign("deplist", $this->config->idepartments);
384       $smarty->assign("alphabet", generate_alphabet());
385       foreach( array("depselect", "regex") as $type){
386         $smarty->assign("$type", $sysfilter[$type]);
387       }
388       $smarty->assign("hint", print_sizelimit_warning());
389       $smarty->assign("wslist", $wslist);
390       $smarty->assign("apply", apply_filter());
391       $display= $smarty->fetch (get_template_path('trust_machines.tpl', TRUE, dirname(__FILE__)));
392       return ($display);
393     }
395     /* Manage group add dialog */
396     if ($this->group_dialog){
398       /* Get global filter config */
399       $this->reload();
401       /* remove already assigned groups */
402       $glist= array();
403       foreach ($this->grouplist as $key => $value){
404         if (!isset($this->groupMembership[$key]) && obj_is_writable($key,"groups/group","memberUid")){
405           $glist[$key]= $value;
406         }
407       }
409       if($this->SubSearch){
410         $smarty->assign("SubSearchCHK"," checked ");
411       }else{
412         $smarty->assign("SubSearchCHK","");
413       }
415       $smarty->assign("regex",$this->GroupRegex);
416       $smarty->assign("guser",$this->GroupUserRegex);
417       $smarty->assign("groups", $glist);
418       $smarty->assign("search_image", get_template_path('images/search.png'));
419       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
420       $smarty->assign("tree_image", get_template_path('images/tree.png'));
421       $smarty->assign("deplist", $this->config->idepartments);
422       $smarty->assign("alphabet", generate_alphabet());
423       $smarty->assign("depselect",$_SESSION['CurrentMainBase']);
424       $smarty->assign("hint", print_sizelimit_warning());
426       $smarty->assign("apply", apply_filter());
427       $display.= $smarty->fetch (get_template_path('posix_groups.tpl', TRUE, dirname(__FILE__)));
428       return ($display);
429     }
431     /* Show main page */
432     $smarty= get_smarty();
434     /* In 'MyAccount' mode, we must remove write acls if we are not in editing mode. */ 
435     $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
437     /* Depending on pwmode, currently hardcoded because there are no other methods */
438     if ( 1 == 1 ){
439       $smarty->assign("pwmode", dirname(__FILE__)."/posix_shadow");
441       $shadowMinACL     =  $this->getacl("shadowMin",$SkipWrite);
442       $smarty->assign("shadowmins", sprintf(_("Password can't be changed up to %s days after last change"), 
443                                               "<input name=\"shadowMin\" size=3 maxlength=4 value=\"".$this->shadowMin."\">"));
445       $shadowMaxACL     =  $this->getacl("shadowMax",$SkipWrite);
446       $smarty->assign("shadowmaxs", sprintf(_("Password must be changed after %s days"), 
447                                               "<input name=\"shadowMax\" size=3 maxlength=4 value=\"".$this->shadowMax."\">"));
449       $shadowInactiveACL=  $this->getacl("shadowInactive",$SkipWrite);
450       $smarty->assign("shadowinactives", sprintf(_("Disable account after %s days of inactivity after password expiery"), 
451                                               "<input name=\"shadowInactive\" size=3 maxlength=4 value=\"".$this->shadowInactive."\">"));
453       $shadowWarningACL =  $this->getacl("shadowWarning",$SkipWrite);
454       $smarty->assign("shadowwarnings", sprintf(_("Warn user %s days before password expiery"), 
455                                               "<input name=\"shadowWarning\" size=3 maxlength=4 value=\"".$this->shadowWarning."\">"));
457       foreach( array("use_shadowMin", "use_shadowMax",
458                      "use_shadowExpire", "use_shadowInactive","use_shadowWarning") as $val){
459         if ($this->$val == 1){
460           $smarty->assign("$val", "checked");
461         } else {
462           $smarty->assign("$val", "");
463         }
464         $smarty->assign("$val"."ACL", $this->getacl($val,$SkipWrite));
465       }
467       if($this->mustchangepassword){
468         $smarty->assign("mustchangepassword", "checked");
469       } else {
470         $smarty->assign("mustchangepassword", "");
471       }
472       $smarty->assign("mustchangepasswordACL", $this->getacl("mustchangepassword",$SkipWrite));
473     }
475     /* Fill calendar */
476     /* If this $this->shadowExpire is empty 
477         use current date as base for calculating selectbox values.
478        (This attribute is empty if this is a new user )*/ 
479     if(empty($this->shadowExpire)){
480       $date= getdate(time());
481     }else{
482       $date= getdate($this->shadowExpire);
483     }
484  
485     $days= array();
486     for($d= 1; $d<32; $d++){
487       $days[$d]= $d;
488     }
489     $years= array();
490     for($y= $date['year']-10; $y<$date['year']+10; $y++){
491       $years[]= $y;
492     }
493     $months= array(_("January"), _("February"), _("March"), _("April"),
494         _("May"), _("June"), _("July"), _("August"), _("September"),
495         _("October"), _("November"), _("December"));
496     $smarty->assign("day", $date["mday"]);
497     $smarty->assign("days", $days);
498     $smarty->assign("months", $months);
499     $smarty->assign("month", $date["mon"]-1);
500     $smarty->assign("years", $years);
501     $smarty->assign("year", $date["year"]);
503     /* Fill arrays */
504     $smarty->assign("shells", $this->loginShellList);
505     $smarty->assign("secondaryGroups", $this->secondaryGroups);
506     $smarty->assign("primaryGroup", $this->primaryGroup);
507     if (!count($this->groupMembership)){
508       $smarty->assign("groupMembership", array("&nbsp;"));
509     } else {
510       $smarty->assign("groupMembership", $this->groupMembership);
511     }
512     if (count($this->groupMembership) > 16){
513       $smarty->assign("groups", "too_many_for_nfs");
514     } else {
515       $smarty->assign("groups", "");
516     }
518     /* Avoid "Undefined index: forceMode" */
519     $smarty->assign("forceMode", "");
521     /* Checkboxes */
522     if ($this->force_ids == 1){
523       $smarty->assign("force_ids", "checked");
524       if ($_SESSION['js']){
525         $smarty->assign("forceMode", "");
526       }
527     } else {
528       if ($_SESSION['js']){
529         $smarty->assign("forceMode", "disabled");
530       }
531       $smarty->assign("force_ids", "");
532     }
534     
536     $smarty->assign("force_idsACL", $this->getacl("uidNumber",$SkipWrite).$this->getacl("gidNumber",$SkipWrite));
538     /* Load attributes and acl's */
539     foreach($this->attributes as $val){
540       if(($_SESSION["js"])&&(($val=="uidNumber")||($val=="gidNumber")))
541       {
542         $smarty->assign("$val"."ACL",$this->getacl($val,$SkipWrite));
543         $smarty->assign("$val", $this->$val);
544         continue;
545       }
546       $smarty->assign("$val", $this->$val);
547       $smarty->assign("$val"."ACL", $this->getacl($val,$SkipWrite));
548     }
549     if($SkipWrite){
550       $smarty->assign("groupMembershipACL","r");
551     }else{
552       $smarty->assign("groupMembershipACL","rw");
553     }
554     $smarty->assign("status", $this->status);
556     /* Work on trust modes */
557     $smarty->assign("trusthide", " disabled ");
558     $smarty->assign("trustmodeACL",  $this->getacl("trustModel",$SkipWrite));
559     if ($this->trustModel == "fullaccess"){
560       $trustmode= 1;
561       // pervent double disable tag in html code, this will disturb our clean w3c html
562       $smarty->assign("trustmode",  $this->getacl("trustModel",$SkipWrite));
564     } elseif ($this->trustModel == "byhost"){
565       $trustmode= 2;
566       $smarty->assign("trusthide", "");
567     } else {
568       // pervent double disable tag in html code, this will disturb our clean w3c html
569       $smarty->assign("trustmode",  $this->getacl("trustModel",$SkipWrite));
570       $trustmode= 0;
571     }
572     $smarty->assign("trustmode", $trustmode);
573     $smarty->assign("trustmodes", array( 0 => _("disabled"), 1 => _("full access"),
574           2 => _("allow access to these hosts")));
578     if((count($this->accessTo))==0)
579       $smarty->assign("emptyArrAccess",true);
580     else
581       $smarty->assign("emptyArrAccess",false);
585     $smarty->assign("workstations", $this->accessTo);
587     $smarty->assign("apply", apply_filter());
588     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
589     return($display);
590   }
593   /* remove object from parent */
594   function remove_from_parent()
595   {
596     /* Cancel if there's nothing to do here */
597     if ((!$this->initially_was_account) || (!$this->acl_is_removeable())){
598       return;
599     }
601     /* include global link_info */
602     $ldap= $this->config->get_ldap_link();
604     /* Remove and write to LDAP */
605     plugin::remove_from_parent();
607     /* Zero out array */
608     $this->attrs['gosaHostACL']= array();
610     /* Keep uid, because we need it for authentification! */
611     unset($this->attrs['uid']);
612     unset($this->attrs['trustModel']);
614     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
615         $this->attributes, "Save");
616     $ldap->cd($this->dn);
617     $this->cleanup();
618     $ldap->modify ($this->attrs); 
620     new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
622     show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/posix account with dn '%s' failed."),$this->dn));
624     /* Delete group only if cn is uid and there are no other
625        members inside */
626     $ldap->cd ($this->config->current['BASE']);
627     $ldap->search ("(&(objectClass=posixGroup)(gidNumber=".$this->gidNumber."))", array("cn", "memberUid"));
628     if ($ldap->count() != 0){
629       $attrs= $ldap->fetch();
630       if ($attrs['cn'][0] == $this->uid &&
631           !isset($this->attrs['memberUid'])){
633         $ldap->rmDir($ldap->getDN());
634       }
635     }
637     /* Optionally execute a command after we're done */
638     $this->handle_post_events("remove",array("uid" => $this->uid));
639   }
642   function save_object()
643   {
644     if (isset($_POST['posixTab'])){
645       /* Save values to object */
646       plugin::save_object();
649       /* Save force GID checkbox */
650       if($this->acl_is_writeable("gidNumber") || $this->acl_is_writeable("uidNumber")){
651         if (isset ($_POST['force_ids'])){
652           $data= 1;
653         } else {
654           $data= 0;
655         }
656         if ($this->force_ids != $data){
657           $this->is_modified= TRUE;
658         }
659         $this->force_ids= $data;
660       }
662       /*Save primary group settings */
663       if($this->acl_is_writeable("primaryGroup") && isset($_POST['primaryGroup'])){
664         $data= $_POST['primaryGroup'];
665         if ($this->primaryGroup != $data){
666           $this->is_modified= TRUE;
667         }
668         $this->primaryGroup= $_POST['primaryGroup'];
669       }
671       foreach(array("shadowMin","shadowMax","shadowExpire","shadowInactive","shadowWarning","mustchangepassword") as $var) {
672         if($this->acl_is_writeable($var)){
673           $use_var = "use_".$var;
674           if(isset($_POST['use_'.$var])){
675             $this->$use_var  = true;
676             $this->$var      = $_POST[$var];
677           }else{
678             $this->$use_var  = false;
679             $this->$var      = 0;
680           }
681         }
682       }
684       /* Trust mode - special handling */
685       if($this->acl_is_writeable("trustModel")){
686         if (isset($_POST['trustmode'])){
687           $saved= $this->trustModel;
688           if ($_POST['trustmode'] == "1"){
689             $this->trustModel= "fullaccess";
690           } elseif ($_POST['trustmode'] == "2"){
691             $this->trustModel= "byhost";
692           } else {
693             $this->trustModel= "";
694           }
695           if ($this->trustModel != $saved){
696             $this->is_modified= TRUE;
697           }
698         }
699       }
700     }
702     /* Get regex from alphabet */
703     if(isset($_GET['search'])){
704       $this->GroupRegex = $_GET['search']."*";
705     }
707     /* Check checkboxes and regexes */
708     if(isset($_POST["PosixGroupDialogPosted"])){
710       if(isset($_POST['SubSearch']) && ($_POST['SubSearch'])){
711         $this->SubSearch = true;
712       }else{
713         $this->SubSearch = false;
714       }
715       if(isset($_POST['guser'])){
716         $this->GroupUserRegex = $_POST['guser'];
717       }
718       if(isset($_POST['regex'])){
719         $this->GroupRegex = $_POST['regex'];
720       }
721     }
722     $this->GroupRegex = preg_replace("/\*\**/","*",$this->GroupRegex);
723     $this->GroupUserRegex = preg_replace("/\*\**/","*",$this->GroupUserRegex);
724   }
727   /* Save data to LDAP, depending on is_account we save or delete */
728   function save()
729   {
731     /* include global link_info */
732     $ldap= $this->config->get_ldap_link();
734     /* Adapt shadow values */
735     if (!$this->use_shadowExpire){
736       $this->shadowExpire= "0";
737     } else {
738       /* Transform seconds to days here */
739       $this->shadowExpire= (int)($this->shadowExpire / (60 * 60 * 24)) ;
740     }
741     if (!$this->use_shadowMax){
742       $this->shadowMax= "0";
743     }
744     if ($this->mustchangepassword){
745       $this->shadowLastChange= (int)(date("U") / 86400) - $this->shadowMax - 1;
746     } else {
747       $this->shadowLastChange= (int)(date("U") / 86400);
748     }
749     if (!$this->use_shadowWarning){
750       $this->shadowWarning= "0";
751     }
753     /* Check what to do with ID's */
754     if ($this->force_ids == 0){
756       /* Use id's that are already set */
757       if ($this->savedUidNumber != ""){
758         $this->uidNumber= $this->savedUidNumber;
759         $this->gidNumber= $this->savedGidNumber;
760       } else {
762         /* Calculate new id's. We need to place a lock before calling get_next_id
763            to get real unique values. */
764         $wait= 10;
765         while (get_lock("uidnumber") != ""){
766           sleep (1);
768           /* Oups - timed out */
769           if ($wait-- == 0){
770             print_red (_("Failed: overriding lock"));
771             break;
772           }
773         }
775         add_lock ("uidnumber", "gosa");
776         $this->uidNumber= $this->get_next_id("uidNumber", $this->dn);
777         if ($this->savedGidNumber != ""){
778           $this->gidNumber= $this->savedGidNumber;
779         } else {
780           $this->gidNumber= $this->get_next_id("gidNumber", $this->dn);
781         }
782       }
784       if ($this->primaryGroup != 0){
785         $this->gidNumber= $this->primaryGroup;
786       }
787     }
789     if ($this->use_shadowMin != "1" ) {
790       $this->shadowMin = "";
791     }
793     if (($this->use_shadowMax != "1") && ($this->mustchangepassword != "1")) {
794       $this->shadowMax = "";
795     }
797     if ($this->use_shadowWarning != "1" ) {
798       $this->shadowWarning = "";
799     }
801     if ($this->use_shadowInactive != "1" ) {
802       $this->shadowInactive = "";
803     }
805     if ($this->use_shadowExpire != "1" ) {
806       $this->shadowExpire = "";
807     }
809     /* Fill gecos */
810     if (isset($this->parent) && $this->parent != NULL){
811       $this->gecos= rewrite($this->parent->by_object['user']->cn);
812       if (!preg_match('/^[a-z0-9 -]+$/i', $this->gecos)){
813         $this->gecos= "";
814       }
815     }
817     foreach(array("shadowMin","shadowMax","shadowWarning","shadowInactive","shadowExpire") as $attr){
818       $this->$attr = (int) $this->$attr;
819     }
820     /* Call parents save to prepare $this->attrs */
821     plugin::save();
823     /* Trust accounts */
824     $objectclasses= array();
825     foreach ($this->attrs['objectClass'] as $key => $class){
826       if (preg_match('/trustAccount/i', $class)){
827         continue;
828       }
829       $objectclasses[]= $this->attrs['objectClass'][$key];
830     }
831     $this->attrs['objectClass']= $objectclasses;
832     if ($this->trustModel != ""){
833       $this->attrs['objectClass'][]= "trustAccount";
834       $this->attrs['trustModel']= $this->trustModel;
835       $this->attrs['accessTo']= array();
836       if ($this->trustModel == "byhost"){
837         foreach ($this->accessTo as $host){
838           $this->attrs['accessTo'][]= $host;
839         }
840       }
841     } else {
842       if ($this->was_trust_account){
843         $this->attrs['accessTo']= array();
844         $this->attrs['trustModel']= array();
845       }
846     }
848     if(empty($this->attrs['gosaDefaultPrinter'])){
849       $thid->attrs['gosaDefaultPrinter']=array();
850     }
853     /* Save data to LDAP */
854     $ldap->cd($this->dn);
855     $this->cleanup();
856     unset($this->attrs['uid']);
857     $ldap->modify ($this->attrs); 
859     /* Log last action */ 
860     if($this->initially_was_account){
861       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
862     }else{
863       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
864     }
866     show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/posix account with dn '%s' failed."),$this->dn));
868     /* Remove lock needed for unique id generation */
869     del_lock ("uidnumber");
871     /* Posix accounts have group interrelationship, 
872        take care about these here if this is a new user without forced gidNumber. */
873     if ($this->force_ids == 0 && $this->primaryGroup == 0 && !$this->initially_was_account){
874       $ldap->cd($this->config->current['BASE']);
875       $ldap->search("(&(objectClass=posixGroup)(gidNumber=".$this->gidNumber."))", array("cn"));
877       /* Create group if it doesn't exist */
878       if ($ldap->count() == 0){
879         $groupdn= preg_replace ('/^'.$this->config->current['DNMODE'].'=[^,]+,'.get_people_ou().'/i', 'cn='.$this->uid.','.get_groups_ou(), $this->dn);
881         $g= new group($this->config, $groupdn);
882         $g->cn= $this->uid;
883         $g->force_gid= 1;
884         $g->gidNumber= $this->gidNumber;
885         $g->description= "Group of user ".$this->givenName." ".$this->sn;
886         $g->save ();
887       }
888     }
890     /* Take care about groupMembership values: add to groups */
891     foreach ($this->groupMembership as $key => $value){
892       if (!isset($this->savedGroupMembership[$key])){
893         $g= new grouptabs($this->config,$this->config->data['TABS']['GROUPTABS'], $key,"groups");
894         $g->set_acl_base($key);
895         $g->by_object['group']->addUser($this->uid);
896         $g->save();
897       }
898     }
900     /* Remove from groups not listed in groupMembership */
901     foreach ($this->savedGroupMembership as $key => $value){
902       if (!isset($this->groupMembership[$key])){
903         $g= new grouptabs($this->config,$this->config->data['TABS']['GROUPTABS'], $key,"groups");
904         $g->set_acl_base($key);
905         $g->by_object['group']->removeUser ($this->uid);
906         $g->save();
907       }
908     }
910     /* Optionally execute a command after we're done */
911     if ($this->initially_was_account == $this->is_account){
912       if ($this->is_modified){
913         $this->handle_post_events("modify",array("uid" => $this->uid));
914       }
915     } else {
916       $this->handle_post_events("add" ,array("uid"=> $this->uid));
917     }
918   }
920   /* Check formular input */
921   function check()
922   {
923     /* Include global link_info */
924     $ldap= $this->config->get_ldap_link();
926     /* Append groups as memberGroup: to check hook 
927      */
928     $tmp_attributes  = $this->attributes;    
929     $this->attributes[] = "memberGroup";
930     $this->memberGroup = array();
931     foreach($this->groupMembership as $dn => $name){
932       $this->memberGroup[] = $name;
933     }
935     /* Call common method to give check the hook */
936     $message= plugin::check();
937     $this->attributes = $tmp_attributes;
939     /* must: homeDirectory */
940     if ($this->homeDirectory == ""){
941       $message[]= _("The required field 'Home directory' is not set.");
942     }
943     if (!is_path($this->homeDirectory)){
944       $message[]= _("Please enter a valid path in 'Home directory' field.");
945     }
947     /* Check ID's if they are forced by user */
948     if ($this->force_ids == "1"){
950       /* Valid uid/gid? */
951       if (!is_id($this->uidNumber)){
952         $message[]= _("Value specified as 'UID' is not valid.");
953       } else {
954         if ($this->uidNumber < $this->config->current['MINID']){
955           $message[]= _("Value specified as 'UID' is too small.");
956         }
957       }
958       if (!is_id($this->gidNumber)){
959         $message[]= _("Value specified as 'GID' is not valid.");
960       } else {
961         if ($this->gidNumber < $this->config->current['MINID']){
962           $message[]= _("Value specified as 'GID' is too small.");
963         }
964       }
965     }
967     /* Check shadow settings, well I like spaghetties... */
968     if ($this->use_shadowMin){
969       if (!is_id($this->shadowMin)){
970         $message[]= _("Value specified as 'shadowMin' is not valid.");
971       }
972     }
973     if ($this->use_shadowMax){
974       if (!is_id($this->shadowMax)){
975         $message[]= _("Value specified as 'shadowMax' is not valid.");
976       }
977     }
978     if ($this->use_shadowWarning){
979       if (!is_id($this->shadowWarning)){
980         $message[]= _("Value specified as 'shadowWarning' is not valid.");
981       }
982       if (!$this->use_shadowMax){
983         $message[]= _("'shadowWarning' without 'shadowMax' makes no sense.");
984       }
985       if ($this->shadowWarning > $this->shadowMax){
986         $message[]= _("Value specified as 'shadowWarning' should be smaller than 'shadowMax'.");
987       }
988       if ($this->use_shadowMin && $this->shadowWarning < $this->shadowMin){
989         $message[]= _("Value specified as 'shadowWarning' should be greater than 'shadowMin'.");
990       }
991     }
992     if ($this->use_shadowInactive){
993       if (!is_id($this->shadowInactive)){
994         $message[]= _("Value specified as 'shadowInactive' is not valid.");
995       }
996       if (!$this->use_shadowMax){
997         $message[]= _("'shadowInactive' without 'shadowMax' makes no sense.");
998       }
999     }
1000     if ($this->use_shadowMin && $this->use_shadowMax){
1001       if ($this->shadowMin > $this->shadowMax){
1002         $message[]= _("Value specified as 'shadowMin' should be smaller than 'shadowMax'.");
1003       }
1004     }
1006     //  if(empty($this->gosaDefaultPrinter)){
1007     //    $message[]= _("You need to specify a valid default printer.");
1008     //  }
1010     return ($message);
1011   }
1013   function addGroup ($groups)
1014   {
1015     /* include global link_info */
1016     $ldap= $this->config->get_ldap_link();
1018     /* Walk through groups and add the descriptive entry if not exists */
1019     foreach ($groups as $value){
1020       if (!array_key_exists($value, $this->groupMembership)){
1021         $ldap->cat($value, array('cn', 'description', 'dn'));
1022         $attrs= $ldap->fetch();
1023         error_reporting (0);
1024         if (!isset($attrs['description'][0])){
1025           $entry= $attrs["cn"][0];
1026         } else {
1027           $dsc= preg_replace ('/^Group of user/', _("Group of user"), $attrs["description"][0]);
1028           $entry= $attrs["cn"][0]." [$dsc]";
1029         }
1030         error_reporting (E_ALL | E_STRICT);
1032         if(obj_is_writable($attrs['dn'],"groups/group","memberUid")){
1033           $this->groupMembership[$attrs['dn']]= $entry;
1034         }
1035       }
1036     }
1038     /* Sort groups */
1039     asort ($this->groupMembership);
1040     reset ($this->groupMembership);
1041   }
1044   /* Del posix user from some groups */
1045   function delGroup ($groups)
1046   {
1047     $dest= array();
1048     foreach($groups as $dn_to_del){
1049       if(isset($this->groupMembership[$dn_to_del]) && obj_is_writable($dn_to_del,"groups/group","memberUid")){
1050         unset($this->groupMembership[$dn_to_del]);
1051       }
1052     }
1053   }
1056   /* Adapt from template, using 'dn' */
1057   function adapt_from_template($dn)
1058   {
1059     /* Include global link_info */
1060     $ldap= $this->config->get_ldap_link();
1062     plugin::adapt_from_template($dn);
1063     $template= $this->attrs['uid'][0];
1065     /* Adapt group membership */
1066     $ldap->cd($this->config->current['BASE']);
1067     $ldap->search("(&(objectClass=posixGroup)(memberUid=".$this->attrs["uid"][0]."))", array("description", "cn"));
1069     while ($this->attrs= $ldap->fetch()){
1070       if (!isset($this->attrs["description"][0])){
1071         $entry= $this->attrs["cn"][0];
1072       } else {
1073         $entry= $this->attrs["cn"][0]." [".$this->attrs["description"][0]."]";
1074       }
1075       $this->groupMembership[$ldap->getDN()]= $entry;
1076     }
1078     /* Fix primary group settings */
1079     $ldap->cd($this->config->current['BASE']);
1080     $ldap->search("(&(objectClass=posixGroup)(cn=$template)(gidNumber=".$this->gidNumber."))", array("cn"));
1081     if ($ldap->count() != 1){
1082       $this->primaryGroup= $this->gidNumber;
1083     }
1085     $ldap->cd($this->config->current['BASE']);
1086     $ldap->search("(&(objectClass=gosaUserTemplate)(uid=".$template.")(accessTo=*))", array("cn","accessTo"));
1087     while($attr = $ldap->fetch()){
1088       $tmp = $attr['accessTo'];
1089       unset ($tmp['count']);
1090       $this->accessTo = $tmp;   
1091     }
1093     /* Adjust shadow checkboxes */
1094     foreach (array("shadowMin", "shadowMax", "shadowWarning", "shadowInactive") as $val){
1095       if ($this->$val != 0){
1096         $oval= "use_".$val;
1097         $this->$oval= "1";
1098       }
1099     }
1101     /* FIXME: NEED review of this section */
1102     /* Need to check shadowExpire separately */
1104     /* 
1105      * If shadowExpire is not enabled in the template, it's a UNIX timestamp - so don't convert it to seconds.
1106      * The check is a hack - if difference between timestamp generated above and here is max 1 day.
1107      */
1108     if(abs($this->shadowExpire - time())>86400) {
1109       $this->shadowExpire= $this->convertToSeconds($this->shadowExpire);
1110     }
1111     
1112     /* Only enable checkbox, if shadowExpire is in the future */
1113     if($this->shadowExpire > time()) {
1114       $this->use_shadowExpire= "1";
1115     }
1116   }
1118   function convertToSeconds($val)
1119   {
1120     if ($val != 0){
1121       $val*= 60 * 60 * 24;
1122     } else {
1123       $date= getdate();
1124       $val= floor($date[0] / (60*60*24)) * 60 * 60 * 24;
1125     }
1126     return($val);
1127   }
1130   function get_next_id($attrib, $dn)
1131   {
1132     $ids= array();
1133     $ldap= $this->config->get_ldap_link();
1135     $ldap->cd ($this->config->current['BASE']);
1136     if (preg_match('/gidNumber/i', $attrib)){
1137       $oc= "posixGroup";
1138     } else {
1139       $oc= "posixAccount";
1140     }
1141     $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
1143     /* Get list of ids */
1144     while ($attrs= $ldap->fetch()){
1145       $ids[]= (int)$attrs["$attrib"][0];
1146     }
1148     /* Add the nobody id */
1149     $ids[]= 65534;
1151     /* get the ranges */
1152     $tmp = array('0'=> 1000); 
1153     if (preg_match('/posixAccount/', $oc) && isset($this->config->current['UIDBASE'])) {
1154       $tmp= split('-',$this->config->current['UIDBASE']);
1155     } elseif(isset($this->config->current['GIDBASE'])){
1156       $tmp= split('-',$this->config->current['GIDBASE']);
1157     }
1159     /* Set hwm to max if not set - for backward compatibility */
1160     $lwm= $tmp[0];
1161     if (isset($tmp[1])){
1162       $hwm= $tmp[1];
1163     } else {
1164       $hwm= pow(2,32);
1165     }
1167     /* Find out next free id near to UID_BASE */
1168     if (!isset($this->config->current['BASE_HOOK'])){
1169       $base= $lwm;
1170     } else {
1171       /* Call base hook */
1172       $base= get_base_from_hook($dn, $attrib);
1173     }
1174     for ($id= $base; $id++; $id < pow(2,32)){
1175       if (!in_array($id, $ids)){
1176         return ($id);
1177       }
1178     }
1180     /* Should not happen */
1181     if ($id == $hwm){
1182       print_red(_("Too many users, can't allocate a free ID!"));
1183       exit;
1184     }
1186   }
1188   function reload()
1189   {
1190     /* Set base for all searches */
1191     $base     = $_SESSION['CurrentMainBase'];
1192     $base     = $base;
1193     $ldap     = $this->config->get_ldap_link();    
1194     $attrs    =  array("cn", "description", "gidNumber");
1195     $Flags    = GL_SIZELIMIT;
1197     /* Get groups */
1198     if ($this->GroupUserRegex == '*'){
1199       $filter = "(&(objectClass=posixGroup)(cn=".$this->GroupRegex."))";
1200     } else {
1201       $filter= "(&(objectClass=posixGroup)(cn=".$this->GroupRegex.")(memberUid=".$this->GroupUserRegex."))";
1202     }
1203     if($this->SubSearch){
1204       $Flags |= GL_SUBSEARCH;
1205     }else{
1206       $base = get_groups_ou().$base;
1207     }
1209     $res= get_list($filter, "groups", $base,$attrs, $Flags);
1210   
1211     /* check sizelimit */
1212     if (preg_match("/size limit/i", $ldap->error)){
1213       $_SESSION['limit_exceeded']= TRUE;
1214     }
1216     /* Create a list of users */
1217     $this->grouplist = array();
1218     foreach ($res as $value){
1219       $this->grouplist[$value['gidNumber'][0]]= $value;
1220     }
1222     $tmp=array();
1223     foreach($this->grouplist as $tkey => $val ){
1224       $tmp[strtolower($val['cn'][0]).$val['cn'][0]]=$val;
1225     }
1227     /* Sort index */
1228     ksort($tmp);
1230     /* Recreate index array[dn]=cn[description]*/
1231     $this->grouplist=array();
1232     foreach($tmp as $val){
1233       if(isset($val['description'])){
1234         $this->grouplist[$val['dn']]=$val['cn'][0]."&nbsp;[".$val['description'][0]."]";
1235       }else{
1236         $this->grouplist[$val['dn']]=$val['cn'][0];
1237       }
1238     }
1240     reset ($this->grouplist);
1241   }
1244   /* Get posts from copy & paste dialog */ 
1245   function saveCopyDialog()
1246   {
1247     if(isset($_POST['homeDirectory'])){
1248       $this->homeDirectory = $_POST['homeDirectory'];
1249       if (isset ($_POST['force_ids'])){
1250         $data= 1;
1251         $this->gidNumber = $_POST['gidNumber'];
1252         $this->uidNumber = $_POST['uidNumber'];
1253       } else {
1254         $data= 0;
1255       }
1256       if ($this->force_ids != $data){
1257         $this->is_modified= TRUE;
1258       }
1259       $this->force_ids= $data;
1260     }
1261   }
1262  
1264   /* Create the posix dialog part for copy & paste */
1265   function getCopyDialog()
1266   {
1267     /* Skip dialog creation if this is not a valid account*/
1268     if(!$this->is_account) return("");
1269     if ($this->force_ids == 1){
1270       $force_ids = "checked";
1271       if ($_SESSION['js']){
1272         $forceMode = "";
1273       }
1274     } else {
1275       if ($_SESSION['js']){
1276         if($this->acl != "#none#")
1277           $forceMode ="disabled";
1278       }
1279       $force_ids = "";
1280     }
1282     $sta = "";
1284     /* Open group add dialog */
1285     if(isset($_POST['edit_groupmembership'])){
1286       $this->group_dialog = TRUE;
1287       $sta = "SubDialog";
1288     }
1290     /* If the group-add dialog is closed, call execute 
1291        to ensure that the membership is updatd */
1292     if(isset($_POST['add_groups_finish']) || isset($_POST['add_groups_cancel'])){
1293       $this->execute();
1294       $this->group_dialog =FALSE;
1295     }
1297     if($this->group_dialog){
1298       $str = $this->execute(true);
1299       $ret = array();
1300       $ret['string'] = $str;
1301       $ret['status'] = $sta;
1302       return($ret);
1303     }
1305     /* If a group member should be deleted, simply call execute */
1306     if(isset($_POST['delete_groupmembership'])){
1307       $this->execute();
1308     }
1310     /* Assigned informations to smarty */
1311     $smarty = get_smarty();
1312     $smarty->assign("homeDirectory",$this->homeDirectory);
1313     $smarty->assign("uidNumber",$this->uidNumber);
1314     $smarty->assign("gidNumber",$this->gidNumber);
1315     $smarty->assign("forceMode",$forceMode);
1316     $smarty->assign("force_ids",$force_ids);
1317     if (!count($this->groupMembership)){
1318       $smarty->assign("groupMembership", array("&nbsp;"));
1319     } else {
1320       $smarty->assign("groupMembership", $this->groupMembership);
1321     }
1323     /* Display wars message if there are more than 16 group members */
1324     if (count($this->groupMembership) > 16){
1325       $smarty->assign("groups", "too_many_for_nfs");
1326     } else {
1327       $smarty->assign("groups", "");
1328     }
1329     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1331     $ret = array();
1332     $ret['string'] = $str;
1333     $ret['status'] = $sta;
1334     return($ret);
1335   }
1338   function PrepareForCopyPaste($source)
1339   {
1340     plugin::PrepareForCopyPaste($source);
1342     /* Avoid using the same gid/uid number as source user */
1343     $this->savedUidNumber = $this->get_next_id("gidNumber", $this->dn);
1344     $this->savedGidNumber = $this->get_next_id("uidNumber", $this->dn);
1345   }
1348   function plInfo()
1349   {
1350     return (array(
1351           "plDescription"     => _("POSIX account"),
1352           "plSelfModify"      => TRUE,
1353           "plDepends"         => array("user"),
1354           "plPriority"        => 2,
1355           "plSection"         => array("personal" => _("My account")),
1356           "plCategory"        => array("users"),
1357           "plOptions"         => array(),
1359           "plProvidedAcls"  => array(
1361             "homeDirectory"       =>  _("Home directory"), 
1362             "loginShell"          =>  _("Shell"),
1363             "uidNumber"           =>  _("User ID"),
1364             "gidNumber"           =>  _("Group ID"),
1366             "mustchangepassword"=>  _("Force password change on login"),
1367             "shadowMin"           =>  _("Shadow min"),
1368             "shadowMax"           =>  _("Shadow max"),
1369             "shadowWarning"       =>  _("Shadow warning"),
1370             "shadowInactive"      =>  _("Shadow inactive"),
1371             "shadowExpire"        =>  _("Shadow expire"),
1372             "trustModel"          =>  _("System trust model")))
1373             );
1374   }
1377 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1378 ?>