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