Code

Updated management class
[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();
37   // Tab definition 
38   protected $tabClass = "usertabs";
39   protected $tabType = "USERTABS";
40   protected $aclCategory = "users";
41   protected $aclPlugin   = "user";
42   protected $objectName   = "user";
44   function __construct($config,$ui)
45   {
46     $this->config = $config;
47     $this->ui = $ui;
48    
49     $this->storagePoints = array(get_ou("userRDN"));
50  
51     // Build filter
52     $filter = new filter(get_template_path("user-filter.xml", true));
53     $filter->setObjectStorage($this->storagePoints);
54     $this->setFilter($filter);
56     // Build headpage
57     $headpage = new listing(get_template_path("user-list.xml", true));
58     $headpage->registerElementFilter("lockLabel", "userManagement::filterLockLabel");
59     $headpage->registerElementFilter("lockImage", "userManagement::filterLockImage");
60     $headpage->setFilter($filter);
62     // Add copy&paste and snapshot handler.
63     if ($this->config->boolValueIsTrue("main", "copyPaste")){
64       $this->cpHandler = new CopyPasteHandler($this->config);
65     }
66     if($this->config->get_cfg_value("enableSnapshots") == "true"){
67       $this->snapHandler = new SnapshotHandler($this->config);
68     }
70     parent::__construct($config, $ui, "users", $headpage);
72     $this->registerAction("new",    "newEntry");
73     $this->registerAction("edit",   "editEntry");
74     $this->registerAction("apply",  "applyChanges");
75     $this->registerAction("save",   "saveChanges");
76     $this->registerAction("cancel", "cancelEdit");
77     $this->registerAction("remove", "removeEntryRequested");
78     $this->registerAction("removeConfirmed", "removeEntryConfirmed");
80     $this->registerAction("copy",   "copyPasteHandler");
81     $this->registerAction("cut",    "copyPasteHandler");
82     $this->registerAction("paste",  "copyPasteHandler");
84     $this->registerAction("snapshot",    "createSnapshotDialog");
85     $this->registerAction("restore",     "restoreSnapshotDialog");
86     $this->registerAction("saveSnapshot","saveSnapshot");
87     $this->registerAction("restoreSnapshot","restoreSnapshot");
88     $this->registerAction("cancelSnapshot","closeDialogs");
90     // Register special user actions 
91     $this->registerAction("lock",   "lockEntry");
92     $this->registerAction("lockUsers",   "lockUsers");
93     $this->registerAction("unlockUsers", "lockUsers");
94     $this->registerAction("new_template", "newTemplate");
95     $this->registerAction("newfromtpl", "newUserFromTemplate");
96     $this->registerAction("templateContinue", "templateContinue");
97     $this->registerAction("templatize", "templatizeUsers");
98     $this->registerAction("templatizeContinue", "templatizeContinue");
100     $this->registerAction("password", "changePassword");
101     $this->registerAction("passwordQueue", "handlePasswordQueue");
102     $this->registerAction("passwordCancel", "closeDialogs");
104     $this->registerAction("sendMessage", "sendMessage");
105     $this->registerAction("saveEventDialog", "saveEventDialog");
106     $this->registerAction("abortEventDialog", "closeDialogs");
107   }
110   // Inject user actions 
111   function detectPostActions()
112   {
113     $action = management::detectPostActions();
114     if(isset($_POST['template_continue'])) $action['action'] = "templateContinue";
115     if(isset($_POST['templatize_continue'])) $action['action'] = "templatizeContinue";
116     if(isset($_POST['save_event_dialog'])) $action['action'] = "saveEventDialog";
117     if(isset($_POST['abort_event_dialog'])) $action['action'] = "abortEventDialog";
118     if(isset($_POST['password_cancel'])){
119       $action['action'] = "passwordCancel";
120     }elseif((count($this->pwd_change_queue) || isset($_POST['password_finish']))){
121       $action['action'] = "passwordQueue";
122     }
123     return($action);
124   }
127   function closeDialogs()
128   {
129     management::closeDialogs();
130     $this->pwd_change_queue = array();
131   }
132     
134   /*! \brief  Sends a message to a set of users using gosa-si events.
135    */ 
136   function sendMessage($action="",$target=array(),$all=array())
137   {
138     if(class_available("DaemonEvent")){
139       $uids = array();
140       $ldap = $this->config->get_ldap_link();
141       $ldap->cd($this->config->current['BASE']);
142       foreach($target as $dn){
143         $ldap->cat($dn,array('uid'));
144         $attrs = $ldap->fetch();
145         if(isset($attrs['uid'][0])){
146           $uids[] = $attrs['uid'][0];
147         }
148       }
149       if(count($uids)){
150         $events = DaemonEvent::get_event_types(USER_EVENT);
151         $event = "DaemonEvent_notify";
152         if(isset($events['BY_CLASS'][$event])){
153           $type = $events['BY_CLASS'][$event];
154           $this->dialogObject = new $type['CLASS_NAME']($this->config);
155           $this->dialogObject->add_users($uids);
156           $this->dialogObject->set_type(SCHEDULED_EVENT);
157         }
158       }
159     }
160   }
163   /*! \brief  Sends a message to a set of users using gosa-si events.
164    */ 
165   function saveEventDialog()
166   {
167     $this->dialogObject->save_object();
168     $msgs = $this->dialogObject->check();
169     if(count($msgs)){
170       msg_dialog::displayChecks($msgs);
171     }else{
172       $o_queue = new gosaSupportDaemon();
173       $o_queue->append($this->dialogObject);
174       if($o_queue->is_error()){
175         msg_dialog::display(_("Infrastructure error"), msgPool::siError($o_queue->get_error()),ERROR_DIALOG);
176       }
177       $this->closeDialogs();
178     }
179   }
182   /*! \brief  Intiates template creation. 
183    */ 
184   function newTemplate($action,$entry)
185   {
186     $this->newEntry();
187     $this->tabObject->set_template_mode ();
188   }
191   /*! \brief  Queues a set of users for password changes
192    */ 
193   function changePassword($action="",$target=array(),$all=array())
194   {
195     $this->dn ="";
196     $this->pwd_change_queue = $target;
198     // Check permisions
199     $disallowed = array();
200     foreach($this->pwd_change_queue as $key => $dn){
201       if(!preg_match("/w/",$this->ui->get_permissions($dn,$this->aclCategory."/password"))){
202         unset($this->pwd_change_queue[$key]);
203         $disallowed[] = $dn; 
204       }
205     }
206     if(count($disallowed)){
207       msg_dialog::display(_("Permission"),msgPool::permModify($disallowed),INFO_DIALOG);
208     }
210     // Now display change dialog.
211     return($this->handlePasswordQueue()); 
212   }
215   function handlePasswordQueue()
216   {
217     // Get next entry from queue.
218     if(empty($this->dn) && count($this->pwd_change_queue)){
219       $this->dn = array_pop($this->pwd_change_queue);
220       set_object_info($this->dn);
221       $smarty = get_smarty();
222       return ($smarty->fetch(get_template_path('password.tpl', TRUE)));
223     }
225     // Check permissions
226     $dn  = $this->dn;
227     $acl = $this->ui->get_permissions($dn, "users/password");
228     $cacl= $this->ui->get_permissions($dn, "users/user");
229     if (preg_match('/w/', $acl) || preg_match('/c/', $cacl)){
230       $message= array();
231       if ($_POST['new_password'] != $_POST['repeated_password']){
232         $message[]= _("The passwords you've entered as 'New password' and 'Repeated new password' do not match.");
233       } else {
234         if ($_POST['new_password'] == ""){
235           $message[] = msgPool::required(_("New password"));
236         }
237       }
239       // Display errors
240       if (count($message) != 0){
241         msg_dialog::displayChecks($message);
242         $smarty = get_smarty();
243         return($smarty->fetch(get_template_path('password.tpl', TRUE)));
244       }
246       // Change cassword 
247       if(!change_password ($this->dn, $_POST['new_password'])){
248         return($smarty->fetch(get_template_path('password.tpl', TRUE)));
249       }
250       if ($this->config->get_cfg_value("passwordHook") != ""){
251         exec($this->config->get_cfg_value("passwordHook")." ".$username." ".$_POST['new_password'], $resarr);
252       }
253       new log("modify","users/".get_class($this),$this->dn,array(),"Password has been changed");
254       $this->dn ="";
255       
256     } else {
257       msg_dialog::display(_("Password change"),
258           _("You have no permission to change this users password!"),
259           WARNING_DIALOG);
260     }
262     // Cleanup
263     if(!count($this->pwd_change_queue)){
264       $this->remove_lock();
265       $this->closeDialogs();
266     }else{
267       return($this->handlePasswordQueue());
268     }
269   }
272   /*! \brief  Save user modifications. 
273    *          Whenever we save a 'new' user, request a password change for him.
274    */ 
275   function saveChanges()
276   {
277     management::saveChanges();
278     if($this->last_dn == "new"){
279       $this->pwd_change_queue[] = $this->last_tabObject->dn;
280       return($this->handlePasswordQueue());
281     }
282   }
285   /*! \brief  Intiates user creation. 
286    *          If we've user templates, then the user will be asked to use to use one. 
287    *          -> See 'templateContinue' for further handling.
288    */ 
289   function newUserFromTemplate($action="",$target=array(),$all=array())
290   {
291     // Call parent method, it knows whats to do, locking and so on ...
292     management::newEntry($action,$target,$all);
294     // Reset uid selection.
295     $this->got_uid= "";
297     // Use template if there are any of them 
298     $templates = array();
299     $templates['none']= _("none");
300     $templates = array_merge($templates,$this->get_templates());
302     // We've templates, so preset the current template and display the input dialog.
303     if (count($templates)){
304       $smarty = get_smarty();
305       foreach(array("sn", "givenName", "uid", "got_uid") as $attr){
306         $smarty->assign("$attr", "");
307       }
308       $smarty->assign("template",  array_pop($target));
309       $smarty->assign("templates", $templates);
310       $smarty->assign("edit_uid", "");
311       return($smarty->fetch(get_template_path('template.tpl', TRUE)));
313       // -> See 'templateContinue' for further handling!
314     }
315   }
319   /*! \brief  Intiates user creation. 
320    *          If we've user templates, then the user will be asked 
321    *           if he wants to use one. 
322    *          -> See 'templateContinue' for further handling.
323    */ 
324   function newEntry($action="",$target=array(),$all=array())
325   {
326   
327     // Call parent method, it manages everything, locking, object creation...
328     management::newEntry($action,$target,$all);
329     
330     // If we've at least one template, then ask the user if he wants to use one?
331     $templates = array();
332     $templates['none']= _("none");
333     $templates = array_merge($templates,$this->get_templates());
335     // Display template selection
336     if (count($templates)){
337       $smarty = get_smarty();
338   
339       // Set default variables, normally empty.
340       foreach(array("sn", "givenName", "uid", "got_uid") as $attr){
341         $smarty->assign($attr, "");
342       }
343       $smarty->assign("template", "none");
344       $smarty->assign("templates", $templates);
345       $smarty->assign("edit_uid", "");
346       return($smarty->fetch(get_template_path('template.tpl', TRUE)));
348       // -> See 'templateContinue' for further handling!
349     }
350   }
353   /* !\brief  This method is called whenever a template selection was displayed.
354    *          Here we act on the use selection. 
355    *          - Does the user want to create a user from template?
356    *          - Create user without template?
357    *          - Input correct, every value given and valid? 
358    */ 
359   function templateContinue()
360   {
361     // Get the list of available templates.
362     $templates = array();
363     $templates['none']= _("none");
364     $templates = array_merge($templates,$this->get_templates());
366     // Input validation, if someone wants to create a user from a template
367     //  then validate the given values.
368     $message = array();
369     if(!isset($_POST['template']) || (empty($_POST['template']))){
370       $message[]= msgPool::invalid(_("Template"));
371     }
372     if(!isset($_POST['sn']) || (empty($_POST['sn']))){
373       $message[]= msgPool::required(_("Name"));
374     }
375     if(!isset($_POST['givenName']) || (empty($_POST['givenName']))){
376       $message[]= msgPool::required(_("Given name"));
377     }
379     /********************
380      * 1   We've had input errors - Display errors and show input dialog again. 
381      ********************/
383     if (count($message) > 0){
384       msg_dialog::displayChecks($message);
386       // Preset input fields with user input. 
387       $smarty = get_smarty();
388       foreach(array("sn", "givenName", "uid", "template") as $attr){
389         if(isset($_POST[$attr])){
390           $smarty->assign("$attr", get_post($attr));
391         }else{
392           $smarty->assign("$attr", "");
393         }
394       }
396       $smarty->assign("templates",$templates);
397       $smarty->assign("got_uid", $this->got_uid);
398       $smarty->assign("edit_uid",false);
399       return($smarty->fetch(get_template_path('template.tpl', TRUE)));
400     }
403     /********************
404      * 2   There was a template selected, now ask for the uid.
405      ********************/
407     if ($_POST['template'] != 'none' && !isset($_POST['uid'])){
409       // Remember user input.
410       $smarty = get_smarty();
411       $this->sn             = $_POST['sn'];
412       $this->givenName      = $_POST['givenName'];
414       // Avoid duplicate entries, check if such a user already exists.
415       $dn= preg_replace("/^[^,]+,/i", "", $_POST['template']);
416       $ldap= $this->config->get_ldap_link();
417       $ldap->cd ($dn);
418       $ldap->search ("(&(sn=".normalizeLdap($this->sn).")(givenName=".normalizeLdap($this->givenName)."))", array("givenName"));
419       if ($ldap->count () != 0){
420         msg_dialog::displayChecks(array(msgPool::duplicated(_("Name"))));
421       }else{
423         // Preset uid field by using the idGenerator 
424         $attributes= array('sn' => $this->sn, 'givenName' => $this->givenName);
425         if ($this->config->get_cfg_value("idGenerator") != ""){
426           $uids= gen_uids ($this->config->get_cfg_value("idGenerator"), $attributes);
427           if (count($uids)){
428             $smarty->assign("edit_uid", "false");
429             $smarty->assign("uids", $uids);
430             $this->uid= current($uids);
431           }
432         } else {
433           $smarty->assign("edit_uid", "");
434           $this->uid= "";
435         }
436         $this->got_uid= true;
437       }
439       // Assign user input 
440       foreach(array("sn", "givenName", "uid", "got_uid") as $attr){
441         $smarty->assign("$attr", $this->$attr);
442       }
443       if (isset($_POST['template'])){
444         $smarty->assign("template", $_POST['template']);
445       }
446       $smarty->assign("templates",$templates); 
447       return($smarty->fetch(get_template_path('template.tpl', TRUE)));
448     }
451     /********************
452      * 3   No template - Ok. Lets fill the data into the user object and skip templating here. 
453      ********************/
454     if ($_POST['template'] == 'none'){
455       foreach(array("sn", "givenName", "uid") as $attr){
456         if (isset($_POST[$attr])){
457           $this->tabObject->by_object['user']->$attr= $_POST[$attr];
458         }
459       }
460       
461       // The user Tab object is already instantiated, so just go back and let the 
462       //  management class do the rest.
463       return("");
464     }
467     /********************
468      * 4   Template selected and uid given - Ok, then lets adapt tempalte values. 
469      ********************/
470     if(isset($_POST['uid'])){
472       // Move user supplied data to sub plugins 
473       foreach(array("uid","sn","givenName") as $attr){
474         $this->$attr = $_POST[$attr];
475         $this->tabObject->$attr       = $this->$attr;
476         $this->tabObject->by_object['user']->$attr = $this->$attr;
477       }
479       // Adapt template values.
480       $template_dn              = $_POST['template'];
481       $this->tabObject->adapt_from_template($template_dn, array("uid","cn","givenName","sn"));
482       $template_base            = preg_replace("/^[^,]+,".preg_quote(get_people_ou(), '/')."/", '', $template_dn);
483       $this->tabObject->by_object['user']->base= $template_base;
485       // The user Tab object is already instantiated, so just go back and let the 
486       //  management class do the rest.
487       return("");
488     }
489   }
492   /* !\brief  This method applies a template to a set of users.
493    */ 
494   function templatizeUsers($action="",$target=array(),$all=array())
495   {
496     $this->dns = array();
497     if(count($target)){
499       // Get the list of available templates.
500       $templates = $this->get_templates();
502       // Check entry locking
503       foreach($target as $dn){
504         if (($user= get_lock($dn)) != ""){
505           return(gen_locked_message ($user, $dn));
506         }
507         $this->dns[] = $dn;
508       }
509           
510       // Display template
511       $smarty = get_smarty();
512       $smarty->assign("templates", $templates);
513       return($smarty->fetch(get_template_path('templatize.tpl', TRUE)));
514     }
515   }
518   /* !\brief  This method is called whenever the templatize dialog was used.
519    */ 
520   function templatizeContinue()
521   {
522     // Template readable? 
523     $template= get_post('template');
524     $acl = $this->ui->get_permissions($template, $this->aclCategory."/".$this->aclPlugin);
525     if (preg_match('/r/', $acl)){
526       $tab = $this->tabClass;
527       foreach ($this->dns as $dn){
529         // User writeable
530         $acl = $this->ui->get_permissions($dn,  $this->aclCategory."/".$this->aclPlugin);
531         if (preg_match('/w/', $acl)){
532           $this->tabObject= new $tab($this->config, $this->config->data['TABS'][$this->tabType], $dn, $this->aclCategory);
533           $this->tabObject->adapt_from_template($template, array("sn", "givenName", "uid"));
534           $this->tabObject->save();
535         } else {
536           msg_dialog::display(_("Permission error"), msgPool::permModify($dn), ERROR_DIALOG);
537         }
538       }
539     } else {
540       msg_dialog::display(_("Permission error"), msgPool::permView($template), ERROR_DIALOG);
541     }
543     // Cleanup!
544     $this->remove_lock(); 
545     $this->closeDialogs();
546   }
549   /* !\brief  Lock/unlock multiple users.
550    */ 
551   function lockUsers($action,$target,$all)
552   {
553     if($action == "lockUsers"){
554       $this->lockEntry($action,$target, $all, "lock");
555     }else{
556       $this->lockEntry($action,$target, $all, "unlock");
557     }
558   }
560   
561   /* !\brief  Locks/unlocks the given user(s).
562    */ 
563   function lockEntry($action,$entry, $all, $type = "toggle")
564   {
565     
566     // Filter out entries we are not allowed to modify
567     $disallowed = array();
568     $dns = array();
569     foreach($entry as $dn){
570       if (!preg_match("/w/",$this->ui->get_permissions($dn,"users/password"))){
571         $disallowed[] = $dn;
572       }else{
573         $allowed[] = $dn;
574       }
575     }
576     if(count($disallowed)){
577       msg_dialog::display(_("Permission"),msgPool::permDelete($disallowed),INFO_DIALOG);
578     }
580     // Try to lock/unlock the rest of the entries.
581     $ldap = $this->config->get_ldap_link();
582     foreach($allowed as $dn){
583       $ldap->cat($dn, array('userPassword'));
584       if($ldap->count() == 1){
586         // We can't lock empty passwords.
587         $val = $ldap->fetch();
588         if(!isset($val['userPassword'])){
589           continue;
590         }
592         // Detect the password method and try to lock/unlock.
593         $pwd = $val['userPassword'][0];
594         $method = passwordMethod::get_method($pwd,$val['dn']);
595         $success= true;
596         if($method instanceOf passwordMethod){
597           if($type == "toggle"){
598             if($method->is_locked($this->config,$val['dn'])){
599               $success= $method->unlock_account($this->config,$val['dn']);
600             }else{
601               $success= $method->lock_account($this->config,$val['dn']);
602             }
603           }elseif($type == "lock" && !$method->is_locked($this->config,$val['dn'])){
604             $success= $method->lock_account($this->config,$val['dn']);
605           }elseif($type == "unlock" && $method->is_locked($this->config,$val['dn'])){
606             $success= $method->unlock_account($this->config,$val['dn']);
607           }
609           // Check if everything went fine.
610           if (!$success){
611             $hn= $method->get_hash_name();
612             if (is_array($hn)){
613               $hn= $hn[0];
614             }
615             msg_dialog::display(_("Account locking"),
616                 sprintf(_("Password method '%s' does not support locking. Account (%s) has not been locked!"), 
617                   $hn,$dn),WARNING_DIALOG);
618           }
619         }else{
620           // Can't lock unknown methods.
621         }
622       }
623     }
624   }
627   /* !\brief  This method returns a list of all available templates.
628    */ 
629   function get_templates()
630   {
631     $templates= array();
632     $ldap= $this->config->get_ldap_link();
633     foreach ($this->config->departments as $key => $value){
634       $acl = $this->ui->get_permissions($value,$this->aclCategory."/".$this->aclPlugin);
635       if (preg_match("/c/",$acl)){
637         // Search all templates from the current dn.
638         $ldap->cd (get_people_ou().$value);
639         $ldap->search ("(objectClass=gosaUserTemplate)", array("uid"));
640         if ($ldap->count() != 0){
641           while ($attrs= $ldap->fetch()){
642             $templates[$ldap->getDN()]= $attrs['uid'][0]." - ".LDAP::fix($key);
643           }
644         }
645       }
646     }
647     natcasesort ($templates);
648     reset ($templates);
649     return($templates);
650   }
653   static function filterLockImage($userPassword)
654   {
655     $image= "images/empty.png";
656     if(isset($userPassword[0]) && preg_match("/^\{[^\}]/",$userPassword[0])){
657       if(preg_match("/^[^\}]*+\}!/",$userPassword[0])){
658         $image= "images/lists/locked.png";
659       }else{
660         $image= "images/lists/unlocked.png";
661       }
662     }
663     return $image;
664   }
667   static function filterLockLabel($userPassword)
668   {
669     $label= "";
670     if(isset($userPassword[0]) && preg_match("/^\{[^\}]/",$userPassword[0])){
671       if(preg_match("/^[^\}]*+\}!/",$userPassword[0])){
672         $label= _("Unlock account");
673       }else{
674         $label= _("Lock account");
675       }
676     }
677     return $label;
678   }
679
680 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
681 ?>