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