Port remaining queries from module events.
[platal.git] / modules / events.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2009 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 class EventsModule extends PLModule
23 {
24 function handlers()
25 {
26 return array(
27 'events' => $this->make_hook('ev', AUTH_COOKIE),
28 'rss' => $this->make_hook('rss', AUTH_PUBLIC, 'user', NO_HTTPS),
29 'events/preview' => $this->make_hook('preview', AUTH_PUBLIC, 'user', NO_AUTH),
30 'events/photo' => $this->make_hook('photo', AUTH_PUBLIC),
31 'events/submit' => $this->make_hook('ev_submit', AUTH_MDP),
32 'admin/events' => $this->make_hook('admin_events', AUTH_MDP, 'admin'),
33
34 'ajax/tips' => $this->make_hook('tips', AUTH_COOKIE, 'user', NO_AUTH),
35 'admin/tips' => $this->make_hook('admin_tips', AUTH_MDP, 'admin'),
36 );
37 }
38
39 private function get_tips($exclude = null)
40 {
41 global $globals;
42 // Add a new special tip when changing plat/al version
43 if ($globals->version != S::v('last_version') && is_null($exclude)) {
44 XDB::execute('UPDATE accounts
45 SET last_version = {?}
46 WHERE uid = {?}',
47 $globals->version, S::i('uid'));
48 return array('id' => 0,
49 'titre' => 'Bienvenue sur la nouvelle version du site !',
50 'text' => 'Le site a été mis à jour depuis ta dernière visite vers la version ' . $globals->version
51 . '.<br /> Nous t\'invitons à <a href="review">faire un tour d\'horizon des '
52 . 'nouveautés</a>.<br /><br />'
53 . 'Tu peux également retrouver ces informations sur <a href="banana/xorg.m4x.innovation">'
54 . 'les forums</a>, ou sur <a href="changelog">la liste exhaustive des modifications</a>.',
55 'priorite' => 255,
56 'promo_min' => 0,
57 'promo_max' => 0,
58 'state' => 'active',
59 'special' => true);
60 }
61
62 $exclude = is_null($exclude) ? '' : ' AND id != ' . intval($exclude) . ' ';
63 $priority = rand(0, 510);
64 do {
65 $priority = (int)($priority/2);
66 $res = XDB::query("SELECT *
67 FROM tips
68 WHERE (peremption = '0000-00-00' OR peremption > CURDATE())
69 AND (promo_min = 0 OR promo_min <= {?})
70 AND (promo_max = 0 OR promo_max >= {?})
71 AND (priorite >= {?})
72 AND (state = 'active')
73 $exclude
74 ORDER BY RAND()
75 LIMIT 1",
76 S::i('promo'), S::i('promo'), $priority);
77 } while ($priority && !$res->numRows());
78 if (!$res->numRows()) {
79 return null;
80 }
81 return $res->fetchOneAssoc();
82 }
83
84 private function upload_image(PlPage &$page, PlUpload &$upload)
85 {
86 if (@!$_FILES['image']['tmp_name'] && !Env::v('image_url')) {
87 return true;
88 }
89 if (!$upload->upload($_FILES['image']) && !$upload->download(Env::v('image_url'))) {
90 $page->trigError('Impossible de télécharger l\'image');
91 return false;
92 } elseif (!$upload->isType('image')) {
93 $page->trigError('Le fichier n\'est pas une image valide au format JPEG, GIF ou PNG.');
94 $upload->rm();
95 return false;
96 } elseif (!$upload->resizeImage(200, 300, 100, 100, 32284)) {
97 $page->trigError('Impossible de retraiter l\'image');
98 return false;
99 }
100 return true;
101 }
102
103 function handler_ev(&$page, $action = 'list', $eid = null, $pound = null)
104 {
105 $page->changeTpl('events/index.tpl');
106 $page->addJsLink('ajax.js');
107 $page->assign('tips', $this->get_tips());
108
109 // Profile update (appears when profile is > 400d old), and birthday
110 // oneboxes.
111 $user = S::user();
112 $profile = $user->profile();
113 if (!is_null($profile)) {
114 if (strtotime($profile->last_change) < time() - (400 * 86400)) {
115 $page->assign('fiche_incitation', $profile->last_change);
116 }
117 if ($profile->next_birthday == date('Y-m-d')) {
118 $birthyear = (int)date('Y', strtotime($profile->birthdate));
119 $curyear = (int)date('Y');
120 $page->assign('birthday', $curyear - $birthyear);
121 }
122 }
123
124 // No-photo onebox.
125 $res = XDB::query("SELECT COUNT(*)
126 FROM photo
127 WHERE uid = {?}",
128 S::user()->id());
129 $page->assign('photo_incitation', $res->fetchOneCell() == 0);
130
131 // Geo-location onebox.
132 require_once 'geoloc.inc.php';
133 $res = localize_addresses(S::user()->id());
134 $page->assign('geoloc_incitation', count($res));
135
136 // Direct link to the RSS feed, when available.
137 if (S::hasAuthToken()) {
138 $page->setRssLink('Polytechnique.org :: News',
139 '/rss/'.S::v('hruid') .'/'.S::v('token').'/rss.xml');
140 }
141
142 // Hide the read event, and reload the page to get to the next event.
143 if ($action == 'read' && $eid) {
144 XDB::execute('DELETE ev.*
145 FROM evenements_vus AS ev
146 INNER JOIN evenements AS e ON e.id = ev.evt_id
147 WHERE peremption < NOW()');
148 XDB::execute('REPLACE INTO evenements_vus VALUES({?},{?})',
149 $eid, S::v('uid'));
150 pl_redirect('events#'.$pound);
151 }
152
153 // Unhide the requested event, and reload the page to display it.
154 if ($action == 'unread' && $eid) {
155 XDB::execute('DELETE FROM evenements_vus
156 WHERE evt_id = {?} AND user_id = {?}',
157 $eid, S::v('uid'));
158 pl_redirect('events#newsid'.$eid);
159 }
160
161 function next_event(PlIterator &$it)
162 {
163 $user = S::user();
164 while ($body = $it->next()) {
165 $uf = UserFilter::getLegacy($body['promo_min'], $body['promo_max']);
166 if ($uf->checkUser($user)) {
167 return $body;
168 }
169 }
170 return null;
171 }
172
173 // Fetch the events to display, along with their metadata.
174 $array = array();
175 $it = XDB::iterator("SELECT e.id, e.titre, e.texte, e.post_id, e.user_id,
176 p.x, p.y, p.attach IS NOT NULL AS img, FIND_IN_SET('wiki', e.flags) AS wiki,
177 FIND_IN_SET('important', e.flags) AS important,
178 e.creation_date > DATE_SUB(CURDATE(), INTERVAL 2 DAY) AS news,
179 e.peremption < DATE_ADD(CURDATE(), INTERVAL 2 DAY) AS end,
180 ev.user_id IS NULL AS nonlu, e.promo_min, e.promo_max
181 FROM evenements AS e
182 LEFT JOIN evenements_photo AS p ON (e.id = p.eid)
183 LEFT JOIN evenements_vus AS ev ON (e.id = ev.evt_id AND ev.user_id = {?})
184 WHERE FIND_IN_SET('valide', e.flags) AND peremption >= NOW()
185 ORDER BY important DESC, news DESC, end DESC, e.peremption, e.creation_date DESC",
186 S::i('uid'));
187 $cats = array('important', 'news', 'end', 'body');
188 $body = next_event($it);
189 foreach ($cats as $cat) {
190 $data = array();
191 if (!$body) {
192 continue;
193 }
194 do {
195 if ($cat == 'body' || $body[$cat]) {
196 $data[] = $body;
197 } else {
198 break;
199 }
200 $body = next_event($it);
201 } while ($body);
202 if (!empty($data)) {
203 $array[$cat] = $data;
204 }
205 }
206
207 $page->assign_by_ref('events', $array);
208 }
209
210 function handler_photo(&$page, $eid = null, $valid = null)
211 {
212 if ($eid && $eid != 'valid') {
213 $res = XDB::query("SELECT * FROM evenements_photo WHERE eid = {?}", $eid);
214 if ($res->numRows()) {
215 $photo = $res->fetchOneAssoc();
216 header('Content-Type: image/' . $photo['attachmime']);
217 echo $photo['attach'];
218 exit;
219 }
220 } elseif ($eid == 'valid') {
221 require_once 'validations.inc.php';
222 $valid = Validate::get_request_by_id($valid);
223 if ($valid && $valid->img) {
224 header('Content-Type: image/' . $valid->imgtype);
225 echo $valid->img;
226 exit;
227 }
228 } else {
229 $upload = new PlUpload(S::user()->login(), 'event');
230 if ($upload->exists() && $upload->isType('image')) {
231 header('Content-Type: ' . $upload->contentType());
232 echo $upload->getContents();
233 exit;
234 }
235 }
236 global $globals;
237 header('Content-Type: image/png');
238 echo file_get_contents($globals->spoolroot . '/htdocs/images/logo.png');
239 exit;
240 }
241
242 function handler_rss(&$page, $user = null, $hash = null)
243 {
244 $this->load('feed.inc.php');
245 $feed = new EventFeed();
246 return $feed->run($page, $user, $hash);
247 }
248
249 function handler_preview(&$page)
250 {
251 $page->changeTpl('events/preview.tpl', NO_SKIN);
252 $texte = Get::v('texte');
253 if (!is_utf8($texte)) {
254 $texte = utf8_encode($texte);
255 }
256 $titre = Get::v('titre');
257 if (!is_utf8($titre)) {
258 $titre = utf8_encode($titre);
259 }
260 $page->assign('texte', $texte);
261 $page->assign('titre', $titre);
262 header('Content-Type: text/html; charset=utf-8');
263 }
264
265 function handler_ev_submit(&$page)
266 {
267 $page->changeTpl('events/submit.tpl');
268 $page->addJsLink('ajax.js');
269
270 $wp = new PlWikiPage('Xorg.Annonce');
271 $wp->buildCache();
272
273 $titre = Post::v('titre');
274 $texte = Post::v('texte');
275 $promo_min = Post::i('promo_min');
276 $promo_max = Post::i('promo_max');
277 $peremption = Post::i('peremption');
278 $valid_mesg = Post::v('valid_mesg');
279 $action = Post::v('action');
280 $upload = new PlUpload(S::user()->login(), 'event');
281 $this->upload_image($page, $upload);
282
283 if (($promo_min > $promo_max && $promo_max != 0)||
284 ($promo_min != 0 && ($promo_min <= 1900 || $promo_min >= 2020)) ||
285 ($promo_max != 0 && ($promo_max <= 1900 || $promo_max >= 2020)))
286 {
287 $page->trigError("L'intervalle de promotions n'est pas valide");
288 $action = null;
289 }
290
291 $page->assign('titre', $titre);
292 $page->assign('texte', $texte);
293 $page->assign('promo_min', $promo_min);
294 $page->assign('promo_max', $promo_max);
295 $page->assign('peremption', $peremption);
296 $page->assign('valid_mesg', $valid_mesg);
297 $page->assign('action', strtolower($action));
298 $page->assign_by_ref('upload', $upload);
299
300 if ($action == 'Supprimer l\'image') {
301 $upload->rm();
302 $page->assign('action', false);
303 } elseif ($action && (!trim($texte) || !trim($titre))) {
304 $page->trigError("L'article doit avoir un titre et un contenu");
305 } elseif ($action) {
306 S::assert_xsrf_token();
307
308 require_once 'validations.inc.php';
309 $evtreq = new EvtReq($titre, $texte, $promo_min, $promo_max,
310 $peremption, $valid_mesg, S::user(), $upload);
311 $evtreq->submit();
312 $page->assign('ok', true);
313 } elseif (!Env::v('preview')) {
314 $upload->rm();
315 }
316 }
317
318 function handler_tips(&$page, $tips = null)
319 {
320 header('Content-Type: text/html; charset="UTF-8"');
321 $page->changeTpl('include/tips.tpl', NO_SKIN);
322 $page->assign('tips', $this->get_tips($tips));
323 }
324
325 function handler_admin_tips(&$page, $action = 'list', $id = null)
326 {
327 $page->setTitle('Administration - Astuces');
328 $page->assign('title', 'Gestion des Astuces');
329 $table_editor = new PLTableEditor('admin/tips', 'tips', 'id');
330 $table_editor->describe('peremption', 'date de péremption', true);
331 $table_editor->describe('promo_min', 'promo. min (0 aucune)', false);
332 $table_editor->describe('promo_max', 'promo. max (0 aucune)', false);
333 $table_editor->describe('titre', 'titre', true);
334 $table_editor->describe('state', 'actif', true);
335 $table_editor->describe('text', 'texte (html) de l\'astuce', false);
336 $table_editor->describe('priorite', '0<=priorité<=255', true);
337 $table_editor->list_on_edit(false);
338 $table_editor->apply($page, $action, $id);
339 if (($action == 'edit' && !is_null($id)) || $action == 'update') {
340 $page->changeTpl('events/admin_tips.tpl');
341 }
342 }
343
344 function handler_admin_events(&$page, $action = 'list', $eid = null)
345 {
346 $page->changeTpl('events/admin.tpl');
347 $page->addJsLink('ajax.js');
348 $page->setTitle('Administration - Evenements');
349 $page->register_modifier('hde', 'html_entity_decode');
350
351 $arch = $action == 'archives';
352 $page->assign('action', $action);
353
354 $upload = new PlUpload(S::user()->login(), 'event');
355 if ((Env::has('preview') || Post::v('action') == "Proposer") && $eid) {
356 $action = 'edit';
357 $this->upload_image($page, $upload);
358 }
359
360 if (Post::v('action') == 'Pas d\'image' && $eid) {
361 S::assert_xsrf_token();
362 $upload->rm();
363 XDB::execute("DELETE FROM evenements_photo WHERE eid = {?}", $eid);
364 $action = 'edit';
365 } elseif (Post::v('action') == 'Supprimer l\'image' && $eid) {
366 S::assert_xsrf_token();
367 $upload->rm();
368 $action = 'edit';
369 } elseif (Post::v('action') == "Proposer" && $eid) {
370 S::assert_xsrf_token();
371 $promo_min = Post::i('promo_min');
372 $promo_max = Post::i('promo_max');
373 if (($promo_min != 0 && ($promo_min <= 1900 || $promo_min >= 2020)) ||
374 ($promo_max != 0 && ($promo_max <= 1900 || $promo_max >= 2020 || $promo_max < $promo_min)))
375 {
376 $page->trigError("L'intervalle de promotions $promo_min -> $promo_max n'est pas valide");
377 $action = 'edit';
378 } else {
379 $res = XDB::query('SELECT flags FROM evenements WHERE id = {?}', $eid);
380 $flags = new PlFlagSet($res->fetchOneCell());
381 $flags->addFlag('wiki');
382 if (Post::v('important')) {
383 $flags->addFlag('important');
384 } else {
385 $flags->rmFlag('important');
386 }
387
388 XDB::execute('UPDATE evenements
389 SET creation_date = creation_date,
390 titre={?}, texte={?}, peremption={?}, promo_min={?}, promo_max={?},
391 flags = {?}
392 WHERE id = {?}',
393 Post::v('titre'), Post::v('texte'), Post::v('peremption'),
394 Post::v('promo_min'), Post::v('promo_max'),
395 $flags, $eid);
396 if ($upload->exists() && list($x, $y, $type) = $upload->imageInfo()) {
397 XDB::execute('REPLACE INTO evenements_photo
398 SET eid = {?}, attachmime = {?}, x = {?}, y = {?}, attach = {?}',
399 $eid, $type, $x, $y, $upload->getContents());
400 $upload->rm();
401 }
402 }
403 }
404
405 if ($action == 'edit') {
406 $res = XDB::query('SELECT titre, texte, peremption, promo_min, promo_max, FIND_IN_SET(\'important\', flags),
407 attach IS NOT NULL
408 FROM evenements AS e
409 LEFT JOIN evenements_photo AS p ON(e.id = p.eid)
410 WHERE id={?}', $eid);
411 list($titre, $texte, $peremption, $promo_min, $promo_max, $important, $img) = $res->fetchOneRow();
412 $page->assign('titre',$titre);
413 $page->assign('texte',$texte);
414 $page->assign('promo_min',$promo_min);
415 $page->assign('promo_max',$promo_max);
416 $page->assign('peremption',$peremption);
417 $page->assign('important', $important);
418 $page->assign('eid', $eid);
419 $page->assign('img', $img);
420 $page->assign_by_ref('upload', $upload);
421
422 $select = "";
423 for ($i = 1 ; $i < 30 ; $i++) {
424 $p_stamp=date("Ymd",time()+3600*24*$i);
425 $year=substr($p_stamp,0,4);
426 $month=substr($p_stamp,4,2);
427 $day=substr($p_stamp,6,2);
428
429 $select .= "<option value=\"$p_stamp\""
430 . (($p_stamp == strtr($peremption, array("-" => ""))) ? " selected" : "")
431 . "> $day / $month / $year</option>\n";
432 }
433 $page->assign('select',$select);
434 } else {
435 switch ($action) {
436 case 'delete':
437 S::assert_xsrf_token();
438 XDB::execute('DELETE from evenements
439 WHERE id = {?}', $eid);
440 break;
441
442 case "archive":
443 S::assert_xsrf_token();
444 XDB::execute('UPDATE evenements
445 SET creation_date = creation_date, flags = CONCAT(flags,",archive")
446 WHERE id = {?}', $eid);
447 break;
448
449 case "unarchive":
450 S::assert_xsrf_token();
451 XDB::execute('UPDATE evenements
452 SET creation_date = creation_date, flags = REPLACE(flags,"archive","")
453 WHERE id = {?}', $eid);
454 $action = 'archives';
455 $arch = true;
456 break;
457
458 case "valid":
459 S::assert_xsrf_token();
460 XDB::execute('UPDATE evenements
461 SET creation_date = creation_date, flags = CONCAT(flags,",valide")
462 WHERE id = {?}', $eid);
463 break;
464
465 case "unvalid":
466 S::assert_xsrf_token();
467 XDB::execute('UPDATE evenements
468 SET creation_date = creation_date, flags = REPLACE(flags,"valide", "")
469 WHERE id = {?}', $eid);
470 break;
471 }
472
473 $pid = ($eid && $action == 'preview') ? $eid : -1;
474 $sql = "SELECT e.id, e.titre, e.texte,e.id = $pid AS preview, e.user_id,
475 DATE_FORMAT(e.creation_date,'%d/%m/%Y %T') AS creation_date,
476 DATE_FORMAT(e.peremption,'%d/%m/%Y') AS peremption,
477 e.promo_min, e.promo_max,
478 FIND_IN_SET('valide', e.flags) AS fvalide,
479 FIND_IN_SET('archive', e.flags) AS farch,
480 FIND_IN_SET('wiki', e.flags) AS wiki
481 FROM evenements AS e
482 WHERE ".($arch ? "" : "!")."FIND_IN_SET('archive',e.flags)
483 ORDER BY FIND_IN_SET('valide',e.flags), e.peremption DESC";
484 $page->assign('evs', XDB::iterator($sql));
485 }
486 $page->assign('arch', $arch);
487 $page->assign('admin_evts', true);
488 }
489 }
490
491 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
492 ?>