Stores if a user wants her unsubscription to be remembered.
[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),
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),
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, 'user', 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('directory_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 $data = array();
396 foreach ($users as $uid) {
397 $data[] = XDB::format('({?}, {?})', $globals->asso('id'), $uid);
398 }
399 XDB::rawExecute('INSERT INTO group_members (asso_id, uid)
400 VALUES ' . implode(',', $data));
401 }
402
403 if (Env::has('add_nonusers')) {
404 S::assert_xsrf_token();
405
406 $nonusers = array_keys(Env::v('add_nonusers'));
407 foreach ($nonusers as $email) {
408 if ($user = User::getSilent($email) || !isvalid_email($email)) {
409 continue;
410 }
411
412 list($local_part, $domain) = explode('@', strtolower($email));
413 $hruid = User::makeHrid($local_part, $domain, 'ext');
414 if ($user = User::getSilent($hruid)) {
415 continue;
416 }
417
418 $parts = explode('.', $local_part);
419 if (count($parts) == 1) {
420 $lastname = $display_name = $full_name = $directory_name = ucfirst($local_part);
421 $firstname = '';
422 } else {
423 $firstname = ucfirst($parts[0]);
424 $lastname = ucwords(implode(' ', array_slice($parts, 1)));
425 $display_name = $firstname;
426 $full_name = $firstname . ' ' . $lastname;
427 $directory_name = strtoupper($lastname) . ' ' . $firstname;
428 }
429 XDB::execute('INSERT INTO accounts (hruid, display_name, full_name, directory_name, firstname, lastname, email, type, state)
430 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, \'xnet\', \'disabled\')',
431 $hruid, $display_name, $full_name, $directory_name, $firstname, $lastname, $email);
432 $uid = XDB::insertId();
433 XDB::execute('INSERT INTO group_members (asso_id, uid)
434 VALUES ({?}, {?})',
435 $globals->asso('id'), $uid);
436 }
437 }
438
439 if (Env::has('add_users') || Env::has('add_nonusers')) {
440 $page->trigSuccess('Ajouts réalisés avec succès.');
441 }
442
443 $user = S::user();
444 $client = new MMList($user, $globals->asso('mail_domain'));
445 $lists = $client->get_lists();
446 $members = array();
447 foreach ($lists as $list) {
448 $details = $client->get_members($list['list']);
449 $members = array_merge($members, list_extract_members($details[1]));
450 }
451 $members = array_unique($members);
452 $uids = array();
453 $users = array();
454 $nonusers = array();
455 foreach ($members as $email) {
456 if ($user = User::getSilent($email)) {
457 $uids[] = $user->id();
458 } else {
459 $nonusers[] = $email;
460 }
461 }
462
463 $aliases = iterate_list_alias($globals->asso('mail_domain'));
464 foreach ($aliases as $alias) {
465 list($local_part, $domain) = explode('@', $alias);
466 $aliases_members = list_alias_members($local_part, $domain);
467 $users = array_merge($users, $aliases_members['users']);
468 $nonusers = array_merge($nonusers, $aliases_members['nonusers']);
469 }
470 foreach ($users as $user) {
471 $uids[] = $user->id();
472 }
473 $nonusers = array_unique($nonusers);
474 $uids = array_unique($uids);
475 if (count($uids)) {
476 $uids = XDB::fetchColumn('SELECT a.uid
477 FROM accounts AS a
478 WHERE a.uid IN {?} AND NOT EXISTS (SELECT *
479 FROM group_members AS g
480 WHERE a.uid = g.uid AND g.asso_id = {?})',
481 $uids, $globals->asso('id'));
482
483 $users = User::getBulkUsersWithUIDs($uids);
484 usort($users, 'User::compareDirectoryName');
485 } else {
486 $users = array();
487 }
488 sort($nonusers);
489
490 $page->assign('users', $users);
491 $page->assign('nonusers', $nonusers);
492 }
493
494 function handler_non_active($page)
495 {
496 global $globals;
497 $page->changeTpl('xnetgrp/non_active.tpl');
498
499 $uids = XDB::fetchColumn('SELECT g.uid
500 FROM group_members AS g
501 INNER JOIN accounts AS a ON (a.uid = g.uid)
502 LEFT JOIN register_pending_xnet AS p ON (p.uid = g.uid)
503 WHERE a.uid = g.uid AND g.asso_id = {?} AND a.type = \'xnet\' AND a.state = \'disabled\' AND p.uid IS NULL',
504 $globals->asso('id'));
505 foreach ($uids as $key => $uid) {
506 if (AccountReq::isPending($uid) || BulkAccountsReq::isPending($uid)) {
507 unset($uids[$key]);
508 }
509 }
510
511 if (Post::has('enable_accounts')) {
512 S::assert_xsrf_token();
513
514 $uids_to_enable = array_intersect(array_keys(Post::v('enable_accounts')), $uids);
515
516 $user = S::user();
517 $group = Platal::globals()->asso('nom');
518 $request = new BulkAccountsReq($user, $uids_to_enable, $group);
519 $request->submit();
520 $page->trigSuccess('Un email va bientôt être envoyé aux personnes sélectionnées pour l\'activation de leur compte.');
521
522 foreach ($uids as $key => $uid) {
523 if (in_array($uid, $uids_to_enable)) {
524 unset($uids[$key]);
525 }
526 }
527 }
528
529 $users = User::getBulkUsersWithUIDs($uids);
530 $page->assign('users', $users);
531 }
532
533 private function removeSubscriptionRequest($uid)
534 {
535 global $globals;
536 XDB::execute("DELETE FROM group_member_sub_requests
537 WHERE asso_id = {?} AND uid = {?}",
538 $globals->asso('id'), $uid);
539 }
540
541 private function validSubscription(User $user)
542 {
543 global $globals;
544 $this->removeSubscriptionRequest($user->id());
545 Group::subscribe($globals->asso('id'), $user->id());
546
547 if (XDB::affectedRows() == 1) {
548 $mailer = new PlMailer();
549 $mailer->addTo($user->forlifeEmail());
550 $mailer->setFrom('"' . S::user()->fullName() . '" <' . S::user()->forlifeEmail() . '>');
551 $mailer->setSubject('[' . $globals->asso('nom') . '] Demande d\'inscription');
552 $message = ($user->isFemale() ? 'Chère' : 'Cher') . " Camarade,\n"
553 . "\n"
554 . " Suite à ta demande d'adhésion à " . $globals->asso('nom')
555 . ", j'ai le plaisir de t'annoncer que ton inscription a été validée !\n"
556 . (is_null($globals->asso('welcome_msg')) ? '' : "\n" . $globals->asso('welcome_msg') . "\n")
557 . "\n"
558 . "Bien cordialement,\n"
559 . "-- \n"
560 . S::user()->fullName() . '.';
561 $mailer->setTxtBody(wordwrap($message, 72));
562 $mailer->send();
563 }
564 }
565
566 function handler_subscribe($page, $u = null)
567 {
568 global $globals;
569 $page->changeTpl('xnetgrp/inscrire.tpl');
570
571 if (!$globals->asso('inscriptible'))
572 $page->kill("Il n'est pas possible de s'inscire en ligne à ce "
573 ."groupe. Essaie de joindre le contact indiqué "
574 ."sur la page de présentation.");
575
576 if (!is_null($u) && may_update()) {
577 $user = User::get($u);
578 if (!$user) {
579 return PL_NOT_FOUND;
580 } else {
581 $page->assign('user', $user);
582 }
583
584 // Retrieves the subscription status, and the reason.
585 $res = XDB::query("SELECT reason
586 FROM group_member_sub_requests
587 WHERE asso_id = {?} AND uid = {?}",
588 $globals->asso('id'), $user->id());
589 $reason = ($res->numRows() ? $res->fetchOneCell() : null);
590
591 $res = XDB::query("SELECT COUNT(*)
592 FROM group_members
593 WHERE asso_id = {?} AND uid = {?}",
594 $globals->asso('id'), $user->id());
595 $already_member = ($res->fetchOneCell() > 0);
596
597 // Handles the membership request.
598 if ($already_member) {
599 $this->removeSubscriptionRequest($user->id());
600 $page->kill($user->fullName() . ' est déjà membre du groupe&nbsp;!');
601 } elseif (Env::has('accept')) {
602 S::assert_xsrf_token();
603
604 $this->validSubscription($user);
605 pl_redirect("member/" . $user->login());
606 } elseif (Env::has('refuse')) {
607 S::assert_xsrf_token();
608
609 $this->removeSubscriptionRequest($user->id());
610 $mailer = new PlMailer();
611 $mailer->addTo($user->forlifeEmail());
612 $mailer->setFrom('"' . S::user()->fullName() . '" <' . S::user()->forlifeEmail() . '>');
613 $mailer->setSubject('['.$globals->asso('nom').'] Demande d\'inscription annulée');
614 $mailer->setTxtBody(Env::v('motif'));
615 $mailer->send();
616 $page->killSuccess("La demande de {$user->fullName()} a bien été refusée.");
617 } else {
618 $page->assign('show_form', true);
619 $page->assign('reason', $reason);
620 }
621 return;
622 }
623
624 if (is_member()) {
625 $page->kill("Tu es déjà membre&nbsp;!");
626 return;
627 }
628
629 $res = XDB::query("SELECT uid
630 FROM group_member_sub_requests
631 WHERE uid = {?} AND asso_id = {?}",
632 S::i('uid'), $globals->asso('id'));
633 if ($res->numRows() != 0) {
634 $page->kill("Tu as déjà demandé ton inscription à ce groupe. Cette demande est actuellement en attente de validation.");
635 return;
636 }
637
638 if (Post::has('inscrire')) {
639 S::assert_xsrf_token();
640
641 XDB::execute("INSERT INTO group_member_sub_requests (asso_id, uid, ts, reason)
642 VALUES ({?}, {?}, NOW(), {?})",
643 $globals->asso('id'), S::i('uid'), Post::v('message'));
644 $uf = New UserFilter(New UFC_Group($globals->asso('id'), true));
645 $admins = $uf->iterUsers();
646 $admin = $admins->next();
647 $to = $admin->bestEmail();
648 while ($admin = $admins->next()) {
649 $to .= ', ' . $admin->bestEmail();
650 }
651
652 $append = "\n"
653 . "-- \n"
654 . "Ce message a été envoyé suite à la demande d'inscription de\n"
655 . S::user()->fullName() . ' (X' . S::v('promo') . ")\n"
656 . "Via le site www.polytechnique.net. Tu peux choisir de valider ou\n"
657 . "de refuser sa demande d'inscription depuis la page :\n"
658 . "http://www.polytechnique.net/" . $globals->asso("diminutif") . "/subscribe/" . S::user()->login() . "\n"
659 . "\n"
660 . "En cas de problème, contacter l'équipe de Polytechnique.org\n"
661 . "à l'adresse : support@polytechnique.org\n";
662
663 if (!$to) {
664 $to = ($globals->asso('mail') != '') ? $globals->asso('mail') . ', ' : '';
665 $to .= 'support@polytechnique.org';
666 $append = "\n-- \nLe groupe ".$globals->asso("nom")
667 ." n'a pas d'administrateur, l'équipe de"
668 ." Polytechnique.org a été prévenue et va rapidement"
669 ." résoudre ce problème.\n";
670 }
671
672 $mailer = new PlMailer();
673 $mailer->addTo($to);
674 $mailer->setFrom('"' . S::user()->fullName() . '" <' . S::user()->forlifeEmail() . '>');
675 $mailer->setSubject('['.$globals->asso('nom').'] Demande d\'inscription');
676 $mailer->setTxtBody(Post::v('message').$append);
677 $mailer->send();
678 }
679 }
680
681 function handler_subscribe_valid($page)
682 {
683 global $globals;
684
685 if (Post::has('valid')) {
686 S::assert_xsrf_token();
687 $subs = Post::v('subs');
688 if (is_array($subs)) {
689 $users = array();
690 foreach ($subs as $hruid => $val) {
691 if ($val == '1') {
692 $user = User::get($hruid);
693 if ($user) {
694 $this->validSubscription($user);
695 }
696 }
697 }
698 }
699 }
700
701 $it = XDB::iterator('SELECT s.uid, a.hruid, s.ts AS date
702 FROM group_member_sub_requests AS s
703 INNER JOIN accounts AS a ON(s.uid = a.uid)
704 WHERE s.asso_id = {?}
705 ORDER BY s.ts', $globals->asso('id'));
706 $page->changeTpl('xnetgrp/subscribe-valid.tpl');
707 $page->assign('valid', $it);
708 }
709
710 function handler_change_rights($page)
711 {
712 if (Env::has('right') && (may_update() || S::suid())) {
713 switch (Env::v('right')) {
714 case 'admin':
715 Platal::session()->stopSUID();
716 break;
717 case 'anim':
718 Platal::session()->doSelfSuid();
719 may_update(true);
720 is_member(true);
721 break;
722 case 'member':
723 Platal::session()->doSelfSuid();
724 may_update(false, true);
725 is_member(true);
726 break;
727 case 'logged':
728 Platal::session()->doSelfSuid();
729 may_update(false, true);
730 is_member(false, true);
731 break;
732 }
733 }
734 http_redirect($_SERVER['HTTP_REFERER']);
735 }
736
737 function handler_admin_annuaire($page)
738 {
739 global $globals;
740
741 $this->load('mail.inc.php');
742 $page->changeTpl('xnetgrp/annuaire-admin.tpl');
743 $user = S::user();
744 $mmlist = new MMList($user, $globals->asso('mail_domain'));
745 $lists = $mmlist->get_lists();
746 if (!$lists) $lists = array();
747 $listes = array_map(create_function('$arr', 'return $arr["list"];'), $lists);
748
749 $subscribers = array();
750
751 foreach ($listes as $list) {
752 list(,$members) = $mmlist->get_members($list);
753 $mails = array_map(create_function('$arr', 'return $arr[1];'), $members);
754 $subscribers = array_unique(array_merge($subscribers, $mails));
755 }
756
757 $not_in_group_x = array();
758 $not_in_group_ext = array();
759
760 foreach ($subscribers as $mail) {
761 $uf = new UserFilter(new PFC_And(new UFC_Group($globals->asso('id')),
762 new UFC_Email($mail)));
763 if ($uf->getTotalCount() == 0) {
764 if (User::isForeignEmailAddress($mail)) {
765 $not_in_group_ext[] = $mail;
766 } else {
767 $not_in_group_x[] = $mail;
768 }
769 }
770 }
771
772 $page->assign('not_in_group_ext', $not_in_group_ext);
773 $page->assign('not_in_group_x', $not_in_group_x);
774 $page->assign('lists', $lists);
775 }
776
777 function handler_admin_member_new($page, $email = null)
778 {
779 global $globals;
780
781 $page->changeTpl('xnetgrp/membres-add.tpl');
782
783 if (is_null($email)) {
784 return;
785 }
786
787 S::assert_xsrf_token();
788 $suggest_account_activation = false;
789
790 // FS#703 : $_GET is urldecoded twice, hence
791 // + (the data) => %2B (in the url) => + (first decoding) => ' ' (second decoding)
792 // Since there can be no spaces in emails, we can fix this with :
793 $email = str_replace(' ', '+', $email);
794
795 // Finds or creates account: first cases are for users with an account.
796 if (!User::isForeignEmailAddress($email)) {
797 // Standard account
798 $user = User::getSilent($email);
799 } else if (!isvalid_email($email)) {
800 // email might not be a regular email but an alias or a hruid
801 $user = User::getSilent($email);
802 if (!$user) {
803 // need a valid email address
804 $page->trigError('«&nbsp;<strong>' . $email . '</strong>&nbsp;» n\'est pas une adresse email valide.');
805 return;
806 }
807 } else if (Env::v('x') && Env::i('userid')) {
808 $user = User::getSilentWithUID(Env::i('userid'));
809 if (!$user) {
810 $page->trigError('Utilisateur invalide.');
811 return;
812 }
813
814 // User has an account but is not yet registered.
815 if ($user->state == 'pending') {
816 // Add email in account table.
817 XDB::query('UPDATE accounts
818 SET email = {?}
819 WHERE uid = {?} AND email IS NULL',
820 Post::t('email'), $user->id());
821 // Add email for marketing if required.
822 if (Env::v('market')) {
823 $market = Marketing::get($user->uid, $email);
824 if (!$market) {
825 $market = new Marketing($user->uid, $email, 'group', $globals->asso('nom'),
826 Env::v('market_from'), S::v('uid'));
827 $market->add();
828 }
829 }
830 }
831 } else {
832 // User is of type xnet. There are 3 possible cases:
833 // * the email is not known yet: we create a new account and
834 // propose to send an email to the user so he can activate
835 // his account,
836 // * the email is known but the user was not contacted in order to
837 // activate yet: we propose to send an email to the user so he
838 // can activate his account,
839 // * the email is known and the user was already contacted or has
840 // an active account: nothing to be done.
841 list($mbox, $domain) = explode('@', strtolower($email));
842 $hruid = User::makeHrid($mbox, $domain, 'ext');
843 // User might already have an account (in another group for example).
844 $user = User::getSilent($hruid);
845
846 // If the user has no account yet, creates new account: build names from email address.
847 if (empty($user)) {
848 $parts = explode('.', $mbox);
849 if (count($parts) == 1) {
850 $lastname = $display_name = $full_name = $directory_name = ucfirst($mbox);
851 $firstname = '';
852 } else {
853 $firstname = ucfirst($parts[0]);
854 $lastname = ucwords(implode(' ', array_slice($parts, 1)));
855 $display_name = $firstname;
856 $full_name = "$firstname $lastname";
857 $directory_name = strtoupper($lastname) . " " . $firstname;
858 }
859 XDB::execute('INSERT INTO accounts (hruid, display_name, full_name, directory_name, firstname, lastname, email, type, state)
860 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, \'xnet\', \'disabled\')',
861 $hruid, $display_name, $full_name, $directory_name, $firstname, $lastname, $email);
862 $user = User::getSilent($hruid);
863 }
864
865 $suggest_account_activation = $this->suggest($user);
866 }
867
868 if ($user) {
869 XDB::execute('INSERT IGNORE INTO group_members (uid, asso_id)
870 VALUES ({?}, {?})',
871 $user->id(), $globals->asso('id'));
872 $this->removeSubscriptionRequest($user->id());
873 if ($suggest_account_activation) {
874 pl_redirect('member/suggest/' . $user->login() . '/' . $email . '/' . $globals->asso('nom'));
875 } else {
876 pl_redirect('member/' . $user->login());
877 }
878 }
879 }
880
881 // Check if the user has a pending or active account, and thus if we should her account's activation.
882 private function suggest(PlUser $user)
883 {
884 $active = XDB::fetchOneCell('SELECT state = \'active\'
885 FROM accounts
886 WHERE uid = {?}',
887 $user->id());
888 $pending = XDB::fetchOneCell('SELECT uid
889 FROM register_pending_xnet
890 WHERE uid = {?}',
891 $user->id());
892 $requested = AccountReq::isPending($user->id()) || BulkAccountsReq::isPending($user->id());
893
894 if ($active || $pending || $requested) {
895 return false;
896 }
897 return true;
898 }
899
900 function handler_admin_member_suggest($page, $hruid, $email)
901 {
902 $page->changeTpl('xnetgrp/membres-suggest.tpl');
903
904 // FS#703 : $_GET is urldecoded twice, hence
905 // + (the data) => %2B (in the url) => + (first decoding) => ' ' (second decoding)
906 // Since there can be no spaces in emails, we can fix this with :
907 $email = str_replace(' ', '+', $email);
908
909 if (Post::has('suggest')) {
910 if (Post::t('suggest') == 'yes') {
911 $user = S::user();
912 $group = Platal::globals()->asso('nom');
913 $request = new AccountReq($user, $hruid, $email, $group);
914 $request->submit();
915 $page->trigSuccessRedirect('Un email va bien être envoyé à ' . $email . ' pour l\'activation de son compte.',
916 $group . '/member/' . $hruid);
917 } else {
918 pl_redirect('member/' . $hruid);
919 }
920 }
921 $page->assign('email', $email);
922 $page->assign('hruid', $hruid);
923 }
924
925 function handler_admin_member_new_ajax($page)
926 {
927 pl_content_headers("text/html");
928 $page->changeTpl('xnetgrp/membres-new-search.tpl', NO_SKIN);
929 $users = array();
930 if (Env::has('login')) {
931 $user = User::getSilent(Env::t('login'));
932 if ($user && $user->state != 'pending') {
933 $users = array($user);
934 }
935 }
936 if (empty($users)) {
937 list($lastname, $firstname) = str_replace(array('-', ' ', "'"), '%', array(Env::t('nom'), Env::t('prenom')));
938 $cond = new PFC_And(new PFC_Not(new UFC_Registered()));
939 if (!empty($lastname)) {
940 $cond->addChild(new UFC_Name(Profile::LASTNAME, $lastname, UFC_Name::CONTAINS));
941 }
942 if (!empty($firstname)) {
943 $cond->addChild(new UFC_Name(Profile::FIRSTNAME, $firstname, UFC_Name::CONTAINS));
944 }
945 if (Env::t('promo')) {
946 $cond->addChild(new UFC_Promo('=', UserFilter::DISPLAY, Env::t('promo')));
947 }
948 $uf = new UserFilter($cond);
949 $users = $uf->getUsers(new PlLimit(30));
950 if ($uf->getTotalCount() > 30) {
951 $page->assign('too_many', true);
952 $users = array();
953 }
954 }
955 $page->assign('users', $users);
956 }
957
958 function unsubscribe(PlUser $user, $remember = false)
959 {
960 global $globals;
961 Group::unsubscribe($globals->asso('id'), $user->id(), $remember);
962
963 if ($globals->asso('notif_unsub')) {
964 $mailer = new PlMailer('xnetgrp/unsubscription-notif.mail.tpl');
965 $admins = $globals->asso()->iterAdmins();
966 while ($admin = $admins->next()) {
967 $mailer->addTo($admin);
968 }
969 $mailer->assign('group', $globals->asso('nom'));
970 $mailer->assign('user', $user);
971 $mailer->assign('selfdone', $user->id() == S::i('uid'));
972 $mailer->send();
973 }
974
975 $domain = $globals->asso('mail_domain');
976 if (!$domain) {
977 return true;
978 }
979
980 $mmlist = new MMList(S::user(), $domain);
981 $listes = $mmlist->get_lists($user->forlifeEmail());
982
983 $may_update = may_update();
984 $warning = false;
985 if (is_array($listes)) {
986 foreach ($listes as $liste) {
987 if ($liste['sub'] == 2) {
988 if ($may_update) {
989 $mmlist->mass_unsubscribe($liste['list'], Array($user->forlifeEmail()));
990 } else {
991 $mmlist->unsubscribe($liste['list']);
992 }
993 } elseif ($liste['sub']) {
994 Platal::page()->trigWarning($user->fullName() . " a une"
995 ." demande d'inscription en cours sur la"
996 ." liste {$liste['list']}@ !");
997 $warning = true;
998 }
999 }
1000 }
1001
1002 XDB::execute('DELETE v
1003 FROM email_virtual AS v
1004 INNER JOIN email_virtual_domains AS d ON (v.domain = d.id)
1005 WHERE v.redirect = {?} AND d.name = {?}',
1006 $user->forlifeEmail(), $domain);
1007 return !$warning;
1008 }
1009
1010 function handler_unsubscribe($page)
1011 {
1012 $page->changeTpl('xnetgrp/membres-del.tpl');
1013 $user = S::user();
1014 if (empty($user)) {
1015 return PL_NOT_FOUND;
1016 }
1017 $page->assign('self', true);
1018 $page->assign('user', $user);
1019
1020 if (!Post::has('confirm')) {
1021 return;
1022 } else {
1023 S::assert_xsrf_token();
1024 }
1025
1026 $hasSingleGroup = ($user->groupCount() == 1);
1027
1028 if ($this->unsubscribe($user, Post::b('remember'))) {
1029 $page->trigSuccess('Tu as été désinscrit du groupe avec succès.');
1030 } else {
1031 $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.');
1032 }
1033
1034 // If user is of type xnet account and this was her last group, disable the account.
1035 if ($user->type == 'xnet' && $hasSingleGroup) {
1036 $user->clear(true);
1037 }
1038 $page->assign('is_member', is_member(true));
1039 }
1040
1041 function handler_admin_member_del($page, $user = null)
1042 {
1043 $page->changeTpl('xnetgrp/membres-del.tpl');
1044 $user = User::getSilent($user);
1045 if (empty($user)) {
1046 return PL_NOT_FOUND;
1047 }
1048
1049 global $globals;
1050
1051 if (!$user->inGroup($globals->asso('id'))) {
1052 pl_redirect('annuaire');
1053 }
1054
1055 $page->assign('self', false);
1056 $page->assign('user', $user);
1057
1058 if (!Post::has('confirm')) {
1059 return;
1060 } else {
1061 S::assert_xsrf_token();
1062 }
1063
1064 $hasSingleGroup = ($user->groupCount() == 1);
1065
1066 if ($this->unsubscribe($user)) {
1067 $page->trigSuccess("{$user->fullName()} a été désinscrit du groupe&nbsp;!");
1068 } else {
1069 $page->trigWarning("{$user->fullName()} a été désinscrit du groupe, mais des erreurs subsistent&nbsp;!");
1070 }
1071
1072 // If user is of type xnet account and this was her last group, disable the account.
1073 if ($user->type == 'xnet' && $hasSingleGroup) {
1074 $user->clear(true);
1075 }
1076 }
1077
1078 private function changeLogin(PlPage $page, PlUser $user, $login)
1079 {
1080 // Search the user's uid.
1081 $xuser = User::getSilent($login);
1082 if (!$xuser) {
1083 $accounts = User::getPendingAccounts($login);
1084 if (!$accounts) {
1085 $page->trigError("L'identifiant $login ne correspond à aucun X.");
1086 return false;
1087 } else if (count($accounts) > 1) {
1088 $page->trigError("L'identifiant $login correspond à plusieurs camarades.");
1089 return false;
1090 }
1091 $xuser = User::getSilent($accounts[0]['uid']);
1092 }
1093
1094 if (!$xuser) {
1095 return false;
1096 }
1097
1098 if ($user->mergeIn($xuser)) {
1099 return $xuser->login();
1100 }
1101 return $user->login();
1102 }
1103
1104 function handler_admin_member($page, $user)
1105 {
1106 global $globals;
1107
1108 $user = User::getSilent($user);
1109 if (empty($user)) {
1110 return PL_NOT_FOUND;
1111 }
1112
1113 if (!$user->inGroup($globals->asso('id'))) {
1114 pl_redirect('annuaire');
1115 }
1116
1117 $page->changeTpl('xnetgrp/membres-edit.tpl');
1118
1119 $mmlist = new MMList(S::user(), $globals->asso('mail_domain'));
1120
1121 if (Post::has('change')) {
1122 require_once 'emails.inc.php';
1123 S::assert_xsrf_token();
1124
1125 // Convert user status to X
1126 if (!Post::blank('login_X')) {
1127 $forlife = $this->changeLogin($page, $user, Post::t('login_X'));
1128 if ($forlife) {
1129 pl_redirect('member/' . $forlife);
1130 }
1131 }
1132
1133 // Update user info
1134 $email_changed = (!$user->profile() && strtolower($user->forlifeEmail()) != strtolower(Post::v('email')));
1135 $from_email = $user->forlifeEmail();
1136 if ($user->type == 'virtual' || ($user->type == 'xnet' && !$user->perms)) {
1137 $lastname = Post::s('lastname');
1138 if (Post::s('type') != 'virtual') {
1139 $firstname = Post::s('firstname');
1140 $full_name = $firstname . ' ' . $lastname;
1141 $directory_name = mb_strtoupper($lastname) . ' ' . $firstname;
1142 } else {
1143 $firstname = '';
1144 $full_name = $lastname;
1145 $directory_name = mb_strtoupper($lastname);
1146 }
1147 XDB::query('UPDATE accounts
1148 SET full_name = {?}, directory_name = {?}, display_name = {?},
1149 firstname = {?}, lastname = {?}, sex = {?}, email = {?}, type = {?}
1150 WHERE uid = {?}',
1151 $full_name, $directory_name, Post::t('display_name'), $firstname, $lastname,
1152 (Post::t('sex') == 'male') ? 'male' : 'female', Post::t('email'),
1153 (Post::t('type') == 'xnet') ? 'xnet' : 'virtual', $user->id());
1154 } else if (!$user->perms) {
1155 XDB::query('UPDATE accounts
1156 SET email = {?}
1157 WHERE uid = {?}',
1158 Post::t('email'), $user->id());
1159 }
1160 if (require_email_update($user, Post::t('email'))) {
1161 $listClient = new MMList(S::user());
1162 $listClient->change_user_email($user->forlifeEmail(), Post::t('email'));
1163 update_alias_user($user->forlifeEmail(), Post::t('email'));
1164 }
1165 if (XDB::affectedRows()) {
1166 $page->trigSuccess('Données de l\'utilisateur mises à jour.');
1167 }
1168
1169 if (($user->type == 'xnet' && !$user->perms) && Post::b('suggest')) {
1170 $request = new AccountReq(S::user(), $user->hruid, Post::t('email'), $globals->asso('nom'));
1171 $request->submit();
1172 $page->trigSuccess('Le compte va bientôt être activé.');
1173 }
1174
1175 // Update group params for user
1176 $perms = Post::v('group_perms');
1177 $comm = Post::t('comm');
1178 $position = (Post::t('group_position') == '') ? null : Post::v('group_position');
1179 if ($user->group_perms != $perms || $user->group_comm != $comm || $user->group_position != $position) {
1180 XDB::query('UPDATE group_members
1181 SET perms = {?}, comm = {?}, position = {?}
1182 WHERE uid = {?} AND asso_id = {?}',
1183 ($perms == 'admin') ? 'admin' : 'membre', $comm, $position,
1184 $user->id(), $globals->asso('id'));
1185 if (XDB::affectedRows()) {
1186 if ($perms != $user->group_perms) {
1187 $page->trigSuccess('Permissions modifiées&nbsp;!');
1188 }
1189 if ($comm != $user->group_comm) {
1190 $page->trigSuccess('Commentaire mis à jour.');
1191 }
1192 if ($position != $user->group_position) {
1193 $page->trigSuccess('Poste mis à jour.');
1194 }
1195 }
1196 }
1197
1198 // Gets user info again as they might have change
1199 $user = User::getSilent($user->id());
1200
1201 // Update ML subscriptions
1202 foreach (Env::v('ml1', array()) as $ml => $state) {
1203 $ask = empty($_REQUEST['ml2'][$ml]) ? 0 : 2;
1204 if ($ask == $state) {
1205 if ($state && $email_changed) {
1206 $mmlist->replace_email($ml, $from_email, $user->forlifeEmail());
1207 $page->trigSuccess("L'abonnement de {$user->fullName()} à $ml@ a été mis à jour.");
1208 }
1209 continue;
1210 }
1211 if ($state == '1') {
1212 $page->trigWarning("{$user->fullName()} a "
1213 ."actuellement une demande d'inscription en "
1214 ."cours sur <strong>$ml@</strong> !!!");
1215 } elseif ($ask) {
1216 $mmlist->mass_subscribe($ml, Array($user->forlifeEmail()));
1217 $page->trigSuccess("{$user->fullName()} a été abonné à $ml@.");
1218 } else {
1219 if ($email_changed) {
1220 $mmlist->mass_unsubscribe($ml, Array($from_email));
1221 } else {
1222 $mmlist->mass_unsubscribe($ml, Array($user->forlifeEmail()));
1223 }
1224 $page->trigSuccess("{$user->fullName()} a été désabonné de $ml@.");
1225 }
1226 }
1227
1228 // Change subscriptioin to aliases
1229 foreach (Env::v('ml3', array()) as $ml => $state) {
1230 require_once 'emails.inc.php';
1231 $ask = !empty($_REQUEST['ml4'][$ml]);
1232 list($local_part, ) = explode('@', $ml);
1233 if($state == $ask) {
1234 if ($state && $email_changed) {
1235 update_list_alias($user->id(), $from_email, $local_part, $globals->asso('mail_domain'));
1236 $page->trigSuccess("L'abonnement de {$user->fullName()} à $ml a été mis à jour.");
1237 }
1238 } else if($ask) {
1239 add_to_list_alias($user->id(), $local_part, $globals->asso('mail_domain'));
1240 $page->trigSuccess("{$user->fullName()} a été abonné à $ml.");
1241 } else {
1242 delete_from_list_alias($user->id(), $local_part, $globals->asso('mail_domain'));
1243 $page->trigSuccess("{$user->fullName()} a été désabonné de $ml.");
1244 }
1245 }
1246
1247 if ($globals->asso('has_nl')) {
1248 // Updates group's newsletter subscription.
1249 if (Post::i('newsletter') == 1) {
1250 XDB::execute('INSERT IGNORE INTO newsletter_ins (uid, nlid)
1251 SELECT {?}, id
1252 FROM newsletters
1253 WHERE group_id = {?}',
1254 $user->id(), $globals->asso('id'));
1255 } else {
1256 XDB::execute('DELETE ni
1257 FROM newsletter_ins AS ni
1258 INNER JOIN newsletters AS n ON (n.id = ni.nlid)
1259 WHERE ni.uid = {?} AND n.group_id = {?}',
1260 $user->id(), $globals->asso('id'));
1261 }
1262 }
1263 }
1264
1265 $res = XDB::rawFetchAllAssoc('SHOW COLUMNS FROM group_members LIKE \'position\'');
1266 $positions = str_replace(array('enum(', ')', '\''), '', $res[0]['Type']);
1267 $nl_registered = XDB::fetchOneCell('SELECT COUNT(ni.uid)
1268 FROM newsletter_ins AS ni
1269 INNER JOIN newsletters AS n ON (n.id = ni.nlid)
1270 WHERE ni.uid = {?} AND n.group_id = {?}',
1271 $user->id(), $globals->asso('id'));
1272
1273 $page->assign('user', $user);
1274 $page->assign('suggest', $this->suggest($user));
1275 $page->assign('listes', $mmlist->get_lists($user->forlifeEmail()));
1276 $page->assign('alias', $user->emailGroupAliases($globals->asso('mail_domain')));
1277 $page->assign('positions', explode(',', $positions));
1278 $page->assign('nl_registered', $nl_registered);
1279 }
1280
1281 function handler_rss(PlPage $page, PlUser $user)
1282 {
1283 global $globals;
1284 $page->assign('asso', $globals->asso());
1285
1286 $this->load('feed.inc.php');
1287 $feed = new XnetGrpEventFeed();
1288 return $feed->run($page, $user, false);
1289 }
1290
1291 private function upload_image(PlPage $page, PlUpload $upload)
1292 {
1293 if (@!$_FILES['image']['tmp_name'] && !Env::v('image_url')) {
1294 return true;
1295 }
1296 if (!$upload->upload($_FILES['image']) && !$upload->download(Env::v('image_url'))) {
1297 $page->trigError('Impossible de télécharger l\'image');
1298 return false;
1299 } elseif (!$upload->isType('image')) {
1300 $page->trigError('Le fichier n\'est pas une image valide au format JPEG, GIF ou PNG.');
1301 $upload->rm();
1302 return false;
1303 } elseif (!$upload->resizeImage(80, 100, 100, 100, 32284)) {
1304 $page->trigError('Impossible de retraiter l\'image');
1305 return false;
1306 }
1307 return true;
1308 }
1309
1310 function handler_photo_announce($page, $eid = null) {
1311 if ($eid) {
1312 $res = XDB::query('SELECT *
1313 FROM group_announces_photo
1314 WHERE eid = {?}', $eid);
1315 if ($res->numRows()) {
1316 $photo = $res->fetchOneAssoc();
1317 pl_cached_dynamic_content_headers("image/" . $photo['attachmime']);
1318 echo $photo['attach'];
1319 exit;
1320 }
1321 } else {
1322 $upload = new PlUpload(S::user()->login(), 'xnetannounce');
1323 if ($upload->exists() && $upload->isType('image')) {
1324 pl_cached_dynamic_content_headers($upload->contentType());
1325 echo $upload->getContents();
1326 exit;
1327 }
1328 }
1329 global $globals;
1330 pl_cached_dynamic_content_headers("image/png");
1331 echo file_get_contents($globals->spoolroot . '/htdocs/images/logo.png');
1332 exit;
1333 }
1334
1335 function handler_edit_announce($page, $aid = null)
1336 {
1337 global $globals, $platal;
1338 $page->changeTpl('xnetgrp/announce-edit.tpl');
1339 $page->assign('new', is_null($aid));
1340 $art = array();
1341
1342 if (Post::v('valid') == 'Visualiser' || Post::v('valid') == 'Enregistrer'
1343 || Post::v('valid') == 'Supprimer l\'image' || Post::v('valid') == 'Pas d\'image') {
1344 S::assert_xsrf_token();
1345
1346 if (!is_null($aid)) {
1347 $art['id'] = $aid;
1348 }
1349 $art['titre'] = Post::v('titre');
1350 $art['texte'] = Post::v('texte');
1351 $art['contacts'] = Post::v('contacts');
1352 $art['promo_min'] = Post::i('promo_min');
1353 $art['promo_max'] = Post::i('promo_max');
1354 $art['nom'] = S::v('nom');
1355 $art['prenom'] = S::v('prenom');
1356 $art['promo'] = S::v('promo');
1357 $art['hruid'] = S::user()->login();
1358 $art['uid'] = S::user()->id();
1359 $art['expiration'] = Post::v('expiration');
1360 $art['public'] = Post::has('public');
1361 $art['xorg'] = Post::has('xorg');
1362 $art['nl'] = Post::has('nl');
1363 $art['event'] = Post::v('event');
1364 $upload = new PlUpload(S::user()->login(), 'xnetannounce');
1365 $this->upload_image($page, $upload);
1366
1367 $art['contact_html'] = $art['contacts'];
1368 if ($art['event']) {
1369 $art['contact_html'] .= "\n{$globals->baseurl}/{$platal->ns}events/sub/{$art['event']}";
1370 }
1371
1372 if (!$art['public'] &&
1373 (($art['promo_min'] > $art['promo_max'] && $art['promo_max'] != 0) ||
1374 ($art['promo_min'] != 0 && ($art['promo_min'] <= 1900 || $art['promo_min'] >= 2020)) ||
1375 ($art['promo_max'] != 0 && ($art['promo_max'] <= 1900 || $art['promo_max'] >= 2020))))
1376 {
1377 $page->trigError("L'intervalle de promotions est invalide.");
1378 Post::kill('valid');
1379 }
1380
1381 if (!trim($art['titre']) || !trim($art['texte'])) {
1382 $page->trigError("L'article doit avoir un titre et un contenu.");
1383 Post::kill('valid');
1384 }
1385
1386 if (Post::v('valid') == 'Supprimer l\'image') {
1387 $upload->rm();
1388 Post::kill('valid');
1389 }
1390 $art['photo'] = $upload->exists() || Post::i('photo');
1391 if (Post::v('valid') == 'Pas d\'image' && !is_null($aid)) {
1392 XDB::query('DELETE FROM group_announces_photo
1393 WHERE eid = {?}', $aid);
1394 $upload->rm();
1395 Post::kill('valid');
1396 $art['photo'] = false;
1397 }
1398 }
1399
1400 if (Post::v('valid') == 'Enregistrer') {
1401 $promo_min = ($art['public'] ? 0 : $art['promo_min']);
1402 $promo_max = ($art['public'] ? 0 : $art['promo_max']);
1403 $flags = new PlFlagSet();
1404 if ($art['public']) {
1405 $flags->addFlag('public');
1406 }
1407 if ($art['photo']) {
1408 $flags->addFlag('photo');
1409 }
1410 if (is_null($aid)) {
1411 $fulltext = $art['texte'];
1412 if (!empty($art['contact_html'])) {
1413 $fulltext .= "\n\n'''Contacts :'''\\\\\n" . $art['contact_html'];
1414 }
1415 $post = null;
1416 if ($globals->asso('forum')) {
1417 require_once 'banana/forum.inc.php';
1418 $banana = new ForumsBanana(S::user());
1419 $post = $banana->post($globals->asso('forum'), null,
1420 $art['titre'], MiniWiki::wikiToText($fulltext, false, 0, 80));
1421 }
1422 XDB::query('INSERT INTO group_announces (uid, asso_id, create_date, titre, texte, contacts,
1423 expiration, promo_min, promo_max, flags, post_id)
1424 VALUES ({?}, {?}, NOW(), {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
1425 S::i('uid'), $globals->asso('id'), $art['titre'], $art['texte'], $art['contact_html'],
1426 $art['expiration'], $promo_min, $promo_max, $flags, $post);
1427 $aid = XDB::insertId();
1428 if ($art['photo']) {
1429 list($imgx, $imgy, $imgtype) = $upload->imageInfo();
1430 XDB::execute('INSERT INTO group_announces_photo
1431 SET eid = {?}, attachmime = {?}, x = {?}, y = {?}, attach = {?}',
1432 $aid, $imgtype, $imgx, $imgy, $upload->getContents());
1433 }
1434 if ($art['xorg']) {
1435 $article = new EvtReq("[{$globals->asso('nom')}] " . $art['titre'], $fulltext,
1436 $art['promo_min'], $art['promo_max'], $art['expiration'], "", S::user(),
1437 $upload);
1438 $article->submit();
1439 $page->trigWarning("L'affichage sur la page d'accueil de Polytechnique.org est en attente de validation.");
1440 } else if ($upload && $upload->exists()) {
1441 $upload->rm();
1442 }
1443 if ($art['nl']) {
1444 $article = new NLReq(S::user(), $globals->asso('nom') . " : " .$art['titre'],
1445 $art['texte'], $art['contact_html']);
1446 $article->submit();
1447 $page->trigWarning("La parution dans la Lettre Mensuelle est en attente de validation.");
1448 }
1449 } else {
1450 XDB::query('UPDATE group_announces
1451 SET titre = {?}, texte = {?}, contacts = {?}, expiration = {?},
1452 promo_min = {?}, promo_max = {?}, flags = {?}
1453 WHERE id = {?} AND asso_id = {?}',
1454 $art['titre'], $art['texte'], $art['contacts'], $art['expiration'],
1455 $promo_min, $promo_max, $flags,
1456 $art['id'], $globals->asso('id'));
1457 if ($art['photo'] && $upload->exists()) {
1458 list($imgx, $imgy, $imgtype) = $upload->imageInfo();
1459 XDB::execute('INSERT INTO group_announces_photo (eid, attachmime, attach, x, y)
1460 VALUES ({?}, {?}, {?}, {?}, {?})
1461 ON DUPLICATE KEY UPDATE attachmime = VALUES(attachmime), attach = VALUES(attach), x = VALUES(x), y = VALUES(y)',
1462 $aid, $imgtype, $upload->getContents(), $imgx, $imgy);
1463 $upload->rm();
1464 }
1465 }
1466 }
1467 if (Post::v('valid') == 'Enregistrer' || Post::v('valid') == 'Annuler') {
1468 pl_redirect("");
1469 }
1470
1471 if (empty($art) && !is_null($aid)) {
1472 $res = XDB::query("SELECT *, FIND_IN_SET('public', flags) AS public,
1473 FIND_IN_SET('photo', flags) AS photo
1474 FROM group_announces
1475 WHERE asso_id = {?} AND id = {?}",
1476 $globals->asso('id'), $aid);
1477 if ($res->numRows()) {
1478 $art = $res->fetchOneAssoc();
1479 $art['contact_html'] = $art['contacts'];
1480 } else {
1481 $page->kill("Aucun article correspond à l'identifiant indiqué.");
1482 }
1483 }
1484
1485 if (is_null($aid)) {
1486 $events = XDB::iterator("SELECT *
1487 FROM group_events
1488 WHERE asso_id = {?} AND archive = 0",
1489 $globals->asso('id'));
1490 if ($events->total()) {
1491 $page->assign('events', $events);
1492 }
1493 }
1494
1495 $art['contact_html'] = @MiniWiki::WikiToHTML($art['contact_html']);
1496 $page->assign('art', $art);
1497 $page->assign_by_ref('upload', $upload);
1498 }
1499
1500 function handler_admin_announce($page)
1501 {
1502 global $globals;
1503 $page->changeTpl('xnetgrp/announce-admin.tpl');
1504
1505 if (Env::has('del')) {
1506 S::assert_xsrf_token();
1507 XDB::execute('DELETE FROM group_announces
1508 WHERE id = {?} AND asso_id = {?}',
1509 Env::i('del'), $globals->asso('id'));
1510 }
1511 $res = XDB::iterator('SELECT id, titre, expiration, expiration < CURRENT_DATE() AS perime
1512 FROM group_announces
1513 WHERE asso_id = {?}
1514 ORDER BY expiration DESC',
1515 $globals->asso('id'));
1516 $page->assign('articles', $res);
1517 }
1518 }
1519
1520 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1521 ?>