Merge branch 'platal-1.0.0'
[platal.git] / modules / xnetevents.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 define('NB_PER_PAGE', 25);
23
24 class XnetEventsModule extends PLModule
25 {
26 function handlers()
27 {
28 return array(
29 '%grp/events' => $this->make_hook('events', AUTH_MDP),
30 '%grp/events/sub' => $this->make_hook('sub', AUTH_MDP),
31 '%grp/events/csv' => $this->make_hook('csv', AUTH_MDP, 'user', NO_HTTPS),
32 '%grp/events/ical' => $this->make_hook('ical', AUTH_MDP, 'user', NO_HTTPS),
33 '%grp/events/edit' => $this->make_hook('edit', AUTH_MDP, 'groupadmin'),
34 '%grp/events/admin' => $this->make_hook('admin', AUTH_MDP, 'groupmember'),
35 );
36 }
37
38 function handler_events(&$page, $archive = null)
39 {
40 global $globals;
41
42 $page->changeTpl('xnetevents/index.tpl');
43 $action = null;
44 $archive = ($archive == 'archive' && may_update());
45
46 if (Post::has('del')) {
47 $action = 'del';
48 $eid = Post::v('del');
49 } elseif (Post::has('archive')) {
50 $action = 'archive';
51 $eid = Post::v('archive');
52 } elseif (Post::has('unarchive')) {
53 $action = 'unarchive';
54 $eid = Post::v('unarchive');
55 }
56
57 if (!is_null($action)) {
58 if (!may_update()) {
59 return PL_FORBIDDEN;
60 }
61 S::assert_xsrf_token();
62
63 $res = XDB::query("SELECT asso_id, short_name FROM group_events
64 WHERE eid = {?} AND asso_id = {?}",
65 $eid, $globals->asso('id'));
66
67 $tmp = $res->fetchOneRow();
68 if (!$tmp) {
69 return PL_FORBIDDEN;
70 }
71 }
72
73 if ($action == 'del') {
74 // deletes the event mailing aliases
75 if ($tmp[1]) {
76 foreach (array('-absents@', '-participants@', '-paye@', '-participants-non-paye@') as $v) {
77 XDB::execute("DELETE FROM virtual
78 WHERE type = 'evt' AND alias LIKE {?}",
79 $tmp[1] . $v . '%');
80 }
81 }
82
83 // deletes the event items
84 XDB::execute('DELETE FROM group_event_items
85 WHERE eid = {?}', $eid);
86
87 // deletes the event participants
88 XDB::execute('DELETE FROM group_event_participants
89 WHERE eid = {?}', $eid);
90
91 // deletes the event
92 XDB::execute('DELETE FROM group_events
93 WHERE eid = {?} AND asso_id = {?}',
94 $eid, $globals->asso('id'));
95
96 // delete the requests for payments
97 XDB::execute("DELETE FROM requests
98 WHERE type = 'paiements' AND data LIKE {?}",
99 PayReq::same_event($eid, $globals->asso('id')));
100 $globals->updateNbValid();
101 }
102
103 if ($action == 'archive') {
104 XDB::execute("UPDATE group_events
105 SET archive = 1
106 WHERE eid = {?} AND asso_id = {?}",
107 $eid, $globals->asso('id'));
108 }
109
110 if ($action == 'unarchive') {
111 XDB::execute("UPDATE group_events
112 SET archive = 0
113 WHERE eid = {?} AND asso_id = {?}",
114 $eid, $globals->asso('id'));
115 }
116
117 $page->assign('archive', $archive);
118 $evenements = XDB::iterator('SELECT e.*, LEFT(10, e.debut) AS first_day, LEFT(10, e.fin) AS last_day,
119 IF(e.deadline_inscription,
120 e.deadline_inscription >= LEFT(NOW(), 10),
121 1) AS inscr_open,
122 e.deadline_inscription,
123 MAX(ep.nb) IS NOT NULL AS inscrit, MAX(ep.paid) AS paid
124 FROM group_events AS e
125 LEFT JOIN group_event_participants AS ep ON (ep.eid = e.eid AND ep.uid = {?})
126 WHERE asso_id = {?} AND archive = {?}
127 GROUP BY e.eid
128 ORDER BY inscr_open DESC, debut DESC',
129 S::i('uid'), $globals->asso('id'), $archive ? 1 : 0);
130
131 $evts = array();
132 $undisplayed_events = 0;
133 $this->load('xnetevents.inc.php');
134
135 while ($e = $evenements->next()) {
136 if (!is_member() && !may_update() && !$e['accept_nonmembre']) {
137 $undisplayed_events ++;
138 continue;
139 }
140
141 $e['show_participants'] = ($e['show_participants'] && (is_member() || may_update()));
142 $e['moments'] = XDB::fetchAllAssoc('SELECT titre, details, montant, ei.item_id, nb, ep.paid
143 FROM group_event_items AS ei
144 LEFT JOIN group_event_participants AS ep
145 ON (ep.eid = ei.eid AND ep.item_id = ei.item_id AND ep.uid = {?})
146 WHERE ei.eid = {?}',
147 S::i('uid'), $e['eid']);
148
149 $e['topay'] = 0;
150 $e['paid'] = $e['moments'][0]['paid'];
151 foreach ($e['moments'] as $m) {
152 $e['topay'] += $m['nb'] * $m['montant'];
153 }
154
155 $query = XDB::query(
156 "SELECT amount
157 FROM payment_transactions AS t
158 WHERE ref = {?} AND uid = {?}", $e['paiement_id'], S::v('uid'));
159 $montants = $query->fetchColumn();
160
161 foreach ($montants as $m) {
162 $p = strtr(substr($m, 0, strpos($m, 'EUR')), ',', '.');
163 $e['paid'] += trim($p);
164 }
165
166 make_event_date($e);
167
168 if (Env::has('updated') && $e['eid'] == Env::i('updated')) {
169 $page->assign('updated', $e);
170 }
171 $evts[] = $e;
172 }
173
174 $page->assign('evenements', $evts);
175 $page->assign('undisplayed_events', $undisplayed_events);
176 }
177
178 function handler_sub(&$page, $eid = null)
179 {
180 $this->load('xnetevents.inc.php');
181 $page->changeTpl('xnetevents/subscribe.tpl');
182
183 $evt = get_event_detail($eid);
184 if (is_null($evt)) {
185 return PL_NOT_FOUND;
186 }
187 if ($evt === false) {
188 global $globals, $platal;
189 $url = $globals->asso('sub_url');
190 if (empty($url)) {
191 $url = $platal->ns . 'subscribe';
192 }
193 $page->kill('Cet événement est reservé aux membres du groupe ' . $globals->asso('nom') .
194 '. Pour devenir membre, rends-toi sur la page de <a href="' . $url . '">demande d\'inscripton</a>.');
195 }
196
197 if (!$evt['inscr_open']) {
198 $page->kill('Les inscriptions pour cet événement sont closes');
199 }
200 if (!$evt['accept_nonmembre'] && !is_member() && !may_update()) {
201 $page->kill('Cet événement est fermé aux non-membres du groupe');
202 }
203
204 global $globals;
205 $res = XDB::query("SELECT stamp
206 FROM requests
207 WHERE type = 'paiements' AND data LIKE {?}",
208 PayReq::same_event($evt['eid'], $globals->asso('id')));
209 $page->assign('validation', $res->numRows());
210 $page->assign('event', $evt);
211
212 if (!Post::has('submit')) {
213 return;
214 } else {
215 S::assert_xsrf_token();
216 }
217
218 $moments = Post::v('moment', array());
219 $pers = Post::v('personnes', array());
220 $subs = array();
221
222 foreach ($moments as $j => $v) {
223 $subs[$j] = intval($v);
224
225 // retreive ohter field when more than one person
226 if ($subs[$j] == 2) {
227 if (!isset($pers[$j]) || !is_numeric($pers[$j])
228 || $pers[$j] < 0)
229 {
230 $page->trigError("Tu dois choisir un nombre d'invités correct&nbsp;!");
231 return;
232 }
233 $subs[$j] = 1 + $pers[$j];
234 }
235 }
236
237 // impossible to unsubscribe if you already paid sthing
238 if (!array_sum($subs) && $evt['paid'] != 0) {
239 $page->trigError("Impossible de te désinscrire complètement " .
240 "parce que tu as fait un paiement par " .
241 "chèque ou par liquide. Contacte un " .
242 "administrateur du groupe si tu es sûr de " .
243 "ne pas venir.");
244 return;
245 }
246
247 // update actual inscriptions
248 $updated = false;
249 $total = 0;
250 $paid = $evt['paid'] ? $evt['paid'] : 0;
251 $telepaid= $evt['telepaid'] ? $evt['telepaid'] : 0;
252 foreach ($subs as $j => $nb) {
253 if ($nb >= 0) {
254 XDB::execute(
255 "REPLACE INTO group_event_participants
256 VALUES ({?}, {?}, {?}, {?}, {?}, {?})",
257 $eid, S::v('uid'), $j, $nb, Env::has('notify_payment') ? 'notify_payment' : '',
258 $j == 1 ? $paid - $telepaid : 0);
259 $updated = $eid;
260 } else {
261 XDB::execute(
262 "DELETE FROM group_event_participants
263 WHERE eid = {?} AND uid = {?} AND item_id = {?}",
264 $eid, S::v("uid"), $j);
265 $updated = $eid;
266 }
267 $total += $nb;
268 }
269 if ($updated !== false) {
270 $page->trigSuccess('Ton inscription à l\'événement a été mise à jour avec succès.');
271 subscribe_lists_event(S::i('uid'), $evt, ($total > 0 ? 1 : 0), 0);
272 }
273 $page->assign('event', get_event_detail($eid));
274 }
275
276 function handler_csv(&$page, $eid = null, $item_id = null)
277 {
278 $this->load('xnetevents.inc.php');
279
280 if (!is_numeric($item_id)) {
281 $item_id = null;
282 }
283
284 $evt = get_event_detail($eid, $item_id);
285 if (!$evt) {
286 return PL_NOT_FOUND;
287 }
288
289 pl_content_headers("text/x-csv");
290 $page->changeTpl('xnetevents/csv.tpl', NO_SKIN);
291
292 $admin = may_update();
293
294 $tri = (Env::v('order') == 'alpha' ? UserFilter::sortByPromo() : UserFilter::sortByName());
295
296 $page->assign('participants',
297 get_event_participants($evt, $item_id, $tri));
298
299 $page->assign('admin', $admin);
300 $page->assign('moments', $evt['moments']);
301 $page->assign('money', $evt['money']);
302 $page->assign('telepayment', $evt['paiement_id']);
303 $page->assign('tout', !Env::v('item_id', false));
304 }
305
306 function handler_ical(&$page, $eid = null)
307 {
308 global $globals;
309
310 $this->load('xnetevents.inc.php');
311 $evt = get_event_detail($eid);
312 if (!$evt) {
313 return PL_FORBIDDEN;
314 }
315 $evt['debut'] = preg_replace('/(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)/', "\\1\\2\\3T\\4\\5\\6", $evt['debut']);
316 $evt['fin'] = preg_replace('/(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)/', "\\1\\2\\3T\\4\\5\\6", $evt['fin']);
317
318 foreach ($evt['moments'] as $m) {
319 $evt['descriptif'] .= "\n\n** " . $m['titre'] . " **\n" . $m['details'];
320 }
321
322 $page->changeTpl('xnetevents/calendar.tpl', NO_SKIN);
323
324 require_once('ical.inc.php');
325 $page->assign('asso', $globals->asso());
326 $page->assign('timestamp', time());
327 $page->assign('admin', may_update());
328
329 if (may_update()) {
330 $page->assign('participants', get_event_participants($evt, null, UserFilter::sortByPromo()));
331 }
332 $page->register_function('display_ical', 'display_ical');
333 $page->assign_by_ref('e', $evt);
334
335 pl_content_headers("text/calendar");
336 }
337
338 function handler_edit(&$page, $eid = null)
339 {
340 global $globals;
341
342 // get eid if the the given one is a short name
343 if (!is_null($eid) && !is_numeric($eid)) {
344 $res = XDB::query("SELECT eid
345 FROM group_events
346 WHERE asso_id = {?} AND short_name = {?}",
347 $globals->asso('id'), $eid);
348 if ($res->numRows()) {
349 $eid = (int)$res->fetchOneCell();
350 }
351 }
352
353 // check the event is in our group
354 if (!is_null($eid)) {
355 $res = XDB::query("SELECT short_name
356 FROM group_events
357 WHERE eid = {?} AND asso_id = {?}",
358 $eid, $globals->asso('id'));
359 if ($res->numRows()) {
360 $infos = $res->fetchOneAssoc();
361 } else {
362 return PL_FORBIDDEN;
363 }
364 }
365
366 $page->changeTpl('xnetevents/edit.tpl');
367
368 $moments = range(1, 4);
369 $error = false;
370 $page->assign('moments', $moments);
371
372 if (Post::v('intitule')) {
373 S::assert_xsrf_token();
374
375 $this->load('xnetevents.inc.php');
376 $short_name = event_change_shortname($page, $eid,
377 $infos['short_name'],
378 Env::v('short_name', ''));
379 if ($short_name != Env::v('short_name')) {
380 $error = true;
381 }
382 $evt = array(
383 'eid' => $eid,
384 'asso_id' => $globals->asso('id'),
385 'paiement_id' => Post::v('paiement_id') > 0 ? Post::v('paiement_id') : null,
386 'debut' => Post::v('deb_Year').'-'.Post::v('deb_Month')
387 .'-'.Post::v('deb_Day').' '.Post::v('deb_Hour')
388 .':'.Post::v('deb_Minute').':00',
389 'fin' => Post::v('fin_Year').'-'.Post::v('fin_Month')
390 .'-'.Post::v('fin_Day').' '.Post::v('fin_Hour')
391 .':'.Post::v('fin_Minute').':00',
392 'short_name' => $short_name,
393 );
394
395 $trivial = array('intitule', 'descriptif', 'noinvite',
396 'show_participants', 'accept_nonmembre', 'uid');
397 foreach ($trivial as $k) {
398 $evt[$k] = Post::v($k);
399 }
400 if (!$eid) {
401 $evt['uid'] = S::v('uid');
402 }
403
404 if (Post::v('deadline')) {
405 $evt['deadline_inscription'] = Post::v('inscr_Year').'-'
406 . Post::v('inscr_Month').'-'
407 . Post::v('inscr_Day');
408 } else {
409 $evt['deadline_inscription'] = null;
410 }
411
412 // Store the modifications in the database
413 XDB::execute('REPLACE INTO group_events
414 SET eid = {?}, asso_id = {?}, uid = {?}, intitule = {?},
415 paiement_id = {?}, descriptif = {?}, debut = {?},
416 fin = {?}, show_participants = {?}, short_name = {?},
417 deadline_inscription = {?}, noinvite = {?},
418 accept_nonmembre = {?}',
419 $evt['eid'], $evt['asso_id'], $evt['uid'],
420 $evt['intitule'], $evt['paiement_id'], $evt['descriptif'],
421 $evt['debut'], $evt['fin'], $evt['show_participants'],
422 $evt['short_name'], $evt['deadline_inscription'],
423 $evt['noinvite'], $evt['accept_nonmembre']);
424
425 // if new event, get its id
426 if (!$eid) {
427 $eid = XDB::insertId();
428 }
429
430 $nb_moments = 0;
431 $money_defaut = 0;
432
433 foreach ($moments as $i) {
434 if (Post::v('titre'.$i)) {
435 $nb_moments++;
436
437 $montant = strtr(Post::v('montant'.$i), ',', '.');
438 $money_defaut += (float)$montant;
439 XDB::execute("
440 REPLACE INTO group_event_items
441 VALUES ({?}, {?}, {?}, {?}, {?})",
442 $eid, $i, Post::v('titre'.$i),
443 Post::v('details'.$i), $montant);
444 } else {
445 XDB::execute("DELETE FROM group_event_items
446 WHERE eid = {?} AND item_id = {?}", $eid, $i);
447 }
448 }
449 // request for a new payment
450 if (Post::v('paiement_id') == -1 && $money_defaut >= 0) {
451 $p = new PayReq(S::user(),
452 Post::v('intitule')." - ".$globals->asso('nom'),
453 Post::v('site'), $money_defaut,
454 Post::v('confirmation'), 0, 999,
455 $globals->asso('id'), $eid);
456 if ($p->accept()) {
457 $p->submit();
458 } else {
459 $page->assign('paiement_message', Post::v('confirmation'));
460 $page->assign('paiement_site', Post::v('site'));
461 $error = true;
462 }
463 }
464
465 // events with no sub-event: add a sub-event with no name
466 if ($nb_moments == 0) {
467 XDB::execute("INSERT INTO group_event_items
468 VALUES ({?}, {?}, '', '', 0)", $eid, 1);
469 }
470
471 if (!$error) {
472 pl_redirect('events');
473 }
474 }
475
476 // get a list of all the payment for this asso
477 $res = XDB::iterator("SELECT id, text
478 FROM payments
479 WHERE asso_id = {?}", $globals->asso('id'));
480 $paiements = array();
481 while ($a = $res->next()) $paiements[$a['id']] = $a['text']; {
482 $page->assign('paiements', $paiements);
483 }
484
485 // when modifying an old event retreive the old datas
486 if ($eid) {
487 $res = XDB::query(
488 "SELECT eid, intitule, descriptif, debut, fin, uid,
489 show_participants, paiement_id, short_name,
490 deadline_inscription, noinvite, accept_nonmembre
491 FROM group_events
492 WHERE eid = {?}", $eid);
493 $evt = $res->fetchOneAssoc();
494 // find out if there is already a request for a payment for this event
495 $res = XDB::query("SELECT stamp
496 FROM requests
497 WHERE type = 'paiements' AND data LIKE {?}",
498 PayReq::same_event($eid, $globals->asso('id')));
499 $stamp = $res->fetchOneCell();
500 if ($stamp) {
501 $evt['paiement_id'] = -2;
502 $evt['paiement_req'] = $stamp;
503 }
504 $page->assign('evt', $evt);
505 // get all the different moments infos
506 $res = XDB::iterator(
507 "SELECT item_id, titre, details, montant
508 FROM group_event_items AS ei
509 INNER JOIN group_events AS e ON(e.eid = ei.eid)
510 WHERE e.eid = {?}
511 ORDER BY item_id", $eid);
512 $items = array();
513 while ($item = $res->next()) {
514 $items[$item['item_id']] = $item;
515 }
516 $page->assign('items', $items);
517 }
518 $page->assign('url_ref', $eid);
519 }
520
521 function handler_admin(&$page, $eid = null, $item_id = null)
522 {
523 global $globals;
524
525 $this->load('xnetevents.inc.php');
526
527 $evt = get_event_detail($eid, $item_id);
528 if (!$evt) {
529 return PL_NOT_FOUND;
530 }
531
532 $page->changeTpl('xnetevents/admin.tpl');
533 if (!$evt['show_participants'] && !may_update()) {
534 return PL_FORBIDDEN;
535 }
536
537 if (may_update() && Post::v('adm')) {
538 S::assert_xsrf_token();
539
540 $member = User::getSilent(Post::v('mail'));
541 if (!$member) {
542 $page->trigError("Membre introuvable");
543 }
544
545 // change the price paid by a participant
546 if (Env::v('adm') == 'prix' && $member) {
547 $amount = strtr(Env::v('montant'), ',', '.');
548 XDB::execute("UPDATE group_event_participants
549 SET paid = paid + {?}
550 WHERE uid = {?} AND eid = {?} AND item_id = 1",
551 $amount, $member->uid, $evt['eid']);
552 subscribe_lists_event($member->uid, $evt, 1, $amount);
553 }
554
555 // change the number of personns coming with a participant
556 if (Env::v('adm') == 'nbs' && $member) {
557 $res = XDB::query("SELECT paid
558 FROM group_event_participants
559 WHERE uid = {?} AND eid = {?}",
560 $member->uid, $evt['eid']);
561
562 $paid = intval($res->fetchOneCell());
563 $nbs = Post::v('nb', array());
564
565 foreach ($nbs as $id => $nb) {
566 $nb = max(intval($nb), 0);
567 XDB::execute('REPLACE INTO group_event_participants
568 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
569 $evt['eid'], $member->uid, $id, $nb, '', $id == 1 ? $paid : 0);
570 }
571
572 $res = XDB::query('SELECT COUNT(uid) AS cnt, SUM(nb) AS nb
573 FROM group_event_participants
574 WHERE uid = {?} AND eid = {?}
575 GROUP BY uid',
576 $member->uid, $evt['eid']);
577 $u = $res->fetchOneAssoc();
578 if ($u['cnt'] == 1 && $paid == 0 && Post::v('cancel')) {
579 XDB::execute("DELETE FROM group_event_participants
580 WHERE uid = {?} AND eid = {?}",
581 $member->uid, $evt['eid']);
582 $u = 0;
583 subscribe_lists_event($member->uid, $evt, -1, $paid);
584 } else {
585 $u = $u['cnt'] ? $u['nb'] : null;
586 subscribe_lists_event($member->uid, $evt, ($u > 0 ? 1 : 0), $paid);
587 }
588 }
589
590 $evt = get_event_detail($eid, $item_id);
591 }
592
593 $page->assign_by_ref('evt', $evt);
594 $page->assign('tout', is_null($item_id));
595
596 if (count($evt['moments'])) {
597 $page->assign('moments', $evt['moments']);
598 }
599
600 if ($evt['paiement_id']) {
601 $infos = User::getBulkUsersWithUIDs(
602 XDB::fetchAllAssoc('SELECT t.uid, t.amount
603 FROM payment_transactions AS t
604 LEFT JOIN group_event_participants AS ep ON(ep.uid = t.uid AND ep.eid = {?})
605 WHERE t.ref = {?} AND ep.uid IS NULL',
606 $evt['eid'], $evt['paiement_id']),
607 'uid', 'user');
608 $page->assign('oublis', count($infos));
609 $page->assign('oubliinscription', $infos);
610 }
611
612 $absents = User::getBulkUsersFromDB('SELECT p.uid
613 FROM group_event_participants AS p
614 LEFT JOIN group_event_participants AS p2 ON (p2.uid = p.uid
615 AND p2.eid = p.eid
616 AND p2.nb != 0)
617 WHERE p.eid = {?} AND p2.eid IS NULL
618 GROUP BY p.uid', $evt['eid']);
619
620 $ofs = Env::i('offset');
621 $tot = (is_null($evt['nb_tot']) ? $evt['nb'] : $evt['nb_tot']);
622 $nbp = ceil($tot / NB_PER_PAGE);
623 if ($nbp > 1) {
624 $links = array();
625 if ($ofs) {
626 $links['précédent'] = $ofs - 1;
627 }
628 for ($i = 1 ; $i <= $nbp; $i++) {
629 $links[(string)$i] = $i - 1;
630 }
631 if ($ofs < $nbp - 1) {
632 $links['suivant'] = $ofs+1;
633 }
634 $page->assign('links', $links);
635 }
636
637 $page->assign('absents', $absents);
638 $page->assign('participants',
639 get_event_participants($evt, $item_id, UserFilter::sortByName(),
640 NB_PER_PAGE, $ofs * NB_PER_PAGE));
641 }
642 }
643
644 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
645 ?>