Code

Only switch account state if allowed
[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 $gosaDefaultLanguage= "";
38   var $accessTo= array();
39   var $trustModel= "";
41   var $glist=array();
42   var $status= "";
43   var $loginShellList= array();
44   var $groupMembership= array();
45   var $savedGroupMembership= array();
46   var $savedUidNumber= "";
47   var $savedGidNumber= "";
48   var $use_shadowMin= "0";
49   var $use_shadowMax= "0";
50   var $use_shadowWarning= "0";
51   var $use_shadowInactive= "0";
52   var $use_shadowExpire= "0";
53   var $must_change_password= "0";
54   var $force_ids= 0;
55   var $group_dialog= FALSE;
56   var $show_ws_dialog= FALSE;
57   var $secondaryGroups= array();
58   var $primaryGroup= 0;
59   var $was_trust_account= FALSE;
61   var $grouplist  = array();
62   var $ui         = array();
64   var $GroupRegex       = "*";
65   var $GroupUserRegex   = "*";
66   var $SubSearch        = false;
68   /* attribute list for save action */
69   var $CopyPasteVars  = array("grouplist","groupMembership","use_shadowMin","use_shadowMax","use_shadowWarning","use_shadowInactive","use_shadowExpire","must_change_password","grouplist","savedGidNumber","savedUidNumber");
70   var $attributes     = array("homeDirectory", "loginShell", "uidNumber", "gidNumber", "gecos",
71       "shadowMin", "shadowMax", "shadowWarning", "shadowInactive", "shadowLastChange",
72       "shadowExpire", "gosaDefaultPrinter", "gosaDefaultLanguage", "uid","accessTo","trustModel");
73   var $objectclasses= array("posixAccount", "shadowAccount");
75   var $uid ="";
77   /* constructor, if 'dn' is set, the node loads the given
78      'dn' from LDAP */
79   function posixAccount ($config, $dn= NULL, $parent= NULL)
80   {
81     /* Configuration is fine, allways */
82     $this->config= $config;
84     /* Load bases attributes */
85     plugin::plugin($config, $dn, $parent);
87     /* set user id */    
88     if(isset($this->attrs['uid'])){
89       $this->uid = $this->attrs['uid'][0];
90     }
92     $ldap= $this->config->get_ldap_link();
94     if ($dn != NULL){
96       /* Correct is_account. shadowAccount is not required. */
97       if (isset($this->attrs['objectClass']) &&
98           in_array ('posixAccount', $this->attrs['objectClass'])){
100         $this->is_account= TRUE;
101       }
103       /* Is this account a trustAccount? */
104       if ($this->is_account && isset($this->attrs['trustModel'])){
105         $this->trustModel= $this->attrs['trustModel'][0];
106         $this->was_trust_account= TRUE;
107       } else {
108         $this->was_trust_account= FALSE;
109         $this->trustModel= "";
110       }
111          
112           $this->accessTo = array(); 
113       if ($this->is_account && isset($this->attrs['accessTo'])){
114         for ($i= 0; $i<$this->attrs['accessTo']['count']; $i++){
115           $tmp= $this->attrs['accessTo'][$i];
116           $this->accessTo[$tmp]= $tmp;
117         }
118       }
119       $this->initially_was_account= $this->is_account;
121       /* Fill group */
122       $this->primaryGroup= $this->gidNumber;
124       /* Generate status text */
125       $current= date("U");
127       $current= floor($current / 60 /60 / 24);
129       if (($current >= $this->shadowExpire) && $this->shadowExpire){
130         $this->status= _("expired");
131         if (($current - $this->shadowExpire) < $this->shadowInactive){
132           $this->status.= ", "._("grace time active");
133         }
134       } elseif (($this->shadowLastChange + $this->shadowMin) >= $current){
135         $this->status= _("active, password not changable");
136       } elseif (($this->shadowLastChange + $this->shadowMax) >= $current){
137         $this->status= _("active, password expired");
138       } else {
139         $this->status= _("active");
140       }
142       /* Get group membership */
143       $ldap->cd($this->config->current['BASE']);
144       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("cn", "description"));
146       while ($this->attrs= $ldap->fetch()){
147         if (!isset($this->attrs["description"][0])){
148           $entry= $this->attrs["cn"][0];
149         } else {
150           $dsc= preg_replace ('/^Group of user/', _("Group of user"), $this->attrs["description"][0]);
151           $entry= $this->attrs["cn"][0]." [$dsc]";
152         }
153         $this->groupMembership[$ldap->getDN()]= $entry;
154       }
155       asort($this->groupMembership);
156       reset($this->groupMembership);
157       $this->savedGroupMembership= $this->groupMembership;
158       $this->savedUidNumber= $this->uidNumber;
159       $this->savedGidNumber= $this->gidNumber;
160     }
162     /* Adjust shadow checkboxes */
163     foreach (array("shadowMin", "shadowMax", "shadowWarning", "shadowInactive",
164           "shadowExpire") as $val){
166       if ($this->$val != 0){
167         $oval= "use_".$val;
168         $this->$oval= "1";
169       }
170     }
172     /* Convert to seconds */
173     $this->shadowExpire= $this->convertToSeconds($this->shadowExpire);
175     /* Generate shell list from CONFIG_DIR./shells */
176     if (file_exists(CONFIG_DIR.'/shells')){
177       $shells = file (CONFIG_DIR.'/shells');
178       foreach ($shells as $line){
179         if (!preg_match ("/^#/", $line)){
180           $this->loginShellList[]= trim($line);
181         }
182       }
183     } else {
184       if ($this->loginShell == ""){
185         $this->loginShellList[]= _("unconfigured");
186       }
187     }
189     /* Insert possibly missing loginShell */
190     if ($this->loginShell != "" && !in_array($this->loginShell, $this->loginShellList)){
191       $this->loginShellList[]= $this->loginShell;
192     }
194     /* Set tag attribute if we've tagging activated */
195     $filter= "(objectClass=posixGroup)";
196     $ui= get_userinfo();
197     if ($ui->gosaUnitTag != "" && isset($config->current['STRICT_UNITS']) &&
198         preg_match('/TRUE/i', $config->current['STRICT_UNITS'])){
199       $filter= "(&(objectClass=posixGroup)(gosaUnitTag=".$ui->gosaUnitTag."))";
200     }
202     /* Generate group list */
203     $ldap->cd($this->config->current['BASE']);
204     $ldap->search("$filter", array("cn", "gidNumber"));
205     $this->secondaryGroups[]= "- "._("automatic")." -";
206     while ($attrs= $ldap->fetch()){
207       $this->secondaryGroups[$attrs['gidNumber'][0]]= $attrs['cn'][0];
208     }
209     asort ($this->secondaryGroups);
211     /* Get global filter config */
212     if (!is_global("sysfilter")){
213       $ui= get_userinfo();
214       $base= get_base_from_people($ui->dn);
215       $sysfilter= array( "depselect"       => $base,
216           "regex"           => "*");
217       register_global("sysfilter", $sysfilter);
218     }
219     $this->ui = get_userinfo();
220   }
223   /* execute generates the html output for this node */
224   function execute($isCopyPaste = false)
225   {
226         /* Call parent execute */
227         plugin::execute();
228   $display= "";
230   /* Department has changed? */
231   if(isset($_POST['depselect'])){
232     $_SESSION['CurrentMainBase']= validate($_POST['depselect']);
233   }
235   if(!$isCopyPaste){
236     /* Do we need to flip is_account state? */
237     if (isset($_POST['modify_state'])){
238       if($this->is_account && $this->acl == "#all#"){
239         $this->is_account= !$this->is_account;
240       }elseif(!$this->is_account && chkacl($this->acl,"create") == ""){
241         $this->is_account= !$this->is_account;
242       }
243     }
245     /* Do we represent a valid posixAccount? */
246     if (!$this->is_account && $this->parent == NULL ){
247       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
248         _("This account has no unix extensions.")."</b>";
249       $display.= back_to_main();
250       return ($display);
251     }
254     /* Show tab dialog headers */
255     if ($this->parent != NULL){
256       if ($this->is_account){
257         if (isset($this->parent->by_object['sambaAccount'])){
258           $obj= $this->parent->by_object['sambaAccount'];
259         }
260         if (isset($obj) && $obj->is_account == TRUE &&
261             ((isset($this->parent->by_object['sambaAccount']))&&($this->parent->by_object['sambaAccount']->is_account))
262             ||(isset($this->parent->by_object['environment'] ))&&($this->parent->by_object['environment'] ->is_account)){
264           /* Samba3 dependency on posix accounts are enabled
265              in the moment, because I need to rely on unique
266              uidNumbers. There'll be a better solution later
267              on. */
268           $display= $this->show_header(_("Remove posix account"),
269               _("This account has unix features enabled. To disable them, you'll need to remove the samba / environment account first."), TRUE);
270         } else {
271           $display= $this->show_header(_("Remove posix account"),
272               _("This account has posix features enabled. You can disable them by clicking below."));
273         }
274       } else {
275         $display= $this->show_header(_("Create posix account"),
276             _("This account has posix features disabled. You can enable them by clicking below."));
277         return($display);
278       }
279     }
280   }
281   /* Trigger group edit? */
282   if (isset($_POST['edit_groupmembership'])){
283     $this->group_dialog= TRUE;
284     $this->dialog= TRUE;
285   }
287   /* Cancel group edit? */
288   if (isset($_POST['add_groups_cancel']) ||
289       isset($_POST['add_groups_finish'])){
290     $this->group_dialog= FALSE;
291     $this->dialog= FALSE;
292   }
294   /* Add selected groups */
295   if (isset($_POST['add_groups_finish']) && isset($_POST['groups']) &&
296       count($_POST['groups'])){
298       if (chkacl ($this->acl, "memberUid") == ""){
299         $this->addGroup ($_POST['groups']);
300         $this->is_modified= TRUE;
301       }
302     }
304     /* Delete selected groups */
305     if (isset($_POST['delete_groupmembership']) && 
306         isset($_POST['group_list']) && count($_POST['group_list'])){
308       if (chkacl ($this->acl, "memberUid") == ""){
309         $this->delGroup ($_POST['group_list']);
310         $this->is_modified= TRUE;
311       }
312     }
314     /* Add user workstation? */
315     if (isset($_POST["add_ws"]) && chkacl($this->acl,"allowedHosts") == ""){
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']) && chkacl($this->acl,"allowedHosts") == ""){
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       $acl= array($this->config->current['BASE'] => ":all");
373       $regex= $sysfilter['regex'];
374       $filter= "(&(|(objectClass=goServer)(objectClass=gotoWorkstation)(objectClass=gotoTerminal))$exclude(cn=*)(cn=$regex))";
375       $res= get_list($filter, $acl, $sysfilter['depselect'], array("cn"), GL_SUBSEARCH | GL_SIZELIMIT);
376       $wslist= array();
377       foreach ($res as $attrs){
378         $wslist[]= preg_replace('/\$/', '', $attrs['cn'][0]);
379       }
380       asort($wslist);
381       $smarty->assign("search_image", get_template_path('images/search.png'));
382       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
383       $smarty->assign("tree_image", get_template_path('images/tree.png'));
384       $smarty->assign("deplist", $this->config->idepartments);
385       $smarty->assign("alphabet", generate_alphabet());
386       foreach( array("depselect", "regex") as $type){
387         $smarty->assign("$type", $sysfilter[$type]);
388       }
389       $smarty->assign("hint", print_sizelimit_warning());
390       $smarty->assign("wslist", $wslist);
391       $smarty->assign("apply", apply_filter());
392       $display= $smarty->fetch (get_template_path('trust_machines.tpl', TRUE, dirname(__FILE__)));
393       return ($display);
394     }
396     /* Manage group add dialog */
397     if ($this->group_dialog){
399       /* Get global filter config */
400       $this->reload();
402       /* remove already assigned groups */
403       $glist= array();
404       foreach ($this->grouplist as $key => $value){
405         if (!isset($this->groupMembership[$key])){
406           $glist[$key]= $value;
407         }
408       }
410       if($this->SubSearch){
411         $smarty->assign("SubSearchCHK"," checked ");
412       }else{
413         $smarty->assign("SubSearchCHK","");
414       }
416       $smarty->assign("regex",$this->GroupRegex);
417       $smarty->assign("guser",$this->GroupUserRegex);
418       $smarty->assign("groups", $glist);
419       $smarty->assign("search_image", get_template_path('images/search.png'));
420       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
421       $smarty->assign("tree_image", get_template_path('images/tree.png'));
422       $smarty->assign("deplist", $this->config->idepartments);
423       $smarty->assign("alphabet", generate_alphabet());
424       $smarty->assign("depselect",$_SESSION['CurrentMainBase']);
425       $smarty->assign("hint", print_sizelimit_warning());
427       $smarty->assign("apply", apply_filter());
428       $display.= $smarty->fetch (get_template_path('posix_groups.tpl', TRUE, dirname(__FILE__)));
429       return ($display);
430     }
432     /* Show main page */
433     $smarty= get_smarty();
435     /* Depending on pwmode, currently hardcoded because there are no other methods */
436     if ( 1 == 1 ){
437       $smarty->assign("pwmode", dirname(__FILE__)."/posix_shadow");
438       $shadowMinACL= chkacl($this->acl, "shadowMin");
439       $smarty->assign("shadowmins", sprintf(_("Password can't be changed up to %s days after last change"), "<input name=\"shadowMin\" size=3 maxlength=4 $shadowMinACL value=\"".$this->shadowMin."\">"));
440       $shadowMaxACL= chkacl($this->acl, "shadowMax");
441       $smarty->assign("shadowmaxs", sprintf(_("Password must be changed after %s days"), "<input name=\"shadowMax\" size=3 maxlength=4 $shadowMaxACL value=\"".$this->shadowMax."\">"));
442       $shadowInactiveACL= chkacl($this->acl, "shadowInactive");
443       $smarty->assign("shadowinactives", sprintf(_("Disable account after %s days of inactivity after password expiery"), "<input name=\"shadowInactive\" size=3 maxlength=4 $shadowInactiveACL value=\"".$this->shadowInactive."\">"));
444       $shadowWarningACL= chkacl($this->acl, "shadowWarning");
445       $smarty->assign("shadowwarnings", sprintf(_("Warn user %s days before password expiery"), "<input name=\"shadowWarning\" size=3 maxlength=4 $shadowWarningACL value=\"".$this->shadowWarning."\">"));
446       foreach( array("must_change_password", "use_shadowMin", "use_shadowMax",
447             "use_shadowExpire", "use_shadowInactive",
448             "use_shadowWarning") as $val){
449         if ($this->$val == 1){
450           $smarty->assign("$val", "checked");
451         } else {
452           $smarty->assign("$val", "");
453         }
454         $smarty->assign("$val"."ACL", chkacl($this->acl, $val));
455       }
456     }
458     /* Fill calendar */
459    
460     /* If this $this->shadowExpire is empty 
461         use current date as base for calculating selectbox values.
462        (This attribute is empty if this is a new user )*/ 
463     if(empty($this->shadowExpire)){
464       $date= getdate(time());
465     }else{
466       $date= getdate($this->shadowExpire);
467     }
469     $days= array();
470     for($d= 1; $d<32; $d++){
471       $days[$d]= $d;
472     }
473     $years= array();
474     for($y= $date['year']-10; $y<$date['year']+10; $y++){
475       $years[]= $y;
476     }
477     $months= array(_("January"), _("February"), _("March"), _("April"),
478         _("May"), _("June"), _("July"), _("August"), _("September"),
479         _("October"), _("November"), _("December"));
480     $smarty->assign("day", $date["mday"]);
481     $smarty->assign("days", $days);
482     $smarty->assign("months", $months);
483     $smarty->assign("month", $date["mon"]-1);
484     $smarty->assign("years", $years);
485     $smarty->assign("year", $date["year"]);
487     /* Fill arrays */
488     $smarty->assign("shells", $this->loginShellList);
489     $smarty->assign("secondaryGroups", $this->secondaryGroups);
490     $smarty->assign("primaryGroup", $this->primaryGroup);
491    if (!count($this->groupMembership)){
492       $smarty->assign("groupMembership", array("&nbsp;"));
493     } else {
494       $smarty->assign("groupMembership", $this->groupMembership);
495     }
496     if (count($this->groupMembership) > 16){
497       $smarty->assign("groups", "too_many_for_nfs");
498     } else {
499       $smarty->assign("groups", "");
500     }
501     $smarty->assign("languages", $this->config->data['MAIN']['LANGUAGES']);
503         /* Avoid "Undefined index: forceMode" */
504     $smarty->assign("forceMode", "");
506     /* Checkboxes */
507     if ($this->force_ids == 1){
508       $smarty->assign("force_ids", "checked");
509       if ($_SESSION['js']){
510         $smarty->assign("forceMode", "");
511       }
512     } else {
513       if ($_SESSION['js']){
514                 if($this->acl != "#none#")
515         $smarty->assign("forceMode", "disabled");
516       }
517       $smarty->assign("force_ids", "");
518     }
519     $smarty->assign("force_idsACL", chkacl($this->acl, "force_ids"));
521     /* Load attributes and acl's */
522     foreach($this->attributes as $val){
523       if((chkacl($this->acl,$val)=="")&&(($_SESSION["js"])&&(($val=="uidNumber")||($val=="gidNumber"))))
524         {
525           $smarty->assign("$val"."ACL","");
526           $smarty->assign("$val", $this->$val);
527           continue;
528         }
529       $smarty->assign("$val", $this->$val);
530       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
531     }
532     $smarty->assign("groupMembershipACL", chkacl($this->acl, "groupMembership"));
533     $smarty->assign("status", $this->status);
535     /* Work on trust modes */
536     $smarty->assign("trustmodeACL", chkacl($this->acl, "trustmode"));
537     if ($this->trustModel == "fullaccess"){
538       $trustmode= 1;
539       // pervent double disable tag in html code, this will disturb our clean w3c html
540     
541     if(chkacl($this->acl, "trustmode")==""){
542           $smarty->assign("trusthide", "disabled");
543       }else{
544           $smarty->assign("trusthide", "");
545       }
547     } elseif ($this->trustModel == "byhost"){
548       $trustmode= 2;
549       $smarty->assign("trusthide", "");
550     } else {
551       // pervent double disable tag in html code, this will disturb our clean w3c html
552       if(chkacl($this->acl, "trustmode")==""){
553           $smarty->assign("trusthide", "disabled");
554       }else{
555           $smarty->assign("trusthide", "");
556       }
557       $trustmode= 0;
558     }
559     $smarty->assign("trustmode", $trustmode);
560     $smarty->assign("trustmodes", array( 0 => _("disabled"), 1 => _("full access"),
561           2 => _("allow access to these hosts")));
565     if((count($this->accessTo))==0)
566       $smarty->assign("emptyArrAccess",true);
567     else
568       $smarty->assign("emptyArrAccess",false);
569     
572     $smarty->assign("workstations", $this->accessTo);
574     $smarty->assign("apply", apply_filter());
575     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
576     return($display);
577   }
580   /* remove object from parent */
581   function remove_from_parent()
582   {
583     /* Cancel if there's nothing to do here */
584     if (!$this->initially_was_account){
585       return;
586     }
588     /* include global link_info */
589     $ldap= $this->config->get_ldap_link();
590     
591         /* Remove and write to LDAP */
592     plugin::remove_from_parent();
594     /* Zero out array */
595     $this->attrs['gosaHostACL']= array();
597     /* Keep uid, because we need it for authentification! */
598     unset($this->attrs['uid']);
599     unset($this->attrs['trustModel']);
601     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
602         $this->attributes, "Save");
603     $ldap->cd($this->dn);
604     $this->cleanup();
605     $ldap->modify ($this->attrs); 
607     show_ldap_error($ldap->get_error(), _("Removing UNIX account failed"));
609     /* Delete group only if cn is uid and there are no other
610        members inside */
611     $ldap->cd ($this->config->current['BASE']);
612     $ldap->search ("(&(objectClass=posixGroup)(gidNumber=".$this->gidNumber."))", array("cn", "memberUid"));
613     if ($ldap->count() != 0){
614       $attrs= $ldap->fetch();
615       if ($attrs['cn'][0] == $this->uid &&
616           !isset($this->attrs['memberUid'])){
618         $ldap->rmDir($ldap->getDN());
619       }
620     }
622     /* Optionally execute a command after we're done */
623     $this->handle_post_events("remove", array("uid" => $this->uid));
624   }
627   function save_object()
628   {
629     if (isset($_POST['posixTab'])){
630       /* Save values to object */
631       plugin::save_object();
633       /* Save force GID attribute */
634       if (chkacl ($this->acl, "force_ids") == ""){
635         if (isset ($_POST['force_ids'])){
636           $data= 1;
637         } else {
638           $data= 0;
639         }
640         if ($this->force_ids != $data){
641           $this->is_modified= TRUE;
642         }
643         $this->force_ids= $data;
645         $data= $_POST['primaryGroup'];
646         if ($this->primaryGroup != $data){
647           $this->is_modified= TRUE;
648         }
649         $this->primaryGroup= $_POST['primaryGroup'];
650       }
652       /* Save pwmode dependent attributes, curently hardcoded because there're
653          no alternatives */
654       if (1 == 1){
655         foreach( array("must_change_password", "use_shadowMin", "use_shadowMax",
656               "use_shadowExpire", "use_shadowInactive",
657               "use_shadowWarning") as $val){
658           if (chkacl($this->acl, "$val") == ""){
659             if (isset ($_POST[$val])){
660               $data= 1;
661             } else {
662               $data= 0;
663             }
664             if ($data != $this->$val){
665               $this->is_modified= TRUE;
666             }
667             $this->$val= $data;
668           }
669         }
670       }
672       /* Trust mode - special handling */
673       if (isset($_POST['trustmode']) && chkacl($this->acl,"allowedHosts") == ""){
674         $saved= $this->trustModel;
675         if ($_POST['trustmode'] == "1"){
676           $this->trustModel= "fullaccess";
677         } elseif ($_POST['trustmode'] == "2"){
678           $this->trustModel= "byhost";
679         } else {
680           $this->trustModel= "";
681         }
682         if ($this->trustModel != $saved){
683           $this->is_modified= TRUE;
684         }
685       }
686     }
688     /* Get regex from alphabet */
689     if(isset($_GET['search'])){
690       $this->GroupRegex = $_GET['search']."*";
691     }
693     /* Check checkboxes and regexes */
694     if(isset($_POST["PosixGroupDialogPosted"])){
695       if(isset($_POST['SubSearch']) && ($_POST['SubSearch'])){
696         $this->SubSearch = true;
697       }else{
698         $this->SubSearch = false;
699       }
700     
701       if(isset($_POST['guser'])){
702         $this->GroupUserRegex = $_POST['guser'];
703       }
704       if(isset($_POST['regex'])){
705         $this->GroupRegex = $_POST['regex'];
706       }
707     }
708     $this->GroupRegex = preg_replace("/\*\**/","*",$this->GroupRegex);
709     $this->GroupUserRegex = preg_replace("/\*\**/","*",$this->GroupUserRegex);
710   }
713   /* Save data to LDAP, depending on is_account we save or delete */
714   function save()
715   {
716         
717     /* include global link_info */
718     $ldap= $this->config->get_ldap_link();
720     /* Adapt shadow values */
721     if (!$this->use_shadowExpire){
722       $this->shadowExpire= "0";
723     } else {
724       /* Transform seconds to days here */
725       $this->shadowExpire= (int)($this->shadowExpire / (60 * 60 * 24)) ;
726     }
727     if (!$this->use_shadowMax){
728       $this->shadowMax= "0";
729     }
730     if ($this->must_change_password){
731       $this->shadowLastChange= (int)(date("U") / 86400) - $this->shadowMax - 1;
732     } else {
733       $this->shadowLastChange= (int)(date("U") / 86400);
734     }
735     if (!$this->use_shadowWarning){
736       $this->shadowWarning= "0";
737     }
739     /* Check what to do with ID's */
740     if ($this->force_ids == 0){
742       /* Use id's that are already set */
743       if ($this->savedUidNumber != ""){
744         $this->uidNumber= $this->savedUidNumber;
745         $this->gidNumber= $this->savedGidNumber;
746       } else {
748         /* Calculate new id's. We need to place a lock before calling get_next_id
749            to get real unique values. */
750         $wait= 10;
751         while (get_lock("uidnumber") != ""){
752           sleep (1);
754           /* Oups - timed out */
755           if ($wait-- == 0){
756             print_red (_("Failed: overriding lock"));
757             break;
758           }
759         }
761         add_lock ("uidnumber", "gosa");
762         $this->uidNumber= $this->get_next_id("uidNumber");
763         if ($this->savedGidNumber != ""){
764           $this->gidNumber= $this->savedGidNumber;
765         } else {
766           $this->gidNumber= $this->get_next_id("gidNumber");
767         }
768       }
770       if ($this->primaryGroup != 0){
771         $this->gidNumber= $this->primaryGroup;
772       }
773     }
775     if ($this->use_shadowMin != "1" ) {
776       $this->shadowMin = "";
777     }
779     if (($this->use_shadowMax != "1") && ($this->must_change_password != "1")) {
780       $this->shadowMax = "";
781     }
783     if ($this->use_shadowWarning != "1" ) {
784       $this->shadowWarning = "";
785     }
787     if ($this->use_shadowInactive != "1" ) {
788       $this->shadowInactive = "";
789     }
791     if ($this->use_shadowExpire != "1" ) {
792       $this->shadowExpire = "";
793     }
795     /* Fill gecos */
796     if (isset($this->parent) && $this->parent != NULL){
797       $this->gecos= rewrite($this->parent->by_object['user']->cn);
798       if (!preg_match('/^[a-z0-9 -]+$/i', $this->gecos)){
799         $this->gecos= "";
800       }
801     }
803         foreach(array("shadowMin","shadowMax","shadowWarning","shadowInactive","shadowExpire") as $attr){
804                 $this->$attr = (int) $this->$attr;
805         }
806     /* Call parents save to prepare $this->attrs */
807     plugin::save();
809     /* Trust accounts */
810     $objectclasses= array();
811     foreach ($this->attrs['objectClass'] as $key => $class){
812       if (preg_match('/trustAccount/i', $class)){
813         continue;
814       }
815       $objectclasses[]= $this->attrs['objectClass'][$key];
816     }
817     $this->attrs['objectClass']= $objectclasses;
818     if ($this->trustModel != ""){
819       $this->attrs['objectClass'][]= "trustAccount";
820       $this->attrs['trustModel']= $this->trustModel;
821       $this->attrs['accessTo']= array();
822       if ($this->trustModel == "byhost"){
823         foreach ($this->accessTo as $host){
824           $this->attrs['accessTo'][]= $host;
825         }
826       }
827     } else {
828       if ($this->was_trust_account){
829         $this->attrs['accessTo']= array();
830         $this->attrs['trustModel']= array();
831       }
832     }
834     if(empty($this->attrs['gosaDefaultPrinter'])){
835       $thid->attrs['gosaDefaultPrinter']=array();
836     }
839     /* Save data to LDAP */
840     $ldap->cd($this->dn);
841     $this->cleanup();
842     unset($this->attrs['uid']);
843     $ldap->modify ($this->attrs); 
845     show_ldap_error($ldap->get_error(), _("Saving UNIX account failed"));
847     /* Remove lock needed for unique id generation */
848     del_lock ("uidnumber");
851     /* Posix accounts have group interrelationship, 
852         take care about these here if this is a new user without forced gidNumber. */
853     if ($this->force_ids == 0 && $this->primaryGroup == 0 && !$this->initially_was_account){
854       $ldap->cd($this->config->current['BASE']);
855       $ldap->search("(&(objectClass=posixGroup)(gidNumber=".$this->gidNumber."))", array("cn"));
857       /* Create group if it doesn't exist */
858       if ($ldap->count() == 0){
859         $groupdn= preg_replace ('/^'.$this->config->current['DNMODE'].'=[^,]+,'.get_people_ou().'/i', 'cn='.$this->uid.','.get_groups_ou(), $this->dn);
860         $g= new group($this->config, $groupdn);
861         $g->cn= $this->uid;
862         $g->force_gid= 1;
863         $g->gidNumber= $this->gidNumber;
864         $g->description= "Group of user ".$this->givenName." ".$this->sn;
865         $g->save ();
866       }
867     }
868  
869     /* Take care about groupMembership values: add to groups */
870     foreach ($this->groupMembership as $key => $value){
871       if (!isset($this->savedGroupMembership[$key])){
872         $g= new grouptabs($this->config,$this->config->data['TABS']['GROUPTABS'], $key, false);
873         $g->by_object['group']->addUser($this->uid);
874         $g->save();
875       }
876     }
877     
878     /* Remove from groups not listed in groupMembership */
879     foreach ($this->savedGroupMembership as $key => $value){
880       if (!isset($this->groupMembership[$key])){
881         $g= new grouptabs($this->config,$this->config->data['TABS']['GROUPTABS'], $key);
882         $g->by_object['group']->removeUser ($this->uid);
883         $g->save();
884       }
885     }
887     /* Optionally execute a command after we're done */
888     if ($this->initially_was_account == $this->is_account){
889       if ($this->is_modified){
890         $this->handle_post_events("modify",array("uid" => $this->uid));
891       }
892     } else {
893       $this->handle_post_events("add",array("uid" , $this->uid));
894     }
895   }
897   /* Check formular input */
898   function check()
899   {
900     /* Include global link_info */
901     $ldap= $this->config->get_ldap_link();
903     /* Call common method to give check the hook */
904     $message= plugin::check();
906     /* must: homeDirectory */
907     if ($this->homeDirectory == ""){
908       $message[]= _("The required field 'Home directory' is not set.");
909     }
910     if (!is_path($this->homeDirectory)){
911       $message[]= _("Please enter a valid path in 'Home directory' field.");
912     }
914     /* Check ID's if they are forced by user */
915     if ($this->force_ids == "1"){
917       /* Valid uid/gid? */
918       if (!is_id($this->uidNumber)){
919         $message[]= _("Value specified as 'UID' is not valid.");
920       } else {
921         if ($this->uidNumber < $this->config->current['MINID']){
922           $message[]= _("Value specified as 'UID' is too small.");
923         }
924       }
925       if (!is_id($this->gidNumber)){
926         $message[]= _("Value specified as 'GID' is not valid.");
927       } else {
928         if ($this->gidNumber < $this->config->current['MINID']){
929           $message[]= _("Value specified as 'GID' is too small.");
930         }
931       }
932     }
934     /* Check shadow settings, well I like spaghetties... */
935     if ($this->use_shadowMin){
936       if (!is_id($this->shadowMin)){
937         $message[]= _("Value specified as 'shadowMin' is not valid.");
938       }
939     }
940     if ($this->use_shadowMax){
941       if (!is_id($this->shadowMax)){
942         $message[]= _("Value specified as 'shadowMax' is not valid.");
943       }
944     }
945     if ($this->use_shadowWarning){
946       if (!is_id($this->shadowWarning)){
947         $message[]= _("Value specified as 'shadowWarning' is not valid.");
948       }
949       if (!$this->use_shadowMax){
950         $message[]= _("'shadowWarning' without 'shadowMax' makes no sense.");
951       }
952       if ($this->shadowWarning > $this->shadowMax){
953         $message[]= _("Value specified as 'shadowWarning' should be smaller than 'shadowMax'.");
954       }
955       if ($this->use_shadowMin && $this->shadowWarning < $this->shadowMin){
956         $message[]= _("Value specified as 'shadowWarning' should be greater than 'shadowMin'.");
957       }
958     }
959     if ($this->use_shadowInactive){
960       if (!is_id($this->shadowInactive)){
961         $message[]= _("Value specified as 'shadowInactive' is not valid.");
962       }
963       if (!$this->use_shadowMax){
964         $message[]= _("'shadowInactive' without 'shadowMax' makes no sense.");
965       }
966     }
967     if ($this->use_shadowMin && $this->use_shadowMax){
968       if ($this->shadowMin > $this->shadowMax){
969         $message[]= _("Value specified as 'shadowMin' should be smaller than 'shadowMax'.");
970       }
971     }
973   //  if(empty($this->gosaDefaultPrinter)){
974   //    $message[]= _("You need to specify a valid default printer.");
975   //  }
977     return ($message);
978   }
980   function addGroup ($groups)
981   {
982     /* include global link_info */
983     $ldap= $this->config->get_ldap_link();
985     /* Walk through groups and add the descriptive entry if not exists */
986     foreach ($groups as $value){
987       if (!array_key_exists($value, $this->groupMembership)){
988         $ldap->cat($value, array('cn', 'description', 'dn'));
989         $attrs= $ldap->fetch();
990         error_reporting (0);
991         if (!isset($attrs['description'][0])){
992           $entry= $attrs["cn"][0];
993         } else {
994           $dsc= preg_replace ('/^Group of user/', _("Group of user"), $attrs["description"][0]);
995           $entry= $attrs["cn"][0]." [$dsc]";
996         }
997         error_reporting (E_ALL);
998         $this->groupMembership[$attrs['dn']]= $entry;
999       }
1000     }
1002     /* Sort groups */
1003     asort ($this->groupMembership);
1004     reset ($this->groupMembership);
1005   }
1008   /* Del posix user from some groups */
1009   function delGroup ($groups)
1010   {
1011     $dest= array();
1013     foreach ($this->groupMembership as $key => $value){
1014       if (!in_array($key, $groups)){
1015         $dest[$key]= $value;
1016       }
1017     }
1018     $this->groupMembership= $dest;
1019   }
1021   /* Adapt from template, using 'dn' */
1022   function adapt_from_template($dn)
1023   {
1024     /* Include global link_info */
1025     $ldap= $this->config->get_ldap_link();
1027     plugin::adapt_from_template($dn);
1028     $template= $this->attrs['uid'][0];
1030     /* Adapt group membership */
1031     $ldap->cd($this->config->current['BASE']);
1032     $ldap->search("(&(objectClass=posixGroup)(memberUid=".$this->attrs["uid"][0]."))", array("description", "cn"));
1034     while ($this->attrs= $ldap->fetch()){
1035       if (!isset($this->attrs["description"][0])){
1036         $entry= $this->attrs["cn"][0];
1037       } else {
1038         $entry= $this->attrs["cn"][0]." [".$this->attrs["description"][0]."]";
1039       }
1040       $this->groupMembership[$ldap->getDN()]= $entry;
1041     }
1043     /* Fix primary group settings */
1044     $ldap->cd($this->config->current['BASE']);
1045     $ldap->search("(&(objectClass=posixGroup)(cn=$template)(gidNumber=".$this->gidNumber."))", array("cn"));
1046     if ($ldap->count() != 1){
1047       $this->primaryGroup= $this->gidNumber;
1048     }
1050     $ldap->cd($this->config->current['BASE']);
1051     $ldap->search("(&(objectClass=gosaUserTemplate)(uid=".$template.")(accessTo=*))", array("cn","accessTo"));
1053     while($attr = $ldap->fetch()){
1054       $tmp = $attr['accessTo'];
1055       unset ($tmp['count']);
1056       $this->accessTo = $tmp;   
1057     }
1059     /* Adjust shadow checkboxes */
1060     foreach (array("shadowMin", "shadowMax", "shadowWarning", "shadowInactive") as $val){
1061       if ($this->$val != 0){
1062         $oval= "use_".$val;
1063         $this->$oval= "1";
1064       }
1065     }
1067     /* 
1068      * If shadowExpire is not enabled in the template, it's a UNIX timestamp - so don't convert it to seconds.
1069      * The check is a hack - if difference between timestamp generated above and here is max 1 day.
1070      */
1071     if(abs($this->shadowExpire - time())>86400) {
1072       $this->shadowExpire= $this->convertToSeconds($this->shadowExpire);
1073     }
1074     
1075     /* Only enable checkbox, if shadowExpire is in the future */
1076     if($this->shadowExpire > time()) {
1077       $this->use_shadowExpire= "1";
1078     }
1079   }
1081   function get_next_id($attrib)
1082   {
1083     $ids= array();
1084     $ldap= $this->config->get_ldap_link();
1086     $ldap->cd ($this->config->current['BASE']);
1087     if (preg_match('/gidNumber/i', $attrib)){
1088       $oc= "posixGroup";
1089     } else {
1090       $oc= "posixAccount";
1091     }
1092     $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
1094     /* Get list of ids */
1095     while ($attrs= $ldap->fetch()){
1096       $ids[]= (int)$attrs["$attrib"][0];
1097     }
1099     /* Add the nobody id */
1100     $ids[]=  65534;
1102     /* Find out next free id near to UID_BASE */
1103     for ($id= $this->config->current['UIDBASE']; $id++; $id < pow(2,32)){
1104       if (!in_array($id, $ids)){
1105         return ($id);
1106       }
1107     }
1109     /* Check if current id reaches the maximum of 32 bit */
1110     if ($id >= pow(2,32)){
1111       echo _("Too many users, can't allocate a free ID!");
1112       exit;
1113     }
1114   }
1116  function reload()
1117   {
1119     /* Set base for all searches */
1120     $base     = $_SESSION['CurrentMainBase'];
1121     $base     = $base;
1122     $ldap     = $this->config->get_ldap_link();    
1123     $attrs    =  array("cn", "description", "gidNumber");
1124     $Flags    = GL_SIZELIMIT;
1126     /* Get groups */
1127     if ($this->GroupUserRegex == '*'){
1128       $filter = "(&(objectClass=posixGroup)(cn=".$this->GroupRegex."))";
1129     } else {
1130       $filter= "(&(objectClass=posixGroup)(cn=".$this->GroupRegex.")(memberUid=".$this->GroupUserRegex."))";
1131     }
1132     if($this->SubSearch){
1133       $Flags |= GL_SUBSEARCH;
1134     }else{
1135       $base = get_groups_ou().$base;
1136     }
1139     $res= get_list($filter, $this->ui->subtreeACL, $base,$attrs, $Flags);
1141     /* check sizelimit */
1142     if (preg_match("/size limit/i", $ldap->error)){
1143       $_SESSION['limit_exceeded']= TRUE;
1144     }
1146     /* Create a list of users */
1147     $this->grouplist = array();
1148     foreach ($res as $value){
1149         $this->grouplist[$value['gidNumber'][0]]= $value;
1150     }
1152     $tmp=array();
1153     foreach($this->grouplist as $tkey => $val ){
1154       $tmp[strtolower($val['cn'][0]).$val['cn'][0]]=$val;
1155     }
1157     /* Sort index */
1158     ksort($tmp);
1160     /* Recreate index array[dn]=cn[description]*/
1161     $this->grouplist=array();
1162     foreach($tmp as $val){
1163       if(isset($val['description'])){
1164         $this->grouplist[$val['dn']]=$val['cn'][0]."&nbsp;[".$val['description'][0]."]";
1165       }else{
1166         $this->grouplist[$val['dn']]=$val['cn'][0];
1167       }
1168     }
1169     reset ($this->grouplist);
1170   }
1172  
1173   /* Get posts from copy & paste dialog */ 
1174   function saveCopyDialog()
1175   {
1176     if(isset($_POST['homeDirectory'])){
1177       $this->homeDirectory = $_POST['homeDirectory'];
1178       if (isset ($_POST['force_ids'])){
1179         $data= 1;
1180         $this->gidNumber = $_POST['gidNumber'];
1181         $this->uidNumber = $_POST['uidNumber'];
1182       } else {
1183         $data= 0;
1184       }
1185       if ($this->force_ids != $data){
1186         $this->is_modified= TRUE;
1187       }
1188       $this->force_ids= $data;
1189     }
1190   }
1193   /* Create the posix dialog part for copy & paste */
1194   function getCopyDialog()
1195   {
1196     /* Skip dialog creation if this is not a valid account */
1197     if(!$this->is_account) return("");
1198     if ($this->force_ids == 1){
1199       $force_ids = "checked";
1200       if ($_SESSION['js']){
1201         $forceMode = "";
1202       }
1203     } else {
1204       if ($_SESSION['js']){
1205         if($this->acl != "#none#")
1206           $forceMode ="disabled";
1207       }
1208       $force_ids = "";
1209     }
1210    
1211     $sta = "";
1212  
1213     /* Open group add dialog */
1214     if(isset($_POST['edit_groupmembership'])){
1215       $this->group_dialog = TRUE;
1216       $sta = "SubDialog";
1217     }
1219     /* If the group-add dialog is closed, call execute 
1220         to ensure that the membership is updatd */
1221     if(isset($_POST['add_groups_finish']) || isset($_POST['add_groups_cancel'])){
1222       $this->execute();
1223       $this->group_dialog =FALSE;
1224     }
1226     if($this->group_dialog){
1227       $str = $this->execute(true);
1228       $ret = array();
1229       $ret['string'] = $str;
1230       $ret['status'] = $sta;
1231       return($ret);
1232     }
1234     /* If a group member should be deleted, simply call execute */
1235     if(isset($_POST['delete_groupmembership'])){
1236       $this->execute();
1237     }
1239     /* Assigned informations to smarty */
1240     $smarty = get_smarty();
1241     $smarty->assign("homeDirectory",$this->homeDirectory);
1242     $smarty->assign("uidNumber",$this->uidNumber);
1243     $smarty->assign("gidNumber",$this->gidNumber);
1244     $smarty->assign("forceMode",$forceMode);
1245     $smarty->assign("force_ids",$force_ids);
1246     if (!count($this->groupMembership)){
1247       $smarty->assign("groupMembership", array("&nbsp;"));
1248     } else {
1249       $smarty->assign("groupMembership", $this->groupMembership);
1250     }
1252     /* Display wars message if there are more than 16 group members */
1253     if (count($this->groupMembership) > 16){
1254       $smarty->assign("groups", "too_many_for_nfs");
1255     } else {
1256       $smarty->assign("groups", "");
1257     }
1258     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1260     $ret = array();
1261     $ret['string'] = $str;
1262     $ret['status'] = $sta;
1263     return($ret);
1264   }
1266   function PrepareForCopyPaste($source)
1267   {
1268     plugin::PrepareForCopyPaste($source);
1269     
1270     /* Avoid using the same gid/uid number as source user */
1271     $this->savedUidNumber = $this->get_next_id("gidNumber");
1272     $this->savedGidNumber = $this->get_next_id("uidNumber");
1273   }
1275   function convertToSeconds($val)
1276   {
1277     if ($val != 0){
1278       $val*= 60 * 60 * 24;
1279     } else {
1280       $date= getdate();
1281       $val= floor($date[0] / (60*60*24)) * 60 * 60 * 24;
1282     }
1283     return($val);
1284   }
1288 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1289 ?>