Code

Some copy & paste fixes added some comments
[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     $tplcreateuserimg  = "<input type='image' class='center' src='images/list_new.png' alt='"._("Create user from template")."'
778                     name='userfrom_tpl_%KEY%' title='"._("Create user with this template")."'>";   
780     $empty    = "<img class='center' src='images/empty.png' style='width:16px;height:16px;' alt=''>"; 
782     // User and Template  Images  
783     $userimg  = "<img class='center' src='images/select_user.png' alt='User' title='%s'>";   
784     $tplimg   = "<img class='center' src='images/select_template.png' alt='Template' title='%s'>";   
785     $editlink = "<a href='?plug=".validate($_GET['plug'])."&amp;id=%s&amp;act=edit_entry'>%s</a>";
787     // Defines Arrays to save User and Templates
788     $tpls = array();
789     $users= array();
791     /* Get Configuration for goFon DB (if it is set), to connect to the asterisk tables.
792      * Read Sip Table for specified account (for each user with phoneAccount).
793      * Check the attributes ip port and regseconds.
794      * If regseconds is set and >0 , the phone is logged in.
795      * Else the phone is currently not logged.
796      * If we can't read any Data from the DB or there is no goFon DB specified
797      * show old style without status icons.
798      */
799     $r_db   =false;
800     $r_con  =false;
801     if (isset($_SESSION['config']->data['SERVERS']['FON'])){
802       $a_SETUP= $_SESSION['config']->data['SERVERS']['FON'];
803       // Connect to DB server
804   
805       /* 
806         If you want to disable the status pictures, just comment out the next line
807       */
808       $r_con = false;
809       $r_db  = false;
810       if(is_callable("mysql_pconnect")){
811         $r_con= @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
812         // Check if we are  connected correctly
813         if($r_con){
814           $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
815         }
816       }
817     }
819     // Test Every Entry and generate divlist Array  
820     foreach($this->list as $key => $val){
821       $connected  = ""; // This string represents timestamp or offline status 
822       $ip_port    = ""; // String that will represent ip : port of the connected phone
823       if((in_array("goFonAccount"    ,$val['objectClass']))){
824   
825         /* Set defaults */
826         $fonac = preg_replace("/%image%/", "select_phone.png", $fonimg);
827         $fonac = preg_replace("/%KEY%/", "$key", $fonac);
828         $fonac = preg_replace("/%title%/", "", $fonac);
830         /* Database connection is ok ?*/
831         if(($r_db)&&(is_callable("mysql_query"))){
832           $res= @mysql_query("SELECT regseconds,name,port,ipaddr FROM ".$a_SETUP['SIP_TABLE']." WHERE (name='".$val['uid'][0]."')");
833           $mysql_entry = @mysql_fetch_row($res);
834           if(is_array($mysql_entry)){
835             if((isset($mysql_entry[0]))&&($mysql_entry[0]>1)){
836               $connected = " | "._("Online")." : ".gmdate("d.m.Y H:i:s",($mysql_entry[0]+(60*60)));
837               $fonac = preg_replace("/%image%/", "select_phone_connected.png", $fonimg);
838               $fonac = preg_replace("/%KEY%/", "$key", $fonac);
839               $fonac = preg_replace("/%title%/", $connected, $fonac);
840               $ip_port= " - ".$mysql_entry[3].":".$mysql_entry[2];
841             }
842             if((isset($mysql_entry[0]))&&($mysql_entry[0]==0)){
843               $connected = " | "._("Offline");
844               $fonac = preg_replace("/%image%/", "select_phone.png", $fonimg);
845               $fonac = preg_replace("/%KEY%/", "$key", $fonac);
846               $fonac = preg_replace("/%title%/", $connected, $fonac);
847             }
848           }
849         }
850       }else{
851         $fonac=$empty;
852       }
854     
856       /* Specify Pics for Extensions */ 
857       //FIXME: Spaghetti code. Please replace by a simple loop.
858       if(in_array("posixAccount"    ,$val['objectClass'])){ 
859         $posix = preg_replace("/%KEY%/", "$key", $posiximg);
860       }else{ 
861         $posix=$empty;
862       }
863       
864       if(in_array("gotoEnvironment"    ,$val['objectClass'])){ 
865         $enviro = preg_replace("/%KEY%/", "$key", $eviroimg);
866       }else{ 
867         $enviro =$empty;
868       }
869    
870       if(in_array("gosaMailAccount" ,$val['objectClass'])){ 
871         $maila = preg_replace("/%KEY%/", "$key", $mailimg);   
872       }else{ 
873         $maila=$empty;
874       } 
875   
876       if(in_array("goFaxAccount"    ,$val['objectClass'])){ 
877         $faxac = preg_replace("/%KEY%/", "$key", $faximg);    
878       }else{ 
879         $faxac=$empty;
880       } 
882       if(in_array("sambaSamAccount" ,$val['objectClass'])){ 
883         $samba = preg_replace("/%KEY%/", "$key", $sambaimg);  
884       }else{ 
885         $samba=$empty;
886       } 
888       if(in_array("gosaUserTemplate",$val['objectClass'])){ 
889         $tpl                          = preg_replace("/%KEY%/", "$key", $tplimg);   
890         $s_img_create_from_template   = preg_replace("/%KEY%/", "$key", $tplcreateuserimg);
891       }else{ 
892         $s_img_create_from_template   = "";
893         $tpl=$userimg;
894       }
896       $usrimg2 = preg_replace("/%KEY%/", "$key", $usrimg);
898       // Generate caption for rows
899       if (isset($val["sn"]) && isset($val["givenName"])){
900         $display= $val["sn"][0].", ".$val["givenName"][0]." [".$val["uid"][0]."]";
901       } else {
902         $display= "[".$val["uid"][0]."]";
903       }
905       /* Create each field */
906       $field1 = array("string" => sprintf($tpl,$val['dn']), "attach" => "style='text-align:center;width:20px;'");
907       $field2 = array("string" => sprintf($editlink,$key,$display).$ip_port, "attach" => "style='' title='dn:&nbsp;".@LDAP::fix($val['dn'])."'");
908       $field3 = array("string" => $usrimg2."&nbsp;".$posix."&nbsp;".$enviro."&nbsp;".$maila."&nbsp;".$fonac."&nbsp;".$faxac."&nbsp;".$samba, "attach" => "style='width:152px;'");
909       $field4 = array("string" => $s_img_create_from_template.preg_replace("/%KEY%/", "$key", $action),"attach" => "style='width:102px;border-right:0px;text-align:right;'");
911       $add = array($field1,$field2,$field3,$field4);
913       // Template or User
914       if(in_array("gosaUserTemplate",$val['objectClass'])){
915         $tpls[strtolower( $val['sn']['0'].$val['uid']['0'])]=$add;
916       }else{
917         $users[strtolower( $val['sn']['0'].$val['uid']['0'])]=$add;
918       }
919     }
921     // Sort Entries 
922     ksort($users);
923     ksort($tpls);
925     // Append Templates
926     foreach($tpls as $key => $val){
927       $divlist->AddEntry( $val, array(""));
928     }
929     // Append Users 
930     foreach($users as $key => $val){
931       $divlist->AddEntry( $val, array(""));
932     }
933     $smarty->assign("userlist",   $divlist->DrawList());
934     $smarty->assign("userlisthead", $listhead);
935     
936     $smarty->assign("search_image", get_template_path('images/search.png'));
937     $smarty->assign("tree_image", get_template_path('images/tree.png'));
938     $smarty->assign("infoimage", get_template_path('images/info.png'));
939     $smarty->assign("launchimage", get_template_path('images/launch.png'));
940     $smarty->assign("deplist", $this->config->idepartments);
942     foreach( array("functionalusers", "unixusers",
943           "mailusers", "sambausers", "proxyusers", 
944           "faxusers", "templates", "subsearch") as $type){
946       $smarty->assign("$type", $userfilter[$type]);
947     }
949     $smarty->assign("CurrentMainBase",$_SESSION['CurrentMainBase']);
950     $smarty->assign("regex", $userfilter["regex"]);
952     /* Extend if we are not using javascript */
953     $smarty->assign("apply", apply_filter());
954     $smarty->assign("alphabet", generate_alphabet());
955     $smarty->assign("hint", print_sizelimit_warning());
957     if((is_callable("mysql_close"))&&($r_con)){
958       @mysql_close($r_con);
959     }
961     /* Return rendered main page */
962     return ($smarty->fetch(get_template_path('headpage.tpl', TRUE)));
963   }
964 #----------------------------------------------------------------- Reviewed after this mark
967   function reload()
968   {
969     /* Get config */
970     $userfilter= get_global('userfilter');
972     /* Set base for all searches */
973     $base= $_SESSION['CurrentMainBase'];
975     /* Regex filter? */
976     if ($userfilter['regex'] != ""){
977       $regex= $userfilter['regex'];
978     } else {
979       $regex= "*";
980     }
982     /* Setup filter depending on selection */
983     $filter="";
984     if ($this->config->current['SAMBAVERSION'] == 3){
985       $samba= "sambaSamAccount";
986     } else {
987       $samba= "sambaAccount";
988     }
989     if ($userfilter['functionalusers'] == "checked"){
990       $filter.= "(&(objectClass=gosaAccount)(!(|(objectClass=posixAccount)".
991                 "(objectClass=gosaMailAccount)(objectClass=$samba)".
992                 "(objectClass=gosaProxyAccount))))";
993     }
994     if ($userfilter['unixusers'] == "checked"){
995       $filter.= "(objectClass=posixAccount)";
996     }
997     if ($userfilter['mailusers'] == "checked"){
998       $filter.= "(objectClass=gosaMailAccount)";
999     }
1000     if ($userfilter['sambausers'] == "checked"){
1001       $filter.= "(objectClass=$samba)";
1002     }
1003     if ($userfilter['proxyusers'] == "checked"){
1004       $filter.= "(objectClass=gosaProxyAccount)";
1005     }
1006     if ($userfilter['templates'] == "checked"){
1007       $filter= "(|(objectClass=gosaUserTemplate)(&(objectClass=gosaAccount)(|$filter)))";
1008     } else {
1009       $filter= "(&(objectClass=gosaAccount)(!(objectClass=gosaUserTemplate))(|$filter))";
1010     }
1011     $filter= "(&(|(uid=".normalizeLdap($regex).")(sn=".normalizeLdap($regex).")(givenName=".normalizeLdap($regex)."))$filter)";
1013     /* Generate userlist */
1014     $ldap= $this->config->get_ldap_link(TRUE);
1015     if ($userfilter['subsearch'] == "checked"){
1016       $this->list= get_list($filter, $this->ui->subtreeACL, $base,
1017                             array("uid", "givenName", "sn", "objectClass"), GL_SUBSEARCH | GL_SIZELIMIT);
1018     } else {
1019       $base= get_people_ou().$base;
1020       $this->list= get_list($filter, $this->ui->subtreeACL, $base, 
1021                             array("uid", "givenName", "sn", "objectClass"), GL_SIZELIMIT);
1022     }
1023     
1024     /* Create base for department search */
1025     if(get_people_ou() == ""){
1026       $dep_base= $base;
1027     }else{
1028       $dep_base= preg_replace("/".normalizePreg(get_people_ou())."/i", "", $base);
1029     }
1031     /* Get all departments within this subtree */
1032     $deps= get_list("(&(|(ou=$regex)(description=$regex))(objectClass=gosaDepartment))", $this->ui->subtreeACL,
1033                     $dep_base, array("ou", "description"), GL_SIZELIMIT | GL_CONVERT);
1034                  
1035     $this->departments = array();
1036     foreach($deps as $value){
1037       if(isset($value['description'][0])){
1038         $this->departments[$value['dn']]= get_sub_department($value['dn'])." - [".$value["description"][0]."]";
1039       }else{
1040         $this->departments[$value['dn']]= get_sub_department($value['dn']);
1041       }
1042     }
1043     natcasesort($this->departments);
1044   }
1047   function remove_lock()
1048   {
1049     /* Remove user lock if a DN is marked as "currently edited" */
1050     if (isset($this->usertab->dn)){
1051       del_lock ($this->usertab->dn);
1052     }
1053   }
1055  
1056   /* Perform copy & paste requests
1057       If copy&paste is in progress this returns a dialog to fix required attributes 
1058    */ 
1059   function copyPasteHandling($s_action,$s_entry)
1060   {
1061     /* Only perform copy/paste if it is enabled */
1062     if($this->CopyPasteHandler){
1064       /* Prepare current object to be pasted */
1065       if( $s_action == "editPaste" || $this->CopyPasteHandler->stillOpen()){
1067         $this->CopyPasteHandler->save_object();
1068         $this->CopyPasteHandler->SetVar("base", $_SESSION['CurrentMainBase']);
1070         /* Execute copy & paste dialog and display returned data, normaly a dialog which allows 
1071             us to solve all attribute mismatches for this object.
1072             If nothing is returned, copy & paste was succesfully or aborted */
1073         if(($ret= $this->CopyPasteHandler->execute())){
1074           return ($ret);
1075         }
1077         /* Reload to have freshly copied entries in the list */
1078         $this->reload();
1079         
1080         /* Use the last dn to search for it's ID in the newly generated list. */
1081         $dn= $this->CopyPasteHandler->lastdn;
1082         foreach($this->list as $id => $entry){
1083           if($entry['dn'] == $dn){
1084             $s_entry= $id;
1085             break;
1086           }
1087         }
1088        
1089         /* Set CPPasswordChange to s_entry which indicates that this entry requires a new password. */
1090         if(isset($_POST['passwordTodo']) && ($_POST['passwordTodo'] == "new")){
1091           $this->CPPasswordChange = $s_entry;
1092         }
1093       }
1095       /* Copy selected object 
1096           Create a new empty object and the current selected object. 
1097           Send both to copy&paste class*/
1098       if($s_action == "copy"){
1099         $this->CopyPasteHandler->Clear();
1100         $dn= $this->list[trim($s_entry)]['dn'];
1101         $acl= get_permissions ($dn, $this->ui->subtreeACL);
1102         $obj    = new usertabs($this->config, $this->config->data['TABS']['USERTABS'], $dn);
1103         $objNew = new usertabs($this->config, $this->config->data['TABS']['USERTABS'], "new");
1104         $obj->    set_acl($acl);
1105         $objNew-> set_acl($acl);
1106         $this->CopyPasteHandler->Copy($obj,$objNew);
1107       }
1109       /* Cut selected object. 
1110           Open user object and send it to the copy & paste handler */
1111       if($s_action == "cut"){
1112         $this->CopyPasteHandler->Clear();
1113         $dn= $this->list[trim($s_entry)]['dn'];
1114         $acl= get_permissions ($dn, $this->ui->subtreeACL);
1115         $obj= new usertabs($this->config, $this->config->data['TABS']['USERTABS'], $dn);
1116         $obj->set_acl($acl);
1117         $this->CopyPasteHandler->Cut($obj);
1118       }
1119     }
1120   }
1123   /* A set of disabled and therefore overloaded functions. They are
1124      not needed in this class. */
1125   function remove_from_parent() { } 
1126   function check() { } 
1127   function save() { } 
1128   function adapt_from_template($dn) { } 
1129   function password_change_needed() { } 
1130   function show_header($button_text, $text, $disabled= FALSE) { }
1132 } /* ... class userManagement */
1135 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1136 ?>