Enables watch of groups (Closes #808).
[platal.git] / modules / carnet.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 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 CarnetModule extends PLModule
23 {
24 function handlers()
25 {
26 return array(
27 'carnet' => $this->make_hook('index', AUTH_COOKIE, 'directory_private'),
28 'carnet/panel' => $this->make_hook('panel', AUTH_COOKIE, 'directory_private'),
29 'carnet/notifs' => $this->make_hook('notifs', AUTH_COOKIE, 'directory_private'),
30
31 'carnet/contacts' => $this->make_hook('contacts', AUTH_COOKIE, 'directory_private'),
32 'carnet/contacts/pdf' => $this->make_hook('pdf', AUTH_COOKIE, 'directory_private'),
33 'carnet/contacts/vcard' => $this->make_hook('vcard', AUTH_COOKIE, 'directory_private'),
34 'carnet/contacts/ical' => $this->make_token_hook('ical', AUTH_COOKIE, 'directory_private'),
35 'carnet/contacts/csv' => $this->make_token_hook('csv', AUTH_COOKIE, 'directory_private'),
36 'carnet/contacts/csv/birthday' => $this->make_token_hook('csv_birthday', AUTH_COOKIE, 'directory_private'),
37
38 'carnet/rss' => $this->make_token_hook('rss', AUTH_COOKIE, 'directory_private'),
39 );
40 }
41
42 function _add_rss_link($page)
43 {
44 if (!S::hasAuthToken()) {
45 return;
46 }
47 $page->setRssLink('Polytechnique.org :: Carnet',
48 '/carnet/rss/' . S::v('hruid') . '/' . S::user()->token . '/rss.xml');
49 }
50
51 function handler_index($page)
52 {
53 $page->changeTpl('carnet/index.tpl');
54 $page->setTitle('Mon carnet');
55 $this->_add_rss_link($page);
56 }
57
58 function handler_panel($page)
59 {
60 $page->changeTpl('carnet/panel.tpl');
61
62 if (Get::has('read')) {
63 XDB::execute('UPDATE watch
64 SET last = FROM_UNIXTIME({?})
65 WHERE uid = {?}',
66 Get::i('read'), S::i('uid'));
67 S::user()->invalidWatchCache();
68 Platal::session()->updateNbNotifs();
69 pl_redirect('carnet/panel');
70 }
71
72 require_once 'notifs.inc.php';
73 $page->assign('now', time());
74
75 $user = S::user();
76 $notifs = Watch::getEvents($user, time() - (7 * 86400));
77 $page->assign('notifs', $notifs);
78 $page->assign('today', date('Y-m-d'));
79 $this->_add_rss_link($page);
80 }
81
82 private function getSinglePromotion(PlPage $page, $promo)
83 {
84 if (!(is_int($promo) || ctype_digit($promo)) || $promo < 1920 || $promo > date('Y')) {
85 $page->trigError('Promotion invalide&nbsp;: ' . $promo . '.');
86 return null;
87 }
88 return (int)$promo;
89 }
90
91 private function getPromo(PlPage $page, $promo)
92 {
93 if (strpos($promo, '-') === false) {
94 $promo = $this->getSinglePromotion($page, $promo);
95 if (!$promo) {
96 return null;
97 } else {
98 return array($promo);
99 }
100 }
101
102 list($promo1, $promo2) = explode('-', $promo);
103 $promo1 = $this->getSinglePromotion($page, $promo1);
104 if (!$promo1) {
105 return null;
106 }
107 $promo2 = $this->getSinglePromotion($page, $promo2);
108 if (!$promo2) {
109 return null;
110 }
111 if ($promo1 > $promo2) {
112 $page->trigError('Intervalle non valide :&nbsp;' . $promo . '.');
113 return null;
114 }
115 $array = array();
116 for ($i = $promo1 ; $i <= $promo2 ; ++$i) {
117 $array[] = $i;
118 }
119 return $array;
120 }
121
122 private function addPromo(PlPage $page, $promo)
123 {
124 $promos = $this->getPromo($page, $promo);
125 if (!$promos || count($promos) == 0) {
126 return;
127 }
128 $to_add = array();
129 foreach ($promos as $promo) {
130 $to_add[] = XDB::format('({?}, {?})', S::i('uid'), $promo);
131 }
132 XDB::execute('INSERT IGNORE INTO watch_promo (uid, promo)
133 VALUES ' . implode(', ', $to_add));
134 S::user()->invalidWatchCache();
135 Platal::session()->updateNbNotifs();
136 }
137
138 private function delPromo(PlPage $page, $promo)
139 {
140 $promos = $this->getPromo($page, $promo);
141 if (!$promos || count($promos) == 0) {
142 return;
143 }
144 $to_delete = array();
145 foreach ($promos as $promo) {
146 $to_delete[] = XDB::format('{?}', $promo);
147 }
148 XDB::execute('DELETE FROM watch_promo
149 WHERE ' . XDB::format('uid = {?}', S::i('uid')) . '
150 AND promo IN (' . implode(', ', $to_delete) . ')');
151 S::user()->invalidWatchCache();
152 Platal::session()->updateNbNotifs();
153 }
154
155 private function getGroup(PlPage $page, $group)
156 {
157 $groupid = XDB::fetchOneCell("SELECT id
158 FROM groups
159 WHERE (nom = {?} OR diminutif = {?}) AND NOT FIND_IN_SET('private', pub)",
160 $group, $group);
161 if (is_null($groupid)) {
162 $search = XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $group);
163 $res = XDB::query('SELECT id
164 FROM groups
165 WHERE (nom ' . $search . ' OR diminutif ' . $search . ") AND NOT FIND_IN_SET('private', pub)",
166 $search, $search);
167 if ($res->numRows() == 1) {
168 $groupid = $res->fetchOneCell();
169 }
170 }
171 return $groupid;
172 }
173
174 private function addGroup(PlPage $page, $group)
175 {
176 $groupid = $this->getGroup($page, $group);
177 if (is_null($groupid)) {
178 return;
179 }
180 XDB::execute('INSERT IGNORE INTO watch_group (uid, groupid)
181 VALUES ({?}, {?})',
182 S::i('uid'), $groupid);
183 S::user()->invalidWatchCache();
184 Platal::session()->updateNbNotifs();
185 }
186
187 private function delGroup(PlPage $page, $group)
188 {
189 $groupid = $this->getGroup($page, $group);
190 if (is_null($groupid)) {
191 return;
192 }
193 XDB::execute('DELETE FROM watch_group
194 WHERE uid = {?} AND groupid = {?}',
195 S::i('uid'), $groupid);
196 S::user()->invalidWatchCache();
197 Platal::session()->updateNbNotifs();
198 }
199
200 public function addNonRegistered(PlPage $page, PlUser $user)
201 {
202 XDB::execute('INSERT IGNORE INTO watch_nonins (uid, ni_id)
203 VALUES ({?}, {?})', S::i('uid'), $user->id());
204 S::user()->invalidWatchCache();
205 Platal::session()->updateNbNotifs();
206 }
207
208 public function delNonRegistered(PlPage $page, PlUser $user)
209 {
210 XDB::execute('DELETE FROM watch_nonins
211 WHERE uid = {?} AND ni_id = {?}',
212 S::i('uid'), $user->id());
213 S::user()->invalidWatchCache();
214 Platal::session()->updateNbNotifs();
215 }
216
217 public function handler_notifs($page, $action = null, $arg = null)
218 {
219 $page->changeTpl('carnet/notifs.tpl');
220
221 if ($action) {
222 S::assert_xsrf_token();
223 switch ($action) {
224 case 'add_promo':
225 $this->addPromo($page, $arg);
226 break;
227
228 case 'del_promo':
229 $this->delPromo($page, $arg);
230 break;
231
232 case 'add_group':
233 $this->addGroup($page, $arg);
234 break;
235
236 case 'del_group':
237 $this->delGroup($page, $arg);
238 break;
239
240 case 'del_nonins':
241 $user = User::get($arg);
242 if ($user) {
243 $this->delNonRegistered($page, $user);
244 }
245 break;
246
247 case 'add_nonins':
248 $user = User::get($arg);
249 if ($user) {
250 $this->addNonRegistered($page, $user);
251 }
252 break;
253 }
254 }
255
256 if (Env::has('subs')) {
257 S::assert_xsrf_token();
258 $flags = new PlFlagSet();
259 foreach (Env::v('sub') as $key=>$value) {
260 $flags->addFlag($key, $value);
261 }
262 XDB::execute('UPDATE watch
263 SET actions = {?}
264 WHERE uid = {?}', $flags, S::i('uid'));
265 S::user()->invalidWatchCache();
266 Platal::session()->updateNbNotifs();
267 }
268
269 if (Env::has('flags_contacts')) {
270 S::assert_xsrf_token();
271 XDB::execute('UPDATE watch
272 SET ' . XDB::changeFlag('flags', 'contacts', Env::b('contacts')) . '
273 WHERE uid = {?}', S::i('uid'));
274 S::user()->invalidWatchCache();
275 Platal::session()->updateNbNotifs();
276 }
277
278 if (Env::has('flags_mail')) {
279 S::assert_xsrf_token();
280 XDB::execute('UPDATE watch
281 SET ' . XDB::changeFlag('flags', 'mail', Env::b('mail')) . '
282 WHERE uid = {?}', S::i('uid'));
283 S::user()->invalidWatchCache();
284 Platal::session()->updateNbNotifs();
285 }
286
287 $user = S::user();
288 $nonins = new UserFilter(new UFC_WatchRegistration($user));
289
290 $promo = XDB::fetchColumn('SELECT promo
291 FROM watch_promo
292 WHERE uid = {?}
293 ORDER BY promo', S::i('uid'));
294 $page->assign('promo_count', count($promo));
295 $ranges = array();
296 $range_start = null;
297 $range_end = null;
298 foreach ($promo as $p) {
299 if (is_null($range_start)) {
300 $range_start = $range_end = $p;
301 } else if ($p != $range_end + 1) {
302 $ranges[] = array($range_start, $range_end);
303 $range_start = $range_end = $p;
304 } else {
305 $range_end = $p;
306 }
307 }
308 $ranges[] = array($range_start, $range_end);
309 $page->assign('promo_ranges', $ranges);
310 $page->assign('nonins', $nonins->getUsers());
311
312 $groups = XDB::fetchColumn('SELECT g.nom
313 FROM watch_group AS w
314 INNER JOIN groups AS g ON (g.id = w.groupid)
315 WHERE w.uid = {?}
316 ORDER BY g.nom',
317 S::i('uid'));
318 $page->assign('groups', $groups);
319 $page->assign('groups_count', count($groups));
320 list($flags, $actions) = XDB::fetchOneRow('SELECT flags, actions
321 FROM watch
322 WHERE uid = {?}', S::i('uid'));
323 $flags = new PlFlagSet($flags);
324 $actions = new PlFlagSet($actions);
325 $page->assign('flags', $flags);
326 $page->assign('actions', $actions);
327 }
328
329 function handler_contacts($page, $action = null, $subaction = null, $ssaction = null)
330 {
331 $page->setTitle('Mes contacts');
332 $this->_add_rss_link($page);
333
334 $uid = S::i('uid');
335 $user = S::user();
336
337 // For XSRF protection, checks both the normal xsrf token, and the special RSS token.
338 // It allows direct linking to contact adding in the RSS feed.
339 if (Env::v('action') && Env::v('token') !== S::user()->token) {
340 S::assert_xsrf_token();
341 }
342 switch (Env::v('action')) {
343 case 'retirer':
344 if (($contact = Profile::get(Env::v('user')))) {
345 if (XDB::execute("DELETE FROM contacts
346 WHERE uid = {?} AND contact = {?}",
347 $uid, $contact->id())) {
348 Platal::session()->updateNbNotifs();
349 $page->trigSuccess("Contact retiré&nbsp;!");
350 }
351 }
352 break;
353
354 case 'ajouter':
355 if (($contact = Profile::get(Env::v('user')))) {
356 XDB::execute('INSERT IGNORE INTO contacts (uid, contact)
357 VALUES ({?}, {?})',
358 $uid, $contact->id());
359 if (XDB::affectedRows() > 0) {
360 Platal::session()->updateNbNotifs();
361 $page->trigSuccess('Contact ajouté&nbsp;!');
362 } else {
363 $page->trigWarning('Contact déjà dans la liste&nbsp;!');
364 }
365 }
366 break;
367 }
368
369 $search = false;
370
371 require_once 'userset.inc.php';
372
373 if ($action == 'search') {
374 $action = $subaction;
375 $subaction = $ssaction;
376 $search = true;
377 }
378 if ($search && trim(Env::v('quick'))) {
379 $base = 'carnet/contacts/search';
380 $view = new QuickSearchSet(new UFC_Contact($user));
381 } else {
382 $base = 'carnet/contacts';
383 $view = new ProfileSet(new UFC_Contact($user));
384 }
385
386 $view->addMod('minifiche', 'Mini-fiches', true);
387 $view->addMod('trombi', 'Trombinoscope', false, array('with_admin' => false, 'with_promo' => true));
388 $view->addMod('map', 'Planisphère');
389 $view->apply('carnet/contacts', $page, $action, $subaction);
390 $page->changeTpl('carnet/mescontacts.tpl');
391 }
392
393 function handler_pdf($page, $arg0 = null, $arg1 = null)
394 {
395 $this->load('contacts.pdf.inc.php');
396 $user = S::user();
397
398 Platal::session()->close();
399
400 $order = array(new UFO_Name());
401 if ($arg0 == 'promo') {
402 $order = array_unshift($order, new UFO_Promo());
403 } else {
404 $order[] = new UFO_Promo();
405 }
406 $filter = new UserFilter(new UFC_Contact($user), $order);
407
408 $pdf = new ContactsPDF();
409
410 $it = $filter->iterProfiles();
411 while ($p = $it->next()) {
412 $pdf = ContactsPDF::addContact($pdf, $p, $arg0 == 'photos' || $arg1 == 'photos');
413 }
414 $pdf->Output();
415
416 exit;
417 }
418
419 function handler_rss(PlPage $page, PlUser $user)
420 {
421 $this->load('feed.inc.php');
422 $feed = new CarnetFeed();
423 return $feed->run($page, $user);
424 }
425
426 function buildBirthRef(Profile $profile)
427 {
428 $date = strtotime($profile->birthdate);
429 $tomorrow = $date + 86400;
430 return array(
431 'timestamp' => $date,
432 'date' => date('Ymd', $date),
433 'tomorrow' => date('Ymd', $tomorrow),
434 'email' => $profile->owner()->bestEmail(),
435 'summary' => 'Anniversaire de ' . $profile->fullName(true)
436 );
437 }
438
439 function handler_csv_birthday(PlPage $page, PlUser $user)
440 {
441 $page->changeTpl('carnet/calendar.outlook.tpl', NO_SKIN);
442 $filter = new UserFilter(new UFC_Contact($user));
443 $profiles = $filter->iterProfiles();
444 $page->assign('events', PlIteratorUtils::map($profiles, array($this, 'buildBirthRef')));
445 $years = array(date("Y"));
446 for ($i = 1; $i <= 10; ++$i) {
447 $years[] = $years[0] + $i;
448 }
449 $page->assign('years', $years);
450 $lang = 'fr';
451 if (preg_match('/([a-zA-Z]{2,8})($|[^a-zA-Z])/', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches)) {
452 $lang = strtolower($matches[1]);
453 }
454 $page->assign('lang', $lang);
455 if ($lang == 'fr') {
456 $encoding = 'iso8859-15';
457 } else {
458 $encoding = 'utf-8';
459 }
460 pl_cached_content_headers('text/comma-separated-values; charset=' . $encoding, 1);
461 }
462
463 function handler_ical(PlPage $page, PlUser $user)
464 {
465 require_once 'ical.inc.php';
466 $page->changeTpl('carnet/calendar.tpl', NO_SKIN);
467 $page->register_function('display_ical', 'display_ical');
468
469 $filter = new UserFilter(new UFC_Contact($user));
470 $profiles = $filter->iterProfiles();
471 $page->assign('events', PlIteratorUtils::map($profiles, array($this, 'buildBirthRef')));
472
473 pl_cached_content_headers('text/calendar', 1);
474 }
475
476 function handler_vcard($page, $photos = null)
477 {
478 $pf = new ProfileFilter(new UFC_Contact(S::user()));
479 $vcard = new VCard($photos == 'photos');
480 $vcard->addProfiles($pf->getProfiles(null, Profile::FETCH_ALL));
481 $vcard->show();
482 }
483
484 function handler_csv(PlPage $page, PlUser $user)
485 {
486 $page->changeTpl('carnet/mescontacts.outlook.tpl', NO_SKIN);
487 $pf = new ProfileFilter(new UFC_Contact($user));
488 require_once 'carnet/outlook.inc.php';
489 Outlook::output_profiles($pf->getProfiles(), 'fr');
490 }
491 }
492
493 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
494 ?>