Fixes the admin/user page that had disappear
[platal.git] / modules / admin.php
CommitLineData
86f0a6af 1<?php
2/***************************************************************************
9f5bd98e 3 * Copyright (C) 2003-2010 Polytechnique.org *
86f0a6af 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
22class AdminModule extends PLModule
23{
24 function handlers()
25 {
26 return array(
eb5a266d 27 'phpinfo' => $this->make_hook('phpinfo', AUTH_MDP, 'admin'),
d1e61677 28 'get_rights' => $this->make_hook('get_rights', AUTH_MDP, 'admin'),
eb5a266d 29 'admin' => $this->make_hook('default', AUTH_MDP, 'admin'),
eb5a266d
SJ
30 'admin/dead-but-active' => $this->make_hook('dead_but_active', AUTH_MDP, 'admin'),
31 'admin/deaths' => $this->make_hook('deaths', AUTH_MDP, 'admin'),
32 'admin/downtime' => $this->make_hook('downtime', AUTH_MDP, 'admin'),
33 'admin/homonyms' => $this->make_hook('homonyms', AUTH_MDP, 'admin'),
34 'admin/logger' => $this->make_hook('logger', AUTH_MDP, 'admin'),
35 'admin/logger/actions' => $this->make_hook('logger_actions', AUTH_MDP, 'admin'),
36 'admin/postfix/blacklist' => $this->make_hook('postfix_blacklist', AUTH_MDP, 'admin'),
37 'admin/postfix/delayed' => $this->make_hook('postfix_delayed', AUTH_MDP, 'admin'),
e7ae7df9 38 'admin/postfix/regexp_bounces' => $this->make_hook('postfix_regexpsbounces', AUTH_MDP, 'admin'),
eb5a266d
SJ
39 'admin/postfix/whitelist' => $this->make_hook('postfix_whitelist', AUTH_MDP, 'admin'),
40 'admin/mx/broken' => $this->make_hook('mx_broken', AUTH_MDP, 'admin'),
41 'admin/skins' => $this->make_hook('skins', AUTH_MDP, 'admin'),
eb5a266d 42 'admin/user' => $this->make_hook('user', AUTH_MDP, 'admin'),
e02d9fbb 43 'admin/add_accounts' => $this->make_hook('add_accounts', AUTH_MDP, 'admin'),
eb5a266d
SJ
44 'admin/validate' => $this->make_hook('validate', AUTH_MDP, 'admin'),
45 'admin/validate/answers' => $this->make_hook('validate_answers', AUTH_MDP, 'admin'),
46 'admin/wiki' => $this->make_hook('wiki', AUTH_MDP, 'admin'),
47 'admin/ipwatch' => $this->make_hook('ipwatch', AUTH_MDP, 'admin'),
48 'admin/icons' => $this->make_hook('icons', AUTH_MDP, 'admin'),
49 'admin/accounts' => $this->make_hook('accounts', AUTH_MDP, 'admin'),
d1e61677 50 'admin/account/types' => $this->make_hook('account_types', AUTH_MDP, 'admin'),
429e4a4b 51 'admin/jobs' => $this->make_hook('jobs', AUTH_MDP, 'admin'),
86f0a6af 52 );
53 }
54
5f9a40b4 55 function handler_phpinfo(&$page)
56 {
57 phpinfo();
58 exit;
59 }
60
866bd535
FB
61 function handler_get_rights(&$page, $level)
62 {
63 if (S::suid()) {
64 $page->kill('Déjà en SUID');
65 }
66 $user =& S::user();
67 Platal::session()->startSUID($user, $level);
68
69 pl_redirect('/');
70 }
71
86f0a6af 72 function handler_default(&$page)
73 {
74 $page->changeTpl('admin/index.tpl');
46f272fe 75 $page->setTitle('Administration');
86f0a6af 76 }
77
78 function handler_postfix_delayed(&$page)
79 {
80 $page->changeTpl('admin/postfix_delayed.tpl');
46f272fe 81 $page->setTitle('Administration - Postfix : Retardés');
86f0a6af 82
83 if (Env::has('del')) {
84 $crc = Env::v('crc');
85 XDB::execute("UPDATE postfix_mailseen SET release = 'del' WHERE crc = {?}", $crc);
6bb2f79a 86 $page->trigSuccess($crc . " verra tous ses emails supprimés&nbsp;!");
86f0a6af 87 } elseif (Env::has('ok')) {
88 $crc = Env::v('crc');
89 XDB::execute("UPDATE postfix_mailseen SET release = 'ok' WHERE crc = {?}", $crc);
6bb2f79a 90 $page->trigSuccess($crc . " a le droit de passer&nbsp;!");
86f0a6af 91 }
92
93 $sql = XDB::iterator(
94 "SELECT crc, nb, update_time, create_time,
77fcaa3f
SJ
95 FIND_IN_SET('del', p.release) AS del,
96 FIND_IN_SET('ok', p.release) AS ok
97 FROM postfix_mailseen AS p
86f0a6af 98 WHERE nb >= 30
77fcaa3f 99 ORDER BY p.release != ''");
86f0a6af 100
101 $page->assign_by_ref('mails', $sql);
102 }
103
104 function handler_postfix_regexpsbounces(&$page, $new = null) {
105 $page->changeTpl('admin/emails_bounces_re.tpl');
46f272fe 106 $page->setTitle('Administration - Postfix : Regexps Bounces');
86f0a6af 107 $page->assign('new', $new);
108
109 if (Post::has('submit')) {
110 foreach (Env::v('lvl') as $id=>$val) {
111 XDB::query(
112 "REPLACE INTO emails_bounces_re (id,pos,lvl,re,text) VALUES ({?}, {?}, {?}, {?}, {?})",
113 $id, $_POST['pos'][$id], $_POST['lvl'][$id], $_POST['re'][$id], $_POST['text'][$id]
114 );
115 }
116 }
117
118 $page->assign('bre', XDB::iterator("SELECT * FROM emails_bounces_re ORDER BY pos"));
119 }
120
441e9e98 121 // {{{ logger view
86f0a6af 122
441e9e98 123 /** Retrieves the available days for a given year and month.
124 * Obtain a list of days of the given month in the given year
125 * that are within the range of dates that we have log entries for.
126 *
127 * @param integer year
128 * @param integer month
129 * @return array days in that month we have log entries covering.
130 * @private
131 */
132 function _getDays($year, $month)
133 {
134 // give a 'no filter' option
135 $months[0] = "----";
136
137 if ($year && $month) {
138 $day_max = Array(-1, 31, checkdate(2, 29, $year) ? 29 : 28 , 31,
139 30, 31, 30, 31, 31, 30, 31, 30, 31);
140 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
141 MONTH(MAX(start)), MONTH(MIN(start)),
142 DAYOFMONTH(MAX(start)),
143 DAYOFMONTH(MIN(start))
6586a74f 144 FROM log_sessions");
441e9e98 145 list($ymax, $ymin, $mmax, $mmin, $dmax, $dmin) = $res->fetchOneRow();
146
147 if (($year < $ymin) || ($year == $ymin && $month < $mmin)) {
148 return array();
149 }
150
151 if (($year > $ymax) || ($year == $ymax && $month > $mmax)) {
152 return array();
153 }
154
155 $min = ($year==$ymin && $month==$mmin) ? intval($dmin) : 1;
156 $max = ($year==$ymax && $month==$mmax) ? intval($dmax) : $day_max[$month];
157
158 for($i = $min; $i<=$max; $i++) {
159 $days[$i] = $i;
160 }
161 }
162 return $days;
163 }
164
165
166 /** Retrieves the available months for a given year.
167 * Obtains a list of month numbers that are within the timeframe that
168 * we have log entries for.
169 *
170 * @param integer year
171 * @return array List of month numbers we have log info for.
172 * @private
173 */
174 function _getMonths($year)
175 {
176 // give a 'no filter' option
177 $months[0] = "----";
178
179 if ($year) {
180 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
181 MONTH(MAX(start)), MONTH(MIN(start))
6586a74f 182 FROM log_sessions");
441e9e98 183 list($ymax, $ymin, $mmax, $mmin) = $res->fetchOneRow();
184
185 if (($year < $ymin) || ($year > $ymax)) {
186 return array();
187 }
188
189 $min = $year == $ymin ? intval($mmin) : 1;
190 $max = $year == $ymax ? intval($mmax) : 12;
191
192 for($i = $min; $i<=$max; $i++) {
193 $months[$i] = $i;
194 }
195 }
196 return $months;
197 }
198
199
200 /** Retrieves the available years.
201 * Obtains a list of years that we have log entries covering.
202 *
203 * @return array years we have log entries for.
204 * @private
205 */
206 function _getYears()
207 {
208 // give a 'no filter' option
209 $years[0] = "----";
210
211 // retrieve available years
6586a74f 212 $res = XDB::query("select YEAR(MAX(start)), YEAR(MIN(start)) FROM log_sessions");
441e9e98 213 list($max, $min) = $res->fetchOneRow();
214
215 for($i = intval($min); $i<=$max; $i++) {
216 $years[$i] = $i;
217 }
218 return $years;
219 }
220
221
222 /** Make a where clause to get a user's sessions.
223 * Prepare the where clause request that will retrieve the sessions.
224 *
225 * @param $year INTEGER Only get log entries made during the given year.
226 * @param $month INTEGER Only get log entries made during the given month.
227 * @param $day INTEGER Only get log entries made during the given day.
228 * @param $uid INTEGER Only get log entries referring to the given user ID.
229 *
230 * @return STRING the WHERE clause of a query, including the 'WHERE' keyword
231 * @private
232 */
233 function _makeWhere($year, $month, $day, $uid)
234 {
235 // start constructing the "where" clause
236 $where = array();
237
238 if ($uid)
239 array_push($where, "uid='$uid'");
240
241 // we were given at least a year
242 if ($year) {
243 if ($day) {
244 $dmin = mktime(0, 0, 0, $month, $day, $year);
245 $dmax = mktime(0, 0, 0, $month, $day+1, $year);
246 } elseif ($month) {
247 $dmin = mktime(0, 0, 0, $month, 1, $year);
248 $dmax = mktime(0, 0, 0, $month+1, 1, $year);
249 } else {
250 $dmin = mktime(0, 0, 0, 1, 1, $year);
251 $dmax = mktime(0, 0, 0, 1, 1, $year+1);
252 }
253 $where[] = "start >= " . date("Ymd000000", $dmin);
254 $where[] = "start < " . date("Ymd000000", $dmax);
255 }
256
257 if (!empty($where)) {
258 return ' WHERE ' . implode($where, " AND ");
259 } else {
260 return '';
261 }
262 // WE know it's totally reversed, so better use array_reverse than a SORT BY start DESC
263 }
264
265 // }}}
266
267 function handler_logger(&$page, $action = null, $arg = null) {
268 if ($action == 'session') {
269
270 // we are viewing a session
271 $res = XDB::query("SELECT ls.*, a.alias AS username, sa.alias AS suer
6586a74f 272 FROM log_sessions AS ls
fe13bc1d
FB
273 LEFT JOIN aliases AS a ON (a.uid = ls.uid AND a.type='a_vie')
274 LEFT JOIN aliases AS sa ON (sa.uid = ls.suid AND sa.type='a_vie')
441e9e98 275 WHERE ls.id = {?}", $arg);
276
277 $page->assign('session', $a = $res->fetchOneAssoc());
278
504ccd57 279 $res = XDB::iterator('SELECT a.text, e.data, e.stamp
6586a74f
FB
280 FROM log_events AS e
281 LEFT JOIN log_actions AS a ON e.action=a.id
441e9e98 282 WHERE e.session={?}', $arg);
283 while ($myarr = $res->next()) {
284 $page->append('events', $myarr);
285 }
286
287 } else {
288 $loguser = $action == 'user' ? $arg : Env::v('loguser');
289
fe13bc1d 290 $res = XDB::query('SELECT uid FROM aliases WHERE alias={?}',
441e9e98 291 $loguser);
292 $loguid = $res->fetchOneCell();
293
294 if ($loguid) {
295 $year = Env::i('year');
296 $month = Env::i('month');
297 $day = Env::i('day');
298 } else {
299 $year = Env::i('year', intval(date('Y')));
300 $month = Env::i('month', intval(date('m')));
301 $day = Env::i('day', intval(date('d')));
302 }
303
304 if (!$year)
305 $month = 0;
306 if (!$month)
307 $day = 0;
308
309 // smarty assignments
310 // retrieve available years
311 $page->assign('years', $this->_getYears());
312 $page->assign('year', $year);
313
314 // retrieve available months for the current year
315 $page->assign('months', $this->_getMonths($year));
316 $page->assign('month', $month);
317
318 // retrieve available days for the current year and month
319 $page->assign('days', $this->_getDays($year, $month));
320 $page->assign('day', $day);
321
322 $page->assign('loguser', $loguser);
323 // smarty assignments
324
325 if ($loguid || $year) {
326
327 // get the requested sessions
328 $where = $this->_makeWhere($year, $month, $day, $loguid);
504ccd57 329 $select = "SELECT s.id, s.start, s.uid,
441e9e98 330 a.alias as username
6586a74f 331 FROM log_sessions AS s
fe13bc1d 332 LEFT JOIN aliases AS a ON (a.uid = s.uid AND a.type='a_vie')
441e9e98 333 $where
334 ORDER BY start DESC";
335 $res = XDB::iterator($select);
336
337 $sessions = array();
338 while ($mysess = $res->next()) {
339 $mysess['events'] = array();
340 $sessions[$mysess['id']] = $mysess;
341 }
342 array_reverse($sessions);
343
344 // attach events
345 $sql = "SELECT s.id, a.text
6586a74f
FB
346 FROM log_sessions AS s
347 LEFT JOIN log_events AS e ON(e.session=s.id)
348 INNER JOIN log_actions AS a ON(a.id=e.action)
441e9e98 349 $where";
350
351 $res = XDB::iterator($sql);
352 while ($event = $res->next()) {
353 array_push($sessions[$event['id']]['events'], $event['text']);
354 }
355 $page->assign_by_ref('sessions', $sessions);
356 } else {
a7de4ef7 357 $page->assign('msg_nofilters', "Sélectionner une annuée et/ou un utilisateur");
441e9e98 358 }
86f0a6af 359 }
360
8b1f8e12 361 $page->changeTpl('admin/logger-view.tpl');
86f0a6af 362
46f272fe 363 $page->setTitle('Administration - Logs des sessions');
86f0a6af 364 }
365
f97f90f0 366 function handler_user(&$page, $login = false)
367 {
84270653 368 global $globals;
1412adb2 369 $page->changeTpl('admin/user.tpl');
f9743cf1 370 $page->setTitle('Administration - Compte');
86f0a6af 371
0c02607e 372 if (S::suid()) {
6bb2f79a 373 $page->kill("Déjà en SUID&nbsp;!!!");
86f0a6af 374 }
375
d5fbeef6 376 // Loads the user identity using the environment.
1ac65dd4
PC
377 if ($login) {
378 $user = User::get($login);
379 }
380 if (empty($user)) {
2ff7e020
VZ
381 return;
382 }
383
4f903ea6
FB
384 $login = $user->login();
385 $registered = ($user->state != 'pending');
86f0a6af 386
4f903ea6
FB
387 // Form processing
388 if (!empty($_POST)) {
389 S::assert_xsrf_token();
390 if (Post::has('uid') && Post::i('uid') != $user->id()) {
391 $page->kill('Une erreur s\'est produite');
392 }
86f0a6af 393 }
394
d5fbeef6 395 // Handles specific requests (AX sync, su, ...).
4f903ea6 396 if(Post::has('logs_account')) {
d5fbeef6 397 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
86f0a6af 398 }
399
a19178e9 400 if(Post::has('su_account') && $registered) {
866bd535 401 if (!Platal::session()->startSUID($user)) {
83752d10 402 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->login());
f97f90f0 403 } else {
d5fbeef6 404 pl_redirect("");
eaf30d86 405 }
d5fbeef6 406 }
86f0a6af 407
f9743cf1 408 // Account Form {{{
83752d10 409 $to_update = array();
4f903ea6 410 if (Post::has('disable_weak_access')) {
83752d10 411 $to_update['weak_password'] = null;
4f903ea6
FB
412 } else if (Post::has('update_account')) {
413 if (Post::s('full_name') != $user->fullName()) {
414 // XXX: Update profile if a profile is associated
415 $to_update['full_name'] = Post::s('full_name');
83752d10 416 }
4f903ea6
FB
417 if (Post::s('display_name') != $user->displayName()) {
418 // XXX: Update profile if a profile is associated
419 $to_update['display_name'] = Post::s('display_name');
83752d10 420 }
4f903ea6
FB
421 if (Post::s('sex') != ($user->isFemale() ? 'female' : 'male')) {
422 $to_update['sex'] = Post::s('sex');
83752d10 423 }
4f903ea6
FB
424 if (!Post::blank('hashpass')) {
425 $to_update['password'] = Post::s('hashpass');
7679a55a
VZ
426 // TODO: Propagate the password update to GoogleApps, when required. Eg:
427 // $account = new GoogleAppsAccount($user);
428 // if ($account->active() && $account->sync_password) {
429 // $account->set_password($pass_encrypted);
430 // }
83752d10 431 }
4f903ea6
FB
432 if (!Post::blank('weak_password')) {
433 $to_update['weak_password'] = Post::s('weak_password');
83752d10 434 }
4f903ea6
FB
435 if (Post::i('token_access', 0) != ($user->token_access ? 1 : 0)) {
436 $to_update['token'] = Post::i('token_access') ? rand_url_id(16) : null;
83752d10 437 }
fcdbb3bf
SJ
438 if (Post::i('skin') != $user->skin) {
439 $to_update['skin'] = Post::i('skin');
83752d10 440 if ($to_update['skin'] == 0) {
7cfaf494 441 $to_update['skin'] = null;
83752d10
FB
442 }
443 }
4f903ea6
FB
444 if (Post::s('state') != $user->state) {
445 $to_update['state'] = Post::s('state');
83752d10 446 }
4f903ea6
FB
447 if (Post::i('is_admin', 0) != ($user->is_admin ? 1 : 0)) {
448 $to_update['is_admin'] = Post::b('is_admin');
83752d10 449 }
4f903ea6
FB
450 if (Post::s('type') != $user->type) {
451 $to_update['type'] = Post::s('type');
83752d10 452 }
4f903ea6 453 if (Post::i('watch', 0) != ($user->watch ? 1 : 0)) {
83752d10 454 $to_update['flags'] = new PlFlagset();
4f903ea6 455 $to_update['flags']->addFlag('watch', Post::i('watch'));
83752d10 456 }
4f903ea6
FB
457 if (Post::t('comment') != $user->comment) {
458 $to_update['comment'] = Post::blank('comment') ? null : Post::t('comment');
83752d10
FB
459 }
460 }
461 if (!empty($to_update)) {
7679a55a
VZ
462 // TODO: fetch the initial values of the fields, and eventually send
463 // a summary of the changes to an admin.
83752d10
FB
464 $set = array();
465 foreach ($to_update as $k => $value) {
466 $set[] = XDB::format($k . ' = {?}', $value);
467 }
468 XDB::execute('UPDATE accounts
469 SET ' . implode(', ', $set) . '
470 WHERE uid = ' . XDB::format('{?}', $user->id()));
471 $page->trigSuccess('Données du compte mise à jour avec succès');
472 $user = User::getWithUID($user->id());
473 }
f9743cf1 474 // }}}
4f903ea6 475
f9743cf1 476 // Profile form {{{
4f903ea6
FB
477 if (Post::has('add_profile') || Post::has('del_profile') || Post::has('owner')) {
478 if (Post::i('del_profile', 0) != 0) {
f9743cf1
FB
479 XDB::execute('DELETE FROM account_profiles
480 WHERE uid = {?} AND pid = {?}',
4f903ea6
FB
481 $user->id(), Post::i('del_profile'));
482 } else if (!Post::blank('new_profile')) {
483 $profile = Profile::get(Post::t('new_profile'));
f9743cf1 484 if (!$profile) {
4f903ea6 485 $page->trigError('Le profil ' . Post::t('new_profile') . ' n\'existe pas');
f9743cf1
FB
486 } else {
487 XDB::execute('INSERT IGNORE INTO account_profiles (uid, pid)
488 VALUES ({?}, {?})',
489 $user->id(), $profile->id());
490 }
491 }
492 XDB::execute('UPDATE account_profiles
493 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
494 WHERE uid = {?}',
4f903ea6 495 Post::i('owner'), $user->id());
f9743cf1 496 }
f9743cf1
FB
497 // }}}
498
4f903ea6
FB
499 // Email forwards form {{{
500 require_once("emails.inc.php");
501 $redirect = ($registered ? new Redirect($user) : null);
502 if (Post::has('add_fwd')) {
503 $email = Post::t('email');
504 if (!isvalid_email_redirection($email)) {
505 $page->trigError("Email non valide: $email");
506 } else {
507 $redirect->add_email($email);
508 $page->trigSuccess("Ajout de $email effectué");
509 }
510 } else if (!Post::blank('del_fwd')) {
511 $redirect->delete_email(Post::t('del_fwd'));
512 } else if (!Post::blank('activate_fwd')) {
513 $redirect->modify_one_email(Post::t('activate_fwd', true));
514 } else if (!Post::blank('deactivate_fwd')) {
515 $redirect->modify_one_email(Post::t('deactivate_fwd', false));
516 } else if (Post::has('disable_fwd')) {
517 $redirect->disable();
518 } else if (Post::has('enable_fwd')) {
519 $redirect->enable();
520 } else if (!Post::blank('clean_fwd')) {
521 $redirect->clean_errors(Post::t('clean_fwd'));
522 }
523 // }}}
d5fbeef6 524
4f903ea6
FB
525 // Email alias form {{{
526 if (Post::has('add_alias')) {
527 // Splits new alias in user and fqdn.
528 $alias = Env::t('email');
529 if (strpos($alias, '@') !== false) {
530 list($alias, $domain) = explode('@', $alias);
531 } else {
532 $domain = $globals->mail->domain;
533 }
84270653 534
4f903ea6
FB
535 // Checks for alias' user validity.
536 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
537 $page->trigError("'$alias' n'est pas un alias valide");
538 }
86f0a6af 539
4f903ea6
FB
540 // Eventually adds the alias to the right domain.
541 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
542 $req = new AliasReq($user, $alias, 'Admin request', false);
543 if ($req->commit()) {
544 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué");
545 } else {
546 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué");
547 }
548 } elseif ($domain == $globals->mail->domain || $domain == $globals->mail->domain2) {
fe13bc1d 549 $res = XDB::execute("INSERT INTO aliases (uid, alias, type)
4f903ea6
FB
550 VALUES ({?}, {?}, 'alias')",
551 $user->id(), $alias);
552 $page->trigSuccess("Nouvel alias '$alias' ajouté");
553 } else {
554 $page->trigError("Le domaine '$domain' n'est pas valide");
555 }
556 } else if (!Post::blank('del_alias')) {
557 XDB::execute("DELETE FROM aliases
fe13bc1d 558 WHERE uid = {?} AND alias = {?} AND
4f903ea6
FB
559 type NOT IN ('a_vie', 'homonyme')",
560 $user->id(), $val);
561 XDB::execute("UPDATE emails
562 SET rewrite = ''
563 WHERE uid = {?} AND rewrite LIKE CONCAT({?}, '@%')",
564 $user->id(), $val);
565 fix_bestalias($user);
566 $page->trigSuccess("L'alias '$val' a été supprimé");
567 } else if (!Post::blank('best')) {
568 XDB::execute("UPDATE aliases
569 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
fe13bc1d 570 WHERE uid = {?}", $user->id());
4f903ea6
FB
571 XDB::execute("UPDATE aliases
572 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
fe13bc1d 573 WHERE uid = {?} AND alias = {?}", $user->id(), $val);
4f903ea6
FB
574 // As having a non-null bestalias value is critical in
575 // plat/al's code, we do an a posteriori check on the
576 // validity of the bestalias.
577 fix_bestalias($user);
578 }
579 // }}}
669cb0e0 580
83353c71
FB
581 // OpenId form {{{
582 if (Post::has('del_openid')) {
864957c1 583 XDB::execute('DELETE FROM account_auth_openid
83353c71
FB
584 WHERE id = {?}', Post::i('del_openid'));
585 }
586 // }}}
587
4f903ea6
FB
588 // Forum form {{{
589 if (Post::has('b_edit')) {
590 XDB::execute("DELETE FROM forum_innd
591 WHERE uid = {?}", $user->id());
592 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
593 XDB::execute("INSERT INTO forum_innd
594 SET ipmin = '0', ipmax = '4294967295',
595 write_perm = {?}, read_perm = {?},
596 comment = {?}, priority = '200', uid = {?}",
597 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
598 }
599 }
600 // }}}
86f0a6af 601
86f0a6af 602
889d9807
FB
603 $page->addJsLink('jquery.ui.core.js');
604 $page->addJsLink('jquery.ui.tabs.js');
669cb0e0 605
d5fbeef6
VZ
606 // Displays last login and last host information.
607 $res = XDB::query("SELECT start, host
6586a74f 608 FROM log_sessions
d5fbeef6
VZ
609 WHERE uid = {?} AND suid = 0
610 ORDER BY start DESC
611 LIMIT 1", $user->id());
612 list($lastlogin,$host) = $res->fetchOneRow();
613 $page->assign('lastlogin', $lastlogin);
614 $page->assign('host', $host);
615
616 // Display active aliases.
8f2104cb 617 $page->assign('virtuals', $user->emailAliases());
4f903ea6
FB
618 $page->assign('aliases', XDB::iterator("SELECT alias, type='a_vie' AS for_life,
619 FIND_IN_SET('bestalias',flags) AS best, expire
620 FROM aliases
fe13bc1d 621 WHERE uid = {?} AND type != 'homonyme'
4f903ea6 622 ORDER BY type != 'a_vie'", $user->id()));
8f2104cb
FB
623 $page->assign('account_types', XDB::iterator('SELECT * FROM account_types ORDER BY type'));
624 $page->assign('skins', XDB::iterator('SELECT id, name FROM skins ORDER BY name'));
f9743cf1
FB
625 $page->assign('profiles', XDB::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
626 FROM account_profiles AS ap
627 INNER JOIN profiles AS p ON (ap.pid = p.pid)
628 WHERE ap.uid = {?}', $user->id()));
83353c71 629 $page->assign('openid', XDB::iterator('SELECT id, url
864957c1
FB
630 FROM account_auth_openid
631 WHERE uid = {?}', $user->id()));
d5fbeef6
VZ
632
633 // Displays email redirection and the general profile.
634 if ($registered && $redirect) {
635 $page->assign('emails', $redirect->emails);
636 }
637
d5fbeef6
VZ
638 $page->assign('user', $user);
639
640 // Displays forum bans.
641 $res = XDB::query("SELECT write_perm, read_perm, comment
7d15f750 642 FROM forum_innd
d5fbeef6
VZ
643 WHERE uid = {?}", $user->id());
644 $bans = $res->fetchOneAssoc();
645 $page->assign('bans', $bans);
86f0a6af 646 }
1f53925a 647
e02d9fbb 648 private static function getHrid($firstname, $lastname, $promo)
7c5200a5 649 {
e02d9fbb 650 if ($firstname != null && $lastname != null && $promo != null) {
69fc05dd 651 return User::makeHrid($firstname, $lastname, $promo);
7c5200a5 652 }
f6eacab0 653 return null;
7c5200a5
VZ
654 }
655
e02d9fbb 656 private static function formatNewUser($infosLine, $separator, $promo, $size)
1f53925a 657 {
e02d9fbb
SJ
658 $infos = explode($separator, $infosLine);
659 if (sizeof($infos) != $size) {
660 return false;
1f53925a 661 }
662
e02d9fbb
SJ
663 array_map('trim', $infos);
664 $hrid = self::getHrid($infos[1], $infos[0], $promo);
665 $res1 = XDB::query('SELECT COUNT(*)
666 FROM accounts
667 WHERE hruid = {?}', $hrid);
668 $res2 = XDB::query('SELECT COUNT(*)
669 FROM profiles
670 WHERE hrpid = {?}', $hrid);
671 if (is_null($hrid) || $res1->fetchOneCell() > 0 || $res2->fetchOneCell() > 0) {
672 $page->trigError("La ligne $line n'a pas été ajoutée.");
673 return false;
674 }
675 $infos['hrid'] = $hrid;
676 return $infos;
677 }
678
679 private static function formatSex(&$page, $sex, $line)
680 {
681 switch ($sex) {
682 case 'F':
683 return PlUser::GENDER_FEMALE;
684 case 'M':
685 return PlUser::GENDER_MALE;
686 default:
687 $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
688 return null;
1f53925a 689 }
e02d9fbb 690 }
1f53925a 691
e02d9fbb
SJ
692 private static function formatBirthDate($birthDate)
693 {
694 return date("Y-m-d", strtotime($birthDate));
695 }
696
697 function handler_add_accounts(&$page, $action = null, $promo = null)
698 {
699 $page->changeTpl('admin/add_accounts.tpl');
700
701 if (Env::has('add_type') && Env::has('people')) {
e02d9fbb
SJ
702 $lines = explode("\n", Env::t('people'));
703 $separator = Env::t('separator');
704 $promotion = Env::i('promotion');
94590511 705 $nameTypes = DirEnum::getOptions(DirEnum::NAMETYPES);
e02d9fbb
SJ
706 $nameTypes = array_flip($nameTypes);
707
708 if (Env::t('add_type') == 'promo') {
709 $type = 'x';
94590511 710 $eduSchools = DirEnum::getOptions(DirEnum::EDUSCHOOLS);
e02d9fbb 711 $eduSchools = array_flip($eduSchools);
94590511 712 $eduDegrees = DirEnum::getOptions(DirEnum::EDUDEGREES);
e02d9fbb
SJ
713 $eduDegrees = array_flip($eduDegrees);
714 var_dump($eduDegrees);
715 switch (Env::t('edu_type')) {
716 case 'X':
717 $degreeid = $eduDegrees[Profile::DEGREE_X];
718 $entry_year = $promotion;
719 $grad_year = $promotion + 3;
720 $promo = 'X' . $promotion;
721 break;
722 case 'M':
723 $degreeid = $eduDegrees[Profile::DEGREE_M];
724 $grad_year = $promotion;
725 $entry_year = $promotion - 2;
726 $promo = 'M' . $promotion;
727 break;
728 case 'D':
729 $degreeid = $eduDegrees[Profile::DEGREE_D];
730 $grad_year = $promotion;
731 $entry_year = $promotion - 3;
732 $promo = 'D' . $promotion;
733 break;
734 default:
735 $page->killError("La formation n'est pas reconnue:" . Env::t('edu_type') . '.');
736 }
737
738 foreach ($lines as $line) {
739 if (($infos = self::formatNewUser($line, $separator, $promotion, 6))
740 && ($sex = self::formatSex($page, $infos[3], $line))) {
741 $name = $infos[1] . ' ' . $infos[0];
742 $birthDate = self::formatBirthDate($infos[2]);
69b46857 743 $xorgId = Profile::getXorgId($infos[4]);
e02d9fbb
SJ
744
745 XDB::execute('INSERT INTO profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex)
746 VALUES ({?}, {?}, {?}, {?})',
747 $infos['hrid'], $xorgId, $infos[5], $birthDate, $sex);
748 $pid = XDB::insertId();
749 XDB::execute('INSERT INTO profile_name (pid, name, typeid)
750 VALUES ({?}, {?}, {?})',
751 $pid, $infos[0], $nameTypes['name_ini']);
752 XDB::execute('INSERT INTO profile_name (pid, name, typeid)
753 VALUES ({?}, {?}, {?})',
754 $pid, $infos[1], $nameTypes['firstname_ini']);
755 XDB::execute('INSERT INTO profile_display (pid, yourself, public_name, private_name,
756 directory_name, short_name, sort_name, promo)
757 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
758 $pid, $infos[1], $name, $name, $name, $name, $infos[0] . ' ' . $infos[1], $promo);
759 XDB::execute('INSERT INTO profile_education (pid, eduid, degreeid, entry_year, grad_year, flags)
760 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
761 $pid, $eduSchools[Profile::EDU_X], $degreeid, $entry_year, $grad_year, 'primary');
762 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, full_name, display_name, sex)
763 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
764 $infos['hrid'], $type, 0, 'active', $name, $infos[1], $sex);
765 $uid = XDB::insertId();
766 XDB::execute('INSERT INTO account_profiles (uid, pid, perms)
767 VALUES ({?}, {?}, {?})',
768 $uid, $pid, 'owner');
769 }
770 }
771 } else if (Env::t('add_type') == 'account') {
772 $type = Env::t('type');
773 foreach ($lines as $line) {
774 if (($infos = self::formatNewUser($line, $separator, $type, 4))
775 && ($sex = self::formatSex(&$page, $infos[3], $line))) {
776 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, email, full_name, display_name, sex)
777 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
778 $infos['hrid'], $type, 0, 'active', $infos[2], $infos[1] . ' ' . $infos[0], $infos[1], $sex);
779 }
780 }
781 } else if (Env::t('add_type') == 'ax_id') {
782 $type = 'x';
783 foreach ($lines as $line) {
784 if ($infos = self::formatNewUser($line, $separator, $promotion, 3)) {
785 XDB::execute('UPDATE profiles
786 SET ax_id = {?}
787 WHERE hrpid = {?}',
788 $infos[2], $infos['hrid']);
789 }
790 }
791 }
792
793 if ($page->nb_errs == 0) {
794 $page->trigSuccess("L'opération a été effectuée avec succès.");
795 } else {
796 $page->trigSuccess("L'opération a été effectuée avec succès, sauf pour les "
797 . $page->nb_errs . 'erreurs signalées ci-dessus.');
798 }
799 } else if (Env::has('add_type')) {
800 $res = XDB::query('SELECT type
801 FROM account_types');
802 $page->assign('account_types', $res->fetchColumn());
803 $page->assign('add_type', Env::s('add_type'));
1f53925a 804 }
1f53925a 805 }
806
7c5200a5
VZ
807 function handler_homonyms(&$page, $op = 'list', $target = null)
808 {
86f0a6af 809 $page->changeTpl('admin/homonymes.tpl');
46f272fe 810 $page->setTitle('Administration - Homonymes');
191711d5 811 $this->load("homonyms.inc.php");
74c55fd6 812
86f0a6af 813 if ($target) {
191711d5
FB
814 $user = User::getSilent($target);
815 if (!$user || !($loginbis = select_if_homonyme($user))) {
816 $target = 0;
86f0a6af 817 } else {
191711d5 818 $page->assign('user', $user);
86f0a6af 819 $page->assign('loginbis',$loginbis);
820 }
821 }
74c55fd6 822
839a80cf
VZ
823 $page->assign('op', $op);
824 $page->assign('target', $target);
74c55fd6 825
86f0a6af 826 // on a un $target valide, on prepare les mails
827 if ($target) {
86f0a6af 828 // on examine l'op a effectuer
829 switch ($op) {
830 case 'mail':
40d428d8
VZ
831 S::assert_xsrf_token();
832
191711d5
FB
833 send_warning_homonyme($user, $loginbis);
834 switch_bestalias($user, $loginbis);
86f0a6af 835 $op = 'list';
191711d5 836 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
86f0a6af 837 break;
839a80cf 838
86f0a6af 839 case 'correct':
40d428d8
VZ
840 S::assert_xsrf_token();
841
191711d5 842 switch_bestalias($user, $loginbis);
32b3ac78
FB
843 XDB::execute("UPDATE aliases
844 SET type = 'homonyme', expire=NOW()
845 WHERE alias = {?}", $loginbis);
05240425 846 XDB::execute("REPLACE INTO homonyms (homonyme_id, uid)
191711d5
FB
847 VALUES ({?}, {?})", $target, $target);
848 send_robot_homonyme($user, $loginbis);
86f0a6af 849 $op = 'list';
191711d5 850 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
86f0a6af 851 break;
852 }
853 }
74c55fd6 854
86f0a6af 855 if ($op == 'list') {
856 $res = XDB::iterator(
32b3ac78 857 "SELECT a.alias AS homonyme, s.alias AS forlife,
e84223d4
PC
858 IF(h.homonyme_id = s.uid, a.expire, NULL) AS expire,
859 IF(h.homonyme_id = s.uid, a.type, NULL) AS type, ac.uid
86f0a6af 860 FROM aliases AS a
1bf36cd1
SJ
861 LEFT JOIN homonyms AS h ON (h.homonyme_id = a.uid)
862 INNER JOIN aliases AS s ON (s.uid = h.uid AND s.type = 'a_vie')
fe13bc1d 863 INNER JOIN accounts AS ac ON (ac.uid = a.uid)
32b3ac78
FB
864 WHERE a.type = 'homonyme' OR a.expire != ''
865 ORDER BY a.alias, forlife");
86f0a6af 866 $hnymes = Array();
867 while ($tab = $res->next()) {
868 $hnymes[$tab['homonyme']][] = $tab;
869 }
1bf36cd1 870 $page->assign_by_ref('hnymes', $hnymes);
86f0a6af 871 }
872 }
74c55fd6 873
32b3ac78
FB
874 function handler_deaths(&$page, $promo = 0, $validate = false)
875 {
86f0a6af 876 $page->changeTpl('admin/deces_promo.tpl');
46f272fe 877 $page->setTitle('Administration - Deces');
74c55fd6 878
dcefa8f7
FB
879 if (!$promo) {
880 $promo = Env::t('promo', 'X1923');
881 }
882 $page->assign('promo', $promo);
883 if (!$promo) {
884 return;
885 }
74c55fd6 886
40d428d8
VZ
887 if ($validate) {
888 S::assert_xsrf_token();
889
dcefa8f7
FB
890 $res = XDB::iterRow('SELECT p.hrpid, pd.directory_name, p.deathdate
891 FROM profiles AS p
892 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
893 WHERE pd.promo = {?}', $promo);
894 while (list($pid, $name, $death) = $res->next()) {
895 $val = Env::v($pid);
e61326ed
VZ
896 if($val == $deces || empty($val)) {
897 continue;
898 }
899
dcefa8f7
FB
900 XDB::execute('UPDATE profiles
901 SET deathdate = {?}, deathdate_rec = NOW()
902 WHERE hrpid = {?}', $val, $pid);
903 $page->trigSuccess('Ajout du décès de ' . $name . ' le ' . $val . '.');
904 if($death == '0000-00-00' || empty($death)) {
6150f591
SJ
905 $profile = Profile::get($pid);
906 $profile->clear();
907 $profile->owner()->clear(false);
e61326ed 908 }
86f0a6af 909 }
86f0a6af 910 }
74c55fd6 911
dcefa8f7
FB
912 $res = XDB::iterator('SELECT p.hrpid, pd.directory_name, p.deathdate
913 FROM profiles AS p
914 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
915 WHERE pd.promo = {?}
916 ORDER BY pd.sort_name', $promo);
86f0a6af 917 $page->assign('decedes', $res);
918 }
74c55fd6 919
32b3ac78
FB
920 function handler_dead_but_active(&$page)
921 {
1c48c2a9 922 $page->changeTpl('admin/dead_but_active.tpl');
46f272fe 923 $page->setTitle('Administration - Décédés');
1c48c2a9
VZ
924
925 $res = XDB::iterator(
e46cf8c4 926 "SELECT a.hruid, pd.promo, p.ax_id, pd.directory_name, p.deathdate, DATE(MAX(s.start)) AS last
fe13bc1d
FB
927 FROM accounts AS a
928 INNER JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET('owner', ap.perms))
929 INNER JOIN profiles AS p ON (p.pid = ap.pid)
930 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
6586a74f 931 LEFT JOIN log_sessions AS s ON (s.uid = a.uid AND suid = 0)
e46cf8c4 932 WHERE a.state = 'active' AND p.deathdate IS NOT NULL
dcefa8f7 933 GROUP BY a.uid
e46cf8c4 934 ORDER BY pd.promo, pd.sort_name");
1c48c2a9
VZ
935 $page->assign('dead', $res);
936 }
937
e654517d 938 function handler_validate(&$page, $action = 'list', $id = null)
939 {
764b894d 940 $page->changeTpl('admin/validation.tpl');
46f272fe 941 $page->setTitle('Administration - Valider une demande');
441c2451 942 $page->addCssLink('nl.css');
3ad44e08 943 $page->addJsLink('ajax.js');
e654517d 944 require_once("validations.inc.php");
945
74c55fd6 946
ed5b9703 947 if ($action == 'edit' and !is_null($id)) {
948 $page->assign('preview_id', $id);
949 }
950
86f0a6af 951 if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
40d428d8
VZ
952 S::assert_xsrf_token();
953
20d7932b 954 $req = Validate::get_typed_request(Env::v('uid'), Env::v('type'), Env::v('stamp'));
343e22c2
FB
955 if ($req) {
956 $req->handle_formu();
957 } else {
958 $page->trigWarning('La validation a déjà été effectuée.');
959 }
86f0a6af 960 }
74c55fd6 961
cfb96867 962 $r = XDB::iterator('SHOW COLUMNS FROM requests_answers');
963 while (($a = $r->next()) && $a['Field'] != 'category');
964 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
74c55fd6 965
cfb96867 966 $hidden = array();
257ae408
SJ
967 $res = XDB::query('SELECT hidden_requests
968 FROM requests_hidden
969 WHERE uid = {?}', S::v('uid'));
e0d7c076 970 $hide_requests = $res->fetchOneCell();
cfb96867 971 if (Post::has('hide')) {
74c55fd6 972 $hide = array();
973 foreach ($categories as $cat)
cfb96867 974 if (!Post::v($cat)) {
975 $hidden[$cat] = 1;
976 $hide[] = $cat;
977 }
e0d7c076 978 $hide_requests = join(',', $hide);
257ae408
SJ
979 XDB::query('REPLACE INTO requests_hidden (uid, hidden_requests)
980 VALUES ({?}, {?})',
e0d7c076
SJ
981 S::v('uid'), $hide_requests);
982 } elseif ($hide_requests) {
983 foreach (explode(',', $hide_requests) as $hide_type)
cfb96867 984 $hidden[$hide_type] = true;
985 }
986 $page->assign('hide_requests', $hidden);
74c55fd6 987
90df2530
FB
988 // Update the count of item to validate here... useful in development configuration
989 // where several copies of the site use the same DB, but not the same "dynamic configuration"
ebfdf077
FB
990 global $globals;
991 $globals->updateNbValid();
86f0a6af 992 $page->assign('vit', new ValidateIterator());
993 }
e654517d 994
32b3ac78
FB
995 function handler_validate_answers(&$page, $action = 'list', $id = null)
996 {
46f272fe 997 $page->setTitle('Administration - Réponses automatiques de validation');
a7de4ef7 998 $page->assign('title', 'Gestion des réponses automatiques');
e18888f4 999 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
a7de4ef7 1000 $table_editor->describe('category','catégorie',true);
e18888f4 1001 $table_editor->describe('title','titre',true);
1002 $table_editor->describe('answer','texte',false);
1003 $table_editor->apply($page, $action, $id);
1004 }
32b3ac78
FB
1005
1006 function handler_skins(&$page, $action = 'list', $id = null)
1007 {
46f272fe 1008 $page->setTitle('Administration - Skins');
e7ae7df9 1009 $page->assign('title', 'Gestion des skins');
1010 $table_editor = new PLTableEditor('admin/skins','skins','id');
1011 $table_editor->describe('name','nom',true);
1012 $table_editor->describe('skin_tpl','nom du template',true);
1013 $table_editor->describe('auteur','auteur',false);
1014 $table_editor->describe('comment','commentaire',true);
1015 $table_editor->describe('date','date',false);
1016 $table_editor->describe('ext','extension du screenshot',false);
1017 $table_editor->apply($page, $action, $id);
74c55fd6 1018 }
669cb0e0 1019
32b3ac78
FB
1020 function handler_postfix_blacklist(&$page, $action = 'list', $id = null)
1021 {
46f272fe 1022 $page->setTitle('Administration - Postfix : Blacklist');
e7ae7df9 1023 $page->assign('title', 'Blacklist de postfix');
1024 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true);
1025 $table_editor->describe('reject_text','Texte de rejet',true);
1026 $table_editor->describe('email','email',true);
1027 $table_editor->apply($page, $action, $id);
74c55fd6 1028 }
32b3ac78
FB
1029
1030 function handler_postfix_whitelist(&$page, $action = 'list', $id = null)
1031 {
46f272fe 1032 $page->setTitle('Administration - Postfix : Whitelist');
e7ae7df9 1033 $page->assign('title', 'Whitelist de postfix');
1034 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true);
1035 $table_editor->describe('email','email',true);
1036 $table_editor->apply($page, $action, $id);
74c55fd6 1037 }
32b3ac78
FB
1038
1039 function handler_mx_broken(&$page, $action = 'list', $id = null)
1040 {
46f272fe 1041 $page->setTitle('Administration - MX Défaillants');
a7de4ef7 1042 $page->assign('title', 'MX Défaillant');
ccdbc270 1043 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true);
1044 $table_editor->describe('host', 'Masque', true);
1045 $table_editor->describe('state', 'Niveau', true);
a7de4ef7 1046 $table_editor->describe('text', 'Description du problème', false);
ccdbc270 1047 $table_editor->apply($page, $action, $id);
1048 }
32b3ac78
FB
1049
1050 function handler_logger_actions(&$page, $action = 'list', $id = null)
1051 {
46f272fe 1052 $page->setTitle('Administration - Actions');
e7ae7df9 1053 $page->assign('title', 'Gestion des actions de logger');
6586a74f 1054 $table_editor = new PLTableEditor('admin/logger/actions','log_actions','id');
a7de4ef7 1055 $table_editor->describe('text','intitulé',true);
e7ae7df9 1056 $table_editor->describe('description','description',true);
1057 $table_editor->apply($page, $action, $id);
74c55fd6 1058 }
32b3ac78 1059
8f2104cb
FB
1060 function handler_downtime(&$page, $action = 'list', $id = null)
1061 {
46f272fe 1062 $page->setTitle('Administration - Coupures');
e7ae7df9 1063 $page->assign('title', 'Gestion des coupures');
06f4daf9 1064 $table_editor = new PLTableEditor('admin/downtime','downtimes','id');
e7ae7df9 1065 $table_editor->describe('debut','date',true);
a7de4ef7 1066 $table_editor->describe('duree','durée',false);
1067 $table_editor->describe('resume','résumé',true);
1068 $table_editor->describe('services','services affectés',true);
e7ae7df9 1069 $table_editor->describe('description','description',false);
1070 $table_editor->apply($page, $action, $id);
74c55fd6 1071 }
bc0903c7 1072
8f2104cb
FB
1073 function handler_account_types(&$page, $action = 'list', $id = null)
1074 {
1075 $page->setTitle('Administration - Types de comptes');
1076 $page->assign('title', 'Gestion des types de comptes');
1077 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true);
1078 $table_editor->describe('type', 'Catégorie', true);
1079 $table_editor->describe('perms', 'Permissions associées', true);
1080 $table_editor->apply($page, $action, $id);
1081 }
1082
8f201b69 1083 function handler_wiki(&$page, $action = 'list', $wikipage = null, $wikipage2 = null)
bc0903c7 1084 {
84fc72ff 1085 if (S::hasAuthToken()) {
a2b461ce 1086 $page->setRssLink('Changement Récents',
84fc72ff 1087 '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::v('token'));
a2b461ce 1088 }
e61326ed 1089
3aec1c21 1090 // update wiki perms
40d428d8
VZ
1091 if ($action == 'update') {
1092 S::assert_xsrf_token();
1093
3aec1c21 1094 $perms_read = Post::v('read');
8f201b69 1095 $perms_edit = Post::v('edit');
3aec1c21 1096 if ($perms_read || $perms_edit) {
8f201b69
FB
1097 foreach ($_POST as $wiki_page => $val) {
1098 if ($val == 'on') {
1099 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1100 if ($wp->setPerms($perms_read ? $perms_read : $wp->readPerms(),
1101 $perms_edit ? $perms_edit : $wp->writePerms())) {
1102 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1103 } else {
1104 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1105 }
1106 }
3aec1c21 1107 }
1108 }
8f201b69
FB
1109 } else if ($action != 'list' && !empty($wikipage)) {
1110 $wp = new PlWikiPage($wikipage);
40d428d8
VZ
1111 S::assert_xsrf_token();
1112
8f201b69
FB
1113 if ($action == 'delete') {
1114 if ($wp->delete()) {
1115 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1116 } else {
1117 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1118 }
1119 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1120 if ($changedLinks = $wp->rename($wikipage2)) {
1121 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1122 if (is_numeric($changedLinks)) {
1123 $s .= $changedLinks.' lien'.(($changedLinks>1)?'s ont été modifiés.':' a été modifié.');
1124 }
1125 $page->trigSuccess($s);
1126 } else {
1127 $page->trigError("Impossible de déplacer la page ".$wikipage);
9162f4ed 1128 }
9162f4ed 1129 }
1130 }
74c55fd6 1131
8f201b69 1132 $perms = PlWikiPage::permOptions();
74c55fd6 1133
3aec1c21 1134 // list wiki pages and their perms
8f201b69 1135 $wiki_pages = PlWikiPage::listPages();
3aec1c21 1136 ksort($wiki_pages);
bc0903c7 1137 $wiki_tree = array();
1138 foreach ($wiki_pages as $file => $desc) {
1139 list($cat, $name) = explode('.', $file);
1140 if (!isset($wiki_tree[$cat])) {
1141 $wiki_tree[$cat] = array();
1142 }
1143 $wiki_tree[$cat][$name] = $desc;
1144 }
1145
3aec1c21 1146 $page->changeTpl('admin/wiki.tpl');
bc0903c7 1147 $page->assign('wiki_pages', $wiki_tree);
3aec1c21 1148 $page->assign('perms_opts', $perms);
1149 }
5480a216 1150
1151 function handler_ipwatch(&$page, $action = 'list', $ip = null)
eaf30d86 1152 {
5480a216 1153 $page->changeTpl('admin/ipwatcher.tpl');
eaf30d86 1154
5480a216 1155 $states = array('safe' => 'Ne pas surveiller',
c339246f 1156 'unsafe' => 'Surveiller les inscriptions',
a7de4ef7 1157 'dangerous' => 'Surveiller tous les accès',
5480a216 1158 'ban' => 'Bannir cette adresse');
1159 $page->assign('states', $states);
1160
1161 switch (Post::v('action')) {
e61326ed 1162 case 'create':
5480a216 1163 if (trim(Post::v('ipN')) != '') {
40d428d8 1164 S::assert_xsrf_token();
61c98f4b
FB
1165 Xdb::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1166 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1167 ip_to_uint(trim(Post::v('ipN'))), ip_to_uint(trim(Post::v('maskN'))),
1168 Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
eaf30d86
PH
1169 };
1170 break;
1171
e61326ed 1172 case 'edit':
40d428d8 1173 S::assert_xsrf_token();
eaf30d86 1174 Xdb::execute('UPDATE ip_watch
61c98f4b 1175 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
9797734d 1176 WHERE ip = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'),
61c98f4b 1177 ip_to_uint(Post::v('maskN')), ip_to_uint(Post::v('ipN')));
5480a216 1178 break;
eaf30d86 1179
e61326ed 1180 default:
5480a216 1181 if ($action == 'delete' && !is_null($ip)) {
40d428d8
VZ
1182 S::assert_xsrf_token();
1183 Xdb::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
5480a216 1184 }
1185 }
1186 if ($action != 'create' && $action != 'edit') {
1187 $action = 'list';
1188 }
1189 $page->assign('action', $action);
1190
1191 if ($action == 'list') {
9797734d
FB
1192 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1193 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1194 IF(w.ip = s.ip, s.host, s.forward_host)),
32b3ac78 1195 w.mask, w.detection, w.state, a.hruid
fe13bc1d 1196 FROM ip_watch AS w
6586a74f
FB
1197 LEFT JOIN log_sessions AS s ON (s.ip = w.ip)
1198 LEFT JOIN log_sessions AS s2 ON (s2.forward_ip = w.ip)
fe13bc1d 1199 LEFT JOIN accounts AS a ON (a.uid = s.uid)
32b3ac78
FB
1200 GROUP BY w.ip, a.hruid
1201 ORDER BY w.state, w.ip, a.hruid";
5480a216 1202 $it = Xdb::iterRow($sql);
1203
1204 $table = array();
1205 $props = array();
90c614cd 1206 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
9797734d 1207 $ip = uint_to_ip($ip);
61c98f4b 1208 $mask = uint_to_ip($mask);
5480a216 1209 if (count($props) == 0 || $props['ip'] != $ip) {
1210 if (count($props) > 0) {
1211 $table[] = $props;
1212 }
1213 $props = array('ip' => $ip,
61c98f4b 1214 'mask' => $mask,
5480a216 1215 'host' => $host,
1216 'detection' => $date,
1217 'state' => $state,
90c614cd 1218 'users' => array($hruid));
5480a216 1219 } else {
90c614cd 1220 $props['users'][] = $hruid;
5480a216 1221 }
1222 }
1223 if (count($props) > 0) {
1224 $table[] = $props;
1225 }
1226 $page->assign('table', $table);
1227 } elseif ($action == 'edit') {
61c98f4b 1228 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
32b3ac78 1229 a1.hruid AS edit, a2.hruid AS hruid, s.host
fe13bc1d
FB
1230 FROM ip_watch AS w
1231 LEFT JOIN accounts AS a1 ON (a1.uid = w.uid)
6586a74f 1232 LEFT JOIN log_sessions AS s ON (w.ip = s.ip)
fe13bc1d 1233 LEFT JOIN accounts AS a2 ON (a2.uid = s.uid)
5480a216 1234 WHERE w.ip = {?}
32b3ac78
FB
1235 GROUP BY a2.hruid
1236 ORDER BY a2.hruid";
9797734d 1237 $it = Xdb::iterRow($sql, ip_to_uint($ip));
5480a216 1238
1239 $props = array();
90c614cd 1240 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
5480a216 1241 if (count($props) == 0) {
1242 $props = array('ip' => $ip,
61c98f4b 1243 'mask' => uint_to_ip($mask),
5480a216 1244 'host' => $host,
1245 'detection' => $detection,
1246 'state' => $state,
1247 'last' => $last,
1248 'description' => $description,
1249 'edit' => $edit,
90c614cd 1250 'users' => array($hruid));
5480a216 1251 } else {
90c614cd 1252 $props['users'][] = $hruid;
5480a216 1253 }
1254 }
1255 $page->assign('ip', $props);
1256 }
1257 }
eaf30d86 1258
04148a2c 1259 function handler_icons(&$page)
f141945d 1260 {
1261 $page->changeTpl('admin/icons.tpl');
1262 $dh = opendir('../htdocs/images/icons');
1263 if (!$dh) {
a7d35093 1264 $page->trigError('Dossier des icones introuvables.');
f141945d 1265 }
1266 $icons = array();
1267 while (($file = readdir($dh)) !== false) {
1268 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1269 array_push($icons, substr($file, 0, -4));
1270 }
1271 }
1272 sort($icons);
1273 $page->assign('icons', $icons);
04148a2c 1274 }
fd1ce8c5
FB
1275
1276 function handler_accounts(&$page)
1277 {
1278 $page->changeTpl('admin/accounts.tpl');
32b3ac78
FB
1279 $page->assign('disabled', XDB::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1280 a.state = \'disabled\' AS disabled, a.comment
1281 FROM accounts AS a
1282 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1283 ORDER BY a.hruid'));
1284 $page->assign('admins', XDB::iterator('SELECT a.hruid
1285 FROM accounts AS a
1286 WHERE a.is_admin
1287 ORDER BY a.hruid'));
fd1ce8c5 1288 }
4d336f59
SJ
1289
1290 function handler_jobs(&$page, $id = -1)
1291 {
1292 $page->changeTpl('admin/jobs.tpl');
1293
1294 if (Env::has('search')) {
1295 $res = XDB::query("SELECT e.id, e.name, e.acronym
1296 FROM profile_job_enum AS e
1297 WHERE e.name LIKE CONCAT('% ', {?}, '%') OR e.acronym LIKE CONCAT('% ', {?}, '%')",
1298 Env::t('job'), Env::t('job'));
1299
1300 if ($res->numRows() <= 20) {
1301 $page->assign('jobs', $res->fetchAllAssoc());
1302 } else {
1303 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1304 }
1305
1306 $page->assign('askedJob', Env::v('job'));
1307 return;
1308 }
1309
1310 if (Env::has('edit')) {
ecad8a08
SJ
1311 // TODO: use address and phone classes to update profile_job_enum and profile_phones once they are done.
1312
4d336f59
SJ
1313 S::assert_xsrf_token();
1314 $selectedJob = Env::has('selectedJob');
1315
63596a65 1316 XDB::execute("DELETE FROM profile_phones
ce0b2c6f 1317 WHERE pid = {?} AND link_type = 'hq'",
63596a65
SJ
1318 $id);
1319 XDB::execute("DELETE FROM profile_addresses
1320 WHERE jobid = {?} AND type = 'hq'",
1321 $id);
1322 XDB::execute('DELETE FROM profile_job_enum
1323 WHERE id = {?}',
1324 $id);
1325
4d336f59
SJ
1326 if (Env::has('change')) {
1327 XDB::execute('UPDATE profile_job
1328 SET jobid = {?}
1329 WHERE jobid = {?}',
1330 Env::i('newJobId'), $id);
4d336f59
SJ
1331
1332 $page->trigSuccess("L'entreprise a bien été remplacée.");
1333 } else {
63596a65
SJ
1334 require_once 'profil.func.inc.php';
1335 require_once 'geocoding.inc.php';
1336
1337 $display_tel = format_display_number(Env::v('tel'), $error_tel);
1338 $display_fax = format_display_number(Env::v('fax'), $error_fax);
1339 $gmapsGeocoder = new GMapsGeocoder();
1340 $address = array('text' => Env::t('address'));
1341 $address = $gmapsGeocoder->getGeocodedAddress($address);
1342 Geocoder::getAreaId($address, 'administrativeArea');
1343 Geocoder::getAreaId($address, 'subAdministrativeArea');
1344 Geocoder::getAreaId($address, 'locality');
1345
4d336f59
SJ
1346 XDB::execute('UPDATE profile_job_enum
1347 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1348 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1349 WHERE id = {?}',
1350 Env::t('name'), Env::t('acronym'), Env::t('url'), Env::t('email'),
1351 Env::t('NAF_code'), Env::i('AX_code'), Env::i('holdingId'), $id);
1352
ce0b2c6f 1353 XDB::execute("INSERT INTO profile_phones (pid, link_type, link_id, tel_id, tel_type,
63596a65
SJ
1354 search_tel, display_tel, pub)
1355 VALUES ({?}, 'hq', 0, 0, 'fixed', {?}, {?}, 'public'),
1356 ({?}, 'hq', 0, 1, 'fax', {?}, {?}, 'public')",
1357 $id, format_phone_number(Env::v('tel')), $display_tel,
1358 $id, format_phone_number(Env::v('fax')), $display_fax);
1359
1360 XDB::execute("INSERT INTO profile_addresses (jobid, type, id, accuracy,
1361 text, postalText, postalCode, localityId,
1362 subAdministrativeAreaId, administrativeAreaId,
1363 countryId, latitude, longitude, updateTime,
1364 north, south, east, west)
1365 VALUES ({?}, 'hq', 0, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
1366 {?}, {?}, FROM_UNIXTIME({?}), {?}, {?}, {?}, {?})",
1367 $id, $address['accuracy'], $address['text'], $address['postalText'],
1368 $address['postalCode'], $address['localityId'],
1369 $address['subAdministrativeAreaId'], $address['administrativeAreaId'],
1370 $address['countryId'], $address['latitude'], $address['longitude'],
1371 $address['updateTime'], $address['north'], $address['south'],
1372 $address['east'], $address['west']);
1373
4d336f59
SJ
1374 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1375 }
1376 }
1377
1378 if (!Env::has('change') && $id != -1) {
63596a65
SJ
1379 $res = XDB::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1380 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1381 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1382 FROM profile_job_enum AS e
1383 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
ce0b2c6f
FB
1384 LEFT JOIN profile_phones AS t ON (t.pid = e.id AND link_type = 'hq' AND tel_id = 0)
1385 LEFT JOIN profile_phones AS f ON (f.pid = e.id AND link_type = 'hq' AND tel_id = 1)
63596a65
SJ
1386 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1387 WHERE e.id = {?}",
4d336f59
SJ
1388 $id);
1389
1390 if ($res->numRows() == 0) {
1391 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1392 } else {
1393 $page->assign('selectedJob', $res->fetchOneAssoc());
1394 }
1395 }
1396 }
86f0a6af 1397}
1398
a7de4ef7 1399// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
86f0a6af 1400?>