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