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