0489b10029b3c11923498b7300b2178bfd3f1e14
[platal.git] / modules / platal.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2007 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 'prefs/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 'review' => $this->make_hook('review', AUTH_PUBLIC),
59 'deconnexion.php' => $this->make_hook('exit', AUTH_PUBLIC),
60 );
61 }
62
63 function handler_index(&$page)
64 {
65 if (S::logged()) {
66 pl_redirect('events');
67 }
68 }
69
70 function handler_cacert(&$page)
71 {
72 $data = file_get_contents("/etc/ssl/xorgCA/cacert.pem","r");
73 header("Pragma:");
74 header("Set-Cookie:");
75 header("Cache-Control:");
76 header("Expires:");
77 header("Content-Type: application/x-x509-ca-cert");
78 header("Content-Length: ".strlen($data));
79 echo $data;
80 exit;
81 }
82
83 function handler_changelog(&$page)
84 {
85 $page->changeTpl('platal/changeLog.tpl');
86
87 $clog = pl_entities(file_get_contents(dirname(__FILE__).'/../ChangeLog'));
88 // url catch only (not all wiki syntax)
89 $clog = preg_replace(array(
90 '/((?:https?|ftp):\/\/(?:\.*,*[\w@~%$£µ&i#\-+=_\/\?;])*)/ui',
91 '/(\s|^)www\.((?:\.*,*[\w@~%$£µ&i#\-+=_\/\?;])*)/iu',
92 '/(?:mailto:)?([a-z0-9.\-+_]+@([\-.+_]?[a-z0-9])+)/i'),
93 array(
94 '<a href="\\0">\\0</a>',
95 '\\1<a href="http://www.\\2">www.\\2</a>',
96 '<a href="mailto:\\0">\\0</a>'),
97 $clog);
98 $clog = preg_replace('!(#[0-9]+(,[0-9]+)*)!e', 'bugize("\1")', $clog);
99 $clog = preg_replace('!vim:.*$!', '', $clog);
100 $page->assign('ChangeLog', $clog);
101 }
102
103 function __set_rss_state($state)
104 {
105 if ($state) {
106 $_SESSION['core_rss_hash'] = rand_url_id(16);
107 XDB::execute('UPDATE auth_user_quick
108 SET core_rss_hash={?} WHERE user_id={?}',
109 S::v('core_rss_hash'), S::v('uid'));
110 } else {
111 XDB::execute('UPDATE auth_user_quick
112 SET core_rss_hash="" WHERE user_id={?}',
113 S::v('uid'));
114 S::kill('core_rss_hash');
115 }
116 }
117
118 function handler_prefs(&$page)
119 {
120 $page->changeTpl('platal/preferences.tpl');
121 $page->assign('xorg_title','Polytechnique.org - Mes préférences');
122
123 if (Post::has('mail_fmt')) {
124 $fmt = Post::v('mail_fmt');
125 if ($fmt != 'texte') $fmt = 'html';
126 XDB::execute("UPDATE auth_user_quick
127 SET core_mail_fmt = '$fmt'
128 WHERE user_id = {?}",
129 S::v('uid'));
130 $_SESSION['mail_fmt'] = $fmt;
131 }
132
133 if (Post::has('rss')) {
134 $this->__set_rss_state(Post::b('rss'));
135 }
136 }
137
138 function handler_webredir(&$page)
139 {
140 $page->changeTpl('platal/webredirect.tpl');
141
142 $page->assign('xorg_title','Polytechnique.org - Redirection de page WEB');
143
144 $log =& S::v('log');
145 $url = Env::v('url');
146
147 if (Env::v('submit') == 'Valider' and Env::has('url')) {
148 XDB::execute('UPDATE auth_user_quick
149 SET redirecturl = {?} WHERE user_id = {?}',
150 $url, S::v('uid'));
151 $log->log('carva_add', 'http://'.Env::v('url'));
152 $page->trig("Redirection activée vers <a href='http://$url'>$url</a>");
153 } elseif (Env::v('submit') == "Supprimer") {
154 XDB::execute("UPDATE auth_user_quick
155 SET redirecturl = ''
156 WHERE user_id = {?}",
157 S::v('uid'));
158 $log->log("carva_del", $url);
159 Post::kill('url');
160 $page->trig('Redirection supprimée');
161 }
162
163 $res = XDB::query('SELECT redirecturl
164 FROM auth_user_quick
165 WHERE user_id = {?}',
166 S::v('uid'));
167 $page->assign('carva', $res->fetchOneCell());
168 }
169
170 function handler_prefs_rss(&$page)
171 {
172 $page->changeTpl('platal/filrss.tpl');
173
174 $page->assign('goback', Env::v('referer', 'login'));
175
176 if (Env::v('act_rss') == 'Activer') {
177 $this->__set_rss_state(true);
178 $page->trig("Ton Fil RSS est activé.");
179 }
180 }
181
182 function handler_password(&$page)
183 {
184 if (Post::has('response2')) {
185 require_once 'secure_hash.inc.php';
186
187 $_SESSION['password'] = $password = Post::v('response2');
188
189 XDB::execute('UPDATE auth_user_md5
190 SET password={?}
191 WHERE user_id={?}', $password,
192 S::v('uid'));
193
194 $log =& S::v('log');
195 $log->log('passwd', '');
196
197 if (Cookie::v('ORGaccess')) {
198 setcookie('ORGaccess', hash_encrypt($password), (time()+25920000), '/', '' ,0);
199 }
200
201 $page->changeTpl('platal/motdepasse.success.tpl');
202 $page->run();
203 }
204
205 $page->changeTpl('platal/motdepasse.tpl');
206 $page->addJsLink('motdepasse.js');
207 $page->assign('xorg_title','Polytechnique.org - Mon mot de passe');
208 }
209
210 function handler_smtppass(&$page)
211 {
212 $page->changeTpl('platal/acces_smtp.tpl');
213 $page->assign('xorg_title','Polytechnique.org - Acces SMTP/NNTP');
214
215 require_once 'wiki.inc.php';
216 wiki_require_page('Xorg.SMTPSécurisé');
217 wiki_require_page('Xorg.NNTPSécurisé');
218
219 $uid = S::v('uid');
220 $pass = Env::v('smtppass1');
221 $log = S::v('log');
222
223 if (Env::v('op') == "Valider" && strlen($pass) >= 6
224 && Env::v('smtppass1') == Env::v('smtppass2'))
225 {
226 XDB::execute('UPDATE auth_user_md5 SET smtppass = {?}
227 WHERE user_id = {?}', $pass, $uid);
228 $page->trig('Mot de passe enregistré');
229 $log->log("passwd_ssl");
230 } elseif (Env::v('op') == "Supprimer") {
231 XDB::execute('UPDATE auth_user_md5 SET smtppass = ""
232 WHERE user_id = {?}', $uid);
233 $page->trig('Compte SMTP et NNTP supprimé');
234 $log->log("passwd_del");
235 }
236
237 $res = XDB::query("SELECT IF(smtppass != '', 'actif', '')
238 FROM auth_user_md5
239 WHERE user_id = {?}", $uid);
240 $page->assign('actif', $res->fetchOneCell());
241 }
242
243 function handler_recovery(&$page)
244 {
245 global $globals;
246
247 $page->changeTpl('platal/recovery.tpl');
248
249 if (!Env::has('login') || !Env::has('birth')) {
250 return;
251 }
252
253 if (!ereg('[0-3][0-9][0-1][0-9][1][9]([0-9]{2})', Env::v('birth'))) {
254 $page->trig('Date de naissance incorrecte ou incohérente');
255 return;
256 }
257
258 $birth = sprintf('%s-%s-%s',
259 substr(Env::v('birth'), 4, 4),
260 substr(Env::v('birth'), 2, 2),
261 substr(Env::v('birth'), 0, 2));
262
263 $mailorg = strtok(Env::v('login'), '@');
264
265 // paragraphe rajouté : si la date de naissance dans la base n'existe pas, on l'update
266 // avec celle fournie ici en espérant que c'est la bonne
267
268 $res = XDB::query(
269 "SELECT user_id, naissance
270 FROM auth_user_md5 AS u
271 INNER JOIN aliases AS a ON (u.user_id=a.id AND type != 'homonyme')
272 WHERE a.alias={?} AND u.perms IN ('admin','user') AND u.deces=0", $mailorg);
273 list($uid, $naissance) = $res->fetchOneRow();
274
275 if ($naissance == $birth) {
276 $res = XDB::query("SELECT COUNT(*)
277 FROM emails
278 WHERE uid = {?} AND flags != 'panne' AND flags != 'filter'", $uid);
279 $count = intval($res->fetchOneCell());
280 if ($count == 0) {
281 $page->assign('no_addr', true);
282 return;
283 }
284
285 $page->assign('ok', true);
286
287 $url = rand_url_id();
288 XDB::execute('INSERT INTO perte_pass (certificat,uid,created)
289 VALUES ({?},{?},NOW())', $url, $uid);
290 $res = XDB::query('SELECT email
291 FROM emails
292 WHERE uid = {?} AND email = {?}',
293 $uid, Post::v('email'));
294 if ($res->numRows()) {
295 $mails = $res->fetchOneCell();
296 } else {
297 $res = XDB::query('SELECT email
298 FROM emails
299 WHERE uid = {?} AND NOT FIND_IN_SET("filter", flags)', $uid);
300 $mails = implode(', ', $res->fetchColumn());
301 }
302 $mymail = new PlMailer();
303 $mymail->setFrom('"Gestion des mots de passe" <support+password@' . $globals->mail->domain . '>');
304 $mymail->addTo($mails);
305 $mymail->setSubject('Ton certificat d\'authentification');
306 $mymail->setTxtBody("Visite la page suivante qui expire dans six heures :
307 {$globals->baseurl}/tmpPWD/$url
308
309 Si en cliquant dessus tu n'y arrives pas, copie intégralement l'adresse dans la barre de ton navigateur. Si tu n'as pas utilisé ce lien dans six heures, tu peux tout simplement recommencer cette procédure.
310
311 --
312 Polytechnique.org
313 \"Le portail des élèves & anciens élèves de l'Ecole polytechnique\"
314
315 Mail envoyé à ".Env::v('login') . (Post::has('email') ? "
316 Adresse de secours : " . Post::v('email') : ""));
317 $mymail->send();
318
319 // on cree un objet logger et on log l'evenement
320 $logger = $_SESSION['log'] = new CoreLogger($uid);
321 $logger->log('recovery', $mails);
322 } else {
323 $page->trig('Les informations que tu as rentrées ne permettent pas de récupérer ton mot de passe.<br />'.
324 'Si tu as un homonyme, utilise prenom.nom.promo comme login');
325 }
326 }
327
328 function handler_tmpPWD(&$page, $certif = null)
329 {
330 XDB::execute('DELETE FROM perte_pass
331 WHERE DATE_SUB(NOW(), INTERVAL 380 MINUTE) > created');
332
333 $res = XDB::query('SELECT uid FROM perte_pass WHERE certificat={?}', $certif);
334 $ligne = $res->fetchOneAssoc();
335 if (!$ligne) {
336 $page->changeTpl('platal/index.tpl');
337 $page->kill("Cette adresse n'existe pas ou n'existe plus sur le serveur.");
338 }
339
340 $uid = $ligne["uid"];
341 if (Post::has('response2')) {
342 $password = Post::v('response2');
343 $logger = new CoreLogger($uid);
344 XDB::query('UPDATE auth_user_md5 SET password={?}
345 WHERE user_id={?} AND perms IN("admin","user")',
346 $password, $uid);
347 XDB::query('DELETE FROM perte_pass WHERE certificat={?}', $certif);
348 $logger->log("passwd","");
349 $page->changeTpl('platal/tmpPWD.success.tpl');
350 } else {
351 $page->changeTpl('platal/motdepasse.tpl');
352 $page->addJsLink('motdepasse.js');
353 }
354 }
355
356 function handler_skin(&$page)
357 {
358 global $globals;
359
360 $page->changeTpl('platal/skins.tpl');
361 $page->assign('xorg_title','Polytechnique.org - Skins');
362
363 if (Env::has('newskin')) { // formulaire soumis, traitons les données envoyées
364 XDB::execute('UPDATE auth_user_quick
365 SET skin={?} WHERE user_id={?}',
366 Env::i('newskin'), S::v('uid'));
367 S::kill('skin');
368 set_skin();
369 }
370
371 $res = XDB::query('SELECT id FROM skins WHERE skin_tpl={?}', S::v('skin'));
372 $page->assign('skin_id', $res->fetchOneCell());
373
374 $sql = "SELECT s.*,auteur,count(*) AS nb
375 FROM skins AS s
376 LEFT JOIN auth_user_quick AS a ON s.id=a.skin
377 WHERE skin_tpl != '' AND ext != ''
378 GROUP BY id ORDER BY s.date DESC";
379 $page->assign('skins', XDB::iterator($sql));
380 }
381
382 function handler_exit(&$page, $level = null)
383 {
384 if (S::has('suid')) {
385 $a4l = S::v('forlife');
386 $suid = S::v('suid');
387 $log = S::v('log');
388 $log->log("suid_stop", S::v('forlife') . " by " . $suid['forlife']);
389 $_SESSION = $suid;
390 S::kill('suid');
391 pl_redirect('admin/user/' . $a4l);
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 http_redirect(rawurldecode(Get::v('redirect')));
417 } else {
418 $page->changeTpl('platal/exit.tpl');
419 }
420 }
421
422 function handler_review(&$page, $action = null)
423 {
424 require_once 'wiki.inc.php';
425 $dir = wiki_work_dir();
426 $dom = 'Review';
427 if (@$GLOBALS['IS_XNET_SITE']) {
428 $dom .= 'Xnet';
429 }
430 if (!is_dir($dir)) {
431 $page->kill("Impossible de trouver le wiki");
432 }
433 if (!file_exists($dir . '/' . $dom . '.Admin')) {
434 $page->kill("Impossible de trouver la page d'administration");
435 }
436 $conf = preg_grep('/^text=/', explode("\n", file_get_contents($dir . '/' . $dom . '.Admin')));
437 $conf = preg_split('/(text\=|\%0a)/', array_shift($conf), -1, PREG_SPLIT_NO_EMPTY);
438 $wiz = new PlWizard('Tour d\'horizon', 'core/plwizard.tpl', true);
439 foreach ($conf as $line) {
440 $list = preg_split('/\s*[*|]\s*/', $line, -1, PREG_SPLIT_NO_EMPTY);
441 $wiz->addPage('ReviewPage', $list[0], $list[1]);
442 }
443 $wiz->apply($page, 'review', $action);
444 }
445 }
446
447 __autoload('PlWizard');
448 class ReviewPage implements PlWizardPage
449 {
450 public function __construct(PlWizard &$wiz) { }
451 public function template() { return 'platal/index.tpl'; }
452 public function prepare(PlatalPage &$page) { }
453 public function process() { }
454 }
455
456 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
457 ?>