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