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