More silent handler, fix sql query.
[platal.git] / modules / xnetgrp.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
23 class XnetGrpModule extends PLModule
24 {
25 function handlers()
26 {
27 return array(
28 '%grp' => $this->make_hook('index', AUTH_PUBLIC),
29 '%grp/asso.php' => $this->make_hook('index', AUTH_PUBLIC),
30 '%grp/logo' => $this->make_hook('logo', AUTH_PUBLIC),
31 '%grp/site' => $this->make_hook('site', AUTH_PUBLIC),
32 '%grp/edit' => $this->make_hook('edit', AUTH_MDP, 'groupadmin'),
33 '%grp/mail' => $this->make_hook('mail', AUTH_MDP, 'groupadmin'),
34 '%grp/forum' => $this->make_hook('forum', AUTH_MDP, 'groupmember'),
35 '%grp/annuaire' => $this->make_hook('annuaire', AUTH_MDP, 'groupannu'),
36 '%grp/annuaire/vcard' => $this->make_hook('vcard', AUTH_MDP, 'groupmember:groupannu'),
37 '%grp/annuaire/csv' => $this->make_hook('csv', AUTH_MDP, 'groupmember:groupannu'),
38 '%grp/directory/sync' => $this->make_hook('directory_sync', AUTH_MDP, 'groupadmin'),
39 '%grp/trombi' => $this->make_hook('trombi', AUTH_MDP, 'groupannu'),
40 '%grp/geoloc' => $this->make_hook('geoloc', AUTH_MDP, 'groupannu'),
41 '%grp/subscribe' => $this->make_hook('subscribe', AUTH_MDP),
42 '%grp/subscribe/valid' => $this->make_hook('subscribe_valid', AUTH_MDP, 'groupadmin'),
43 '%grp/unsubscribe' => $this->make_hook('unsubscribe', AUTH_MDP, 'groupmember'),
44
45 '%grp/change_rights' => $this->make_hook('change_rights', AUTH_MDP),
46 '%grp/admin/annuaire' => $this->make_hook('admin_annuaire', AUTH_MDP, 'groupadmin'),
47 '%grp/member' => $this->make_hook('admin_member', AUTH_MDP, 'groupadmin'),
48 '%grp/member/new' => $this->make_hook('admin_member_new', AUTH_MDP, 'groupadmin'),
49 '%grp/member/new/ajax' => $this->make_hook('admin_member_new_ajax', AUTH_MDP, 'user', NO_AUTH),
50 '%grp/member/del' => $this->make_hook('admin_member_del', AUTH_MDP, 'groupadmin'),
51 '%grp/member/suggest' => $this->make_hook('admin_member_suggest', AUTH_MDP, 'groupadmin'),
52
53 '%grp/rss' => $this->make_token_hook('rss', AUTH_PUBLIC),
54 '%grp/announce/new' => $this->make_hook('edit_announce', AUTH_MDP, 'groupadmin'),
55 '%grp/announce/edit' => $this->make_hook('edit_announce', AUTH_MDP, 'groupadmin'),
56 '%grp/announce/photo' => $this->make_hook('photo_announce', AUTH_PUBLIC),
57 '%grp/admin/announces' => $this->make_hook('admin_announce', AUTH_MDP, 'groupadmin'),
58 );
59 }
60
61 function handler_index($page, $arg = null)
62 {
63 global $globals, $platal;
64 if (!is_null($arg)) {
65 return PL_NOT_FOUND;
66 }
67 $page->changeTpl('xnetgrp/asso.tpl');
68
69 if (S::logged()) {
70 if (Env::has('read')) {
71 XDB::query('DELETE r.*
72 FROM group_announces_read AS r
73 INNER JOIN group_announces AS a ON (a.id = r.announce_id)
74 WHERE expiration < CURRENT_DATE()');
75 XDB::query('INSERT INTO group_announces_read
76 VALUES ({?}, {?})',
77 Env::i('read'), S::i('uid'));
78 pl_redirect("");
79 }
80 if (Env::has('unread')) {
81 XDB::query('DELETE FROM group_announces_read
82 WHERE announce_id = {?} AND uid = {?}',
83 Env::i('unread'), S::i('uid'));
84 pl_redirect("#art" . Env::i('unread'));
85 }
86
87 /* TODO: refines this filter on promotions by using userfilter. */
88 $user = S::user();
89 if ($user->hasProfile()) {
90 $promo = XDB::format('{?}', $user->profile()->entry_year);
91 $minCondition = ' OR promo_min <= ' . $promo;
92 $maxCondition = ' OR promo_max >= ' . $promo;
93 } else {
94 $minCondition = '';
95 $maxCondition = '';
96 }
97 $arts = XDB::iterator('SELECT a.*, FIND_IN_SET(\'photo\', a.flags) AS photo
98 FROM group_announces AS a
99 LEFT JOIN group_announces_read AS r ON (r.uid = {?} AND r.announce_id = a.id)
100 WHERE asso_id = {?} AND expiration >= CURRENT_DATE()
101 AND (promo_min = 0' . $minCondition . ')
102 AND (promo_max = 0' . $maxCondition . ')
103 AND r.announce_id IS NULL
104 ORDER BY a.expiration',
105 S::i('uid'), $globals->asso('id'));
106 $index = XDB::iterator('SELECT a.id, a.titre, r.uid IS NULL AS nonlu
107 FROM group_announces AS a
108 LEFT JOIN group_announces_read AS r ON (a.id = r.announce_id AND r.uid = {?})
109 WHERE asso_id = {?} AND expiration >= CURRENT_DATE()
110 AND (promo_min = 0' . $minCondition . ')
111 AND (promo_max = 0' . $maxCondition . ')
112 ORDER BY a.expiration',
113 S::i('uid'), $globals->asso('id'));
114 $page->assign('article_index', $index);
115 } else {
116 $arts = XDB::iterator("SELECT *, FIND_IN_SET('photo', flags) AS photo
117 FROM group_announces
118 WHERE asso_id = {?} AND expiration >= CURRENT_DATE()
119 AND FIND_IN_SET('public', flags)",
120 $globals->asso('id'));
121 }
122 if (may_update()) {
123 $subs_valid = XDB::query("SELECT uid
124 FROM group_member_sub_requests
125 WHERE asso_id = {?}",
126 $globals->asso('id'));
127 $page->assign('requests', $subs_valid->numRows());
128 }
129
130 if (!S::hasAuthToken()) {
131 $page->setRssLink("Polytechnique.net :: {$globals->asso("nom")} :: News publiques",
132 $platal->ns . "rss/rss.xml");
133 } else {
134 $page->setRssLink("Polytechnique.net :: {$globals->asso("nom")} :: News",
135 $platal->ns . 'rss/' . S::v('hruid') . '/' . S::user()->token . '/rss.xml');
136 }
137
138 $page->assign('articles', $arts);
139 }
140
141 function handler_logo($page)
142 {
143 global $globals;
144 $globals->asso()->getLogo()->send();
145 }
146
147 function handler_site($page)
148 {
149 global $globals;
150 $site = $globals->asso('site');
151 if (!$site) {
152 $page->trigError('Le groupe n\'a pas de site web.');
153 return $this->handler_index($page);
154 }
155 http_redirect($site);
156 exit;
157 }
158
159 function handler_edit($page)
160 {
161 global $globals;
162 $page->changeTpl('xnetgrp/edit.tpl');
163
164 if (Post::has('submit')) {
165 S::assert_xsrf_token();
166
167 $flags = new PlFlagSet('wiki_desc');
168 $flags->addFlag('notif_unsub', Post::i('notif_unsub') == 1);
169 $site = Post::t('site');
170 if ($site && ($site != "http://")) {
171 $scheme = parse_url($site, PHP_URL_SCHEME);
172 if (!$scheme) {
173 $site = "http://" . $site;
174 }
175 } else {
176 $site = "";
177 }
178 if (S::admin()) {
179 $page->assign('super', true);
180
181 if (Post::v('mail_domain') && (strstr(Post::v('mail_domain'), '.') === false)) {
182 $page->trigError('Le domaine doit être un FQDN (aucune modification effectuée)&nbsp;!!!');
183 return;
184 }
185 if (Post::t('nom') == '' || Post::t('diminutif') == '') {
186 $page->trigError('Ni le nom ni le diminutif du groupe ne peuvent être vide.');
187 return;
188 }
189 $axDate = make_datetime(Post::v('axDate'));
190 if (Post::t('axDate') != '') {
191 $axDate = make_datetime(Post::v('axDate'))->format('Y-m-d');
192 } else {
193 $axDate = null;
194 }
195 XDB::execute(
196 "UPDATE groups
197 SET nom={?}, diminutif={?}, cat={?}, dom={?},
198 descr={?}, site={?}, mail={?}, resp={?},
199 forum={?}, mail_domain={?}, ax={?}, axDate = {?}, pub={?},
200 sub_url={?}, inscriptible={?}, unsub_url={?},
201 flags = {?}, welcome_msg = {?}
202 WHERE id={?}",
203 Post::v('nom'), Post::v('diminutif'),
204 Post::v('cat'), (Post::i('dom') == 0) ? null : Post::i('dom'),
205 Post::v('descr'), $site,
206 Post::v('mail'), Post::v('resp'),
207 Post::v('forum'), Post::v('mail_domain'),
208 Post::has('ax'), $axDate, Post::v('pub'),
209 Post::v('sub_url'), Post::v('inscriptible'),
210 Post::v('unsub_url'), $flags, Post::t('welcome_msg'),
211 $globals->asso('id'));
212 if (Post::v('mail_domain')) {
213 XDB::execute('INSERT IGNORE INTO email_virtual_domains (name)
214 VALUES ({?})',
215 Post::t('mail_domain'));
216 XDB::execute('UPDATE email_virtual_domains
217 SET aliasing = id
218 WHERE name = {?}',
219 Post::t('mail_domain'));
220 }
221 } else {
222 XDB::execute(
223 "UPDATE groups
224 SET descr={?}, site={?}, mail={?}, resp={?},
225 forum={?}, pub= {?}, sub_url={?},
226 unsub_url = {?}, flags = {?}, welcome_msg = {?}
227 WHERE id={?}",
228 Post::v('descr'), $site,
229 Post::v('mail'), Post::v('resp'),
230 Post::v('forum'), Post::v('pub'),
231 Post::v('sub_url'), Post::v('unsub_url'),
232 $flags, Post::t('welcome_msg'),
233 $globals->asso('id'));
234 }
235
236 Phone::deletePhones(0, Phone::LINK_GROUP, $globals->asso('id'));
237 $phone = new Phone(array('link_type' => 'group', 'link_id' => $globals->asso('id'), 'id' => 0,
238 'type' => 'fixed', 'display' => Post::v('phone'), 'pub' => 'public'));
239 $fax = new Phone(array('link_type' => 'group', 'link_id' => $globals->asso('id'), 'id' => 1,
240 'type' => 'fax', 'display' => Post::v('fax'), 'pub' => 'public'));
241 $phone->save();
242 $fax->save();
243 Address::deleteAddresses(null, Address::LINK_GROUP, null, $globals->asso('id'));
244 $address = new Address(array('groupid' => $globals->asso('id'), 'type' => Address::LINK_GROUP, 'text' => Post::v('address')));
245 $address->save();
246
247 if ($_FILES['logo']['name']) {
248 $upload = PlUpload::get($_FILES['logo'], $globals->asso('id'), 'asso.logo', true);
249 if (!$upload) {
250 $page->trigError("Impossible de télécharger le logo.");
251 } else {
252 XDB::execute('UPDATE groups
253 SET logo = {?}, logo_mime = {?}
254 WHERE id = {?}', $upload->getContents(), $upload->contentType(),
255 $globals->asso('id'));
256 $upload->rm();
257 }
258 }
259
260 pl_redirect('../' . Post::v('diminutif', $globals->asso('diminutif')) . '/edit');
261 }
262
263 if (S::admin()) {
264 $dom = XDB::iterator('SELECT *
265 FROM group_dom
266 ORDER BY nom');
267 $page->assign('dom', $dom);
268 $page->assign('super', true);
269 }
270 }
271
272 function handler_mail($page)
273 {
274 global $globals;
275
276 $page->changeTpl('xnetgrp/mail.tpl');
277 $mmlist = new MMList(S::user(), $globals->asso('mail_domain'));
278 $page->assign('listes', $mmlist->get_lists());
279 $page->assign('user', S::user());
280
281 if (Post::has('send')) {
282 S::assert_xsrf_token();
283 $from = Post::v('from');
284 $sujet = Post::v('sujet');
285 $body = Post::v('body');
286
287 $mls = array_keys(Env::v('ml', array()));
288 $mbr = array_keys(Env::v('membres', array()));
289
290 $this->load('mail.inc.php');
291 set_time_limit(120);
292 $tos = get_all_redirects($mbr, $mls, $mmlist);
293
294 $upload = PlUpload::get($_FILES['uploaded'], S::user()->login(), 'xnet.emails', true);
295 if (!$upload && @$_FILES['uploaded']['name'] && PlUpload::$lastError != null) {
296 $page->trigError(PlUpload::$lastError);
297 return;
298 }
299
300 send_xnet_mails($from, $sujet, $body, Env::v('wiki'), $tos, Post::v('replyto'), $upload, @$_FILES['uploaded']['name']);
301 if ($upload) {
302 $upload->rm();
303 }
304 $page->killSuccess("Email envoyé&nbsp;!");
305 $page->assign('sent', true);
306 }
307 }
308
309 function handler_forum($page, $group = null, $artid = null)
310 {
311 global $globals;
312 $page->changeTpl('xnetgrp/forum.tpl');
313 if (!$globals->asso('forum')) {
314 return PL_NOT_FOUND;
315 }
316 require_once 'banana/forum.inc.php';
317 $get = array();
318 get_banana_params($get, $globals->asso('forum'), $group, $artid);
319 run_banana($page, 'ForumsBanana', $get);
320 }
321
322 function handler_annuaire($page, $action = null, $subaction = null)
323 {
324 global $globals;
325
326 if ($action == 'trombi') {
327 __autoload('userset');
328 if ($action == 'trombi') {
329 $view = new ProfileSet(new UFC_Group($globals->asso('id')));
330 } else {
331 $view = new UserSet(new UFC_Group($globals->asso('id')));
332 }
333 $view->addMod('trombi', 'Trombinoscope');
334 $view->apply('annuaire', $page, $action, $subaction);
335 $page->changeTpl('xnetgrp/annuaire.tpl');
336 $count = XDB::fetchOneCell('SELECT COUNT(*)
337 FROM group_members
338 WHERE asso_id = {?}',
339 $globals->asso('id'));
340 $page->assign('nb_tot', $count);
341 return;
342 }
343
344 $page->changeTpl('xnetgrp/annuaire.tpl');
345 $sort = Env::s('order', 'directory_name');
346 $ofs = Env::i('offset');
347 if ($ofs < 0) {
348 $ofs = 0;
349 }
350
351 $sdesc = $sort{0} == '-';
352 $sf = $sdesc ? substr($sort, 1) : $sort;
353 if ($sf == 'promo') {
354 $se = new UFO_Promo(null, $sdesc);
355 } else {
356 $se = new UFO_Name($sf, null, null, $sdesc);
357 }
358
359 if (Env::b('admin')) {
360 $uf = $globals->asso()->getAdminsFilter(null, $se);
361 } else {
362 $uf = $globals->asso()->getMembersFilter(null, $se);
363 }
364 $users = $uf->getUsers(new PlLimit(NB_PER_PAGE, $ofs * NB_PER_PAGE));
365 $count = $uf->getTotalCount();
366
367 $page->assign('nb_tot', $count);
368 $page->assign('pages', floor(($count + NB_PER_PAGE - 1) / NB_PER_PAGE));
369 $page->assign('current', $ofs);
370 $page->assign('order', $sort);
371 $page->assign('users', $users);
372 $page->assign('only_admin', Env::b('admin'));
373 }
374
375 function handler_trombi($page)
376 {
377 pl_redirect('annuaire/trombi');
378 }
379
380 function handler_geoloc($page)
381 {
382 pl_redirect('annuaire/geoloc');
383 }
384
385 function handler_vcard($page, $photos = null)
386 {
387 global $globals;
388 $vcard = new VCard($photos == 'photos', 'Membre du groupe ' . $globals->asso('nom'));
389 $vcard->addProfiles($globals->asso()->getMembersFilter()->getProfiles(null, Profile::FETCH_ALL));
390 $vcard->show();
391 }
392
393 function handler_csv($page, $filename = null)
394 {
395 global $globals;
396 if (is_null($filename)) {
397 $filename = $globals->asso('diminutif') . '.csv';
398 }
399 $users = $globals->asso()->getMembersFilter(null, new UFO_Name('directory_name'))->getUsers();
400 pl_cached_content_headers('text/x-csv', 1);
401 $page->changeTpl('xnetgrp/annuaire-csv.tpl', NO_SKIN);
402 $page->assign('users', $users);
403 }
404
405 function handler_directory_sync($page)
406 {
407 global $globals;
408 require_once 'emails.inc.php';
409
410 $page->changeTpl('xnetgrp/sync.tpl');
411 Platal::load('lists', 'lists.inc.php');
412
413 if (Env::has('add_users')) {
414 S::assert_xsrf_token();
415
416 $users = array_keys(Env::v('add_users'));
417 $data = array();
418 foreach ($users as $uid) {
419 $data[] = XDB::format('({?}, {?})', $globals->asso('id'), $uid);
420 }
421 XDB::rawExecute('INSERT INTO group_members (asso_id, uid)
422 VALUES ' . implode(',', $data));
423 }
424
425 if (Env::has('add_nonusers')) {
426 S::assert_xsrf_token();
427
428 $nonusers = array_keys(Env::v('add_nonusers'));
429 foreach ($nonusers as $email) {
430 if ($user = User::getSilent($email) || !isvalid_email($email)) {
431 continue;
432 }
433
434 list($local_part, $domain) = explode('@', strtolower($email));
435 $hruid = User::makeHrid($local_part, $domain, 'ext');
436 if ($user = User::getSilent($hruid)) {
437 continue;
438 }
439
440 $parts = explode('.', $local_part);
441 if (count($parts) == 1) {
442 $lastname = $display_name = $full_name = $directory_name = ucfirst($local_part);
443 $firstname = '';
444 } else {
445 $firstname = ucfirst($parts[0]);
446 $lastname = ucwords(implode(' ', array_slice($parts, 1)));
447 $display_name = $firstname;
448 $full_name = $firstname . ' ' . $lastname;
449 $directory_name = strtoupper($lastname) . ' ' . $firstname;
450 }
451 XDB::execute('INSERT INTO accounts (hruid, display_name, full_name, directory_name, firstname, lastname, email, type, state)
452 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, \'xnet\', \'disabled\')',
453 $hruid, $display_name, $full_name, $directory_name, $firstname, $lastname, $email);
454 $uid = XDB::insertId();
455 XDB::execute('INSERT INTO group_members (asso_id, uid)
456 VALUES ({?}, {?})',
457 $globals->asso('id'), $uid);
458 }
459 }
460
461 if (Env::has('add_users') || Env::has('add_nonusers')) {
462 $page->trigSuccess('Ajouts réalisés avec succès.');
463 }
464
465 $user = S::user();
466 $client = new MMList($user, $globals->asso('mail_domain'));
467 $lists = $client->get_lists();
468 $members = array();
469 foreach ($lists as $list) {
470 $details = $client->get_members($list['list']);
471 $members = array_merge($members, list_extract_members($details[1]));
472 }
473 $members = array_unique($members);
474 $uids = array();
475 $users = array();
476 $nonusers = array();
477 foreach ($members as $email) {
478 if ($user = User::getSilent($email)) {
479 $uids[] = $user->id();
480 } else {
481 $nonusers[] = $email;
482 }
483 }
484
485 $aliases = iterate_list_alias($globals->asso('mail_domain'));
486 foreach ($aliases as $alias) {
487 list($local_part, $domain) = explode('@', $alias);
488 $aliases_members = list_alias_members($local_part, $domain);
489 $users = array_merge($users, $aliases_members['users']);
490 $nonusers = array_merge($nonusers, $aliases_members['nonusers']);
491 }
492 foreach ($users as $user) {
493 $uids[] = $user->id();
494 }
495 $nonusers = array_unique($nonusers);
496 $uids = array_unique($uids);
497 $uids = XDB::fetchColumn('SELECT a.uid
498 FROM accounts AS a
499 WHERE a.uid IN {?} AND NOT EXISTS (SELECT *
500 FROM group_members AS g
501 WHERE a.uid = g.uid AND g.asso_id = {?})',
502 $uids, $globals->asso('id'));
503
504 $users = User::getBulkUsersWithUIDs($uids);
505 usort($users, 'User::compareDirectoryName');
506 sort($nonusers);
507
508 $page->assign('users', $users);
509 $page->assign('nonusers', $nonusers);
510 }
511
512 private function removeSubscriptionRequest($uid)
513 {
514 global $globals;
515 XDB::execute("DELETE FROM group_member_sub_requests
516 WHERE asso_id = {?} AND uid = {?}",
517 $globals->asso('id'), $uid);
518 }
519
520 private function validSubscription(User $user)
521 {
522 global $globals;
523 $this->removeSubscriptionRequest($user->id());
524 XDB::execute("INSERT IGNORE INTO group_members (asso_id, uid)
525 VALUES ({?}, {?})",
526 $globals->asso('id'), $user->id());
527 if (XDB::affectedRows() == 1) {
528 $mailer = new PlMailer();
529 $mailer->addTo($user->forlifeEmail());
530 $mailer->setFrom('"' . S::user()->fullName() . '" <' . S::user()->forlifeEmail() . '>');
531 $mailer->setSubject('[' . $globals->asso('nom') . '] Demande d\'inscription');
532 $message = ($user->isFemale() ? 'Chère' : 'Cher') . " Camarade,\n"
533 . "\n"
534 . " Suite à ta demande d'adhésion à " . $globals->asso('nom')
535 . ", j'ai le plaisir de t'annoncer que ton inscription a été validée !\n"
536 . (is_null($globals->asso('welcome_msg')) ? '' : "\n" . $globals->asso('welcome_msg') . "\n")
537 . "\n"
538 . "Bien cordialement,\n"
539 . "-- \n"
540 . S::user()->fullName() . '.';
541 $mailer->setTxtBody(wordwrap($message, 72));
542 $mailer->send();
543 }
544 }
545
546 function handler_subscribe($page, $u = null)
547 {
548 global $globals;
549 $page->changeTpl('xnetgrp/inscrire.tpl');
550
551 if (!$globals->asso('inscriptible'))
552 $page->kill("Il n'est pas possible de s'inscire en ligne à ce "
553 ."groupe. Essaie de joindre le contact indiqué "
554 ."sur la page de présentation.");
555
556 if (!is_null($u) && may_update()) {
557 $user = User::get($u);
558 if (!$user) {
559 return PL_NOT_FOUND;
560 } else {
561 $page->assign('user', $user);
562 }
563
564 // Retrieves the subscription status, and the reason.
565 $res = XDB::query("SELECT reason
566 FROM group_member_sub_requests
567 WHERE asso_id = {?} AND uid = {?}",
568 $globals->asso('id'), $user->id());
569 $reason = ($res->numRows() ? $res->fetchOneCell() : null);
570
571 $res = XDB::query("SELECT COUNT(*)
572 FROM group_members
573 WHERE asso_id = {?} AND uid = {?}",
574 $globals->asso('id'), $user->id());
575 $already_member = ($res->fetchOneCell() > 0);
576
577 // Handles the membership request.
578 if ($already_member) {
579 $this->removeSubscriptionRequest($user->id());
580 $page->kill($user->fullName() . ' est déjà membre du groupe&nbsp;!');
581 } elseif (Env::has('accept')) {
582 S::assert_xsrf_token();
583
584 $this->validSubscription($user);
585 pl_redirect("member/" . $user->login());
586 } elseif (Env::has('refuse')) {
587 S::assert_xsrf_token();
588
589 $this->removeSubscriptionRequest($user->id());
590 $mailer = new PlMailer();
591 $mailer->addTo($user->forlifeEmail());
592 $mailer->setFrom('"' . S::user()->fullName() . '" <' . S::user()->forlifeEmail() . '>');
593 $mailer->setSubject('['.$globals->asso('nom').'] Demande d\'inscription annulée');
594 $mailer->setTxtBody(Env::v('motif'));
595 $mailer->send();
596 $page->killSuccess("La demande de {$user->fullName()} a bien été refusée.");
597 } else {
598 $page->assign('show_form', true);
599 $page->assign('reason', $reason);
600 }
601 return;
602 }
603
604 if (is_member()) {
605 $page->kill("Tu es déjà membre&nbsp;!");
606 return;
607 }
608
609 $res = XDB::query("SELECT uid
610 FROM group_member_sub_requests
611 WHERE uid = {?} AND asso_id = {?}",
612 S::i('uid'), $globals->asso('id'));
613 if ($res->numRows() != 0) {
614 $page->kill("Tu as déjà demandé ton inscription à ce groupe. Cette demande est actuellement en attente de validation.");
615 return;
616 }
617
618 if (Post::has('inscrire')) {
619 S::assert_xsrf_token();
620
621 XDB::execute("INSERT INTO group_member_sub_requests (asso_id, uid, ts, reason)
622 VALUES ({?}, {?}, NOW(), {?})",
623 $globals->asso('id'), S::i('uid'), Post::v('message'));
624 $uf = New UserFilter(New UFC_Group($globals->asso('id'), true));
625 $admins = $uf->iterUsers();
626 $admin = $admins->next();
627 $to = $admin->bestEmail();
628 while ($admin = $admins->next()) {
629 $to .= ', ' . $admin->bestEmail();
630 }
631
632 $append = "\n"
633 . "-- \n"
634 . "Ce message a été envoyé suite à la demande d'inscription de\n"
635 . S::user()->fullName() . ' (X' . S::v('promo') . ")\n"
636 . "Via le site www.polytechnique.net. Tu peux choisir de valider ou\n"
637 . "de refuser sa demande d'inscription depuis la page :\n"
638 . "http://www.polytechnique.net/" . $globals->asso("diminutif") . "/subscribe/" . S::user()->login() . "\n"
639 . "\n"
640 . "En cas de problème, contacter l'équipe de Polytechnique.org\n"
641 . "à l'adresse : support@polytechnique.org\n";
642
643 if (!$to) {
644 $to = ($globals->asso('mail') != '') ? $globals->asso('mail') . ', ' : '';
645 $to .= 'support@polytechnique.org';
646 $append = "\n-- \nLe groupe ".$globals->asso("nom")
647 ." n'a pas d'administrateur, l'équipe de"
648 ." Polytechnique.org a été prévenue et va rapidement"
649 ." résoudre ce problème.\n";
650 }
651
652 $mailer = new PlMailer();
653 $mailer->addTo($to);
654 $mailer->setFrom('"' . S::user()->fullName() . '" <' . S::user()->forlifeEmail() . '>');
655 $mailer->setSubject('['.$globals->asso('nom').'] Demande d\'inscription');
656 $mailer->setTxtBody(Post::v('message').$append);
657 $mailer->send();
658 }
659 }
660
661 function handler_subscribe_valid($page)
662 {
663 global $globals;
664
665 if (Post::has('valid')) {
666 S::assert_xsrf_token();
667 $subs = Post::v('subs');
668 if (is_array($subs)) {
669 $users = array();
670 foreach ($subs as $hruid => $val) {
671 if ($val == '1') {
672 $user = User::get($hruid);
673 if ($user) {
674 $this->validSubscription($user);
675 }
676 }
677 }
678 }
679 }
680
681 $it = XDB::iterator('SELECT s.uid, a.hruid, s.ts AS date
682 FROM group_member_sub_requests AS s
683 INNER JOIN accounts AS a ON(s.uid = a.uid)
684 WHERE s.asso_id = {?}
685 ORDER BY s.ts', $globals->asso('id'));
686 $page->changeTpl('xnetgrp/subscribe-valid.tpl');
687 $page->assign('valid', $it);
688 }
689
690 function handler_change_rights($page)
691 {
692 if (Env::has('right') && (may_update() || S::suid())) {
693 switch (Env::v('right')) {
694 case 'admin':
695 Platal::session()->stopSUID();
696 break;
697 case 'anim':
698 Platal::session()->doSelfSuid();
699 may_update(true);
700 is_member(true);
701 break;
702 case 'member':
703 Platal::session()->doSelfSuid();
704 may_update(false, true);
705 is_member(true);
706 break;
707 case 'logged':
708 Platal::session()->doSelfSuid();
709 may_update(false, true);
710 is_member(false, true);
711 break;
712 }
713 }
714 http_redirect($_SERVER['HTTP_REFERER']);
715 }
716
717 function handler_admin_annuaire($page)
718 {
719 global $globals;
720
721 $this->load('mail.inc.php');
722 $page->changeTpl('xnetgrp/annuaire-admin.tpl');
723 $user = S::user();
724 $mmlist = new MMList($user, $globals->asso('mail_domain'));
725 $lists = $mmlist->get_lists();
726 if (!$lists) $lists = array();
727 $listes = array_map(create_function('$arr', 'return $arr["list"];'), $lists);
728
729 $subscribers = array();
730
731 foreach ($listes as $list) {
732 list(,$members) = $mmlist->get_members($list);
733 $mails = array_map(create_function('$arr', 'return $arr[1];'), $members);
734 $subscribers = array_unique(array_merge($subscribers, $mails));
735 }
736
737 $not_in_group_x = array();
738 $not_in_group_ext = array();
739
740 foreach ($subscribers as $mail) {
741 $uf = new UserFilter(new PFC_And(new UFC_Group($globals->asso('id')),
742 new UFC_Email($mail)));
743 if ($uf->getTotalCount() == 0) {
744 if (User::isForeignEmailAddress($mail)) {
745 $not_in_group_ext[] = $mail;
746 } else {
747 $not_in_group_x[] = $mail;
748 }
749 }
750 }
751
752 $page->assign('not_in_group_ext', $not_in_group_ext);
753 $page->assign('not_in_group_x', $not_in_group_x);
754 $page->assign('lists', $lists);
755 }
756
757 function handler_admin_member_new($page, $email = null)
758 {
759 global $globals;
760
761 $page->changeTpl('xnetgrp/membres-add.tpl');
762
763 if (is_null($email)) {
764 return;
765 }
766
767 S::assert_xsrf_token();
768 $suggest_account_activation = false;
769
770 // FS#703 : $_GET is urldecoded twice, hence
771 // + (the data) => %2B (in the url) => + (first decoding) => ' ' (second decoding)
772 // Since there can be no spaces in emails, we can fix this with :
773 $email = str_replace(' ', '+', $email);
774
775 // Finds or creates account: first cases are for users with an account.
776 if (!User::isForeignEmailAddress($email)) {
777 // Standard account
778 $user = User::getSilent($email);
779 } else if (!isvalid_email($email)) {
780 // email might not be a regular email but an alias or a hruid
781 $user = User::getSilent($email);
782 if (!$user) {
783 // need a valid email address
784 $page->trigError('«&nbsp;<strong>' . $email . '</strong>&nbsp;» n\'est pas une adresse email valide.');
785 return;
786 }
787 } else if (Env::v('x') && Env::i('userid')) {
788 $user = User::getSilentWithUID(Env::i('userid'));
789 if (!$user) {
790 $page->trigError('Utilisateur invalide.');
791 return;
792 }
793
794 // User has an account but is not yet registered.
795 if ($user->state == 'pending') {
796 // Add email in account table.
797 XDB::query('UPDATE accounts
798 SET email = {?}
799 WHERE uid = {?} AND email IS NULL',
800 Post::t('email'), $user->id());
801 // Add email for marketing if required.
802 if (Env::v('market')) {
803 $market = Marketing::get($user->uid, $email);
804 if (!$market) {
805 $market = new Marketing($user->uid, $email, 'group', $globals->asso('nom'),
806 Env::v('market_from'), S::v('uid'));
807 $market->add();
808 }
809 }
810 }
811 } else {
812 // User is of type xnet. There are 3 possible cases:
813 // * the email is not known yet: we create a new account and
814 // propose to send an email to the user so he can activate
815 // his account,
816 // * the email is known but the user was not contacted in order to
817 // activate yet: we propose to send an email to the user so he
818 // can activate his account,
819 // * the email is known and the user was already contacted or has
820 // an active account: nothing to be done.
821 list($mbox, $domain) = explode('@', strtolower($email));
822 $hruid = User::makeHrid($mbox, $domain, 'ext');
823 // User might already have an account (in another group for example).
824 $user = User::getSilent($hruid);
825
826 // If the user has no account yet, creates new account: build names from email address.
827 if (empty($user)) {
828 $parts = explode('.', $mbox);
829 if (count($parts) == 1) {
830 $lastname = $display_name = $full_name = $directory_name = ucfirst($mbox);
831 $firstname = '';
832 } else {
833 $firstname = ucfirst($parts[0]);
834 $lastname = ucwords(implode(' ', array_slice($parts, 1)));
835 $display_name = $firstname;
836 $full_name = "$firstname $lastname";
837 $directory_name = strtoupper($lastname) . " " . $firstname;
838 }
839 XDB::execute('INSERT INTO accounts (hruid, display_name, full_name, directory_name, firstname, lastname, email, type, state)
840 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, \'xnet\', \'disabled\')',
841 $hruid, $display_name, $full_name, $directory_name, $firstname, $lastname, $email);
842 $user = User::getSilent($hruid);
843 }
844
845 $suggest_account_activation = $this->suggest($user);
846 }
847
848 if ($user) {
849 XDB::execute('INSERT IGNORE INTO group_members (uid, asso_id)
850 VALUES ({?}, {?})',
851 $user->id(), $globals->asso('id'));
852 $this->removeSubscriptionRequest($user->id());
853 if ($suggest_account_activation) {
854 pl_redirect('member/suggest/' . $user->login() . '/' . $email . '/' . $globals->asso('nom'));
855 } else {
856 pl_redirect('member/' . $user->login());
857 }
858 }
859 }
860
861 // Check if the user has a pending or active account, and thus if we should her account's activation.
862 private function suggest(PlUser $user)
863 {
864 $active = XDB::fetchOneCell('SELECT state = \'active\'
865 FROM accounts
866 WHERE uid = {?}',
867 $user->id());
868 $pending = XDB::fetchOneCell('SELECT uid
869 FROM register_pending_xnet
870 WHERE uid = {?}',
871 $user->id());
872 $requested = AccountReq::isPending($user->id());
873
874 if ($active || $pending || $requested) {
875 return false;
876 }
877 return true;
878 }
879
880 function handler_admin_member_suggest($page, $hruid, $email)
881 {
882 $page->changeTpl('xnetgrp/membres-suggest.tpl');
883
884 // FS#703 : $_GET is urldecoded twice, hence
885 // + (the data) => %2B (in the url) => + (first decoding) => ' ' (second decoding)
886 // Since there can be no spaces in emails, we can fix this with :
887 $email = str_replace(' ', '+', $email);
888
889 if (Post::has('suggest')) {
890 if (Post::t('suggest') == 'yes') {
891 $user = S::user();
892 $group = Platal::globals()->asso('nom');
893 $request = new AccountReq($user, $hruid, $email, $group);
894 $request->submit();
895 $page->trigSuccessRedirect('Un email va bien être envoyé à ' . $email . ' pour l\'activation de son compte.',
896 $group . '/member/' . $hruid);
897 } else {
898 pl_redirect('member/' . $hruid);
899 }
900 }
901 $page->assign('email', $email);
902 $page->assign('hruid', $hruid);
903 }
904
905 function handler_admin_member_new_ajax($page)
906 {
907 pl_content_headers("text/html");
908 $page->changeTpl('xnetgrp/membres-new-search.tpl', NO_SKIN);
909 $users = array();
910 if (Env::has('login')) {
911 $user = User::getSilent(Env::t('login'));
912 if ($user && $user->state != 'pending') {
913 $users = array($user);
914 }
915 }
916 if (empty($users)) {
917 list($lastname, $firstname) = str_replace(array('-', ' ', "'"), '%', array(Env::t('nom'), Env::t('prenom')));
918 $cond = new PFC_And(new PFC_Not(new UFC_Registered()));
919 if (!empty($lastname)) {
920 $cond->addChild(new UFC_Name(Profile::LASTNAME, $lastname, UFC_Name::CONTAINS));
921 }
922 if (!empty($firstname)) {
923 $cond->addChild(new UFC_Name(Profile::FIRSTNAME, $firstname, UFC_Name::CONTAINS));
924 }
925 if (Env::t('promo')) {
926 $cond->addChild(new UFC_Promo('=', UserFilter::DISPLAY, Env::t('promo')));
927 }
928 $uf = new UserFilter($cond);
929 $users = $uf->getUsers(new PlLimit(30));
930 if ($uf->getTotalCount() > 30) {
931 $page->assign('too_many', true);
932 $users = array();
933 }
934 }
935 $page->assign('users', $users);
936 }
937
938 function unsubscribe(PlUser $user)
939 {
940 global $globals;
941 XDB::execute("DELETE FROM group_members
942 WHERE uid = {?} AND asso_id = {?}",
943 $user->id(), $globals->asso('id'));
944
945 if ($globals->asso('notif_unsub')) {
946 $mailer = new PlMailer('xnetgrp/unsubscription-notif.mail.tpl');
947 $admins = $globals->asso()->iterAdmins();
948 while ($admin = $admins->next()) {
949 $mailer->addTo($admin);
950 }
951 $mailer->assign('group', $globals->asso('nom'));
952 $mailer->assign('user', $user);
953 $mailer->assign('selfdone', $user->id() == S::i('uid'));
954 $mailer->send();
955 }
956
957 $domain = $globals->asso('mail_domain');
958 if (!$domain) {
959 return true;
960 }
961
962 $mmlist = new MMList(S::user(), $domain);
963 $listes = $mmlist->get_lists($user->forlifeEmail());
964
965 $may_update = may_update();
966 $warning = false;
967 if (is_array($listes)) {
968 foreach ($listes as $liste) {
969 if ($liste['sub'] == 2) {
970 if ($may_update) {
971 $mmlist->mass_unsubscribe($liste['list'], Array($user->forlifeEmail()));
972 } else {
973 $mmlist->unsubscribe($liste['list']);
974 }
975 } elseif ($liste['sub']) {
976 Platal::page()->trigWarning($user->fullName() . " a une"
977 ." demande d'inscription en cours sur la"
978 ." liste {$liste['list']}@ !");
979 $warning = true;
980 }
981 }
982 }
983
984 XDB::execute('DELETE v
985 FROM email_virtual AS v
986 INNER JOIN email_virtual_domains AS d ON (v.domain = d.id)
987 WHERE v.redirect = {?} AND d.name = {?}',
988 $user->forlifeEmail(), $domain);
989 return !$warning;
990 }
991
992 function handler_unsubscribe($page)
993 {
994 $page->changeTpl('xnetgrp/membres-del.tpl');
995 $user = S::user();
996 if (empty($user)) {
997 return PL_NOT_FOUND;
998 }
999 $page->assign('self', true);
1000 $page->assign('user', $user);
1001
1002 if (!Post::has('confirm')) {
1003 return;
1004 } else {
1005 S::assert_xsrf_token();
1006 }
1007
1008 $hasSingleGroup = ($user->groupCount() == 1);
1009
1010 if ($this->unsubscribe($user)) {
1011 $page->trigSuccess('Tu as été désinscrit du groupe avec succès.');
1012 } else {
1013 $page->trigWarning('Tu as été désinscrit du groupe, mais des erreurs se sont produites lors des désinscriptions des alias et des listes de diffusion.');
1014 }
1015
1016 // If user is of type xnet account and this was her last group, disable the account.
1017 if ($user->type == 'xnet' && $hasSingleGroup) {
1018 $user->clear(true);
1019 }
1020 $page->assign('is_member', is_member(true));
1021 }
1022
1023 function handler_admin_member_del($page, $user = null)
1024 {
1025 $page->changeTpl('xnetgrp/membres-del.tpl');
1026 $user = User::getSilent($user);
1027 if (empty($user)) {
1028 return PL_NOT_FOUND;
1029 }
1030
1031 global $globals;
1032
1033 if (!$user->inGroup($globals->asso('id'))) {
1034 pl_redirect('annuaire');
1035 }
1036
1037 $page->assign('self', false);
1038 $page->assign('user', $user);
1039
1040 if (!Post::has('confirm')) {
1041 return;
1042 } else {
1043 S::assert_xsrf_token();
1044 }
1045
1046 $hasSingleGroup = ($user->groupCount() == 1);
1047
1048 if ($this->unsubscribe($user)) {
1049 $page->trigSuccess("{$user->fullName()} a été désinscrit du groupe&nbsp;!");
1050 } else {
1051 $page->trigWarning("{$user->fullName()} a été désinscrit du groupe, mais des erreurs subsistent&nbsp;!");
1052 }
1053
1054 // If user is of type xnet account and this was her last group, disable the account.
1055 if ($user->type == 'xnet' && $hasSingleGroup) {
1056 $user->clear(true);
1057 }
1058 }
1059
1060 private function changeLogin(PlPage $page, PlUser $user, $login)
1061 {
1062 // Search the user's uid.
1063 $xuser = User::getSilent($login);
1064 if (!$xuser) {
1065 $accounts = User::getPendingAccounts($login);
1066 if (!$accounts) {
1067 $page->trigError("L'identifiant $login ne correspond à aucun X.");
1068 return false;
1069 } else if (count($accounts) > 1) {
1070 $page->trigError("L'identifiant $login correspond à plusieurs camarades.");
1071 return false;
1072 }
1073 $xuser = User::getSilent($accounts[0]['uid']);
1074 }
1075
1076 if (!$xuser) {
1077 return false;
1078 }
1079
1080 if ($user->mergeIn($xuser)) {
1081 return $xuser->login();
1082 }
1083 return $user->login();
1084 }
1085
1086 function handler_admin_member($page, $user)
1087 {
1088 global $globals;
1089
1090 $user = User::getSilent($user);
1091 if (empty($user)) {
1092 return PL_NOT_FOUND;
1093 }
1094
1095 if (!$user->inGroup($globals->asso('id'))) {
1096 pl_redirect('annuaire');
1097 }
1098
1099 $page->changeTpl('xnetgrp/membres-edit.tpl');
1100
1101 $mmlist = new MMList(S::user(), $globals->asso('mail_domain'));
1102
1103 if (Post::has('change')) {
1104 require_once 'emails.inc.php';
1105 S::assert_xsrf_token();
1106
1107 // Convert user status to X
1108 if (!Post::blank('login_X')) {
1109 $forlife = $this->changeLogin($page, $user, Post::t('login_X'));
1110 if ($forlife) {
1111 pl_redirect('member/' . $forlife);
1112 }
1113 }
1114
1115 // Update user info
1116 $email_changed = (!$user->profile() && strtolower($user->forlifeEmail()) != strtolower(Post::v('email')));
1117 $from_email = $user->forlifeEmail();
1118 if ($user->type == 'virtual' || ($user->type == 'xnet' && !$user->perms)) {
1119 $lastname = Post::s('lastname');
1120 if (Post::s('type') != 'virtual') {
1121 $firstname = Post::s('firstname');
1122 $full_name = $firstname . ' ' . $lastname;
1123 $directory_name = mb_strtoupper($lastname) . ' ' . $firstname;
1124 } else {
1125 $firstname = '';
1126 $full_name = $lastname;
1127 $directory_name = mb_strtoupper($lastname);
1128 }
1129 XDB::query('UPDATE accounts
1130 SET full_name = {?}, directory_name = {?}, display_name = {?},
1131 firstname = {?}, lastname = {?}, sex = {?}, email = {?}, type = {?}
1132 WHERE uid = {?}',
1133 $full_name, $directory_name, Post::t('display_name'), $firstname, $lastname,
1134 (Post::t('sex') == 'male') ? 'male' : 'female', Post::t('email'),
1135 (Post::t('type') == 'xnet') ? 'xnet' : 'virtual', $user->id());
1136 } else if (!$user->perms) {
1137 XDB::query('UPDATE accounts
1138 SET email = {?}
1139 WHERE uid = {?}',
1140 Post::t('email'), $user->id());
1141 }
1142 if (require_email_update($user, Post::t('email'))) {
1143 $listClient = new MMList(S::user());
1144 $listClient->change_user_email($user->forlifeEmail(), Post::t('email'));
1145 update_alias_user($user->forlifeEmail(), Post::t('email'));
1146 }
1147 if (XDB::affectedRows()) {
1148 $page->trigSuccess('Données de l\'utilisateur mises à jour.');
1149 }
1150
1151 if (($user->type == 'xnet' && !$user->perms) && Post::b('suggest')) {
1152 $request = new AccountReq(S::user(), $user->hruid, Post::t('email'), $globals->asso('nom'));
1153 $request->submit();
1154 $page->trigSuccess('Le compte va bientôt être activé.');
1155 }
1156
1157 // Update group params for user
1158 $perms = Post::v('group_perms');
1159 $comm = Post::t('comm');
1160 $position = (Post::t('group_position') == '') ? null : Post::v('group_position');
1161 if ($user->group_perms != $perms || $user->group_comm != $comm || $user->group_position != $position) {
1162 XDB::query('UPDATE group_members
1163 SET perms = {?}, comm = {?}, position = {?}
1164 WHERE uid = {?} AND asso_id = {?}',
1165 ($perms == 'admin') ? 'admin' : 'membre', $comm, $position,
1166 $user->id(), $globals->asso('id'));
1167 if (XDB::affectedRows()) {
1168 if ($perms != $user->group_perms) {
1169 $page->trigSuccess('Permissions modifiées&nbsp;!');
1170 }
1171 if ($comm != $user->group_comm) {
1172 $page->trigSuccess('Commentaire mis à jour.');
1173 }
1174 if ($position != $user->group_position) {
1175 $page->trigSuccess('Poste mis à jour.');
1176 }
1177 }
1178 }
1179
1180 // Gets user info again as they might have change
1181 $user = User::getSilent($user->id());
1182
1183 // Update ML subscriptions
1184 foreach (Env::v('ml1', array()) as $ml => $state) {
1185 $ask = empty($_REQUEST['ml2'][$ml]) ? 0 : 2;
1186 if ($ask == $state) {
1187 if ($state && $email_changed) {
1188 $mmlist->replace_email($ml, $from_email, $user->forlifeEmail());
1189 $page->trigSuccess("L'abonnement de {$user->fullName()} à $ml@ a été mis à jour.");
1190 }
1191 continue;
1192 }
1193 if ($state == '1') {
1194 $page->trigWarning("{$user->fullName()} a "
1195 ."actuellement une demande d'inscription en "
1196 ."cours sur <strong>$ml@</strong> !!!");
1197 } elseif ($ask) {
1198 $mmlist->mass_subscribe($ml, Array($user->forlifeEmail()));
1199 $page->trigSuccess("{$user->fullName()} a été abonné à $ml@.");
1200 } else {
1201 if ($email_changed) {
1202 $mmlist->mass_unsubscribe($ml, Array($from_email));
1203 } else {
1204 $mmlist->mass_unsubscribe($ml, Array($user->forlifeEmail()));
1205 }
1206 $page->trigSuccess("{$user->fullName()} a été désabonné de $ml@.");
1207 }
1208 }
1209
1210 // Change subscriptioin to aliases
1211 foreach (Env::v('ml3', array()) as $ml => $state) {
1212 require_once 'emails.inc.php';
1213 $ask = !empty($_REQUEST['ml4'][$ml]);
1214 list($local_part, ) = explode('@', $ml);
1215 if($state == $ask) {
1216 if ($state && $email_changed) {
1217 update_list_alias($user->id(), $from_email, $local_part, $globals->asso('mail_domain'));
1218 $page->trigSuccess("L'abonnement de {$user->fullName()} à $ml a été mis à jour.");
1219 }
1220 } else if($ask) {
1221 add_to_list_alias($user->id(), $local_part, $globals->asso('mail_domain'));
1222 $page->trigSuccess("{$user->fullName()} a été abonné à $ml.");
1223 } else {
1224 delete_from_list_alias($user->id(), $local_part, $globals->asso('mail_domain'));
1225 $page->trigSuccess("{$user->fullName()} a été désabonné de $ml.");
1226 }
1227 }
1228 }
1229
1230 $res = XDB::rawFetchAllAssoc('SHOW COLUMNS FROM group_members LIKE \'position\'');
1231 $positions = str_replace(array('enum(', ')', '\''), '', $res[0]['Type']);
1232
1233 $page->assign('user', $user);
1234 $page->assign('suggest', $this->suggest($user));
1235 $page->assign('listes', $mmlist->get_lists($user->forlifeEmail()));
1236 $page->assign('alias', $user->emailGroupAliases($globals->asso('mail_domain')));
1237 $page->assign('positions', explode(',', $positions));
1238 }
1239
1240 function handler_rss(PlPage $page, PlUser $user)
1241 {
1242 global $globals;
1243 $page->assign('asso', $globals->asso());
1244
1245 $this->load('feed.inc.php');
1246 $feed = new XnetGrpEventFeed();
1247 return $feed->run($page, $user, false);
1248 }
1249
1250 private function upload_image(PlPage $page, PlUpload $upload)
1251 {
1252 if (@!$_FILES['image']['tmp_name'] && !Env::v('image_url')) {
1253 return true;
1254 }
1255 if (!$upload->upload($_FILES['image']) && !$upload->download(Env::v('image_url'))) {
1256 $page->trigError('Impossible de télécharger l\'image');
1257 return false;
1258 } elseif (!$upload->isType('image')) {
1259 $page->trigError('Le fichier n\'est pas une image valide au format JPEG, GIF ou PNG.');
1260 $upload->rm();
1261 return false;
1262 } elseif (!$upload->resizeImage(200, 300, 100, 100, 32284)) {
1263 $page->trigError('Impossible de retraiter l\'image');
1264 return false;
1265 }
1266 return true;
1267 }
1268
1269 function handler_photo_announce($page, $eid = null) {
1270 if ($eid) {
1271 $res = XDB::query('SELECT *
1272 FROM group_announces_photo
1273 WHERE eid = {?}', $eid);
1274 if ($res->numRows()) {
1275 $photo = $res->fetchOneAssoc();
1276 pl_cached_dynamic_content_headers("image/" . $photo['attachmime']);
1277 echo $photo['attach'];
1278 exit;
1279 }
1280 } else {
1281 $upload = new PlUpload(S::user()->login(), 'xnetannounce');
1282 if ($upload->exists() && $upload->isType('image')) {
1283 pl_cached_dynamic_content_headers($upload->contentType());
1284 echo $upload->getContents();
1285 exit;
1286 }
1287 }
1288 global $globals;
1289 pl_cached_dynamic_content_headers("image/png");
1290 echo file_get_contents($globals->spoolroot . '/htdocs/images/logo.png');
1291 exit;
1292 }
1293
1294 function handler_edit_announce($page, $aid = null)
1295 {
1296 global $globals, $platal;
1297 $page->changeTpl('xnetgrp/announce-edit.tpl');
1298 $page->assign('new', is_null($aid));
1299 $art = array();
1300
1301 if (Post::v('valid') == 'Visualiser' || Post::v('valid') == 'Enregistrer'
1302 || Post::v('valid') == 'Supprimer l\'image' || Post::v('valid') == 'Pas d\'image') {
1303 S::assert_xsrf_token();
1304
1305 if (!is_null($aid)) {
1306 $art['id'] = $aid;
1307 }
1308 $art['titre'] = Post::v('titre');
1309 $art['texte'] = Post::v('texte');
1310 $art['contacts'] = Post::v('contacts');
1311 $art['promo_min'] = Post::i('promo_min');
1312 $art['promo_max'] = Post::i('promo_max');
1313 $art['nom'] = S::v('nom');
1314 $art['prenom'] = S::v('prenom');
1315 $art['promo'] = S::v('promo');
1316 $art['hruid'] = S::user()->login();
1317 $art['uid'] = S::user()->id();
1318 $art['expiration'] = Post::v('expiration');
1319 $art['public'] = Post::has('public');
1320 $art['xorg'] = Post::has('xorg');
1321 $art['nl'] = Post::has('nl');
1322 $art['event'] = Post::v('event');
1323 $upload = new PlUpload(S::user()->login(), 'xnetannounce');
1324 $this->upload_image($page, $upload);
1325
1326 $art['contact_html'] = $art['contacts'];
1327 if ($art['event']) {
1328 $art['contact_html'] .= "\n{$globals->baseurl}/{$platal->ns}events/sub/{$art['event']}";
1329 }
1330
1331 if (!$art['public'] &&
1332 (($art['promo_min'] > $art['promo_max'] && $art['promo_max'] != 0) ||
1333 ($art['promo_min'] != 0 && ($art['promo_min'] <= 1900 || $art['promo_min'] >= 2020)) ||
1334 ($art['promo_max'] != 0 && ($art['promo_max'] <= 1900 || $art['promo_max'] >= 2020))))
1335 {
1336 $page->trigError("L'intervalle de promotions est invalide.");
1337 Post::kill('valid');
1338 }
1339
1340 if (!trim($art['titre']) || !trim($art['texte'])) {
1341 $page->trigError("L'article doit avoir un titre et un contenu.");
1342 Post::kill('valid');
1343 }
1344
1345 if (Post::v('valid') == 'Supprimer l\'image') {
1346 $upload->rm();
1347 Post::kill('valid');
1348 }
1349 $art['photo'] = $upload->exists() || Post::i('photo');
1350 if (Post::v('valid') == 'Pas d\'image' && !is_null($aid)) {
1351 XDB::query('DELETE FROM group_announces_photo
1352 WHERE eid = {?}', $aid);
1353 $upload->rm();
1354 Post::kill('valid');
1355 $art['photo'] = false;
1356 }
1357 }
1358
1359 if (Post::v('valid') == 'Enregistrer') {
1360 $promo_min = ($art['public'] ? 0 : $art['promo_min']);
1361 $promo_max = ($art['public'] ? 0 : $art['promo_max']);
1362 $flags = new PlFlagSet();
1363 if ($art['public']) {
1364 $flags->addFlag('public');
1365 }
1366 if ($art['photo']) {
1367 $flags->addFlag('photo');
1368 }
1369 if (is_null($aid)) {
1370 $fulltext = $art['texte'];
1371 if (!empty($art['contact_html'])) {
1372 $fulltext .= "\n\n'''Contacts :'''\\\\\n" . $art['contact_html'];
1373 }
1374 $post = null;
1375 if ($globals->asso('forum')) {
1376 require_once 'banana/forum.inc.php';
1377 $banana = new ForumsBanana(S::user());
1378 $post = $banana->post($globals->asso('forum'), null,
1379 $art['titre'], MiniWiki::wikiToText($fulltext, false, 0, 80));
1380 }
1381 XDB::query('INSERT INTO group_announces (uid, asso_id, create_date, titre, texte, contacts,
1382 expiration, promo_min, promo_max, flags, post_id)
1383 VALUES ({?}, {?}, NOW(), {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
1384 S::i('uid'), $globals->asso('id'), $art['titre'], $art['texte'], $art['contact_html'],
1385 $art['expiration'], $promo_min, $promo_max, $flags, $post);
1386 $aid = XDB::insertId();
1387 if ($art['photo']) {
1388 list($imgx, $imgy, $imgtype) = $upload->imageInfo();
1389 XDB::execute('INSERT INTO group_announces_photo
1390 SET eid = {?}, attachmime = {?}, x = {?}, y = {?}, attach = {?}',
1391 $aid, $imgtype, $imgx, $imgy, $upload->getContents());
1392 }
1393 if ($art['xorg']) {
1394 $article = new EvtReq("[{$globals->asso('nom')}] " . $art['titre'], $fulltext,
1395 $art['promo_min'], $art['promo_max'], $art['expiration'], "", S::user(),
1396 $upload);
1397 $article->submit();
1398 $page->trigWarning("L'affichage sur la page d'accueil de Polytechnique.org est en attente de validation.");
1399 } else if ($upload && $upload->exists()) {
1400 $upload->rm();
1401 }
1402 if ($art['nl']) {
1403 $article = new NLReq(S::user(), $globals->asso('nom') . " : " .$art['titre'],
1404 $art['texte'], $art['contact_html']);
1405 $article->submit();
1406 $page->trigWarning("La parution dans la Lettre Mensuelle est en attente de validation.");
1407 }
1408 } else {
1409 XDB::query('UPDATE group_announces
1410 SET titre = {?}, texte = {?}, contacts = {?}, expiration = {?},
1411 promo_min = {?}, promo_max = {?}, flags = {?}
1412 WHERE id = {?} AND asso_id = {?}',
1413 $art['titre'], $art['texte'], $art['contacts'], $art['expiration'],
1414 $promo_min, $promo_max, $flags,
1415 $art['id'], $globals->asso('id'));
1416 if ($art['photo'] && $upload->exists()) {
1417 list($imgx, $imgy, $imgtype) = $upload->imageInfo();
1418 XDB::execute('INSERT INTO group_announces_photo (eid, attachmime, attach, x, y)
1419 VALUES ({?}, {?}, {?}, {?}, {?})
1420 ON DUPLICATE KEY UPDATE attachmime = VALUES(attachmime), attach = VALUES(attach), x = VALUES(x), y = VALUES(y)',
1421 $aid, $imgtype, $upload->getContents(), $imgx, $imgy);
1422 $upload->rm();
1423 }
1424 }
1425 }
1426 if (Post::v('valid') == 'Enregistrer' || Post::v('valid') == 'Annuler') {
1427 pl_redirect("");
1428 }
1429
1430 if (empty($art) && !is_null($aid)) {
1431 $res = XDB::query("SELECT *, FIND_IN_SET('public', flags) AS public,
1432 FIND_IN_SET('photo', flags) AS photo
1433 FROM group_announces
1434 WHERE asso_id = {?} AND id = {?}",
1435 $globals->asso('id'), $aid);
1436 if ($res->numRows()) {
1437 $art = $res->fetchOneAssoc();
1438 $art['contact_html'] = $art['contacts'];
1439 } else {
1440 $page->kill("Aucun article correspond à l'identifiant indiqué.");
1441 }
1442 }
1443
1444 if (is_null($aid)) {
1445 $events = XDB::iterator("SELECT *
1446 FROM group_events
1447 WHERE asso_id = {?} AND archive = 0",
1448 $globals->asso('id'));
1449 if ($events->total()) {
1450 $page->assign('events', $events);
1451 }
1452 }
1453
1454 $art['contact_html'] = @MiniWiki::WikiToHTML($art['contact_html']);
1455 $page->assign('art', $art);
1456 $page->assign_by_ref('upload', $upload);
1457 }
1458
1459 function handler_admin_announce($page)
1460 {
1461 global $globals;
1462 $page->changeTpl('xnetgrp/announce-admin.tpl');
1463
1464 if (Env::has('del')) {
1465 S::assert_xsrf_token();
1466 XDB::execute('DELETE FROM group_announces
1467 WHERE id = {?} AND asso_id = {?}',
1468 Env::i('del'), $globals->asso('id'));
1469 }
1470 $res = XDB::iterator('SELECT id, titre, expiration, expiration < CURRENT_DATE() AS perime
1471 FROM group_announces
1472 WHERE asso_id = {?}
1473 ORDER BY expiration DESC',
1474 $globals->asso('id'));
1475 $page->assign('articles', $res);
1476 }
1477 }
1478
1479 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1480 ?>