REPLACE INTO should only be used if the data deletion is wanted.
[platal.git] / modules / events.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 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::user()->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 reminder_tips
68 WHERE (expiration = '0000-00-00' OR expiration > CURDATE())
69 AND (promo_min = 0 OR promo_min <= {?})
70 AND (promo_max = 0 OR promo_max >= {?})
71 AND (priority >= {?})
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
108 $user = S::user();
109
110 /** XXX: Tips and reminder only for user with 'email' permission.
111 * We can do better in the future by storing a userfilter
112 * with the tip/reminder.
113 */
114 if ($user->checkPerms(User::PERM_MAIL)) {
115 $page->assign('tips', $this->get_tips());
116
117 }
118
119 // Adds a reminder onebox to the page.
120 require_once 'reminder.inc.php';
121 if (($reminder = Reminder::GetCandidateReminder($user))) {
122 $reminder->Prepare($page);
123 }
124
125 // Wishes "Happy birthday" when required
126 $profile = $user->profile();
127 if (!is_null($profile)) {
128 if ($profile->next_birthday == date('Y-m-d')) {
129 $birthyear = (int)date('Y', strtotime($profile->birthdate));
130 $curyear = (int)date('Y');
131 $page->assign('birthday', $curyear - $birthyear);
132 }
133 }
134
135 // Direct link to the RSS feed, when available.
136 if (S::hasAuthToken()) {
137 $page->setRssLink('Polytechnique.org :: News',
138 '/rss/' . S::v('hruid') . '/' . S::user()->token . '/rss.xml');
139 }
140
141 // Hide the read event, and reload the page to get to the next event.
142 if ($action == 'read' && $eid) {
143 XDB::execute('DELETE ev.*
144 FROM announce_read AS ev
145 INNER JOIN announces AS e ON e.id = ev.evt_id
146 WHERE expiration < NOW()');
147 XDB::execute('INSERT IGNORE INTO announce_read (evt_id, uid)
148 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 announce_read
156 WHERE evt_id = {?} AND uid = {?}',
157 $eid, S::v('uid'));
158 pl_redirect('events#newsid'.$eid);
159 }
160
161 // Fetch the events to display, along with their metadata.
162 $array = array();
163 $it = XDB::iterator("SELECT e.id, e.titre, e.texte, e.post_id, e.uid,
164 p.x, p.y, p.attach IS NOT NULL AS img, FIND_IN_SET('wiki', e.flags) AS wiki,
165 FIND_IN_SET('important', e.flags) AS important,
166 e.creation_date > DATE_SUB(CURDATE(), INTERVAL 2 DAY) AS news,
167 e.expiration < DATE_ADD(CURDATE(), INTERVAL 2 DAY) AS end,
168 ev.uid IS NULL AS nonlu, e.promo_min, e.promo_max
169 FROM announces AS e
170 LEFT JOIN announce_photos AS p ON (e.id = p.eid)
171 LEFT JOIN announce_read AS ev ON (e.id = ev.evt_id AND ev.uid = {?})
172 WHERE FIND_IN_SET('valide', e.flags) AND expiration >= NOW()
173 ORDER BY important DESC, news DESC, end DESC, e.expiration, e.creation_date DESC",
174 S::i('uid'));
175 $cats = array('important', 'news', 'end', 'body');
176
177 $this->load('feed.inc.php');
178 $user = S::user();
179 $body = EventFeed::nextEvent($it, $user);
180 foreach ($cats as $cat) {
181 $data = array();
182 if (!$body) {
183 continue;
184 }
185 do {
186 if ($cat == 'body' || $body[$cat]) {
187 $data[] = $body;
188 } else {
189 break;
190 }
191 $body = EventFeed::nextEvent($it, $user);
192 } while ($body);
193 if (!empty($data)) {
194 $array[$cat] = $data;
195 }
196 }
197
198 $page->assign_by_ref('events', $array);
199 }
200
201 function handler_photo(&$page, $eid = null, $valid = null)
202 {
203 if ($eid && $eid != 'valid') {
204 $res = XDB::query("SELECT * FROM announce_photos WHERE eid = {?}", $eid);
205 if ($res->numRows()) {
206 $photo = $res->fetchOneAssoc();
207 pl_cached_dynamic_content_headers("image/" . $photo['attachmime']);
208 echo $photo['attach'];
209 exit;
210 }
211 } elseif ($eid == 'valid') {
212 $valid = Validate::get_request_by_id($valid);
213 if ($valid && $valid->img) {
214 pl_cached_dynamic_content_headers("image/" . $valid->imgtype);
215 echo $valid->img;
216 exit;
217 }
218 } else {
219 $upload = new PlUpload(S::user()->login(), 'event');
220 if ($upload->exists() && $upload->isType('image')) {
221 pl_cached_dynamic_content_headers($upload->contentType());
222 echo $upload->getContents();
223 exit;
224 }
225 }
226 global $globals;
227 pl_cached_dynamic_content_headers("image/png");
228 echo file_get_contents($globals->spoolroot . '/htdocs/images/logo.png');
229 exit;
230 }
231
232 function handler_rss(&$page, $user = null, $hash = null)
233 {
234 $this->load('feed.inc.php');
235 $feed = new EventFeed();
236 return $feed->run($page, $user, $hash);
237 }
238
239 function handler_preview(&$page)
240 {
241 $page->changeTpl('events/preview.tpl', NO_SKIN);
242 $texte = Get::v('texte');
243 if (!is_utf8($texte)) {
244 $texte = utf8_encode($texte);
245 }
246 $titre = Get::v('titre');
247 if (!is_utf8($titre)) {
248 $titre = utf8_encode($titre);
249 }
250 $page->assign('texte', $texte);
251 $page->assign('titre', $titre);
252 pl_content_headers("text/html");
253 }
254
255 function handler_ev_submit(&$page)
256 {
257 $page->changeTpl('events/submit.tpl');
258 $page->addJsLink('ajax.js');
259
260 $wp = new PlWikiPage('Xorg.Annonce');
261 $wp->buildCache();
262
263 $titre = Post::v('titre');
264 $texte = Post::v('texte');
265 $promo_min = Post::i('promo_min');
266 $promo_max = Post::i('promo_max');
267 $expiration = Post::i('expiration');
268 $valid_mesg = Post::v('valid_mesg');
269 $action = Post::v('action');
270 $upload = new PlUpload(S::user()->login(), 'event');
271 $this->upload_image($page, $upload);
272
273 if (($promo_min > $promo_max && $promo_max != 0)||
274 ($promo_min != 0 && ($promo_min <= 1900 || $promo_min >= 2020)) ||
275 ($promo_max != 0 && ($promo_max <= 1900 || $promo_max >= 2020)))
276 {
277 $page->trigError("L'intervalle de promotions n'est pas valide");
278 $action = null;
279 }
280
281 $page->assign('titre', $titre);
282 $page->assign('texte', $texte);
283 $page->assign('promo_min', $promo_min);
284 $page->assign('promo_max', $promo_max);
285 $page->assign('expiration', $expiration);
286 $page->assign('valid_mesg', $valid_mesg);
287 $page->assign('action', strtolower($action));
288 $page->assign_by_ref('upload', $upload);
289
290 if ($action == 'Supprimer l\'image') {
291 $upload->rm();
292 $page->assign('action', false);
293 } elseif ($action && (!trim($texte) || !trim($titre))) {
294 $page->trigError("L'article doit avoir un titre et un contenu");
295 } elseif ($action) {
296 S::assert_xsrf_token();
297
298 $evtreq = new EvtReq($titre, $texte, $promo_min, $promo_max,
299 $expiration, $valid_mesg, S::user(), $upload);
300 $evtreq->submit();
301 $page->assign('ok', true);
302 } elseif (!Env::v('preview')) {
303 $upload->rm();
304 }
305 }
306
307 function handler_tips(&$page, $tips = null)
308 {
309 pl_content_headers("text/html");
310 $page->changeTpl('include/tips.tpl', NO_SKIN);
311 $page->assign('tips', $this->get_tips($tips));
312 }
313
314 function handler_admin_tips(&$page, $action = 'list', $id = null)
315 {
316 $page->setTitle('Administration - Astuces');
317 $page->assign('title', 'Gestion des Astuces');
318 $table_editor = new PLTableEditor('admin/tips', 'reminder_tips', 'id');
319 $table_editor->describe('expiration', 'date de péremption', true);
320 $table_editor->describe('promo_min', 'promo. min (0 aucune)', false);
321 $table_editor->describe('promo_max', 'promo. max (0 aucune)', false);
322 $table_editor->describe('title', 'titre', true);
323 $table_editor->describe('state', 'actif', true);
324 $table_editor->describe('text', 'texte (html) de l\'astuce', false);
325 $table_editor->describe('priority', '0<=priorité<=255', true);
326 $table_editor->list_on_edit(false);
327 $table_editor->apply($page, $action, $id);
328 if (($action == 'edit' && !is_null($id)) || $action == 'update') {
329 $page->changeTpl('events/admin_tips.tpl');
330 }
331 }
332
333 function handler_admin_events(&$page, $action = 'list', $eid = null)
334 {
335 $page->changeTpl('events/admin.tpl');
336 $page->addJsLink('ajax.js');
337 $page->setTitle('Administration - Evenements');
338 $page->register_modifier('hde', 'html_entity_decode');
339
340 $arch = $action == 'archives';
341 $page->assign('action', $action);
342
343 $upload = new PlUpload(S::user()->login(), 'event');
344 if ((Env::has('preview') || Post::v('action') == "Proposer") && $eid) {
345 $action = 'edit';
346 $this->upload_image($page, $upload);
347 }
348
349 if (Post::v('action') == 'Pas d\'image' && $eid) {
350 S::assert_xsrf_token();
351 $upload->rm();
352 XDB::execute("DELETE FROM announce_photos WHERE eid = {?}", $eid);
353 $action = 'edit';
354 } elseif (Post::v('action') == 'Supprimer l\'image' && $eid) {
355 S::assert_xsrf_token();
356 $upload->rm();
357 $action = 'edit';
358 } elseif (Post::v('action') == "Proposer" && $eid) {
359 S::assert_xsrf_token();
360 $promo_min = Post::i('promo_min');
361 $promo_max = Post::i('promo_max');
362 if (($promo_min != 0 && ($promo_min <= 1900 || $promo_min >= 2020)) ||
363 ($promo_max != 0 && ($promo_max <= 1900 || $promo_max >= 2020 || $promo_max < $promo_min)))
364 {
365 $page->trigError("L'intervalle de promotions $promo_min -> $promo_max n'est pas valide");
366 $action = 'edit';
367 } else {
368 $res = XDB::query('SELECT flags FROM announces WHERE id = {?}', $eid);
369 $flags = new PlFlagSet($res->fetchOneCell());
370 $flags->addFlag('wiki');
371 if (Post::v('important')) {
372 $flags->addFlag('important');
373 } else {
374 $flags->rmFlag('important');
375 }
376
377 XDB::execute('UPDATE announces
378 SET creation_date = creation_date,
379 titre={?}, texte={?}, expiration={?}, promo_min={?}, promo_max={?},
380 flags = {?}
381 WHERE id = {?}',
382 Post::v('titre'), Post::v('texte'), Post::v('expiration'),
383 Post::v('promo_min'), Post::v('promo_max'),
384 $flags, $eid);
385 if ($upload->exists() && list($x, $y, $type) = $upload->imageInfo()) {
386 XDB::execute('INSERT INTO announce_photos (eid, attachmime, attach, x, y)
387 VALUES ({?}, {?}, {?}, {?}, {?})
388 ON DUPLICATE KEY UPDATE attachmime = VALUES(attachmime), attach = VALUES(attach), x = VALUES(x), y = VALUES(y)',
389 $eid, $type, $upload->getContents(), $x, $y);
390 $upload->rm();
391 }
392 }
393 }
394
395 if ($action == 'edit') {
396 $res = XDB::query('SELECT titre, texte, expiration, promo_min, promo_max, FIND_IN_SET(\'important\', flags),
397 attach IS NOT NULL
398 FROM announces AS e
399 LEFT JOIN announce_photos AS p ON(e.id = p.eid)
400 WHERE id={?}', $eid);
401 list($titre, $texte, $expiration, $promo_min, $promo_max, $important, $img) = $res->fetchOneRow();
402 $page->assign('titre',$titre);
403 $page->assign('texte',$texte);
404 $page->assign('promo_min',$promo_min);
405 $page->assign('promo_max',$promo_max);
406 $page->assign('expiration',$expiration);
407 $page->assign('important', $important);
408 $page->assign('eid', $eid);
409 $page->assign('img', $img);
410 $page->assign_by_ref('upload', $upload);
411
412 $select = "";
413 for ($i = 1 ; $i < 30 ; $i++) {
414 $p_stamp=date("Ymd",time()+3600*24*$i);
415 $year=substr($p_stamp,0,4);
416 $month=substr($p_stamp,4,2);
417 $day=substr($p_stamp,6,2);
418
419 $select .= "<option value=\"$p_stamp\""
420 . (($p_stamp == strtr($expiration, array("-" => ""))) ? " selected" : "")
421 . "> $day / $month / $year</option>\n";
422 }
423 $page->assign('select',$select);
424 } else {
425 switch ($action) {
426 case 'delete':
427 S::assert_xsrf_token();
428 XDB::execute('DELETE from announces
429 WHERE id = {?}', $eid);
430 break;
431
432 case "archive":
433 S::assert_xsrf_token();
434 XDB::execute('UPDATE announces
435 SET creation_date = creation_date, flags = CONCAT(flags,",archive")
436 WHERE id = {?}', $eid);
437 break;
438
439 case "unarchive":
440 S::assert_xsrf_token();
441 XDB::execute('UPDATE announces
442 SET creation_date = creation_date, flags = REPLACE(flags,"archive","")
443 WHERE id = {?}', $eid);
444 $action = 'archives';
445 $arch = true;
446 break;
447
448 case "valid":
449 S::assert_xsrf_token();
450 XDB::execute('UPDATE announces
451 SET creation_date = creation_date, flags = CONCAT(flags,",valide")
452 WHERE id = {?}', $eid);
453 break;
454
455 case "unvalid":
456 S::assert_xsrf_token();
457 XDB::execute('UPDATE announces
458 SET creation_date = creation_date, flags = REPLACE(flags,"valide", "")
459 WHERE id = {?}', $eid);
460 break;
461 }
462
463 $pid = ($eid && $action == 'preview') ? $eid : -1;
464 $sql = "SELECT e.id, e.titre, e.texte,e.id = $pid AS preview, e.uid,
465 DATE_FORMAT(e.creation_date,'%d/%m/%Y %T') AS creation_date,
466 DATE_FORMAT(e.expiration,'%d/%m/%Y') AS expiration,
467 e.promo_min, e.promo_max,
468 FIND_IN_SET('valide', e.flags) AS fvalide,
469 FIND_IN_SET('archive', e.flags) AS farch,
470 FIND_IN_SET('wiki', e.flags) AS wiki
471 FROM announces AS e
472 WHERE ".($arch ? "" : "!")."FIND_IN_SET('archive',e.flags)
473 ORDER BY FIND_IN_SET('valide',e.flags), e.expiration DESC";
474 $page->assign('evs', XDB::iterator($sql));
475 }
476 $page->assign('arch', $arch);
477 $page->assign('admin_evts', true);
478 }
479 }
480
481 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
482 ?>