Code

31cbc42de5ff35bb9eb72e548a603d96dfcb3222
[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 $mustchangepassword= "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   var $view_logged = FALSE;
70   /* attribute list for save action */
71   var $CopyPasteVars  = 
72       array("grouplist","groupMembership","use_shadowMin",
73       "use_shadowMax","use_shadowWarning","use_shadowInactive","use_shadowExpire",
74       "must_change_password","printerList","grouplist","savedGidNumber","savedUidNumber");
76   var $attributes     = array("homeDirectory", "loginShell", "uidNumber", "gidNumber", "gecos",
77       "shadowMin", "shadowMax", "shadowWarning", "shadowInactive", "shadowLastChange",
78       "shadowExpire", "gosaDefaultPrinter", "gosaDefaultLanguage", "uid","accessTo","trustModel");
80   var $objectclasses= array("posixAccount", "shadowAccount");
82   var $uid= "";
84   /* constructor, if 'dn' is set, the node loads the given
85      'dn' from LDAP */
86   function posixAccount ($config, $dn= NULL)
87   {
88     /* Configuration is fine, allways */
89     $this->config= $config;
91     /* Load bases attributes */
92     plugin::plugin($config, $dn);
94     /* Setting uid to default */
95     if(isset($this->attrs['uid'][0])){
96       $this->uid = $this->attrs['uid'][0];
97     }
99     $ldap= $this->config->get_ldap_link();
101     if ($dn != NULL){
103       /* Correct is_account. shadowAccount is not required. */
104       if (isset($this->attrs['objectClass']) &&
105           in_array ('posixAccount', $this->attrs['objectClass'])){
107         $this->is_account= TRUE;
108       }
110       /* Is this account a trustAccount? */
111       if ($this->is_account && isset($this->attrs['trustModel'])){
112         $this->trustModel= $this->attrs['trustModel'][0];
113         $this->was_trust_account= TRUE;
114       } else {
115         $this->was_trust_account= FALSE;
116         $this->trustModel= "";
117       }
119       $this->accessTo = array(); 
120       if ($this->is_account && isset($this->attrs['accessTo'])){
121         for ($i= 0; $i<$this->attrs['accessTo']['count']; $i++){
122           $tmp= $this->attrs['accessTo'][$i];
123           $this->accessTo[$tmp]= $tmp;
124         }
125       }
126       $this->initially_was_account= $this->is_account;
128       /* Fill group */
129       $this->primaryGroup= $this->gidNumber;
131       /* Generate status text */
132       $current= date("U");
134       $current= floor($current / 60 /60 / 24);
136       if (($current >= $this->shadowExpire) && $this->shadowExpire){
137         $this->status= _("expired");
138         if (($current - $this->shadowExpire) < $this->shadowInactive){
139           $this->status.= ", "._("grace time active");
140         }
141       } elseif (($this->shadowLastChange + $this->shadowMin) >= $current){
142         $this->status= _("active, password not changable");
143       } elseif (($this->shadowLastChange + $this->shadowMax) >= $current){
144         $this->status= _("active, password expired");
145       } else {
146         $this->status= _("active");
147       }
149       /* Get group membership */
150       $ldap->cd($this->config->current['BASE']);
151       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("cn", "description"));
153       while ($this->attrs= $ldap->fetch()){
154         if (!isset($this->attrs["description"][0])){
155           $entry= $this->attrs["cn"][0];
156         } else {
157           $dsc= preg_replace ('/^Group of user/', _("Group of user"), $this->attrs["description"][0]);
158           $entry= $this->attrs["cn"][0]." [$dsc]";
159         }
160         $this->groupMembership[$ldap->getDN()]= $entry;
161       }
162       asort($this->groupMembership);
163       reset($this->groupMembership);
164       $this->savedGroupMembership= $this->groupMembership;
165       $this->savedUidNumber= $this->uidNumber;
166       $this->savedGidNumber= $this->gidNumber;
167     }
169     /* Adjust shadow checkboxes */
170     foreach (array("shadowMin", "shadowMax", "shadowWarning", "shadowInactive",
171           "shadowExpire") as $val){
173       if ($this->$val != 0){
174         $oval= "use_".$val;
175         $this->$oval= "1";
176       }
177     }
179     /* Convert to seconds */
180     $this->shadowExpire= $this->convertToSeconds($this->shadowExpire);
182     /* Generate shell list from CONFIG_DIR./shells */
183     if (file_exists(CONFIG_DIR.'/shells')){
184       $shells = file (CONFIG_DIR.'/shells');
185       foreach ($shells as $line){
186         if (!preg_match ("/^#/", $line)){
187           $this->loginShellList[]= trim($line);
188         }
189       }
190     } else {
191       if ($this->loginShell == ""){
192         $this->loginShellList[]= _("unconfigured");
193       }
194     }
196     /* Insert possibly missing loginShell */
197     if ($this->loginShell != "" && !in_array($this->loginShell, $this->loginShellList)){
198       $this->loginShellList[]= $this->loginShell;
199     }
201     /* Generate group list */
202     $this->ui = get_userinfo(); 
203     $this->secondaryGroups[]= "- "._("automatic")." -";
204     $ldap->cd($this->config->current['BASE']);
205     $ldap->search("(objectClass=posixGroup)", array("cn", "gidNumber"));
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     /* Log view */
231     if($this->is_account && !$this->view_logged){
232       $this->view_logged = TRUE;
233       @log::log("view","users/".get_class($this),$this->dn);
234     }
236     /* Department has changed? */
237     if(isset($_POST['depselect'])){
238       $_SESSION['CurrentMainBase']= validate($_POST['depselect']);
239     }
241     if(!$isCopyPaste){
243       /* Do we need to flip is_account state? */
244       if(isset($_POST['modify_state'])){
245         if($this->is_account && $this->acl_is_removeable()){
246           $this->is_account= FALSE;
247         }elseif(!$this->is_account && $this->acl_is_createable()){
248           $this->is_account= TRUE;
249         }
250       }
252       /* Do we represent a valid posixAccount? */
253       if (!$this->is_account && $this->parent == NULL ){
254         $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
255           _("This account has no unix extensions.")."</b>";
256         $display.= back_to_main();
257         return ($display);
258       }
261       /* Show tab dialog headers */
262       if ($this->parent != NULL){
263         if ($this->is_account){
264           if (isset($this->parent->by_object['sambaAccount'])){
265             $obj= $this->parent->by_object['sambaAccount'];
266           }
267           if (isset($obj) && $obj->is_account == TRUE &&
268               ((isset($this->parent->by_object['sambaAccount']))&&($this->parent->by_object['sambaAccount']->is_account))
269               ||(isset($this->parent->by_object['environment'] ))&&($this->parent->by_object['environment'] ->is_account)){
271             /* Samba3 dependency on posix accounts are enabled
272                in the moment, because I need to rely on unique
273                uidNumbers. There'll be a better solution later
274                on. */
275             $display= $this->show_disable_header(_("Remove posix account"),
276                 _("This account has unix features enabled. To disable them, you'll need to remove the samba / environment account first."), TRUE);
277           } else {
278             $display= $this->show_disable_header(_("Remove posix account"),
279                 _("This account has posix features enabled. You can disable them by clicking below."));
280           }
281         } else {
282           $display= $this->show_enable_header(_("Create posix account"),
283               _("This account has posix features disabled. You can enable them by clicking below."));
284           return($display);
285         }
286       }
287     }
288     /* Trigger group edit? */
289     if (isset($_POST['edit_groupmembership'])){
290       $this->group_dialog= TRUE;
291       $this->dialog= TRUE;
292     }
294     /* Cancel group edit? */
295     if (isset($_POST['add_groups_cancel']) ||
296         isset($_POST['add_groups_finish'])){
297       $this->group_dialog= FALSE;
298       $this->dialog= FALSE;
299     }
301     /* Add selected groups */
302     if (isset($_POST['add_groups_finish']) && isset($_POST['groups']) &&
303         count($_POST['groups'])){
305       $this->addGroup ($_POST['groups']);
306     }
308     /* Delete selected groups */
309     if (isset($_POST['delete_groupmembership']) && 
310         isset($_POST['group_list']) && count($_POST['group_list'])){
312       $this->delGroup ($_POST['group_list']);
313     }
315     /* Add user workstation? */
316     if (isset($_POST["add_ws"])){
317       $this->show_ws_dialog= TRUE;
318       $this->dialog= TRUE;
319     }
321     /* Add user workstation? */
322     if (isset($_POST["add_ws_finish"]) && isset($_POST['wslist'])){
323       foreach($_POST['wslist'] as $ws){
324         $this->accessTo[$ws]= $ws;
325       }
326       ksort($this->accessTo);
327       $this->is_modified= TRUE;
328     }
330     /* Remove user workstations? */
331     if (isset($_POST["delete_ws"]) && isset($_POST['workstation_list'])){
332       foreach($_POST['workstation_list'] as $name){
333         unset ($this->accessTo[$name]);
334       }
335       $this->is_modified= TRUE;
336     }
338     /* Add user workstation finished? */
339     if (isset($_POST["add_ws_finish"]) || isset($_POST["add_ws_cancel"])){
340       $this->show_ws_dialog= FALSE;
341       $this->dialog= FALSE;
342     }
344     /* Templates now! */
345     $smarty= get_smarty();
347     /* Show ws dialog */
348     if ($this->show_ws_dialog){
349       /* Save data */
350       $sysfilter= get_global("sysfilter");
351       foreach( array("depselect", "regex") as $type){
352         if (isset($_POST[$type])){
353           $sysfilter[$type]= $_POST[$type];
354         }
355       }
356       if (isset($_GET['search'])){
357         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
358         if ($s == "**"){
359           $s= "*";
360         }
361         $sysfilter['regex']= $s;
362       }
363       register_global("sysfilter", $sysfilter);
365       /* Get workstation list */
366       $exclude= "";
367       foreach($this->accessTo as $ws){
368         $exclude.= "(cn=$ws)";
369       }
370       if ($exclude != ""){
371         $exclude= "(!(|$exclude))";
372       }
373       $regex= $sysfilter['regex'];
374       $filter= "(&(|(objectClass=goServer)(objectClass=gotoWorkstation)(objectClass=gotoTerminal))$exclude(cn=*)(cn=$regex))";
375       $res= get_list($filter, "groups", $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]) && obj_is_writable($key,"groups/group","memberUid")){
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     /* In 'MyAccount' mode, we must remove write acls if we are not in editing mode. */ 
436     $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
438     /* Depending on pwmode, currently hardcoded because there are no other methods */
439     if ( 1 == 1 ){
440       $smarty->assign("pwmode", dirname(__FILE__)."/posix_shadow");
442       $shadowMinACL     =  $this->getacl("shadowMin",$SkipWrite);
443       $smarty->assign("shadowmins", sprintf(_("Password can't be changed up to %s days after last change"), 
444                                               "<input name=\"shadowMin\" size=3 maxlength=4 value=\"".$this->shadowMin."\">"));
446       $shadowMaxACL     =  $this->getacl("shadowMax",$SkipWrite);
447       $smarty->assign("shadowmaxs", sprintf(_("Password must be changed after %s days"), 
448                                               "<input name=\"shadowMax\" size=3 maxlength=4 value=\"".$this->shadowMax."\">"));
450       $shadowInactiveACL=  $this->getacl("shadowInactive",$SkipWrite);
451       $smarty->assign("shadowinactives", sprintf(_("Disable account after %s days of inactivity after password expiery"), 
452                                               "<input name=\"shadowInactive\" size=3 maxlength=4 value=\"".$this->shadowInactive."\">"));
454       $shadowWarningACL =  $this->getacl("shadowWarning",$SkipWrite);
455       $smarty->assign("shadowwarnings", sprintf(_("Warn user %s days before password expiery"), 
456                                               "<input name=\"shadowWarning\" size=3 maxlength=4 value=\"".$this->shadowWarning."\">"));
458       foreach( array("use_shadowMin", "use_shadowMax",
459                      "use_shadowExpire", "use_shadowInactive","use_shadowWarning") as $val){
460         if ($this->$val == 1){
461           $smarty->assign("$val", "checked");
462         } else {
463           $smarty->assign("$val", "");
464         }
465         $smarty->assign("$val"."ACL", $this->getacl($val,$SkipWrite));
466       }
468       if($this->mustchangepassword){
469         $smarty->assign("mustchangepassword", "checked");
470       } else {
471         $smarty->assign("mustchangepassword", "");
472       }
473       $smarty->assign("mustchangepasswordACL", $this->getacl("mustchangepassword",$SkipWrite));
474     }
476     /* Fill calendar */
477     /* If this $this->shadowExpire is empty 
478         use current date as base for calculating selectbox values.
479        (This attribute is empty if this is a new user )*/ 
480     if(empty($this->shadowExpire)){
481       $date= getdate(time());
482     }else{
483       $date= getdate($this->shadowExpire);
484     }
485  
486     $days= array();
487     for($d= 1; $d<32; $d++){
488       $days[$d]= $d;
489     }
490     $years= array();
491     for($y= $date['year']-10; $y<$date['year']+10; $y++){
492       $years[]= $y;
493     }
494     $months= array(_("January"), _("February"), _("March"), _("April"),
495         _("May"), _("June"), _("July"), _("August"), _("September"),
496         _("October"), _("November"), _("December"));
497     $smarty->assign("day", $date["mday"]);
498     $smarty->assign("days", $days);
499     $smarty->assign("months", $months);
500     $smarty->assign("month", $date["mon"]-1);
501     $smarty->assign("years", $years);
502     $smarty->assign("year", $date["year"]);
504     /* Fill arrays */
505     $smarty->assign("shells", $this->loginShellList);
506     $smarty->assign("secondaryGroups", $this->secondaryGroups);
507     $smarty->assign("primaryGroup", $this->primaryGroup);
508     if (!count($this->groupMembership)){
509       $smarty->assign("groupMembership", array("&nbsp;"));
510     } else {
511       $smarty->assign("groupMembership", $this->groupMembership);
512     }
513     if (count($this->groupMembership) > 16){
514       $smarty->assign("groups", "too_many_for_nfs");
515     } else {
516       $smarty->assign("groups", "");
517     }
518     $smarty->assign("languages", $this->config->data['MAIN']['LANGUAGES']);
520     /* Avoid "Undefined index: forceMode" */
521     $smarty->assign("forceMode", "");
523     /* Checkboxes */
524     if ($this->force_ids == 1){
525       $smarty->assign("force_ids", "checked");
526       if ($_SESSION['js']){
527         $smarty->assign("forceMode", "");
528       }
529     } else {
530       if ($_SESSION['js']){
531         $smarty->assign("forceMode", "disabled");
532       }
533       $smarty->assign("force_ids", "");
534     }
536     
538     $smarty->assign("force_idsACL", $this->getacl("uidNumber",$SkipWrite).$this->getacl("gidNumber",$SkipWrite));
540     /* Load attributes and acl's */
541     foreach($this->attributes as $val){
542       if(($_SESSION["js"])&&(($val=="uidNumber")||($val=="gidNumber")))
543       {
544         $smarty->assign("$val"."ACL",$this->getacl($val,$SkipWrite));
545         $smarty->assign("$val", $this->$val);
546         continue;
547       }
548       $smarty->assign("$val", $this->$val);
549       $smarty->assign("$val"."ACL", $this->getacl($val,$SkipWrite));
550     }
551     if($SkipWrite){
552       $smarty->assign("groupMembershipACL","r");
553     }else{
554       $smarty->assign("groupMembershipACL","rw");
555     }
556     $smarty->assign("status", $this->status);
558     /* Work on trust modes */
559     $smarty->assign("trusthide", " disabled ");
560     $smarty->assign("trustmodeACL",  $this->getacl("trustModel",$SkipWrite));
561     if ($this->trustModel == "fullaccess"){
562       $trustmode= 1;
563       // pervent double disable tag in html code, this will disturb our clean w3c html
564       $smarty->assign("trustmode",  $this->getacl("trustModel",$SkipWrite));
566     } elseif ($this->trustModel == "byhost"){
567       $trustmode= 2;
568       $smarty->assign("trusthide", "");
569     } else {
570       // pervent double disable tag in html code, this will disturb our clean w3c html
571       $smarty->assign("trustmode",  $this->getacl("trustModel",$SkipWrite));
572       $trustmode= 0;
573     }
574     $smarty->assign("trustmode", $trustmode);
575     $smarty->assign("trustmodes", array( 0 => _("disabled"), 1 => _("full access"),
576           2 => _("allow access to these hosts")));
580     if((count($this->accessTo))==0)
581       $smarty->assign("emptyArrAccess",true);
582     else
583       $smarty->assign("emptyArrAccess",false);
587     $smarty->assign("workstations", $this->accessTo);
589     $smarty->assign("apply", apply_filter());
590     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
591     return($display);
592   }
595   /* remove object from parent */
596   function remove_from_parent()
597   {
598     /* Cancel if there's nothing to do here */
599     if ((!$this->initially_was_account) || (!$this->acl_is_removeable())){
600       return;
601     }
603     /* include global link_info */
604     $ldap= $this->config->get_ldap_link();
606     /* Remove and write to LDAP */
607     plugin::remove_from_parent();
609     /* Zero out array */
610     $this->attrs['gosaHostACL']= array();
612     /* Keep uid, because we need it for authentification! */
613     unset($this->attrs['uid']);
614     unset($this->attrs['trustModel']);
616     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
617         $this->attributes, "Save");
618     $ldap->cd($this->dn);
619     $this->cleanup();
620     $ldap->modify ($this->attrs); 
622     @log::log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
624     show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/posix account with dn '%s' failed."),$this->dn));
626     /* Delete group only if cn is uid and there are no other
627        members inside */
628     $ldap->cd ($this->config->current['BASE']);
629     $ldap->search ("(&(objectClass=posixGroup)(gidNumber=".$this->gidNumber."))", array("cn", "memberUid"));
630     if ($ldap->count() != 0){
631       $attrs= $ldap->fetch();
632       if ($attrs['cn'][0] == $this->uid &&
633           !isset($this->attrs['memberUid'])){
635         $ldap->rmDir($ldap->getDN());
636       }
637     }
639     /* Optionally execute a command after we're done */
640     $this->handle_post_events("remove",array("uid" => $this->uid));
641   }
644   function save_object()
645   {
646     if (isset($_POST['posixTab'])){
647       /* Save values to object */
648       plugin::save_object();
651       /* Save force GID checkbox */
652       if($this->acl_is_writeable("gidNumber") || $this->acl_is_writeable("uidNumber")){
653         if (isset ($_POST['force_ids'])){
654           $data= 1;
655         } else {
656           $data= 0;
657         }
658         if ($this->force_ids != $data){
659           $this->is_modified= TRUE;
660         }
661         $this->force_ids= $data;
662       }
664       /*Save primary group settings */
665       if($this->acl_is_writeable("primaryGroup") && isset($_POST['primaryGroup'])){
666         $data= $_POST['primaryGroup'];
667         if ($this->primaryGroup != $data){
668           $this->is_modified= TRUE;
669         }
670         $this->primaryGroup= $_POST['primaryGroup'];
671       }
673       foreach(array("shadowMin","shadowMax","shadowExpire","shadowInactive","shadowWarning","mustchangepassword") as $var) {
674         if($this->acl_is_writeable($var)){
675           $use_var = "use_".$var;
676           if(isset($_POST['use_'.$var])){
677             $this->$use_var  = true;
678             $this->$var      = $_POST[$var];
679           }else{
680             $this->$use_var  = false;
681             $this->$var      = 0;
682           }
683         }
684       }
686       /* Trust mode - special handling */
687       if($this->acl_is_writeable("trustModel")){
688         if (isset($_POST['trustmode'])){
689           $saved= $this->trustModel;
690           if ($_POST['trustmode'] == "1"){
691             $this->trustModel= "fullaccess";
692           } elseif ($_POST['trustmode'] == "2"){
693             $this->trustModel= "byhost";
694           } else {
695             $this->trustModel= "";
696           }
697           if ($this->trustModel != $saved){
698             $this->is_modified= TRUE;
699           }
700         }
701       }
702     }
704     /* Get regex from alphabet */
705     if(isset($_GET['search'])){
706       $this->GroupRegex = $_GET['search']."*";
707     }
709     /* Check checkboxes and regexes */
710     if(isset($_POST["PosixGroupDialogPosted"])){
712       if(isset($_POST['SubSearch']) && ($_POST['SubSearch'])){
713         $this->SubSearch = true;
714       }else{
715         $this->SubSearch = false;
716       }
717       if(isset($_POST['guser'])){
718         $this->GroupUserRegex = $_POST['guser'];
719       }
720       if(isset($_POST['regex'])){
721         $this->GroupRegex = $_POST['regex'];
722       }
723     }
724     $this->GroupRegex = preg_replace("/\*\**/","*",$this->GroupRegex);
725     $this->GroupUserRegex = preg_replace("/\*\**/","*",$this->GroupUserRegex);
726   }
729   /* Save data to LDAP, depending on is_account we save or delete */
730   function save()
731   {
733     /* include global link_info */
734     $ldap= $this->config->get_ldap_link();
736     /* Adapt shadow values */
737     if (!$this->use_shadowExpire){
738       $this->shadowExpire= "0";
739     } else {
740       /* Transform seconds to days here */
741       $this->shadowExpire= (int)($this->shadowExpire / (60 * 60 * 24)) ;
742     }
743     if (!$this->use_shadowMax){
744       $this->shadowMax= "0";
745     }
746     if ($this->mustchangepassword){
747       $this->shadowLastChange= (int)(date("U") / 86400) - $this->shadowMax - 1;
748     } else {
749       $this->shadowLastChange= (int)(date("U") / 86400);
750     }
751     if (!$this->use_shadowWarning){
752       $this->shadowWarning= "0";
753     }
755     /* Check what to do with ID's */
756     if ($this->force_ids == 0){
758       /* Use id's that are already set */
759       if ($this->savedUidNumber != ""){
760         $this->uidNumber= $this->savedUidNumber;
761         $this->gidNumber= $this->savedGidNumber;
762       } else {
764         /* Calculate new id's. We need to place a lock before calling get_next_id
765            to get real unique values. */
766         $wait= 10;
767         while (get_lock("uidnumber") != ""){
768           sleep (1);
770           /* Oups - timed out */
771           if ($wait-- == 0){
772             print_red (_("Failed: overriding lock"));
773             break;
774           }
775         }
777         add_lock ("uidnumber", "gosa");
778         $this->uidNumber= $this->get_next_id("uidNumber", $this->dn);
779         if ($this->savedGidNumber != ""){
780           $this->gidNumber= $this->savedGidNumber;
781         } else {
782           $this->gidNumber= $this->get_next_id("gidNumber", $this->dn);
783         }
784       }
786       if ($this->primaryGroup != 0){
787         $this->gidNumber= $this->primaryGroup;
788       }
789     }
791     if ($this->use_shadowMin != "1" ) {
792       $this->shadowMin = "";
793     }
795     if (($this->use_shadowMax != "1") && ($this->mustchangepassword != "1")) {
796       $this->shadowMax = "";
797     }
799     if ($this->use_shadowWarning != "1" ) {
800       $this->shadowWarning = "";
801     }
803     if ($this->use_shadowInactive != "1" ) {
804       $this->shadowInactive = "";
805     }
807     if ($this->use_shadowExpire != "1" ) {
808       $this->shadowExpire = "";
809     }
811     /* Fill gecos */
812     if (isset($this->parent) && $this->parent != NULL){
813       $this->gecos= rewrite($this->parent->by_object['user']->cn);
814       if (!preg_match('/^[a-z0-9 -]+$/i', $this->gecos)){
815         $this->gecos= "";
816       }
817     }
819     foreach(array("shadowMin","shadowMax","shadowWarning","shadowInactive","shadowExpire") as $attr){
820       $this->$attr = (int) $this->$attr;
821     }
822     /* Call parents save to prepare $this->attrs */
823     plugin::save();
825     /* Trust accounts */
826     $objectclasses= array();
827     foreach ($this->attrs['objectClass'] as $key => $class){
828       if (preg_match('/trustAccount/i', $class)){
829         continue;
830       }
831       $objectclasses[]= $this->attrs['objectClass'][$key];
832     }
833     $this->attrs['objectClass']= $objectclasses;
834     if ($this->trustModel != ""){
835       $this->attrs['objectClass'][]= "trustAccount";
836       $this->attrs['trustModel']= $this->trustModel;
837       $this->attrs['accessTo']= array();
838       if ($this->trustModel == "byhost"){
839         foreach ($this->accessTo as $host){
840           $this->attrs['accessTo'][]= $host;
841         }
842       }
843     } else {
844       if ($this->was_trust_account){
845         $this->attrs['accessTo']= array();
846         $this->attrs['trustModel']= array();
847       }
848     }
850     if(empty($this->attrs['gosaDefaultPrinter'])){
851       $thid->attrs['gosaDefaultPrinter']=array();
852     }
855     /* Save data to LDAP */
856     $ldap->cd($this->dn);
857     $this->cleanup();
858     unset($this->attrs['uid']);
859     $ldap->modify ($this->attrs); 
861     /* Log last action */ 
862     if($this->initially_was_account){
863       @log::log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
864     }else{
865       @log::log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
866     }
868     show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/posix account with dn '%s' failed."),$this->dn));
870     /* Remove lock needed for unique id generation */
871     del_lock ("uidnumber");
873     /* Posix accounts have group interrelationship, 
874        take care about these here if this is a new user without forced gidNumber. */
875     if ($this->force_ids == 0 && $this->primaryGroup == 0 && !$this->initially_was_account){
876       $ldap->cd($this->config->current['BASE']);
877       $ldap->search("(&(objectClass=posixGroup)(gidNumber=".$this->gidNumber."))", array("cn"));
879       /* Create group if it doesn't exist */
880       if ($ldap->count() == 0){
881         $groupdn= preg_replace ('/^'.$this->config->current['DNMODE'].'=[^,]+,'.get_people_ou().'/i', 'cn='.$this->uid.','.get_groups_ou(), $this->dn);
883         $g= new group($this->config, $groupdn);
884         $g->cn= $this->uid;
885         $g->force_gid= 1;
886         $g->gidNumber= $this->gidNumber;
887         $g->description= "Group of user ".$this->givenName." ".$this->sn;
888         $g->save ();
889       }
890     }
892     /* Take care about groupMembership values: add to groups */
893     foreach ($this->groupMembership as $key => $value){
894       if (!isset($this->savedGroupMembership[$key])){
895         $g= new grouptabs($this->config,$this->config->data['TABS']['GROUPTABS'], $key,"groups");
896         $g->set_acl_base($key);
897         $g->by_object['group']->addUser($this->uid);
898         $g->save();
899       }
900     }
902     /* Remove from groups not listed in groupMembership */
903     foreach ($this->savedGroupMembership as $key => $value){
904       if (!isset($this->groupMembership[$key])){
905         $g= new grouptabs($this->config,$this->config->data['TABS']['GROUPTABS'], $key,"groups");
906         $g->set_acl_base($key);
907         $g->by_object['group']->removeUser ($this->uid);
908         $g->save();
909       }
910     }
912     /* Optionally execute a command after we're done */
913     if ($this->initially_was_account == $this->is_account){
914       if ($this->is_modified){
915         $this->handle_post_events("modify",array("uid" => $this->uid));
916       }
917     } else {
918       $this->handle_post_events("add" ,array("uid"=> $this->uid));
919     }
920   }
922   /* Check formular input */
923   function check()
924   {
925     /* Include global link_info */
926     $ldap= $this->config->get_ldap_link();
928     /* Call common method to give check the hook */
929     $message= plugin::check();
931     /* must: homeDirectory */
932     if ($this->homeDirectory == ""){
933       $message[]= _("The required field 'Home directory' is not set.");
934     }
935     if (!is_path($this->homeDirectory)){
936       $message[]= _("Please enter a valid path in 'Home directory' field.");
937     }
939     /* Check ID's if they are forced by user */
940     if ($this->force_ids == "1"){
942       /* Valid uid/gid? */
943       if (!is_id($this->uidNumber)){
944         $message[]= _("Value specified as 'UID' is not valid.");
945       } else {
946         if ($this->uidNumber < $this->config->current['MINID']){
947           $message[]= _("Value specified as 'UID' is too small.");
948         }
949       }
950       if (!is_id($this->gidNumber)){
951         $message[]= _("Value specified as 'GID' is not valid.");
952       } else {
953         if ($this->gidNumber < $this->config->current['MINID']){
954           $message[]= _("Value specified as 'GID' is too small.");
955         }
956       }
957     }
959     /* Check shadow settings, well I like spaghetties... */
960     if ($this->use_shadowMin){
961       if (!is_id($this->shadowMin)){
962         $message[]= _("Value specified as 'shadowMin' is not valid.");
963       }
964     }
965     if ($this->use_shadowMax){
966       if (!is_id($this->shadowMax)){
967         $message[]= _("Value specified as 'shadowMax' is not valid.");
968       }
969     }
970     if ($this->use_shadowWarning){
971       if (!is_id($this->shadowWarning)){
972         $message[]= _("Value specified as 'shadowWarning' is not valid.");
973       }
974       if (!$this->use_shadowMax){
975         $message[]= _("'shadowWarning' without 'shadowMax' makes no sense.");
976       }
977       if ($this->shadowWarning > $this->shadowMax){
978         $message[]= _("Value specified as 'shadowWarning' should be smaller than 'shadowMax'.");
979       }
980       if ($this->use_shadowMin && $this->shadowWarning < $this->shadowMin){
981         $message[]= _("Value specified as 'shadowWarning' should be greater than 'shadowMin'.");
982       }
983     }
984     if ($this->use_shadowInactive){
985       if (!is_id($this->shadowInactive)){
986         $message[]= _("Value specified as 'shadowInactive' is not valid.");
987       }
988       if (!$this->use_shadowMax){
989         $message[]= _("'shadowInactive' without 'shadowMax' makes no sense.");
990       }
991     }
992     if ($this->use_shadowMin && $this->use_shadowMax){
993       if ($this->shadowMin > $this->shadowMax){
994         $message[]= _("Value specified as 'shadowMin' should be smaller than 'shadowMax'.");
995       }
996     }
998     //  if(empty($this->gosaDefaultPrinter)){
999     //    $message[]= _("You need to specify a valid default printer.");
1000     //  }
1002     return ($message);
1003   }
1005   function addGroup ($groups)
1006   {
1007     /* include global link_info */
1008     $ldap= $this->config->get_ldap_link();
1010     /* Walk through groups and add the descriptive entry if not exists */
1011     foreach ($groups as $value){
1012       if (!array_key_exists($value, $this->groupMembership)){
1013         $ldap->cat($value, array('cn', 'description', 'dn'));
1014         $attrs= $ldap->fetch();
1015         error_reporting (0);
1016         if (!isset($attrs['description'][0])){
1017           $entry= $attrs["cn"][0];
1018         } else {
1019           $dsc= preg_replace ('/^Group of user/', _("Group of user"), $attrs["description"][0]);
1020           $entry= $attrs["cn"][0]." [$dsc]";
1021         }
1022         error_reporting (E_ALL);
1024         if(obj_is_writable($attrs['dn'],"groups/group","memberUid")){
1025           $this->groupMembership[$attrs['dn']]= $entry;
1026         }
1027       }
1028     }
1030     /* Sort groups */
1031     asort ($this->groupMembership);
1032     reset ($this->groupMembership);
1033   }
1036   /* Del posix user from some groups */
1037   function delGroup ($groups)
1038   {
1039     $dest= array();
1040     foreach($groups as $dn_to_del){
1041       if(isset($this->groupMembership[$dn_to_del]) && obj_is_writable($dn_to_del,"groups/group","memberUid")){
1042         unset($this->groupMembership[$dn_to_del]);
1043       }
1044     }
1045   }
1048   /* Adapt from template, using 'dn' */
1049   function adapt_from_template($dn)
1050   {
1051     /* Include global link_info */
1052     $ldap= $this->config->get_ldap_link();
1054     plugin::adapt_from_template($dn);
1055     $template= $this->attrs['uid'][0];
1057     /* Adapt group membership */
1058     $ldap->cd($this->config->current['BASE']);
1059     $ldap->search("(&(objectClass=posixGroup)(memberUid=".$this->attrs["uid"][0]."))", array("description", "cn"));
1061     while ($this->attrs= $ldap->fetch()){
1062       if (!isset($this->attrs["description"][0])){
1063         $entry= $this->attrs["cn"][0];
1064       } else {
1065         $entry= $this->attrs["cn"][0]." [".$this->attrs["description"][0]."]";
1066       }
1067       $this->groupMembership[$ldap->getDN()]= $entry;
1068     }
1070     /* Fix primary group settings */
1071     $ldap->cd($this->config->current['BASE']);
1072     $ldap->search("(&(objectClass=posixGroup)(cn=$template)(gidNumber=".$this->gidNumber."))", array("cn"));
1073     if ($ldap->count() != 1){
1074       $this->primaryGroup= $this->gidNumber;
1075     }
1077     $ldap->cd($this->config->current['BASE']);
1078     $ldap->search("(&(objectClass=gosaUserTemplate)(uid=".$template.")(accessTo=*))", array("cn","accessTo"));
1079     while($attr = $ldap->fetch()){
1080       $tmp = $attr['accessTo'];
1081       unset ($tmp['count']);
1082       $this->accessTo = $tmp;   
1083     }
1085     /* Adjust shadow checkboxes */
1086     foreach (array("shadowMin", "shadowMax", "shadowWarning", "shadowInactive") as $val){
1087       if ($this->$val != 0){
1088         $oval= "use_".$val;
1089         $this->$oval= "1";
1090       }
1091     }
1093     /* FIXME: NEED review of this section */
1094     /* Need to check shadowExpire separately */
1096     /* 
1097      * If shadowExpire is not enabled in the template, it's a UNIX timestamp - so don't convert it to seconds.
1098      * The check is a hack - if difference between timestamp generated above and here is max 1 day.
1099      */
1100     if(abs($this->shadowExpire - time())>86400) {
1101       $this->shadowExpire= $this->convertToSeconds($this->shadowExpire);
1102     }
1103     
1104     /* Only enable checkbox, if shadowExpire is in the future */
1105     if($this->shadowExpire > time()) {
1106       $this->use_shadowExpire= "1";
1107     }
1108   }
1110   function convertToSeconds($val)
1111   {
1112     if ($val != 0){
1113       $val*= 60 * 60 * 24;
1114     } else {
1115       $date= getdate();
1116       $val= floor($date[0] / (60*60*24)) * 60 * 60 * 24;
1117     }
1118     return($val);
1119   }
1122   function get_next_id($attrib, $dn)
1123   {
1124     $ids= array();
1125     $ldap= $this->config->get_ldap_link();
1127     $ldap->cd ($this->config->current['BASE']);
1128     if (preg_match('/gidNumber/i', $attrib)){
1129       $oc= "posixGroup";
1130     } else {
1131       $oc= "posixAccount";
1132     }
1133     $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
1135     /* Get list of ids */
1136     while ($attrs= $ldap->fetch()){
1137       $ids[]= (int)$attrs["$attrib"][0];
1138     }
1140     /* Add the nobody id */
1141     $ids[]= 65534;
1143     /* get the ranges */
1144     $tmp = array('0'=> 1000); 
1145     if (preg_match('/posixAccount/', $oc) && isset($this->config->current['UIDBASE'])) {
1146       $tmp= split('-',$this->config->current['UIDBASE']);
1147     } elseif(isset($this->config->current['GIDBASE'])){
1148       $tmp= split('-',$this->config->current['GIDBASE']);
1149     }
1151     /* Set hwm to max if not set - for backward compatibility */
1152     $lwm= $tmp[0];
1153     if (isset($tmp[1])){
1154       $hwm= $tmp[1];
1155     } else {
1156       $hwm= pow(2,32);
1157     }
1159     /* Find out next free id near to UID_BASE */
1160     if (!isset($this->config->current['BASE_HOOK'])){
1161       $base= $lwm;
1162     } else {
1163       /* Call base hook */
1164       $base= get_base_from_hook($dn, $attrib);
1165     }
1166     for ($id= $base; $id++; $id < pow(2,32)){
1167       if (!in_array($id, $ids)){
1168         return ($id);
1169       }
1170     }
1172     /* Should not happen */
1173     if ($id == $hwm){
1174       print_red(_("Too many users, can't allocate a free ID!"));
1175       exit;
1176     }
1178   }
1180   function reload()
1181   {
1182     /* Set base for all searches */
1183     $base     = $_SESSION['CurrentMainBase'];
1184     $base     = $base;
1185     $ldap     = $this->config->get_ldap_link();    
1186     $attrs    =  array("cn", "description", "gidNumber");
1187     $Flags    = GL_SIZELIMIT;
1189     /* Get groups */
1190     if ($this->GroupUserRegex == '*'){
1191       $filter = "(&(objectClass=posixGroup)(cn=".$this->GroupRegex."))";
1192     } else {
1193       $filter= "(&(objectClass=posixGroup)(cn=".$this->GroupRegex.")(memberUid=".$this->GroupUserRegex."))";
1194     }
1195     if($this->SubSearch){
1196       $Flags |= GL_SUBSEARCH;
1197     }else{
1198       $base = get_groups_ou().$base;
1199     }
1201     $res= get_list($filter, "groups", $base,$attrs, $Flags);
1202   
1203     /* check sizelimit */
1204     if (preg_match("/size limit/i", $ldap->error)){
1205       $_SESSION['limit_exceeded']= TRUE;
1206     }
1208     /* Create a list of users */
1209     $this->grouplist = array();
1210     foreach ($res as $value){
1211       $this->grouplist[$value['gidNumber'][0]]= $value;
1212     }
1214     $tmp=array();
1215     foreach($this->grouplist as $tkey => $val ){
1216       $tmp[strtolower($val['cn'][0]).$val['cn'][0]]=$val;
1217     }
1219     /* Sort index */
1220     ksort($tmp);
1222     /* Recreate index array[dn]=cn[description]*/
1223     $this->grouplist=array();
1224     foreach($tmp as $val){
1225       if(isset($val['description'])){
1226         $this->grouplist[$val['dn']]=$val['cn'][0]."&nbsp;[".$val['description'][0]."]";
1227       }else{
1228         $this->grouplist[$val['dn']]=$val['cn'][0];
1229       }
1230     }
1232     reset ($this->grouplist);
1233   }
1236   /* Get posts from copy & paste dialog */ 
1237   function saveCopyDialog()
1238   {
1239     if(isset($_POST['homeDirectory'])){
1240       $this->homeDirectory = $_POST['homeDirectory'];
1241       if (isset ($_POST['force_ids'])){
1242         $data= 1;
1243         $this->gidNumber = $_POST['gidNumber'];
1244         $this->uidNumber = $_POST['uidNumber'];
1245       } else {
1246         $data= 0;
1247       }
1248       if ($this->force_ids != $data){
1249         $this->is_modified= TRUE;
1250       }
1251       $this->force_ids= $data;
1252     }
1253   }
1254  
1256   /* Create the posix dialog part for copy & paste */
1257   function getCopyDialog()
1258   {
1259     /* Skip dialog creation if this is not a valid account*/
1260     if(!$this->is_account) return("");
1261     if ($this->force_ids == 1){
1262       $force_ids = "checked";
1263       if ($_SESSION['js']){
1264         $forceMode = "";
1265       }
1266     } else {
1267       if ($_SESSION['js']){
1268         if($this->acl != "#none#")
1269           $forceMode ="disabled";
1270       }
1271       $force_ids = "";
1272     }
1274     $sta = "";
1276     /* Open group add dialog */
1277     if(isset($_POST['edit_groupmembership'])){
1278       $this->group_dialog = TRUE;
1279       $sta = "SubDialog";
1280     }
1282     /* If the group-add dialog is closed, call execute 
1283        to ensure that the membership is updatd */
1284     if(isset($_POST['add_groups_finish']) || isset($_POST['add_groups_cancel'])){
1285       $this->execute();
1286       $this->group_dialog =FALSE;
1287     }
1289     if($this->group_dialog){
1290       $str = $this->execute(true);
1291       $ret = array();
1292       $ret['string'] = $str;
1293       $ret['status'] = $sta;
1294       return($ret);
1295     }
1297     /* If a group member should be deleted, simply call execute */
1298     if(isset($_POST['delete_groupmembership'])){
1299       $this->execute();
1300     }
1302     /* Assigned informations to smarty */
1303     $smarty = get_smarty();
1304     $smarty->assign("homeDirectory",$this->homeDirectory);
1305     $smarty->assign("uidNumber",$this->uidNumber);
1306     $smarty->assign("gidNumber",$this->gidNumber);
1307     $smarty->assign("forceMode",$forceMode);
1308     $smarty->assign("force_ids",$force_ids);
1309     if (!count($this->groupMembership)){
1310       $smarty->assign("groupMembership", array("&nbsp;"));
1311     } else {
1312       $smarty->assign("groupMembership", $this->groupMembership);
1313     }
1315     /* Display wars message if there are more than 16 group members */
1316     if (count($this->groupMembership) > 16){
1317       $smarty->assign("groups", "too_many_for_nfs");
1318     } else {
1319       $smarty->assign("groups", "");
1320     }
1321     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1323     $ret = array();
1324     $ret['string'] = $str;
1325     $ret['status'] = $sta;
1326     return($ret);
1327   }
1330   function PrepareForCopyPaste($source)
1331   {
1332     plugin::PrepareForCopyPaste($source);
1334     /* Avoid using the same gid/uid number as source user */
1335     $this->savedUidNumber = $this->get_next_id("gidNumber", $this->dn);
1336     $this->savedGidNumber = $this->get_next_id("uidNumber", $this->dn);
1337   }
1340   function plInfo()
1341   {
1342     return (array(
1343           "plDescription"     => _("POSIX account"),
1344           "plSelfModify"      => TRUE,
1345           "plDepends"         => array("user"),
1346           "plPriority"        => 2,
1347           "plSection"         => array("personal" => _("My account")),
1348           "plCategory"        => array("users"),
1349           "plOptions"         => array(),
1351           "plProvidedAcls"  => array(
1353             "homeDirectory"       =>  _("Home directory"), 
1354             "loginShell"          =>  _("Shell"),
1355             "uidNumber"           =>  _("User ID"),
1356             "gidNumber"           =>  _("Group ID"),
1358             "mustchangepassword"=>  _("Force password change on login"),
1359             "shadowMin"           =>  _("Shadow min"),
1360             "shadowMax"           =>  _("Shadow max"),
1361             "shadowWarning"       =>  _("Shadow warning"),
1362             "shadowInactive"      =>  _("Shadow inactive"),
1363             "shadowExpire"        =>  _("Shadow expire"),
1364             "trustModel"          =>  _("System trust model")))
1365             );
1366   }
1369 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1370 ?>