rework XOrgDB -> XDB (shorter, easier to use).
[platal.git] / include / xorg / session.inc.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2006 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
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. *
10 * *
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. *
15 * *
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., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 require_once 'platal/session.inc.php';
23
24 // {{{ class XorgSession
25
26 class XorgSession
27 {
28 var $challenge;
29
30 // {{{ function XorgSession()
31
32 function XorgSession()
33 {
34 $this->challenge = md5(uniqid(rand(), 1));
35
36 if (!Session::has('uid')) {
37 try_cookie();
38 }
39 set_skin();
40 }
41
42 // }}}
43 // {{{ function init
44
45 function init() {
46 @session_start();
47 if (!Session::has('session')) {
48 $_SESSION['session'] = new XorgSession;
49 }
50 }
51
52 // }}}
53 // {{{ function destroy()
54
55 function destroy() {
56 @session_destroy();
57 unset($_SESSION);
58 XorgSession::init();
59 }
60
61 // }}}
62 // {{{ function doAuth()
63
64 /** Try to do an authentication.
65 *
66 * @param page the calling page (by reference)
67 */
68 function doAuth(&$page,$new_name=false)
69 {
70 global $globals;
71 if (identified()) { // ok, c'est bon, on n'a rien à faire
72 return true;
73 }
74
75 if (Session::has('session')) {
76 $session =& Session::getMixed('session');
77 }
78 if (Env::has('username') && Env::has('response') && isset($session->challenge))
79 {
80 // si on vient de recevoir une identification par passwordpromptscreen.tpl
81 // ou passwordpromptscreenlogged.tpl
82 $uname = Env::get('username');
83
84 if (Env::get('domain') == "alias") {
85
86 $res = XDB::query(
87 "SELECT redirect
88 FROM virtual
89 INNER JOIN virtual_redirect USING(vid)
90 WHERE alias LIKE {?}", $uname."@".$globals->mail->alias_dom);
91 $redirect = $res->fetchOneCell();
92 if ($redirect) {
93 $login = substr($redirect, 0, strpos($redirect, '@'));
94 } else {
95 $login = "";
96 }
97 } else {
98 $login = $uname;
99 }
100
101 $field = (!$redirect && preg_match('/^\d*$/', $uname)) ? 'id' : 'alias';
102 $res = XDB::query(
103 "SELECT u.user_id, u.password
104 FROM auth_user_md5 AS u
105 INNER JOIN aliases AS a ON ( a.id=u.user_id AND type!='homonyme' )
106 WHERE a.$field = {?} AND u.perms IN('admin','user')", $login);
107
108 $logger =& Session::getMixed('log');
109 if (list($uid, $password) = $res->fetchOneRow()) {
110 require_once('secure_hash.inc.php');
111 $expected_response=hash_encrypt("$uname:$password:{$session->challenge}");
112 // le password de la base est peut-être encore encodé en md5
113 if (Env::get('response') != $expected_response) {
114 $new_password = hash_xor(Env::get('xorpass'), $password);
115 $expected_response = hash_encrypt("$uname:$new_password:{$session->challenge}");
116 if (Env::get('response') == $expected_response) {
117 XDB::execute("UPDATE auth_user_md5 SET password = {?} WHERE user_id = {?}", $new_password, $uid);
118 }
119 }
120 if (Env::get('response') == $expected_response) {
121 if (Env::has('domain')) {
122 if (($domain = Env::get('domain', 'login')) == 'alias') {
123 setcookie('ORGdomain', "alias", (time()+25920000), '/', '', 0);
124 } else {
125 setcookie('ORGdomain', '', (time()-3600), '/', '', 0);
126 }
127 // pour que la modification soit effective dans le reste de la page
128 $_COOKIE['ORGdomain'] = $domain;
129 }
130
131 unset($session->challenge);
132 if ($logger) {
133 $logger->log('auth_ok');
134 }
135 start_connexion($uid, true);
136 if (Env::get('remember', 'false') == 'true') {
137 $cookie = hash_encrypt(Session::get('password'));
138 setcookie('ORGaccess',$cookie,(time()+25920000),'/','',0);
139 if ($logger) {
140 $logger->log("cookie_on");
141 }
142 } else {
143 setcookie('ORGaccess', '', time() - 3600, '/', '', 0);
144
145 if ($logger) {
146 $logger->log("cookie_off");
147 }
148 }
149 return true;
150 } elseif ($logger) {
151 $logger->log('auth_fail','bad password');
152 }
153 } elseif ($logger) {
154 $logger->log('auth_fail','bad login');
155 }
156 }
157 $this->doLogin($page,$new_name);
158 }
159
160 // }}}
161 // {{{ function doAuthCookie()
162
163 /** Try to do a cookie-based authentication.
164 *
165 * @param page the calling page (by reference)
166 */
167 function doAuthCookie(&$page)
168 {
169 if (logged()) {
170 return;
171 }
172
173 if (Env::has('username') and Env::has('response')) {
174 return $this->doAuth($page);
175 }
176
177 if ($r = try_cookie()) {
178 return $this->doAuth($page,($r>0));
179 }
180 }
181
182 // }}}
183 // {{{ function doLogin()
184
185 /** Display login screen.
186 */
187 function doLogin(&$page, $new_name=false)
188 {
189 if (logged() and !$new_name) {
190 $page->changeTpl('password_prompt_logged.tpl');
191 $page->addJsLink('javascript/do_challenge_response_logged.js');
192 $page->assign("xorg_tpl", "password_prompt_logged.tpl");
193 $page->run();
194 } else {
195 $page->changeTpl('password_prompt.tpl');
196 $page->addJsLink('javascript/do_challenge_response.js');
197 $page->assign("xorg_tpl", "password_prompt.tpl");
198
199 global $globals;
200 if ($globals->mail->alias_dom) {
201 $page->assign("domains", Array(
202 $globals->mail->domain."/".$globals->mail->domain2,
203 $globals->mail->alias_dom."/".$globals->mail->alias_dom2));
204 $page->assign("domains_value", Array("login", "alias"));
205 $page->assign("r_domain", Cookie::get('ORGdomain', 'login'));
206 }
207 $page->run();
208 }
209 exit;
210 }
211
212 // }}}
213 }
214
215 // }}}
216 // {{{ function try_cookie()
217
218 /** réalise la récupération de $_SESSION pour qqn avec cookie
219 * @return int 0 if all OK, -1 if no cookie, 1 if cookie with bad hash,
220 * -2 should not happen
221 */
222 function try_cookie()
223 {
224 global $globals;
225 if (Cookie::get('ORGaccess') == '' or !Cookie::has('ORGuid')) {
226 return -1;
227 }
228
229 $res = @XDB::query(
230 "SELECT user_id,password FROM auth_user_md5 WHERE user_id = {?} AND perms IN('admin','user')",
231 Cookie::getInt('ORGuid')
232 );
233 if ($res->numRows() != 0) {
234 list($uid, $password) = $res->fetchOneRow();
235 require_once('secure_hash.inc.php');
236 $expected_value = hash_encrypt($password);
237 if ($expected_value == Cookie::get('ORGaccess')) {
238 start_connexion($uid, false);
239 return 0;
240 } else {
241 return 1;
242 }
243 }
244
245 return -2;
246 }
247
248 // }}}
249 // {{{ function start_connexion()
250
251 /** place les variables de session dépendants de auth_user_md5
252 * et met à jour les dates de dernière connexion si nécessaire
253 * @return void
254 * @see controlpermanent.inc.php controlauthentication.inc.php
255 */
256 function start_connexion ($uid, $identified)
257 {
258 global $globals;
259 $res = XDB::query("
260 SELECT u.user_id AS uid, prenom, nom, perms, promo, matricule, password, FIND_IN_SET('femme', u.flags) AS femme,
261 UNIX_TIMESTAMP(s.start) AS lastlogin, s.host, a.alias AS forlife, a2.alias AS bestalias,
262 q.core_mail_fmt AS mail_fmt, UNIX_TIMESTAMP(q.banana_last) AS banana_last, q.watch_last, q.core_rss_hash
263 FROM auth_user_md5 AS u
264 INNER JOIN auth_user_quick AS q USING(user_id)
265 INNER JOIN aliases AS a ON (u.user_id = a.id AND a.type='a_vie')
266 INNER JOIN aliases AS a2 ON (u.user_id = a2.id AND FIND_IN_SET('bestalias',a2.flags))
267 LEFT JOIN logger.sessions AS s ON (s.uid=u.user_id AND s.suid=0)
268 WHERE u.user_id = {?} AND u.perms IN('admin','user')
269 ORDER BY s.start DESC
270 LIMIT 1", $uid);
271 $sess = $res->fetchOneAssoc();
272 $suid = Session::getMixed('suid');
273
274 if ($suid) {
275 $logger = new DiogenesCoreLogger($uid, $suid);
276 $logger->log("suid_start", Session::get('forlife')." by {$suid['uid']}");
277 $sess['suid'] = $suid;
278 } else {
279 $logger = Session::getMixed('log', new DiogenesCoreLogger($uid));
280 $logger->log("connexion", $_SERVER['PHP_SELF']);
281 setcookie('ORGuid', $uid, (time()+25920000), '/', '', 0);
282 }
283
284 $_SESSION = $sess;
285 $_SESSION['log'] = $logger;
286 $_SESSION['auth'] = ($identified ? AUTH_MDP : AUTH_COOKIE);
287 set_skin();
288 }
289
290 // }}}
291 // {{{ function set_skin()
292
293 function set_skin()
294 {
295 global $globals;
296 if (logged() && $globals->skin->enable) {
297 $uid = Session::getInt('uid');
298 $res = XDB::query("SELECT skin,skin_tpl
299 FROM auth_user_quick AS a
300 INNER JOIN skins AS s ON a.skin=s.id
301 WHERE user_id = {?} AND skin_tpl != ''", $uid);
302 if (list($_SESSION['skin_id'], $_SESSION['skin']) = $res->fetchOneRow()) {
303 return;
304 }
305 }
306 if ($globals->skin->enable) {
307 $_SESSION['skin'] = $globals->skin->def_tpl;
308 $_SESSION['skin_id'] = $globals->skin->def_id;
309 } else {
310 $_SESSION['skin'] = 'default.tpl';
311 $_SESSION['skin_id'] = -1;
312 }
313 }
314
315 // }}}
316
317 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker:
318 ?>