Code

Push first set of changes
[gosa.git] / 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->display (get_template_path('headers.tpl'));
94   $smarty->assign("version",get_gosa_version());
95   $smarty->display(get_template_path('login.tpl'));
96   exit();
97 }
101 /*****************************************************************************
102  *                               M   A   I   N                               *
103  *****************************************************************************/
105 /* Set error handler to own one, initialize time calculation
106    and start session. */
107 session::start();
108 session::set('errorsAlreadyPosted',array());
110 /* Destroy old session if exists. 
111    Else you will get your old session back, if you not logged out correctly. */
112 if(is_array(session::get_all()) && count(session::get_all())){
113   session::destroy();
114   session::start();
117 $username= "";
119 /* Reset errors */
120 session::set('errors',"");
121 session::set('errorsAlreadyPosted',"");
122 session::set('LastError',"");
124 /* Check if we need to run setup */
125 if (!file_exists(CONFIG_DIR."/".CONFIG_FILE)){
126   header("location:setup.php");
127   exit();
130 /* Reset errors */
131 session::set('errors',"");
133 /* Check for java script */
134 if(isset($_POST['javascript']) && $_POST['javascript'] == "true") {
135   session::global_set('js',TRUE);
136 }elseif(isset($_POST['javascript'])) {
137   session::global_set('js',FALSE);
140 /* Check if gosa.conf (.CONFIG_FILE) is accessible */
141 if (!is_readable(CONFIG_DIR."/".CONFIG_FILE)){
142   msg_dialog::display(_("Configuration error"),sprintf(_("GOsa configuration %s/%s is not readable. Aborted."), CONFIG_DIR,CONFIG_FILE),FATAL_ERROR_DIALOG);
143   exit();
146 /* Parse configuration file */
147 $config= new config(CONFIG_DIR."/".CONFIG_FILE, $BASE_DIR);
148 session::global_set('DEBUGLEVEL',$config->get_cfg_value('DEBUGLEVEL'));
149 if ($_SERVER["REQUEST_METHOD"] != "POST"){
150   @DEBUG (DEBUG_CONFIG, __LINE__, __FUNCTION__, __FILE__, $config->data, "config");
153 /* Enable compressed output */
154 if ($config->get_cfg_value("sendCompressedOutput") != ""){
155   ob_start("ob_gzhandler");
158 /* Set template compile directory */
159 $smarty->compile_dir= $config->get_cfg_value("templateCompileDirectory", '/var/spool/gosa');
161 /* Check for compile directory */
162 if (!(is_dir($smarty->compile_dir) && is_writable($smarty->compile_dir))){
163   msg_dialog::display(_("Smarty error"),sprintf(_("Directory '%s' specified as compile directory is not accessible!"),
164         $smarty->compile_dir),FATAL_ERROR_DIALOG);
165   exit();
168 /* Check for old files in compile directory */
169 clean_smarty_compile_dir($smarty->compile_dir);
171 /* Language setup */
172 $lang= get_browser_language();
173 putenv("LANGUAGE=");
174 putenv("LANG=$lang");
175 setlocale(LC_ALL, $lang);
176 $GLOBALS['t_language']= $lang;
177 $GLOBALS['t_gettext_message_dir'] = $BASE_DIR.'/locale/';
179 /* Set the text domain as 'messages' */
180 $domain = 'messages';
181 bindtextdomain($domain, LOCALE_DIR);
182 textdomain($domain);
183 $smarty->assign ('nextfield', 'username');
185 if ($_SERVER["REQUEST_METHOD"] != "POST"){
186   @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__, $lang, "Setting language to");
190 /* Check for SSL connection */
191 $ssl= "";
192 if (!isset($_SERVER['HTTPS']) ||
193     !stristr($_SERVER['HTTPS'], "on")) {
195   if (empty($_SERVER['REQUEST_URI'])) {
196     $ssl= "https://".$_SERVER['HTTP_HOST'].
197       $_SERVER['PATH_INFO'];
198   } else {
199     $ssl= "https://".$_SERVER['HTTP_HOST'].
200       $_SERVER['REQUEST_URI'];
201   }
204 /* If SSL is forced, just forward to the SSL enabled site */
205 if ($config->get_cfg_value("forcessl") == 'true' && $ssl != ''){
206   header ("Location: $ssl");
207   exit;
210 /* Do we have htaccess authentification enabled? */
211 $htaccess_authenticated= FALSE;
212 if ($config->get_cfg_value("htaccessAuthentication") == "true" ){
213   if (!isset($_SERVER['REMOTE_USER'])){
214     msg_dialog::display(_("Configuration error"), _("There is a problem with the authentication setup!"), FATAL_ERROR_DIALOG);
215     exit;
216   }
218   $tmp= process_htaccess($_SERVER['REMOTE_USER'], isset($_SERVER['KRB5CCNAME']));
219   $username= $tmp['username'];
220   $server= $tmp['server'];
221   if ($username == ""){
222     msg_dialog::display(_("Error"), _("Cannot find a valid user for the current authentication setup!"), FATAL_ERROR_DIALOG);
223     exit;
224   }
225   if ($server == ""){
226     msg_dialog::display(_("Error"), _("User information is not unique accross the configured LDAP trees!"), FATAL_ERROR_DIALOG);
227     exit;
228   }
230   $htaccess_authenticated= TRUE;
233 /* Got a formular answer, validate and try to log in */
234 if (($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['login'])) || $htaccess_authenticated){
236   /* Reset error messages */
237   $message= "";
239   /* Destroy old sessions, they cause a successfull login to relog again ...*/
240   if(session::global_is_set('_LAST_PAGE_REQUEST')){
241     session::global_set('_LAST_PAGE_REQUEST',time());
242   }
244   if (!$htaccess_authenticated){
245     $server= validate($_POST["server"]);
246   }
247   $config->set_current($server);
249   /* Admin-logon and verify */
250   $ldap = $config->get_ldap_link();
251   if (is_null($ldap) || (is_int($ldap) && $ldap == 0)){
252     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
253     displayLogin();
254     exit();
255   }
257   /* Check for schema file presence */
258   #TODO: these three lines should go to the class_config.inc, shouldn't they?
259   if(!isset($config->data['MAIN']['SCHEMACHECK'])){
260     $config->data['MAIN']['SCHEMACHECK'] = "true";
261   }
262   if ($config->get_cfg_value("schemaCheck") == "true"){
263     $recursive = ($config->get_cfg_value("ldapFollowReferrals") == "true");
264     $tls =       ($config->get_cfg_value("ldapTLS") == "true");
266     if(!count($ldap->get_objectclasses())){
267       msg_dialog::display(_("LDAP error"), _("Cannot detect information about the installed LDAP schema!"), ERROR_DIALOG);
268       displayLogin();
269       exit()  ;
270     }else{
271       $cfg = array();
272       $cfg['admin']     = $config->current['ADMINDN'];
273       $cfg['password']  = $config->current['ADMINPASSWORD'];
274       $cfg['connection']= $config->current['SERVER'];
275       $cfg['tls']       = $tls;
276       $str = check_schema($cfg, $config->get_cfg_value("rfc2307bis") == "true");
277       $checkarr = array();
278       foreach($str as $tr){
279         if(isset($tr['IS_MUST_HAVE']) && !$tr['STATUS']){
280           msg_dialog::display(_("LDAP error"), _("Your LDAP setup contains old schema definitions:")."<br><br><i>".$tr['MSG']."</i>", ERROR_DIALOG);
281           displayLogin();
282           exit();
283         }
284       }
285     }
286   }
288   /* Check for locking area */
289   $ldap->cat($config->get_cfg_value("config"), array("dn"));
290   $attrs= $ldap->fetch();
291   if (!count ($attrs)){
292     $ldap->cd($config->current['BASE']);
293     $ldap->create_missing_trees($config->get_cfg_value("config"));
294   }
296   /* Check for valid input */
297   $ok= true;
298   if (!$htaccess_authenticated){
299     $username= $_POST["username"];
300     if (!ereg("^[@A-Za-z0-9_.-]+$", $username)){
301       $message= _("Please specify a valid username!");
302       $ok= false;
303     } elseif (mb_strlen($_POST["password"], 'UTF-8') == 0){
304       $message= _("Please specify your password!");
305       $smarty->assign ('nextfield', 'password');
306       $ok= false;
307     }
308   }
310   if ($ok) {
312     /* Login as user, initialize user ACL's */
313     if ($htaccess_authenticated){
314       $ui= ldap_login_user_htaccess($username);
315       if ($ui === NULL || !$ui){
316         msg_dialog::display(_("Authentication error"), _("Cannot retrieve user information for htaccess authentication!"), FATAL_ERROR_DIALOG);
317         exit;
318       }
319     } else {
320       $ui= ldap_login_user($username, $_POST["password"]);
321     }
322     if ($ui === NULL || !$ui){
323       $message= _("Please check the username/password combination.");
324       $smarty->assign ('nextfield', 'password');
325       new log("security","login","",array(),"Authentication failed for user \"$username\"") ;
326     } else {
327       /* Remove all locks of this user */
328       del_user_locks($ui->dn);
330       /* Save userinfo and plugin structure */
331       session::global_set('ui',$ui);
332       session::global_set('session_cnt',0);
334       /* Let GOsa trigger a new connection for each POST, save
335          config to session. */
336       $config->get_departments();
337       $config->make_idepartments();
338       session::global_set('config',$config);
340       /* Restore filter settings from cookie, if available */
341       if($config->get_cfg_value("storeFilterSettings") == "true"){
343         if(isset($_COOKIE['GOsa_Filter_Settings']) || isset($HTTP_COOKIE_VARS['GOsa_Filter_Settings'])){
345           if(isset($_COOKIE['GOsa_Filter_Settings'])){
346             $cookie_all = unserialize(base64_decode($_COOKIE['GOsa_Filter_Settings']));
347           }else{
348             $cookie_all = unserialize(base64_decode($HTTP_COOKIE_VARS['GOsa_Filter_Settings']));
349           }
350           if(isset($cookie_all[$ui->dn])){
351             $cookie = $cookie_all[$ui->dn];
352             $cookie_vars= array("MultiDialogFilters","CurrentMainBase","plug");
353             foreach($cookie_vars as $var){
354               if(isset($cookie[$var])){
355                 session::global_set($var,$cookie[$var]);
356               }
357             }
358             if(isset($cookie['plug'])){
359               $plug =$cookie['plug'];
360             }
361           }
362         }
363       }
365       /* are we using accountexpiration */
366       if ($config->get_cfg_value("handleExpiredAccounts") == "true"){
367         $expired= ldap_expired_account($config, $ui->dn, $ui->username);
369         if ($expired == 1){
370           $message= _("Account locked. Please contact your system administrator!");
371           $smarty->assign ('nextfield', 'password');
372           new log("security","login","",array(),"Account for user \"$username\" has expired") ;
373         } elseif ($expired == 3){
374           $plist= new pluglist($config, $ui);
375           foreach ($plist->dirlist as $key => $value){
376             if (preg_match("/\bpassword\b/i",$value)){
377               $plug=$key;
378               new log("security","login","",array(),"User \"$username\" password forced to change") ;
379               header ("Location: main.php?plug=$plug&amp;reset=1");
380               exit;
381             }
382           }
383         }
384       }
386       /* Not account expired or password forced change go to main page */
387       new log("security","login","",array(),"User \"$username\" logged in successfully") ;
388       $plist= new pluglist($config, $ui);
389       if(isset($plug) && isset($plist->dirlist[$plug])){
390         header ("Location: main.php?plug=".$plug."&amp;global_check=1");
391       }else{
392         header ("Location: main.php?global_check=1");
393       }
394       exit;
395     }
396   }
399 /* Fill template with required values */
400 $smarty->assign ('date', gmdate("D, d M Y H:i:s"));
401 $smarty->assign ('username', $username);
402 $smarty->assign ('personal_img', get_template_path('images/login-head.png'));
403 $smarty->assign ('password_img', get_template_path('images/password.png'));
404 $smarty->assign ('directory_img', get_template_path('images/ldapserver.png'));
406 /* Some error to display? */
407 if (!isset($message)){
408   $message= "";
411 $smarty->assign ("message", $message);
413 /* Displasy SSL mode warning? */
414 if ($ssl != "" && $config->get_cfg_value('WARNSSL') == 'true'){
415   $smarty->assign ("ssl", "<b>"._("Warning").":<\/b> "._("Session will not be encrypted.")." <a style=\"color:red;\" href=\"$ssl\"><b>"._("Enter SSL session")."<\/b></a>!");
416 } else {
417   $smarty->assign ("ssl", "");
420 /* Translation of cookie-warning. Whether to display it, is determined by JavaScript */
421 $smarty->assign ("cookies", "<b>"._("Warning").":<\/b> "._("Your browser has cookies disabled. Please enable cookies and reload this page before logging in!"));
423 /* Generate server list */
424 $servers= array();
425 if (isset($_POST['server'])){
426   $selected= validate($_POST['server']);
427 } else {
428   $selected= $config->data['MAIN']['DEFAULT'];
430 foreach ($config->data['LOCATIONS'] as $key => $ignored){
431   $servers[$key]= $key;
433 $smarty->assign ("server_options", $servers);
434 $smarty->assign ("server_id", $selected);
436 /* show login screen */
437 $smarty->assign ("PHPSESSID", session_id());
438 if (session::is_set('errors')){
439   $smarty->assign("errors", session::get('errors'));
441 if ($error_collector != ""){
442   $smarty->assign("php_errors", preg_replace("/%BUGBODY%/",$error_collector_mailto,$error_collector)."</div>");
443 } else {
444   $smarty->assign("php_errors", "");
447 /* Set focus to the error button if we've an error message */
448 $focus= "";
449 if (session::is_set('errors') && session::get('errors') != ""){
450   $focus= '<script language="JavaScript" type="text/javascript">';
451   $focus.= 'document.forms[0].error_accept.focus();';
452   $focus.= '</script>';
454 $smarty->assign("focus", $focus);
455 displayLogin();
457 // vim:tabstop=2:expandtab:shiftwidth=2:softtabstop=2:filetype=php:syntax:ruler:
458 ?>
460 </body>
461 </html>