Code

Updated in
[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 users";
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;
53   function __construct($config,$ui)
54   {
55     $this->config = $config;
56     $this->ui = $ui;
57    
58     $this->storagePoints = array(get_ou("userRDN"));
59  
60     // Build filter
61     if (session::global_is_set(get_class($this)."_filter")){
62       $filter= session::global_get(get_class($this)."_filter");
63     } else {
64       $filter = new filter(get_template_path("user-filter.xml", true));
65       $filter->setObjectStorage($this->storagePoints);
66     }
67     $this->setFilter($filter);
69     // Build headpage
70     $headpage = new listing(get_template_path("user-list.xml", true));
71     $headpage->registerElementFilter("lockLabel", "userManagement::filterLockLabel");
72     $headpage->registerElementFilter("lockImage", "userManagement::filterLockImage");
73     $headpage->registerElementFilter("filterProperties", "userManagement::filterProperties");
74     $headpage->setFilter($filter);
76     // Add copy&paste and snapshot handler.
77     if ($this->config->boolValueIsTrue("main", "copyPaste")){
78       $this->cpHandler = new CopyPasteHandler($this->config);
79     }
80     if($this->config->get_cfg_value("enableSnapshots") == "true"){
81       $this->snapHandler = new SnapshotHandler($this->config);
82     }
84     parent::__construct($config, $ui, "users", $headpage);
86     // Register special user actions 
87     $this->registerAction("lock",   "lockEntry");
88     $this->registerAction("lockUsers",   "lockUsers");
89     $this->registerAction("unlockUsers", "lockUsers");
90     $this->registerAction("new_template", "newTemplate");
91     $this->registerAction("newfromtpl", "newUserFromTemplate");
92     $this->registerAction("templateContinue", "templateContinue");
93     $this->registerAction("templatize", "templatizeUsers");
94     $this->registerAction("templatizeContinue", "templatizeContinue");
96     $this->registerAction("password", "changePassword");
97     $this->registerAction("passwordQueue", "handlePasswordQueue");
98     $this->registerAction("passwordCancel", "closeDialogs");
100     $this->registerAction("sendMessage", "sendMessage");
101     $this->registerAction("saveEventDialog", "saveEventDialog");
102     $this->registerAction("abortEventDialog", "closeDialogs");
104     // Register shortcut icon actions 
105     $this->registerAction("edit_user","editEntry");
106     $this->registerAction("edit_posixAccount","editEntry");
107     $this->registerAction("edit_mailAccount","editEntry");
108     $this->registerAction("edit_sambaAccount","editEntry");
109     $this->registerAction("edit_netatalk","editEntry");
110     $this->registerAction("edit_environment","editEntry");
111     $this->registerAction("edit_gofaxAccount","editEntry");
112     $this->registerAction("edit_phoneAccount","editEntry");
113   }
116   function refreshProposal()
117   {
118     $this->proposal = passwordMethod::getPasswordProposal($this->config);
119     $this->proposalEnabled = (!empty($this->proposal));
120   }
123   // Inject user actions 
124   function detectPostActions()
125   {
126     $action = management::detectPostActions();
127     if(isset($_POST['template_continue'])) $action['action'] = "templateContinue";
128     if(isset($_POST['templatize_continue'])) $action['action'] = "templatizeContinue";
129     if(isset($_POST['save_event_dialog'])) $action['action'] = "saveEventDialog";
130     if(isset($_POST['abort_event_dialog'])) $action['action'] = "abortEventDialog";
131     if(isset($_POST['password_cancel'])){
132       $action['action'] = "passwordCancel";
133     }elseif((count($this->pwd_change_queue) || isset($_POST['password_finish']) || isset($_POST['refreshProposal']))){
134       $action['action'] = "passwordQueue";
135     }
136     return($action);
137   }
140   function editEntry($action="",$target=array(),$all=array(), $altTabClass ="", $altTabType = "", $altAclCategory="")
141   {
142     $str = management::editEntry($action,$target);
143     if($str) return($str);
145     if(preg_match("/^edit_/",$action)){
146       $tab = preg_replace("/^edit_/","",$action); 
147       if(isset($this->tabObject->by_object[$tab])){
148         $this->tabObject->current = $tab;
149       }else{
150         trigger_error("Unknown tab: ".$tab);
151       }
152     }
153   }
155   
156   function closeDialogs()
157   {
158     management::closeDialogs();
159     $this->pwd_change_queue = array();
160   }
161     
163   /*! \brief  Sends a message to a set of users using gosa-si events.
164    */ 
165   function sendMessage($action="",$target=array(),$all=array())
166   {
167     if(class_available("DaemonEvent")){
168       $uids = array();
169       $ldap = $this->config->get_ldap_link();
170       $ldap->cd($this->config->current['BASE']);
171       foreach($target as $dn){
172         $ldap->cat($dn,array('uid'));
173         $attrs = $ldap->fetch();
174         if(isset($attrs['uid'][0])){
175           $uids[] = $attrs['uid'][0];
176         }
177       }
178       if(count($uids)){
179         $events = DaemonEvent::get_event_types(USER_EVENT);
180         $event = "DaemonEvent_notify";
181         if(isset($events['BY_CLASS'][$event])){
182           $type = $events['BY_CLASS'][$event];
183           $this->dialogObject = new $type['CLASS_NAME']($this->config);
184           $this->dialogObject->add_users($uids);
185           $this->dialogObject->set_type(SCHEDULED_EVENT);
186         }
187       }
188     }
189   }
192   /*! \brief  Sends a message to a set of users using gosa-si events.
193    */ 
194   function saveEventDialog()
195   {
196     $this->dialogObject->save_object();
197     $msgs = $this->dialogObject->check();
198     if(count($msgs)){
199       msg_dialog::displayChecks($msgs);
200     }else{
201       $o_queue = new gosaSupportDaemon();
202       $o_queue->append($this->dialogObject);
203       if($o_queue->is_error()){
204         msg_dialog::display(_("Infrastructure error"), msgPool::siError($o_queue->get_error()),ERROR_DIALOG);
205       }
206       $this->closeDialogs();
207     }
208   }
211   /*! \brief  Intiates template creation. 
212    */ 
213   function newTemplate($action,$entry)
214   {
215     $this->newEntry();
216     $this->tabObject->set_template_mode ();
217   }
220   /*! \brief  Queues a set of users for password changes
221    */ 
222   function changePassword($action="",$target=array(),$all=array())
223   {
224     $this->dn ="";
225     $this->pwd_change_queue = $target;
227     // Check permisions
228     $disallowed = array();
229     foreach($this->pwd_change_queue as $key => $dn){
230       if(!preg_match("/w/",$this->ui->get_permissions($dn,$this->aclCategory."/password"))){
231         unset($this->pwd_change_queue[$key]);
232         $disallowed[] = $dn; 
233       }
234     }
235     if(count($disallowed)){
236       msg_dialog::display(_("Permission"),msgPool::permModify($disallowed),INFO_DIALOG);
237     }
239     // Now display change dialog.
240     return($this->handlePasswordQueue()); 
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" , $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" , $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               // Display errors
324               if (count($message) != 0){
325                   msg_dialog::displayChecks($message);
326                   return($smarty->fetch(get_template_path('password.tpl', TRUE)));
327               }
329               // Change password
330               if(isset($this->force_hash_type[$this->dn])){
331                   if(!change_password ($this->dn, $new_password,0,$this->force_hash_type[$this->dn])){
332                       return($smarty->fetch(get_template_path('password.tpl', TRUE)));
333                   }
334               }else{
335                   if(!change_password ($this->dn, $new_password)){
336                       return($smarty->fetch(get_template_path('password.tpl', TRUE)));
337                   }
338               }
339               if ($this->config->get_cfg_value("passwordHook") != ""){
340                   $ldap = $this->config->get_ldap_link();
341                   $ldap->cd($this->config->current['BASE']);
342                   $ldap->cat($this->dn,array('uid'));
343                   $attrs = $ldap->fetch();
344                   exec($this->config->get_cfg_value("passwordHook")." ".
345                           escapeshellarg($attrs['uid'][0])." ".escapeshellarg($new_password), $resarr);
346                   $check_hook_output = "";
347                   if(count($resarr) > 0) {
348                       $check_hook_output= join('\n', $resarr);
349                   }
350                   if(!empty($check_hook_output)){
351                       $message[] = sprintf(_("Check-hook reported a problem: %s. Password change canceled!"),$check_hook_output);
352                       msg_dialog::displayChecks($message);
353                       return($smarty->fetch(get_template_path('password.tpl', TRUE)));
354                   }
355               }
358               // The user has to change his password on next login
359               // - We are going to update samba and posix attributes here, to enforce
360               //   such a password change.
361               if($this->passwordChangeForceable && $this->enforcePasswordChange){
363                   // Check if we are able to enforce a password change
364                   $ldap = $this->config->get_ldap_link();
365                   $ldap->cd($this->config->current['BASE']);
366                   $ldap->cat($this->dn);
367                   $attrs = $ldap->fetch();
368                   $samba = in_array_strict('sambaSamAccount', $attrs['objectClass']);
369                   $posix = in_array_strict('posixAccount', $attrs['objectClass']);
371                   // Update the posix shadow flag...
372                   if($posix){
373                       $current= floor(date("U") /60 /60 /24);
374                       $enforceDate = $current -  $attrs['shadowMax'][0];
375                       $new_attrs = array();
376                       $new_attrs['shadowLastChange'] = $enforceDate;
377                       $ldap->cd($this->dn);
378                       $ldap->modify($new_attrs);
380 #                     $posixAccount = new posixAccount($this->config, $this->dn);
381 #                     $posixAccount->is_modified=TRUE;
382 #                     $posixAccount->activate_shadowExpire=1;
383 #                     $posixAccount->shadowExpire = date('d.m.Y', time() - (1 * 24 * 60 *60));
384 #                     $posixAccount->save();
385                   }
387                   // Update the samba kickoff flag...
388                   if($samba){
389                       $sambaAccount = new sambaAccount($this->config, $this->dn);
390                       $sambaAccount->is_modified=TRUE;
391                       $sambaAccount->flag_enforcePasswordChange = TRUE;
392                       $sambaAccount->flag_cannotChangePassword = FALSE;
393                       $sambaAccount->save();
394                   }
395               }
397               new log("modify","users/".get_class($this),$this->dn,array(),"Password has been changed");
398               $this->dn ="";
400           } else {
401               msg_dialog::display(_("Password change"),
402                       _("You have no permission to change this users password!"),
403                       WARNING_DIALOG);
404           }
405       }
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   }
418   /*! \brief  Save user modifications. 
419    *          Whenever we save a 'new' user, request a password change for him.
420    */ 
421   function saveChanges()
422   {
423     $str = management::saveChanges();
424   
425     if(!empty($str)) return($str);
427     if($this->last_tabObject instanceOf multi_plug){
428       foreach($this->last_tabObject->a_handles as $user){
429         if($user->password_change_needed()){
430           $this->force_hash_type[$user->dn] = $user->by_object['user']->pw_storage;
431           $this->pwd_change_queue[] = $user->dn;
432         }
433       }
434       return($this->handlePasswordQueue());
435     }
437     if(isset($this->last_tabObject->by_object['user']) && $this->last_tabObject->by_object['user']->password_change_needed()){
438       $this->force_hash_type[$this->last_tabObject->dn] = $this->last_tabObject->by_object['user']->pw_storage;
439       $this->pwd_change_queue[] = $this->last_tabObject->dn;
440       return($this->handlePasswordQueue());
441     }
442   }
444   function cancelEdit()
445   {
446     $str = management::cancelEdit();
447     if(!empty($str)) return($str);
449     if(isset($this->last_tabObject->by_object['user']) && 
450         $this->last_tabObject->by_object['user']->dn != "new" &&  
451         $this->last_tabObject->by_object['user']->password_change_needed()){
452       $this->force_hash_type[$this->last_tabObject->dn] = $this->last_tabObject->by_object['user']->pw_storage;
453       $this->pwd_change_queue[] = $this->last_tabObject->dn;
454       return($this->handlePasswordQueue());
455     }
456   }
459   /*! \brief  Intiates user creation. 
460    *          If we've user templates, then the user will be asked to use to use one. 
461    *          -> See 'templateContinue' for further handling.
462    */ 
463   function newUserFromTemplate($action="",$target=array(),$all=array())
464   {
465     // Call parent method, it knows whats to do, locking and so on ...
466     $str = management::newEntry($action,$target,$all);
467     if(!empty($str)) return($str);
469     // Reset uid selection.
470     $this->got_uid= "";
472     // Use template if there are any of them 
473     $templates = array();
474     $templates['none']= _("none");
475     $templates = array_merge($templates,$this->get_templates());
477     // We've templates, so preset the current template and display the input dialog.
478     if (count($templates)){
479       $smarty = get_smarty();
480       foreach(array("sn", "givenName", "uid", "got_uid") as $attr){
481         $smarty->assign("$attr", "");
482       }
483       $smarty->assign("template",  array_pop($target));
484       $smarty->assign("templates", $templates);
485       $smarty->assign("edit_uid", "");
486       $smarty->assign("allowUidProposalModification", $this->config->get_cfg_value("allowUidProposalModification", "false"));
487       return($smarty->fetch(get_template_path('template.tpl', TRUE)));
489       // -> See 'templateContinue' for further handling!
490     }
491   }
495   /*! \brief  Intiates user creation. 
496    *          If we've user templates, then the user will be asked 
497    *           if he wants to use one. 
498    *          -> See 'templateContinue' for further handling.
499    */ 
500   function newEntry($action="",$target=array(),$all=array(), $altTabClass ="", $altTabType = "", $altAclCategory="")
501   {
502   
503     // Call parent method, it manages everything, locking, object creation...
504     $str = management::newEntry($action,$target,$all);
505     if(!empty($str)) return($str);
506     
507     // If we've at least one template, then ask the user if he wants to use one?
508     $templates = array();
509     $templates['none']= _("none");
510     $templates = array_merge($templates,$this->get_templates());
512     // Display template selection
513     if (count($templates) > 1){
514       $smarty = get_smarty();
515   
516       // Set default variables, normally empty.
517       foreach(array("sn", "givenName", "uid", "got_uid") as $attr){
518         $smarty->assign($attr, "");
519       }
520       $smarty->assign("template", "none");
521       $smarty->assign("templates", $templates);
522       $smarty->assign("edit_uid", "");
523       $smarty->assign("allowUidProposalModification", $this->config->get_cfg_value("allowUidProposalModification", "false"));
524       return($smarty->fetch(get_template_path('template.tpl', TRUE)));
526       // -> See 'templateContinue' for further handling!
527     }
528   }
531   /* !\brief  This method is called whenever a template selection was displayed.
532    *          Here we act on the use selection. 
533    *          - Does the user want to create a user from template?
534    *          - Create user without template?
535    *          - Input correct, every value given and valid? 
536    */ 
537   function templateContinue()
538   {
539     // Get the list of available templates.
540     $templates = array();
541     $templates['none']= _("none");
542     $templates = array_merge($templates,$this->get_templates());
544     // Input validation, if someone wants to create a user from a template
545     //  then validate the given values.
546     $message = array();
547     if(!isset($_POST['template']) || (empty($_POST['template']))){
548       $message[]= msgPool::invalid(_("Template"));
549     }
550     if(!isset($_POST['sn']) || (empty($_POST['sn']))){
551       $message[]= msgPool::required(_("Name"));
552     }
553     if(!isset($_POST['givenName']) || (empty($_POST['givenName']))){
554       $message[]= msgPool::required(_("Given name"));
555     }
557     /********************
558      * 1   We've had input errors - Display errors and show input dialog again. 
559      ********************/
561     if (count($message) > 0){
562       msg_dialog::displayChecks($message);
564       // Preset input fields with user input. 
565       $smarty = get_smarty();
566       foreach(array("sn", "givenName", "uid", "template") as $attr){
567         if(isset($_POST[$attr])){
568           $smarty->assign("$attr", get_post($attr));
569         }else{
570           $smarty->assign("$attr", "");
571         }
572       }
574       $smarty->assign("templates",$templates);
575       $smarty->assign("got_uid", $this->got_uid);
576       $smarty->assign("edit_uid",false);
577       $smarty->assign("allowUidProposalModification", $this->config->get_cfg_value("allowUidProposalModification", "false"));
578       return($smarty->fetch(get_template_path('template.tpl', TRUE)));
579     }
582     /********************
583      * 2   There was a template selected, now ask for the uid.
584      ********************/
586     if ($_POST['template'] != 'none' && !isset($_POST['uid'])){
588       // Remember user input.
589       $smarty = get_smarty();
590       $this->sn             = $_POST['sn'];
591       $this->givenName      = $_POST['givenName'];
593       // Avoid duplicate entries, check if such a user already exists.
594       $dn= preg_replace("/^[^,]+,/i", "", $_POST['template']);
595       $ldap= $this->config->get_ldap_link();
596       $ldap->cd ($dn);
597       $ldap->search ("(&(sn=".normalizeLdap($this->sn).")(givenName=".normalizeLdap($this->givenName)."))", array("givenName"));
598       if ($ldap->count () != 0){
599         msg_dialog::displayChecks(array(msgPool::duplicated(_("Name"))));
600       }else{
602         // Preset uid field by using the idGenerator 
603         $attributes= array('sn' => $this->sn, 'givenName' => $this->givenName);
604         if ($this->config->get_cfg_value("idGenerator") != ""){
605           $uids= gen_uids ($this->config->get_cfg_value("idGenerator"), $attributes);
606           if (count($uids)){
607             $smarty->assign("edit_uid", "false");
608             $smarty->assign("uids", $uids);
609             $this->uid= current($uids);
610           }
611         } else {
612           $smarty->assign("edit_uid", "");
613           $this->uid= "";
614         }
615         $this->got_uid= true;
616       }
618       // Assign user input 
619       foreach(array("sn", "givenName", "uid", "got_uid") as $attr){
620         $smarty->assign("$attr", $this->$attr);
621       }
622       if (isset($_POST['template'])){
623         $smarty->assign("template", $_POST['template']);
624       }
625       $smarty->assign("templates",$templates); 
626       $smarty->assign("allowUidProposalModification", $this->config->get_cfg_value("allowUidProposalModification", "false"));
627       return($smarty->fetch(get_template_path('template.tpl', TRUE)));
628     }
631     /********************
632      * 3   No template - Ok. Lets fill the data into the user object and skip templating here. 
633      ********************/
634     if ($_POST['template'] == 'none'){
635       foreach(array("sn", "givenName", "uid") as $attr){
636         if (isset($_POST[$attr])){
637           $this->tabObject->by_object['user']->$attr= $_POST[$attr];
638         }
639       }
640       
641       // The user Tab object is already instantiated, so just go back and let the 
642       //  management class do the rest.
643       return("");
644     }
647     /********************
648      * 4   Template selected and uid given - Ok, then lets adapt tempalte values. 
649      ********************/
650     if(isset($_POST['uid'])){
652       // Move user supplied data to sub plugins 
653       foreach(array("uid","sn","givenName") as $attr){
654         $this->$attr = $_POST[$attr];
655         $this->tabObject->$attr       = $this->$attr;
656         $this->tabObject->by_object['user']->$attr = $this->$attr;
657       }
659       // Adapt template values.
660       $template_dn              = $_POST['template'];
661       $this->tabObject->adapt_from_template($template_dn, array("uid","cn","givenName","sn"));
662       $template_base            = preg_replace("/^[^,]+,".preg_quote(get_people_ou(), '/i')."/", '', $template_dn);
663       $this->tabObject->by_object['user']->base= $template_base;
665       // The user Tab object is already instantiated, so just go back and let the 
666       //  management class do the rest.
667       return("");
668     }
669   }
672   /* !\brief  This method applies a template to a set of users.
673    */ 
674   function templatizeUsers($action="",$target=array(),$all=array())
675   {
676     $this->dns = array();
677     if(count($target)){
679       // Get the list of available templates.
680       $templates = $this->get_templates();
682       // Check entry locking
683       foreach($target as $dn){
684         if (($user= get_lock($dn)) != ""){
685           $this->dn = $dn;
686           return(gen_locked_message ($user, $dn));
687         }
688         $this->dns[] = $dn;
689       }
690           
691       // Display template
692       $smarty = get_smarty();
693       $smarty->assign("templates", $templates);
694       return($smarty->fetch(get_template_path('templatize.tpl', TRUE)));
695     }
696   }
699   /* !\brief  This method is called whenever the templatize dialog was used.
700    */ 
701   function templatizeContinue()
702   {
703     // Template readable? 
704     $template= get_post('template');
705     $acl = $this->ui->get_permissions($template, $this->aclCategory."/".$this->aclPlugin);
706     if (preg_match('/r/', $acl)){
707       $tab = $this->tabClass;
708       foreach ($this->dns as $dn){
710         // User writeable
711         $acl = $this->ui->get_permissions($dn,  $this->aclCategory."/".$this->aclPlugin);
712         if (preg_match('/w/', $acl)){
713           $this->tabObject= new $tab($this->config, $this->config->data['TABS'][$this->tabType], $dn, $this->aclCategory);
714           $this->tabObject->adapt_from_template($template, array("sn", "givenName", "uid"));
715           $this->tabObject->save();
716         } else {
717           msg_dialog::display(_("Permission error"), msgPool::permModify($dn), ERROR_DIALOG);
718         }
719       }
720     } else {
721       msg_dialog::display(_("Permission error"), msgPool::permView($template), ERROR_DIALOG);
722     }
724     // Cleanup!
725     $this->remove_lock(); 
726     $this->closeDialogs();
727   }
730   /* !\brief  Lock/unlock multiple users.
731    */ 
732   function lockUsers($action,$target,$all)
733   {
734     if(!count($target)) return;
735     if($action == "lockUsers"){
736       $this->lockEntry($action,$target, $all, "lock");
737     }else{
738       $this->lockEntry($action,$target, $all, "unlock");
739     }
740   }
742   
743   /* !\brief  Locks/unlocks the given user(s).
744    */ 
745   function lockEntry($action,$entry, $all, $type = "toggle")
746   {
747     
748     // Filter out entries we are not allowed to modify
749     $disallowed = array();
750     $dns = array();
751     foreach($entry as $dn){
752       if (!preg_match("/w/",$this->ui->get_permissions($dn,"users/password"))){
753         $disallowed[] = $dn;
754       }else{
755         $allowed[] = $dn;
756       }
757     }
758     if(count($disallowed)){
759       msg_dialog::display(_("Permission"),msgPool::permDelete($disallowed),INFO_DIALOG);
760     }
762     // Try to lock/unlock the rest of the entries.
763     $ldap = $this->config->get_ldap_link();
764     foreach($allowed as $dn){
765       $ldap->cat($dn, array('userPassword'));
766       if($ldap->count() == 1){
768         // We can't lock empty passwords.
769         $val = $ldap->fetch();
770         if(!isset($val['userPassword'])){
771           continue;
772         }
774         // Detect the password method and try to lock/unlock.
775         $pwd = $val['userPassword'][0];
776         $method = passwordMethod::get_method($pwd,$val['dn']);
777         $success= true;
778         if($method instanceOf passwordMethod){
779           if($type == "toggle"){
780             if($method->is_locked($this->config,$val['dn'])){
781               $success= $method->unlock_account($this->config,$val['dn']);
782             }else{
783               $success= $method->lock_account($this->config,$val['dn']);
784             }
785           }elseif($type == "lock" && !$method->is_locked($this->config,$val['dn'])){
786             $success= $method->lock_account($this->config,$val['dn']);
787           }elseif($type == "unlock" && $method->is_locked($this->config,$val['dn'])){
788             $success= $method->unlock_account($this->config,$val['dn']);
789           }
791           // Check if everything went fine.
792           if (!$success){
793             $hn= $method->get_hash_name();
794             if (is_array($hn)){
795               $hn= $hn[0];
796             }
797             msg_dialog::display(_("Account locking"),
798                 sprintf(_("Password method '%s' does not support locking. Account (%s) has not been locked!"), 
799                   $hn,$dn),WARNING_DIALOG);
800           }
801         }else{
802           // Can't lock unknown methods.
803         }
804       }
805     }
806   }
809   /* !\brief  This method returns a list of all available templates.
810    */ 
811   function get_templates()
812   {
813     $templates= array();
814     $ldap= $this->config->get_ldap_link();
815     foreach ($this->config->departments as $key => $value){
816       $acl = $this->ui->get_permissions($value,$this->aclCategory."/".$this->aclPlugin);
817       if (preg_match("/c/",$acl)){
819         // Search all templates from the current dn.
820         $ldap->cd (get_people_ou().$value);
821         $ldap->search ("(objectClass=gosaUserTemplate)", array("uid"));
822         if ($ldap->count() != 0){
823           while ($attrs= $ldap->fetch()){
824             $templates[$ldap->getDN()]= $attrs['uid'][0]." - ".LDAP::fix($key);
825           }
826         }
827       }
828     }
829     natcasesort ($templates);
830     reset ($templates);
831     return($templates);
832   }
835   function copyPasteHandler($action="",$target=array(),$all=array(),
836       $altTabClass ="", $altTabType = "", $altAclCategory="",$altAclPlugin="")
837   {
838     if ($this->config->boolValueIsTrue("main", "copyPaste")){
839       $this->cpHandler->lastdn = "";
840       $str = management::copyPasteHandler($action,$target,$all);
841       if($this->cpHandler->lastdn != "" && isset($_POST['passwordTodo']) && $_POST['passwordTodo'] == "new"){
842         $this->pwd_change_queue[] = $this->cpHandler->lastdn;
843         return($this->handlePasswordQueue());
844       }
845       return($str);
846     }
848     return "";
849   }
852   static function filterLockImage($userPassword)
853   {
854     $image= "images/empty.png";
855     if(isset($userPassword[0]) && preg_match("/^\{[^\}]/",$userPassword[0])){
856       if(preg_match("/^[^\}]*+\}!/",$userPassword[0])){
857         $image= "images/lists/locked.png";
858       }else{
859         $image= "images/lists/unlocked.png";
860       }
861     }
862     return $image;
863   }
866   static function filterLockLabel($userPassword)
867   {
868     $label= "";
869     if(isset($userPassword[0]) && preg_match("/^\{[^\}]/",$userPassword[0])){
870       if(preg_match("/^[^\}]*+\}!/",$userPassword[0])){
871         $label= _("Unlock account");
872       }else{
873         $label= _("Lock account");
874       }
875     }
876     return $label;
877   }
880   static function filterProperties($row, $classes)
881   {
882     $result= "";
883     $map= array( "gosaAccount" => array( "image" => "plugins/users/images/select_user.png",
884                                          "plugin" => "user",
885                                          "alt" => _("Generic"),
886                                          "title" => _("Edit generic properties")),
887                  "posixAccount" => array("image" => "images/penguin.png",
888                                          "plugin" => "posixAccount",
889                                          "alt" => _("POSIX"),
890                                          "title" => _("Edit POSIX properties")),
891                  "gosaMailAccount" => array("image" => "images/mailto.png",
892                                          "alt" => _("Mail"),
893                                          "plugin" => "mailAccount",
894                                          "title" => _("Edit mail properties")),
895                  "sambaSamAccount" => array("image" => "plugins/systems/images/select_winstation.png",
896                                          "plugin" => "sambaAccount",
897                                          "alt" => _("Samba"),
898                                          "title" => _("Edit samba properties")),
899                  "apple-user" => array("image" => "plugins/netatalk/images/select_netatalk.png",
900                                          "plugin" => "netatalk",
901                                          "alt" => _("Netatalk"),
902                                          "title" => _("Edit netatalk properties")),
903                  "gotoEnvironment" => array("image" => "plugins/users/images/small_environment.png",
904                                          "plugin" => "environment",
905                                          "alt" => _("Environment"),
906                                          "title" => _("Edit environment properties")),
907                  "goFaxAccount" => array("image" => "plugins/users/images/fax_small.png",
908                                          "plugin" => "gofaxAccount",
909                                          "alt" => _("FAX"),
910                                          "title" => _("Edit FAX properties")),
911                  "goFonAccount" => array("image" => "plugins/gofon/images/select_phone.png",
912                                          "plugin" => "phoneAccount",
913                                          "alt" => _("Phone"),
914                                          "title" => _("Edit phone properties")));
916     // Walk thru map
917     foreach ($map as $oc => $properties) {
918       if (in_array_ics($oc, $classes)) {
919         $result.="<input class='center' type='image' src='".$properties['image']."' ".
920                  "alt='".$properties['alt']."' title='".$properties['title'].
921                  "' name='listing_edit_".$properties['plugin']."_$row' style='padding:1px'>";
922       } else {
923         $result.="<img src='images/empty.png' alt=' ' class='center' style='padding:1px'>";
924       }
925     }
926     return $result;
927   }
929
930 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
931 ?>