Code

Added netatalk share management
[gosa.git] / plugins / admin / users / class_userManagement.inc
1 <?php
2 /*
3    This code is part of GOsa (https://gosa.gonicus.de)
4    Copyright (C) 2003-2006 - Cajus Pollmeier <pollmeier@gonicus.de>
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
21 /* Include user tab class */
22 require "tabs_user.inc";
25 class userManagement extends plugin
26 {
27   /* Plugin definitions */
28   var $plHeadline= "Users";
29   var $plDescription= "This does something";
31   /* Dialog attributes */
32   var $usertab= NULL;
33   var $ui= NULL;
34   var $acl= "";
35   var $templates= array();
36   var $got_uid= false;
37   var $departments= array();
38   var $CopyPasteHandler   = NULL;
39   var $CPPasswordChange   = ""; // Contains the entry id which should get a new password
41   function userManagement($config, $ui)
42   {
43   
44     /* Save configuration for internal use */
45     $this->config= $config;
46     $this->ui= $ui;
48     /* Copy & Paste handler */
49     if ($this->config->boolValueIsTrue("main", "enableCopyPaste")){
50       $this->CopyPasteHandler= new CopyPasteHandler($this->config);
51     }
53     /* Get global filter config */
54     if (!isset($_SESSION["userfilter"])){
55       $base= get_base_from_people($ui->dn);
56       $userfilter= array( "mailusers"       => "checked",
57                           "unixusers"       => "checked",
58                           "templates"       => "",
59                           "subsearch"       => "",
60                           "proxyusers"      => "checked",
61                           "sambausers"      => "checked",
62                           "faxusers"        => "checked",
63                           "functionalusers" => "checked",
64                           "regex"           => "*");
65       $_SESSION["userfilter"]= $userfilter;
66     }
67     
68     /* Transfer global base to dialogs people base */
69     if(!isset($_SESSION['CurrentMainBase'])){
70       $base= get_base_from_people($ui->dn);
71       $_SESSION['CurrentMainBase']= $base;
72     }
74     /* LOCK MESSAGE Vars */
75     $_SESSION['LOCK_VARS_TO_USE'] = array("/^act$/","/^id$/","/^user_edit_/","/^user_del_/");
76   }
79   function execute()
80   {
81     //FIXME: This function lacks structure! It's dammn spaghetti code.
82   
83     /* Call parent execute */
84     plugin::execute();
86     $smarty= get_smarty();                  // Smarty instance
87     $userfilter= get_global("userfilter");  // contains Filter Settings
88     $s_action= "";                          // Contains the action to be taken
89     $s_entry= "";                           // The value for s_action
90     $base_back= "";                         // The Link for Backbutton
92     /* Department folder change requested? */
93     if( isset($_GET['act']) && $_GET['act'] == "dep_open" ){
94       $s_action= "open";
95       $s_entry= base64_decode($_GET['dep_id']);
97       /* Set current main base to the requested department DN */
98       $_SESSION['CurrentMainBase']= $this->config->departments[trim($s_entry)];
99     }
101     /* Edit entry button pressed? */
102     if( isset($_GET['act']) && $_GET['act'] == "edit_entry" ){
103       $s_action= "edit";
104       $s_entry= validate($_GET['id']);
105     }
107     /* Test relevant POST values */  
108     foreach($_POST as $key => $val){
110       /* Get every possible POST combination and set s_action/s_entry accordingly */
111       foreach(array("del"       => "user_del",    "edit"      => "user_edit",
112                     "back"      => "dep_back",    "new"       => "user_new",
113                     "home"      => "dep_home",    "new_tpl"   => "user_tplnew",
114                     "change_pw" => "user_chgpw",  "root"      => "dep_root",
115                     "editPaste" => "editPaste",   "copy"      => "copy",
116                     "cut"       => "cut") as $act => $name){
118         if (preg_match("/".$name.".*/", $key)){
119           $s_action= $act;
120           $s_entry= preg_replace("/".$name."_/i", "", $key);
121           break;
122         }
123       }
124       
125     } /* ...Test POST */
127     /* Remove coordinate prefix from POST, required by some browsers */
128     $s_entry= preg_replace("/_.$/", "", $s_entry);
130     /* Seperate possibly encoded tab and entry, default to tab "user" */
131     if(preg_match("/.*-.*/", $s_entry)){
132       $s_tab= preg_replace("/^[^-]*-/i", "" ,$s_entry);
133       $s_entry= preg_replace("/-[^-]*$/i", "", $s_entry);
134     }else{
135       $s_tab= "user";
136     }
138     /* Department has changed? */
139     if(isset($_POST['CurrentMainBase'])){
140       $_SESSION['CurrentMainBase']= validate($_POST['CurrentMainBase']);
141     }
143     /* Home-button is pressed, move to users home DN */
144     if($s_action == "home"){
145       $_SESSION['CurrentMainBase']= preg_replace('/^[^,]+,'.normalizePreg(get_people_ou()).'/', "", $this->ui->dn);
146     }
148     /* Root-button is pressed, move to root DN */
149     if($s_action == "root"){
150       $_SESSION['CurrentMainBase']= $this->config->current['BASE'];
151     }
153     /* If Back-button is pressed, move back one step in DN */
154     if($s_action == "back"){
155       //FIXME: This is not 100% correct. We'll only display ou's, but there may be
156       //       a step between. You'll stumble in a "hidden" department in this case.
157       $base_back= preg_replace("/^[^,]+,/", "", $_SESSION['CurrentMainBase']);
159       /* The department array keeps non DN entries as index. We need to convert
160          it before checking the existance. */
161       $base_back= trim(convert_department_dn($base_back));
163       /* Check if the department exists, otherwise revert to the configure base DN */
164       if(isset($this->config->departments[$base_back])){
165         $_SESSION['CurrentMainBase']= $this->config->departments[$base_back];
166       }else{
167         $_SESSION['CurrentMainBase']= $this->config->departments['/'];
168       }
169     }
171     $ret = $this->copyPasteHandling($s_action,$s_entry);
172     if($ret){
173       return($ret);
174     }
176     /* Save filter data if we are in the headpage */
177     if(!isset($this->usertab)){
178       $values= array("functionalusers", "unixusers", "mailusers", "sambausers",
179                      "proxyusers", "faxusers", "templates", "subsearch");
180       $userfilter= saveFilter($userfilter, $values);
181       register_global("userfilter", $userfilter);
182     }
184     /* React on user interaction here */
185     if (($_SERVER["REQUEST_METHOD"] == "POST")||($_SERVER["REQUEST_METHOD"]== "GET")){
187       /* User wants to edit data? */
188       if (($s_action=="edit") && (!isset($this->usertab->config))){
190         /* Get 'dn' from posted 'uid', must be unique */
191         $this->dn= $this->list[trim($s_entry)]['dn'];
193         /* Check locking, save current plugin in 'back_plugin', so
194            the dialog knows where to return. */
195         if (($user= get_lock($this->dn)) != ""){
196           return(gen_locked_message ($user, $this->dn));
197         }
199         /* Lock the current entry, so everyone will get the
200            above dialog */
201         add_lock ($this->dn, $this->ui->dn);
203         /* Set up the users ACL's for this 'dn' */
204         $acl= get_permissions ($this->dn, $this->ui->subtreeACL);
206         /* Register usertab to trigger edit dialog */
207         $this->usertab= new usertabs($this->config, 
208                                      $this->config->data['TABS']['USERTABS'], $this->dn);
210         /* Switch tab, in case that was requested by the user */
211         $this->usertab->current = $s_tab;
212         
213         /* Set ACL and move DN to the headline */
214         $this->usertab->set_acl($acl);
215         $_SESSION['objectinfo']= $this->dn;
216       }
217     }
219     /* Reset all relevant data, if we get a _cancel request */
220     if (isset($_POST['edit_cancel']) || isset($_POST['password_cancel'])){
221       if (isset($this->usertab)){
222         del_lock ($this->usertab->dn);
223         unset ($this->usertab);
224       }
225       $this->usertab= NULL;
226       $this->lognames= array();;
227       $this->sn= "";
228       $this->givenName= "";
229       $this->uid= "";
230       unset ($_SESSION['objectinfo']);
231     }
233     /* Password change requested */
234     if (($s_action == "change_pw") || (!empty($this->CPPasswordChange))){
236       if(!empty($this->CPPasswordChange)){
237         $s_entry = $this->CPPasswordChange;
238         $this->CPPasswordChange = "";
239       }
241       /* Get 'dn' from posted 'uid' */
242       $this->dn= $this->list[trim($s_entry)]['dn'];
244       /* Load permissions for selected 'dn' and check if
245          we're allowed to remove this 'dn' */
246       $acl= get_permissions ($this->dn, $this->ui->subtreeACL);
247       $acl= get_module_permission($acl, "user", $this->dn);
248       if (chkacl($acl, "password") == ""){
250         /* User is allowed to change passwords, save 'dn' and 'acl' for next
251            dialog. */
252         $this->acl= $acl;
253         $_SESSION['objectinfo']= $this->dn;
254         return ($smarty->fetch(get_template_path('password.tpl', TRUE)));
256       } else {
257         /* User is not allowed. Show message and cancel. */
258         print_red (_("You are not allowed to set this users password!"));
259       }
260     }
262     /* Perform password change */
263     if (isset($_POST['password_finish'])){
265       /* For security reasons, check if user is allowed to set password again */
266       if (chkacl($this->acl, "password") == "" || chkacl($this->acl, "create")){
268         /* Check input and feed errors into 'message' */
269         $message= array();
271         /* Sanity checks... */
272         if ($_POST['new_password'] != $_POST['repeated_password']){
274           /* Matching passwords in new and repeated? */
275           $message[]= _("The passwords you've entered as 'New password' and 'Repeated new password' do not match.");
276         } else {
278           /* Empty password is not permitted by default. */
279           if ($_POST['new_password'] == ""){
280             $message[]= _("The password you've entered as 'New password' is empty.");
281           }
282         }
284         /* Errors, or password change? */
285         if (count($message) != 0){
287           /* Show error message and continue editing */
288           show_errors ($message);
289           return($smarty->fetch(get_template_path('password.tpl', TRUE)));
290         }
292         $config= $this->config;
293         $ldap_ui= $this->config->get_ldap_link();
294         if(isset($this->usertab->dn)){
295           $user = ($ldap_ui->fetch($ldap_ui->cat($this->usertab->dn)));
296         }else{
297           $user = ($ldap_ui->fetch($ldap_ui->cat($this->dn)));
298         }
299         if((is_array($user))&&(isset($user['uid']))){
300           $username= $user['uid'][0];
301         }
303         /* Set password, perform required steps */
304         if ($this->usertab){
305           if ($this->usertab->password_change_needed()){
306             $obj= $this->usertab->by_object['user'];
307             change_password ($this->usertab->dn, $_POST['new_password'],
308                 0, $obj->pw_storage);
309             if (isset($config->data['MAIN']['EXTERNALPWDHOOK'])){
310               exec($config->data['MAIN']['EXTERNALPWDHOOK']." ".$username." ".$_POST['new_password'], $resarr);
311             }
313             gosa_log ("Password for '".$this->usertab->dn."' has been changed");
314             unset($this->usertab);
315             $this->usertab= NULL;
316           }
317         } else {
318           change_password ($this->dn, $_POST['new_password']);
319           if (isset($config->data['MAIN']['EXTERNALPWDHOOK'])){
320             exec($config->data['MAIN']['EXTERNALPWDHOOK']." ".$username." ".$_POST['new_password'], $resarr);
321           }
323           gosa_log ("Password for '".$this->dn."' has been changed");
324         }
325       } else {
327         /* Missing permissions, show message */
328         print_red (_("You are not allowed to set this users password!"));
329       }
331       /* Clean session, delete lock */
332       del_lock ($this->dn);
333       $this->reload();
334       unset ($this->usertab);
335       $this->usertab= NULL;
336       $this->lognames= array();;
337       $this->sn= "";
338       $this->givenName= "";
339       $this->uid= "";
340       unset ($_SESSION['objectinfo']);
341     }
343     /* Remove user was requested */
344     if ($s_action=="del"){
346       /* Get 'dn' from posted 'uid' */
347       $this->dn= $this->list[trim($s_entry)]['dn'];
349       /* Load permissions for selected 'dn' and check if
350          we're allowed to remove this 'dn' */
351       $acl= get_permissions ($this->dn, $this->ui->subtreeACL);
352       $this->acl= get_module_permission($acl, "user", $this->dn);
353       if (chkacl($this->acl, "delete") == ""){
355         /* Check locking, save current plugin in 'back_plugin', so
356            the dialog knows where to return. */
357         if (($user= get_lock($this->dn)) != ""){
358           return(gen_locked_message ($user, $this->dn));
359         }
361         /* Lock the current entry, so nobody will edit it during deletion */
362         add_lock ($this->dn, $this->ui->dn);
363         $smarty->assign("info", sprintf(_("You're about to delete the user %s."), @LDAP::fix($this->dn)));
364         return($smarty->fetch(get_template_path('remove.tpl', TRUE)));
365       } else {
367         /* Obviously the user isn't allowed to delete. Show message and
368            clean session. */
369         print_red (_("You are not allowed to delete this user!"));
370       }
371     }
373     /* Confirmation for deletion has been passed. User should be deleted. */
374     if (isset($_POST['delete_user_confirm'])){
376       /* Some nice guy may send this as POST, so we've to check
377          for the permissions again. */
378       if (chkacl($this->acl, "delete") == ""){
380         /* Delete request is permitted, perform LDAP action */
381         $this->usertab= new usertabs($this->config, $this->config->data['TABS']['USERTABS'],
382             $this->dn);
383         $this->usertab->set_acl(array($this->acl));
384         $this->usertab->delete ();
385         gosa_log ("User object '".$this->dn."' has been removed");
386         unset ($this->usertab);
387         $this->usertab= NULL;
389         /* User list has changed, reload it. */
390         $this->reload ();
391       } else {
393         /* Normally this shouldn't be reached, send some extra
394            logs to notify the administrator */
395         print_red (_("You are not allowed to delete this user!"));
397         if(isset($this->ui->uid)){
398           gosa_log ("Warning: '".$this->ui->uid."' tried to trick user deletion.");
399         }
400       }
402       /* Remove lock file after successfull deletion */
403       del_lock ($this->dn);
404     }
407     /* Delete user canceled? */
408     if (isset($_POST['delete_cancel'])){
409       del_lock ($this->dn);
410     }
413     /* Finish user edit is triggered by the tabulator dialog, so
414        the user wants to save edited data. Check and save at this
415        point. */
416     if ((isset($_POST['edit_finish'])) && (isset($this->usertab->config))){
418       /* Check tabs, will feed message array */
419       $this->usertab->last= $this->usertab->current;
420       $this->usertab->save_object();
421       $message= $this->usertab->check();
423       /* Save, or display error message? */
424       if (count($message) == 0){
426         /* No errors. Go ahead and prepare to ask for a password
427            in case we're creating a new user. 'dn' will be 'new'
428            in this case. It is set to the correct value later. */
429         if ($this->dn == "new"){
430           $set_pass= 1;
431         } else {
432           $set_pass= 0;
433         }
435         /* Save user data to ldap */
436         if($this->usertab->save() == 1){
437           gosa_log ("User object '".$this->dn."' saving failed.");
438           return;
439         }
440         gosa_log ("User object '".$this->dn."' has been saved");
442         /* User has been saved successfully, remove lock from
443            LDAP. */
444         if ($this->dn != "new"){
445           del_lock ($this->dn);
446         }
448         /* In case of new users, ask for a password */
449         if (($set_pass || $this->usertab->password_change_needed()) &&
450             !$this->is_template){
452           return($smarty->fetch(get_template_path('password.tpl', TRUE)));
453         }
455         /* There's no page reload so we have to read new users at
456            this point. */
457         $this->reload ();
458         unset ($this->usertab);
459         $this->usertab= NULL;
460         unset ($_SESSION['objectinfo']);
462       } else {
463         /* Ok. There seem to be errors regarding to the tab data,
464            show message and continue as usual. */
465         show_errors($message);
466       }
467     }
469     /* Generate template list */
470     if (($s_action=="new")||($s_action=="create_user_from_tpl")){
472       $this->templates= array();
474       $ldap= $this->config->get_ldap_link();
476       /* Create list of tempaltes */
477       foreach ($this->config->departments as $key => $value){
478     
479         /* Get acls from different ou's */
480         $acl= get_permissions (get_people_ou().$value, $this->ui->subtreeACL);
481         $acl= get_module_permission($acl, "user", get_people_ou().$value);
482   
483         /* If creation of a new user is allowed, append this template */
484         if (chkacl($acl, "create") == ""){
485           
486           /* Search all templates from the current dn */
487           $ldap->cd (get_people_ou().$value);
488           $ldap->search ("(objectClass=gosaUserTemplate)", array("uid"));
490           /* Append */
491           if ($ldap->count() != 0){
492             while ($attrs= $ldap->fetch()){
493               $this->templates[$ldap->getDN()]=
494                 $attrs['uid'][0]." - ".@LDAP::fix($key);
495             }
496             $this->templates['none']= _("none");
497           }
498         }
499       }
501       /* Sort templates */
502       natcasesort ($this->templates);
503       reset ($this->templates);
504     }
506     /* New user/template request */
507     if (($s_action=="create_user_from_tpl")||($s_action=="new") || ($s_action=="new_tpl")){
508       /* By default we set 'dn' to 'new', all relevant plugins will
509          react on this. */
510       $this->dn= "new";
511       if (isset($this->config->current['IDGEN'])){
512         $this->got_uid= false;
513       } else {
514         $this->got_uid= true;
515       }
517       /* Create new usertab object */
518       $this->usertab= new usertabs($this->config,
519           $this->config->data['TABS']['USERTABS'], $this->dn);
520       $this->usertab->set_acl(array(':all'));
521       $this->usertab->by_object['user']->base= $_SESSION['CurrentMainBase'];
523       /* Take care about templates */
524       if ($s_action=="new_tpl"){
525         $this->is_template= TRUE;
526         $this->usertab->set_template_mode ();
527       } else {
528         $this->is_template= FALSE;
529       }
531       /* Use template if there are any of them */
532       if ((count($this->templates) && ($s_action!='new_tpl'))||($s_action=="create_user_from_tpl")){
533         foreach(array("sn", "givenName", "uid", "got_uid", "templates") as $attr){
534           $smarty->assign("$attr", $this->$attr);
535         }
536         if ($s_action=="create_user_from_tpl"){
537           $smarty->assign("template", $this->dn= $this->list[trim($s_entry)]['dn']);
538         } else {
539           $smarty->assign("template", "none");
540         }
541         $smarty->assign("edit_uid", "");
542         return($smarty->fetch(get_template_path('template.tpl', TRUE)));
543       }
544     }
546     /* Continue template editing */
547     if ((isset($_POST['template_continue']) && $_POST['template'] != 'none' && !isset($_POST['uid']))){
548       $this->sn= $_POST['sn'];
549       $this->givenName= $_POST['givenName'];
551       /* Check for requred values */
552       $message= array();
553       if ($this->sn == "") {
554         $message[]= _("The required field 'Name' is not set.");
555       }
556       if ($this->givenName == "") {
557         $message[]= _("The required field 'Given name' is not set.");
558       }
560       /* Check if dn is used */
561       $dn= preg_replace("/^[^,]+,/i", "", $_POST['template']);
562       $ldap= $this->config->get_ldap_link();
563       $ldap->cd ($dn);
564       $ldap->search ("(&(sn=".normalizeLdap($this->sn).")(givenName=".normalizeLdap($this->givenName)."))", array("givenName"));
565       if ($ldap->count () != 0){
566         $message[]= _("A person with the choosen name is already used in this tree.");
567       }
569       /* Show error message / continue editing */
570       if (count($message) > 0){
571         show_errors ($message);
572       } else {
573         $attributes= array('sn' => $this->sn, 'givenName' => $this->givenName);
574         if (isset($this->config->current['IDGEN']) &&
575             $this->config->current['IDGEN'] != ""){
576           $uids= gen_uids ($this->config->current['IDGEN'], $attributes);
577           if (count($uids)){
578             $smarty->assign("edit_uid", "false");
579             $smarty->assign("uids", $uids);
580             $this->uid= current($uids);
581           }
582         } else {
583           $smarty->assign("edit_uid", "");
584           $this->uid= "";
585         }
586         $this->got_uid= true;
587       }
589       foreach(array("sn", "givenName", "uid", "got_uid", "templates") as $attr){
590         $smarty->assign("$attr", $this->$attr);
591       }
592       if (isset($_POST['template'])){
593         $smarty->assign("template", $_POST['template']);
594       }
595       return($smarty->fetch(get_template_path('template.tpl', TRUE)));
596     }
598     /* No template. Ok. Lets fill data into the normal user dialog */
599     if (isset($_POST['template_continue']) && $_POST['template'] == 'none'){
600       foreach(array("sn", "givenName", "uid") as $attr){
601         if (isset($_POST[$attr])){
602           $this->usertab->by_object['user']->$attr= $_POST[$attr];
603         }
604       }
605     }
607     /* Finish template preamble */
608     if (isset($_POST['template_continue']) && $_POST['template'] != 'none' && (isset($_POST['uid']))){
610       /* Might not be filled if IDGEN is unset */
611       $this->sn                 = $_POST['sn'];
612       $this->givenName          = $_POST['givenName'];
614       /* Move user supplied data to sub plugins */
615       $this->uid                = $_POST['uid'];
616       $this->usertab->uid       = $this->uid;
617       $this->usertab->sn        = $this->sn;
618       $this->usertab->givenName = $this->givenName;
619       $template_dn              = $_POST['template'];
620       $this->usertab->adapt_from_template($template_dn);
621       $template_base            = preg_replace("/^[^,]+,".normalizePreg(get_people_ou())."/", '', $template_dn);
622       $this->usertab->by_object['user']->base= $template_base;
624       /* Set up the users ACL's for this 'dn' */
625       $acl= get_permissions ($template_base, $this->ui->subtreeACL);
626       $this->usertab->set_acl($acl);
627     }
628     
629     if (isset($_POST['template_continue']) && ($_POST['template'] == 'none')){
630       $this->usertab->by_object['user']->base= $_SESSION['CurrentMainBase'];
631     }
633     /* Show tab dialog if object is present */
634     if(isset($this->usertab->config)){
635       $display= $this->usertab->execute();
637       /* Don't show buttons if tab dialog requests this */
638       if (!$this->usertab->by_object[$this->usertab->current]->dialog){
639         $display.= "<p style=\"text-align:right\">\n";
640         $display.= "<input type=submit name=\"edit_finish\" value=\""._("Save")."\">\n";
641         $display.= "&nbsp;\n";
642         $display.= "<input type=submit name=\"edit_cancel\" value=\""._("Cancel")."\">\n";
643         $display.= "</p>";
644       }
645       return ($display);
646     }
648     /* Reload if we need a reload... */
649     if (!isset($this->usertab) &&
650         !isset($_POST['new_user']) &&
651         !isset($_POST['new_template']) &&
652         !isset($_POST['delete_user']) &&
653         !isset($_POST['setpass_user']) &&
654         !isset($_POST['select_user'])){
655       $this->reload();
656     }
658     /* Check for exeeded sizelimit */
659     if (($message= check_sizelimit()) != ""){
660       return($message);
661     }
663     /* Prepare departments */
664     $options= "";
665     foreach ($this->config->idepartments as $key => $value){
666       if ($_SESSION['CurrentMainBase'] == $key){
667         $options.= "<option selected value='$key'>$value</option>";
668       } else {
669         $options.= "<option value='$key'>$value</option>";
670       }
671     }
673     /* Choose correct paste icon */
674     if($this->CopyPasteHandler){
675       $Copy_Paste= $this->CopyPasteHandler->generatePasteIcon();
676     }else{
677       $Copy_Paste= "";
678     }
680 #------------------------------------------------------------------------ Review mark
681     //FIXME: Hmm. I spent some hours in the past to get rid of HTML inside the
682     //       PHP code. The section from here until the end of the execute() function
683     //       is not what I'd call a good solution. It works, but its somewhat ugly.
684     //       Currently I've no idea to make it better. HERE docs can help to make
685     //       the code more readable. Smarty templates would be the best solution.
686     //       Just not sure how to do it right now.
688     /* NEW LIST MANAGMENT */
689     //FIXME: Who cares? The old one is not present, and the big letters don't
690     //       make clear that it's still spaghetti code...
691     //FIXME: Variable naming - field1....
692     $listhead = "<div style='background:#F0F0F9;padding:5px;'>".
693       " <input class='center' type='image' src='images/list_root.png' align='middle' title='"._("Go to root department")."' name='dep_root' alt='"._("Root")."'>&nbsp;".
694       " <input class='center' type='image' align='middle' src='images/list_back.png' title='"._("Go up one department")."' alt='"._("Up")."' name='dep_back'>&nbsp;".
695       " <input class='center' type='image' align='middle' src='images/list_home.png' title='"._("Go to users department")."' alt='"._("Home")."' name='dep_home'>&nbsp;".
696       " <input class='center' type='image' src='images/list_reload.png' align='middle' title='"._("Reload list")."' name='submit_department' alt='"._("Submit")."'>&nbsp;".
697       " <img   class='center' src='images/list_seperator.png' align='middle' alt='' height='16' width='1'>&nbsp;".
698       " <input class='center' type='image' align='middle' src='images/list_new_user.png' title='"._("Create new user")."' alt='"._("New user")."' name='user_new'>&nbsp;".
699       " <input class='center' type='image' align='middle' src='images/list_new.png' title='"._("Create new template")."' alt='"._("New template")."' name='user_tplnew'>&nbsp;".
700       $Copy_Paste.
701       " <img   class='center' src='images/list_seperator.png' align='middle' alt='' height='16' width='1'>&nbsp;".
702       _("Base")."&nbsp;<select name='CurrentMainBase' onChange='mainform.submit()' class='center'>$options</select>".
703       " <input class='center' type='image' src='images/list_submit.png' align='middle' title='"._("Submit department")."' name='submit_department' alt='"._("Submit")."'>&nbsp;".
704       "</div>";
705     
706     if($this->CopyPasteHandler){
707       $action = "<input class='center' type='image'
708         src='images/editcut.png' alt='"._("cut")."' name='cut_%KEY%' title='"._("Cut this entry")."'>&nbsp;";
709       $action.= "<input class='center' type='image'
710         src='images/editcopy.png' alt='"._("copy")."' name='copy_%KEY%' title='"._("Copy this entry")."'>&nbsp;";
711       $action.= "<input class='center' type='image' src='images/edit.png' alt='"._("edit")."'     
712         name='user_edit_%KEY%' title='"._("Edit user")."'>";
713       $action.= "<input class='center' type='image' src='images/list_password.png' alt='"._("password")."' 
714         name='user_chgpw_%KEY%' title='"._("Change password")."'>";
715       $action.= "<input class='center' type='image' src='images/edittrash.png' alt='"._("delete")."'   
716         name='user_del_%KEY%' title='"._("Delete user")."'>";
717     }else{
718       $action= "<input class='center' type='image' src='images/edit.png' alt='"._("edit")."'     
719         name='user_edit_%KEY%' title='"._("Edit user")."'>";
720       $action.= "<input class='center' type='image' src='images/list_password.png' alt='"._("password")."' 
721         name='user_chgpw_%KEY%' title='"._("Change password")."'>";
722       $action.= "<input class='center' type='image' src='images/edittrash.png' alt='"._("delete")."'   
723         name='user_del_%KEY%' title='"._("Delete user")."'>";
724     }
726     $divlist = new divlist("userstab");
727     $divlist->SetHeader(array(
728           array("string" => "&nbsp;", "attach" => "style='text-align:center;width:20px;'"),
729           array("string" => _("Username")." / "._("Department"), "attach" => "style=''"),
730           array("string" => _("Properties"), "attach" => "style='width:152px;'"),
731           array("string" => _("Actions"), "attach" => "style='width:102px;border-right:0px;text-align:right;'")));
733     $divlist->SetSummary(_("This table displays all users, in the selected tree."));
734     $divlist->SetEntriesPerPage(0);
736     /* Defining Links */
737     $linkopen = "<a href='?plug=".validate($_GET['plug'])."&amp;act=dep_open&amp;dep_id=%s'>%s</a>";
739     /* Insert departments in divlist*/
740     foreach($this->departments as $key => $val){
742       if(!isset($this->config->departments[trim($key)])){
743         $this->config->departments[trim($key)]="";
744       }
746       $non_empty="";
747       $nkey= normalizePreg($key);
748       foreach($this->config->departments as $keyd => $vald ){
749         if(preg_match("/$nkey\/.*/", $keyd)){
750           $non_empty="full";
751         }
752       }
754       $field1 = array("string" => "<img src='images/".$non_empty."folder.png' alt='department'>", "attach" => "style='text-align:center;width:20px;'");
755       $field2 = array("string" => sprintf($linkopen,base64_encode($key),$val), "attach" => "style=''");
756       $field3 = array("string" => "&nbsp;", "attach" => "style='width:152px;'");
757       $field4 = array("string" => "&nbsp;", "attach" => "style='width:90px;border-right:0px;text-align:right;'");
759       $divlist->AddEntry(array($field1,$field2,$field3,$field4));
760     }
762     /* Pictures for Extensions */
763     $usrimg   ="<input class='center' type='image' src='images/penguin.png' alt='"._("GOsa")."'   
764                     name='user_edit_%KEY%-user' title='"._("Edit generic properties")."'>";
765     $posiximg = "<input class='center' type='image' src='images/select_user.png' alt='"._("Posix")."'  
766                     name='user_edit_%KEY%-posixAccount' title='"._("Edit UNIX properties")."'>";
767     $eviroimg = "<input class='center' type='image' src='images/smallenv.png' alt='"._("Environment")."'  
768                     name='user_edit_%KEY%-environment' title='"._("Edit environment properties")."'>";
769     $mailimg  = "<input class='center' type='image' src='images/mailto.png' alt='"._("Mail")."'     
770                     name='user_edit_%KEY%-mailAccount' title='"._("Edit mail properties")."'>";
771     $fonimg   = "<input class='center' type='image' src='images/%image%' alt='"._("Phone")."'     
772                     name='user_edit_%KEY%-phoneAccount' title='"._("Edit phone properties")."%title%'>";
773     $faximg   = "<input class='center' type='image' src='images/fax_small.png' alt='"._("Fax")."'     
774                     name='user_edit_%KEY%-gofaxAccount' title='"._("Edit fax properies")."'>";
775     $sambaimg = "<input class='center' type='image' src='images/select_winstation.png' alt='"._("Samba")."'     
776                     name='user_edit_%KEY%-sambaAccount' title='"._("Edit samba properties")."'>"; 
777     $netatalkimg = "<input class='center' type='image' src='images/select_netatalk.png' alt='"._("Netatalk")."'
778                     name='user_edit_%KEY%-netatalk' title='"._("Edit netatalk properties")."'>";
779     $tplcreateuserimg  = "<input type='image' class='center' src='images/list_new.png' alt='"._("Create user from template")."'
780                     name='userfrom_tpl_%KEY%' title='"._("Create user with this template")."'>";   
782     $empty    = "<img class='center' src='images/empty.png' style='width:16px;height:16px;' alt=''>"; 
784     // User and Template  Images  
785     $userimg  = "<img class='center' src='images/select_user.png' alt='User' title='%s'>";   
786     $tplimg   = "<img class='center' src='images/select_template.png' alt='Template' title='%s'>";   
787     $editlink = "<a href='?plug=".validate($_GET['plug'])."&amp;id=%s&amp;act=edit_entry'>%s</a>";
789     // Defines Arrays to save User and Templates
790     $tpls = array();
791     $users= array();
793     /* Get Configuration for goFon DB (if it is set), to connect to the asterisk tables.
794      * Read Sip Table for specified account (for each user with phoneAccount).
795      * Check the attributes ip port and regseconds.
796      * If regseconds is set and >0 , the phone is logged in.
797      * Else the phone is currently not logged.
798      * If we can't read any Data from the DB or there is no goFon DB specified
799      * show old style without status icons.
800      */
801     $r_db   =false;
802     $r_con  =false;
803     if (isset($_SESSION['config']->data['SERVERS']['FON'])){
804       $a_SETUP= $_SESSION['config']->data['SERVERS']['FON'];
805       // Connect to DB server
806   
807       /* 
808         If you want to disable the status pictures, just comment out the next line
809       */
810       $r_con = false;
811       $r_db  = false;
812       if(is_callable("mysql_pconnect")){
813         $r_con= @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
814         // Check if we are  connected correctly
815         if($r_con){
816           $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
817         }
818       }
819     }
821     // Test Every Entry and generate divlist Array  
822     foreach($this->list as $key => $val){
823       $connected  = ""; // This string represents timestamp or offline status 
824       $ip_port    = ""; // String that will represent ip : port of the connected phone
825       if((in_array("goFonAccount"    ,$val['objectClass']))){
826   
827         /* Set defaults */
828         $fonac = preg_replace("/%image%/", "select_phone.png", $fonimg);
829         $fonac = preg_replace("/%KEY%/", "$key", $fonac);
830         $fonac = preg_replace("/%title%/", "", $fonac);
832         /* Database connection is ok ?*/
833         if(($r_db)&&(is_callable("mysql_query"))){
834           $res= @mysql_query("SELECT regseconds,name,port,ipaddr FROM ".$a_SETUP['SIP_TABLE']." WHERE (name='".$val['uid'][0]."')");
835           $mysql_entry = @mysql_fetch_row($res);
836           if(is_array($mysql_entry)){
837             if((isset($mysql_entry[0]))&&($mysql_entry[0]>1)){
838               $connected = " | "._("Online")." : ".gmdate("d.m.Y H:i:s",($mysql_entry[0]+(60*60)));
839               $fonac = preg_replace("/%image%/", "select_phone_connected.png", $fonimg);
840               $fonac = preg_replace("/%KEY%/", "$key", $fonac);
841               $fonac = preg_replace("/%title%/", $connected, $fonac);
842               $ip_port= " - ".$mysql_entry[3].":".$mysql_entry[2];
843             }
844             if((isset($mysql_entry[0]))&&($mysql_entry[0]==0)){
845               $connected = " | "._("Offline");
846               $fonac = preg_replace("/%image%/", "select_phone.png", $fonimg);
847               $fonac = preg_replace("/%KEY%/", "$key", $fonac);
848               $fonac = preg_replace("/%title%/", $connected, $fonac);
849             }
850           }
851         }
852       }else{
853         $fonac=$empty;
854       }
856     
858       /* Specify Pics for Extensions */ 
859       //FIXME: Spaghetti code. Please replace by a simple loop.
860       if(in_array("posixAccount"    ,$val['objectClass'])){ 
861         $posix = preg_replace("/%KEY%/", "$key", $posiximg);
862       }else{ 
863         $posix=$empty;
864       }
865       
866       if(in_array("gotoEnvironment"    ,$val['objectClass'])){ 
867         $enviro = preg_replace("/%KEY%/", "$key", $eviroimg);
868       }else{ 
869         $enviro =$empty;
870       }
871    
872       if(in_array("gosaMailAccount" ,$val['objectClass'])){ 
873         $maila = preg_replace("/%KEY%/", "$key", $mailimg);   
874       }else{ 
875         $maila=$empty;
876       } 
877   
878       if(in_array("goFaxAccount"    ,$val['objectClass'])){ 
879         $faxac = preg_replace("/%KEY%/", "$key", $faximg);    
880       }else{ 
881         $faxac=$empty;
882       } 
884       if(in_array("sambaSamAccount" ,$val['objectClass'])){ 
885         $samba = preg_replace("/%KEY%/", "$key", $sambaimg);  
886       }else{ 
887         $samba=$empty;
888       } 
890       if(in_array("apple-user" ,$val['objectClass'])){
891         $netatalk = preg_replace("/%KEY%/", "$key", $netatalkimg);
892       }else{
893         $netatalk=$empty;
894       }
896       if(in_array("gosaUserTemplate",$val['objectClass'])){ 
897         $tpl                          = preg_replace("/%KEY%/", "$key", $tplimg);   
898         $s_img_create_from_template   = preg_replace("/%KEY%/", "$key", $tplcreateuserimg);
899       }else{ 
900         $s_img_create_from_template   = "";
901         $tpl=$userimg;
902       }
904       $usrimg2 = preg_replace("/%KEY%/", "$key", $usrimg);
906       // Generate caption for rows
907       if (isset($val["sn"]) && isset($val["givenName"])){
908         $display= $val["sn"][0].", ".$val["givenName"][0]." [".$val["uid"][0]."]";
909       } else {
910         $display= "[".$val["uid"][0]."]";
911       }
913       /* Create each field */
914       $field1 = array("string" => sprintf($tpl,$val['dn']), "attach" => "style='text-align:center;width:20px;'");
915       $field2 = array("string" => sprintf($editlink,$key,$display).$ip_port, "attach" => "style='' title='dn:&nbsp;".@LDAP::fix($val['dn'])."'");
916       $field3 = array("string" => $usrimg2."&nbsp;".$posix."&nbsp;".$enviro."&nbsp;".$maila."&nbsp;".$fonac."&nbsp;".$faxac."&nbsp;".$samba."&nbsp".$netatalk, "attach" => "style='width:152px;'");
917       $field4 = array("string" => $s_img_create_from_template.preg_replace("/%KEY%/", "$key", $action),"attach" => "style='width:102px;border-right:0px;text-align:right;'");
919       $add = array($field1,$field2,$field3,$field4);
921       // Template or User
922       if(in_array("gosaUserTemplate",$val['objectClass'])){
923         $tpls[strtolower( $val['sn']['0'].$val['uid']['0'])]=$add;
924       }else{
925         $users[strtolower( $val['sn']['0'].$val['uid']['0'])]=$add;
926       }
927     }
929     // Sort Entries 
930     ksort($users);
931     ksort($tpls);
933     // Append Templates
934     foreach($tpls as $key => $val){
935       $divlist->AddEntry( $val, array(""));
936     }
937     // Append Users 
938     foreach($users as $key => $val){
939       $divlist->AddEntry( $val, array(""));
940     }
941     $smarty->assign("userlist",   $divlist->DrawList());
942     $smarty->assign("userlisthead", $listhead);
943     
944     $smarty->assign("search_image", get_template_path('images/search.png'));
945     $smarty->assign("tree_image", get_template_path('images/tree.png'));
946     $smarty->assign("infoimage", get_template_path('images/info.png'));
947     $smarty->assign("launchimage", get_template_path('images/launch.png'));
948     $smarty->assign("deplist", $this->config->idepartments);
950     foreach( array("functionalusers", "unixusers",
951           "mailusers", "sambausers", "proxyusers", 
952           "faxusers", "templates", "subsearch") as $type){
954       $smarty->assign("$type", $userfilter[$type]);
955     }
957     $smarty->assign("CurrentMainBase",$_SESSION['CurrentMainBase']);
958     $smarty->assign("regex", $userfilter["regex"]);
960     /* Extend if we are not using javascript */
961     $smarty->assign("apply", apply_filter());
962     $smarty->assign("alphabet", generate_alphabet());
963     $smarty->assign("hint", print_sizelimit_warning());
965     if((is_callable("mysql_close"))&&($r_con)){
966       @mysql_close($r_con);
967     }
969     /* Return rendered main page */
970     return ($smarty->fetch(get_template_path('headpage.tpl', TRUE)));
971   }
972 #----------------------------------------------------------------- Reviewed after this mark
975   function reload()
976   {
977     /* Get config */
978     $userfilter= get_global('userfilter');
980     /* Set base for all searches */
981     $base= $_SESSION['CurrentMainBase'];
983     /* Regex filter? */
984     if ($userfilter['regex'] != ""){
985       $regex= $userfilter['regex'];
986     } else {
987       $regex= "*";
988     }
990     /* Setup filter depending on selection */
991     $filter="";
992     if ($this->config->current['SAMBAVERSION'] == 3){
993       $samba= "sambaSamAccount";
994     } else {
995       $samba= "sambaAccount";
996     }
997     if ($userfilter['functionalusers'] == "checked"){
998       $filter.= "(&(objectClass=gosaAccount)(!(|(objectClass=posixAccount)".
999                 "(objectClass=gosaMailAccount)(objectClass=$samba)".
1000                 "(objectClass=gosaProxyAccount))))";
1001     }
1002     if ($userfilter['unixusers'] == "checked"){
1003       $filter.= "(objectClass=posixAccount)";
1004     }
1005     if ($userfilter['mailusers'] == "checked"){
1006       $filter.= "(objectClass=gosaMailAccount)";
1007     }
1008     if ($userfilter['sambausers'] == "checked"){
1009       $filter.= "(objectClass=$samba)";
1010     }
1011     if ($userfilter['proxyusers'] == "checked"){
1012       $filter.= "(objectClass=gosaProxyAccount)";
1013     }
1014     if ($userfilter['templates'] == "checked"){
1015       $filter= "(|(objectClass=gosaUserTemplate)(&(objectClass=gosaAccount)(|$filter)))";
1016     } else {
1017       $filter= "(&(objectClass=gosaAccount)(!(objectClass=gosaUserTemplate))(|$filter))";
1018     }
1019     $filter= "(&(|(uid=".normalizeLdap($regex).")(sn=".normalizeLdap($regex).")(givenName=".normalizeLdap($regex)."))$filter)";
1021     /* Generate userlist */
1022     $ldap= $this->config->get_ldap_link(TRUE);
1023     if ($userfilter['subsearch'] == "checked"){
1024       $this->list= get_list($filter, $this->ui->subtreeACL, $base,
1025                             array("uid", "givenName", "sn", "objectClass"), GL_SUBSEARCH | GL_SIZELIMIT);
1026     } else {
1027       $base= get_people_ou().$base;
1028       $this->list= get_list($filter, $this->ui->subtreeACL, $base, 
1029                             array("uid", "givenName", "sn", "objectClass"), GL_SIZELIMIT);
1030     }
1031     
1032     /* Create base for department search */
1033     if(get_people_ou() == ""){
1034       $dep_base= $base;
1035     }else{
1036       $dep_base= preg_replace("/".normalizePreg(get_people_ou())."/i", "", $base);
1037     }
1039     /* Get all departments within this subtree */
1040     $deps= get_list("(&(|(ou=$regex)(description=$regex))(objectClass=gosaDepartment))", $this->ui->subtreeACL,
1041                     $dep_base, array("ou", "description"), GL_SIZELIMIT | GL_CONVERT);
1042                  
1043     $this->departments = array();
1044     foreach($deps as $value){
1045       if(isset($value['description'][0])){
1046         $this->departments[$value['dn']]= get_sub_department($value['dn'])." - [".$value["description"][0]."]";
1047       }else{
1048         $this->departments[$value['dn']]= get_sub_department($value['dn']);
1049       }
1050     }
1051     natcasesort($this->departments);
1052   }
1055   function remove_lock()
1056   {
1057     /* Remove user lock if a DN is marked as "currently edited" */
1058     if (isset($this->usertab->dn)){
1059       del_lock ($this->usertab->dn);
1060     }
1061   }
1063  
1064   /* Perform copy & paste requests
1065       If copy&paste is in progress this returns a dialog to fix required attributes 
1066    */ 
1067   function copyPasteHandling($s_action,$s_entry)
1068   {
1069     /* Only perform copy/paste if it is enabled */
1070     if($this->CopyPasteHandler){
1072       /* Prepare current object to be pasted */
1073       if( $s_action == "editPaste" || $this->CopyPasteHandler->stillOpen()){
1075         $this->CopyPasteHandler->save_object();
1076         $this->CopyPasteHandler->SetVar("base", $_SESSION['CurrentMainBase']);
1078         /* Execute copy & paste dialog and display returned data, normaly a dialog which allows 
1079             us to solve all attribute mismatches for this object.
1080             If nothing is returned, copy & paste was succesfully or aborted */
1081         if(($ret= $this->CopyPasteHandler->execute())){
1082           return ($ret);
1083         }
1085         /* Reload to have freshly copied entries in the list */
1086         $this->reload();
1087         
1088         /* Use the last dn to search for it's ID in the newly generated list. */
1089         $dn= $this->CopyPasteHandler->lastdn;
1090         foreach($this->list as $id => $entry){
1091           if($entry['dn'] == $dn){
1092             $s_entry= $id;
1093             break;
1094           }
1095         }
1096        
1097         /* Set CPPasswordChange to s_entry which indicates that this entry requires a new password. */
1098         if(isset($_POST['passwordTodo']) && ($_POST['passwordTodo'] == "new")){
1099           $this->CPPasswordChange = $s_entry;
1100         }
1101       }
1103       /* Copy selected object 
1104           Create a new empty object and the current selected object. 
1105           Send both to copy&paste class*/
1106       if($s_action == "copy"){
1107         $this->CopyPasteHandler->Clear();
1108         $dn= $this->list[trim($s_entry)]['dn'];
1109         $acl= get_permissions ($dn, $this->ui->subtreeACL);
1110         $obj    = new usertabs($this->config, $this->config->data['TABS']['USERTABS'], $dn);
1111         $objNew = new usertabs($this->config, $this->config->data['TABS']['USERTABS'], "new");
1112         $obj->    set_acl($acl);
1113         $objNew-> set_acl($acl);
1114         $this->CopyPasteHandler->Copy($obj,$objNew);
1115       }
1117       /* Cut selected object. 
1118           Open user object and send it to the copy & paste handler */
1119       if($s_action == "cut"){
1120         $this->CopyPasteHandler->Clear();
1121         $dn= $this->list[trim($s_entry)]['dn'];
1122         $acl= get_permissions ($dn, $this->ui->subtreeACL);
1123         $obj= new usertabs($this->config, $this->config->data['TABS']['USERTABS'], $dn);
1124         $obj->set_acl($acl);
1125         $this->CopyPasteHandler->Cut($obj);
1126       }
1127     }
1128   }
1131   /* A set of disabled and therefore overloaded functions. They are
1132      not needed in this class. */
1133   function remove_from_parent() { } 
1134   function check() { } 
1135   function save() { } 
1136   function adapt_from_template($dn) { } 
1137   function password_change_needed() { } 
1138   function show_header($button_text, $text, $disabled= FALSE) { }
1140 } /* ... class userManagement */
1143 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1144 ?>