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