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