Code

Detect type of LDAP server (Sun LDAP and OpenLDAP for now) on login
[gosa.git] / trunk / gosa-core / html / index.php
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  * 
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 /* Load required includes */
24 require_once ("../include/php_setup.inc");
25 require_once ("functions.inc");
26 require_once ("class_log.inc");
27 header("Content-type: text/html; charset=UTF-8");
30 /**
31  * Display the login page and exit().
32  *
33  */
34 function displayLogin()
35 {
36   global $smarty,$message,$config,$ssl,$error_collector;
37   error_reporting(E_ALL | E_STRICT);
38   /* Fill template with required values */
39   $username = "";
40   if(isset($_POST["username"])){
41     $username= $_POST["username"];
42   }
43   $smarty->assign ('date', gmdate("D, d M Y H:i:s"));
44   $smarty->assign ('username', $username);
45   $smarty->assign ('personal_img', get_template_path('images/login-head.png'));
46   $smarty->assign ('password_img', get_template_path('images/password.png'));
47   $smarty->assign ('directory_img', get_template_path('images/ldapserver.png'));
49   /* Some error to display? */
50   if (!isset($message)){
51     $message= "";
52   }
53   $smarty->assign ("message", $message);
55   /* Displasy SSL mode warning? */
56   if ($ssl != "" && $config->get_cfg_value('warnssl') == 'true'){
57     $smarty->assign ("ssl", _("Warning").": <a style=\"color:red;\" href=\"$ssl\">"._("Session is not encrypted!")."</a>");
58   } else {
59     $smarty->assign ("ssl", "");
60   }
62   if(!$config->check_session_lifetime()){
63     $smarty->assign ("lifetime", _("Warning").": ".
64         _("The session lifetime configured in your gosa.conf will be overridden by php.ini settings."));
65   }else{
66     $smarty->assign ("lifetime", "");
67   }
69   /* Generate server list */
70   $servers= array();
71   if (isset($_POST['server'])){
72     $selected= validate($_POST['server']);
73   } else {
74     $selected= $config->data['MAIN']['DEFAULT'];
75   }
76   foreach ($config->data['LOCATIONS'] as $key => $ignored){
77     $servers[$key]= $key;
78   }
79   $smarty->assign ("server_options", $servers);
80   $smarty->assign ("server_id", $selected);
82   /* show login screen */
83   $smarty->assign ("PHPSESSID", session_id());
84   if (session::is_set('errors')){
85     $smarty->assign("errors", session::get('errors'));
86   }
87   if ($error_collector != ""){
88     $smarty->assign("php_errors", $error_collector."</div>");
89   } else {
90     $smarty->assign("php_errors", "");
91   }
92   $smarty->assign("msg_dialogs", msg_dialog::get_dialogs());
93   $smarty->assign("iePngWorkaround", $config->get_cfg_value("iePngWorkaround","false" ) == "true");
94   $smarty->display (get_template_path('headers.tpl'));
95   $smarty->assign("version",get_gosa_version());
96   $smarty->display(get_template_path('login.tpl'));
97   exit();
98 }
102 /*****************************************************************************
103  *                               M   A   I   N                               *
104  *****************************************************************************/
106 /* Set error handler to own one, initialize time calculation
107    and start session. */
108 session::start();
109 session::set('errorsAlreadyPosted',array());
111 /* Destroy old session if exists. 
112    Else you will get your old session back, if you not logged out correctly. */
113 if(is_array(session::get_all()) && count(session::get_all())){
114   session::destroy();
115   session::start();
118 $username= "";
120 /* Reset errors */
121 session::set('errors',"");
122 session::set('errorsAlreadyPosted',"");
123 session::set('LastError',"");
125 /* Check if we need to run setup */
126 if (!file_exists(CONFIG_DIR."/".CONFIG_FILE)){
127   header("location:setup.php");
128   exit();
131 /* Reset errors */
132 session::set('errors',"");
134 /* Check for java script */
135 if(isset($_POST['javascript']) && $_POST['javascript'] == "true") {
136   session::global_set('js',TRUE);
137 }elseif(isset($_POST['javascript'])) {
138   session::global_set('js',FALSE);
141 /* Check if gosa.conf (.CONFIG_FILE) is accessible */
142 if (!is_readable(CONFIG_DIR."/".CONFIG_FILE)){
143   msg_dialog::display(_("Configuration error"),sprintf(_("GOsa configuration %s/%s is not readable. Aborted."), CONFIG_DIR,CONFIG_FILE),FATAL_ERROR_DIALOG);
144   exit();
147 /* Parse configuration file */
148 $config= new config(CONFIG_DIR."/".CONFIG_FILE, $BASE_DIR);
149 session::global_set('DEBUGLEVEL',$config->get_cfg_value('DEBUGLEVEL'));
150 if ($_SERVER["REQUEST_METHOD"] != "POST"){
151   @DEBUG (DEBUG_CONFIG, __LINE__, __FUNCTION__, __FILE__, $config->data, "config");
154 /* Enable compressed output */
155 if ($config->get_cfg_value("sendCompressedOutput") != ""){
156   ob_start("ob_gzhandler");
159 /* Set template compile directory */
160 $smarty->compile_dir= $config->get_cfg_value("templateCompileDirectory", '/var/spool/gosa');
162 /* Check for compile directory */
163 if (!(is_dir($smarty->compile_dir) && is_writable($smarty->compile_dir))){
164   msg_dialog::display(_("Smarty error"),sprintf(_("Directory '%s' specified as compile directory is not accessible!"),
165         $smarty->compile_dir),FATAL_ERROR_DIALOG);
166   exit();
169 /* Check for old files in compile directory */
170 clean_smarty_compile_dir($smarty->compile_dir);
172 /* Language setup */
173 $lang= get_browser_language();
174 putenv("LANGUAGE=");
175 putenv("LANG=$lang");
176 setlocale(LC_ALL, $lang);
177 $GLOBALS['t_language']= $lang;
178 $GLOBALS['t_gettext_message_dir'] = $BASE_DIR.'/locale/';
180 /* Set the text domain as 'messages' */
181 $domain = 'messages';
182 bindtextdomain($domain, LOCALE_DIR);
183 textdomain($domain);
184 $smarty->assign ('nextfield', 'username');
186 if ($_SERVER["REQUEST_METHOD"] != "POST"){
187   @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, $lang, "Setting language to");
191 /* Check for SSL connection */
192 $ssl= "";
193 if (!isset($_SERVER['HTTPS']) ||
194     !stristr($_SERVER['HTTPS'], "on")) {
196   if (empty($_SERVER['REQUEST_URI'])) {
197     $ssl= "https://".$_SERVER['HTTP_HOST'].
198       $_SERVER['PATH_INFO'];
199   } else {
200     $ssl= "https://".$_SERVER['HTTP_HOST'].
201       $_SERVER['REQUEST_URI'];
202   }
205 /* If SSL is forced, just forward to the SSL enabled site */
206 if ($config->get_cfg_value("forcessl") == 'true' && $ssl != ''){
207   header ("Location: $ssl");
208   exit;
211 /* Do we have htaccess authentification enabled? */
212 $htaccess_authenticated= FALSE;
213 if ($config->get_cfg_value("htaccessAuthentication") == "true" ){
214   if (!isset($_SERVER['REMOTE_USER'])){
215     msg_dialog::display(_("Configuration error"), _("There is a problem with the authentication setup!"), FATAL_ERROR_DIALOG);
216     exit;
217   }
219   $tmp= process_htaccess($_SERVER['REMOTE_USER'], isset($_SERVER['KRB5CCNAME']));
220   $username= $tmp['username'];
221   $server= $tmp['server'];
222   if ($username == ""){
223     msg_dialog::display(_("Error"), _("Cannot find a valid user for the current authentication setup!"), FATAL_ERROR_DIALOG);
224     exit;
225   }
226   if ($server == ""){
227     msg_dialog::display(_("Error"), _("User information is not unique accross the configured LDAP trees!"), FATAL_ERROR_DIALOG);
228     exit;
229   }
231   $htaccess_authenticated= TRUE;
234 /* Got a formular answer, validate and try to log in */
235 if (($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['login'])) || $htaccess_authenticated){
237   /* Reset error messages */
238   $message= "";
240   /* Destroy old sessions, they cause a successfull login to relog again ...*/
241   if(session::global_is_set('_LAST_PAGE_REQUEST')){
242     session::global_set('_LAST_PAGE_REQUEST',time());
243   }
245   if (!$htaccess_authenticated){
246     $server= validate($_POST["server"]);
247   }
248   $config->set_current($server);
250   /* Admin-logon and verify */
251   $ldap = $config->get_ldap_link();
252   if (is_null($ldap) || (is_int($ldap) && $ldap == 0)){
253     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
254     displayLogin();
255     exit();
256   }
258   /* Check for schema file presence */
259   #TODO: these three lines should go to the class_config.inc, shouldn't they?
260   if(!isset($config->data['MAIN']['SCHEMACHECK'])){
261     $config->data['MAIN']['SCHEMACHECK'] = "true";
262   }
263   if ($config->get_cfg_value("schemaCheck") == "true"){
264     $recursive = ($config->get_cfg_value("ldapFollowReferrals") == "true");
265     $tls =       ($config->get_cfg_value("ldapTLS") == "true");
267     if(!count($ldap->get_objectclasses())){
268       msg_dialog::display(_("LDAP error"), _("Cannot detect information about the installed LDAP schema!"), ERROR_DIALOG);
269       displayLogin();
270       exit()  ;
271     }else{
272       $cfg = array();
273       $cfg['admin']     = $config->current['ADMINDN'];
274       $cfg['password']  = $config->current['ADMINPASSWORD'];
275       $cfg['connection']= $config->current['SERVER'];
276       $cfg['tls']       = $tls;
277       $str = check_schema($cfg, $config->get_cfg_value("rfc2307bis") == "true");
278       $checkarr = array();
279       foreach($str as $tr){
280         if(isset($tr['IS_MUST_HAVE']) && !$tr['STATUS']){
281           msg_dialog::display(_("LDAP error"), _("Your LDAP setup contains old schema definitions:")."<br><br><i>".$tr['MSG']."</i>", ERROR_DIALOG);
282           displayLogin();
283           exit();
284         }
285       }
286     }
287   }
289   /* Determine LDAP server comma escaping style */
290   if (!isset($config->comma_escape_style)) {
291     $comma_escape_style = "unknown";
292     $ldap = $config->get_ldap_link();
293     $ldap->cd("");
294     $ldap->cat("");
295     $attrs = $ldap->fetch();
296     if (isset($attrs["vendorName"]) && $attrs["vendorName"][0] == "Sun Microsystems, Inc.") {
297       $comma_escape_style = "comma";
298     }
299     for($i = 0 ; $i < $attrs['objectClass']['count']; $i++){
300       if ($attrs['objectClass'][$i] == "OpenLDAProotDSE") {
301         $comma_escape_style = "2C";
302       }
303     }
304     $config->comma_escape_style = $comma_escape_style;
305   }
307   /* Check for locking area */
308   $ldap->cat($config->get_cfg_value("config"), array("dn"));
309   $attrs= $ldap->fetch();
310   if (!count ($attrs)){
311     $ldap->cd($config->current['BASE']);
312     $ldap->create_missing_trees($config->get_cfg_value("config"));
313   }
315   /* Check for valid input */
316   $ok= true;
317   if (!$htaccess_authenticated){
318     $username= $_POST["username"];
319     if (!ereg("^[@A-Za-z0-9_.-]+$", $username)){
320       $message= _("Please specify a valid username!");
321       $ok= false;
322     } elseif (mb_strlen($_POST["password"], 'UTF-8') == 0){
323       $message= _("Please specify your password!");
324       $smarty->assign ('nextfield', 'password');
325       $ok= false;
326     }
327   }
329   if ($ok) {
331     /* Login as user, initialize user ACL's */
332     if ($htaccess_authenticated){
333       $ui= ldap_login_user_htaccess($username);
334       if ($ui === NULL || !$ui){
335         msg_dialog::display(_("Authentication error"), _("Cannot retrieve user information for htaccess authentication!"), FATAL_ERROR_DIALOG);
336         exit;
337       }
338     } else {
339       $ui= ldap_login_user($username, $_POST["password"]);
340     }
341     if ($ui === NULL || !$ui){
342       $message= _("Please check the username/password combination.");
343       $smarty->assign ('nextfield', 'password');
344       new log("security","login","",array(),"Authentication failed for user \"$username\"") ;
345     } else {
346       /* Remove all locks of this user */
347       del_user_locks($ui->dn);
349       /* Save userinfo and plugin structure */
350       session::global_set('ui',$ui);
351       session::global_set('session_cnt',0);
353       /* Let GOsa trigger a new connection for each POST, save
354          config to session. */
355       $config->get_departments();
356       $config->make_idepartments();
357       session::global_set('config',$config);
359       /* Restore filter settings from cookie, if available */
360       if($config->get_cfg_value("storeFilterSettings") == "true"){
362         if(isset($_COOKIE['GOsa_Filter_Settings']) || isset($HTTP_COOKIE_VARS['GOsa_Filter_Settings'])){
364           if(isset($_COOKIE['GOsa_Filter_Settings'])){
365             $cookie_all = unserialize(base64_decode($_COOKIE['GOsa_Filter_Settings']));
366           }else{
367             $cookie_all = unserialize(base64_decode($HTTP_COOKIE_VARS['GOsa_Filter_Settings']));
368           }
369           if(isset($cookie_all[$ui->dn])){
370             $cookie = $cookie_all[$ui->dn];
371             $cookie_vars= array("MultiDialogFilters","CurrentMainBase","plug");
372             foreach($cookie_vars as $var){
373               if(isset($cookie[$var])){
374                 session::global_set($var,$cookie[$var]);
375               }
376             }
377             if(isset($cookie['plug'])){
378               $plug =$cookie['plug'];
379             }
380           }
381         }
382       }
384       /* are we using accountexpiration */
385       if ($config->get_cfg_value("handleExpiredAccounts") == "true"){
386         $expired= ldap_expired_account($config, $ui->dn, $ui->username);
388         if ($expired == 1){
389           $message= _("Account locked. Please contact your system administrator!");
390           $smarty->assign ('nextfield', 'password');
391           new log("security","login","",array(),"Account for user \"$username\" has expired") ;
392         } elseif ($expired == 3){
393           $plist= new pluglist($config, $ui);
394           foreach ($plist->dirlist as $key => $value){
395             if (preg_match("/\bpassword\b/i",$value)){
396               $plug=$key;
397               new log("security","login","",array(),"User \"$username\" password forced to change") ;
398               header ("Location: main.php?plug=$plug&amp;reset=1");
399               exit;
400             }
401           }
402         }
403       }
405       /* Not account expired or password forced change go to main page */
406       new log("security","login","",array(),"User \"$username\" logged in successfully") ;
407       $plist= new pluglist($config, $ui);
408       if(isset($plug) && isset($plist->dirlist[$plug])){
409         header ("Location: main.php?plug=".$plug."&amp;global_check=1");
410       }else{
411         header ("Location: main.php?global_check=1");
412       }
413       exit;
414     }
415   }
418 /* Fill template with required values */
419 $smarty->assign ('date', gmdate("D, d M Y H:i:s"));
420 $smarty->assign ('username', $username);
421 $smarty->assign ('personal_img', get_template_path('images/login-head.png'));
422 $smarty->assign ('password_img', get_template_path('images/password.png'));
423 $smarty->assign ('directory_img', get_template_path('images/ldapserver.png'));
425 /* Some error to display? */
426 if (!isset($message)){
427   $message= "";
430 $smarty->assign ("message", $message);
432 /* Displasy SSL mode warning? */
433 if ($ssl != "" && $config->get_cfg_value('WARNSSL') == 'true'){
434   $smarty->assign ("ssl", "<b>"._("Warning").":<\/b> "._("Session will not be encrypted.")." <a style=\"color:red;\" href=\"$ssl\"><b>"._("Enter SSL session")."<\/b></a>!");
435 } else {
436   $smarty->assign ("ssl", "");
439 /* Translation of cookie-warning. Whether to display it, is determined by JavaScript */
440 $smarty->assign ("cookies", "<b>"._("Warning").":<\/b> "._("Your browser has cookies disabled. Please enable cookies and reload this page before logging in!"));
442 /* Generate server list */
443 $servers= array();
444 if (isset($_POST['server'])){
445   $selected= validate($_POST['server']);
446 } else {
447   $selected= $config->data['MAIN']['DEFAULT'];
449 foreach ($config->data['LOCATIONS'] as $key => $ignored){
450   $servers[$key]= $key;
452 $smarty->assign ("server_options", $servers);
453 $smarty->assign ("server_id", $selected);
455 /* show login screen */
456 $smarty->assign ("PHPSESSID", session_id());
457 if (session::is_set('errors')){
458   $smarty->assign("errors", session::get('errors'));
460 if ($error_collector != ""){
461   $smarty->assign("php_errors", preg_replace("/%BUGBODY%/",$error_collector_mailto,$error_collector)."</div>");
462 } else {
463   $smarty->assign("php_errors", "");
466 /* Set focus to the error button if we've an error message */
467 $focus= "";
468 if (session::is_set('errors') && session::get('errors') != ""){
469   $focus= '<script language="JavaScript" type="text/javascript">';
470   $focus.= 'document.forms[0].error_accept.focus();';
471   $focus.= '</script>';
473 $smarty->assign("focus", $focus);
474 displayLogin();
476 // vim:tabstop=2:expandtab:shiftwidth=2:softtabstop=2:filetype=php:syntax:ruler:
477 ?>
479 </body>
480 </html>