begin to work on xnet a bit.
[platal.git] / modules / platal.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 function bugize($list)
23 {
24 $list = split(',', $list);
25 $ans = array();
26
27 foreach ($list as $bug) {
28 $clean = str_replace('#', '', $bug);
29 $ans[] = "<a href='http://trackers.polytechnique.org/task/$clean'>$bug</a>";
30 }
31
32 return join(',', $ans);
33 }
34
35
36 class PlatalModule extends PLModule
37 {
38 function handlers()
39 {
40 return array(
41 'index' => $this->make_hook('index', AUTH_PUBLIC),
42 'cacert.pem' => $this->make_hook('cacert', AUTH_PUBLIC),
43 'changelog' => $this->make_hook('changelog', AUTH_PUBLIC),
44
45 // Preferences thingies
46 'prefs' => $this->make_hook('prefs', AUTH_COOKIE),
47 'prefs/rss' => $this->make_hook('prefs_rss', AUTH_COOKIE),
48 'prefs/webredirect'
49 => $this->make_hook('webredir', AUTH_MDP),
50 'skin' => $this->make_hook('skin', AUTH_COOKIE),
51
52 // password related thingies
53 'password' => $this->make_hook('password', AUTH_MDP),
54 'tmpPWD' => $this->make_hook('tmpPWD', AUTH_PUBLIC),
55 'password/smtp' => $this->make_hook('smtppass', AUTH_MDP),
56 'recovery' => $this->make_hook('recovery', AUTH_PUBLIC),
57 'exit' => $this->make_hook('exit', AUTH_PUBLIC),
58
59 // happenings related thingies
60 'rss' => $this->make_hook('rss', AUTH_PUBLIC),
61 );
62 }
63
64 function handler_index(&$page)
65 {
66 if (logged()) {
67 redirect("events");
68 }
69
70 return PL_OK;
71 }
72
73 function handler_cacert(&$page)
74 {
75 $data = file_get_contents('/etc/ssl/xorgCA/cacert.pem');
76 header('Content-Type: application/x-x509-ca-cert');
77 header('Content-Length: '.strlen($data));
78 echo $data;
79 exit;
80 }
81
82 function handler_changelog(&$page)
83 {
84 $page->changeTpl('changeLog.tpl');
85
86 $clog = htmlentities(file_get_contents(dirname(__FILE__).'/../ChangeLog'));
87 $clog = preg_replace('!(#[0-9]+(,[0-9]+)*)!e', 'bugize("\1")', $clog);
88 $page->assign('ChangeLog', $clog);
89 }
90
91 function __set_rss_state($state)
92 {
93 global $globals;
94
95 if ($state) {
96 $_SESSION['core_rss_hash'] = rand_url_id(16);
97 $globals->xdb->execute('UPDATE auth_user_quick
98 SET core_rss_hash={?} WHERE user_id={?}',
99 Session::get('core_rss_hash'),
100 Session::getInt('uid'));
101 } else {
102 $globals->xdb->execute('UPDATE auth_user_quick
103 SET core_rss_hash="" WHERE user_id={?}',
104 Session::getInt('uid'));
105 Session::kill('core_rss_hash');
106 }
107 }
108
109 function handler_prefs(&$page)
110 {
111 global $globals;
112
113 $page->changeTpl('preferences.tpl');
114 $page->assign('xorg_title','Polytechnique.org - Mes préférences');
115
116 if (Env::has('mail_fmt')) {
117 $fmt = Env::get('mail_fmt');
118 if ($fmt != 'texte') $fmt = 'html';
119 $globals->xdb->execute("UPDATE auth_user_quick
120 SET core_mail_fmt = '$fmt'
121 WHERE user_id = {?}",
122 Session::getInt('uid'));
123 $_SESSION['mail_fmt'] = $fmt;
124 redirect($globals->baseurl.'/preferences');
125 }
126
127 if (Env::has('rss')) {
128 $this->__set_rss_state(Env::getBool('rss'));
129 }
130
131 $page->assign('prefs', $globals->hook->prefs());
132
133 return PL_OK;
134 }
135
136 function handler_webredir(&$page)
137 {
138 global $globals;
139
140 $page->changeTpl('webredirect.tpl');
141
142 $page->assign('xorg_title','Polytechnique.org - Redirection de page WEB');
143
144 $log =& Session::getMixed('log');
145 $url = Env::get('url');
146
147 if (Env::get('submit') == 'Valider' and Env::has('url')) {
148 $globals->xdb->execute('UPDATE auth_user_quick
149 SET redirecturl = {?} WHERE user_id = {?}',
150 $url, Session::getInt('uid'));
151 $log->log('carva_add', 'http://'.Env::get('url'));
152 $page->trig("Redirection activée vers <a href='http://$url'>$url</a>");
153 } elseif (Env::get('submit') == "Supprimer") {
154 $globals->xdb->execute("UPDATE auth_user_quick
155 SET redirecturl = ''
156 WHERE user_id = {?}",
157 Session::getInt('uid'));
158 $log->log("carva_del", $url);
159 Post::kill('url');
160 $page->trig('Redirection supprimée');
161 }
162
163 $res = $globals->xdb->query('SELECT redirecturl
164 FROM auth_user_quick
165 WHERE user_id = {?}',
166 Session::getInt('uid'));
167 $page->assign('carva', $res->fetchOneCell());
168
169 return PL_OK;
170 }
171
172 function handler_prefs_rss(&$page)
173 {
174 global $globals;
175
176 $page->changeTpl('filrss.tpl');
177
178 $page->assign('goback', Env::get('referer', 'login'));
179
180 if (Env::get('act_rss') == 'Activer') {
181 $this->__set_rss_state(true);
182 $page->trig("Ton Fil RSS est activé.");
183 }
184
185 return PL_OK;
186 }
187
188 function handler_password(&$page)
189 {
190 global $globals;
191
192 if (Post::has('response2')) {
193 require_once 'secure_hash.inc.php';
194
195 $_SESSION['password'] = $password = Post::get('response2');
196
197 $globals->xdb->execute('UPDATE auth_user_md5
198 SET password={?}
199 WHERE user_id={?}', $password,
200 Session::getInt('uid'));
201
202 $log =& Session::getMixed('log');
203 $log->log('passwd', '');
204
205 if (Cookie::get('ORGaccess')) {
206 setcookie('ORGaccess', hash_encrypt($password), (time()+25920000), '/', '' ,0);
207 }
208
209 $page->changeTpl('motdepasse.success.tpl');
210 $page->run();
211 }
212
213 $page->changeTpl('motdepasse.tpl');
214 $page->addJsLink('javascript/motdepasse.js');
215 $page->assign('xorg_title','Polytechnique.org - Mon mot de passe');
216
217 return PL_OK;
218 }
219
220 function handler_smtppass(&$page)
221 {
222 global $globals;
223
224 $page->changeTpl('acces_smtp.tpl');
225 $page->assign('xorg_title','Polytechnique.org - Acces SMTP/NNTP');
226
227 $uid = Session::getInt('uid');
228 $pass = Env::get('smtppass1');
229 $log = Session::getMixed('log');
230
231 if (Env::get('op') == "Valider" && strlen($pass) >= 6
232 && Env::get('smtppass1') == Env::get('smtppass2'))
233 {
234 $globals->xdb->execute('UPDATE auth_user_md5 SET smtppass = {?}
235 WHERE user_id = {?}', $pass, $uid);
236 $page->trig('Mot de passe enregistré');
237 $log->log("passwd_ssl");
238 } elseif (Env::get('op') == "Supprimer") {
239 $globals->xdb->execute('UPDATE auth_user_md5 SET smtppass = ""
240 WHERE user_id = {?}', $uid);
241 $page->trig('Compte SMTP et NNTP supprimé');
242 $log->log("passwd_del");
243 }
244
245 $res = $globals->xdb->query("SELECT IF(smtppass != '', 'actif', '')
246 FROM auth_user_md5
247 WHERE user_id = {?}", $uid);
248 $page->assign('actif', $res->fetchOneCell());
249
250 return PL_OK;
251 }
252
253 function handler_recovery(&$page)
254 {
255 global $globals;
256
257 $page->changeTpl('recovery.tpl');
258
259 if (!Env::has('login') || !Env::has('birth')) {
260 return PL_OK;
261 }
262
263 if (!ereg('[0-3][0-9][0-1][0-9][1][9]([0-9]{2})', Env::get('birth'))) {
264 $page->trig_run('Date de naissance incorrecte ou incohérente');
265 }
266 $birth = sprintf('%s-%s-%s', substr(Env::get('birth'),4,4), substr(Env::get('birth'),2,2), substr(Env::get('birth'),0,2));
267
268 $mailorg = strtok(Env::get('login'), '@');
269
270 // paragraphe rajouté : si la date de naissance dans la base n'existe pas, on l'update
271 // avec celle fournie ici en espérant que c'est la bonne
272
273 $res = $globals->xdb->query(
274 "SELECT user_id, naissance
275 FROM auth_user_md5 AS u
276 INNER JOIN aliases AS a ON (u.user_id=a.id AND type!='homonyme')
277 WHERE a.alias={?} AND u.perms IN ('admin','user') AND u.deces=0", $mailorg);
278 list($uid, $naissance) = $res->fetchOneRow();
279
280 if ($naissance == $birth) {
281 $page->assign('ok', true);
282
283 $url = rand_url_id();
284 $globals->xdb->execute('INSERT INTO perte_pass (certificat,uid,created) VALUES ({?},{?},NOW())', $url, $uid);
285 $res = $globals->xdb->query('SELECT email FROM emails WHERE uid = {?} AND NOT FIND_IN_SET("filter", flags)', $uid);
286 $mails = implode(', ', $res->fetchColumn());
287
288 require_once "diogenes/diogenes.hermes.inc.php";
289 $mymail = new HermesMailer();
290 $mymail->setFrom('"Gestion des mots de passe" <support+password@polytechnique.org>');
291 $mymail->addTo($mails);
292 $mymail->setSubject('Ton certificat d\'authentification');
293 $mymail->setTxtBody("Visite la page suivante qui expire dans six heures :
294 {$globals->baseurl}/tmpPWD/$url
295
296 Si en cliquant dessus tu n'y arrives pas, copie intégralement l'adresse dans la barre de ton navigateur.
297
298 --
299 Polytechnique.org
300 \"Le portail des élèves & anciens élèves de l'Ecole polytechnique\"".(Post::get('email') ? "
301
302 Adresse de secours :
303 ".Post::get('email') : "")."
304
305 Mail envoyé à ".Env::get('login'));
306 $mymail->send();
307
308 // on cree un objet logger et on log l'evenement
309 $logger = $_SESSION['log'] = new DiogenesCoreLogger($uid);
310 $logger->log('recovery', $emails);
311 } else {
312 $page->trig('Pas de résultat correspondant aux champs entrés dans notre base de données.');
313 }
314
315 return PL_OK;
316 }
317
318 function handler_tmpPWD(&$page, $certif = null)
319 {
320 global $globals;
321
322 $globals->xdb->execute('DELETE FROM perte_pass
323 WHERE DATE_SUB(NOW(), INTERVAL 380 MINUTE) > created');
324
325 $res = $globals->xdb->query('SELECT uid FROM perte_pass WHERE certificat={?}', $certif);
326 $ligne = $res->fetchOneAssoc();
327 if (!$ligne) {
328 $page->changeTpl('index.tpl');
329 $page->kill("Cette adresse n'existe pas ou n'existe plus sur le serveur.");
330 }
331
332 $uid = $ligne["uid"];
333 if (Post::has('response2')) {
334 $password = Post::get('response2');
335 $logger = new DiogenesCoreLogger($uid);
336 $globals->xdb->query('UPDATE auth_user_md5 SET password={?}
337 WHERE user_id={?} AND perms IN("admin","user")',
338 $password, $uid);
339 $globals->xdb->query('DELETE FROM perte_pass WHERE certificat={?}', $certif);
340 $logger->log("passwd","");
341 $page->changeTpl('tmpPWD.success.tpl');
342 } else {
343 $page->changeTpl('motdepasse.tpl');
344 $page->addJsLink('javascript/motdepasse.js');
345 }
346
347 return PL_OK;
348 }
349
350 function handler_skin(&$page)
351 {
352 global $globals;
353
354 if (!$globals->skin->enable) {
355 redirect('./');
356 }
357
358 $page->changeTpl('skins.tpl');
359 $page->assign('xorg_title','Polytechnique.org - Skins');
360
361 if (Env::has('newskin')) { // formulaire soumis, traitons les données envoyées
362 $globals->xdb->execute('UPDATE auth_user_quick
363 SET skin={?} WHERE user_id={?}',
364 Env::getInt('newskin'),
365 Session::getInt('uid'));
366 set_skin();
367 }
368
369 $sql = "SELECT s.*,auteur,count(*) AS nb
370 FROM skins AS s
371 LEFT JOIN auth_user_quick AS a ON s.id=a.skin
372 WHERE skin_tpl != '' AND ext != ''
373 GROUP BY id ORDER BY s.date DESC";
374 $page->assign_by_ref('skins', $globals->xdb->iterator($sql));
375 return PL_OK;
376 }
377
378 function handler_exit(&$page, $level = null)
379 {
380 if (Session::has('suid')) {
381 if (Session::has('suid')) {
382 $a4l = Session::get('forlife');
383 $suid = Session::getMixed('suid');
384 $log = Session::getMixed('log');
385 $log->log("suid_stop", Session::get('forlife') . " by " . $suid['forlife']);
386 $_SESSION = $suid;
387 Session::kill('suid');
388 redirect($globals->baseurl.'/admin/utilisateurs.php?login='.$a4l);
389 } else {
390 redirect("events");
391 }
392 }
393
394 if ($level == 'forget' || $level == 'forgetall') {
395 setcookie('ORGaccess', '', time() - 3600, '/', '', 0);
396 Cookie::kill('ORGaccess');
397 if (isset($_SESSION['log']))
398 $_SESSION['log']->log("cookie_off");
399 }
400
401 if ($level == 'forgetuid' || $level == 'forgetall') {
402 setcookie('ORGuid', '', time() - 3600, '/', '', 0);
403 Cookie::kill('ORGuid');
404 setcookie('ORGdomain', '', time() - 3600, '/', '', 0);
405 Cookie::kill('ORGdomain');
406 }
407
408 if (isset($_SESSION['log'])) {
409 $ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
410 $_SESSION['log']->log('deconnexion',$ref);
411 }
412
413 XorgSession::destroy();
414
415 if (Get::has('redirect')) {
416 redirect(rawurldecode(Get::get('redirect')));
417 } else {
418 $page->changeTpl('exit.tpl');
419 }
420 return PL_OK;
421 }
422
423 function handler_rss(&$page, $user = null, $hash = null)
424 {
425 global $globals;
426
427 require_once 'rss.inc.php';
428
429 $uid = init_rss('rss.tpl', $user, $hash);
430
431 $rss = $globals->xdb->iterator(
432 'SELECT e.id, e.titre, e.texte, e.creation_date
433 FROM auth_user_md5 AS u
434 INNER JOIN evenements AS e ON ( (e.promo_min = 0 || e.promo_min <= u.promo)
435 AND (e.promo_max = 0 || e.promo_max >= u.promo) )
436 WHERE u.user_id = {?} AND FIND_IN_SET(e.flags, "valide")
437 AND peremption >= NOW()', $uid);
438 $page->assign('rss', $rss);
439
440 return PL_OK;
441 }
442 }
443
444 ?>