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