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