b004fde7f367bbe287c0ff8deaeedae493639310
[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 $suggest_account_activation = $this->suggest($user);
733 }
734
735 if ($user) {
736 XDB::execute('INSERT IGNORE INTO group_members (uid, asso_id)
737 VALUES ({?}, {?})',
738 $user->id(), $globals->asso('id'));
739 $this->removeSubscriptionRequest($user->id());
740 if ($suggest_account_activation) {
741 pl_redirect('member/suggest/' . $user->login() . '/' . $email . '/' . $globals->asso('nom'));
742 } else {
743 pl_redirect('member/' . $user->login());
744 }
745 }
746 }
747
748 // Check if the user has a pending or active account, and thus if we should her account's activation.
749 private function suggest(PlUser $user)
750 {
751 $active = XDB::fetchOneCell('SELECT state = \'active\'
752 FROM accounts
753 WHERE uid = {?}',
754 $user->id());
755 $pending = XDB::fetchOneCell('SELECT uid
756 FROM register_pending_xnet
757 WHERE uid = {?}',
758 $user->id());
759 $requested = AccountReq::isPending($user->id());
760
761 if ($active || $pending || $requested) {
762 return false;
763 }
764 return true;
765 }
766
767 function handler_admin_member_suggest($page, $hruid, $email)
768 {
769 $page->changeTpl('xnetgrp/membres-suggest.tpl');
770
771 if (Post::has('suggest')) {
772 if (Post::t('suggest') == 'yes') {
773 $user = S::user();
774 $group = Platal::globals()->asso('nom');
775 $request = new AccountReq($user, $hruid, $email, $group);
776 $request->submit();
777 $page->trigSuccessRedirect('Un email va bien être envoyé à ' . $email . ' pour l\'activation de son compte.',
778 $group . '/member/' . $hruid);
779 } else {
780 pl_redirect('member/' . $hruid);
781 }
782 }
783 $page->assign('email', $email);
784 $page->assign('hruid', $hruid);
785 }
786
787 function handler_admin_member_new_ajax($page)
788 {
789 pl_content_headers("text/html");
790 $page->changeTpl('xnetgrp/membres-new-search.tpl', NO_SKIN);
791 $users = array();
792 if (Env::has('login')) {
793 $user = User::getSilent(Env::t('login'));
794 if ($user && $user->state != 'pending') {
795 $users = array($user);
796 }
797 }
798 if (empty($users)) {
799 list($lastname, $firstname) = str_replace(array('-', ' ', "'"), '%', array(Env::t('nom'), Env::t('prenom')));
800 $cond = new PFC_And(new PFC_Not(new UFC_Registered()));
801 if (!empty($lastname)) {
802 $cond->addChild(new UFC_Name(Profile::LASTNAME, $lastname, UFC_Name::CONTAINS));
803 }
804 if (!empty($firstname)) {
805 $cond->addChild(new UFC_Name(Profile::FIRSTNAME, $firstname, UFC_Name::CONTAINS));
806 }
807 if (Env::t('promo')) {
808 $cond->addChild(new UFC_Promo('=', UserFilter::DISPLAY, Env::t('promo')));
809 }
810 $uf = new UserFilter($cond);
811 $users = $uf->getUsers(new PlLimit(30));
812 if ($uf->getTotalCount() > 30) {
813 $page->assign('too_many', true);
814 $users = array();
815 }
816 }
817 $page->assign('users', $users);
818 }
819
820 function unsubscribe(PlUser $user)
821 {
822 global $globals;
823 XDB::execute("DELETE FROM group_members
824 WHERE uid = {?} AND asso_id = {?}",
825 $user->id(), $globals->asso('id'));
826
827 if ($globals->asso('notif_unsub')) {
828 $mailer = new PlMailer('xnetgrp/unsubscription-notif.mail.tpl');
829 $admins = $globals->asso()->iterAdmins();
830 while ($admin = $admins->next()) {
831 $mailer->addTo($admin);
832 }
833 $mailer->assign('group', $globals->asso('nom'));
834 $mailer->assign('user', $user);
835 $mailer->assign('selfdone', $user->id() == S::i('uid'));
836 $mailer->send();
837 }
838
839 $domain = $globals->asso('mail_domain');
840 if (!$domain) {
841 return true;
842 }
843
844 $mmlist = new MMList(S::user(), $domain);
845 $listes = $mmlist->get_lists($user->forlifeEmail());
846
847 $may_update = may_update();
848 $warning = false;
849 if (is_array($listes)) {
850 foreach ($listes as $liste) {
851 if ($liste['sub'] == 2) {
852 if ($may_update) {
853 $mmlist->mass_unsubscribe($liste['list'], Array($user->forlifeEmail()));
854 } else {
855 $mmlist->unsubscribe($liste['list']);
856 }
857 } elseif ($liste['sub']) {
858 Platal::page()->trigWarning($user->fullName() . " a une"
859 ." demande d'inscription en cours sur la"
860 ." liste {$liste['list']}@ !");
861 $warning = true;
862 }
863 }
864 }
865
866 XDB::execute('DELETE v
867 FROM email_virtual AS v
868 INNER JOIN email_virtual_domains AS d ON (v.domain = d.id)
869 WHERE v.redirect = {?} AND d.name = {?}',
870 $user->forlifeEmail(), $domain);
871 return !$warning;
872 }
873
874 function handler_unsubscribe($page)
875 {
876 $page->changeTpl('xnetgrp/membres-del.tpl');
877 $user = S::user();
878 if (empty($user)) {
879 return PL_NOT_FOUND;
880 }
881 $page->assign('self', true);
882 $page->assign('user', $user);
883
884 if (!Post::has('confirm')) {
885 return;
886 } else {
887 S::assert_xsrf_token();
888 }
889
890 $hasSingleGroup = ($user->groupCount() == 1);
891
892 if ($this->unsubscribe($user)) {
893 $page->trigSuccess('Tu as été désinscrit du groupe avec succès.');
894 } else {
895 $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.');
896 }
897
898 // If user is of type xnet account and this was her last group, disable the account.
899 if ($user->type == 'xnet' && $hasSingleGroup) {
900 $user->clear(true);
901 }
902 $page->assign('is_member', is_member(true));
903 }
904
905 function handler_admin_member_del($page, $user = null)
906 {
907 $page->changeTpl('xnetgrp/membres-del.tpl');
908 $user = User::getSilent($user);
909 if (empty($user)) {
910 return PL_NOT_FOUND;
911 }
912
913 global $globals;
914
915 if (!$user->inGroup($globals->asso('id'))) {
916 pl_redirect('annuaire');
917 }
918
919 $page->assign('self', false);
920 $page->assign('user', $user);
921
922 if (!Post::has('confirm')) {
923 return;
924 } else {
925 S::assert_xsrf_token();
926 }
927
928 $hasSingleGroup = ($user->groupCount() == 1);
929
930 if ($this->unsubscribe($user)) {
931 $page->trigSuccess("{$user->fullName()} a été désinscrit du groupe&nbsp;!");
932 } else {
933 $page->trigWarning("{$user->fullName()} a été désinscrit du groupe, mais des erreurs subsistent&nbsp;!");
934 }
935
936 // If user is of type xnet account and this was her last group, disable the account.
937 if ($user->type == 'xnet' && $hasSingleGroup) {
938 $user->clear(true);
939 }
940 }
941
942 private function changeLogin(PlPage $page, PlUser $user, $login)
943 {
944 // Search the user's uid.
945 $xuser = User::getSilent($login);
946 if (!$xuser) {
947 $accounts = User::getPendingAccounts($login);
948 if (!$accounts) {
949 $page->trigError("L'identifiant $login ne correspond à aucun X.");
950 return false;
951 } else if (count($accounts) > 1) {
952 $page->trigError("L'identifiant $login correspond à plusieurs camarades.");
953 return false;
954 }
955 $xuser = User::getSilent($accounts[0]['uid']);
956 }
957
958 if (!$xuser) {
959 return false;
960 }
961
962 if ($user->mergeIn($xuser)) {
963 return $xuser->login();
964 }
965 return $user->login();
966 }
967
968 function handler_admin_member($page, $user)
969 {
970 global $globals;
971
972 $user = User::getSilent($user);
973 if (empty($user)) {
974 return PL_NOT_FOUND;
975 }
976
977 if (!$user->inGroup($globals->asso('id'))) {
978 pl_redirect('annuaire');
979 }
980
981 $page->changeTpl('xnetgrp/membres-edit.tpl');
982
983 $mmlist = new MMList(S::user(), $globals->asso('mail_domain'));
984
985 if (Post::has('change')) {
986 S::assert_xsrf_token();
987
988 // Convert user status to X
989 if (!Post::blank('login_X')) {
990 $forlife = $this->changeLogin($page, $user, Post::t('login_X'));
991 if ($forlife) {
992 pl_redirect('member/' . $forlife);
993 }
994 }
995
996 // Update user info
997 $email_changed = (!$user->profile() && strtolower($user->forlifeEmail()) != strtolower(Post::v('email')));
998 $from_email = $user->forlifeEmail();
999 if ($user->type == 'virtual' || ($user->type == 'xnet' && !$user->perms)) {
1000 XDB::query('UPDATE accounts
1001 SET full_name = {?}, directory_name = {?}, display_name = {?},
1002 sex = {?}, email = {?}, type = {?}
1003 WHERE uid = {?}',
1004 Post::t('full_name'), Post::t('directory_name'), Post::t('display_name'),
1005 (Post::t('sex') == 'male') ? 'male' : 'female', Post::t('email'),
1006 (Post::t('type') == 'xnet') ? 'xnet' : 'virtual', $user->id());
1007 } else if (!$user->perms) {
1008 XDB::query('UPDATE accounts
1009 SET email = {?}
1010 WHERE uid = {?}',
1011 Post::t('email'), $user->id());
1012 }
1013 if (XDB::affectedRows()) {
1014 $page->trigSuccess('Données de l\'utilisateur mises à jour.');
1015 }
1016
1017 if (($user->type == 'xnet' && !$user->perms) && Post::b('suggest')) {
1018 $request = new AccountReq(S::user(), $user->hruid, Post::t('email'), $globals->asso('nom'));
1019 $request->submit();
1020 $page->trigSuccess('Le compte va bientôt être activé.');
1021 }
1022
1023 // Update group params for user
1024 $perms = Post::v('group_perms');
1025 $comm = Post::t('comm');
1026 $position = (Post::t('group_position') == '') ? null : Post::v('group_position');
1027 if ($user->group_perms != $perms || $user->group_comm != $comm || $user->group_position != $position) {
1028 XDB::query('UPDATE group_members
1029 SET perms = {?}, comm = {?}, position = {?}
1030 WHERE uid = {?} AND asso_id = {?}',
1031 ($perms == 'admin') ? 'admin' : 'membre', $comm, $position,
1032 $user->id(), $globals->asso('id'));
1033 if (XDB::affectedRows()) {
1034 if ($perms != $user->group_perms) {
1035 $page->trigSuccess('Permissions modifiées&nbsp;!');
1036 }
1037 if ($comm != $user->group_comm) {
1038 $page->trigSuccess('Commentaire mis à jour.');
1039 }
1040 if ($position != $user->group_position) {
1041 $page->trigSuccess('Poste mis à jour.');
1042 }
1043 }
1044 }
1045
1046 // Gets user info again as they might have change
1047 $user = User::getSilent($user->id());
1048
1049 // Update ML subscriptions
1050 foreach (Env::v('ml1', array()) as $ml => $state) {
1051 $ask = empty($_REQUEST['ml2'][$ml]) ? 0 : 2;
1052 if ($ask == $state) {
1053 if ($state && $email_changed) {
1054 $mmlist->replace_email($ml, $from_email, $user->forlifeEmail());
1055 $page->trigSuccess("L'abonnement de {$user->fullName()} à $ml@ a été mis à jour.");
1056 }
1057 continue;
1058 }
1059 if ($state == '1') {
1060 $page->trigWarning("{$user->fullName()} a "
1061 ."actuellement une demande d'inscription en "
1062 ."cours sur <strong>$ml@</strong> !!!");
1063 } elseif ($ask) {
1064 $mmlist->mass_subscribe($ml, Array($user->forlifeEmail()));
1065 $page->trigSuccess("{$user->fullName()} a été abonné à $ml@.");
1066 } else {
1067 if ($email_changed) {
1068 $mmlist->mass_unsubscribe($ml, Array($from_email));
1069 } else {
1070 $mmlist->mass_unsubscribe($ml, Array($user->forlifeEmail()));
1071 }
1072 $page->trigSuccess("{$user->fullName()} a été désabonné de $ml@.");
1073 }
1074 }
1075
1076 // Change subscriptioin to aliases
1077 foreach (Env::v('ml3', array()) as $ml => $state) {
1078 require_once 'emails.inc.php';
1079 $ask = !empty($_REQUEST['ml4'][$ml]);
1080 if($state == $ask) {
1081 if ($state && $email_changed) {
1082 update_list_alias($user, $from_email, $ml, $globals->asso('mail_domain'));
1083 $page->trigSuccess("L'abonnement de {$user->fullName()} à $ml a été mis à jour.");
1084 }
1085 } else if($ask) {
1086 add_to_list_alias($user, $ml, $globals->asso('mail_domain'));
1087 $page->trigSuccess("{$user->fullName()} a été abonné à $ml.");
1088 } else {
1089 delete_from_list_alias($user, $ml, $globals->asso('mail_domain'));
1090 $page->trigSuccess("{$user->fullName()} a été désabonné de $ml.");
1091 }
1092 }
1093 }
1094
1095 $res = XDB::rawFetchAllAssoc('SHOW COLUMNS FROM group_members LIKE \'position\'');
1096 $positions = str_replace(array('enum(', ')', '\''), '', $res[0]['Type']);
1097
1098 $page->assign('user', $user);
1099 $page->assign('suggest', $this->suggest($user));
1100 $page->assign('listes', $mmlist->get_lists($user->forlifeEmail()));
1101 $page->assign('alias', $user->emailGroupAliases($globals->asso('mail_domain')));
1102 $page->assign('positions', explode(',', $positions));
1103 }
1104
1105 function handler_rss(PlPage $page, PlUser $user)
1106 {
1107 global $globals;
1108 $page->assign('asso', $globals->asso());
1109
1110 $this->load('feed.inc.php');
1111 $feed = new XnetGrpEventFeed();
1112 return $feed->run($page, $user, false);
1113 }
1114
1115 private function upload_image(PlPage $page, PlUpload $upload)
1116 {
1117 if (@!$_FILES['image']['tmp_name'] && !Env::v('image_url')) {
1118 return true;
1119 }
1120 if (!$upload->upload($_FILES['image']) && !$upload->download(Env::v('image_url'))) {
1121 $page->trigError('Impossible de télécharger l\'image');
1122 return false;
1123 } elseif (!$upload->isType('image')) {
1124 $page->trigError('Le fichier n\'est pas une image valide au format JPEG, GIF ou PNG.');
1125 $upload->rm();
1126 return false;
1127 } elseif (!$upload->resizeImage(200, 300, 100, 100, 32284)) {
1128 $page->trigError('Impossible de retraiter l\'image');
1129 return false;
1130 }
1131 return true;
1132 }
1133
1134 function handler_photo_announce($page, $eid = null) {
1135 if ($eid) {
1136 $res = XDB::query('SELECT *
1137 FROM group_announces_photo
1138 WHERE eid = {?}', $eid);
1139 if ($res->numRows()) {
1140 $photo = $res->fetchOneAssoc();
1141 pl_cached_dynamic_content_headers("image/" . $photo['attachmime']);
1142 echo $photo['attach'];
1143 exit;
1144 }
1145 } else {
1146 $upload = new PlUpload(S::user()->login(), 'xnetannounce');
1147 if ($upload->exists() && $upload->isType('image')) {
1148 pl_cached_dynamic_content_headers($upload->contentType());
1149 echo $upload->getContents();
1150 exit;
1151 }
1152 }
1153 global $globals;
1154 pl_cached_dynamic_content_headers("image/png");
1155 echo file_get_contents($globals->spoolroot . '/htdocs/images/logo.png');
1156 exit;
1157 }
1158
1159 function handler_edit_announce($page, $aid = null)
1160 {
1161 global $globals, $platal;
1162 $page->changeTpl('xnetgrp/announce-edit.tpl');
1163 $page->assign('new', is_null($aid));
1164 $art = array();
1165
1166 if (Post::v('valid') == 'Visualiser' || Post::v('valid') == 'Enregistrer'
1167 || Post::v('valid') == 'Supprimer l\'image' || Post::v('valid') == 'Pas d\'image') {
1168 S::assert_xsrf_token();
1169
1170 if (!is_null($aid)) {
1171 $art['id'] = $aid;
1172 }
1173 $art['titre'] = Post::v('titre');
1174 $art['texte'] = Post::v('texte');
1175 $art['contacts'] = Post::v('contacts');
1176 $art['promo_min'] = Post::i('promo_min');
1177 $art['promo_max'] = Post::i('promo_max');
1178 $art['nom'] = S::v('nom');
1179 $art['prenom'] = S::v('prenom');
1180 $art['promo'] = S::v('promo');
1181 $art['hruid'] = S::user()->login();
1182 $art['uid'] = S::user()->id();
1183 $art['expiration'] = Post::v('expiration');
1184 $art['public'] = Post::has('public');
1185 $art['xorg'] = Post::has('xorg');
1186 $art['nl'] = Post::has('nl');
1187 $art['event'] = Post::v('event');
1188 $upload = new PlUpload(S::user()->login(), 'xnetannounce');
1189 $this->upload_image($page, $upload);
1190
1191 $art['contact_html'] = $art['contacts'];
1192 if ($art['event']) {
1193 $art['contact_html'] .= "\n{$globals->baseurl}/{$platal->ns}events/sub/{$art['event']}";
1194 }
1195
1196 if (!$art['public'] &&
1197 (($art['promo_min'] > $art['promo_max'] && $art['promo_max'] != 0) ||
1198 ($art['promo_min'] != 0 && ($art['promo_min'] <= 1900 || $art['promo_min'] >= 2020)) ||
1199 ($art['promo_max'] != 0 && ($art['promo_max'] <= 1900 || $art['promo_max'] >= 2020))))
1200 {
1201 $page->trigError("L'intervalle de promotions est invalide.");
1202 Post::kill('valid');
1203 }
1204
1205 if (!trim($art['titre']) || !trim($art['texte'])) {
1206 $page->trigError("L'article doit avoir un titre et un contenu.");
1207 Post::kill('valid');
1208 }
1209
1210 if (Post::v('valid') == 'Supprimer l\'image') {
1211 $upload->rm();
1212 Post::kill('valid');
1213 }
1214 $art['photo'] = $upload->exists() || Post::i('photo');
1215 if (Post::v('valid') == 'Pas d\'image' && !is_null($aid)) {
1216 XDB::query('DELETE FROM group_announces_photo
1217 WHERE eid = {?}', $aid);
1218 $upload->rm();
1219 Post::kill('valid');
1220 $art['photo'] = false;
1221 }
1222 }
1223
1224 if (Post::v('valid') == 'Enregistrer') {
1225 $promo_min = ($art['public'] ? 0 : $art['promo_min']);
1226 $promo_max = ($art['public'] ? 0 : $art['promo_max']);
1227 $flags = new PlFlagSet();
1228 if ($art['public']) {
1229 $flags->addFlag('public');
1230 }
1231 if ($art['photo']) {
1232 $flags->addFlag('photo');
1233 }
1234 if (is_null($aid)) {
1235 $fulltext = $art['texte'];
1236 if (!empty($art['contact_html'])) {
1237 $fulltext .= "\n\n'''Contacts :'''\\\\\n" . $art['contact_html'];
1238 }
1239 $post = null;/*
1240 if ($globals->asso('forum')) {
1241 require_once 'banana/forum.inc.php';
1242 $banana = new ForumsBanana(S::user());
1243 $post = $banana->post($globals->asso('forum'), null,
1244 $art['titre'], MiniWiki::wikiToText($fulltext, false, 0, 80));
1245 }*/
1246 XDB::query('INSERT INTO group_announces (uid, asso_id, create_date, titre, texte, contacts,
1247 expiration, promo_min, promo_max, flags, post_id)
1248 VALUES ({?}, {?}, NOW(), {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
1249 S::i('uid'), $globals->asso('id'), $art['titre'], $art['texte'], $art['contact_html'],
1250 $art['expiration'], $promo_min, $promo_max, $flags, $post);
1251 $aid = XDB::insertId();
1252 if ($art['photo']) {
1253 list($imgx, $imgy, $imgtype) = $upload->imageInfo();
1254 XDB::execute('INSERT INTO group_announces_photo
1255 SET eid = {?}, attachmime = {?}, x = {?}, y = {?}, attach = {?}',
1256 $aid, $imgtype, $imgx, $imgy, $upload->getContents());
1257 }
1258 if ($art['xorg']) {
1259 $article = new EvtReq("[{$globals->asso('nom')}] " . $art['titre'], $fulltext,
1260 $art['promo_min'], $art['promo_max'], $art['expiration'], "", S::user(),
1261 $upload);
1262 $article->submit();
1263 $page->trigWarning("L'affichage sur la page d'accueil de Polytechnique.org est en attente de validation.");
1264 } else if ($upload && $upload->exists()) {
1265 $upload->rm();
1266 }
1267 if ($art['nl']) {
1268 $article = new NLReq(S::user(), $globals->asso('nom') . " : " .$art['titre'],
1269 $art['texte'], $art['contact_html']);
1270 $article->submit();
1271 $page->trigWarning("La parution dans la Lettre Mensuelle est en attente de validation.");
1272 }
1273 } else {
1274 XDB::query('UPDATE group_announces
1275 SET titre = {?}, texte = {?}, contacts = {?}, expiration = {?},
1276 promo_min = {?}, promo_max = {?}, flags = {?}
1277 WHERE id = {?} AND asso_id = {?}',
1278 $art['titre'], $art['texte'], $art['contacts'], $art['expiration'],
1279 $promo_min, $promo_max, $flags,
1280 $art['id'], $globals->asso('id'));
1281 if ($art['photo'] && $upload->exists()) {
1282 list($imgx, $imgy, $imgtype) = $upload->imageInfo();
1283 XDB::execute('INSERT INTO group_announces_photo (eid, attachmime, attach, x, y)
1284 VALUES ({?}, {?}, {?}, {?}, {?})
1285 ON DUPLICATE KEY UPDATE attachmime = VALUES(attachmime), attach = VALUES(attach), x = VALUES(x), y = VALUES(y)',
1286 $aid, $imgtype, $upload->getContents(), $imgx, $imgy);
1287 $upload->rm();
1288 }
1289 }
1290 }
1291 if (Post::v('valid') == 'Enregistrer' || Post::v('valid') == 'Annuler') {
1292 pl_redirect("");
1293 }
1294
1295 if (empty($art) && !is_null($aid)) {
1296 $res = XDB::query("SELECT *, FIND_IN_SET('public', flags) AS public,
1297 FIND_IN_SET('photo', flags) AS photo
1298 FROM group_announces
1299 WHERE asso_id = {?} AND id = {?}",
1300 $globals->asso('id'), $aid);
1301 if ($res->numRows()) {
1302 $art = $res->fetchOneAssoc();
1303 $art['contact_html'] = $art['contacts'];
1304 } else {
1305 $page->kill("Aucun article correspond à l'identifiant indiqué.");
1306 }
1307 }
1308
1309 if (is_null($aid)) {
1310 $events = XDB::iterator("SELECT *
1311 FROM group_events
1312 WHERE asso_id = {?} AND archive = 0",
1313 $globals->asso('id'));
1314 if ($events->total()) {
1315 $page->assign('events', $events);
1316 }
1317 }
1318
1319 $art['contact_html'] = @MiniWiki::WikiToHTML($art['contact_html']);
1320 $page->assign('art', $art);
1321 $page->assign_by_ref('upload', $upload);
1322 }
1323
1324 function handler_admin_announce($page)
1325 {
1326 global $globals;
1327 $page->changeTpl('xnetgrp/announce-admin.tpl');
1328
1329 if (Env::has('del')) {
1330 S::assert_xsrf_token();
1331 XDB::execute('DELETE FROM group_announces
1332 WHERE id = {?} AND asso_id = {?}',
1333 Env::i('del'), $globals->asso('id'));
1334 }
1335 $res = XDB::iterator('SELECT id, titre, expiration, expiration < CURRENT_DATE() AS perime
1336 FROM group_announces
1337 WHERE asso_id = {?}
1338 ORDER BY expiration DESC',
1339 $globals->asso('id'));
1340 $page->assign('articles', $res);
1341 }
1342 }
1343
1344 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1345 ?>