Code

Fixed problem related to template-based user-creation and dates (dateOfBirth, shadowE...
[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       $this->is_account= !$this->is_account;
239     }
241     /* Do we represent a valid posixAccount? */
242     if (!$this->is_account && $this->parent == NULL ){
243       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
244         _("This account has no unix extensions.")."</b>";
245       $display.= back_to_main();
246       return ($display);
247     }
250     /* Show tab dialog headers */
251     if ($this->parent != NULL){
252       if ($this->is_account){
253         if (isset($this->parent->by_object['sambaAccount'])){
254           $obj= $this->parent->by_object['sambaAccount'];
255         }
256         if (isset($obj) && $obj->is_account == TRUE &&
257             ((isset($this->parent->by_object['sambaAccount']))&&($this->parent->by_object['sambaAccount']->is_account))
258             ||(isset($this->parent->by_object['environment'] ))&&($this->parent->by_object['environment'] ->is_account)){
260           /* Samba3 dependency on posix accounts are enabled
261              in the moment, because I need to rely on unique
262              uidNumbers. There'll be a better solution later
263              on. */
264           $display= $this->show_header(_("Remove posix account"),
265               _("This account has unix features enabled. To disable them, you'll need to remove the samba / environment account first."), TRUE);
266         } else {
267           $display= $this->show_header(_("Remove posix account"),
268               _("This account has posix features enabled. You can disable them by clicking below."));
269         }
270       } else {
271         $display= $this->show_header(_("Create posix account"),
272             _("This account has posix features disabled. You can enable them by clicking below."));
273         return($display);
274       }
275     }
276   }
277   /* Trigger group edit? */
278   if (isset($_POST['edit_groupmembership'])){
279     $this->group_dialog= TRUE;
280     $this->dialog= TRUE;
281   }
283   /* Cancel group edit? */
284   if (isset($_POST['add_groups_cancel']) ||
285       isset($_POST['add_groups_finish'])){
286     $this->group_dialog= FALSE;
287     $this->dialog= FALSE;
288   }
290   /* Add selected groups */
291   if (isset($_POST['add_groups_finish']) && isset($_POST['groups']) &&
292       count($_POST['groups'])){
294       if (chkacl ($this->acl, "memberUid") == ""){
295         $this->addGroup ($_POST['groups']);
296         $this->is_modified= TRUE;
297       }
298     }
300     /* Delete selected groups */
301     if (isset($_POST['delete_groupmembership']) && 
302         isset($_POST['group_list']) && count($_POST['group_list'])){
304       if (chkacl ($this->acl, "memberUid") == ""){
305         $this->delGroup ($_POST['group_list']);
306         $this->is_modified= TRUE;
307       }
308     }
310     /* Add user workstation? */
311     if (isset($_POST["add_ws"])){
312       $this->show_ws_dialog= TRUE;
313       $this->dialog= TRUE;
314     }
316     /* Add user workstation? */
317     if (isset($_POST["add_ws_finish"]) && isset($_POST['wslist'])){
318       foreach($_POST['wslist'] as $ws){
319         $this->accessTo[$ws]= $ws;
320       }
321       ksort($this->accessTo);
322       $this->is_modified= TRUE;
323     }
325     /* Remove user workstations? */
326     if (isset($_POST["delete_ws"]) && isset($_POST['workstation_list'])){
327       foreach($_POST['workstation_list'] as $name){
328         unset ($this->accessTo[$name]);
329       }
330       $this->is_modified= TRUE;
331     }
333     /* Add user workstation finished? */
334     if (isset($_POST["add_ws_finish"]) || isset($_POST["add_ws_cancel"])){
335       $this->show_ws_dialog= FALSE;
336       $this->dialog= FALSE;
337     }
339     /* Templates now! */
340     $smarty= get_smarty();
342     /* Show ws dialog */
343     if ($this->show_ws_dialog){
344       /* Save data */
345       $sysfilter= get_global("sysfilter");
346       foreach( array("depselect", "regex") as $type){
347         if (isset($_POST[$type])){
348           $sysfilter[$type]= $_POST[$type];
349         }
350       }
351       if (isset($_GET['search'])){
352         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
353         if ($s == "**"){
354           $s= "*";
355         }
356         $sysfilter['regex']= $s;
357       }
358       register_global("sysfilter", $sysfilter);
360       /* Get workstation list */
361       $exclude= "";
362       foreach($this->accessTo as $ws){
363         $exclude.= "(cn=$ws)";
364       }
365       if ($exclude != ""){
366         $exclude= "(!(|$exclude))";
367       }
368       $acl= array($this->config->current['BASE'] => ":all");
369       $regex= $sysfilter['regex'];
370       $filter= "(&(|(objectClass=goServer)(objectClass=gotoWorkstation)(objectClass=gotoTerminal))$exclude(cn=*)(cn=$regex))";
371       $res= get_list($filter, $acl, $sysfilter['depselect'], array("cn"), GL_SUBSEARCH | GL_SIZELIMIT);
372       $wslist= array();
373       foreach ($res as $attrs){
374         $wslist[]= preg_replace('/\$/', '', $attrs['cn'][0]);
375       }
376       asort($wslist);
377       $smarty->assign("search_image", get_template_path('images/search.png'));
378       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
379       $smarty->assign("tree_image", get_template_path('images/tree.png'));
380       $smarty->assign("deplist", $this->config->idepartments);
381       $smarty->assign("alphabet", generate_alphabet());
382       foreach( array("depselect", "regex") as $type){
383         $smarty->assign("$type", $sysfilter[$type]);
384       }
385       $smarty->assign("hint", print_sizelimit_warning());
386       $smarty->assign("wslist", $wslist);
387       $smarty->assign("apply", apply_filter());
388       $display= $smarty->fetch (get_template_path('trust_machines.tpl', TRUE, dirname(__FILE__)));
389       return ($display);
390     }
392     /* Manage group add dialog */
393     if ($this->group_dialog){
395       /* Get global filter config */
396       $this->reload();
398       /* remove already assigned groups */
399       $glist= array();
400       foreach ($this->grouplist as $key => $value){
401         if (!isset($this->groupMembership[$key])){
402           $glist[$key]= $value;
403         }
404       }
406       if($this->SubSearch){
407         $smarty->assign("SubSearchCHK"," checked ");
408       }else{
409         $smarty->assign("SubSearchCHK","");
410       }
412       $smarty->assign("regex",$this->GroupRegex);
413       $smarty->assign("guser",$this->GroupUserRegex);
414       $smarty->assign("groups", $glist);
415       $smarty->assign("search_image", get_template_path('images/search.png'));
416       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
417       $smarty->assign("tree_image", get_template_path('images/tree.png'));
418       $smarty->assign("deplist", $this->config->idepartments);
419       $smarty->assign("alphabet", generate_alphabet());
420       $smarty->assign("depselect",$_SESSION['CurrentMainBase']);
421       $smarty->assign("hint", print_sizelimit_warning());
423       $smarty->assign("apply", apply_filter());
424       $display.= $smarty->fetch (get_template_path('posix_groups.tpl', TRUE, dirname(__FILE__)));
425       return ($display);
426     }
428     /* Show main page */
429     $smarty= get_smarty();
431     /* Depending on pwmode, currently hardcoded because there are no other methods */
432     if ( 1 == 1 ){
433       $smarty->assign("pwmode", dirname(__FILE__)."/posix_shadow");
434       $shadowMinACL= chkacl($this->acl, "shadowMin");
435       $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."\">"));
436       $shadowMaxACL= chkacl($this->acl, "shadowMax");
437       $smarty->assign("shadowmaxs", sprintf(_("Password must be changed after %s days"), "<input name=\"shadowMax\" size=3 maxlength=4 $shadowMaxACL value=\"".$this->shadowMax."\">"));
438       $shadowInactiveACL= chkacl($this->acl, "shadowInactive");
439       $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."\">"));
440       $shadowWarningACL= chkacl($this->acl, "shadowWarning");
441       $smarty->assign("shadowwarnings", sprintf(_("Warn user %s days before password expiery"), "<input name=\"shadowWarning\" size=3 maxlength=4 $shadowWarningACL value=\"".$this->shadowWarning."\">"));
442       foreach( array("must_change_password", "use_shadowMin", "use_shadowMax",
443             "use_shadowExpire", "use_shadowInactive",
444             "use_shadowWarning") as $val){
445         if ($this->$val == 1){
446           $smarty->assign("$val", "checked");
447         } else {
448           $smarty->assign("$val", "");
449         }
450         $smarty->assign("$val"."ACL", chkacl($this->acl, $val));
451       }
452     }
454     /* Fill calendar */
455    
456     /* If this $this->shadowExpire is empty 
457         use current date as base for calculating selectbox values.
458        (This attribute is empty if this is a new user )*/ 
459     if(empty($this->shadowExpire)){
460       $date= getdate(time());
461     }else{
462       $date= getdate($this->shadowExpire);
463     }
465     $days= array();
466     for($d= 1; $d<32; $d++){
467       $days[$d]= $d;
468     }
469     $years= array();
470     for($y= $date['year']-10; $y<$date['year']+10; $y++){
471       $years[]= $y;
472     }
473     $months= array(_("January"), _("February"), _("March"), _("April"),
474         _("May"), _("June"), _("July"), _("August"), _("September"),
475         _("October"), _("November"), _("December"));
476     $smarty->assign("day", $date["mday"]);
477     $smarty->assign("days", $days);
478     $smarty->assign("months", $months);
479     $smarty->assign("month", $date["mon"]-1);
480     $smarty->assign("years", $years);
481     $smarty->assign("year", $date["year"]);
483     /* Fill arrays */
484     $smarty->assign("shells", $this->loginShellList);
485     $smarty->assign("secondaryGroups", $this->secondaryGroups);
486     $smarty->assign("primaryGroup", $this->primaryGroup);
487    if (!count($this->groupMembership)){
488       $smarty->assign("groupMembership", array("&nbsp;"));
489     } else {
490       $smarty->assign("groupMembership", $this->groupMembership);
491     }
492     if (count($this->groupMembership) > 16){
493       $smarty->assign("groups", "too_many_for_nfs");
494     } else {
495       $smarty->assign("groups", "");
496     }
497     $smarty->assign("languages", $this->config->data['MAIN']['LANGUAGES']);
499         /* Avoid "Undefined index: forceMode" */
500     $smarty->assign("forceMode", "");
502     /* Checkboxes */
503     if ($this->force_ids == 1){
504       $smarty->assign("force_ids", "checked");
505       if ($_SESSION['js']){
506         $smarty->assign("forceMode", "");
507       }
508     } else {
509       if ($_SESSION['js']){
510                 if($this->acl != "#none#")
511         $smarty->assign("forceMode", "disabled");
512       }
513       $smarty->assign("force_ids", "");
514     }
515     $smarty->assign("force_idsACL", chkacl($this->acl, "force_ids"));
517     /* Load attributes and acl's */
518     foreach($this->attributes as $val){
519       if((chkacl($this->acl,$val)=="")&&(($_SESSION["js"])&&(($val=="uidNumber")||($val=="gidNumber"))))
520         {
521           $smarty->assign("$val"."ACL","");
522           $smarty->assign("$val", $this->$val);
523           continue;
524         }
525       $smarty->assign("$val", $this->$val);
526       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
527     }
528     $smarty->assign("groupMembershipACL", chkacl($this->acl, "groupMembership"));
529     $smarty->assign("status", $this->status);
531     /* Work on trust modes */
532     $smarty->assign("trustmodeACL", chkacl($this->acl, "trustmode"));
533     if ($this->trustModel == "fullaccess"){
534       $trustmode= 1;
535       // pervent double disable tag in html code, this will disturb our clean w3c html
536     
537     if(chkacl($this->acl, "trustmode")==""){
538           $smarty->assign("trusthide", "disabled");
539       }else{
540           $smarty->assign("trusthide", "");
541       }
543     } elseif ($this->trustModel == "byhost"){
544       $trustmode= 2;
545       $smarty->assign("trusthide", "");
546     } else {
547       // pervent double disable tag in html code, this will disturb our clean w3c html
548       if(chkacl($this->acl, "trustmode")==""){
549           $smarty->assign("trusthide", "disabled");
550       }else{
551           $smarty->assign("trusthide", "");
552       }
553       $trustmode= 0;
554     }
555     $smarty->assign("trustmode", $trustmode);
556     $smarty->assign("trustmodes", array( 0 => _("disabled"), 1 => _("full access"),
557           2 => _("allow access to these hosts")));
561     if((count($this->accessTo))==0)
562       $smarty->assign("emptyArrAccess",true);
563     else
564       $smarty->assign("emptyArrAccess",false);
565     
568     $smarty->assign("workstations", $this->accessTo);
570     $smarty->assign("apply", apply_filter());
571     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
572     return($display);
573   }
576   /* remove object from parent */
577   function remove_from_parent()
578   {
579     /* Cancel if there's nothing to do here */
580     if (!$this->initially_was_account){
581       return;
582     }
584     /* include global link_info */
585     $ldap= $this->config->get_ldap_link();
586     
587         /* Remove and write to LDAP */
588     plugin::remove_from_parent();
590     /* Zero out array */
591     $this->attrs['gosaHostACL']= array();
593     /* Keep uid, because we need it for authentification! */
594     unset($this->attrs['uid']);
595     unset($this->attrs['trustModel']);
597     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
598         $this->attributes, "Save");
599     $ldap->cd($this->dn);
600     $this->cleanup();
601     $ldap->modify ($this->attrs); 
603     show_ldap_error($ldap->get_error(), _("Removing UNIX account failed"));
605     /* Delete group only if cn is uid and there are no other
606        members inside */
607     $ldap->cd ($this->config->current['BASE']);
608     $ldap->search ("(&(objectClass=posixGroup)(gidNumber=".$this->gidNumber."))", array("cn", "memberUid"));
609     if ($ldap->count() != 0){
610       $attrs= $ldap->fetch();
611       if ($attrs['cn'][0] == $this->uid &&
612           !isset($this->attrs['memberUid'])){
614         $ldap->rmDir($ldap->getDN());
615       }
616     }
618     /* Optionally execute a command after we're done */
619     $this->handle_post_events("remove", array("uid" => $this->uid));
620   }
623   function save_object()
624   {
625     if (isset($_POST['posixTab'])){
626       /* Save values to object */
627       plugin::save_object();
629       /* Save force GID attribute */
630       if (chkacl ($this->acl, "force_ids") == ""){
631         if (isset ($_POST['force_ids'])){
632           $data= 1;
633         } else {
634           $data= 0;
635         }
636         if ($this->force_ids != $data){
637           $this->is_modified= TRUE;
638         }
639         $this->force_ids= $data;
641         $data= $_POST['primaryGroup'];
642         if ($this->primaryGroup != $data){
643           $this->is_modified= TRUE;
644         }
645         $this->primaryGroup= $_POST['primaryGroup'];
646       }
648       /* Save pwmode dependent attributes, curently hardcoded because there're
649          no alternatives */
650       if (1 == 1){
651         foreach( array("must_change_password", "use_shadowMin", "use_shadowMax",
652               "use_shadowExpire", "use_shadowInactive",
653               "use_shadowWarning") as $val){
654           if (chkacl($this->acl, "$val") == ""){
655             if (isset ($_POST[$val])){
656               $data= 1;
657             } else {
658               $data= 0;
659             }
660             if ($data != $this->$val){
661               $this->is_modified= TRUE;
662             }
663             $this->$val= $data;
664           }
665         }
666       }
668       /* Trust mode - special handling */
669       if (isset($_POST['trustmode'])){
670         $saved= $this->trustModel;
671         if ($_POST['trustmode'] == "1"){
672           $this->trustModel= "fullaccess";
673         } elseif ($_POST['trustmode'] == "2"){
674           $this->trustModel= "byhost";
675         } else {
676           $this->trustModel= "";
677         }
678         if ($this->trustModel != $saved){
679           $this->is_modified= TRUE;
680         }
681       }
682     }
684     /* Get regex from alphabet */
685     if(isset($_GET['search'])){
686       $this->GroupRegex = $_GET['search']."*";
687     }
689     /* Check checkboxes and regexes */
690     if(isset($_POST["PosixGroupDialogPosted"])){
691       if(isset($_POST['SubSearch']) && ($_POST['SubSearch'])){
692         $this->SubSearch = true;
693       }else{
694         $this->SubSearch = false;
695       }
696     
697       if(isset($_POST['guser'])){
698         $this->GroupUserRegex = $_POST['guser'];
699       }
700       if(isset($_POST['regex'])){
701         $this->GroupRegex = $_POST['regex'];
702       }
703     }
704     $this->GroupRegex = preg_replace("/\*\**/","*",$this->GroupRegex);
705     $this->GroupUserRegex = preg_replace("/\*\**/","*",$this->GroupUserRegex);
706   }
709   /* Save data to LDAP, depending on is_account we save or delete */
710   function save()
711   {
712         
713     /* include global link_info */
714     $ldap= $this->config->get_ldap_link();
716     /* Adapt shadow values */
717     if (!$this->use_shadowExpire){
718       $this->shadowExpire= "0";
719     } else {
720       /* Transform seconds to days here */
721       $this->shadowExpire= (int)($this->shadowExpire / (60 * 60 * 24)) ;
722     }
723     if (!$this->use_shadowMax){
724       $this->shadowMax= "0";
725     }
726     if ($this->must_change_password){
727       $this->shadowLastChange= (int)(date("U") / 86400) - $this->shadowMax - 1;
728     } else {
729       $this->shadowLastChange= (int)(date("U") / 86400);
730     }
731     if (!$this->use_shadowWarning){
732       $this->shadowWarning= "0";
733     }
735     /* Check what to do with ID's */
736     if ($this->force_ids == 0){
738       /* Use id's that are already set */
739       if ($this->savedUidNumber != ""){
740         $this->uidNumber= $this->savedUidNumber;
741         $this->gidNumber= $this->savedGidNumber;
742       } else {
744         /* Calculate new id's. We need to place a lock before calling get_next_id
745            to get real unique values. */
746         $wait= 10;
747         while (get_lock("uidnumber") != ""){
748           sleep (1);
750           /* Oups - timed out */
751           if ($wait-- == 0){
752             print_red (_("Failed: overriding lock"));
753             break;
754           }
755         }
757         add_lock ("uidnumber", "gosa");
758         $this->uidNumber= $this->get_next_id("uidNumber");
759         if ($this->savedGidNumber != ""){
760           $this->gidNumber= $this->savedGidNumber;
761         } else {
762           $this->gidNumber= $this->get_next_id("gidNumber");
763         }
764       }
766       if ($this->primaryGroup != 0){
767         $this->gidNumber= $this->primaryGroup;
768       }
769     }
771     if ($this->use_shadowMin != "1" ) {
772       $this->shadowMin = "";
773     }
775     if (($this->use_shadowMax != "1") && ($this->must_change_password != "1")) {
776       $this->shadowMax = "";
777     }
779     if ($this->use_shadowWarning != "1" ) {
780       $this->shadowWarning = "";
781     }
783     if ($this->use_shadowInactive != "1" ) {
784       $this->shadowInactive = "";
785     }
787     if ($this->use_shadowExpire != "1" ) {
788       $this->shadowExpire = "";
789     }
791     /* Fill gecos */
792     if (isset($this->parent) && $this->parent != NULL){
793       $this->gecos= rewrite($this->parent->by_object['user']->cn);
794       if (!preg_match('/^[a-z0-9 -]+$/i', $this->gecos)){
795         $this->gecos= "";
796       }
797     }
799         foreach(array("shadowMin","shadowMax","shadowWarning","shadowInactive","shadowExpire") as $attr){
800                 $this->$attr = (int) $this->$attr;
801         }
802     /* Call parents save to prepare $this->attrs */
803     plugin::save();
805     /* Trust accounts */
806     $objectclasses= array();
807     foreach ($this->attrs['objectClass'] as $key => $class){
808       if (preg_match('/trustAccount/i', $class)){
809         continue;
810       }
811       $objectclasses[]= $this->attrs['objectClass'][$key];
812     }
813     $this->attrs['objectClass']= $objectclasses;
814     if ($this->trustModel != ""){
815       $this->attrs['objectClass'][]= "trustAccount";
816       $this->attrs['trustModel']= $this->trustModel;
817       $this->attrs['accessTo']= array();
818       if ($this->trustModel == "byhost"){
819         foreach ($this->accessTo as $host){
820           $this->attrs['accessTo'][]= $host;
821         }
822       }
823     } else {
824       if ($this->was_trust_account){
825         $this->attrs['accessTo']= array();
826         $this->attrs['trustModel']= array();
827       }
828     }
830     if(empty($this->attrs['gosaDefaultPrinter'])){
831       $thid->attrs['gosaDefaultPrinter']=array();
832     }
835     /* Save data to LDAP */
836     $ldap->cd($this->dn);
837     $this->cleanup();
838     unset($this->attrs['uid']);
839     $ldap->modify ($this->attrs); 
841     show_ldap_error($ldap->get_error(), _("Saving UNIX account failed"));
843     /* Remove lock needed for unique id generation */
844     del_lock ("uidnumber");
847     /* Posix accounts have group interrelationship, 
848         take care about these here if this is a new user without forced gidNumber. */
849     if ($this->force_ids == 0 && $this->primaryGroup == 0 && !$this->initially_was_account){
850       $ldap->cd($this->config->current['BASE']);
851       $ldap->search("(&(objectClass=posixGroup)(gidNumber=".$this->gidNumber."))", array("cn"));
853       /* Create group if it doesn't exist */
854       if ($ldap->count() == 0){
855         $groupdn= preg_replace ('/^'.$this->config->current['DNMODE'].'=[^,]+,'.get_people_ou().'/i', 'cn='.$this->uid.','.get_groups_ou(), $this->dn);
856         $g= new group($this->config, $groupdn);
857         $g->cn= $this->uid;
858         $g->force_gid= 1;
859         $g->gidNumber= $this->gidNumber;
860         $g->description= "Group of user ".$this->givenName." ".$this->sn;
861         $g->save ();
862       }
863     }
864  
865     /* Take care about groupMembership values: add to groups */
866     foreach ($this->groupMembership as $key => $value){
867       if (!isset($this->savedGroupMembership[$key])){
868         $g= new grouptabs($this->config,$this->config->data['TABS']['GROUPTABS'], $key, false);
869         $g->by_object['group']->addUser($this->uid);
870         $g->save();
871       }
872     }
873     
874     /* Remove from groups not listed in groupMembership */
875     foreach ($this->savedGroupMembership as $key => $value){
876       if (!isset($this->groupMembership[$key])){
877         $g= new grouptabs($this->config,$this->config->data['TABS']['GROUPTABS'], $key);
878         $g->by_object['group']->removeUser ($this->uid);
879         $g->save();
880       }
881     }
883     /* Optionally execute a command after we're done */
884     if ($this->initially_was_account == $this->is_account){
885       if ($this->is_modified){
886         $this->handle_post_events("modify",array("uid" => $this->uid));
887       }
888     } else {
889       $this->handle_post_events("add",array("uid" , $this->uid));
890     }
891   }
893   /* Check formular input */
894   function check()
895   {
896     /* Include global link_info */
897     $ldap= $this->config->get_ldap_link();
899     /* Call common method to give check the hook */
900     $message= plugin::check();
902     /* must: homeDirectory */
903     if ($this->homeDirectory == ""){
904       $message[]= _("The required field 'Home directory' is not set.");
905     }
906     if (!is_path($this->homeDirectory)){
907       $message[]= _("Please enter a valid path in 'Home directory' field.");
908     }
910     /* Check ID's if they are forced by user */
911     if ($this->force_ids == "1"){
913       /* Valid uid/gid? */
914       if (!is_id($this->uidNumber)){
915         $message[]= _("Value specified as 'UID' is not valid.");
916       } else {
917         if ($this->uidNumber < $this->config->current['MINID']){
918           $message[]= _("Value specified as 'UID' is too small.");
919         }
920       }
921       if (!is_id($this->gidNumber)){
922         $message[]= _("Value specified as 'GID' is not valid.");
923       } else {
924         if ($this->gidNumber < $this->config->current['MINID']){
925           $message[]= _("Value specified as 'GID' is too small.");
926         }
927       }
928     }
930     /* Check shadow settings, well I like spaghetties... */
931     if ($this->use_shadowMin){
932       if (!is_id($this->shadowMin)){
933         $message[]= _("Value specified as 'shadowMin' is not valid.");
934       }
935     }
936     if ($this->use_shadowMax){
937       if (!is_id($this->shadowMax)){
938         $message[]= _("Value specified as 'shadowMax' is not valid.");
939       }
940     }
941     if ($this->use_shadowWarning){
942       if (!is_id($this->shadowWarning)){
943         $message[]= _("Value specified as 'shadowWarning' is not valid.");
944       }
945       if (!$this->use_shadowMax){
946         $message[]= _("'shadowWarning' without 'shadowMax' makes no sense.");
947       }
948       if ($this->shadowWarning > $this->shadowMax){
949         $message[]= _("Value specified as 'shadowWarning' should be smaller than 'shadowMax'.");
950       }
951       if ($this->use_shadowMin && $this->shadowWarning < $this->shadowMin){
952         $message[]= _("Value specified as 'shadowWarning' should be greater than 'shadowMin'.");
953       }
954     }
955     if ($this->use_shadowInactive){
956       if (!is_id($this->shadowInactive)){
957         $message[]= _("Value specified as 'shadowInactive' is not valid.");
958       }
959       if (!$this->use_shadowMax){
960         $message[]= _("'shadowInactive' without 'shadowMax' makes no sense.");
961       }
962     }
963     if ($this->use_shadowMin && $this->use_shadowMax){
964       if ($this->shadowMin > $this->shadowMax){
965         $message[]= _("Value specified as 'shadowMin' should be smaller than 'shadowMax'.");
966       }
967     }
969   //  if(empty($this->gosaDefaultPrinter)){
970   //    $message[]= _("You need to specify a valid default printer.");
971   //  }
973     return ($message);
974   }
976   function addGroup ($groups)
977   {
978     /* include global link_info */
979     $ldap= $this->config->get_ldap_link();
981     /* Walk through groups and add the descriptive entry if not exists */
982     foreach ($groups as $value){
983       if (!array_key_exists($value, $this->groupMembership)){
984         $ldap->cat($value, array('cn', 'description', 'dn'));
985         $attrs= $ldap->fetch();
986         error_reporting (0);
987         if (!isset($attrs['description'][0])){
988           $entry= $attrs["cn"][0];
989         } else {
990           $dsc= preg_replace ('/^Group of user/', _("Group of user"), $attrs["description"][0]);
991           $entry= $attrs["cn"][0]." [$dsc]";
992         }
993         error_reporting (E_ALL);
994         $this->groupMembership[$attrs['dn']]= $entry;
995       }
996     }
998     /* Sort groups */
999     asort ($this->groupMembership);
1000     reset ($this->groupMembership);
1001   }
1004   /* Del posix user from some groups */
1005   function delGroup ($groups)
1006   {
1007     $dest= array();
1009     foreach ($this->groupMembership as $key => $value){
1010       if (!in_array($key, $groups)){
1011         $dest[$key]= $value;
1012       }
1013     }
1014     $this->groupMembership= $dest;
1015   }
1017   /* Adapt from template, using 'dn' */
1018   function adapt_from_template($dn)
1019   {
1020     /* Include global link_info */
1021     $ldap= $this->config->get_ldap_link();
1023     plugin::adapt_from_template($dn);
1024     $template= $this->attrs['uid'][0];
1026     /* Adapt group membership */
1027     $ldap->cd($this->config->current['BASE']);
1028     $ldap->search("(&(objectClass=posixGroup)(memberUid=".$this->attrs["uid"][0]."))", array("description", "cn"));
1030     while ($this->attrs= $ldap->fetch()){
1031       if (!isset($this->attrs["description"][0])){
1032         $entry= $this->attrs["cn"][0];
1033       } else {
1034         $entry= $this->attrs["cn"][0]." [".$this->attrs["description"][0]."]";
1035       }
1036       $this->groupMembership[$ldap->getDN()]= $entry;
1037     }
1039     /* Fix primary group settings */
1040     $ldap->cd($this->config->current['BASE']);
1041     $ldap->search("(&(objectClass=posixGroup)(cn=$template)(gidNumber=".$this->gidNumber."))", array("cn"));
1042     if ($ldap->count() != 1){
1043       $this->primaryGroup= $this->gidNumber;
1044     }
1046     $ldap->cd($this->config->current['BASE']);
1047     $ldap->search("(&(objectClass=gosaUserTemplate)(uid=".$template.")(accessTo=*))", array("cn","accessTo"));
1049     while($attr = $ldap->fetch()){
1050       $tmp = $attr['accessTo'];
1051       unset ($tmp['count']);
1052       $this->accessTo = $tmp;   
1053     }
1055     /* Adjust shadow checkboxes */
1056     foreach (array("shadowMin", "shadowMax", "shadowWarning", "shadowInactive") as $val){
1057       if ($this->$val != 0){
1058         $oval= "use_".$val;
1059         $this->$oval= "1";
1060       }
1061     }
1063     /* FIXME: NEED review of this section */
1064     /* Need to check shadowExpire separately */
1066     /* 
1067      * If shadowExpire is not enabled in the template, it's a UNIX timestamp - so don't convert it to seconds.
1068      * The check is a hack - if difference between timestamp generated above and here is max 1 day.
1069      */
1070     if(abs($this->shadowExpire - time())>86400) {
1071       $this->shadowExpire= $this->convertToSeconds($this->shadowExpire);
1072     }
1073     
1074     /* Only enable checkbox, if shadowExpire is in the future */
1075     if($this->shadowExpire > time()) {
1076       $this->use_shadowExpire= "1";
1077     }
1078   }
1080   function get_next_id($attrib)
1081   {
1082     $ids= array();
1083     $ldap= $this->config->get_ldap_link();
1085     $ldap->cd ($this->config->current['BASE']);
1086     if (preg_match('/gidNumber/i', $attrib)){
1087       $oc= "posixGroup";
1088     } else {
1089       $oc= "posixAccount";
1090     }
1091     $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
1093     /* Get list of ids */
1094     while ($attrs= $ldap->fetch()){
1095       $ids[]= (int)$attrs["$attrib"][0];
1096     }
1098     /* Add the nobody id */
1099     $ids[]=  65534;
1101     /* Find out next free id near to UID_BASE */
1102     for ($id= $this->config->current['UIDBASE']; $id++; $id < pow(2,32)){
1103       if (!in_array($id, $ids)){
1104         return ($id);
1105       }
1106     }
1108     /* Check if current id reaches the maximum of 32 bit */
1109     if ($id >= pow(2,32)){
1110       echo _("Too many users, can't allocate a free ID!");
1111       exit;
1112     }
1113   }
1115  function reload()
1116   {
1118     /* Set base for all searches */
1119     $base     = $_SESSION['CurrentMainBase'];
1120     $base     = $base;
1121     $ldap     = $this->config->get_ldap_link();    
1122     $attrs    =  array("cn", "description", "gidNumber");
1123     $Flags    = GL_SIZELIMIT;
1125     /* Get groups */
1126     if ($this->GroupUserRegex == '*'){
1127       $filter = "(&(objectClass=posixGroup)(cn=".$this->GroupRegex."))";
1128     } else {
1129       $filter= "(&(objectClass=posixGroup)(cn=".$this->GroupRegex.")(memberUid=".$this->GroupUserRegex."))";
1130     }
1131     if($this->SubSearch){
1132       $Flags |= GL_SUBSEARCH;
1133     }else{
1134       $base = get_groups_ou().$base;
1135     }
1138     $res= get_list($filter, $this->ui->subtreeACL, $base,$attrs, $Flags);
1140     /* check sizelimit */
1141     if (preg_match("/size limit/i", $ldap->error)){
1142       $_SESSION['limit_exceeded']= TRUE;
1143     }
1145     /* Create a list of users */
1146     $this->grouplist = array();
1147     foreach ($res as $value){
1148         $this->grouplist[$value['gidNumber'][0]]= $value;
1149     }
1151     $tmp=array();
1152     foreach($this->grouplist as $tkey => $val ){
1153       $tmp[strtolower($val['cn'][0]).$val['cn'][0]]=$val;
1154     }
1156     /* Sort index */
1157     ksort($tmp);
1159     /* Recreate index array[dn]=cn[description]*/
1160     $this->grouplist=array();
1161     foreach($tmp as $val){
1162       if(isset($val['description'])){
1163         $this->grouplist[$val['dn']]=$val['cn'][0]."&nbsp;[".$val['description'][0]."]";
1164       }else{
1165         $this->grouplist[$val['dn']]=$val['cn'][0];
1166       }
1167     }
1168     reset ($this->grouplist);
1169   }
1171  
1172   /* Get posts from copy & paste dialog */ 
1173   function saveCopyDialog()
1174   {
1175     if(isset($_POST['homeDirectory'])){
1176       $this->homeDirectory = $_POST['homeDirectory'];
1177       if (isset ($_POST['force_ids'])){
1178         $data= 1;
1179         $this->gidNumber = $_POST['gidNumber'];
1180         $this->uidNumber = $_POST['uidNumber'];
1181       } else {
1182         $data= 0;
1183       }
1184       if ($this->force_ids != $data){
1185         $this->is_modified= TRUE;
1186       }
1187       $this->force_ids= $data;
1188     }
1189   }
1192   /* Create the posix dialog part for copy & paste */
1193   function getCopyDialog()
1194   {
1195     /* Skip dialog creation if this is not a valid account */
1196     if(!$this->is_account) return("");
1197     if ($this->force_ids == 1){
1198       $force_ids = "checked";
1199       if ($_SESSION['js']){
1200         $forceMode = "";
1201       }
1202     } else {
1203       if ($_SESSION['js']){
1204         if($this->acl != "#none#")
1205           $forceMode ="disabled";
1206       }
1207       $force_ids = "";
1208     }
1209    
1210     $sta = "";
1211  
1212     /* Open group add dialog */
1213     if(isset($_POST['edit_groupmembership'])){
1214       $this->group_dialog = TRUE;
1215       $sta = "SubDialog";
1216     }
1218     /* If the group-add dialog is closed, call execute 
1219         to ensure that the membership is updatd */
1220     if(isset($_POST['add_groups_finish']) || isset($_POST['add_groups_cancel'])){
1221       $this->execute();
1222       $this->group_dialog =FALSE;
1223     }
1225     if($this->group_dialog){
1226       $str = $this->execute(true);
1227       $ret = array();
1228       $ret['string'] = $str;
1229       $ret['status'] = $sta;
1230       return($ret);
1231     }
1233     /* If a group member should be deleted, simply call execute */
1234     if(isset($_POST['delete_groupmembership'])){
1235       $this->execute();
1236     }
1238     /* Assigned informations to smarty */
1239     $smarty = get_smarty();
1240     $smarty->assign("homeDirectory",$this->homeDirectory);
1241     $smarty->assign("uidNumber",$this->uidNumber);
1242     $smarty->assign("gidNumber",$this->gidNumber);
1243     $smarty->assign("forceMode",$forceMode);
1244     $smarty->assign("force_ids",$force_ids);
1245     if (!count($this->groupMembership)){
1246       $smarty->assign("groupMembership", array("&nbsp;"));
1247     } else {
1248       $smarty->assign("groupMembership", $this->groupMembership);
1249     }
1251     /* Display wars message if there are more than 16 group members */
1252     if (count($this->groupMembership) > 16){
1253       $smarty->assign("groups", "too_many_for_nfs");
1254     } else {
1255       $smarty->assign("groups", "");
1256     }
1257     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1259     $ret = array();
1260     $ret['string'] = $str;
1261     $ret['status'] = $sta;
1262     return($ret);
1263   }
1265   function PrepareForCopyPaste($source)
1266   {
1267     plugin::PrepareForCopyPaste($source);
1268     
1269     /* Avoid using the same gid/uid number as source user */
1270     $this->savedUidNumber = $this->get_next_id("gidNumber");
1271     $this->savedGidNumber = $this->get_next_id("uidNumber");
1272   }
1274   function convertToSeconds($val)
1275   {
1276     if ($val != 0){
1277       $val*= 60 * 60 * 24;
1278     } else {
1279       $date= getdate();
1280       $val= floor($date[0] / (60*60*24)) * 60 * 60 * 24;
1281     }
1282     return($val);
1283   }
1287 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1288 ?>