Merge commit 'origin/fusionax' into account
[platal.git] / modules / admin.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2009 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 class AdminModule extends PLModule
23 {
24 function handlers()
25 {
26 return array(
27 'phpinfo' => $this->make_hook('phpinfo', AUTH_MDP, 'admin'),
28 'get_rights' => $this->make_hook('get_rights', AUTH_MDP, 'admin'),
29 'admin' => $this->make_hook('default', AUTH_MDP, 'admin'),
30 'admin/ax-xorg' => $this->make_hook('ax_xorg', AUTH_MDP, 'admin'),
31 'admin/dead-but-active' => $this->make_hook('dead_but_active', AUTH_MDP, 'admin'),
32 'admin/deaths' => $this->make_hook('deaths', AUTH_MDP, 'admin'),
33 'admin/downtime' => $this->make_hook('downtime', AUTH_MDP, 'admin'),
34 'admin/homonyms' => $this->make_hook('homonyms', AUTH_MDP, 'admin'),
35 'admin/logger' => $this->make_hook('logger', AUTH_MDP, 'admin'),
36 'admin/logger/actions' => $this->make_hook('logger_actions', AUTH_MDP, 'admin'),
37 'admin/postfix/blacklist' => $this->make_hook('postfix_blacklist', AUTH_MDP, 'admin'),
38 'admin/postfix/delayed' => $this->make_hook('postfix_delayed', AUTH_MDP, 'admin'),
39 'admin/postfix/regexp_bounces' => $this->make_hook('postfix_regexpsbounces', AUTH_MDP, 'admin'),
40 'admin/postfix/whitelist' => $this->make_hook('postfix_whitelist', AUTH_MDP, 'admin'),
41 'admin/mx/broken' => $this->make_hook('mx_broken', AUTH_MDP, 'admin'),
42 'admin/skins' => $this->make_hook('skins', AUTH_MDP, 'admin'),
43 'admin/synchro_ax' => $this->make_hook('synchro_ax', AUTH_MDP, 'admin'),
44 'admin/user' => $this->make_hook('user', AUTH_MDP, 'admin'),
45 'admin/promo' => $this->make_hook('promo', AUTH_MDP, 'admin'),
46 'admin/validate' => $this->make_hook('validate', AUTH_MDP, 'admin'),
47 'admin/validate/answers' => $this->make_hook('validate_answers', AUTH_MDP, 'admin'),
48 'admin/wiki' => $this->make_hook('wiki', AUTH_MDP, 'admin'),
49 'admin/ipwatch' => $this->make_hook('ipwatch', AUTH_MDP, 'admin'),
50 'admin/icons' => $this->make_hook('icons', AUTH_MDP, 'admin'),
51 'admin/accounts' => $this->make_hook('accounts', AUTH_MDP, 'admin'),
52 'admin/account/types' => $this->make_hook('account_types', AUTH_MDP, 'admin'),
53 );
54 }
55
56 function handler_phpinfo(&$page)
57 {
58 phpinfo();
59 exit;
60 }
61
62 function handler_get_rights(&$page, $level)
63 {
64 if (S::suid()) {
65 $page->kill('Déjà en SUID');
66 }
67 $user =& S::user();
68 Platal::session()->startSUID($user, $level);
69
70 pl_redirect('/');
71 }
72
73 function handler_default(&$page)
74 {
75 $page->changeTpl('admin/index.tpl');
76 $page->setTitle('Administration');
77 }
78
79 function handler_postfix_delayed(&$page)
80 {
81 $page->changeTpl('admin/postfix_delayed.tpl');
82 $page->setTitle('Administration - Postfix : Retardés');
83
84 if (Env::has('del')) {
85 $crc = Env::v('crc');
86 XDB::execute("UPDATE postfix_mailseen SET release = 'del' WHERE crc = {?}", $crc);
87 $page->trigSuccess($crc." verra tous ses emails supprimés !");
88 } elseif (Env::has('ok')) {
89 $crc = Env::v('crc');
90 XDB::execute("UPDATE postfix_mailseen SET release = 'ok' WHERE crc = {?}", $crc);
91 $page->trigSuccess($crc." a le droit de passer !");
92 }
93
94 $sql = XDB::iterator(
95 "SELECT crc, nb, update_time, create_time,
96 FIND_IN_SET('del', release) AS del,
97 FIND_IN_SET('ok', release) AS ok
98 FROM postfix_mailseen
99 WHERE nb >= 30
100 ORDER BY release != ''");
101
102 $page->assign_by_ref('mails', $sql);
103 }
104
105 function handler_postfix_regexpsbounces(&$page, $new = null) {
106 $page->changeTpl('admin/emails_bounces_re.tpl');
107 $page->setTitle('Administration - Postfix : Regexps Bounces');
108 $page->assign('new', $new);
109
110 if (Post::has('submit')) {
111 foreach (Env::v('lvl') as $id=>$val) {
112 XDB::query(
113 "REPLACE INTO emails_bounces_re (id,pos,lvl,re,text) VALUES ({?}, {?}, {?}, {?}, {?})",
114 $id, $_POST['pos'][$id], $_POST['lvl'][$id], $_POST['re'][$id], $_POST['text'][$id]
115 );
116 }
117 }
118
119 $page->assign('bre', XDB::iterator("SELECT * FROM emails_bounces_re ORDER BY pos"));
120 }
121
122 // {{{ logger view
123
124 /** Retrieves the available days for a given year and month.
125 * Obtain a list of days of the given month in the given year
126 * that are within the range of dates that we have log entries for.
127 *
128 * @param integer year
129 * @param integer month
130 * @return array days in that month we have log entries covering.
131 * @private
132 */
133 function _getDays($year, $month)
134 {
135 // give a 'no filter' option
136 $months[0] = "----";
137
138 if ($year && $month) {
139 $day_max = Array(-1, 31, checkdate(2, 29, $year) ? 29 : 28 , 31,
140 30, 31, 30, 31, 31, 30, 31, 30, 31);
141 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
142 MONTH(MAX(start)), MONTH(MIN(start)),
143 DAYOFMONTH(MAX(start)),
144 DAYOFMONTH(MIN(start))
145 FROM logger.sessions");
146 list($ymax, $ymin, $mmax, $mmin, $dmax, $dmin) = $res->fetchOneRow();
147
148 if (($year < $ymin) || ($year == $ymin && $month < $mmin)) {
149 return array();
150 }
151
152 if (($year > $ymax) || ($year == $ymax && $month > $mmax)) {
153 return array();
154 }
155
156 $min = ($year==$ymin && $month==$mmin) ? intval($dmin) : 1;
157 $max = ($year==$ymax && $month==$mmax) ? intval($dmax) : $day_max[$month];
158
159 for($i = $min; $i<=$max; $i++) {
160 $days[$i] = $i;
161 }
162 }
163 return $days;
164 }
165
166
167 /** Retrieves the available months for a given year.
168 * Obtains a list of month numbers that are within the timeframe that
169 * we have log entries for.
170 *
171 * @param integer year
172 * @return array List of month numbers we have log info for.
173 * @private
174 */
175 function _getMonths($year)
176 {
177 // give a 'no filter' option
178 $months[0] = "----";
179
180 if ($year) {
181 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
182 MONTH(MAX(start)), MONTH(MIN(start))
183 FROM logger.sessions");
184 list($ymax, $ymin, $mmax, $mmin) = $res->fetchOneRow();
185
186 if (($year < $ymin) || ($year > $ymax)) {
187 return array();
188 }
189
190 $min = $year == $ymin ? intval($mmin) : 1;
191 $max = $year == $ymax ? intval($mmax) : 12;
192
193 for($i = $min; $i<=$max; $i++) {
194 $months[$i] = $i;
195 }
196 }
197 return $months;
198 }
199
200
201 /** Retrieves the available years.
202 * Obtains a list of years that we have log entries covering.
203 *
204 * @return array years we have log entries for.
205 * @private
206 */
207 function _getYears()
208 {
209 // give a 'no filter' option
210 $years[0] = "----";
211
212 // retrieve available years
213 $res = XDB::query("select YEAR(MAX(start)), YEAR(MIN(start)) FROM logger.sessions");
214 list($max, $min) = $res->fetchOneRow();
215
216 for($i = intval($min); $i<=$max; $i++) {
217 $years[$i] = $i;
218 }
219 return $years;
220 }
221
222
223 /** Make a where clause to get a user's sessions.
224 * Prepare the where clause request that will retrieve the sessions.
225 *
226 * @param $year INTEGER Only get log entries made during the given year.
227 * @param $month INTEGER Only get log entries made during the given month.
228 * @param $day INTEGER Only get log entries made during the given day.
229 * @param $uid INTEGER Only get log entries referring to the given user ID.
230 *
231 * @return STRING the WHERE clause of a query, including the 'WHERE' keyword
232 * @private
233 */
234 function _makeWhere($year, $month, $day, $uid)
235 {
236 // start constructing the "where" clause
237 $where = array();
238
239 if ($uid)
240 array_push($where, "uid='$uid'");
241
242 // we were given at least a year
243 if ($year) {
244 if ($day) {
245 $dmin = mktime(0, 0, 0, $month, $day, $year);
246 $dmax = mktime(0, 0, 0, $month, $day+1, $year);
247 } elseif ($month) {
248 $dmin = mktime(0, 0, 0, $month, 1, $year);
249 $dmax = mktime(0, 0, 0, $month+1, 1, $year);
250 } else {
251 $dmin = mktime(0, 0, 0, 1, 1, $year);
252 $dmax = mktime(0, 0, 0, 1, 1, $year+1);
253 }
254 $where[] = "start >= " . date("Ymd000000", $dmin);
255 $where[] = "start < " . date("Ymd000000", $dmax);
256 }
257
258 if (!empty($where)) {
259 return ' WHERE ' . implode($where, " AND ");
260 } else {
261 return '';
262 }
263 // WE know it's totally reversed, so better use array_reverse than a SORT BY start DESC
264 }
265
266 // }}}
267
268 function handler_logger(&$page, $action = null, $arg = null) {
269 if ($action == 'session') {
270
271 // we are viewing a session
272 $res = XDB::query("SELECT ls.*, a.alias AS username, sa.alias AS suer
273 FROM logger.sessions AS ls
274 LEFT JOIN aliases AS a ON (a.id = ls.uid AND a.type='a_vie')
275 LEFT JOIN aliases AS sa ON (sa.id = ls.suid AND sa.type='a_vie')
276 WHERE ls.id = {?}", $arg);
277
278 $page->assign('session', $a = $res->fetchOneAssoc());
279
280 $res = XDB::iterator('SELECT a.text, e.data, e.stamp
281 FROM logger.events AS e
282 LEFT JOIN logger.actions AS a ON e.action=a.id
283 WHERE e.session={?}', $arg);
284 while ($myarr = $res->next()) {
285 $page->append('events', $myarr);
286 }
287
288 } else {
289 $loguser = $action == 'user' ? $arg : Env::v('loguser');
290
291 $res = XDB::query('SELECT id FROM aliases WHERE alias={?}',
292 $loguser);
293 $loguid = $res->fetchOneCell();
294
295 if ($loguid) {
296 $year = Env::i('year');
297 $month = Env::i('month');
298 $day = Env::i('day');
299 } else {
300 $year = Env::i('year', intval(date('Y')));
301 $month = Env::i('month', intval(date('m')));
302 $day = Env::i('day', intval(date('d')));
303 }
304
305 if (!$year)
306 $month = 0;
307 if (!$month)
308 $day = 0;
309
310 // smarty assignments
311 // retrieve available years
312 $page->assign('years', $this->_getYears());
313 $page->assign('year', $year);
314
315 // retrieve available months for the current year
316 $page->assign('months', $this->_getMonths($year));
317 $page->assign('month', $month);
318
319 // retrieve available days for the current year and month
320 $page->assign('days', $this->_getDays($year, $month));
321 $page->assign('day', $day);
322
323 $page->assign('loguser', $loguser);
324 // smarty assignments
325
326 if ($loguid || $year) {
327
328 // get the requested sessions
329 $where = $this->_makeWhere($year, $month, $day, $loguid);
330 $select = "SELECT s.id, s.start, s.uid,
331 a.alias as username
332 FROM logger.sessions AS s
333 LEFT JOIN aliases AS a ON (a.id = s.uid AND a.type='a_vie')
334 $where
335 ORDER BY start DESC";
336 $res = XDB::iterator($select);
337
338 $sessions = array();
339 while ($mysess = $res->next()) {
340 $mysess['events'] = array();
341 $sessions[$mysess['id']] = $mysess;
342 }
343 array_reverse($sessions);
344
345 // attach events
346 $sql = "SELECT s.id, a.text
347 FROM logger.sessions AS s
348 LEFT JOIN logger.events AS e ON(e.session=s.id)
349 INNER JOIN logger.actions AS a ON(a.id=e.action)
350 $where";
351
352 $res = XDB::iterator($sql);
353 while ($event = $res->next()) {
354 array_push($sessions[$event['id']]['events'], $event['text']);
355 }
356 $page->assign_by_ref('sessions', $sessions);
357 } else {
358 $page->assign('msg_nofilters', "Sélectionner une annuée et/ou un utilisateur");
359 }
360 }
361
362 $page->changeTpl('admin/logger-view.tpl');
363
364 $page->setTitle('Administration - Logs des sessions');
365 }
366
367 function handler_user(&$page, $login = false)
368 {
369 global $globals;
370 $page->changeTpl('admin/utilisateurs.tpl');
371 $page->setTitle('Administration - Compte');
372
373 if (S::suid()) {
374 $page->kill("Déjà en SUID !!!");
375 }
376
377 // Loads the user identity using the environment.
378 $user = User::get($login);
379 $login = $user->login();
380 $registered = ($user->state != 'pending');
381
382 // Form processing
383 if (!empty($_POST)) {
384 S::assert_xsrf_token();
385 if (Post::has('uid') && Post::i('uid') != $user->id()) {
386 $page->kill('Une erreur s\'est produite');
387 }
388 }
389
390 // Handles specific requests (AX sync, su, ...).
391 if(Post::has('logs_account')) {
392 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
393 }
394
395 if(Post::has('su_button') && $registered) {
396 if (!Platal::session()->startSUID($user)) {
397 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->login());
398 } else {
399 pl_redirect("");
400 }
401 }
402
403 // Account Form {{{
404 $to_update = array();
405 if (Post::has('disable_weak_access')) {
406 $to_update['weak_password'] = null;
407 } else if (Post::has('update_account')) {
408 if (Post::s('full_name') != $user->fullName()) {
409 // XXX: Update profile if a profile is associated
410 $to_update['full_name'] = Post::s('full_name');
411 }
412 if (Post::s('display_name') != $user->displayName()) {
413 // XXX: Update profile if a profile is associated
414 $to_update['display_name'] = Post::s('display_name');
415 }
416 if (Post::s('sex') != ($user->isFemale() ? 'female' : 'male')) {
417 $to_update['sex'] = Post::s('sex');
418 }
419 if (!Post::blank('hashpass')) {
420 $to_update['password'] = Post::s('hashpass');
421 }
422 if (!Post::blank('weak_password')) {
423 $to_update['weak_password'] = Post::s('weak_password');
424 }
425 if (Post::i('token_access', 0) != ($user->token_access ? 1 : 0)) {
426 $to_update['token'] = Post::i('token_access') ? rand_url_id(16) : null;
427 }
428 if (Post::i('skin', 0) != $user->skin) {
429 $to_update['skin'] = Post::i('skin', 0);
430 if ($to_update['skin'] == 0) {
431 $to_update['skin'] = null;
432 }
433 }
434 if (Post::s('state') != $user->state) {
435 $to_update['state'] = Post::s('state');
436 }
437 if (Post::i('is_admin', 0) != ($user->is_admin ? 1 : 0)) {
438 $to_update['is_admin'] = Post::b('is_admin');
439 }
440 if (Post::s('type') != $user->type) {
441 $to_update['type'] = Post::s('type');
442 }
443 if (Post::i('watch', 0) != ($user->watch ? 1 : 0)) {
444 $to_update['flags'] = new PlFlagset();
445 $to_update['flags']->addFlag('watch', Post::i('watch'));
446 }
447 if (Post::t('comment') != $user->comment) {
448 $to_update['comment'] = Post::blank('comment') ? null : Post::t('comment');
449 }
450 }
451 if (!empty($to_update)) {
452 $set = array();
453 foreach ($to_update as $k => $value) {
454 $set[] = XDB::format($k . ' = {?}', $value);
455 }
456 XDB::execute('UPDATE accounts
457 SET ' . implode(', ', $set) . '
458 WHERE uid = ' . XDB::format('{?}', $user->id()));
459 $page->trigSuccess('Données du compte mise à jour avec succès');
460 $user = User::getWithUID($user->id());
461 }
462 // }}}
463
464 // Profile form {{{
465 if (Post::has('add_profile') || Post::has('del_profile') || Post::has('owner')) {
466 if (Post::i('del_profile', 0) != 0) {
467 XDB::execute('DELETE FROM account_profiles
468 WHERE uid = {?} AND pid = {?}',
469 $user->id(), Post::i('del_profile'));
470 } else if (!Post::blank('new_profile')) {
471 $profile = Profile::get(Post::t('new_profile'));
472 if (!$profile) {
473 $page->trigError('Le profil ' . Post::t('new_profile') . ' n\'existe pas');
474 } else {
475 XDB::execute('INSERT IGNORE INTO account_profiles (uid, pid)
476 VALUES ({?}, {?})',
477 $user->id(), $profile->id());
478 }
479 }
480 XDB::execute('UPDATE account_profiles
481 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
482 WHERE uid = {?}',
483 Post::i('owner'), $user->id());
484 }
485 // }}}
486
487 // Email forwards form {{{
488 require_once("emails.inc.php");
489 $redirect = ($registered ? new Redirect($user) : null);
490 if (Post::has('add_fwd')) {
491 $email = Post::t('email');
492 if (!isvalid_email_redirection($email)) {
493 $page->trigError("Email non valide: $email");
494 } else {
495 $redirect->add_email($email);
496 $page->trigSuccess("Ajout de $email effectué");
497 }
498 } else if (!Post::blank('del_fwd')) {
499 $redirect->delete_email(Post::t('del_fwd'));
500 } else if (!Post::blank('activate_fwd')) {
501 $redirect->modify_one_email(Post::t('activate_fwd', true));
502 } else if (!Post::blank('deactivate_fwd')) {
503 $redirect->modify_one_email(Post::t('deactivate_fwd', false));
504 } else if (Post::has('disable_fwd')) {
505 $redirect->disable();
506 } else if (Post::has('enable_fwd')) {
507 $redirect->enable();
508 } else if (!Post::blank('clean_fwd')) {
509 $redirect->clean_errors(Post::t('clean_fwd'));
510 }
511 // }}}
512
513 // Email alias form {{{
514 if (Post::has('add_alias')) {
515 // Splits new alias in user and fqdn.
516 $alias = Env::t('email');
517 if (strpos($alias, '@') !== false) {
518 list($alias, $domain) = explode('@', $alias);
519 } else {
520 $domain = $globals->mail->domain;
521 }
522
523 // Checks for alias' user validity.
524 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
525 $page->trigError("'$alias' n'est pas un alias valide");
526 }
527
528 // Eventually adds the alias to the right domain.
529 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
530 $req = new AliasReq($user, $alias, 'Admin request', false);
531 if ($req->commit()) {
532 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué");
533 } else {
534 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué");
535 }
536 } elseif ($domain == $globals->mail->domain || $domain == $globals->mail->domain2) {
537 $res = XDB::execute("INSERT INTO aliases (id, alias, type)
538 VALUES ({?}, {?}, 'alias')",
539 $user->id(), $alias);
540 $page->trigSuccess("Nouvel alias '$alias' ajouté");
541 } else {
542 $page->trigError("Le domaine '$domain' n'est pas valide");
543 }
544 } else if (!Post::blank('del_alias')) {
545 XDB::execute("DELETE FROM aliases
546 WHERE id = {?} AND alias = {?} AND
547 type NOT IN ('a_vie', 'homonyme')",
548 $user->id(), $val);
549 XDB::execute("UPDATE emails
550 SET rewrite = ''
551 WHERE uid = {?} AND rewrite LIKE CONCAT({?}, '@%')",
552 $user->id(), $val);
553 fix_bestalias($user);
554 $page->trigSuccess("L'alias '$val' a été supprimé");
555 } else if (!Post::blank('best')) {
556 XDB::execute("UPDATE aliases
557 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
558 WHERE id = {?}", $user->id());
559 XDB::execute("UPDATE aliases
560 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
561 WHERE id = {?} AND alias = {?}", $user->id(), $val);
562 // As having a non-null bestalias value is critical in
563 // plat/al's code, we do an a posteriori check on the
564 // validity of the bestalias.
565 fix_bestalias($user);
566 }
567 // }}}
568
569 // Forum form {{{
570 if (Post::has('b_edit')) {
571 XDB::execute("DELETE FROM forum_innd
572 WHERE uid = {?}", $user->id());
573 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
574 XDB::execute("INSERT INTO forum_innd
575 SET ipmin = '0', ipmax = '4294967295',
576 write_perm = {?}, read_perm = {?},
577 comment = {?}, priority = '200', uid = {?}",
578 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
579 }
580 }
581 // }}}
582
583
584 $page->addJsLink('ui.core.js');
585 $page->addJsLink('ui.tabs.js');
586
587
588 // Displays last login and last host information.
589 $res = XDB::query("SELECT start, host
590 FROM logger.sessions
591 WHERE uid = {?} AND suid = 0
592 ORDER BY start DESC
593 LIMIT 1", $user->id());
594 list($lastlogin,$host) = $res->fetchOneRow();
595 $page->assign('lastlogin', $lastlogin);
596 $page->assign('host', $host);
597
598 // Display active aliases.
599 $page->assign('virtuals', $user->emailAliases());
600 $page->assign('aliases', XDB::iterator("SELECT alias, type='a_vie' AS for_life,
601 FIND_IN_SET('bestalias',flags) AS best, expire
602 FROM aliases
603 WHERE id = {?} AND type != 'homonyme'
604 ORDER BY type != 'a_vie'", $user->id()));
605 $page->assign('account_types', XDB::iterator('SELECT * FROM account_types ORDER BY type'));
606 $page->assign('skins', XDB::iterator('SELECT id, name FROM skins ORDER BY name'));
607 $page->assign('profiles', XDB::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
608 FROM account_profiles AS ap
609 INNER JOIN profiles AS p ON (ap.pid = p.pid)
610 WHERE ap.uid = {?}', $user->id()));
611
612 // Displays email redirection and the general profile.
613 if ($registered && $redirect) {
614 $page->assign('emails', $redirect->emails);
615 }
616
617 $page->assign('mr', $mr);
618 $page->assign('user', $user);
619
620 // Displays forum bans.
621 $res = XDB::query("SELECT write_perm, read_perm, comment
622 FROM forum_innd
623 WHERE uid = {?}", $user->id());
624 $bans = $res->fetchOneAssoc();
625 $page->assign('bans', $bans);
626 }
627
628 function getHruid($line, $key)
629 {
630 var_dump($line);
631 if (!isset($line['nom']) || !isset($line['prenom']) || !isset($line['promo'])) {
632 return null;
633 }
634 return make_forlife($line['prenom'], $line['nom'], $line['promo']);
635 }
636
637 function getMatricule($line, $key)
638 {
639 $mat = $line['matricule'];
640 $year = intval(substr($mat, 0, 3));
641 $rang = intval(substr($mat, 3, 3));
642 if ($year > 200) { $year /= 10; };
643 if ($year < 96) {
644 return null;
645 } else {
646 return sprintf('%04u%04u', 1900+$year, $rang);
647 }
648 }
649
650 function handler_promo(&$page, $action = null, $promo = null)
651 {
652 if (Env::has('promo')) {
653 if(Env::i('promo') > 1900 && Env::i('promo') < 2050) {
654 $action = Env::v('valid_promo') == 'Ajouter des membres' ? 'add' : 'ax';
655 pl_redirect('admin/promo/' . $action . '/' . Env::i('promo'));
656 } else {
657 $page->trigError('Promotion non valide.');
658 }
659 }
660
661 $page->changeTpl('admin/promo.tpl');
662 if ($promo > 1900 && $promo < 2050 && ($action == 'add' || $action == 'ax')) {
663 $page->assign('promo', $promo);
664 } else {
665 return;
666 }
667
668 $importer = new CSVImporter('auth_user_md5', 'matricule');
669 $importer->registerFunction('matricule', 'matricule Ecole vers X.org', array($this, 'getMatricule'));
670 switch ($action) {
671 case 'add':
672 $fields = array('hruid', 'nom', 'nom_ini', 'prenom', 'naissance_ini',
673 'prenom_ini', 'promo', 'promo_sortie', 'flags',
674 'matricule', 'matricule_ax', 'perms');
675 $importer->forceValue('hruid', array($this, 'getHruid'));
676 $importer->forceValue('promo', $promo);
677 $importer->forceValue('promo_sortie', $promo + 3);
678 break;
679 case 'ax':
680 $fields = array('matricule', 'matricule_ax');
681 break;
682 }
683 $importer->apply($page, "admin/promo/$action/$promo", $fields);
684 }
685
686 function handler_homonyms(&$page, $op = 'list', $target = null)
687 {
688 $page->changeTpl('admin/homonymes.tpl');
689 $page->setTitle('Administration - Homonymes');
690 $this->load("homonyms.inc.php");
691
692 if ($target) {
693 $user = User::getSilent($target);
694 if (!$user || !($loginbis = select_if_homonyme($user))) {
695 $target = 0;
696 } else {
697 $page->assign('user', $user);
698 $page->assign('loginbis',$loginbis);
699 }
700 }
701
702 $page->assign('op', $op);
703 $page->assign('target', $target);
704
705 // on a un $target valide, on prepare les mails
706 if ($target) {
707 // on examine l'op a effectuer
708 switch ($op) {
709 case 'mail':
710 S::assert_xsrf_token();
711
712 send_warning_homonyme($user, $loginbis);
713 switch_bestalias($user, $loginbis);
714 $op = 'list';
715 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
716 break;
717
718 case 'correct':
719 S::assert_xsrf_token();
720
721 switch_bestalias($user, $loginbis);
722 XDB::execute("UPDATE aliases
723 SET type = 'homonyme', expire=NOW()
724 WHERE alias = {?}", $loginbis);
725 XDB::execute("REPLACE INTO homonymes (homonyme_id,user_id)
726 VALUES ({?}, {?})", $target, $target);
727 send_robot_homonyme($user, $loginbis);
728 $op = 'list';
729 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
730 break;
731 }
732 }
733
734 if ($op == 'list') {
735 $res = XDB::iterator(
736 "SELECT a.alias AS homonyme, s.alias AS forlife,
737 IF(h.homonyme_id = s.id, a.expire, NULL) AS expire,
738 IF(h.homonyme_id = s.id, a.type, NULL) AS type,
739 ac.uid AS user_id
740 FROM aliases AS a
741 LEFT JOIN homonymes AS h ON (h.homonyme_id = a.id)
742 INNER JOIN aliases AS s ON (s.id = h.user_id AND s.type='a_vie')
743 INNER JOIN accounts AS ac ON (ac.uid = a.id)
744 WHERE a.type = 'homonyme' OR a.expire != ''
745 ORDER BY a.alias, forlife");
746 $hnymes = Array();
747 while ($tab = $res->next()) {
748 $hnymes[$tab['homonyme']][] = $tab;
749 }
750 $page->assign_by_ref('hnymes',$hnymes);
751 }
752 }
753
754 function handler_deaths(&$page, $promo = 0, $validate = false)
755 {
756 $page->changeTpl('admin/deces_promo.tpl');
757 $page->setTitle('Administration - Deces');
758
759 if (!$promo)
760 $promo = Env::i('promo');
761 if (Env::has('sub10')) $promo -= 10;
762 if (Env::has('sub01')) $promo -= 1;
763 if (Env::has('add01')) $promo += 1;
764 if (Env::has('add10')) $promo += 10;
765
766 $page->assign('promo',$promo);
767
768 if ($validate) {
769 S::assert_xsrf_token();
770
771 $res = XDB::iterRow("SELECT user_id,matricule,nom,prenom,deces FROM auth_user_md5 WHERE promo = {?}", $promo);
772 while (list($uid,$mat,$nom,$prenom,$deces) = $res->next()) {
773 $val = Env::v($mat);
774 if($val == $deces || empty($val)) {
775 continue;
776 }
777
778 XDB::execute('UPDATE auth_user_md5 SET deces={?} WHERE matricule = {?}', $val, $mat);
779 $page->trigSuccess('Ajout du décès de ' . $prenom . " " . $nom . ' le ' . $val . '.');
780 if($deces == '0000-00-00' || empty($deces)) {
781 require_once('notifs.inc.php');
782 register_watch_op($uid, WATCH_DEATH, $val);
783 require_once('user.func.inc.php');
784 user_clear_all_subs($uid, false); // by default, dead ppl do not loose their email
785 }
786 }
787 }
788
789 $res = XDB::iterator('SELECT matricule, nom, prenom, deces FROM auth_user_md5 WHERE promo = {?} ORDER BY nom,prenom', $promo);
790 $page->assign('decedes', $res);
791 }
792
793 function handler_dead_but_active(&$page)
794 {
795 $page->changeTpl('admin/dead_but_active.tpl');
796 $page->setTitle('Administration - Décédés');
797
798 $res = XDB::iterator(
799 "SELECT u.promo, u.nom, u.prenom, u.deces, u.matricule_ax, u.hruid, DATE(MAX(s.start)) AS last
800 FROM auth_user_md5 AS u
801 LEFT JOIN logger.sessions AS s ON (s.uid = u.user_id AND suid = 0)
802 WHERE perms IN ('admin', 'user') AND deces <> 0
803 GROUP BY u.user_id
804 ORDER BY u.promo, u.nom");
805 $page->assign('dead', $res);
806 }
807
808 function handler_validate(&$page, $action = 'list', $id = null)
809 {
810 $page->changeTpl('admin/valider.tpl');
811 $page->setTitle('Administration - Valider une demande');
812 $page->addCssLink('nl.css');
813 $page->addJsLink('ajax.js');
814 require_once("validations.inc.php");
815
816
817 if ($action == 'edit' and !is_null($id)) {
818 $page->assign('preview_id', $id);
819 }
820
821 if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
822 S::assert_xsrf_token();
823
824 $req = Validate::get_typed_request(Env::v('uid'), Env::v('type'), Env::v('stamp'));
825 if ($req) {
826 $req->handle_formu();
827 } else {
828 $page->trigWarning('La validation a déjà été effectuée.');
829 }
830 }
831
832 $r = XDB::iterator('SHOW COLUMNS FROM requests_answers');
833 while (($a = $r->next()) && $a['Field'] != 'category');
834 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
835
836 $hidden = array();
837 $res = XDB::query('SELECT hidden_requests FROM requests_hidden WHERE user_id = {?}', S::v('uid'));
838 $hide_requests = $res->fetchOneCell();
839 if (Post::has('hide')) {
840 $hide = array();
841 foreach ($categories as $cat)
842 if (!Post::v($cat)) {
843 $hidden[$cat] = 1;
844 $hide[] = $cat;
845 }
846 $hide_requests = join(',', $hide);
847 XDB::query('REPLACE INTO requests_hidden (user_id, hidden_requests) VALUES({?}, {?})',
848 S::v('uid'), $hide_requests);
849 } elseif ($hide_requests) {
850 foreach (explode(',', $hide_requests) as $hide_type)
851 $hidden[$hide_type] = true;
852 }
853 $page->assign('hide_requests', $hidden);
854
855 // Update the count of item to validate here... useful in development configuration
856 // where several copies of the site use the same DB, but not the same "dynamic configuration"
857 global $globals;
858 $globals->updateNbValid();
859 $page->assign('vit', new ValidateIterator());
860 }
861
862 function handler_validate_answers(&$page, $action = 'list', $id = null)
863 {
864 $page->setTitle('Administration - Réponses automatiques de validation');
865 $page->assign('title', 'Gestion des réponses automatiques');
866 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
867 $table_editor->describe('category','catégorie',true);
868 $table_editor->describe('title','titre',true);
869 $table_editor->describe('answer','texte',false);
870 $table_editor->apply($page, $action, $id);
871 }
872
873 function handler_skins(&$page, $action = 'list', $id = null)
874 {
875 $page->setTitle('Administration - Skins');
876 $page->assign('title', 'Gestion des skins');
877 $table_editor = new PLTableEditor('admin/skins','skins','id');
878 $table_editor->describe('name','nom',true);
879 $table_editor->describe('skin_tpl','nom du template',true);
880 $table_editor->describe('auteur','auteur',false);
881 $table_editor->describe('comment','commentaire',true);
882 $table_editor->describe('date','date',false);
883 $table_editor->describe('ext','extension du screenshot',false);
884 $table_editor->apply($page, $action, $id);
885 }
886
887 function handler_postfix_blacklist(&$page, $action = 'list', $id = null)
888 {
889 $page->setTitle('Administration - Postfix : Blacklist');
890 $page->assign('title', 'Blacklist de postfix');
891 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true);
892 $table_editor->describe('reject_text','Texte de rejet',true);
893 $table_editor->describe('email','email',true);
894 $table_editor->apply($page, $action, $id);
895 }
896
897 function handler_postfix_whitelist(&$page, $action = 'list', $id = null)
898 {
899 $page->setTitle('Administration - Postfix : Whitelist');
900 $page->assign('title', 'Whitelist de postfix');
901 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true);
902 $table_editor->describe('email','email',true);
903 $table_editor->apply($page, $action, $id);
904 }
905
906 function handler_mx_broken(&$page, $action = 'list', $id = null)
907 {
908 $page->setTitle('Administration - MX Défaillants');
909 $page->assign('title', 'MX Défaillant');
910 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true);
911 $table_editor->describe('host', 'Masque', true);
912 $table_editor->describe('state', 'Niveau', true);
913 $table_editor->describe('text', 'Description du problème', false);
914 $table_editor->apply($page, $action, $id);
915 }
916
917 function handler_logger_actions(&$page, $action = 'list', $id = null)
918 {
919 $page->setTitle('Administration - Actions');
920 $page->assign('title', 'Gestion des actions de logger');
921 $table_editor = new PLTableEditor('admin/logger/actions','logger.actions','id');
922 $table_editor->describe('text','intitulé',true);
923 $table_editor->describe('description','description',true);
924 $table_editor->apply($page, $action, $id);
925 }
926
927 function handler_downtime(&$page, $action = 'list', $id = null)
928 {
929 $page->setTitle('Administration - Coupures');
930 $page->assign('title', 'Gestion des coupures');
931 $table_editor = new PLTableEditor('admin/downtime','coupures','id');
932 $table_editor->describe('debut','date',true);
933 $table_editor->describe('duree','durée',false);
934 $table_editor->describe('resume','résumé',true);
935 $table_editor->describe('services','services affectés',true);
936 $table_editor->describe('description','description',false);
937 $table_editor->apply($page, $action, $id);
938 }
939
940 function handler_account_types(&$page, $action = 'list', $id = null)
941 {
942 $page->setTitle('Administration - Types de comptes');
943 $page->assign('title', 'Gestion des types de comptes');
944 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true);
945 $table_editor->describe('type', 'Catégorie', true);
946 $table_editor->describe('perms', 'Permissions associées', true);
947 $table_editor->apply($page, $action, $id);
948 }
949
950 function handler_wiki(&$page, $action = 'list', $wikipage = null, $wikipage2 = null)
951 {
952 if (S::hasAuthToken()) {
953 $page->setRssLink('Changement Récents',
954 '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::v('token'));
955 }
956
957 // update wiki perms
958 if ($action == 'update') {
959 S::assert_xsrf_token();
960
961 $perms_read = Post::v('read');
962 $perms_edit = Post::v('edit');
963 if ($perms_read || $perms_edit) {
964 foreach ($_POST as $wiki_page => $val) {
965 if ($val == 'on') {
966 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
967 if ($wp->setPerms($perms_read ? $perms_read : $wp->readPerms(),
968 $perms_edit ? $perms_edit : $wp->writePerms())) {
969 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
970 } else {
971 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
972 }
973 }
974 }
975 }
976 } else if ($action != 'list' && !empty($wikipage)) {
977 $wp = new PlWikiPage($wikipage);
978 S::assert_xsrf_token();
979
980 if ($action == 'delete') {
981 if ($wp->delete()) {
982 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
983 } else {
984 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
985 }
986 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
987 if ($changedLinks = $wp->rename($wikipage2)) {
988 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
989 if (is_numeric($changedLinks)) {
990 $s .= $changedLinks.' lien'.(($changedLinks>1)?'s ont été modifiés.':' a été modifié.');
991 }
992 $page->trigSuccess($s);
993 } else {
994 $page->trigError("Impossible de déplacer la page ".$wikipage);
995 }
996 }
997 }
998
999 $perms = PlWikiPage::permOptions();
1000
1001 // list wiki pages and their perms
1002 $wiki_pages = PlWikiPage::listPages();
1003 ksort($wiki_pages);
1004 $wiki_tree = array();
1005 foreach ($wiki_pages as $file => $desc) {
1006 list($cat, $name) = explode('.', $file);
1007 if (!isset($wiki_tree[$cat])) {
1008 $wiki_tree[$cat] = array();
1009 }
1010 $wiki_tree[$cat][$name] = $desc;
1011 }
1012
1013 $page->changeTpl('admin/wiki.tpl');
1014 $page->assign('wiki_pages', $wiki_tree);
1015 $page->assign('perms_opts', $perms);
1016 }
1017
1018 function handler_ipwatch(&$page, $action = 'list', $ip = null)
1019 {
1020 $page->changeTpl('admin/ipwatcher.tpl');
1021
1022 $states = array('safe' => 'Ne pas surveiller',
1023 'unsafe' => 'Surveiller les inscriptions',
1024 'dangerous' => 'Surveiller tous les accès',
1025 'ban' => 'Bannir cette adresse');
1026 $page->assign('states', $states);
1027
1028 switch (Post::v('action')) {
1029 case 'create':
1030 if (trim(Post::v('ipN')) != '') {
1031 S::assert_xsrf_token();
1032 Xdb::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1033 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1034 ip_to_uint(trim(Post::v('ipN'))), ip_to_uint(trim(Post::v('maskN'))),
1035 Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
1036 };
1037 break;
1038
1039 case 'edit':
1040 S::assert_xsrf_token();
1041 Xdb::execute('UPDATE ip_watch
1042 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1043 WHERE ip = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'),
1044 ip_to_uint(Post::v('maskN')), ip_to_uint(Post::v('ipN')));
1045 break;
1046
1047 default:
1048 if ($action == 'delete' && !is_null($ip)) {
1049 S::assert_xsrf_token();
1050 Xdb::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1051 }
1052 }
1053 if ($action != 'create' && $action != 'edit') {
1054 $action = 'list';
1055 }
1056 $page->assign('action', $action);
1057
1058 if ($action == 'list') {
1059 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1060 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1061 IF(w.ip = s.ip, s.host, s.forward_host)),
1062 w.mask, w.detection, w.state, a.hruid
1063 FROM ip_watch AS w
1064 LEFT JOIN logger.sessions AS s ON (s.ip = w.ip)
1065 LEFT JOIN logger.sessions AS s2 ON (s2.forward_ip = w.ip)
1066 LEFT JOIN accounts AS a ON (a.uid = s.uid)
1067 GROUP BY w.ip, a.hruid
1068 ORDER BY w.state, w.ip, a.hruid";
1069 $it = Xdb::iterRow($sql);
1070
1071 $table = array();
1072 $props = array();
1073 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1074 $ip = uint_to_ip($ip);
1075 $mask = uint_to_ip($mask);
1076 if (count($props) == 0 || $props['ip'] != $ip) {
1077 if (count($props) > 0) {
1078 $table[] = $props;
1079 }
1080 $props = array('ip' => $ip,
1081 'mask' => $mask,
1082 'host' => $host,
1083 'detection' => $date,
1084 'state' => $state,
1085 'users' => array($hruid));
1086 } else {
1087 $props['users'][] = $hruid;
1088 }
1089 }
1090 if (count($props) > 0) {
1091 $table[] = $props;
1092 }
1093 $page->assign('table', $table);
1094 } elseif ($action == 'edit') {
1095 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1096 a1.hruid AS edit, a2.hruid AS hruid, s.host
1097 FROM ip_watch AS w
1098 LEFT JOIN accounts AS a1 ON (a1.uid = w.uid)
1099 LEFT JOIN logger.sessions AS s ON (w.ip = s.ip)
1100 LEFT JOIN accounts AS a2 ON (a2.uid = s.uid)
1101 WHERE w.ip = {?}
1102 GROUP BY a2.hruid
1103 ORDER BY a2.hruid";
1104 $it = Xdb::iterRow($sql, ip_to_uint($ip));
1105
1106 $props = array();
1107 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1108 if (count($props) == 0) {
1109 $props = array('ip' => $ip,
1110 'mask' => uint_to_ip($mask),
1111 'host' => $host,
1112 'detection' => $detection,
1113 'state' => $state,
1114 'last' => $last,
1115 'description' => $description,
1116 'edit' => $edit,
1117 'users' => array($hruid));
1118 } else {
1119 $props['users'][] = $hruid;
1120 }
1121 }
1122 $page->assign('ip', $props);
1123 }
1124 }
1125
1126 function handler_icons(&$page)
1127 {
1128 $page->changeTpl('admin/icons.tpl');
1129 $dh = opendir('../htdocs/images/icons');
1130 if (!$dh) {
1131 $page->trigError('Dossier des icones introuvables.');
1132 }
1133 $icons = array();
1134 while (($file = readdir($dh)) !== false) {
1135 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1136 array_push($icons, substr($file, 0, -4));
1137 }
1138 }
1139 sort($icons);
1140 $page->assign('icons', $icons);
1141 }
1142
1143 function handler_accounts(&$page)
1144 {
1145 $page->changeTpl('admin/accounts.tpl');
1146 $page->assign('disabled', XDB::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1147 a.state = \'disabled\' AS disabled, a.comment
1148 FROM accounts AS a
1149 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1150 ORDER BY a.hruid'));
1151 $page->assign('admins', XDB::iterator('SELECT a.hruid
1152 FROM accounts AS a
1153 WHERE a.is_admin
1154 ORDER BY a.hruid'));
1155 }
1156 }
1157
1158 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1159 ?>