Code

828f5cf0dbb8e46e0db37a2f4c069e33e0be8819
[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           $ldap_ui->cat($this->usertab->dn, array('uid'));
296           $user = $ldap_ui->fetch();
297         }else{
298           $ldap_ui->cat($this->dn, array('uid'));
299           $user = $ldap_ui->fetch();
300         }
301         if((is_array($user))&&(isset($user['uid']))){
302           $username= $user['uid'][0];
303         }
305         /* Set password, perform required steps */
306         if ($this->usertab){
307           if ($this->usertab->password_change_needed()){
308             $obj= $this->usertab->by_object['user'];
309             change_password ($this->usertab->dn, $_POST['new_password'],
310                 0, $obj->pw_storage);
311             if (isset($config->data['MAIN']['EXTERNALPWDHOOK'])){
312               exec($config->data['MAIN']['EXTERNALPWDHOOK']." ".$username." ".$_POST['new_password'], $resarr);
313             }
315             gosa_log ("Password for '".$this->usertab->dn."' has been changed");
316             unset($this->usertab);
317             $this->usertab= NULL;
318           }
319         } else {
320           change_password ($this->dn, $_POST['new_password']);
321           if (isset($config->data['MAIN']['EXTERNALPWDHOOK'])){
322             exec($config->data['MAIN']['EXTERNALPWDHOOK']." ".$username." ".$_POST['new_password'], $resarr);
323           }
325           gosa_log ("Password for '".$this->dn."' has been changed");
326         }
327       } else {
329         /* Missing permissions, show message */
330         print_red (_("You are not allowed to set this users password!"));
331       }
333       /* Clean session, delete lock */
334       del_lock ($this->dn);
335       $this->reload();
336       unset ($this->usertab);
337       $this->usertab= NULL;
338       $this->lognames= array();;
339       $this->sn= "";
340       $this->givenName= "";
341       $this->uid= "";
342       unset ($_SESSION['objectinfo']);
343     }
345     /* Remove user was requested */
346     if ($s_action=="del"){
348       /* Get 'dn' from posted 'uid' */
349       $this->dn= $this->list[trim($s_entry)]['dn'];
351       /* Load permissions for selected 'dn' and check if
352          we're allowed to remove this 'dn' */
353       $acl= get_permissions ($this->dn, $this->ui->subtreeACL);
354       $this->acl= get_module_permission($acl, "user", $this->dn);
355       if (chkacl($this->acl, "delete") == ""){
357         /* Check locking, save current plugin in 'back_plugin', so
358            the dialog knows where to return. */
359         if (($user= get_lock($this->dn)) != ""){
360           return(gen_locked_message ($user, $this->dn));
361         }
363         /* Lock the current entry, so nobody will edit it during deletion */
364         add_lock ($this->dn, $this->ui->dn);
365         $smarty->assign("info", sprintf(_("You're about to delete the user %s."), @LDAP::fix($this->dn)));
366         return($smarty->fetch(get_template_path('remove.tpl', TRUE)));
367       } else {
369         /* Obviously the user isn't allowed to delete. Show message and
370            clean session. */
371         print_red (_("You are not allowed to delete this user!"));
372       }
373     }
375     /* Confirmation for deletion has been passed. User should be deleted. */
376     if (isset($_POST['delete_user_confirm'])){
378       /* Some nice guy may send this as POST, so we've to check
379          for the permissions again. */
380       if (chkacl($this->acl, "delete") == ""){
382         /* Delete request is permitted, perform LDAP action */
383         $this->usertab= new usertabs($this->config, $this->config->data['TABS']['USERTABS'],
384             $this->dn);
385         $this->usertab->set_acl(array($this->acl));
386         $this->usertab->delete ();
387         gosa_log ("User object '".$this->dn."' has been removed");
388         unset ($this->usertab);
389         $this->usertab= NULL;
391         /* User list has changed, reload it. */
392         $this->reload ();
393       } else {
395         /* Normally this shouldn't be reached, send some extra
396            logs to notify the administrator */
397         print_red (_("You are not allowed to delete this user!"));
399         if(isset($this->ui->uid)){
400           gosa_log ("Warning: '".$this->ui->uid."' tried to trick user deletion.");
401         }
402       }
404       /* Remove lock file after successfull deletion */
405       del_lock ($this->dn);
406     }
409     /* Delete user canceled? */
410     if (isset($_POST['delete_cancel'])){
411       del_lock ($this->dn);
412     }
415     /* Finish user edit is triggered by the tabulator dialog, so
416        the user wants to save edited data. Check and save at this
417        point. */
418     if ((isset($_POST['edit_finish'])) && (isset($this->usertab->config))){
420       /* Check tabs, will feed message array */
421       $this->usertab->last= $this->usertab->current;
422       $this->usertab->save_object();
423       $message= $this->usertab->check();
425       /* Save, or display error message? */
426       if (count($message) == 0){
428         /* No errors. Go ahead and prepare to ask for a password
429            in case we're creating a new user. 'dn' will be 'new'
430            in this case. It is set to the correct value later. */
431         if ($this->dn == "new"){
432           $set_pass= 1;
433         } else {
434           $set_pass= 0;
435         }
437         /* Save user data to ldap */
438         if($this->usertab->save() == 1){
439           gosa_log ("User object '".$this->dn."' saving failed.");
440           return;
441         }
442         gosa_log ("User object '".$this->dn."' has been saved");
444         /* User has been saved successfully, remove lock from
445            LDAP. */
446         if ($this->dn != "new"){
447           del_lock ($this->dn);
448         }
450         /* In case of new users, ask for a password */
451         if (($set_pass || $this->usertab->password_change_needed()) &&
452             !$this->is_template){
454           return($smarty->fetch(get_template_path('password.tpl', TRUE)));
455         }
457         /* There's no page reload so we have to read new users at
458            this point. */
459         $this->reload ();
460         unset ($this->usertab);
461         $this->usertab= NULL;
462         unset ($_SESSION['objectinfo']);
464       } else {
465         /* Ok. There seem to be errors regarding to the tab data,
466            show message and continue as usual. */
467         show_errors($message);
468       }
469     }
471     /* Generate template list */
472     if (($s_action=="new")||($s_action=="create_user_from_tpl")){
474       $this->templates= array();
476       $ldap= $this->config->get_ldap_link();
478       /* Create list of tempaltes */
479       foreach ($this->config->departments as $key => $value){
480     
481         /* Get acls from different ou's */
482         $acl= get_permissions (get_people_ou().$value, $this->ui->subtreeACL);
483         $acl= get_module_permission($acl, "user", get_people_ou().$value);
484   
485         /* If creation of a new user is allowed, append this template */
486         if (chkacl($acl, "create") == ""){
487           
488           /* Search all templates from the current dn */
489           $ldap->cd (get_people_ou().$value);
490           $ldap->search ("(objectClass=gosaUserTemplate)", array("uid"));
492           /* Append */
493           if ($ldap->count() != 0){
494             while ($attrs= $ldap->fetch()){
495               $this->templates[$ldap->getDN()]=
496                 $attrs['uid'][0]." - ".@LDAP::fix($key);
497             }
498             $this->templates['none']= _("none");
499           }
500         }
501       }
503       /* Sort templates */
504       natcasesort ($this->templates);
505       reset ($this->templates);
506     }
508     /* New user/template request */
509     if (($s_action=="create_user_from_tpl")||($s_action=="new") || ($s_action=="new_tpl")){
510       /* By default we set 'dn' to 'new', all relevant plugins will
511          react on this. */
512       $this->dn= "new";
513       if (isset($this->config->current['IDGEN'])){
514         $this->got_uid= false;
515       } else {
516         $this->got_uid= true;
517       }
519       /* Create new usertab object */
520       $this->usertab= new usertabs($this->config,
521           $this->config->data['TABS']['USERTABS'], $this->dn);
522       $this->usertab->set_acl(array(':all'));
523       $this->usertab->by_object['user']->base= $_SESSION['CurrentMainBase'];
525       /* Take care about templates */
526       if ($s_action=="new_tpl"){
527         $this->is_template= TRUE;
528         $this->usertab->set_template_mode ();
529       } else {
530         $this->is_template= FALSE;
531       }
533       /* Use template if there are any of them */
534       if ((count($this->templates) && ($s_action!='new_tpl'))||($s_action=="create_user_from_tpl")){
535         foreach(array("sn", "givenName", "uid", "got_uid", "templates") as $attr){
536           $smarty->assign("$attr", $this->$attr);
537         }
538         if ($s_action=="create_user_from_tpl"){
539           $smarty->assign("template", $this->dn= $this->list[trim($s_entry)]['dn']);
540         } else {
541           $smarty->assign("template", "none");
542         }
543         $smarty->assign("edit_uid", "");
544         return($smarty->fetch(get_template_path('template.tpl', TRUE)));
545       }
546     }
548     /* Continue template editing */
549     if ((isset($_POST['template_continue']) && $_POST['template'] != 'none' && !isset($_POST['uid']))){
550       $this->sn= $_POST['sn'];
551       $this->givenName= $_POST['givenName'];
553       /* Check for requred values */
554       $message= array();
555       if ($this->sn == "") {
556         $message[]= _("The required field 'Name' is not set.");
557       }
558       if ($this->givenName == "") {
559         $message[]= _("The required field 'Given name' is not set.");
560       }
562       /* Check if dn is used */
563       $dn= preg_replace("/^[^,]+,/i", "", $_POST['template']);
564       $ldap= $this->config->get_ldap_link();
565       $ldap->cd ($dn);
566       $ldap->search ("(&(sn=".normalizeLdap($this->sn).")(givenName=".normalizeLdap($this->givenName)."))", array("givenName"));
567       if ($ldap->count () != 0){
568         $message[]= _("A person with the choosen name is already used in this tree.");
569       }
571       /* Show error message / continue editing */
572       if (count($message) > 0){
573         show_errors ($message);
574       } else {
575         $attributes= array('sn' => $this->sn, 'givenName' => $this->givenName);
576         if (isset($this->config->current['IDGEN']) &&
577             $this->config->current['IDGEN'] != ""){
578           $uids= gen_uids ($this->config->current['IDGEN'], $attributes);
579           if (count($uids)){
580             $smarty->assign("edit_uid", "false");
581             $smarty->assign("uids", $uids);
582             $this->uid= current($uids);
583           }
584         } else {
585           $smarty->assign("edit_uid", "");
586           $this->uid= "";
587         }
588         $this->got_uid= true;
589       }
591       foreach(array("sn", "givenName", "uid", "got_uid", "templates") as $attr){
592         $smarty->assign("$attr", $this->$attr);
593       }
594       if (isset($_POST['template'])){
595         $smarty->assign("template", $_POST['template']);
596       }
597       return($smarty->fetch(get_template_path('template.tpl', TRUE)));
598     }
600     /* No template. Ok. Lets fill data into the normal user dialog */
601     if (isset($_POST['template_continue']) && $_POST['template'] == 'none'){
602       foreach(array("sn", "givenName", "uid") as $attr){
603         if (isset($_POST[$attr])){
604           $this->usertab->by_object['user']->$attr= $_POST[$attr];
605         }
606       }
607     }
609     /* Finish template preamble */
610     if (isset($_POST['template_continue']) && $_POST['template'] != 'none' && (isset($_POST['uid']))){
612       /* Might not be filled if IDGEN is unset */
613       $this->sn                 = $_POST['sn'];
614       $this->givenName          = $_POST['givenName'];
616       /* Move user supplied data to sub plugins */
617       $this->uid                = $_POST['uid'];
618       $this->usertab->uid       = $this->uid;
619       $this->usertab->sn        = $this->sn;
620       $this->usertab->givenName = $this->givenName;
621       $template_dn              = $_POST['template'];
622       $this->usertab->adapt_from_template($template_dn);
623       $template_base            = preg_replace("/^[^,]+,".normalizePreg(get_people_ou())."/", '', $template_dn);
624       $this->usertab->by_object['user']->base= $template_base;
626       /* Set up the users ACL's for this 'dn' */
627       $acl= get_permissions ($template_base, $this->ui->subtreeACL);
628       $this->usertab->set_acl($acl);
629     }
630     
631     if (isset($_POST['template_continue']) && ($_POST['template'] == 'none')){
632       $this->usertab->by_object['user']->base= $_SESSION['CurrentMainBase'];
633     }
635     /* Show tab dialog if object is present */
636     if(isset($this->usertab->config)){
637       $display= $this->usertab->execute();
639       /* Don't show buttons if tab dialog requests this */
640       if (!$this->usertab->by_object[$this->usertab->current]->dialog){
641         $display.= "<p style=\"text-align:right\">\n";
642         $display.= "<input type=submit name=\"edit_finish\" value=\""._("Save")."\">\n";
643         $display.= "&nbsp;\n";
644         $display.= "<input type=submit name=\"edit_cancel\" value=\""._("Cancel")."\">\n";
645         $display.= "</p>";
646       }
647       return ($display);
648     }
650     /* Reload if we need a reload... */
651     if (!isset($this->usertab) &&
652         !isset($_POST['new_user']) &&
653         !isset($_POST['new_template']) &&
654         !isset($_POST['delete_user']) &&
655         !isset($_POST['setpass_user']) &&
656         !isset($_POST['select_user'])){
657       $this->reload();
658     }
660     /* Check for exeeded sizelimit */
661     if (($message= check_sizelimit()) != ""){
662       return($message);
663     }
665     /* Prepare departments */
666     $options= "";
667     foreach ($this->config->idepartments as $key => $value){
668       if ($_SESSION['CurrentMainBase'] == $key){
669         $options.= "<option selected value='$key'>$value</option>";
670       } else {
671         $options.= "<option value='$key'>$value</option>";
672       }
673     }
675     /* Choose correct paste icon */
676     if($this->CopyPasteHandler){
677       $Copy_Paste= $this->CopyPasteHandler->generatePasteIcon();
678     }else{
679       $Copy_Paste= "";
680     }
682 #------------------------------------------------------------------------ Review mark
683     //FIXME: Hmm. I spent some hours in the past to get rid of HTML inside the
684     //       PHP code. The section from here until the end of the execute() function
685     //       is not what I'd call a good solution. It works, but its somewhat ugly.
686     //       Currently I've no idea to make it better. HERE docs can help to make
687     //       the code more readable. Smarty templates would be the best solution.
688     //       Just not sure how to do it right now.
690     /* NEW LIST MANAGMENT */
691     //FIXME: Who cares? The old one is not present, and the big letters don't
692     //       make clear that it's still spaghetti code...
693     //FIXME: Variable naming - field1....
694     $listhead = "<div style='background:#F0F0F9;padding:5px;'>".
695       " <input class='center' type='image' src='images/list_root.png' align='middle' title='"._("Go to root department")."' name='dep_root' alt='"._("Root")."'>&nbsp;".
696       " <input class='center' type='image' align='middle' src='images/list_back.png' title='"._("Go up one department")."' alt='"._("Up")."' name='dep_back'>&nbsp;".
697       " <input class='center' type='image' align='middle' src='images/list_home.png' title='"._("Go to users department")."' alt='"._("Home")."' name='dep_home'>&nbsp;".
698       " <input class='center' type='image' src='images/list_reload.png' align='middle' title='"._("Reload list")."' name='submit_department' alt='"._("Submit")."'>&nbsp;".
699       " <img   class='center' src='images/list_seperator.png' align='middle' alt='' height='16' width='1'>&nbsp;".
700       " <input class='center' type='image' align='middle' src='images/list_new_user.png' title='"._("Create new user")."' alt='"._("New user")."' name='user_new'>&nbsp;".
701       " <input class='center' type='image' align='middle' src='images/list_new.png' title='"._("Create new template")."' alt='"._("New template")."' name='user_tplnew'>&nbsp;".
702       $Copy_Paste.
703       " <img   class='center' src='images/list_seperator.png' align='middle' alt='' height='16' width='1'>&nbsp;".
704       _("Base")."&nbsp;<select name='CurrentMainBase' onChange='mainform.submit()' class='center'>$options</select>".
705       " <input class='center' type='image' src='images/list_submit.png' align='middle' title='"._("Submit department")."' name='submit_department' alt='"._("Submit")."'>&nbsp;".
706       "</div>";
707     
708     if($this->CopyPasteHandler){
709       $action = "<input class='center' type='image'
710         src='images/editcut.png' alt='"._("cut")."' name='cut_%KEY%' title='"._("Cut this entry")."'>&nbsp;";
711       $action.= "<input class='center' type='image'
712         src='images/editcopy.png' alt='"._("copy")."' name='copy_%KEY%' title='"._("Copy this entry")."'>&nbsp;";
713       $action.= "<input class='center' type='image' src='images/edit.png' alt='"._("edit")."'     
714         name='user_edit_%KEY%' title='"._("Edit user")."'>";
715       $action.= "<input class='center' type='image' src='images/list_password.png' alt='"._("password")."' 
716         name='user_chgpw_%KEY%' title='"._("Change password")."'>";
717       $action.= "<input class='center' type='image' src='images/edittrash.png' alt='"._("delete")."'   
718         name='user_del_%KEY%' title='"._("Delete user")."'>";
719     }else{
720       $action= "<input class='center' type='image' src='images/edit.png' alt='"._("edit")."'     
721         name='user_edit_%KEY%' title='"._("Edit user")."'>";
722       $action.= "<input class='center' type='image' src='images/list_password.png' alt='"._("password")."' 
723         name='user_chgpw_%KEY%' title='"._("Change password")."'>";
724       $action.= "<input class='center' type='image' src='images/edittrash.png' alt='"._("delete")."'   
725         name='user_del_%KEY%' title='"._("Delete user")."'>";
726     }
728     $divlist = new divlist("userstab");
729     $divlist->SetHeader(array(
730           array("string" => "&nbsp;", "attach" => "style='text-align:center;width:20px;'"),
731           array("string" => _("Username")." / "._("Department"), "attach" => "style=''"),
732           array("string" => _("Properties"), "attach" => "style='width:152px;'"),
733           array("string" => _("Actions"), "attach" => "style='width:102px;border-right:0px;text-align:right;'")));
735     $divlist->SetSummary(_("This table displays all users, in the selected tree."));
736     $divlist->SetEntriesPerPage(0);
738     /* Defining Links */
739     $linkopen = "<a href='?plug=".validate($_GET['plug'])."&amp;act=dep_open&amp;dep_id=%s'>%s</a>";
741     /* Insert departments in divlist*/
742     foreach($this->departments as $key => $val){
744       if(!isset($this->config->departments[trim($key)])){
745         $this->config->departments[trim($key)]="";
746       }
748       $non_empty="";
749       $nkey= normalizePreg($key);
750       foreach($this->config->departments as $keyd => $vald ){
751         if(preg_match("/$nkey\/.*/", $keyd)){
752           $non_empty="full";
753         }
754       }
756       $field1 = array("string" => "<img src='images/".$non_empty."folder.png' alt='department'>", "attach" => "style='text-align:center;width:20px;'");
757       $field2 = array("string" => sprintf($linkopen,base64_encode($key),$val), "attach" => "style=''");
758       $field3 = array("string" => "&nbsp;", "attach" => "style='width:152px;'");
759       $field4 = array("string" => "&nbsp;", "attach" => "style='width:90px;border-right:0px;text-align:right;'");
761       $divlist->AddEntry(array($field1,$field2,$field3,$field4));
762     }
764     /* Pictures for Extensions */
765     $usrimg   ="<input class='center' type='image' src='images/penguin.png' alt='"._("GOsa")."'   
766                     name='user_edit_%KEY%-user' title='"._("Edit generic properties")."'>";
767     $posiximg = "<input class='center' type='image' src='images/select_user.png' alt='"._("Posix")."'  
768                     name='user_edit_%KEY%-posixAccount' title='"._("Edit UNIX properties")."'>";
769     $eviroimg = "<input class='center' type='image' src='images/smallenv.png' alt='"._("Environment")."'  
770                     name='user_edit_%KEY%-environment' title='"._("Edit environment properties")."'>";
771     $mailimg  = "<input class='center' type='image' src='images/mailto.png' alt='"._("Mail")."'     
772                     name='user_edit_%KEY%-mailAccount' title='"._("Edit mail properties")."'>";
773     $fonimg   = "<input class='center' type='image' src='images/%image%' alt='"._("Phone")."'     
774                     name='user_edit_%KEY%-phoneAccount' title='"._("Edit phone properties")."%title%'>";
775     $faximg   = "<input class='center' type='image' src='images/fax_small.png' alt='"._("Fax")."'     
776                     name='user_edit_%KEY%-gofaxAccount' title='"._("Edit fax properies")."'>";
777     $sambaimg = "<input class='center' type='image' src='images/select_winstation.png' alt='"._("Samba")."'     
778                     name='user_edit_%KEY%-sambaAccount' title='"._("Edit samba properties")."'>"; 
779     $netatalkimg = "<input class='center' type='image' src='images/select_netatalk.png' alt='"._("Netatalk")."'
780                     name='user_edit_%KEY%-netatalk' title='"._("Edit netatalk properties")."'>";
781     $tplcreateuserimg  = "<input type='image' class='center' src='images/list_new.png' alt='"._("Create user from template")."'
782                     name='userfrom_tpl_%KEY%' title='"._("Create user with this template")."'>";   
784     $empty    = "<img class='center' src='images/empty.png' style='width:16px;height:16px;' alt=''>"; 
786     // User and Template  Images  
787     $userimg  = "<img class='center' src='images/select_user.png' alt='User' title='%s'>";   
788     $tplimg   = "<img class='center' src='images/select_template.png' alt='Template' title='%s'>";   
789     $editlink = "<a href='?plug=".validate($_GET['plug'])."&amp;id=%s&amp;act=edit_entry'>%s</a>";
791     // Defines Arrays to save User and Templates
792     $tpls = array();
793     $users= array();
795     /* Get Configuration for goFon DB (if it is set), to connect to the asterisk tables.
796      * Read Sip Table for specified account (for each user with phoneAccount).
797      * Check the attributes ip port and regseconds.
798      * If regseconds is set and >0 , the phone is logged in.
799      * Else the phone is currently not logged.
800      * If we can't read any Data from the DB or there is no goFon DB specified
801      * show old style without status icons.
802      */
803     $r_db   =false;
804     $r_con  =false;
805     if (isset($_SESSION['config']->data['SERVERS']['FON'])){
806       $a_SETUP= $_SESSION['config']->data['SERVERS']['FON'];
807       // Connect to DB server
808   
809       /* 
810         If you want to disable the status pictures, just comment out the next line
811       */
812       $r_con = false;
813       $r_db  = false;
814       if(is_callable("mysql_pconnect")){
815         $r_con= @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
816         // Check if we are  connected correctly
817         if($r_con){
818           $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
819         }
820       }
821     }
823     // Test Every Entry and generate divlist Array  
824     foreach($this->list as $key => $val){
825       $connected  = ""; // This string represents timestamp or offline status 
826       $ip_port    = ""; // String that will represent ip : port of the connected phone
827       if((in_array("goFonAccount"    ,$val['objectClass']))){
828   
829         /* Set defaults */
830         $fonac = preg_replace("/%image%/", "select_phone.png", $fonimg);
831         $fonac = preg_replace("/%KEY%/", "$key", $fonac);
832         $fonac = preg_replace("/%title%/", "", $fonac);
834         /* Database connection is ok ?*/
835         if(($r_db)&&(is_callable("mysql_query"))){
836           $res= @mysql_query("SELECT regseconds,name,port,ipaddr FROM ".$a_SETUP['SIP_TABLE']." WHERE (name='".$val['uid'][0]."')");
837           $mysql_entry = @mysql_fetch_row($res);
838           if(is_array($mysql_entry)){
839             if((isset($mysql_entry[0]))&&($mysql_entry[0]>1)){
840               $connected = " | "._("Online")." : ".gmdate("d.m.Y H:i:s",($mysql_entry[0]+(60*60)));
841               $fonac = preg_replace("/%image%/", "select_phone_connected.png", $fonimg);
842               $fonac = preg_replace("/%KEY%/", "$key", $fonac);
843               $fonac = preg_replace("/%title%/", $connected, $fonac);
844               $ip_port= " - ".$mysql_entry[3].":".$mysql_entry[2];
845             }
846             if((isset($mysql_entry[0]))&&($mysql_entry[0]==0)){
847               $connected = " | "._("Offline");
848               $fonac = preg_replace("/%image%/", "select_phone.png", $fonimg);
849               $fonac = preg_replace("/%KEY%/", "$key", $fonac);
850               $fonac = preg_replace("/%title%/", $connected, $fonac);
851             }
852           }
853         }
854       }else{
855         $fonac=$empty;
856       }
858     
860       /* Specify Pics for Extensions */ 
861       //FIXME: Spaghetti code. Please replace by a simple loop.
862       if(in_array("posixAccount"    ,$val['objectClass'])){ 
863         $posix = preg_replace("/%KEY%/", "$key", $posiximg);
864       }else{ 
865         $posix=$empty;
866       }
867       
868       if(in_array("gotoEnvironment"    ,$val['objectClass'])){ 
869         $enviro = preg_replace("/%KEY%/", "$key", $eviroimg);
870       }else{ 
871         $enviro =$empty;
872       }
873    
874       if(in_array("gosaMailAccount" ,$val['objectClass'])){ 
875         $maila = preg_replace("/%KEY%/", "$key", $mailimg);   
876       }else{ 
877         $maila=$empty;
878       } 
879   
880       if(in_array("goFaxAccount"    ,$val['objectClass'])){ 
881         $faxac = preg_replace("/%KEY%/", "$key", $faximg);    
882       }else{ 
883         $faxac=$empty;
884       } 
886       if(in_array("sambaSamAccount" ,$val['objectClass'])){ 
887         $samba = preg_replace("/%KEY%/", "$key", $sambaimg);  
888       }else{ 
889         $samba=$empty;
890       } 
892       if(in_array("apple-user" ,$val['objectClass'])){
893         $netatalk = preg_replace("/%KEY%/", "$key", $netatalkimg);
894       }else{
895         $netatalk=$empty;
896       }
898       if(in_array("gosaUserTemplate",$val['objectClass'])){ 
899         $tpl                          = preg_replace("/%KEY%/", "$key", $tplimg);   
900         $s_img_create_from_template   = preg_replace("/%KEY%/", "$key", $tplcreateuserimg);
901       }else{ 
902         $s_img_create_from_template   = "";
903         $tpl=$userimg;
904       }
906       $usrimg2 = preg_replace("/%KEY%/", "$key", $usrimg);
908       // Generate caption for rows
909       if (isset($val["sn"]) && isset($val["givenName"])){
910         $display= $val["sn"][0].", ".$val["givenName"][0]." [".$val["uid"][0]."]";
911       } else {
912         $display= "[".$val["uid"][0]."]";
913       }
915       /* Create each field */
916       $field1 = array("string" => sprintf($tpl,$val['dn']), "attach" => "style='text-align:center;width:20px;'");
917       $field2 = array("string" => sprintf($editlink,$key,$display).$ip_port, "attach" => "style='' title='dn:&nbsp;".@LDAP::fix($val['dn'])."'");
918       $field3 = array("string" => $usrimg2."&nbsp;".$posix."&nbsp;".$enviro."&nbsp;".$maila."&nbsp;".$fonac."&nbsp;".$faxac."&nbsp;".$samba."&nbsp".$netatalk, "attach" => "style='width:152px;'");
919       $field4 = array("string" => $s_img_create_from_template.preg_replace("/%KEY%/", "$key", $action),"attach" => "style='width:102px;border-right:0px;text-align:right;'");
921       $add = array($field1,$field2,$field3,$field4);
923       // Template or User
924       if(in_array("gosaUserTemplate",$val['objectClass'])){
925         $tpls[strtolower( $val['sn']['0'].$val['uid']['0'])]=$add;
926       }else{
927         $users[strtolower( $val['sn']['0'].$val['uid']['0'])]=$add;
928       }
929     }
931     // Sort Entries 
932     ksort($users);
933     ksort($tpls);
935     // Append Templates
936     foreach($tpls as $key => $val){
937       $divlist->AddEntry( $val, array(""));
938     }
939     // Append Users 
940     foreach($users as $key => $val){
941       $divlist->AddEntry( $val, array(""));
942     }
943     $smarty->assign("userlist",   $divlist->DrawList());
944     $smarty->assign("userlisthead", $listhead);
945     
946     $smarty->assign("search_image", get_template_path('images/search.png'));
947     $smarty->assign("tree_image", get_template_path('images/tree.png'));
948     $smarty->assign("infoimage", get_template_path('images/info.png'));
949     $smarty->assign("launchimage", get_template_path('images/launch.png'));
950     $smarty->assign("deplist", $this->config->idepartments);
952     foreach( array("functionalusers", "unixusers",
953           "mailusers", "sambausers", "proxyusers", 
954           "faxusers", "templates", "subsearch") as $type){
956       $smarty->assign("$type", $userfilter[$type]);
957     }
959     $smarty->assign("CurrentMainBase",$_SESSION['CurrentMainBase']);
960     $smarty->assign("regex", $userfilter["regex"]);
962     /* Extend if we are not using javascript */
963     $smarty->assign("apply", apply_filter());
964     $smarty->assign("alphabet", generate_alphabet());
965     $smarty->assign("hint", print_sizelimit_warning());
967     if((is_callable("mysql_close"))&&($r_con)){
968       @mysql_close($r_con);
969     }
971     /* Return rendered main page */
972     return ($smarty->fetch(get_template_path('headpage.tpl', TRUE)));
973   }
974 #----------------------------------------------------------------- Reviewed after this mark
977   function reload()
978   {
979     /* Get config */
980     $userfilter= get_global('userfilter');
982     /* Set base for all searches */
983     $base= $_SESSION['CurrentMainBase'];
985     /* Regex filter? */
986     if ($userfilter['regex'] != ""){
987       $regex= $userfilter['regex'];
988     } else {
989       $regex= "*";
990     }
992     /* Setup filter depending on selection */
993     $filter="";
994     if ($this->config->current['SAMBAVERSION'] == 3){
995       $samba= "sambaSamAccount";
996     } else {
997       $samba= "sambaAccount";
998     }
999     if ($userfilter['functionalusers'] == "checked"){
1000       $filter.= "(&(objectClass=gosaAccount)(!(|(objectClass=posixAccount)".
1001                 "(objectClass=gosaMailAccount)(objectClass=$samba)".
1002                 "(objectClass=gosaProxyAccount))))";
1003     }
1004     if ($userfilter['unixusers'] == "checked"){
1005       $filter.= "(objectClass=posixAccount)";
1006     }
1007     if ($userfilter['mailusers'] == "checked"){
1008       $filter.= "(objectClass=gosaMailAccount)";
1009     }
1010     if ($userfilter['sambausers'] == "checked"){
1011       $filter.= "(objectClass=$samba)";
1012     }
1013     if ($userfilter['proxyusers'] == "checked"){
1014       $filter.= "(objectClass=gosaProxyAccount)";
1015     }
1016     if ($userfilter['templates'] == "checked"){
1017       $filter= "(|(objectClass=gosaUserTemplate)(&(objectClass=gosaAccount)(|$filter)))";
1018     } else {
1019       $filter= "(&(objectClass=gosaAccount)(!(objectClass=gosaUserTemplate))(|$filter))";
1020     }
1021     $filter= "(&(|(uid=".normalizeLdap($regex).")(sn=".normalizeLdap($regex).")(givenName=".normalizeLdap($regex)."))$filter)";
1023     /* Generate userlist */
1024     $ldap= $this->config->get_ldap_link(TRUE);
1025     if ($userfilter['subsearch'] == "checked"){
1026       $this->list= get_list($filter, $this->ui->subtreeACL, $base,
1027                             array("uid", "givenName", "sn", "objectClass"), GL_SUBSEARCH | GL_SIZELIMIT);
1028     } else {
1029       $base= get_people_ou().$base;
1030       $this->list= get_list($filter, $this->ui->subtreeACL, $base, 
1031                             array("uid", "givenName", "sn", "objectClass"), GL_SIZELIMIT);
1032     }
1033     
1034     /* Create base for department search */
1035     if(get_people_ou() == ""){
1036       $dep_base= $base;
1037     }else{
1038       $dep_base= preg_replace("/".normalizePreg(get_people_ou())."/i", "", $base);
1039     }
1041     /* Get all departments within this subtree */
1042     $deps= get_list("(&(|(ou=$regex)(description=$regex))(objectClass=gosaDepartment))", $this->ui->subtreeACL,
1043                     $dep_base, array("ou", "description"), GL_SIZELIMIT | GL_CONVERT);
1044                  
1045     $this->departments = array();
1046     foreach($deps as $value){
1047       if(isset($value['description'][0])){
1048         $this->departments[$value['dn']]= get_sub_department($value['dn'])." - [".$value["description"][0]."]";
1049       }else{
1050         $this->departments[$value['dn']]= get_sub_department($value['dn']);
1051       }
1052     }
1053     natcasesort($this->departments);
1054   }
1057   function remove_lock()
1058   {
1059     /* Remove user lock if a DN is marked as "currently edited" */
1060     if (isset($this->usertab->dn)){
1061       del_lock ($this->usertab->dn);
1062     }
1063   }
1065  
1066   /* Perform copy & paste requests
1067       If copy&paste is in progress this returns a dialog to fix required attributes 
1068    */ 
1069   function copyPasteHandling($s_action,$s_entry)
1070   {
1071     /* Only perform copy/paste if it is enabled */
1072     if($this->CopyPasteHandler){
1074       /* Prepare current object to be pasted */
1075       if( $s_action == "editPaste" || $this->CopyPasteHandler->stillOpen()){
1077         $this->CopyPasteHandler->save_object();
1078         $this->CopyPasteHandler->SetVar("base", $_SESSION['CurrentMainBase']);
1080         /* Execute copy & paste dialog and display returned data, normaly a dialog which allows 
1081             us to solve all attribute mismatches for this object.
1082             If nothing is returned, copy & paste was succesfully or aborted */
1083         if(($ret= $this->CopyPasteHandler->execute())){
1084           return ($ret);
1085         }
1087         /* Reload to have freshly copied entries in the list */
1088         $this->reload();
1089         
1090         /* Use the last dn to search for it's ID in the newly generated list. */
1091         $dn= $this->CopyPasteHandler->lastdn;
1092         foreach($this->list as $id => $entry){
1093           if($entry['dn'] == $dn){
1094             $s_entry= $id;
1095             break;
1096           }
1097         }
1098        
1099         /* Set CPPasswordChange to s_entry which indicates that this entry requires a new password. */
1100         if(isset($_POST['passwordTodo']) && ($_POST['passwordTodo'] == "new")){
1101           $this->CPPasswordChange = $s_entry;
1102         }
1103       }
1105       /* Copy selected object 
1106           Create a new empty object and the current selected object. 
1107           Send both to copy&paste class*/
1108       if($s_action == "copy"){
1109         $this->CopyPasteHandler->Clear();
1110         $dn= $this->list[trim($s_entry)]['dn'];
1111         $acl= get_permissions ($dn, $this->ui->subtreeACL);
1112         $obj    = new usertabs($this->config, $this->config->data['TABS']['USERTABS'], $dn);
1113         $objNew = new usertabs($this->config, $this->config->data['TABS']['USERTABS'], "new");
1114         $obj->    set_acl($acl);
1115         $objNew-> set_acl($acl);
1116         $this->CopyPasteHandler->Copy($obj,$objNew);
1117       }
1119       /* Cut selected object. 
1120           Open user object and send it to the copy & paste handler */
1121       if($s_action == "cut"){
1122         $this->CopyPasteHandler->Clear();
1123         $dn= $this->list[trim($s_entry)]['dn'];
1124         $acl= get_permissions ($dn, $this->ui->subtreeACL);
1125         $obj= new usertabs($this->config, $this->config->data['TABS']['USERTABS'], $dn);
1126         $obj->set_acl($acl);
1127         $this->CopyPasteHandler->Cut($obj);
1128       }
1129     }
1130   }
1133   /* A set of disabled and therefore overloaded functions. They are
1134      not needed in this class. */
1135   function remove_from_parent() { } 
1136   function check() { } 
1137   function save() { } 
1138   function adapt_from_template($dn) { } 
1139   function password_change_needed() { } 
1140   function show_header($button_text, $text, $disabled= FALSE) { }
1142 } /* ... class userManagement */
1145 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1146 ?>