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