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