Code

Backports from 2.7
[gosa.git] / gosa-core / plugins / admin / users / class_userManagement.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 class userManagement extends management
24 {
25     var $plHeadline     = "Users";
26     var $plDescription  = "Manage aspects of user accounts like generic, POSIX, samba and mail settings";
27     var $plIcon  = "plugins/users/images/user.png";
29     var $sn = "";
30     var $givenName = "";
31     var $uid = "";
32     var $got_uid = "";
33     var $edit_uid = "";
35     var $pwd_change_queue = array();
36     var $force_hash_type = array();
38     // Tab definition 
39     protected $tabClass = "usertabs";
40     protected $tabType = "USERTABS";
41     protected $aclCategory = "users";
42     protected $aclPlugin   = "user";
43     protected $objectName   = "user";
45     protected $proposal = "";
46     protected $proposalEnabled = FALSE;
47     protected $proposalSelected = FALSE;
49     protected $passwordChangeForceable = FALSE;
50     protected $enforcePasswordChange = FALSE;
52     function __construct($config,$ui)
53     {
54         $this->config = $config;
55         $this->ui = $ui;
57         $this->storagePoints = array(get_ou("core", "userRDN"));
59         // Build filter
60         if (session::global_is_set(get_class($this)."_filter")){
61             $filter= session::global_get(get_class($this)."_filter");
62         } else {
63             $filter = new filter(get_template_path("user-filter.xml", true));
64             $filter->setObjectStorage($this->storagePoints);
65         }
66         $this->setFilter($filter);
68         // Build headpage
69         $headpage = new listing(get_template_path("user-list.xml", true));
70         $headpage->registerElementFilter("lockLabel", "userManagement::filterLockLabel");
71         $headpage->registerElementFilter("lockImage", "userManagement::filterLockImage");
72         $headpage->registerElementFilter("filterProperties", "userManagement::filterProperties");
73         $headpage->setFilter($filter);
75         // Add copy&paste and snapshot handler.
76         if ($this->config->boolValueIsTrue("core", "copyPaste")){
77             $this->cpHandler = new CopyPasteHandler($this->config);
78         }
79         if($this->config->get_cfg_value("core","enableSnapshots") == "true"){
80             $this->snapHandler = new SnapshotHandler($this->config);
81         }
83         parent::__construct($config, $ui, "users", $headpage);
85         // Register special user actions 
86         $this->registerAction("lock",   "lockEntry");
87         $this->registerAction("lockUsers",   "lockUsers");
88         $this->registerAction("unlockUsers", "lockUsers");
89         $this->registerAction("new_template", "newTemplate");
90         $this->registerAction("newfromtpl", "newUserFromTemplate");
91         $this->registerAction("templateContinue", "templateContinue");
92         $this->registerAction("templatize", "templatizeUsers");
93         $this->registerAction("templatizeContinue", "templatizeContinue");
95         $this->registerAction("password", "changePassword");
96         $this->registerAction("passwordQueue", "handlePasswordQueue");
97         $this->registerAction("passwordCancel", "closeDialogs");
99         $this->registerAction("sendMessage", "sendMessage");
100         $this->registerAction("saveEventDialog", "saveEventDialog");
101         $this->registerAction("abortEventDialog", "closeDialogs");
103         // Register shortcut icon actions 
104         $this->registerAction("edit_user","editEntry");
105         $this->registerAction("edit_posixAccount","editEntry");
106         $this->registerAction("edit_mailAccount","editEntry");
107         $this->registerAction("edit_sambaAccount","editEntry");
108         $this->registerAction("edit_netatalk","editEntry");
109         $this->registerAction("edit_environment","editEntry");
110         $this->registerAction("edit_gofaxAccount","editEntry");
111         $this->registerAction("edit_phoneAccount","editEntry");
112     }
115     // Inject user actions 
116     function detectPostActions()
117     {
118         $action = management::detectPostActions();
119         if(isset($_POST['template_continue'])) $action['action'] = "templateContinue";
120         if(isset($_POST['templatize_continue'])) $action['action'] = "templatizeContinue";
121         if(isset($_POST['save_event_dialog'])) $action['action'] = "saveEventDialog";
122         if(isset($_POST['abort_event_dialog'])) $action['action'] = "abortEventDialog";
123         if(isset($_POST['password_cancel'])){
124             $action['action'] = "passwordCancel";
125         }elseif((count($this->pwd_change_queue) || isset($_POST['password_finish']) || isset($_POST['refreshProposal']))){
126             $action['action'] = "passwordQueue";
127         }
128         return($action);
129     }
132     function editEntry($action="",$target=array(),$all=array(), $altTabClass ="", $altTabType = "", $altAclCategory="")
133     {
134         $str = management::editEntry($action,$target);
135         if($str) return($str);
137         if(preg_match("/^edit_/",$action)){
138             $tab = preg_replace("/^edit_/","",$action); 
139             if(isset($this->tabObject->by_object[$tab])){
140                 $this->tabObject->current = $tab;
141             }else{
142                 trigger_error("Unknown tab: ".$tab);
143             }
144         }
145     }
148     function closeDialogs()
149     {
150         management::closeDialogs();
151         $this->pwd_change_queue = array();
152     }
155     /*! \brief  Sends a message to a set of users using gosa-si events.
156      */ 
157     function sendMessage($action="",$target=array(),$all=array())
158     {
159         if(class_available("DaemonEvent")){
160             $uids = array();
161             $ldap = $this->config->get_ldap_link();
162             $ldap->cd($this->config->current['BASE']);
163             foreach($target as $dn){
164                 $ldap->cat($dn,array('uid'));
165                 $attrs = $ldap->fetch();
166                 if(isset($attrs['uid'][0])){
167                     $uids[] = $attrs['uid'][0];
168                 }
169             }
170             if(count($uids)){
171                 $events = DaemonEvent::get_event_types(USER_EVENT);
172                 $event = "DaemonEvent_notify";
173                 if(isset($events['BY_CLASS'][$event])){
174                     $type = $events['BY_CLASS'][$event];
175                     $this->dialogObject = new $type['CLASS_NAME']($this->config);
176                     $this->dialogObject->add_users($uids);
177                     $this->dialogObject->set_type(SCHEDULED_EVENT);
178                 }
179             }
180         }
181     }
184     /*! \brief  Sends a message to a set of users using gosa-si events.
185      */ 
186     function saveEventDialog()
187     {
188         $this->dialogObject->save_object();
189         $msgs = $this->dialogObject->check();
190         if(count($msgs)){
191             msg_dialog::displayChecks($msgs);
192         }else{
193             $o_queue = new gosaSupportDaemon();
194             $o_queue->append($this->dialogObject);
195             if($o_queue->is_error()){
196                 msg_dialog::display(_("Infrastructure error"), msgPool::siError($o_queue->get_error()),ERROR_DIALOG);
197             }
198             $this->closeDialogs();
199         }
200     }
203     /*! \brief  Intiates template creation. 
204      */ 
205     function newTemplate($action,$entry)
206     {
207         $this->newEntry();
208         $this->tabObject->set_template_mode ();
209     }
212     /*! \brief  Queues a set of users for password changes
213      */ 
214     function changePassword($action="",$target=array(),$all=array())
215     {
216         $this->dn ="";
217         $this->pwd_change_queue = $target;
219         // Check permisions
220         $disallowed = array();
221         foreach($this->pwd_change_queue as $key => $dn){
222             if(!preg_match("/w/",$this->ui->get_permissions($dn,$this->aclCategory."/password"))){
223                 unset($this->pwd_change_queue[$key]);
224                 $disallowed[] = $dn; 
225             }
226         }
227         if(count($disallowed)){
228             msg_dialog::display(_("Permission"),msgPool::permModify($disallowed),INFO_DIALOG);
229         }
231         // Now display change dialog.
232         return($this->handlePasswordQueue()); 
233     }
237     function refreshProposal()
238     {
239         $this->proposal = passwordMethod::getPasswordProposal($this->config);
240         $this->proposalEnabled = (!empty($this->proposal));
241     }
244     function handlePasswordQueue()
245     {
246         // skip if nothing is to do
247         if(empty($this->dn) && !count($this->pwd_change_queue)) return;
249         // Refresh proposal if requested
250         if(isset($_POST['refreshProposal'])) $this->refreshProposal();
251         if(isset($_POST['proposalSelected'])) $this->proposalSelected = get_post('proposalSelected') == 1;
253         $this->enforcePasswordChange = isset($_POST['new_password']) && isset($_POST['enforcePasswordChange']);
255         $smarty = get_smarty();
256         $smarty->assign("proposal" , set_post($this->proposal));
257         $smarty->assign("proposalEnabled" , $this->proposalEnabled);
258         $smarty->assign("proposalSelected" , $this->proposalSelected);
260         $smarty->assign("passwordChangeForceable" , $this->passwordChangeForceable);
261         $smarty->assign("enforcePasswordChange" , $this->enforcePasswordChange);
263         // Get next entry from queue.
264         if(empty($this->dn) && count($this->pwd_change_queue)){
266             // Generate new proposal
267             $this->refreshProposal();
268             $this->proposalSelected = ($this->proposal != "");
269             $this->dn = array_pop($this->pwd_change_queue);
271             // Check if we are able to enforce a password change
272             $ldap = $this->config->get_ldap_link();
273             $ldap->cd($this->config->current['BASE']);
274             $ldap->cat($this->dn);
275             $attrs = $ldap->fetch();
276             $this->passwordChangeForceable = 
277                     in_array_strict('sambaAccount', $attrs['objectClass']) || 
278                     (in_array_strict('posixAccount', $attrs['objectClass']) && isset($attrs['shadowMax']));
279             $smarty->assign("passwordChangeForceable" , $this->passwordChangeForceable);
280             $smarty->assign("enforcePasswordChange" , $this->enforcePasswordChange);
282             // Assign proposal variables
283             $smarty->assign("proposal" , set_post($this->proposal));
284             $smarty->assign("proposalEnabled" , $this->proposalEnabled);
285             $smarty->assign("proposalSelected" , $this->proposalSelected);
287             set_object_info($this->dn);
288             return ($smarty->fetch(get_template_path('password.tpl', TRUE)));
289         }
291         // If we've just refreshed the proposal then do not check the password for validity.
292         if(isset($_POST['refreshProposal'])){
293             return ($smarty->fetch(get_template_path('password.tpl', TRUE)));
294         }
296         // Check permissions
297         if(isset($_POST['password_finish'])){
299             $dn  = $this->dn;
300             $acl = $this->ui->get_permissions($dn, "users/password");
301             $cacl= $this->ui->get_permissions($dn, "users/user");
302             if (preg_match('/w/', $acl) || preg_match('/c/', $cacl)){
304                 // Get posted passwords
305                 if($this->proposalSelected){
306                     $new_password = $this->proposal;
307                     $repeated_password = $this->proposal;
308                 }else{
309                     $new_password = get_post('new_password');
310                     $repeated_password = get_post('repeated_password');
311                 }
313                 // Check posted passwords now.            
314                 $message= array();
315                 if ($new_password != $repeated_password){
316                     $message[]= _("The passwords you've entered as 'New password' and 'Repeated new password' do not match.");
317                 } else {
318                     if ($new_password == ""){
319                         $message[] = msgPool::required(_("New password"));
320                     }
321                 }
323                 // Call external check hook to validate the password change
324                 if(!count($message)){
325                     $attrs = array();
326                     $attrs['current_password'] = '';
327                     $attrs['new_password'] = $new_password;
328                     $checkRes = password::callCheckHook($this->config,$this->dn,$attrs);
329                     if(count($checkRes)){
330                         $message[] = sprintf(_("Check-hook reported a problem: %s. Password change canceled!"), 
331                                 implode($checkRes));
332                     }
333                 }
335                 // Display errors
336                 if (count($message) != 0){
337                     msg_dialog::displayChecks($message);
338                     return($smarty->fetch(get_template_path('password.tpl', TRUE)));
339                 }
343                 // Change password 
344                 if(isset($this->force_hash_type[$this->dn])){
345                     if(!change_password ($this->dn, $new_password,0,$this->force_hash_type[$this->dn],'', $message)){
346                         msg_dialog::displayChecks(array($message));
347                         return($smarty->fetch(get_template_path('password.tpl', TRUE)));
348                     }
349                 }else{
350                     if(!change_password ($this->dn, $new_password,0,'','',$message)){
351                         msg_dialog::displayChecks(array($message));
352                         return($smarty->fetch(get_template_path('password.tpl', TRUE)));
353                     }
354                 }
355         
356                 // The user has to change his password on next login
357                 // - We are going to update samba and posix attributes here, to enforce
358                 //   such a password change.
359                 if($this->passwordChangeForceable && $this->enforcePasswordChange){
361                     // Check if we are able to enforce a password change
362                     $ldap = $this->config->get_ldap_link();
363                     $ldap->cd($this->config->current['BASE']);
364                     $ldap->cat($this->dn);
365                     $attrs = $ldap->fetch();
366                     $samba = in_array_strict('sambaSamAccount', $attrs['objectClass']);
367                     $posix = in_array_strict('posixAccount', $attrs['objectClass']);
369                     // Update the posix shadow flag...
370                     if($posix){
372                         $current= floor(date("U") /60 /60 /24);
373                         $enforceDate = $current -  $attrs['shadowMax'][0];
374                         $new_attrs = array();
375                         $new_attrs['shadowLastChange'] = $enforceDate;
376                         $ldap->cd($this->dn);
377                         $ldap->modify($new_attrs);
379 #                       $posixAccount = new posixAccount($this->config, $this->dn);
380 #                       $posixAccount->is_modified=TRUE;
381 #                       $posixAccount->activate_shadowExpire=1;
382 #                       $posixAccount->shadowExpire = date('d.m.Y', time() - (1 * 24 * 60 *60));
383 #                       $posixAccount->save();
384                     }
385                    
386                     // Update the samba kickoff flag...
387                     if($samba){
388                         $sambaAccount = new sambaAccount($this->config, $this->dn);
389                         $sambaAccount->is_modified=TRUE;
390                         $sambaAccount->flag_enforcePasswordChange = TRUE;
391                         $sambaAccount->flag_cannotChangePassword = FALSE;
392                         $sambaAccount->save();
393                     }
394                 }
396                 new log("modify","users/".get_class($this),$this->dn,array(),"Password has been changed");
397                 $this->dn ="";
399             } else {
400                 msg_dialog::display(_("Password change"),
401                         _("You have no permission to change this users password!"),
402                         WARNING_DIALOG);
403             }
404         }
406         // Cleanup
407         if(!count($this->pwd_change_queue) && $this->dn=""){
408             $this->remove_lock();
409             $this->closeDialogs();
410         }else{
411             return($this->handlePasswordQueue());
412         }
413     }
416     /*! \brief  Save user modifications. 
417      *          Whenever we save a 'new' user, request a password change for him.
418      */ 
419     function saveChanges()
420     {
421         $str = management::saveChanges();
423         if(!empty($str)) return($str);
425         if($this->last_tabObject instanceOf multi_plug){
426             foreach($this->last_tabObject->a_handles as $user){
427                 if($user->password_change_needed()){
428                     $this->force_hash_type[$user->dn] = $user->by_object['user']->pw_storage;
429                     $this->pwd_change_queue[] = $user->dn;
430                 }
431             }
432             return($this->handlePasswordQueue());
433         }
435         if(isset($this->last_tabObject->by_object['user']) && $this->last_tabObject->by_object['user']->password_change_needed()){
436             $this->force_hash_type[$this->last_tabObject->dn] = $this->last_tabObject->by_object['user']->pw_storage;
437             $this->pwd_change_queue[] = $this->last_tabObject->dn;
438             return($this->handlePasswordQueue());
439         }
440     }
442     function cancelEdit()
443     {
444         $str = management::cancelEdit();
445         if(!empty($str)) return($str);
447         if(isset($this->last_tabObject->by_object['user']) && 
448                 $this->last_tabObject->by_object['user']->dn != "new" &&  
449                 $this->last_tabObject->by_object['user']->password_change_needed()){
450             $this->force_hash_type[$this->last_tabObject->dn] = $this->last_tabObject->by_object['user']->pw_storage;
451             $this->pwd_change_queue[] = $this->last_tabObject->dn;
452             return($this->handlePasswordQueue());
453         }
454     }
457     /*! \brief  Intiates user creation. 
458      *          If we've user templates, then the user will be asked to use to use one. 
459      *          -> See 'templateContinue' for further handling.
460      */ 
461     function newUserFromTemplate($action="",$target=array(),$all=array())
462     {
463         // Call parent method, it knows whats to do, locking and so on ...
464         $str = management::newEntry($action,$target,$all);
465         if(!empty($str)) return($str);
467         // Reset uid selection.
468         $this->got_uid= "";
470         // Use template if there are any of them 
471         $templates = array();
472         $templates['none']= _("none");
473         $templates = array_merge($templates,$this->get_templates());
475         // We've templates, so preset the current template and display the input dialog.
476         if (count($templates)){
477             $smarty = get_smarty();
478             foreach(array("sn", "givenName", "uid", "got_uid") as $attr){
479                 $smarty->assign("$attr", "");
480             }
481             $smarty->assign("template",  array_pop($target));
482             $smarty->assign("templates", $templates);
483             $smarty->assign("edit_uid", "");
484             $smarty->assign("allowUidProposalModification", $this->config->get_cfg_value("core","allowUidProposalModification"));
485             return($smarty->fetch(get_template_path('template.tpl', TRUE)));
487             // -> See 'templateContinue' for further handling!
488         }
489     }
493     /*! \brief  Intiates user creation. 
494      *          If we've user templates, then the user will be asked 
495      *           if he wants to use one. 
496      *          -> See 'templateContinue' for further handling.
497      */ 
498     function newEntry($action="",$target=array(),$all=array(), $altTabClass ="", $altTabType = "", $altAclCategory="")
499     {
501         // Call parent method, it manages everything, locking, object creation...
502         $str = management::newEntry($action,$target,$all);
503         if(!empty($str)) return($str);
505         // If we've at least one template, then ask the user if he wants to use one?
506         $templates = array();
507         $templates['none']= _("none");
508         $templates = array_merge($templates,$this->get_templates());
510         // Display template selection
511         if (count($templates) > 1){
512             $smarty = get_smarty();
514             // Set default variables, normally empty.
515             foreach(array("sn", "givenName", "uid", "got_uid") as $attr){
516                 $smarty->assign($attr, "");
517             }
518             $smarty->assign("template", "none");
519             $smarty->assign("templates", $templates);
520             $smarty->assign("edit_uid", "");
521             $smarty->assign("allowUidProposalModification", $this->config->get_cfg_value("core","allowUidProposalModification"));
522             return($smarty->fetch(get_template_path('template.tpl', TRUE)));
524             // -> See 'templateContinue' for further handling!
525         }
526     }
529     /* !\brief  This method is called whenever a template selection was displayed.
530      *          Here we act on the use selection. 
531      *          - Does the user want to create a user from template?
532      *          - Create user without template?
533      *          - Input correct, every value given and valid? 
534      */ 
535     function templateContinue()
536     {
537         // Get the list of available templates.
538         $templates = array();
539         $templates['none']= _("none");
540         $templates = array_merge($templates,$this->get_templates());
542         // Input validation, if someone wants to create a user from a template
543         //  then validate the given values.
544         $message = array();
545         if(!isset($_POST['template']) || (empty($_POST['template']))){
546             $message[]= msgPool::invalid(_("Template"));
547         }
548         if(!isset($_POST['sn']) || (empty($_POST['sn']))){
549             $message[]= msgPool::required(_("Name"));
550         }
551         if(!isset($_POST['givenName']) || (empty($_POST['givenName']))){
552             $message[]= msgPool::required(_("Given name"));
553         }
555         /********************
556          * 1   We've had input errors - Display errors and show input dialog again. 
557          ********************/
559         if (count($message) > 0){
560             msg_dialog::displayChecks($message);
562             // Preset input fields with user input. 
563             $smarty = get_smarty();
564             foreach(array("sn", "givenName", "uid", "template") as $attr){
565                 if(isset($_POST[$attr])){
566                     $smarty->assign("$attr", set_post(get_post($attr)));
567                 }else{
568                     $smarty->assign("$attr", "");
569                 }
570             }
572             $smarty->assign("templates",$templates);
573             $smarty->assign("got_uid", $this->got_uid);
574             $smarty->assign("edit_uid",false);
575             $smarty->assign("allowUidProposalModification", $this->config->get_cfg_value("core","allowUidProposalModification"));
576             return($smarty->fetch(get_template_path('template.tpl', TRUE)));
577         }
579         /********************
580          * 2   There was a template selected, now ask for the uid.
581          ********************/
583         if ($_POST['template'] != 'none' && !isset($_POST['uid'])){
585             // Remember user input.
586             $smarty = get_smarty();
587             $this->sn             = get_post('sn');
588             $this->givenName      = get_post('givenName');
590             // Avoid duplicate entries, check if such a user already exists.
591             $dn= preg_replace("/^[^,]+,/i", "", get_post('template'));
592             $ldap= $this->config->get_ldap_link();
593             $ldap->cd ($dn);
594             $ldap->search ("(&(sn=".normalizeLdap($this->sn).")(givenName=".normalizeLdap($this->givenName)."))", array("givenName"));
596             if ($ldap->count () != 0){
597                 msg_dialog::displayChecks(array(msgPool::duplicated(_("Name"))));
598                 $smarty->assign("edit_uid", "");
599             }else{
601                 // Preset uid field by using the idGenerator 
602                 $attributes= array('sn' => $this->sn, 'givenName' => $this->givenName);
603                 if ($this->config->get_cfg_value("core","idGenerator") != ""){
604                     $genStr = $this->config->get_cfg_value("core","idGenerator");
605                     $smarty->assign("edit_uid", "");
606                     if(!empty($genStr)){
607                         $uids= gen_uids($genStr, $attributes);
608                         if (count($uids)){
609                             $smarty->assign("edit_uid", "false");
610                             $smarty->assign("uids", $uids);
611                             $this->uid= current($uids);
612                         }else{
613                             msg_dialog::displayChecks(array(_("Cannot generate a unique id, please specify it manually!")));
614                         }
615                     }
616                 } else {
617                     $smarty->assign("edit_uid", "");
618                     $this->uid= "";
619                 }
620                 $this->got_uid= true;
621             }
623             // Assign user input 
624             foreach(array("sn", "givenName", "uid", "got_uid") as $attr){
625                 $smarty->assign("$attr", set_post($this->$attr));
626             }
627             if (isset($_POST['template'])){
628                 $smarty->assign("template", get_post('template'));
629             }
630             $smarty->assign("templates",$templates); 
631             $smarty->assign("allowUidProposalModification", $this->config->get_cfg_value("core","allowUidProposalModification"));
632             return($smarty->fetch(get_template_path('template.tpl', TRUE)));
633         }
636         /********************
637          * 3   No template - Ok. Lets fill the data into the user object and skip templating here. 
638          ********************/
639         if (get_post('template') == 'none'){
640             foreach(array("sn", "givenName", "uid") as $attr){
641                 if (isset($_POST[$attr])){
642                     $this->tabObject->by_object['user']->$attr= get_post($attr);
643                 }
644             }
646             // The user Tab object is already instantiated, so just go back and let the 
647             //  management class do the rest.
648             return("");
649         }
652         /********************
653          * 4   Template selected and uid given - Ok, then lets adapt tempalte values. 
654          ********************/
655         if(isset($_POST['uid'])){
657             // Move user supplied data to sub plugins 
658             foreach(array("uid","sn","givenName") as $attr){
659                 $this->$attr = get_post($attr);
660                 $this->tabObject->$attr       = $this->$attr;
661                 $this->tabObject->by_object['user']->$attr = $this->$attr;
662             }
664             // Adapt template values.
665             $template_dn              = get_post('template');
666             $this->tabObject->adapt_from_template($template_dn, array("uid","cn","givenName","sn"));
667             $template_base            = preg_replace("/^[^,]+,".preg_quote(get_people_ou(), '/i')."/", '', $template_dn);
668             $this->tabObject->by_object['user']->base= $template_base;
670             // The user Tab object is already instantiated, so just go back and let the 
671             //  management class do the rest.
672             return("");
673         }
674     }
677     /* !\brief  This method applies a template to a set of users.
678      */ 
679     function templatizeUsers($action="",$target=array(),$all=array())
680     {
681         $this->dns = array();
682         if(count($target)){
684             // Get the list of available templates.
685             $templates = $this->get_templates();
687             // Check entry locking
688             foreach($target as $dn){
689                 if (($user= get_lock($dn)) != ""){
690                     $this->dn = $dn;
691                     return(gen_locked_message ($user, $dn));
692                 }
693                 $this->dns[] = $dn;
694             }
696             // Display template
697             $smarty = get_smarty();
698             $smarty->assign("templates", $templates);
699             return($smarty->fetch(get_template_path('templatize.tpl', TRUE)));
700         }
701     }
704     /* !\brief  This method is called whenever the templatize dialog was used.
705      */ 
706     function templatizeContinue()
707     {
708         // Template readable? 
709         $template= get_post('template');
710         $acl = $this->ui->get_permissions($template, $this->aclCategory."/".$this->aclPlugin);
711         if (preg_match('/r/', $acl)){
712             $tab = $this->tabClass;
713             foreach ($this->dns as $dn){
715                 // User writeable
716                 $acl = $this->ui->get_permissions($dn,  $this->aclCategory."/".$this->aclPlugin);
717                 if (preg_match('/w/', $acl)){
718                     $this->tabObject= new $tab($this->config, $this->config->data['TABS'][$this->tabType], $dn, $this->aclCategory);
719                     $this->tabObject->adapt_from_template($template, array("sn", "givenName", "uid"));
720                     $this->tabObject->save();
721                 } else {
722                     msg_dialog::display(_("Permission error"), msgPool::permModify($dn), ERROR_DIALOG);
723                 }
724             }
725         } else {
726             msg_dialog::display(_("Permission error"), msgPool::permView($template), ERROR_DIALOG);
727         }
729         // Cleanup!
730         $this->remove_lock(); 
731         $this->closeDialogs();
732     }
735     /* !\brief  Lock/unlock multiple users.
736      */ 
737     function lockUsers($action,$target,$all)
738     {
739         if(!count($target)) return;
740         if($action == "lockUsers"){
741             $this->lockEntry($action,$target, $all, "lock");
742         }else{
743             $this->lockEntry($action,$target, $all, "unlock");
744         }
745     }
748     /* !\brief  Locks/unlocks the given user(s).
749      */ 
750     function lockEntry($action,$entry, $all, $type = "toggle")
751     {
753         // Filter out entries we are not allowed to modify
754         $disallowed = array();
755         $dns = array();
756         foreach($entry as $dn){
757             if (!preg_match("/w/",$this->ui->get_permissions($dn,"users/password"))){
758                 $disallowed[] = $dn;
759             }else{
760                 $allowed[] = $dn;
761             }
762         }
763         if(count($disallowed)){
764             msg_dialog::display(_("Permission"),msgPool::permDelete($disallowed),INFO_DIALOG);
765         }
767         // Try to lock/unlock the rest of the entries.
768         $ldap = $this->config->get_ldap_link();
769         foreach($allowed as $dn){
770             $ldap->cat($dn, array('userPassword'));
771             if($ldap->count() == 1){
773                 // We can't lock empty passwords.
774                 $val = $ldap->fetch();
775                 if(!isset($val['userPassword'])){
776                     continue;
777                 }
779                 // Detect the password method and try to lock/unlock.
780                 $pwd = $val['userPassword'][0];
781                 $method = passwordMethod::get_method($pwd,$val['dn']);
782                 $success= true;
783                 if($method instanceOf passwordMethod){
784                     if($type == "toggle"){
785                         if($method->is_locked($this->config,$val['dn'])){
786                             $success= $method->unlock_account($this->config,$val['dn']);
787                         }else{
788                             $success= $method->lock_account($this->config,$val['dn']);
789                         }
790                     }elseif($type == "lock" && !$method->is_locked($this->config,$val['dn'])){
791                         $success= $method->lock_account($this->config,$val['dn']);
792                     }elseif($type == "unlock" && $method->is_locked($this->config,$val['dn'])){
793                         $success= $method->unlock_account($this->config,$val['dn']);
794                     }
796                     // Check if everything went fine.
797                     if (!$success){
798                         $hn= $method->get_hash_name();
799                         if (is_array($hn)){
800                             $hn= $hn[0];
801                         }
802                         msg_dialog::display(_("Account locking"),
803                                 sprintf(_("Password method '%s' does not support locking. Account (%s) has not been locked!"), 
804                                     $hn,$dn),WARNING_DIALOG);
805                     }
806                 }else{
807                     // Can't lock unknown methods.
808                 }
809             }
810         }
811     }
814     /* !\brief  This method returns a list of all available templates.
815      */ 
816     function get_templates()
817     {
818         $templates= array();
819         $ldap= $this->config->get_ldap_link();
820         foreach ($this->config->departments as $key => $value){
821             $acl = $this->ui->get_permissions($value,$this->aclCategory."/".$this->aclPlugin);
822             if (preg_match("/c/",$acl)){
824                 // Search all templates from the current dn.
825                 $ldap->cd (get_people_ou().$value);
826                 $ldap->search ("(objectClass=gosaUserTemplate)", array("uid"));
827                 if ($ldap->count() != 0){
828                     while ($attrs= $ldap->fetch()){
829                         $templates[$ldap->getDN()]= $attrs['uid'][0]." - ".LDAP::fix($key);
830                     }
831                 }
832             }
833         }
834         natcasesort ($templates);
835         reset ($templates);
836         return($templates);
837     }
840     function copyPasteHandler($action="",$target=array(),$all=array(),
841             $altTabClass ="", $altTabType = "", $altAclCategory="",$altAclPlugin="")
842     {
843         if ($this->config->boolValueIsTrue("core", "copyPaste")){
844             $this->cpHandler->lastdn = "";
845             $str = management::copyPasteHandler($action,$target,$all);
846             if($this->cpHandler->lastdn != "" && isset($_POST['passwordTodo']) && $_POST['passwordTodo'] == "new"){
847                 $this->pwd_change_queue[] = $this->cpHandler->lastdn;
848                 return($this->handlePasswordQueue());
849             }
850             return($str);
851         }
853         return "";
854     }
857     static function filterLockImage($userPassword)
858     {
859         $image= "images/empty.png";
860         if(isset($userPassword[0]) && preg_match("/^\{[^\}]/",$userPassword[0])){
861             if(preg_match("/^[^\}]*+\}!/",$userPassword[0])){
862                 $image= "images/lists/locked.png";
863             }else{
864                 $image= "images/lists/unlocked.png";
865             }
866         }
867         return $image;
868     }
871     static function filterLockLabel($userPassword)
872     {
873         $label= "";
874         if(isset($userPassword[0]) && preg_match("/^\{[^\}]/",$userPassword[0])){
875             if(preg_match("/^[^\}]*+\}!/",$userPassword[0])){
876                 $label= _("Unlock account")."<rowClass:entry-locked/><rowLabel:locked/>";
877             }else{
878                 $label= _("Lock account");
879             }
880         }
881         return $label;
882     }
885     static function filterProperties($row, $classes)
886     {
887         $result= "";
888         $map= array( "gosaAccount" => array( "image" => "plugins/users/images/select_user.png",
889                     "plugin" => "user",
890                     "alt" => _("Generic"),
891                     "title" => _("Edit generic properties")),
892                 "posixAccount" => array("image" => "images/penguin.png",
893                     "plugin" => "posixAccount",
894                     "alt" => _("POSIX"),
895                     "title" => _("Edit POSIX properties")),
896                 "gosaMailAccount" => array("image" => "images/mailto.png",
897                     "alt" => _("Mail"),
898                     "plugin" => "mailAccount",
899                     "title" => _("Edit mail properties")),
900                 "sambaSamAccount" => array("image" => "plugins/systems/images/select_winstation.png",
901                     "plugin" => "sambaAccount",
902                     "alt" => _("Samba"),
903                     "title" => _("Edit samba properties")),
904                 "apple-user" => array("image" => "plugins/netatalk/images/select_netatalk.png",
905                     "plugin" => "netatalk",
906                     "alt" => _("Netatalk"),
907                     "title" => _("Edit Netatalk properties")),
908                 "gotoEnvironment" => array("image" => "plugins/users/images/small_environment.png",
909                     "plugin" => "environment",
910                     "alt" => _("Environment"),
911                     "title" => _("Edit environment properties")),
912                 "goFaxAccount" => array("image" => "plugins/users/images/fax_small.png",
913                         "plugin" => "gofaxAccount",
914                         "alt" => _("FAX"),
915                         "title" => _("Edit FAX properties")),
916                 "goFonAccount" => array("image" => "plugins/gofon/images/select_phone.png",
917                         "plugin" => "phoneAccount",
918                         "alt" => _("Phone"),
919                         "title" => _("Edit phone properties")));
921         // Walk thru map
922         foreach ($map as $oc => $properties) {
923             if (in_array_ics($oc, $classes)) {
924                 $result.= image($properties['image'], "listing_edit_".$properties['plugin']."_$row", $properties['title']);
925             } else {
926                 $result.= image('images/empty.png');
927             }
928         }
929         return $result;
930     }
932
933 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
934 ?>