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