Code

Only store changed attribute
[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 $printerList= array();
56   var $group_dialog= FALSE;
57   var $show_ws_dialog= FALSE;
58   var $secondaryGroups= array();
59   var $primaryGroup= 0;
60   var $was_trust_account= FALSE;
62   var $grouplist  = array();
63   var $ui         = array();
65   /* attribute list for save action */
66   var $attributes= array("homeDirectory", "loginShell", "uidNumber", "gidNumber", "gecos",
67       "shadowMin", "shadowMax", "shadowWarning", "shadowInactive", "shadowLastChange",
68       "shadowExpire", "gosaDefaultPrinter", "gosaDefaultLanguage", "uid","accessTo","trustModel");
69   var $objectclasses= array("posixAccount", "shadowAccount");
72   /* constructor, if 'dn' is set, the node loads the given
73      'dn' from LDAP */
74   function posixAccount ($config, $dn= NULL)
75   {
76     /* Configuration is fine, allways */
77     $this->config= $config;
79     /* Load bases attributes */
80     plugin::plugin($config, $dn);
82     $ldap= $this->config->get_ldap_link();
84     if ($dn != NULL){
86       /* Correct is_account. shadowAccount is not required. */
87       if (isset($this->attrs['objectClass']) &&
88           in_array ('posixAccount', $this->attrs['objectClass'])){
90         $this->is_account= TRUE;
91       }
93       /* Is this account a trustAccount? */
94       if ($this->is_account && isset($this->attrs['trustModel'])){
95         $this->trustModel= $this->attrs['trustModel'][0];
96         $this->was_trust_account= TRUE;
97       } else {
98         $this->was_trust_account= FALSE;
99         $this->trustModel= "";
100       }
101          
102           $this->accessTo = array(); 
103       if ($this->is_account && isset($this->attrs['accessTo'])){
104         for ($i= 0; $i<$this->attrs['accessTo']['count']; $i++){
105           $tmp= $this->attrs['accessTo'][$i];
106           $this->accessTo[$tmp]= $tmp;
107         }
108       }
109       $this->initially_was_account= $this->is_account;
111       /* Fill group */
112       $this->primaryGroup= $this->gidNumber;
114       /* Generate status text */
115       $current= date("U");
116       if (($current >= $this->shadowExpire) && $this->shadowExpire){
117         $this->status= "expired";
118         if (($this->shadowExpire - $current) < $this->shadowInactive){
119           $this->status.= ", grace time active";
120         }
121       } elseif (($this->shadowLastChange + $this->shadowMin) >= $current){
122         $this->status= "active, password not changable";
123       } elseif (($this->shadowLastChange + $this->shadowMax) >= $current){
124         $this->status= "active, password expired";
125       } else {
126         $this->status= "active";
127       }
129       /* Get group membership */
130       $ldap->cd($this->config->current['BASE']);
131       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("cn", "description"));
133       while ($this->attrs= $ldap->fetch()){
134         if (!isset($this->attrs["description"][0])){
135           $entry= $this->attrs["cn"][0];
136         } else {
137           $dsc= preg_replace ('/^Group of user/', _("Group of user"), $this->attrs["description"][0]);
138           $entry= $this->attrs["cn"][0]." [$dsc]";
139         }
140         $this->groupMembership[$ldap->getDN()]= $entry;
141       }
142       asort($this->groupMembership);
143       reset($this->groupMembership);
144       $this->savedGroupMembership= $this->groupMembership;
145       $this->savedUidNumber= $this->uidNumber;
146       $this->savedGidNumber= $this->gidNumber;
147     }
149     /* Adjust shadow checkboxes */
150     foreach (array("shadowMin", "shadowMax", "shadowWarning", "shadowInactive",
151           "shadowExpire") as $val){
153       if ($this->$val != 0){
154         $oval= "use_".$val;
155         $this->$oval= "1";
156       }
157     }
159     /* Convert to seconds */
160     if ($this->shadowExpire != 0){
161       $this->shadowExpire*= 60 * 60 * 24;
162     } else {
163       $date= getdate();
164       $this->shadowExpire= floor($date[0] / (60*60*24)) * 60 * 60 * 24;
165     }
167     /* Generate shell list from /etc/gosa/shells */
168     if (file_exists('/etc/gosa/shells')){
169       $shells = file ('/etc/gosa/shells');
170       foreach ($shells as $line){
171         if (!preg_match ("/^#/", $line)){
172           $this->loginShellList[]= trim($line);
173         }
174       }
175     } else {
176       if ($this->loginShell == ""){
177         $this->loginShellList[]= _("unconfigured");
178       }
179     }
181     /* Insert possibly missing loginShell */
182     if ($this->loginShell != "" && !in_array($this->loginShell, $this->loginShellList)){
183       $this->loginShellList[]= $this->loginShell;
184     }
186     /* Generate printer list */
187     if (isset($this->config->data['SERVERS']['CUPS'])){
188       $this->printerList= get_printer_list ($this->config->data['SERVERS']['CUPS']);
189       asort($this->printerList);
190     }
192     /* Generate group list */
193     $ldap->cd($this->config->current['BASE']);
194     $ldap->search("(objectClass=posixGroup)", array("cn", "gidNumber"));
195     $this->secondaryGroups[]= "- "._("automatic")." -";
196     while ($attrs= $ldap->fetch()){
197       $this->secondaryGroups[$attrs['gidNumber'][0]]= $attrs['cn'][0];
198     }
199     asort ($this->secondaryGroups);
201     /* Get global filter config */
202     if (!is_global("sysfilter")){
203       $ui= get_userinfo();
204       $base= get_base_from_people($ui->dn);
205       $sysfilter= array( "depselect"       => $base,
206           "regex"           => "*");
207       register_global("sysfilter", $sysfilter);
208     }
209     $this->ui = get_userinfo();
210   }
213   /* execute generates the html output for this node */
214   function execute()
215   {
216         /* Call parent execute */
217         plugin::execute();
219     /* Do we need to flip is_account state? */
220     if (isset($_POST['modify_state'])){
221       $this->is_account= !$this->is_account;
222     }
224     /* Do we represent a valid posixAccount? */
225     if (!$this->is_account && $this->parent == NULL ){
226       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
227         _("This account has no unix extensions.")."</b>";
228       $display.= back_to_main();
229       return ($display);
230     }
232     $display= "";
234     /* Show tab dialog headers */
235     if ($this->parent != NULL){
236       if ($this->is_account){
237         if (isset($this->parent->by_object['sambaAccount'])){
238           $obj= $this->parent->by_object['sambaAccount'];
239         }
240         if (isset($obj) && $obj->is_account == TRUE &&
241              ((isset($this->parent->by_object['sambaAccount']))&&($this->parent->by_object['sambaAccount']->is_account))
242                         ||(isset($this->parent->by_object['environment'] ))&&($this->parent->by_object['environment'] ->is_account)){
244           /* Samba3 dependency on posix accounts are enabled
245              in the moment, because I need to rely on unique
246              uidNumbers. There'll be a better solution later
247              on. */
248           $display= $this->show_header(_("Remove posix account"),
249               _("This account has unix features enabled. To disable them, you'll need to remove the samba / environment account first."), TRUE);
250         } else {
251           $display= $this->show_header(_("Remove posix account"),
252               _("This account has posix features enabled. You can disable them by clicking below."));
253         }
254       } else {
255         $display= $this->show_header(_("Create posix account"),
256             _("This account has posix features disabled. You can enable them by clicking below."));
257         return($display);
258       }
259     }
261     /* Trigger group edit? */
262     if (isset($_POST['edit_groupmembership'])){
263       $this->group_dialog= TRUE;
264       $this->dialog= TRUE;
265     }
267     /* Cancel group edit? */
268     if (isset($_POST['add_groups_cancel']) ||
269         isset($_POST['add_groups_finish'])){
270       $this->group_dialog= FALSE;
271       $this->dialog= FALSE;
272     }
274     /* Add selected groups */
275     if (isset($_POST['add_groups_finish']) && isset($_POST['groups']) &&
276         count($_POST['groups'])){
278       if (chkacl ($this->acl, "memberUid") == ""){
279         $this->addGroup ($_POST['groups']);
280         $this->is_modified= TRUE;
281       }
282     }
284     /* Delete selected groups */
285     if (isset($_POST['delete_groupmembership']) && 
286         isset($_POST['group_list']) && count($_POST['group_list'])){
288       if (chkacl ($this->acl, "memberUid") == ""){
289         $this->delGroup ($_POST['group_list']);
290         $this->is_modified= TRUE;
291       }
292     }
294     /* Add user workstation? */
295     if (isset($_POST["add_ws"])){
296       $this->show_ws_dialog= TRUE;
297       $this->dialog= TRUE;
298     }
300     /* Add user workstation? */
301     if (isset($_POST["add_ws_finish"]) && isset($_POST['wslist'])){
302       foreach($_POST['wslist'] as $ws){
303         $this->accessTo[$ws]= $ws;
304       }
305       ksort($this->accessTo);
306       $this->is_modified= TRUE;
307     }
309     /* Remove user workstations? */
310     if (isset($_POST["delete_ws"]) && isset($_POST['workstation_list'])){
311       foreach($_POST['workstation_list'] as $name){
312         unset ($this->accessTo[$name]);
313       }
314       $this->is_modified= TRUE;
315     }
317     /* Add user workstation finished? */
318     if (isset($_POST["add_ws_finish"]) || isset($_POST["add_ws_cancel"])){
319       $this->show_ws_dialog= FALSE;
320       $this->dialog= FALSE;
321     }
323     /* Templates now! */
324     $smarty= get_smarty();
326     /* Show ws dialog */
327     if ($this->show_ws_dialog){
328       /* Save data */
329       $sysfilter= get_global("sysfilter");
330       foreach( array("depselect", "regex") as $type){
331         if (isset($_POST[$type])){
332           $sysfilter[$type]= $_POST[$type];
333         }
334       }
335       if (isset($_GET['search'])){
336         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
337         if ($s == "**"){
338           $s= "*";
339         }
340         $sysfilter['regex']= $s;
341       }
342       register_global("sysfilter", $sysfilter);
344       /* Get workstation list */
345       $exclude= "";
346       foreach($this->accessTo as $ws){
347         $exclude.= "(cn=$ws)";
348       }
349       if ($exclude != ""){
350         $exclude= "(!(|$exclude))";
351       }
352       $acl= array($this->config->current['BASE'] => ":all");
353       $regex= $sysfilter['regex'];
354       $filter= "(&(|(objectClass=goServer)(objectClass=gotoWorkstation)(objectClass=gotoTerminal))$exclude(cn=*)(cn=$regex))";
355       $res= get_list($acl, "$filter", TRUE, $sysfilter['depselect'], array("cn"), TRUE);
356       $wslist= array();
357       foreach ($res as $attrs){
358         $wslist[]= preg_replace('/\$/', '', $attrs['cn'][0]);
359       }
360       asort($wslist);
361       $smarty->assign("search_image", get_template_path('images/search.png'));
362       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
363       $smarty->assign("tree_image", get_template_path('images/tree.png'));
364       $smarty->assign("deplist", $this->config->idepartments);
365       $smarty->assign("alphabet", generate_alphabet());
366       foreach( array("depselect", "regex") as $type){
367         $smarty->assign("$type", $sysfilter[$type]);
368       }
369       $smarty->assign("hint", print_sizelimit_warning());
370       $smarty->assign("wslist", $wslist);
371       $smarty->assign("apply", apply_filter());
372       $display= $smarty->fetch (get_template_path('trust_machines.tpl', TRUE, dirname(__FILE__)));
373       return ($display);
374     }
376     /* Manage group add dialog */
377     if ($this->group_dialog){
379       /* Save data */
380       $groupfilter= get_global("groupfilter");
381       foreach( array("depselect", "guser", "regex") as $type){
382         if (isset($_POST[$type])){
383           $groupfilter[$type]= $_POST[$type];
384         }
385       }
386       if (isset($_POST['depselect'])){
387         foreach( array("primarygroups", "sambagroups", "mailgroups", "appgroups",
388               "functionalgroups") as $type){
390           if (isset($_POST[$type])) {
391             $groupfilter[$type]= "checked";
392           } else {
393             $groupfilter[$type]= "";
394           }
395         }
396       }
397       if (isset($_GET['search'])){
398         $s= mb_substr($_GET['search'], 0, 1, "UTF8")."*";
399         if ($s == "**"){
400           $s= "*";
401         }
402         $groupfilter['regex']= $s;
403       }
404       register_global("groupfilter", $groupfilter);
406       /* Calculate actual groups */
407                 
408       $this->reload();
409       $glist= array();
410       foreach ($this->grouplist as $key => $value){
411         if (!isset($this->groupMembership[$key])){
412           $glist[$key]= $value;
413         }
414       }
416       $smarty->assign("groups", $glist);
417       $smarty->assign("search_image", get_template_path('images/search.png'));
418       $smarty->assign("launchimage", get_template_path('images/small_filter.png'));
419       $smarty->assign("tree_image", get_template_path('images/tree.png'));
420       $smarty->assign("deplist", $this->config->idepartments);
421       $smarty->assign("alphabet", generate_alphabet());
422       foreach( array("depselect", "guser", "regex", "primarygroups", "mailgroups",
423             "appgroups", "sambagroups", "functionalgroups") as $type){
424         $smarty->assign("$type", $groupfilter[$type]);
425       }
426       $smarty->assign("hint", print_sizelimit_warning());
428       $smarty->assign("apply", apply_filter());
429       $display.= $smarty->fetch (get_template_path('posix_groups.tpl', TRUE, dirname(__FILE__)));
430       return ($display);
431     }
433     /* Show main page */
434     $smarty= get_smarty();
436     /* Depending on pwmode, currently hardcoded because there are no other methods */
437     if ( 1 == 1 ){
438       $smarty->assign("pwmode", dirname(__FILE__)."/posix_shadow");
439       $shadowMinACL= chkacl($this->acl, "shadowMin");
440       $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."\">"));
441       $shadowMaxACL= chkacl($this->acl, "shadowMax");
442       $smarty->assign("shadowmaxs", sprintf(_("Password must be changed after %s days"), "<input name=\"shadowMax\" size=3 maxlength=4 $shadowMaxACL value=\"".$this->shadowMax."\">"));
443       $shadowInactiveACL= chkacl($this->acl, "shadowInactive");
444       $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."\">"));
445       $shadowWarningACL= chkacl($this->acl, "shadowWarning");
446       $smarty->assign("shadowwarnings", sprintf(_("Warn user %s days before password expiery"), "<input name=\"shadowWarning\" size=3 maxlength=4 $shadowWarningACL value=\"".$this->shadowWarning."\">"));
447       foreach( array("must_change_password", "use_shadowMin", "use_shadowMax",
448             "use_shadowExpire", "use_shadowInactive",
449             "use_shadowWarning") as $val){
450         if ($this->$val == 1){
451           $smarty->assign("$val", "checked");
452         } else {
453           $smarty->assign("$val", "");
454         }
455         $smarty->assign("$val"."ACL", chkacl($this->acl, $val));
456       }
457     }
459     /* Fill calendar */
460     $date= getdate($this->shadowExpire);
462     $days= array();
463     for($d= 1; $d<32; $d++){
464       $days[$d]= $d;
465     }
466     $years= array();
467     for($y= $date['year']-10; $y<$date['year']+10; $y++){
468       $years[]= $y;
469     }
470     $months= array(_("January"), _("February"), _("March"), _("April"),
471         _("May"), _("June"), _("July"), _("August"), _("September"),
472         _("October"), _("November"), _("December"));
473     $smarty->assign("day", $date["mday"]);
474     $smarty->assign("days", $days);
475     $smarty->assign("months", $months);
476     $smarty->assign("month", $date["mon"]-1);
477     $smarty->assign("years", $years);
478     $smarty->assign("year", $date["year"]);
480     /* Fill arrays */
481     $smarty->assign("shells", $this->loginShellList);
482     $smarty->assign("secondaryGroups", $this->secondaryGroups);
483     $smarty->assign("primaryGroup", $this->primaryGroup);
484     if (!count($this->groupMembership)){
485       $smarty->assign("groupMembership", array("&nbsp;"));
486     } else {
487       $smarty->assign("groupMembership", $this->groupMembership);
488     }
489     if (count($this->groupMembership) > 16){
490       $smarty->assign("groups", "too_many_for_nfs");
491     } else {
492       $smarty->assign("groups", "");
493     }
494     $smarty->assign("printerList", $this->printerList);
495     $smarty->assign("languages", $this->config->data['MAIN']['LANGUAGES']);
497         /* Avoid "Undefined index: forceMode" */
498     $smarty->assign("forceMode", "");
500     /* Checkboxes */
501     if ($this->force_ids == 1){
502       $smarty->assign("force_ids", "checked");
503       if ($_SESSION['js']){
504         $smarty->assign("forceMode", "");
505       }
506     } else {
507       if ($_SESSION['js']){
508                 if($this->acl != "#none#")
509         $smarty->assign("forceMode", "disabled");
510       }
511       $smarty->assign("force_ids", "");
512     }
513     $smarty->assign("force_idsACL", chkacl($this->acl, "force_ids"));
515     /* Load attributes and acl's */
516     foreach($this->attributes as $val){
517       if((chkacl($this->acl,$val)=="")&&(($_SESSION["js"])&&(($val=="uidNumber")||($val=="gidNumber"))))
518         {
519           $smarty->assign("$val"."ACL","");
520           $smarty->assign("$val", $this->$val);
521           continue;
522         }
523       $smarty->assign("$val", $this->$val);
524       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
525     }
526     $smarty->assign("groupMembershipACL", chkacl($this->acl, "groupMembership"));
527     $smarty->assign("status", $this->status);
529     /* Work on trust modes */
530     $smarty->assign("trustmodeACL", chkacl($this->acl, "trustmode"));
531     if ($this->trustModel == "fullaccess"){
532       $trustmode= 1;
533       // pervent double disable tag in html code, this will disturb our clean w3c html
534     
535     if(chkacl($this->acl, "trustmode")==""){
536           $smarty->assign("trusthide", "disabled");
537       }else{
538           $smarty->assign("trusthide", "");
539       }
541     } elseif ($this->trustModel == "byhost"){
542       $trustmode= 2;
543       $smarty->assign("trusthide", "");
544     } else {
545       // pervent double disable tag in html code, this will disturb our clean w3c html
546       if(chkacl($this->acl, "trustmode")==""){
547           $smarty->assign("trusthide", "disabled");
548       }else{
549           $smarty->assign("trusthide", "");
550       }
551       $trustmode= 0;
552     }
553     $smarty->assign("trustmode", $trustmode);
554     $smarty->assign("trustmodes", array( 0 => _("disabled"), 1 => _("full access"),
555           2 => _("allow access to these hosts")));
559     if((count($this->accessTo))==0)
560       $smarty->assign("emptyArrAccess",true);
561     else
562       $smarty->assign("emptyArrAccess",false);
563     
566     $smarty->assign("workstations", $this->accessTo);
568     $smarty->assign("apply", apply_filter());
569     $display.= $smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
570     return($display);
571   }
574   /* remove object from parent */
575   function remove_from_parent()
576   {
577     /* Cancel if there's nothing to do here */
578     if (!$this->initially_was_account){
579       return;
580     }
582     /* include global link_info */
583     $ldap= $this->config->get_ldap_link();
584     
585         /* Remove and write to LDAP */
586     plugin::remove_from_parent();
588     /* Zero out array */
589     $this->attrs['gosaHostACL']= array();
591     /* Keep uid, because we need it for authentification! */
592     unset($this->attrs['uid']);
593     unset($this->attrs['trustModel']);
595     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
596         $this->attributes, "Save");
597     $ldap->cd($this->dn);
598     $ldap->modify($this->attrs);
599     show_ldap_error($ldap->get_error());
601     /* Delete group only if cn is uid and there are no other
602        members inside */
603     $ldap->cd ($this->config->current['BASE']);
604     $ldap->search ("(&(objectClass=posixGroup)(gidNumber=".$this->gidNumber."))", array("cn", "memberUid"));
605     if ($ldap->count() != 0){
606       $attrs= $ldap->fetch();
607       if ($attrs['cn'][0] == $this->uid &&
608           !isset($this->attrs['memberUid'])){
610         $ldap->rmDir($ldap->getDN());
611       }
612     }
614     /* Optionally execute a command after we're done */
615     $this->handle_post_events("remove");
616   }
619   function save_object()
620   {
621     if (isset($_POST['posixTab'])){
622       /* Save values to object */
623       plugin::save_object();
625       /* Save force GID attribute */
626       if (chkacl ($this->acl, "force_ids") == ""){
627         if (isset ($_POST['force_ids'])){
628           $data= 1;
629         } else {
630           $data= 0;
631         }
632         if ($this->force_ids != $data){
633           $this->is_modified= TRUE;
634         }
635         $this->force_ids= $data;
637         $data= $_POST['primaryGroup'];
638         if ($this->primaryGroup != $data){
639           $this->is_modified= TRUE;
640         }
641         $this->primaryGroup= $_POST['primaryGroup'];
642       }
644       /* Save pwmode dependent attributes, curently hardcoded because there're
645          no alternatives */
646       if (1 == 1){
647         foreach( array("must_change_password", "use_shadowMin", "use_shadowMax",
648               "use_shadowExpire", "use_shadowInactive",
649               "use_shadowWarning") as $val){
650           if (chkacl($this->acl, "$val") == ""){
651             if (isset ($_POST[$val])){
652               $data= 1;
653             } else {
654               $data= 0;
655             }
656             if ($data != $this->$val){
657               $this->is_modified= TRUE;
658             }
659             $this->$val= $data;
660           }
661         }
662       }
664       /* Trust mode - special handling */
665       if (isset($_POST['trustmode'])){
666         $saved= $this->trustModel;
667         if ($_POST['trustmode'] == "1"){
668           $this->trustModel= "fullaccess";
669         } elseif ($_POST['trustmode'] == "2"){
670           $this->trustModel= "byhost";
671         } else {
672           $this->trustModel= "";
673         }
674         if ($this->trustModel != $saved){
675           $this->is_modified= TRUE;
676         }
677       }
678     }
679   }
682   /* Save data to LDAP, depending on is_account we save or delete */
683   function save()
684   {
685         
686     /* include global link_info */
687     $ldap= $this->config->get_ldap_link();
689     /* Adapt shadow values */
690     if (!$this->use_shadowExpire){
691       $this->shadowExpire= "0";
692     } else {
693       /* Transform seconds to days here */
694       $this->shadowExpire= (int)($this->shadowExpire / (60 * 60 * 24)) ;
695     }
696     if (!$this->use_shadowMax){
697       $this->shadowMax= "0";
698     }
699     if ($this->must_change_password){
700       $this->shadowLastChange= (int)(date("U") / 86400) - $this->shadowMax - 1;
701     } else {
702       $this->shadowLastChange= (int)(date("U") / 86400);
703     }
704     if (!$this->use_shadowWarning){
705       $this->shadowWarning= "0";
706     }
708     /* Check what to do with ID's */
709     if ($this->force_ids == 0){
711       /* Use id's that are already set */
712       if ($this->savedUidNumber != ""){
713         $this->uidNumber= $this->savedUidNumber;
714         $this->gidNumber= $this->savedGidNumber;
715       } else {
717         /* Calculate new id's. We need to place a lock before calling get_next_id
718            to get real unique values. */
719         $wait= 10;
720         while (get_lock("uidnumber") != ""){
721           sleep (1);
723           /* Oups - timed out */
724           if ($wait-- == 0){
725             print_red (_("Failed: overriding lock"));
726             break;
727           }
728         }
730         add_lock ("uidnumber", "gosa");
731         $this->uidNumber= $this->get_next_id("uidNumber");
732         if ($this->savedGidNumber != ""){
733           $this->gidNumber= $this->savedGidNumber;
734         } else {
735           $this->gidNumber= $this->get_next_id("gidNumber");
736         }
737       }
739       if ($this->primaryGroup != 0){
740         $this->gidNumber= $this->primaryGroup;
741       }
742     }
744     if ($this->use_shadowMin != "1" ) {
745       $this->shadowMin = "";
746     }
748     if (($this->use_shadowMax != "1") && ($this->must_change_password != "1")) {
749       $this->shadowMax = "";
750     }
752     if ($this->use_shadowWarning != "1" ) {
753       $this->shadowWarning = "";
754     }
756     if ($this->use_shadowInactive != "1" ) {
757       $this->shadowInactive = "";
758     }
760     if ($this->use_shadowExpire != "1" ) {
761       $this->shadowExpire = "";
762     }
764     /* Fill gecos */
765     if (isset($this->parent) && $this->parent != NULL){
766       $this->gecos= rewrite($this->parent->by_object['user']->cn);
767       if (!preg_match('/[a-z0-9 -]/i', $this->gecos)){
768         $this->gecos= "";
769       }
770     }
772         foreach(array("shadowMin","shadowMax","shadowWarning","shadowInactive","shadowExpire") as $attr){
773                 $this->$attr = (int) $this->$attr;
774         }
775     /* Call parents save to prepare $this->attrs */
776     plugin::save();
778     /* Trust accounts */
779     $objectclasses= array();
780     foreach ($this->attrs['objectClass'] as $key => $class){
781       if (preg_match('/trustAccount/i', $class)){
782         continue;
783       }
784       $objectclasses[]= $this->attrs['objectClass'][$key];
785     }
786     $this->attrs['objectClass']= $objectclasses;
787     if ($this->trustModel != ""){
788       $this->attrs['objectClass'][]= "trustAccount";
789       $this->attrs['trustModel']= $this->trustModel;
790       $this->attrs['accessTo']= array();
791       if ($this->trustModel == "byhost"){
792         foreach ($this->accessTo as $host){
793           $this->attrs['accessTo'][]= $host;
794         }
795       }
796     } else {
797       if ($this->was_trust_account){
798         $this->attrs['accessTo']= array();
799         $this->attrs['trustModel']= array();
800       }
801     }
803     if(empty($this->attrs['gosaDefaultPrinter'])){
804       $thid->attrs['gosaDefaultPrinter']=array();
805     }
808     /* Save data to LDAP */
809     $ldap->cd($this->dn);
810     $ldap->modify($this->attrs);
811     show_ldap_error($ldap->get_error());
813     /* Remove lock needed for unique id generation */
814     del_lock ("uidnumber");
817     /* Posix accounts have group interrelationship, take care about these here. */
818     if ($this->force_ids == 0 && $this->primaryGroup == 0){
819       $ldap->cd($this->config->current['BASE']);
820       $ldap->search("(&(objectClass=posixGroup)(gidNumber=".$this->gidNumber."))", array("cn"));
822       /* Create group if it doesn't exist */
823       if ($ldap->count() == 0){
824         $groupdn= preg_replace ('/^'.$this->config->current['DNMODE'].'=[^,]+,'.get_people_ou().'/i', 'cn='.$this->uid.','.get_groups_ou(), $this->dn);
826         $g= new group($this->config, $groupdn);
827         $g->cn= $this->uid;
828         $g->force_gid= 1;
829         $g->gidNumber= $this->gidNumber;
830         $g->description= "Group of user ".$this->givenName." ".$this->sn;
831         $g->save ();
832       }
833     }
835     /* Take care about groupMembership values: add to groups */
836     foreach ($this->groupMembership as $key => $value){
837       $g= new group($this->config, $key);
838       $g->addUser ($this->uid);
839       $g->save();
841       /* May need to save the mail part, too */
842       if ($g->has_mailAccount){
843         $m= new mailgroup($this->config, $key);
844         $m->save();
845       }
846     }
848     /* Remove from groups not listed in groupMembership */
849     foreach ($this->savedGroupMembership as $key => $value){
850       if (!array_key_exists ($key, $this->groupMembership)){
851         $g= new group($this->config, $key);
852         $g->removeUser ($this->uid);
853         $g->save();
855         /* May need to save the mail part, too */
856         if ($g->has_mailAccount){
857           $m= new mailgroup($this->config, $key);
858           $m->save();
859         }
860       }
861     }
863     /* Optionally execute a command after we're done */
864     if ($this->initially_was_account == $this->is_account){
865       if ($this->is_modified){
866         $this->handle_post_events("mofify");
867       }
868     } else {
869       $this->handle_post_events("add");
870     }
871   }
873   /* Check formular input */
874   function check()
875   {
876     /* Include global link_info */
877     $ldap= $this->config->get_ldap_link();
879     /* Reset message array */
880     $message= array();
882     /* must: homeDirectory */
883     if ($this->homeDirectory == ""){
884       $message[]= _("The required field 'Home directory' is not set.");
885     }
886     if (!is_path($this->homeDirectory)){
887       $message[]= _("Please enter a valid path in 'Home directory' field.");
888     }
890     /* Check ID's if they are forced by user */
891     if ($this->force_ids == "1"){
893       /* Valid uid/gid? */
894       if (!is_id($this->uidNumber)){
895         $message[]= _("Value specified as 'UID' is not valid.");
896       } else {
897         if ($this->uidNumber < $this->config->current['MINID']){
898           $message[]= _("Value specified as 'UID' is too small.");
899         }
900       }
901       if (!is_id($this->gidNumber)){
902         $message[]= _("Value specified as 'GID' is not valid.");
903       } else {
904         if ($this->gidNumber < $this->config->current['MINID']){
905           $message[]= _("Value specified as 'GID' is too small.");
906         }
907       }
908     }
910     /* Check shadow settings, well I like spaghetties... */
911     if ($this->use_shadowMin){
912       if (!is_id($this->shadowMin)){
913         $message[]= _("Value specified as 'shadowMin' is not valid.");
914       }
915     }
916     if ($this->use_shadowMax){
917       if (!is_id($this->shadowMax)){
918         $message[]= _("Value specified as 'shadowMax' is not valid.");
919       }
920     }
921     if ($this->use_shadowWarning){
922       if (!is_id($this->shadowWarning)){
923         $message[]= _("Value specified as 'shadowWarning' is not valid.");
924       }
925       if (!$this->use_shadowMax){
926         $message[]= _("'shadowWarning' without 'shadowMax' makes no sense.");
927       }
928       if ($this->shadowWarning > $this->shadowMax){
929         $message[]= _("Value specified as 'shadowWarning' should be smaller than 'shadowMax'.");
930       }
931       if ($this->use_shadowMin && $this->shadowWarning < $this->shadowMin){
932         $message[]= _("Value specified as 'shadowWarning' should be greater than 'shadowMin'.");
933       }
934     }
935     if ($this->use_shadowInactive){
936       if (!is_id($this->shadowInactive)){
937         $message[]= _("Value specified as 'shadowInactive' is not valid.");
938       }
939       if (!$this->use_shadowMax){
940         $message[]= _("'shadowInactive' without 'shadowMax' makes no sense.");
941       }
942     }
943     if ($this->use_shadowMin && $this->use_shadowMax){
944       if ($this->shadowMin > $this->shadowMax){
945         $message[]= _("Value specified as 'shadowMin' should be smaller than 'shadowMax'.");
946       }
947     }
949   //  if(empty($this->gosaDefaultPrinter)){
950   //    $message[]= _("You need to specify a valid default printer.");
951   //  }
953     return ($message);
954   }
956   function addGroup ($groups)
957   {
958     /* include global link_info */
959     $ldap= $this->config->get_ldap_link();
961     /* Walk through groups and add the descriptive entry if not exists */
962     foreach ($groups as $value){
963       if (!array_key_exists($value, $this->groupMembership)){
964         $ldap->cat($value);
965         $attrs= $ldap->fetch();
966         error_reporting (0);
967         if (!isset($attrs['description'][0])){
968           $entry= $attrs["cn"][0];
969         } else {
970           $dsc= preg_replace ('/^Group of user/', _("Group of user"), $attrs["description"][0]);
971           $entry= $attrs["cn"][0]." [$dsc]";
972         }
973         error_reporting (E_ALL);
974         $this->groupMembership[$ldap->getDN()]= $entry;
975       }
976     }
978     /* Sort groups */
979     asort ($this->groupMembership);
980     reset ($this->groupMembership);
981   }
984   /* Del posix user from some groups */
985   function delGroup ($groups)
986   {
987     $dest= array();
989     foreach ($this->groupMembership as $key => $value){
990       if (!in_array($key, $groups)){
991         $dest[$key]= $value;
992       }
993     }
994     $this->groupMembership= $dest;
995   }
997   /* Adapt from template, using 'dn' */
998   function adapt_from_template($dn)
999   {
1000     /* Include global link_info */
1001     $ldap= $this->config->get_ldap_link();
1003     plugin::adapt_from_template($dn);
1004     $template= $this->attrs['uid'][0];
1006     /* Adapt group membership */
1007     $ldap->cd($this->config->current['BASE']);
1008     $ldap->search("(&(objectClass=posixGroup)(memberUid=".$this->attrs["uid"][0]."))", array("description", "cn"));
1010     while ($this->attrs= $ldap->fetch()){
1011       if (!isset($this->attrs["description"][0])){
1012         $entry= $this->attrs["cn"][0];
1013       } else {
1014         $entry= $this->attrs["cn"][0]." [".$this->attrs["description"][0]."]";
1015       }
1016       $this->groupMembership[$ldap->getDN()]= $entry;
1017     }
1019     /* Fix primary group settings */
1020     $ldap->cd($this->config->current['BASE']);
1021     $ldap->search("(&(objectClass=posixGroup)(cn=$template)(gidNumber=".$this->gidNumber."))", array("cn"));
1022     if ($ldap->count() != 1){
1023       $this->primaryGroup= $this->gidNumber;
1024     }
1026         $ldap->cd($this->config->current['BASE']);
1027     $ldap->search("(&(objectClass=gosaUserTemplate)(uid=".$template."))", array("cn","accessTo"));
1028         while($attr = $ldap->fetch()){
1029                 $tmp = $attr['accessTo'];
1030                 unset ($tmp['count']);
1031                 $this->accessTo = $tmp; 
1032         }
1033         
1034     /* Adjust shadow checkboxes */
1035     foreach (array("shadowMin", "shadowMax", "shadowWarning", "shadowInactive",
1036           "shadowExpire") as $val){
1038       if ($this->$val != 0){
1039         $oval= "use_".$val;
1040         $this->$oval= "1";
1041       }
1042     }
1043   }
1045   function get_next_id($attrib)
1046   {
1047     $ids= array();
1048     $ldap= $this->config->get_ldap_link();
1050     $ldap->cd ($this->config->current['BASE']);
1051     if (preg_match('/gidNumber/i', $attrib)){
1052       $oc= "posixGroup";
1053     } else {
1054       $oc= "posixAccount";
1055     }
1056     $ldap->search ("(&(objectClass=$oc)($attrib=*))", array("$attrib"));
1058     /* Get list of ids */
1059     while ($attrs= $ldap->fetch()){
1060       $ids[]= (int)$attrs["$attrib"][0];
1061     }
1063     /* Find out next free id near to UID_BASE */
1064     for ($id= $this->config->current['UIDBASE']; $id++; $id<65000){
1065       if (!in_array($id, $ids)){
1066         return ($id);
1067       }
1068     }
1070     /* Should not happen */
1071     if ($id == 65000){
1072       print_red(_("Too many users, can't allocate a free ID!"));
1073       exit;
1074     }
1076   }
1078  function reload()
1079   {
1081     /* Get config */
1082     $groupfilter= get_global('groupfilter');
1084     /* Set base for all searches */
1085     $base= $groupfilter['depselect'];
1087     /* Regex filter? */
1088     if ($groupfilter['regex'] != ""){
1089       $regex= $groupfilter['regex'];
1090     } else {
1091       $regex= "*";
1092     }
1094     $error = "";
1095     $ldap = $this->config->get_ldap_link();    
1097     $base= get_groups_ou().$base;
1098     $res= get_list($this->ui->subtreeACL, "(objectClass=posixGroup)", FALSE, $base, array("cn", "description", "gidNumber"), TRUE);
1099     if (preg_match("/size limit/i", $error)){
1100       $_SESSION['limit_exceeded']= TRUE;
1101     }
1103     $error = $ldap->error;
1104     $this->grouplist = array();
1105     foreach ($res as $value){
1106         $this->grouplist[$value['gidNumber'][0]]= $value;
1107     }
1109     $tmp=array();
1110     foreach($this->grouplist as $tkey => $val ){
1111       $tmp[strtolower($val['cn'][0]).$val['cn'][0]]=$val;
1112     }
1114     /* Sort index */
1115     ksort($tmp);
1117     /* Recreate index array[dn]=cn[description]*/
1118     $this->grouplist=array();
1119     foreach($tmp as $val){
1120       if(isset($val['description'])){
1121         $this->grouplist[$val['dn']]=$val['cn'][0]."&nbsp;[".$val['description'][0]."]";
1122       }else{
1123         $this->grouplist[$val['dn']]=$val['cn'][0];
1124       }
1125     }
1126     reset ($this->grouplist);
1127   }
1130 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1131 ?>