Updates ChangeLog (Closes #1035).
[platal.git] / modules / admin.php
CommitLineData
86f0a6af 1<?php
2/***************************************************************************
fc34b3d1 3 * Copyright (C) 2003-2011 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'),
93e38398 28 'get_rights' => $this->make_hook('get_rights', AUTH_COOKIE, 'admin'),
b47cc6f0 29 'set_skin' => $this->make_hook('set_skin', AUTH_COOKIE, 'admin'),
eb5a266d 30 'admin' => $this->make_hook('default', AUTH_MDP, 'admin'),
eb5a266d
SJ
31 'admin/dead-but-active' => $this->make_hook('dead_but_active', AUTH_MDP, 'admin'),
32 'admin/deaths' => $this->make_hook('deaths', AUTH_MDP, 'admin'),
33 'admin/downtime' => $this->make_hook('downtime', AUTH_MDP, 'admin'),
34 'admin/homonyms' => $this->make_hook('homonyms', AUTH_MDP, 'admin'),
35 'admin/logger' => $this->make_hook('logger', AUTH_MDP, 'admin'),
36 'admin/logger/actions' => $this->make_hook('logger_actions', AUTH_MDP, 'admin'),
37 'admin/postfix/blacklist' => $this->make_hook('postfix_blacklist', AUTH_MDP, 'admin'),
38 'admin/postfix/delayed' => $this->make_hook('postfix_delayed', AUTH_MDP, 'admin'),
e7ae7df9 39 'admin/postfix/regexp_bounces' => $this->make_hook('postfix_regexpsbounces', AUTH_MDP, 'admin'),
eb5a266d
SJ
40 'admin/postfix/whitelist' => $this->make_hook('postfix_whitelist', AUTH_MDP, 'admin'),
41 'admin/mx/broken' => $this->make_hook('mx_broken', AUTH_MDP, 'admin'),
42 'admin/skins' => $this->make_hook('skins', AUTH_MDP, 'admin'),
eb5a266d 43 'admin/user' => $this->make_hook('user', AUTH_MDP, 'admin'),
e02d9fbb 44 'admin/add_accounts' => $this->make_hook('add_accounts', AUTH_MDP, 'admin'),
e33b29e5 45 'admin/validate' => $this->make_hook('validate', AUTH_MDP, 'admin,edit_directory'),
eb5a266d
SJ
46 'admin/validate/answers' => $this->make_hook('validate_answers', AUTH_MDP, 'admin'),
47 'admin/wiki' => $this->make_hook('wiki', AUTH_MDP, 'admin'),
48 'admin/ipwatch' => $this->make_hook('ipwatch', AUTH_MDP, 'admin'),
49 'admin/icons' => $this->make_hook('icons', AUTH_MDP, 'admin'),
a7fada4f 50 'admin/geocoding' => $this->make_hook('geocoding', AUTH_MDP, 'admin'),
eb5a266d 51 'admin/accounts' => $this->make_hook('accounts', AUTH_MDP, 'admin'),
8338711c 52 'admin/account/watch' => $this->make_hook('account_watch', AUTH_MDP, 'admin'),
d1e61677 53 'admin/account/types' => $this->make_hook('account_types', AUTH_MDP, 'admin'),
ef7de370 54 'admin/jobs' => $this->make_hook('jobs', AUTH_MDP, 'admin,edit_directory'),
4d5946ac 55 'admin/profile' => $this->make_hook('profile', AUTH_MDP, 'admin,edit_directory')
86f0a6af 56 );
57 }
58
26ba053e 59 function handler_phpinfo($page)
5f9a40b4 60 {
61 phpinfo();
62 exit;
63 }
64
26ba053e 65 function handler_get_rights($page)
866bd535
FB
66 {
67 if (S::suid()) {
68 $page->kill('Déjà en SUID');
69 }
20b087ff
FB
70 S::assert_xsrf_token();
71 $level = Post::s('account_type');
72 if ($level != 'admin') {
73 $user = User::getSilentWithUID(S::user()->id());
74 $user->is_admin = false;
75 $types = DirEnum::getOptions(DirEnum::ACCOUNTTYPES);
76 if (!empty($types[$level])) {
77 $user->setPerms($types[$level]);
78 }
79 S::set('suid_startpage', $_SERVER['HTTP_REFERER']);
80 Platal::session()->startSUID($user);
81 }
82 if (!empty($_SERVER['HTTP_REFERER'])) {
83 http_redirect($_SERVER['HTTP_REFERER']);
84 } else {
85 pl_redirect('/');
86 }
866bd535
FB
87 }
88
26ba053e 89 function handler_set_skin($page)
b47cc6f0
FB
90 {
91 S::assert_xsrf_token();
92 S::set('skin', Post::s('change_skin'));
93 if (!empty($_SERVER['HTTP_REFERER'])) {
94 http_redirect($_SERVER['HTTP_REFERER']);
95 } else {
96 pl_redirect('/');
97 }
98 }
99
26ba053e 100 function handler_default($page)
86f0a6af 101 {
102 $page->changeTpl('admin/index.tpl');
46f272fe 103 $page->setTitle('Administration');
86f0a6af 104 }
105
26ba053e 106 function handler_postfix_delayed($page)
86f0a6af 107 {
108 $page->changeTpl('admin/postfix_delayed.tpl');
46f272fe 109 $page->setTitle('Administration - Postfix : Retardés');
86f0a6af 110
111 if (Env::has('del')) {
112 $crc = Env::v('crc');
113 XDB::execute("UPDATE postfix_mailseen SET release = 'del' WHERE crc = {?}", $crc);
6bb2f79a 114 $page->trigSuccess($crc . " verra tous ses emails supprimés&nbsp;!");
86f0a6af 115 } elseif (Env::has('ok')) {
116 $crc = Env::v('crc');
117 XDB::execute("UPDATE postfix_mailseen SET release = 'ok' WHERE crc = {?}", $crc);
6bb2f79a 118 $page->trigSuccess($crc . " a le droit de passer&nbsp;!");
86f0a6af 119 }
120
121 $sql = XDB::iterator(
122 "SELECT crc, nb, update_time, create_time,
77fcaa3f
SJ
123 FIND_IN_SET('del', p.release) AS del,
124 FIND_IN_SET('ok', p.release) AS ok
125 FROM postfix_mailseen AS p
86f0a6af 126 WHERE nb >= 30
77fcaa3f 127 ORDER BY p.release != ''");
86f0a6af 128
129 $page->assign_by_ref('mails', $sql);
130 }
86f0a6af 131
441e9e98 132 // {{{ logger view
86f0a6af 133
441e9e98 134 /** Retrieves the available days for a given year and month.
135 * Obtain a list of days of the given month in the given year
136 * that are within the range of dates that we have log entries for.
137 *
138 * @param integer year
139 * @param integer month
140 * @return array days in that month we have log entries covering.
141 * @private
142 */
143 function _getDays($year, $month)
144 {
145 // give a 'no filter' option
9bef113f
PC
146 $days = array();
147 $days[0] = "----";
441e9e98 148
149 if ($year && $month) {
150 $day_max = Array(-1, 31, checkdate(2, 29, $year) ? 29 : 28 , 31,
151 30, 31, 30, 31, 31, 30, 31, 30, 31);
152 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
153 MONTH(MAX(start)), MONTH(MIN(start)),
154 DAYOFMONTH(MAX(start)),
155 DAYOFMONTH(MIN(start))
6586a74f 156 FROM log_sessions");
441e9e98 157 list($ymax, $ymin, $mmax, $mmin, $dmax, $dmin) = $res->fetchOneRow();
158
159 if (($year < $ymin) || ($year == $ymin && $month < $mmin)) {
160 return array();
161 }
162
163 if (($year > $ymax) || ($year == $ymax && $month > $mmax)) {
164 return array();
165 }
166
167 $min = ($year==$ymin && $month==$mmin) ? intval($dmin) : 1;
168 $max = ($year==$ymax && $month==$mmax) ? intval($dmax) : $day_max[$month];
169
170 for($i = $min; $i<=$max; $i++) {
171 $days[$i] = $i;
172 }
173 }
174 return $days;
175 }
176
177
178 /** Retrieves the available months for a given year.
179 * Obtains a list of month numbers that are within the timeframe that
180 * we have log entries for.
181 *
182 * @param integer year
183 * @return array List of month numbers we have log info for.
184 * @private
185 */
186 function _getMonths($year)
187 {
188 // give a 'no filter' option
9bef113f 189 $months = array();
441e9e98 190 $months[0] = "----";
191
192 if ($year) {
193 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
194 MONTH(MAX(start)), MONTH(MIN(start))
6586a74f 195 FROM log_sessions");
441e9e98 196 list($ymax, $ymin, $mmax, $mmin) = $res->fetchOneRow();
197
198 if (($year < $ymin) || ($year > $ymax)) {
199 return array();
200 }
201
202 $min = $year == $ymin ? intval($mmin) : 1;
203 $max = $year == $ymax ? intval($mmax) : 12;
204
205 for($i = $min; $i<=$max; $i++) {
206 $months[$i] = $i;
207 }
208 }
209 return $months;
210 }
211
212
213 /** Retrieves the available years.
214 * Obtains a list of years that we have log entries covering.
215 *
216 * @return array years we have log entries for.
217 * @private
218 */
219 function _getYears()
220 {
221 // give a 'no filter' option
9bef113f 222 $years = array();
441e9e98 223 $years[0] = "----";
224
225 // retrieve available years
6586a74f 226 $res = XDB::query("select YEAR(MAX(start)), YEAR(MIN(start)) FROM log_sessions");
441e9e98 227 list($max, $min) = $res->fetchOneRow();
228
229 for($i = intval($min); $i<=$max; $i++) {
230 $years[$i] = $i;
231 }
232 return $years;
233 }
234
235
236 /** Make a where clause to get a user's sessions.
237 * Prepare the where clause request that will retrieve the sessions.
238 *
239 * @param $year INTEGER Only get log entries made during the given year.
240 * @param $month INTEGER Only get log entries made during the given month.
241 * @param $day INTEGER Only get log entries made during the given day.
242 * @param $uid INTEGER Only get log entries referring to the given user ID.
243 *
244 * @return STRING the WHERE clause of a query, including the 'WHERE' keyword
245 * @private
246 */
247 function _makeWhere($year, $month, $day, $uid)
248 {
249 // start constructing the "where" clause
250 $where = array();
251
252 if ($uid)
9bef113f 253 array_push($where, "s.uid='$uid'");
441e9e98 254
255 // we were given at least a year
256 if ($year) {
257 if ($day) {
258 $dmin = mktime(0, 0, 0, $month, $day, $year);
259 $dmax = mktime(0, 0, 0, $month, $day+1, $year);
260 } elseif ($month) {
261 $dmin = mktime(0, 0, 0, $month, 1, $year);
262 $dmax = mktime(0, 0, 0, $month+1, 1, $year);
263 } else {
264 $dmin = mktime(0, 0, 0, 1, 1, $year);
265 $dmax = mktime(0, 0, 0, 1, 1, $year+1);
266 }
267 $where[] = "start >= " . date("Ymd000000", $dmin);
268 $where[] = "start < " . date("Ymd000000", $dmax);
269 }
270
271 if (!empty($where)) {
272 return ' WHERE ' . implode($where, " AND ");
273 } else {
274 return '';
275 }
276 // WE know it's totally reversed, so better use array_reverse than a SORT BY start DESC
277 }
278
279 // }}}
280
26ba053e 281 function handler_logger($page, $action = null, $arg = null) {
441e9e98 282 if ($action == 'session') {
283
284 // we are viewing a session
bdbda592 285 $res = XDB::query("SELECT ls.*, a.hruid AS username, sa.hruid AS suer
6586a74f 286 FROM log_sessions AS ls
bdbda592
FB
287 INNER JOIN accounts AS a ON (a.uid = ls.uid)
288 LEFT JOIN accounts AS sa ON (sa.uid = ls.suid)
441e9e98 289 WHERE ls.id = {?}", $arg);
290
291 $page->assign('session', $a = $res->fetchOneAssoc());
292
504ccd57 293 $res = XDB::iterator('SELECT a.text, e.data, e.stamp
6586a74f
FB
294 FROM log_events AS e
295 LEFT JOIN log_actions AS a ON e.action=a.id
441e9e98 296 WHERE e.session={?}', $arg);
297 while ($myarr = $res->next()) {
298 $page->append('events', $myarr);
299 }
300
c8ab90e7 301 } else {
441e9e98 302 $loguser = $action == 'user' ? $arg : Env::v('loguser');
c8ab90e7
RB
303
304 if ($loguser) {
305 $user = User::get($loguser);
306 $loguid = $user->id();
307 } else {
308 $loguid = null;
309 }
441e9e98 310
311 if ($loguid) {
312 $year = Env::i('year');
313 $month = Env::i('month');
314 $day = Env::i('day');
315 } else {
316 $year = Env::i('year', intval(date('Y')));
317 $month = Env::i('month', intval(date('m')));
318 $day = Env::i('day', intval(date('d')));
319 }
320
321 if (!$year)
322 $month = 0;
323 if (!$month)
324 $day = 0;
325
326 // smarty assignments
327 // retrieve available years
328 $page->assign('years', $this->_getYears());
329 $page->assign('year', $year);
330
331 // retrieve available months for the current year
332 $page->assign('months', $this->_getMonths($year));
333 $page->assign('month', $month);
334
335 // retrieve available days for the current year and month
336 $page->assign('days', $this->_getDays($year, $month));
337 $page->assign('day', $day);
338
339 $page->assign('loguser', $loguser);
340 // smarty assignments
341
342 if ($loguid || $year) {
343
344 // get the requested sessions
345 $where = $this->_makeWhere($year, $month, $day, $loguid);
504ccd57 346 $select = "SELECT s.id, s.start, s.uid,
bdbda592 347 a.hruid as username
6586a74f 348 FROM log_sessions AS s
bdbda592 349 INNER JOIN accounts AS a ON (a.uid = s.uid)
441e9e98 350 $where
351 ORDER BY start DESC";
352 $res = XDB::iterator($select);
353
354 $sessions = array();
355 while ($mysess = $res->next()) {
356 $mysess['events'] = array();
357 $sessions[$mysess['id']] = $mysess;
358 }
359 array_reverse($sessions);
360
361 // attach events
362 $sql = "SELECT s.id, a.text
6586a74f
FB
363 FROM log_sessions AS s
364 LEFT JOIN log_events AS e ON(e.session=s.id)
365 INNER JOIN log_actions AS a ON(a.id=e.action)
441e9e98 366 $where";
367
368 $res = XDB::iterator($sql);
369 while ($event = $res->next()) {
370 array_push($sessions[$event['id']]['events'], $event['text']);
371 }
372 $page->assign_by_ref('sessions', $sessions);
373 } else {
c8ab90e7 374 $page->assign('msg_nofilters', "Sélectionner une année et/ou un utilisateur");
441e9e98 375 }
86f0a6af 376 }
377
8b1f8e12 378 $page->changeTpl('admin/logger-view.tpl');
86f0a6af 379
46f272fe 380 $page->setTitle('Administration - Logs des sessions');
86f0a6af 381 }
382
26ba053e 383 function handler_user($page, $login = false)
f97f90f0 384 {
84270653 385 global $globals;
1412adb2 386 $page->changeTpl('admin/user.tpl');
f9743cf1 387 $page->setTitle('Administration - Compte');
86f0a6af 388
0c02607e 389 if (S::suid()) {
6bb2f79a 390 $page->kill("Déjà en SUID&nbsp;!!!");
86f0a6af 391 }
392
d5fbeef6 393 // Loads the user identity using the environment.
1ac65dd4
PC
394 if ($login) {
395 $user = User::get($login);
396 }
397 if (empty($user)) {
8338711c 398 pl_redirect('admin/accounts');
2ff7e020
VZ
399 }
400
a8a11a70 401 $listClient = new MMList(S::user());
4f903ea6
FB
402 $login = $user->login();
403 $registered = ($user->state != 'pending');
86f0a6af 404
4f903ea6
FB
405 // Form processing
406 if (!empty($_POST)) {
407 S::assert_xsrf_token();
408 if (Post::has('uid') && Post::i('uid') != $user->id()) {
409 $page->kill('Une erreur s\'est produite');
410 }
86f0a6af 411 }
412
d5fbeef6 413 // Handles specific requests (AX sync, su, ...).
9bef113f 414 if(Post::has('log_account')) {
d5fbeef6 415 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
86f0a6af 416 }
417
a19178e9 418 if(Post::has('su_account') && $registered) {
866bd535 419 if (!Platal::session()->startSUID($user)) {
83752d10 420 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->login());
f97f90f0 421 } else {
d5fbeef6 422 pl_redirect("");
eaf30d86 423 }
d5fbeef6 424 }
86f0a6af 425
40965e32
SJ
426 // Handles account deletion.
427 if (Post::has('account_deletion_confirmation')) {
428 $uid = $user->id();
429 $name = $user->fullName();
4cd83ff8 430 $profile = $user->profile();
879d38da 431 if ($profile && Post::b('clear_profile')) {
4cd83ff8
FB
432 $user->profile()->clear();
433 }
40965e32 434 $user->clear(true);
879d38da
FB
435 $page->trigSuccess("L'utilisateur $name ($uid) a bien été désinscrit.");
436 if (Post::b('erase_account')) {
437 XDB::execute('DELETE FROM accounts
438 WHERE uid = {?}',
439 $uid);
440 $page->trigSuccess("L'utilisateur $name ($uid) a été supprimé de la base de données");
441 }
40965e32
SJ
442 }
443
f9743cf1 444 // Account Form {{{
83752d10 445 $to_update = array();
4f903ea6 446 if (Post::has('disable_weak_access')) {
83752d10 447 $to_update['weak_password'] = null;
4f903ea6 448 } else if (Post::has('update_account')) {
aef87266
SJ
449 if (!$user->hasProfile()) {
450 if (Post::s('full_name') != $user->fullName()) {
451 $to_update['full_name'] = Post::s('full_name');
452 }
453 if (Post::s('display_name') != $user->displayName()) {
454 $to_update['display_name'] = Post::s('display_name');
455 }
456 if (Post::s('directory_name') != $user->directoryName()) {
457 $to_update['directory_name'] = Post::s('directory_name');
458 }
d081acb2 459 }
4f903ea6
FB
460 if (Post::s('sex') != ($user->isFemale() ? 'female' : 'male')) {
461 $to_update['sex'] = Post::s('sex');
aef87266
SJ
462 if ($user->hasProfile()) {
463 XDB::execute('UPDATE profiles
464 SET sex = {?}
465 WHERE pid = {?}',
466 Post::s('sex'), $user->profile()->id());
467 }
83752d10 468 }
2477a631
SJ
469 if (!Post::blank('pwhash')) {
470 $to_update['password'] = Post::s('pwhash');
3168041b 471 require_once 'googleapps.inc.php';
1549059d
VZ
472 $account = new GoogleAppsAccount($user);
473 if ($account->active() && $account->sync_password) {
2477a631 474 $account->set_password(Post::s('pwhash'));
1549059d 475 }
83752d10 476 }
4f903ea6
FB
477 if (!Post::blank('weak_password')) {
478 $to_update['weak_password'] = Post::s('weak_password');
83752d10 479 }
4f903ea6
FB
480 if (Post::i('token_access', 0) != ($user->token_access ? 1 : 0)) {
481 $to_update['token'] = Post::i('token_access') ? rand_url_id(16) : null;
83752d10 482 }
fcdbb3bf
SJ
483 if (Post::i('skin') != $user->skin) {
484 $to_update['skin'] = Post::i('skin');
83752d10 485 if ($to_update['skin'] == 0) {
7cfaf494 486 $to_update['skin'] = null;
83752d10
FB
487 }
488 }
4f903ea6
FB
489 if (Post::s('state') != $user->state) {
490 $to_update['state'] = Post::s('state');
83752d10 491 }
4f903ea6
FB
492 if (Post::i('is_admin', 0) != ($user->is_admin ? 1 : 0)) {
493 $to_update['is_admin'] = Post::b('is_admin');
83752d10 494 }
4f903ea6
FB
495 if (Post::s('type') != $user->type) {
496 $to_update['type'] = Post::s('type');
83752d10 497 }
4f903ea6 498 if (Post::i('watch', 0) != ($user->watch ? 1 : 0)) {
83752d10 499 $to_update['flags'] = new PlFlagset();
4f903ea6 500 $to_update['flags']->addFlag('watch', Post::i('watch'));
83752d10 501 }
4f903ea6
FB
502 if (Post::t('comment') != $user->comment) {
503 $to_update['comment'] = Post::blank('comment') ? null : Post::t('comment');
83752d10 504 }
a8a11a70
FB
505 if (!$user->checkPerms(User::PERM_MAIL) && Post::t('email') != $user->forlifeEmail()) {
506 $to_update['email'] = Post::t('email');
507 $listClient->change_user_email($user->forlifeEmail(), Post::t('email'));
508 }
83752d10
FB
509 }
510 if (!empty($to_update)) {
01f78cbb
SJ
511 $res = XDB::query('SELECT *
512 FROM accounts
513 WHERE uid = {?}', $user->id());
514 $oldValues = $res->fetchAllAssoc();
515 $oldValues = $oldValues[0];
516
83752d10 517 $set = array();
01f78cbb 518 $diff = array();
83752d10 519 foreach ($to_update as $k => $value) {
01f78cbb
SJ
520 $value = XDB::format('{?}', $value);
521 $set[] = $k . ' = ' . $value;
522 $diff[$k] = array($oldValues[$k], trim($value, "'"));
523 unset($oldValues[$k]);
83752d10 524 }
a8a11a70
FB
525 XDB::rawExecute('UPDATE accounts
526 SET ' . implode(', ', $set) . '
527 WHERE uid = ' . XDB::format('{?}', $user->id()));
83752d10
FB
528 $page->trigSuccess('Données du compte mise à jour avec succès');
529 $user = User::getWithUID($user->id());
01f78cbb
SJ
530
531 /* Formats the $diff and send it to the site administrators. The rules are the folowing:
532 * -formats: password, token, weak_password
533 */
534 foreach (array('password', 'token', 'weak_password') as $key) {
535 if (isset($diff[$key])) {
536 $diff[$key] = array('old value', 'new value');
537 } else {
538 $oldValues[$key] = 'old value';
539 }
540 }
541
542 $mail = new PlMailer('admin/useredit.mail.tpl');
543 $mail->assign('admin', S::user()->hruid);
544 $mail->assign('hruid', $user->hruid);
545 $mail->assign('diff', $diff);
546 $mail->assign('oldValues', $oldValues);
547 $mail->send();
83752d10 548 }
f9743cf1 549 // }}}
4f903ea6 550
f9743cf1 551 // Profile form {{{
4f903ea6
FB
552 if (Post::has('add_profile') || Post::has('del_profile') || Post::has('owner')) {
553 if (Post::i('del_profile', 0) != 0) {
f9743cf1
FB
554 XDB::execute('DELETE FROM account_profiles
555 WHERE uid = {?} AND pid = {?}',
4f903ea6
FB
556 $user->id(), Post::i('del_profile'));
557 } else if (!Post::blank('new_profile')) {
558 $profile = Profile::get(Post::t('new_profile'));
f9743cf1 559 if (!$profile) {
4f903ea6 560 $page->trigError('Le profil ' . Post::t('new_profile') . ' n\'existe pas');
f9743cf1
FB
561 } else {
562 XDB::execute('INSERT IGNORE INTO account_profiles (uid, pid)
563 VALUES ({?}, {?})',
564 $user->id(), $profile->id());
565 }
566 }
567 XDB::execute('UPDATE account_profiles
568 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
569 WHERE uid = {?}',
4f903ea6 570 Post::i('owner'), $user->id());
f9743cf1 571 }
f9743cf1
FB
572 // }}}
573
4f903ea6
FB
574 // Email forwards form {{{
575 require_once("emails.inc.php");
576 $redirect = ($registered ? new Redirect($user) : null);
577 if (Post::has('add_fwd')) {
578 $email = Post::t('email');
579 if (!isvalid_email_redirection($email)) {
580 $page->trigError("Email non valide: $email");
581 } else {
582 $redirect->add_email($email);
583 $page->trigSuccess("Ajout de $email effectué");
584 }
585 } else if (!Post::blank('del_fwd')) {
586 $redirect->delete_email(Post::t('del_fwd'));
587 } else if (!Post::blank('activate_fwd')) {
afc337ee 588 $redirect->modify_one_email(Post::t('activate_fwd'), true);
4f903ea6 589 } else if (!Post::blank('deactivate_fwd')) {
afc337ee 590 $redirect->modify_one_email(Post::t('deactivate_fwd'), false);
4f903ea6
FB
591 } else if (Post::has('disable_fwd')) {
592 $redirect->disable();
593 } else if (Post::has('enable_fwd')) {
594 $redirect->enable();
595 } else if (!Post::blank('clean_fwd')) {
596 $redirect->clean_errors(Post::t('clean_fwd'));
597 }
598 // }}}
d5fbeef6 599
4f903ea6
FB
600 // Email alias form {{{
601 if (Post::has('add_alias')) {
602 // Splits new alias in user and fqdn.
603 $alias = Env::t('email');
604 if (strpos($alias, '@') !== false) {
605 list($alias, $domain) = explode('@', $alias);
606 } else {
f036c896 607 $domain = $user->mainEmailDomain();
4f903ea6 608 }
84270653 609
4f903ea6
FB
610 // Checks for alias' user validity.
611 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
612 $page->trigError("'$alias' n'est pas un alias valide");
613 }
86f0a6af 614
4f903ea6
FB
615 // Eventually adds the alias to the right domain.
616 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
617 $req = new AliasReq($user, $alias, 'Admin request', false);
618 if ($req->commit()) {
b284e2fa 619 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué.");
4f903ea6 620 } else {
b284e2fa 621 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué.");
4f903ea6 622 }
f036c896 623 } elseif ($domain == $user->mainEmailDomain()) {
b284e2fa 624 XDB::execute('INSERT INTO email_source_account (email, uid, domain, type, flags)
f036c896 625 SELECT {?}, {?}, id, \'alias\', \'\'
b284e2fa
SJ
626 FROM email_virtual_domains
627 WHERE name = {?}',
f036c896 628 $alias, $user->id(), $domain);
4f903ea6
FB
629 $page->trigSuccess("Nouvel alias '$alias' ajouté");
630 } else {
f036c896 631 $page->trigError("Le domaine '$domain' n'est pas valide pour cet utilisateur.");
4f903ea6
FB
632 }
633 } else if (!Post::blank('del_alias')) {
b284e2fa
SJ
634 $delete_alias = Post::t('del_alias');
635 list($email, $domain) = explode('@', $delete_alias);
636 XDB::execute('DELETE s
637 FROM email_source_account AS s
638 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
639 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
f036c896 640 WHERE s.email = {?} AND s.uid = {?} AND d.name = {?} AND type != \'forlife\'',
b284e2fa
SJ
641 $email, $user->id(), $domain);
642 XDB::execute('UPDATE email_redirect_account AS r
643 INNER JOIN email_virtual_domains AS m ON (m.name = {?})
644 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
645 SET r.rewrite = \'\'
646 WHERE r.uid = {?} AND r.rewrite = CONCAT({?}, \'@\', d.name)',
647 $domain, $user->id(), $email);
4f903ea6 648 fix_bestalias($user);
b284e2fa 649 $page->trigSuccess("L'alias '$delete_alias' a été supprimé");
4f903ea6 650 } else if (!Post::blank('best')) {
b284e2fa
SJ
651 $best_alias = Post::t('best');
652 // First delete the bestalias flag from all this user's emails.
653 XDB::execute("UPDATE email_source_account
4f903ea6 654 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
fe13bc1d 655 WHERE uid = {?}", $user->id());
b284e2fa
SJ
656 // Then gives the bestalias flag to the given email.
657 list($email, $domain) = explode('@', $best_alias);
658 XDB::execute("UPDATE email_source_account AS s
659 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
660 SET s.flags = CONCAT_WS(',', IF(s.flags = '', NULL, s.flags), 'bestalias')
661 WHERE s.uid = {?} AND s.email = {?} AND d.name = {?}", $user->id(), $email, $domain);
662
4f903ea6
FB
663 // As having a non-null bestalias value is critical in
664 // plat/al's code, we do an a posteriori check on the
665 // validity of the bestalias.
666 fix_bestalias($user);
667 }
668 // }}}
669cb0e0 669
83353c71
FB
670 // OpenId form {{{
671 if (Post::has('del_openid')) {
864957c1 672 XDB::execute('DELETE FROM account_auth_openid
83353c71
FB
673 WHERE id = {?}', Post::i('del_openid'));
674 }
675 // }}}
676
4f903ea6
FB
677 // Forum form {{{
678 if (Post::has('b_edit')) {
679 XDB::execute("DELETE FROM forum_innd
680 WHERE uid = {?}", $user->id());
681 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
682 XDB::execute("INSERT INTO forum_innd
683 SET ipmin = '0', ipmax = '4294967295',
684 write_perm = {?}, read_perm = {?},
685 comment = {?}, priority = '200', uid = {?}",
686 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
687 }
688 }
689 // }}}
86f0a6af 690
86f0a6af 691
b7bad73e 692 $page->addJsLink('jquery.ui.xorg.js');
669cb0e0 693
d5fbeef6
VZ
694 // Displays last login and last host information.
695 $res = XDB::query("SELECT start, host
6586a74f 696 FROM log_sessions
d5fbeef6
VZ
697 WHERE uid = {?} AND suid = 0
698 ORDER BY start DESC
699 LIMIT 1", $user->id());
700 list($lastlogin,$host) = $res->fetchOneRow();
701 $page->assign('lastlogin', $lastlogin);
702 $page->assign('host', $host);
703
1d889ac4 704 // Display mailing lists
a8a11a70 705 $page->assign('mlists', $listClient->get_all_user_lists($user->forlifeEmail()));
1d889ac4 706
d5fbeef6 707 // Display active aliases.
06a548e5 708 $page->assign('virtuals', $user->emailGroupAliases());
b284e2fa
SJ
709 $aliases = XDB::iterator("SELECT CONCAT(s.email, '@', d.name) AS email, (s.type = 'forlife') AS forlife,
710 (s.email REGEXP '\\\\.[0-9]{2}$') AS hundred_year,
711 FIND_IN_SET('bestalias', s.flags) AS bestalias, s.expire,
08d33afc 712 (s.type = 'alias_aux') AS alias
b284e2fa
SJ
713 FROM email_source_account AS s
714 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
715 WHERE s.uid = {?}
716 ORDER BY !alias, s.email",
08d33afc 717 $user->id());
b284e2fa 718 $page->assign('aliases', $aliases);
8f2104cb
FB
719 $page->assign('account_types', XDB::iterator('SELECT * FROM account_types ORDER BY type'));
720 $page->assign('skins', XDB::iterator('SELECT id, name FROM skins ORDER BY name'));
f9743cf1
FB
721 $page->assign('profiles', XDB::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
722 FROM account_profiles AS ap
723 INNER JOIN profiles AS p ON (ap.pid = p.pid)
724 WHERE ap.uid = {?}', $user->id()));
83353c71 725 $page->assign('openid', XDB::iterator('SELECT id, url
864957c1
FB
726 FROM account_auth_openid
727 WHERE uid = {?}', $user->id()));
d5fbeef6
VZ
728
729 // Displays email redirection and the general profile.
730 if ($registered && $redirect) {
731 $page->assign('emails', $redirect->emails);
732 }
733
d5fbeef6 734 $page->assign('user', $user);
aef87266 735 $page->assign('hasProfile', $user->hasProfile());
d5fbeef6
VZ
736
737 // Displays forum bans.
738 $res = XDB::query("SELECT write_perm, read_perm, comment
7d15f750 739 FROM forum_innd
d5fbeef6
VZ
740 WHERE uid = {?}", $user->id());
741 $bans = $res->fetchOneAssoc();
742 $page->assign('bans', $bans);
86f0a6af 743 }
1f53925a 744
e02d9fbb 745 private static function getHrid($firstname, $lastname, $promo)
7c5200a5 746 {
e02d9fbb 747 if ($firstname != null && $lastname != null && $promo != null) {
69fc05dd 748 return User::makeHrid($firstname, $lastname, $promo);
7c5200a5 749 }
f6eacab0 750 return null;
7c5200a5
VZ
751 }
752
26ba053e 753 private static function formatNewUser($page, $infosLine, $separator, $promo, $size)
1f53925a 754 {
e02d9fbb 755 $infos = explode($separator, $infosLine);
cb0c8b1c
SJ
756 if (sizeof($infos) > $size || sizeof($infos) < 2) {
757 $page->trigError("La ligne $infosLine n'a pas été ajoutée.");
e02d9fbb 758 return false;
1f53925a 759 }
760
16714428 761 $infos = array_map('trim', $infos);
e02d9fbb
SJ
762 $hrid = self::getHrid($infos[1], $infos[0], $promo);
763 $res1 = XDB::query('SELECT COUNT(*)
764 FROM accounts
765 WHERE hruid = {?}', $hrid);
766 $res2 = XDB::query('SELECT COUNT(*)
767 FROM profiles
768 WHERE hrpid = {?}', $hrid);
769 if (is_null($hrid) || $res1->fetchOneCell() > 0 || $res2->fetchOneCell() > 0) {
981fce7b 770 $page->trigError("La ligne $infosLine n'a pas été ajoutée: une entrée similaire existe déjà");
e02d9fbb
SJ
771 return false;
772 }
773 $infos['hrid'] = $hrid;
774 return $infos;
775 }
776
26ba053e 777 private static function formatSex($page, $sex, $line)
e02d9fbb
SJ
778 {
779 switch ($sex) {
780 case 'F':
781 return PlUser::GENDER_FEMALE;
782 case 'M':
783 return PlUser::GENDER_MALE;
784 default:
785 $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
786 return null;
1f53925a 787 }
e02d9fbb 788 }
1f53925a 789
e02d9fbb
SJ
790 private static function formatBirthDate($birthDate)
791 {
16714428
RB
792 // strtotime believes dd/mm/yyyy to be an US date (i.e mm/dd/yyyy), and
793 // dd-mm-yyyy to be a normal date (i.e dd-mm-yyyy)...
794 return date("Y-m-d", strtotime(str_replace('/', '-', $birthDate)));
e02d9fbb
SJ
795 }
796
26ba053e 797 function handler_add_accounts($page, $action = null, $promo = null)
e02d9fbb
SJ
798 {
799 $page->changeTpl('admin/add_accounts.tpl');
800
801 if (Env::has('add_type') && Env::has('people')) {
e02d9fbb
SJ
802 $lines = explode("\n", Env::t('people'));
803 $separator = Env::t('separator');
804 $promotion = Env::i('promotion');
94590511 805 $nameTypes = DirEnum::getOptions(DirEnum::NAMETYPES);
e02d9fbb
SJ
806 $nameTypes = array_flip($nameTypes);
807
808 if (Env::t('add_type') == 'promo') {
809 $type = 'x';
94590511 810 $eduSchools = DirEnum::getOptions(DirEnum::EDUSCHOOLS);
e02d9fbb 811 $eduSchools = array_flip($eduSchools);
94590511 812 $eduDegrees = DirEnum::getOptions(DirEnum::EDUDEGREES);
e02d9fbb 813 $eduDegrees = array_flip($eduDegrees);
e02d9fbb
SJ
814 switch (Env::t('edu_type')) {
815 case 'X':
816 $degreeid = $eduDegrees[Profile::DEGREE_X];
817 $entry_year = $promotion;
818 $grad_year = $promotion + 3;
819 $promo = 'X' . $promotion;
d9e99995 820 $hrpromo = $promotion;
e02d9fbb
SJ
821 break;
822 case 'M':
823 $degreeid = $eduDegrees[Profile::DEGREE_M];
824 $grad_year = $promotion;
825 $entry_year = $promotion - 2;
826 $promo = 'M' . $promotion;
d9e99995
FB
827 $hrpromo = $promo;
828 $type = 'master';
e02d9fbb
SJ
829 break;
830 case 'D':
831 $degreeid = $eduDegrees[Profile::DEGREE_D];
832 $grad_year = $promotion;
833 $entry_year = $promotion - 3;
834 $promo = 'D' . $promotion;
d9e99995
FB
835 $hrpromo = $promo;
836 $type = 'phd';
e02d9fbb
SJ
837 break;
838 default:
839 $page->killError("La formation n'est pas reconnue:" . Env::t('edu_type') . '.');
840 }
841
7f55b0d6 842 XDB::startTransaction();
e02d9fbb 843 foreach ($lines as $line) {
d9e99995 844 if ($infos = self::formatNewUser($page, $line, $separator, $hrpromo, 6)) {
cb0c8b1c
SJ
845 $sex = self::formatSex($page, $infos[3], $line);
846 if (!is_null($sex)) {
4452750b
SJ
847 $fullName = $infos[1] . ' ' . $infos[0];
848 $directoryName = $infos[0] . ' ' . $infos[1];
cb0c8b1c
SJ
849 $birthDate = self::formatBirthDate($infos[2]);
850 $xorgId = Profile::getXorgId($infos[4]);
851 if (is_null($xorgId)) {
852 $page->trigError("La ligne $line n'a pas été ajoutée car le matricule École est mal renseigné.");
853 continue;
854 }
855
856 XDB::execute('INSERT INTO profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex)
857 VALUES ({?}, {?}, {?}, {?}, {?})',
858 $infos['hrid'], $xorgId, $infos[5], $birthDate, $sex);
859 $pid = XDB::insertId();
860 XDB::execute('INSERT INTO profile_name (pid, name, typeid)
d9e99995
FB
861 VALUES ({?}, {?}, {?}),
862 ({?}, {?}, {?}),
863 ({?}, {?}, {?}),
864 ({?}, {?}, {?})',
865 $pid, $infos[0], $nameTypes['name_ini'],
866 $pid, $infos[0], $nameTypes['lastname'],
867 $pid, $infos[1], $nameTypes['firstname_ini'],
868 $pid, $infos[1], $nameTypes['firstname']);
cb0c8b1c
SJ
869 XDB::execute('INSERT INTO profile_display (pid, yourself, public_name, private_name,
870 directory_name, short_name, sort_name, promo)
871 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
4452750b 872 $pid, $infos[1], $fullName, $fullName, $directoryName, $fullName, $directoryName, $promo);
84db0fde
SJ
873 XDB::execute('INSERT INTO profile_education (id, pid, eduid, degreeid, entry_year, grad_year, flags)
874 VALUES (100, {?}, {?}, {?}, {?}, {?}, \'primary\')',
875 $pid, $eduSchools[Profile::EDU_X], $degreeid, $entry_year, $grad_year);
4452750b 876 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, full_name, directory_name, display_name, sex)
d9e99995
FB
877 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
878 $infos['hrid'], $type, 0, 'pending', $fullName, $directoryName, $infos[1], $sex);
cb0c8b1c
SJ
879 $uid = XDB::insertId();
880 XDB::execute('INSERT INTO account_profiles (uid, pid, perms)
881 VALUES ({?}, {?}, {?})',
882 $uid, $pid, 'owner');
bedc4295 883 Profile::rebuildSearchTokens($pid, false);
cb0c8b1c 884 }
e02d9fbb
SJ
885 }
886 }
7f55b0d6 887 XDB::commit();
e02d9fbb
SJ
888 } else if (Env::t('add_type') == 'account') {
889 $type = Env::t('type');
4029afb0 890 $newAccounts = array();
e02d9fbb 891 foreach ($lines as $line) {
cb0c8b1c
SJ
892 if ($infos = self::formatNewUser($page, $line, $separator, $type, 4)) {
893 $sex = self::formatSex($page, $infos[3], $line);
894 if (!is_null($sex)) {
4452750b
SJ
895 $fullName = $infos[1] . ' ' . $infos[0];
896 $directoryName = $infos[0] . ' ' . $infos[1];
d9e99995
FB
897 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state,
898 email, full_name, directory_name,
899 display_name, sex)
900 VALUES ({?}, {?}, {?}, {?},
901 {?}, {?}, {?}, {?}, {?})',
902 $infos['hrid'], $type, 0, 'pending',
903 $infos[2], $fullName, $directoryName,
904 $infos[1], $sex);
4029afb0 905 $newAccounts[$infos['hrid']] = $infos[1] . ' ' . $infos[0];
cb0c8b1c 906 }
e02d9fbb
SJ
907 }
908 }
4029afb0
SJ
909 if (!empty($newAccounts)) {
910 $page->assign('newAccounts', $newAccounts);
911 }
e02d9fbb
SJ
912 } else if (Env::t('add_type') == 'ax_id') {
913 $type = 'x';
914 foreach ($lines as $line) {
cb0c8b1c 915 if ($infos = self::formatNewUser($page, $line, $separator, $promotion, 3)) {
e02d9fbb
SJ
916 XDB::execute('UPDATE profiles
917 SET ax_id = {?}
918 WHERE hrpid = {?}',
919 $infos[2], $infos['hrid']);
920 }
921 }
922 }
923
cb0c8b1c
SJ
924 $errors = $page->nb_errs();
925 if ($errors == 0) {
e02d9fbb
SJ
926 $page->trigSuccess("L'opération a été effectuée avec succès.");
927 } else {
cb0c8b1c
SJ
928 $page->trigSuccess('L\'opération a été effectuée avec succès, sauf pour '
929 . (($errors == 1) ? 'l\'erreur signalée' : "les $errors erreurs signalées") . ' ci-dessus.');
e02d9fbb
SJ
930 }
931 } else if (Env::has('add_type')) {
932 $res = XDB::query('SELECT type
933 FROM account_types');
934 $page->assign('account_types', $res->fetchColumn());
935 $page->assign('add_type', Env::s('add_type'));
1f53925a 936 }
1f53925a 937 }
938
26ba053e 939 function handler_homonyms($page, $op = 'list', $target = null)
7c5200a5 940 {
86f0a6af 941 $page->changeTpl('admin/homonymes.tpl');
46f272fe 942 $page->setTitle('Administration - Homonymes');
191711d5 943 $this->load("homonyms.inc.php");
74c55fd6 944
86f0a6af 945 if ($target) {
4371e993
SJ
946 $user = User::getSilentWithUID($target);
947 if (!$user || !($loginbis = select_if_homonym($user))) {
191711d5 948 $target = 0;
86f0a6af 949 } else {
191711d5 950 $page->assign('user', $user);
86f0a6af 951 $page->assign('loginbis',$loginbis);
952 }
953 }
74c55fd6 954
839a80cf
VZ
955 $page->assign('op', $op);
956 $page->assign('target', $target);
74c55fd6 957
4371e993 958 // When we have a valid target, prepare emails.
86f0a6af 959 if ($target) {
4371e993
SJ
960 require_once 'emails.inc.php';
961 // Examine what operation needs to be performed.
86f0a6af 962 switch ($op) {
963 case 'mail':
40d428d8
VZ
964 S::assert_xsrf_token();
965
191711d5 966 send_warning_homonyme($user, $loginbis);
4371e993 967 fix_bestalias($user);
86f0a6af 968 $op = 'list';
191711d5 969 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
86f0a6af 970 break;
839a80cf 971
86f0a6af 972 case 'correct':
40d428d8
VZ
973 S::assert_xsrf_token();
974
f036c896
SJ
975 XDB::execute('DELETE FROM email_source_account
976 WHERE email = {?} AND type = \'alias\'',
977 $loginbis);
4371e993 978 XDB::execute('INSERT INTO email_source_other (hrmid, email, domain, type, expire)
f036c896 979 SELECT {?}, {?}, id, \'homonym\', NOW()
4371e993
SJ
980 FROM email_virtual_domains
981 WHERE name = {?}',
f88d9154 982 User::makeHomonymHrmid($loginbis), $loginbis, $user->mainEmailDomain());
4371e993 983 fix_bestalias($user);
191711d5 984 send_robot_homonyme($user, $loginbis);
86f0a6af 985 $op = 'list';
191711d5 986 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
86f0a6af 987 break;
988 }
989 }
74c55fd6 990
86f0a6af 991 if ($op == 'list') {
4371e993
SJ
992 // Retrieves homonyms that are already been fixed.
993 $res = XDB::iterator('SELECT o.email AS homonym, f.email AS forlife, o.expire, f.uid
994 FROM email_source_other AS o
995 INNER JOIN homonyms_list AS h ON (o.hrmid = h.hrmid)
996 INNER JOIN email_source_account AS f ON (h.uid = f.uid AND f.type = \'forlife\')
f036c896
SJ
997 WHERE o.expire IS NOT NULL
998 ORDER BY homonym, forlife');
4371e993
SJ
999 $homonyms = array();
1000 while ($item = $res->next()) {
1001 $homonyms[$item['homonym']][] = $item;
1002 }
1003 $page->assign_by_ref('homonyms', $homonyms);
1004
1005 // Retrieves homonyms that needs to be fixed.
1006 $res = XDB::iterator('SELECT e.email AS homonym, f.email AS forlife, e.expire, e.uid, (e.expire < NOW()) AS urgent
1007 FROM email_source_account AS e
1008 INNER JOIN homonyms_list AS l ON (e.uid = l.uid)
1009 INNER JOIN homonyms_list AS h ON (l.hrmid = h.hrmid)
1010 INNER JOIN email_source_account AS f ON (h.uid = f.uid AND f.type = \'forlife\')
f036c896
SJ
1011 WHERE e.expire IS NOT NULL
1012 ORDER BY homonym, forlife');
4371e993
SJ
1013 $homonyms_to_fix = array();
1014 while ($item = $res->next()) {
1015 $homonyms_to_fix[$item['homonym']][] = $item;
1016 }
1017 $page->assign_by_ref('homonyms_to_fix', $homonyms_to_fix);
86f0a6af 1018 }
1019 }
74c55fd6 1020
26ba053e 1021 function handler_deaths($page, $promo = 0, $validate = false)
32b3ac78 1022 {
86f0a6af 1023 $page->changeTpl('admin/deces_promo.tpl');
46f272fe 1024 $page->setTitle('Administration - Deces');
74c55fd6 1025
dcefa8f7
FB
1026 if (!$promo) {
1027 $promo = Env::t('promo', 'X1923');
1028 }
1029 $page->assign('promo', $promo);
1030 if (!$promo) {
1031 return;
1032 }
74c55fd6 1033
40d428d8
VZ
1034 if ($validate) {
1035 S::assert_xsrf_token();
1036
f198bf30 1037 $res = XDB::iterRow('SELECT p.pid, pd.directory_name, p.deathdate
dcefa8f7
FB
1038 FROM profiles AS p
1039 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1040 WHERE pd.promo = {?}', $promo);
1041 while (list($pid, $name, $death) = $res->next()) {
f198bf30 1042 $val = Env::v('death_' . $pid);
71497fb8 1043 if ($val == $death) {
e61326ed
VZ
1044 continue;
1045 }
1046
71497fb8
SJ
1047 if (empty($val)) {
1048 $val = null;
1049 }
dcefa8f7
FB
1050 XDB::execute('UPDATE profiles
1051 SET deathdate = {?}, deathdate_rec = NOW()
f198bf30 1052 WHERE pid = {?}', $val, $pid);
71497fb8
SJ
1053
1054 $page->trigSuccess('Édition du décès de ' . $name . ' (' . ($val ? $val : 'ressuscité') . ').');
1055 if ($val && ($death == '0000-00-00' || empty($death))) {
438b7a0c 1056 $profile = Profile::get($pid);
6150f591
SJ
1057 $profile->clear();
1058 $profile->owner()->clear(false);
e61326ed 1059 }
86f0a6af 1060 }
86f0a6af 1061 }
74c55fd6 1062
f198bf30 1063 $res = XDB::iterator('SELECT p.pid, pd.directory_name, p.deathdate
dcefa8f7
FB
1064 FROM profiles AS p
1065 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1066 WHERE pd.promo = {?}
1067 ORDER BY pd.sort_name', $promo);
71497fb8 1068 $page->assign('profileList', $res);
86f0a6af 1069 }
74c55fd6 1070
26ba053e 1071 function handler_dead_but_active($page)
32b3ac78 1072 {
1c48c2a9 1073 $page->changeTpl('admin/dead_but_active.tpl');
46f272fe 1074 $page->setTitle('Administration - Décédés');
1c48c2a9
VZ
1075
1076 $res = XDB::iterator(
e46cf8c4 1077 "SELECT a.hruid, pd.promo, p.ax_id, pd.directory_name, p.deathdate, DATE(MAX(s.start)) AS last
fe13bc1d
FB
1078 FROM accounts AS a
1079 INNER JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET('owner', ap.perms))
1080 INNER JOIN profiles AS p ON (p.pid = ap.pid)
1081 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
6586a74f 1082 LEFT JOIN log_sessions AS s ON (s.uid = a.uid AND suid = 0)
e46cf8c4 1083 WHERE a.state = 'active' AND p.deathdate IS NOT NULL
dcefa8f7 1084 GROUP BY a.uid
e46cf8c4 1085 ORDER BY pd.promo, pd.sort_name");
1c48c2a9
VZ
1086 $page->assign('dead', $res);
1087 }
1088
26ba053e 1089 function handler_validate($page, $action = 'list', $id = null)
e654517d 1090 {
764b894d 1091 $page->changeTpl('admin/validation.tpl');
46f272fe 1092 $page->setTitle('Administration - Valider une demande');
84163d58 1093 $page->addCssLink('nl.Polytechnique.org.css');
e654517d 1094
5b8c317d 1095 if ($action == 'edit' && !is_null($id)) {
ed5b9703 1096 $page->assign('preview_id', $id);
5b8c317d
SJ
1097 } else {
1098 $page->assign('preview_id', null);
ed5b9703 1099 }
1100
86f0a6af 1101 if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
40d428d8
VZ
1102 S::assert_xsrf_token();
1103
20d7932b 1104 $req = Validate::get_typed_request(Env::v('uid'), Env::v('type'), Env::v('stamp'));
343e22c2
FB
1105 if ($req) {
1106 $req->handle_formu();
1107 } else {
1108 $page->trigWarning('La validation a déjà été effectuée.');
1109 }
86f0a6af 1110 }
74c55fd6 1111
cfb96867 1112 $r = XDB::iterator('SHOW COLUMNS FROM requests_answers');
1113 while (($a = $r->next()) && $a['Field'] != 'category');
1114 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
74c55fd6 1115
cfb96867 1116 $hidden = array();
257ae408
SJ
1117 $res = XDB::query('SELECT hidden_requests
1118 FROM requests_hidden
1119 WHERE uid = {?}', S::v('uid'));
e0d7c076 1120 $hide_requests = $res->fetchOneCell();
cfb96867 1121 if (Post::has('hide')) {
74c55fd6 1122 $hide = array();
1123 foreach ($categories as $cat)
cfb96867 1124 if (!Post::v($cat)) {
1125 $hidden[$cat] = 1;
1126 $hide[] = $cat;
1127 }
e0d7c076 1128 $hide_requests = join(',', $hide);
00ba8a74
SJ
1129 XDB::query('INSERT INTO requests_hidden (uid, hidden_requests)
1130 VALUES ({?}, {?})
1131 ON DUPLICATE KEY UPDATE hidden_requests = VALUES(hidden_requests)',
e0d7c076
SJ
1132 S::v('uid'), $hide_requests);
1133 } elseif ($hide_requests) {
1134 foreach (explode(',', $hide_requests) as $hide_type)
cfb96867 1135 $hidden[$hide_type] = true;
1136 }
1137 $page->assign('hide_requests', $hidden);
74c55fd6 1138
90df2530
FB
1139 // Update the count of item to validate here... useful in development configuration
1140 // where several copies of the site use the same DB, but not the same "dynamic configuration"
ebfdf077
FB
1141 global $globals;
1142 $globals->updateNbValid();
7b094a73 1143 $page->assign('vit', Validate::iterate());
e33b29e5 1144 $page->assign('isAdmin', S::admin());
86f0a6af 1145 }
e654517d 1146
26ba053e 1147 function handler_validate_answers($page, $action = 'list', $id = null)
32b3ac78 1148 {
46f272fe 1149 $page->setTitle('Administration - Réponses automatiques de validation');
a7de4ef7 1150 $page->assign('title', 'Gestion des réponses automatiques');
e18888f4 1151 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
a7de4ef7 1152 $table_editor->describe('category','catégorie',true);
e18888f4 1153 $table_editor->describe('title','titre',true);
1154 $table_editor->describe('answer','texte',false);
1155 $table_editor->apply($page, $action, $id);
1156 }
32b3ac78 1157
26ba053e 1158 function handler_skins($page, $action = 'list', $id = null)
32b3ac78 1159 {
46f272fe 1160 $page->setTitle('Administration - Skins');
e7ae7df9 1161 $page->assign('title', 'Gestion des skins');
1162 $table_editor = new PLTableEditor('admin/skins','skins','id');
1163 $table_editor->describe('name','nom',true);
1164 $table_editor->describe('skin_tpl','nom du template',true);
1165 $table_editor->describe('auteur','auteur',false);
1166 $table_editor->describe('comment','commentaire',true);
1167 $table_editor->describe('date','date',false);
1168 $table_editor->describe('ext','extension du screenshot',false);
1169 $table_editor->apply($page, $action, $id);
74c55fd6 1170 }
669cb0e0 1171
26ba053e 1172 function handler_postfix_blacklist($page, $action = 'list', $id = null)
32b3ac78 1173 {
46f272fe 1174 $page->setTitle('Administration - Postfix : Blacklist');
e7ae7df9 1175 $page->assign('title', 'Blacklist de postfix');
1176 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true);
1177 $table_editor->describe('reject_text','Texte de rejet',true);
1178 $table_editor->describe('email','email',true);
1179 $table_editor->apply($page, $action, $id);
74c55fd6 1180 }
32b3ac78 1181
26ba053e 1182 function handler_postfix_whitelist($page, $action = 'list', $id = null)
32b3ac78 1183 {
46f272fe 1184 $page->setTitle('Administration - Postfix : Whitelist');
e7ae7df9 1185 $page->assign('title', 'Whitelist de postfix');
1186 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true);
1187 $table_editor->describe('email','email',true);
1188 $table_editor->apply($page, $action, $id);
74c55fd6 1189 }
32b3ac78 1190
26ba053e 1191 function handler_mx_broken($page, $action = 'list', $id = null)
32b3ac78 1192 {
46f272fe 1193 $page->setTitle('Administration - MX Défaillants');
a7de4ef7 1194 $page->assign('title', 'MX Défaillant');
ccdbc270 1195 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true);
1196 $table_editor->describe('host', 'Masque', true);
1197 $table_editor->describe('state', 'Niveau', true);
a7de4ef7 1198 $table_editor->describe('text', 'Description du problème', false);
ccdbc270 1199 $table_editor->apply($page, $action, $id);
1200 }
32b3ac78 1201
26ba053e 1202 function handler_logger_actions($page, $action = 'list', $id = null)
32b3ac78 1203 {
46f272fe 1204 $page->setTitle('Administration - Actions');
e7ae7df9 1205 $page->assign('title', 'Gestion des actions de logger');
6586a74f 1206 $table_editor = new PLTableEditor('admin/logger/actions','log_actions','id');
a7de4ef7 1207 $table_editor->describe('text','intitulé',true);
e7ae7df9 1208 $table_editor->describe('description','description',true);
1209 $table_editor->apply($page, $action, $id);
74c55fd6 1210 }
32b3ac78 1211
26ba053e 1212 function handler_downtime($page, $action = 'list', $id = null)
8f2104cb 1213 {
46f272fe 1214 $page->setTitle('Administration - Coupures');
e7ae7df9 1215 $page->assign('title', 'Gestion des coupures');
06f4daf9 1216 $table_editor = new PLTableEditor('admin/downtime','downtimes','id');
e7ae7df9 1217 $table_editor->describe('debut','date',true);
a7de4ef7 1218 $table_editor->describe('duree','durée',false);
1219 $table_editor->describe('resume','résumé',true);
1220 $table_editor->describe('services','services affectés',true);
e7ae7df9 1221 $table_editor->describe('description','description',false);
1222 $table_editor->apply($page, $action, $id);
74c55fd6 1223 }
bc0903c7 1224
a7fada4f
SJ
1225 private static function isCountryIncomplete(array &$item)
1226 {
1227 $warning = false;
1228 foreach (array('worldRegion', 'country', 'capital', 'phonePrefix', 'licensePlate', 'countryPlain') as $field) {
1229 if ($item[$field] == '') {
1230 $item[$field . '_warning'] = true;
1231 $warning = true;
1232 }
1233 }
1234 if (is_null($item['belongsTo'])) {
1235 foreach (array('nationality', 'nationalityEn') as $field) {
1236 if ($item[$field] == '') {
1237 $item[$field . '_warning'] = true;
1238 $warning = true;
1239 }
1240 }
1241 }
1242 return $warning;
1243 }
1244
846bfc83
SJ
1245 private static function updateCountry(array $item)
1246 {
1247 XDB::execute('UPDATE geoloc_countries
1248 SET countryPlain = {?}
1249 WHERE iso_3166_1_a2 = {?}',
1250 mb_strtoupper(replace_accent($item['country'])), $item['iso_3166_1_a2']);
1251 }
1252
a7fada4f
SJ
1253 private static function isLanguageIncomplete(array &$item)
1254 {
1255 if ($item['language'] == '') {
1256 $item['language_warning'] = true;
1257 return true;
1258 }
1259 return false;
1260 }
1261
846bfc83
SJ
1262 private static function updateLanguage(array $item) {}
1263
1264 function handler_geocoding(&$page, $category = null, $action = null, $id = null)
a7fada4f
SJ
1265 {
1266 // Warning, this handler requires the following packages:
1267 // * pkg-isocodes
1268 // * isoquery
1269
1270 static $properties = array(
1271 'country' => array(
1272 'name' => 'pays',
1273 'isocode' => '3166',
1274 'table' => 'geoloc_countries',
1275 'id' => 'iso_3166_1_a2',
1276 'main_fields' => array('iso_3166_1_a3', 'iso_3166_1_num', 'countryEn'),
1277 'other_fields' => array('worldRegion', 'country', 'capital', 'nationality', 'nationalityEn',
846bfc83 1278 'phonePrefix', 'phoneFormat', 'licensePlate', 'belongsTo')
a7fada4f
SJ
1279 ),
1280 'language' => array(
1281 'name' => 'langages',
1282 'isocode' => '639',
1283 'table' => 'profile_langskill_enum',
1284 'id' => 'iso_639_2b',
1285 'main_fields' => array('iso_639_2t', 'iso_639_1', 'language_en'),
1286 'other_fields' => array('language')
1287
1288 )
1289 );
a7fada4f 1290
846bfc83 1291 if (is_null($category) || !array_key_exists($category, $properties)) {
a7fada4f
SJ
1292 pl_redirect('admin');
1293 }
1294
846bfc83
SJ
1295 $data = $properties[$category];
1296
1297 if ($action == 'edit' || $action == 'add') {
1298 $main_fields = array_merge(array($data['id']), $data['main_fields']);
1299 $all_fields = array_merge($main_fields, $data['other_fields']);
1300
1301 if (is_null($id)) {
1302 if (Post::has('new_id')) {
1303 $id = Post::v('new_id');
1304 } else {
1305 pl_redirect('admin/geocoding/' . $category);
1306 }
1307 }
1308
1309 $list = array();
1310 exec('isoquery --iso=' . $data['isocode'] . ' ' . $id, $list);
1311 if (count($list) == 1) {
1312 $array = explode("\t", $list[0]);
1313 foreach ($main_fields as $i => $field) {
1314 $iso[$field] = $array[$i];
1315 }
1316 } else {
1317 $iso = array();
1318 }
1319
1320 if ($action == 'add') {
1321 if (Post::has('new_id')) {
1322 S::assert_xsrf_token();
1323 }
1324
1325 if (count($iso)) {
1326 $item = $iso;
1327 } else {
1328 $item = array($data['id'] => $id);
1329 }
1330 XDB::execute('INSERT INTO ' . $data['table'] . '(' . implode(', ', array_keys($item)) . ')
1331 VALUES ' . XDB::formatArray($item));
1332 $page->trigSuccess($id . ' a bien été ajouté à la base.');
1333 } elseif ($action == 'edit') {
1334 if (Post::has('edit')) {
1335 S::assert_xsrf_token();
1336
1337 $item = array();
1338 $set = array();
1339 foreach ($all_fields as $field) {
1340 $item[$field] = Post::t($field);
1341 $set[] = $field . XDB::format(' = {?}', ($item[$field] ? $item[$field] : null));
1342 }
1343 XDB::execute('UPDATE ' . $data['table'] . '
1344 SET ' . implode(', ', $set) . '
1345 WHERE ' . $data['id'] . ' = {?}',
1346 $id);
1347 call_user_func_array(array('self', 'update' . ucfirst($category)), array($item));
1348 $page->trigSuccess($id . ' a bien été mis à jour.');
1349 } elseif (Post::has('del')) {
1350 S::assert_xsrf_token();
1351
1352 XDB::execute('DELETE FROM ' . $data['table'] . '
1353 WHERE ' . $data['id'] . ' = {?}',
1354 $id);
1355 $page->trigSuccessRedirect($id . ' a bien été supprimé.', 'admin/geocoding/' . $category);
1356 } else {
1357 $item = XDB::fetchOneAssoc('SELECT *
1358 FROM ' . $data['table'] . '
1359 WHERE ' . $data['id'] . ' = {?}',
1360 $id);
1361 }
1362 }
1363
1364 $page->changeTpl('admin/geocoding_edit.tpl');
1365 $page->setTitle('Administration - ' . ucfirst($data['name']));
1366 $page->assign('category', $category);
1367 $page->assign('name', $data['name']);
1368 $page->assign('all_fields', $all_fields);
1369 $page->assign('id', $id);
1370 $page->assign('iso', $iso);
1371 $page->assign('item', $item);
1372 return;
1373 }
a7fada4f
SJ
1374
1375 $page->changeTpl('admin/geocoding.tpl');
1376 $page->setTitle('Administration - ' . ucfirst($data['name']));
846bfc83 1377 $page->assign('category', $category);
a7fada4f
SJ
1378 $page->assign('name', $data['name']);
1379 $page->assign('id', $data['id']);
1380 $page->assign('main_fields', $data['main_fields']);
1381 $page->assign('all_fields', array_merge($data['main_fields'], $data['other_fields']));
1382
1383 // First build the list provided by the iso codes.
1384 $list = array();
1385 exec('isoquery --iso=' . $data['isocode'], $list);
1386
1387 foreach ($list as $key => $item) {
1388 $array = explode("\t", $item);
1389 unset($list[$key]);
1390 $list[$array[0]] = array();
1391 foreach ($data['main_fields'] as $i => $field) {
1392 $list[$array[0]][$field] = $array[$i + 1];
1393 }
1394 }
1395 ksort($list);
1396
1397 // Retrieve all data from the database.
1398 $db_list = XDB::rawFetchAllAssoc('SELECT *
1399 FROM ' . $data['table'] . '
1400 ORDER BY ' . $data['id'],
1401 $data['id']);
1402
1403 // Sort both iso and database data into 5 categories:
1404 // $missing: data from the iso list not in the database,
1405 // $non_existing: data from the database not in the iso list,
1406 // $erroneous: data that differ on main fields,
1407 // $incomplete: data with empty fields in the data base,
1408 // $remaining: remaining correct and complete data from the database.
1409
1410 $missing = $non_existing = $erroneous = $incomplete = $remaining = array();
1411 foreach (array_keys($list) as $id) {
1412 if (!array_key_exists($id, $db_list)) {
1413 $missing[$id] = $list[$id];
1414 }
1415 }
1416
1417 foreach ($db_list as $id => $item) {
1418 if (!array_key_exists($id, $list)) {
1419 $non_existing[$id] = $item;
1420 } else {
1421 $error = false;
1422 foreach ($data['main_fields'] as $field) {
1423 if ($item[$field] != $list[$id][$field]) {
1424 $item[$field . '_error'] = true;
1425 $error = true;
1426 }
1427 }
1428 if ($error == true) {
1429 $erroneous[$id] = $item;
846bfc83 1430 } elseif (call_user_func_array(array('self', 'is' . ucfirst($category) . 'Incomplete'), array(&$item))) {
a7fada4f
SJ
1431 $incomplete[$id] = $item;
1432 } else {
1433 $remaining[$id] = $item;
1434 }
1435 }
1436 }
1437
1438 $page->assign('lists', array(
1439 'manquant' => $missing,
1440 'disparu' => $non_existing,
1441 'erroné' => $erroneous,
1442 'incomplet' => $incomplete,
1443 'restant' => $remaining
1444 ));
1445 }
1446
8338711c
FB
1447 function handler_accounts(PlPage $page)
1448 {
1449 $page->changeTpl('admin/accounts.tpl');
1450 $page->setTitle('Administration - Comptes');
8338711c
FB
1451
1452 if (Post::has('create_account')) {
1453 S::assert_xsrf_token();
1454 $firstname = Post::t('firstname');
1455 $lastname = strtoupper(Post::t('lastname'));
e8c61abe 1456 $sex = Post::s('sex');
8338711c 1457 $email = Post::t('email');
67cff520
FB
1458 $type = Post::s('type');
1459 $login = PlUser::makeHrid($firstname, $lastname, $type);
8338711c
FB
1460 if (!isvalid_email($email)) {
1461 $page->trigError("Invalid email address: $email");
1462 } else if (strlen(Post::s('pwhash')) != 40) {
1463 $page->trigError("Invalid password hash");
1464 } else {
1465 $full_name = $firstname . ' ' . $lastname;
1466 $directory_name = $lastname . ' ' . $firstname;
1467 XDB::execute("INSERT INTO accounts (hruid, type, state, password,
1468 registration_date, email, full_name,
1469 display_name, sex, directory_name)
67cff520
FB
1470 VALUES ({?}, {?}, 'active', {?}, NOW(), {?}, {?}, {?}, {?}, {?})",
1471 $login, $type, Post::s('pwhash'), $email, $full_name, $full_name, $sex,
8338711c
FB
1472 $directory_name);
1473 }
1474 }
1475
67cff520
FB
1476 $uf = new UserFilter(new UFC_AccountType('ax', 'school', 'fx'));
1477 $page->assign('users', $uf->iterUsers());
8338711c
FB
1478
1479 }
1480
26ba053e 1481 function handler_account_types($page, $action = 'list', $id = null)
8f2104cb
FB
1482 {
1483 $page->setTitle('Administration - Types de comptes');
1484 $page->assign('title', 'Gestion des types de comptes');
1485 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true);
1486 $table_editor->describe('type', 'Catégorie', true);
1487 $table_editor->describe('perms', 'Permissions associées', true);
1488 $table_editor->apply($page, $action, $id);
1489 }
1490
26ba053e 1491 function handler_wiki($page, $action = 'list', $wikipage = null, $wikipage2 = null)
bc0903c7 1492 {
84fc72ff 1493 if (S::hasAuthToken()) {
a2b461ce 1494 $page->setRssLink('Changement Récents',
2ab3486b 1495 '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::user()->token);
a2b461ce 1496 }
e61326ed 1497
3aec1c21 1498 // update wiki perms
40d428d8
VZ
1499 if ($action == 'update') {
1500 S::assert_xsrf_token();
1501
3aec1c21 1502 $perms_read = Post::v('read');
8f201b69 1503 $perms_edit = Post::v('edit');
3aec1c21 1504 if ($perms_read || $perms_edit) {
8f201b69
FB
1505 foreach ($_POST as $wiki_page => $val) {
1506 if ($val == 'on') {
1507 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1508 if ($wp->setPerms($perms_read ? $perms_read : $wp->readPerms(),
1509 $perms_edit ? $perms_edit : $wp->writePerms())) {
1510 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1511 } else {
1512 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1513 }
1514 }
3aec1c21 1515 }
1516 }
8f201b69
FB
1517 } else if ($action != 'list' && !empty($wikipage)) {
1518 $wp = new PlWikiPage($wikipage);
40d428d8
VZ
1519 S::assert_xsrf_token();
1520
8f201b69
FB
1521 if ($action == 'delete') {
1522 if ($wp->delete()) {
1523 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1524 } else {
1525 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1526 }
1527 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1528 if ($changedLinks = $wp->rename($wikipage2)) {
1529 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1530 if (is_numeric($changedLinks)) {
1531 $s .= $changedLinks.' lien'.(($changedLinks>1)?'s ont été modifiés.':' a été modifié.');
1532 }
1533 $page->trigSuccess($s);
1534 } else {
1535 $page->trigError("Impossible de déplacer la page ".$wikipage);
9162f4ed 1536 }
9162f4ed 1537 }
1538 }
74c55fd6 1539
8f201b69 1540 $perms = PlWikiPage::permOptions();
74c55fd6 1541
3aec1c21 1542 // list wiki pages and their perms
8f201b69 1543 $wiki_pages = PlWikiPage::listPages();
3aec1c21 1544 ksort($wiki_pages);
bc0903c7 1545 $wiki_tree = array();
1546 foreach ($wiki_pages as $file => $desc) {
1547 list($cat, $name) = explode('.', $file);
1548 if (!isset($wiki_tree[$cat])) {
1549 $wiki_tree[$cat] = array();
1550 }
1551 $wiki_tree[$cat][$name] = $desc;
1552 }
1553
3aec1c21 1554 $page->changeTpl('admin/wiki.tpl');
bc0903c7 1555 $page->assign('wiki_pages', $wiki_tree);
3aec1c21 1556 $page->assign('perms_opts', $perms);
1557 }
5480a216 1558
26ba053e 1559 function handler_ipwatch($page, $action = 'list', $ip = null)
eaf30d86 1560 {
5480a216 1561 $page->changeTpl('admin/ipwatcher.tpl');
eaf30d86 1562
5480a216 1563 $states = array('safe' => 'Ne pas surveiller',
c339246f 1564 'unsafe' => 'Surveiller les inscriptions',
a7de4ef7 1565 'dangerous' => 'Surveiller tous les accès',
5480a216 1566 'ban' => 'Bannir cette adresse');
1567 $page->assign('states', $states);
1568
1569 switch (Post::v('action')) {
e61326ed 1570 case 'create':
5480a216 1571 if (trim(Post::v('ipN')) != '') {
40d428d8 1572 S::assert_xsrf_token();
61c98f4b
FB
1573 Xdb::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1574 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1575 ip_to_uint(trim(Post::v('ipN'))), ip_to_uint(trim(Post::v('maskN'))),
1576 Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
eaf30d86
PH
1577 };
1578 break;
1579
e61326ed 1580 case 'edit':
40d428d8 1581 S::assert_xsrf_token();
eaf30d86 1582 Xdb::execute('UPDATE ip_watch
61c98f4b 1583 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
9797734d 1584 WHERE ip = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'),
61c98f4b 1585 ip_to_uint(Post::v('maskN')), ip_to_uint(Post::v('ipN')));
5480a216 1586 break;
eaf30d86 1587
e61326ed 1588 default:
5480a216 1589 if ($action == 'delete' && !is_null($ip)) {
40d428d8
VZ
1590 S::assert_xsrf_token();
1591 Xdb::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
5480a216 1592 }
1593 }
1594 if ($action != 'create' && $action != 'edit') {
1595 $action = 'list';
1596 }
1597 $page->assign('action', $action);
1598
1599 if ($action == 'list') {
9797734d
FB
1600 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1601 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1602 IF(w.ip = s.ip, s.host, s.forward_host)),
32b3ac78 1603 w.mask, w.detection, w.state, a.hruid
fe13bc1d 1604 FROM ip_watch AS w
6586a74f
FB
1605 LEFT JOIN log_sessions AS s ON (s.ip = w.ip)
1606 LEFT JOIN log_sessions AS s2 ON (s2.forward_ip = w.ip)
fe13bc1d 1607 LEFT JOIN accounts AS a ON (a.uid = s.uid)
32b3ac78
FB
1608 GROUP BY w.ip, a.hruid
1609 ORDER BY w.state, w.ip, a.hruid";
5480a216 1610 $it = Xdb::iterRow($sql);
1611
1612 $table = array();
1613 $props = array();
90c614cd 1614 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
9797734d 1615 $ip = uint_to_ip($ip);
61c98f4b 1616 $mask = uint_to_ip($mask);
5480a216 1617 if (count($props) == 0 || $props['ip'] != $ip) {
1618 if (count($props) > 0) {
1619 $table[] = $props;
1620 }
1621 $props = array('ip' => $ip,
61c98f4b 1622 'mask' => $mask,
5480a216 1623 'host' => $host,
1624 'detection' => $date,
1625 'state' => $state,
90c614cd 1626 'users' => array($hruid));
5480a216 1627 } else {
90c614cd 1628 $props['users'][] = $hruid;
5480a216 1629 }
1630 }
1631 if (count($props) > 0) {
1632 $table[] = $props;
1633 }
1634 $page->assign('table', $table);
1635 } elseif ($action == 'edit') {
61c98f4b 1636 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
32b3ac78 1637 a1.hruid AS edit, a2.hruid AS hruid, s.host
fe13bc1d
FB
1638 FROM ip_watch AS w
1639 LEFT JOIN accounts AS a1 ON (a1.uid = w.uid)
6586a74f 1640 LEFT JOIN log_sessions AS s ON (w.ip = s.ip)
fe13bc1d 1641 LEFT JOIN accounts AS a2 ON (a2.uid = s.uid)
5480a216 1642 WHERE w.ip = {?}
32b3ac78
FB
1643 GROUP BY a2.hruid
1644 ORDER BY a2.hruid";
9797734d 1645 $it = Xdb::iterRow($sql, ip_to_uint($ip));
5480a216 1646
1647 $props = array();
90c614cd 1648 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
5480a216 1649 if (count($props) == 0) {
1650 $props = array('ip' => $ip,
61c98f4b 1651 'mask' => uint_to_ip($mask),
5480a216 1652 'host' => $host,
1653 'detection' => $detection,
1654 'state' => $state,
1655 'last' => $last,
1656 'description' => $description,
1657 'edit' => $edit,
90c614cd 1658 'users' => array($hruid));
5480a216 1659 } else {
90c614cd 1660 $props['users'][] = $hruid;
5480a216 1661 }
1662 }
1663 $page->assign('ip', $props);
1664 }
1665 }
eaf30d86 1666
26ba053e 1667 function handler_icons($page)
f141945d 1668 {
1669 $page->changeTpl('admin/icons.tpl');
1670 $dh = opendir('../htdocs/images/icons');
1671 if (!$dh) {
a7d35093 1672 $page->trigError('Dossier des icones introuvables.');
f141945d 1673 }
1674 $icons = array();
1675 while (($file = readdir($dh)) !== false) {
1676 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1677 array_push($icons, substr($file, 0, -4));
1678 }
1679 }
1680 sort($icons);
1681 $page->assign('icons', $icons);
04148a2c 1682 }
fd1ce8c5 1683
26ba053e 1684 function handler_account_watch($page)
fd1ce8c5
FB
1685 {
1686 $page->changeTpl('admin/accounts.tpl');
32b3ac78
FB
1687 $page->assign('disabled', XDB::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1688 a.state = \'disabled\' AS disabled, a.comment
1689 FROM accounts AS a
1690 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1691 ORDER BY a.hruid'));
1692 $page->assign('admins', XDB::iterator('SELECT a.hruid
1693 FROM accounts AS a
1694 WHERE a.is_admin
1695 ORDER BY a.hruid'));
fd1ce8c5 1696 }
4d336f59 1697
26ba053e 1698 function handler_jobs($page, $id = -1)
4d336f59
SJ
1699 {
1700 $page->changeTpl('admin/jobs.tpl');
1701
1702 if (Env::has('search')) {
308bbdb0
SJ
1703 $res = XDB::query("SELECT id, name, acronym
1704 FROM profile_job_enum
1705 WHERE name LIKE CONCAT('%', {?}, '%') OR acronym LIKE CONCAT('%', {?}, '%')",
4d336f59
SJ
1706 Env::t('job'), Env::t('job'));
1707
1708 if ($res->numRows() <= 20) {
1709 $page->assign('jobs', $res->fetchAllAssoc());
1710 } else {
1711 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1712 }
1713
1714 $page->assign('askedJob', Env::v('job'));
1715 return;
1716 }
1717
1718 if (Env::has('edit')) {
1719 S::assert_xsrf_token();
1720 $selectedJob = Env::has('selectedJob');
1721
0b6c8b36 1722 Phone::deletePhones(0, Phone::LINK_COMPANY, $id);
781a24bc 1723 Address::deleteAddresses(null, Address::LINK_COMPANY, $id);
4d336f59 1724 if (Env::has('change')) {
e954a945
SJ
1725 if (Env::has('newJobId') && Env::i('newJobId') > 0) {
1726 XDB::execute('UPDATE profile_job
1727 SET jobid = {?}
1728 WHERE jobid = {?}',
1729 Env::i('newJobId'), $id);
1730 XDB::execute('DELETE FROM profile_job_enum
1731 WHERE id = {?}',
1732 $id);
1733
1734 $page->trigSuccess("L'entreprise a bien été remplacée.");
1735 } else {
1736 $page->trigError("L'entreprise n'a pas été remplacée car l'identifiant fourni n'est pas valide.");
1737 }
4d336f59
SJ
1738 } else {
1739 XDB::execute('UPDATE profile_job_enum
1740 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1741 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1742 WHERE id = {?}',
1743 Env::t('name'), Env::t('acronym'), Env::t('url'), Env::t('email'),
e4fb72eb
SJ
1744 (Env::t('NAF_code') == 0 ? null : Env::t('NAF_code')),
1745 (Env::i('AX_code') == 0 ? null : Env::t('AX_code')),
1746 (Env::i('holdingId') == 0 ? null : Env::t('holdingId')), $id);
4d336f59 1747
0b6c8b36
SJ
1748 $phone = new Phone(array('display' => Env::v('tel'), 'link_id' => $id, 'id' => 0, 'type' => 'fixed',
1749 'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
1750 $fax = new Phone(array('display' => Env::v('fax'), 'link_id' => $id, 'id' => 1, 'type' => 'fax',
1751 'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
c32bed90 1752 $address = new Address(array('jobid' => $id, 'type' => Address::LINK_COMPANY, 'text' => Env::t('address')));
0b6c8b36
SJ
1753 $phone->save();
1754 $fax->save();
a710dfd7 1755 $address->save();
63596a65 1756
4d336f59
SJ
1757 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1758 }
1759 }
1760
1761 if (!Env::has('change') && $id != -1) {
63596a65
SJ
1762 $res = XDB::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1763 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1764 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1765 FROM profile_job_enum AS e
1766 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
9483a7c7
SJ
1767 LEFT JOIN profile_phones AS t ON (t.pid = e.id AND t.link_type = 'hq' AND t.tel_id = 0)
1768 LEFT JOIN profile_phones AS f ON (f.pid = e.id AND f.link_type = 'hq' AND f.tel_id = 1)
63596a65
SJ
1769 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1770 WHERE e.id = {?}",
4d336f59
SJ
1771 $id);
1772
1773 if ($res->numRows() == 0) {
1774 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1775 } else {
1776 $page->assign('selectedJob', $res->fetchOneAssoc());
1777 }
1778 }
1779 }
4d5946ac 1780
26ba053e 1781 function handler_profile($page)
4d5946ac
SJ
1782 {
1783 $page->changeTpl('admin/profile.tpl');
1784
1785 if (Post::has('checked')) {
1786 S::assert_xsrf_token();
1787 $res = XDB::iterator('SELECT DISTINCT(pm.pid), pd.public_name
1788 FROM profile_modifications AS pm
1789 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1790 WHERE pm.type = \'self\'');
1791
1792 while ($profile = $res->next()) {
1793 if (Post::has('checked_' . $profile['pid'])) {
1794 XDB::execute('DELETE FROM profile_modifications
1795 WHERE type = \'self\' AND pid = {?}', $profile['pid']);
1796
1797 $page->trigSuccess('Profil de ' . $profile['public_name'] . ' vérifié.');
1798 }
1799 }
1800 }
1801
1802 $res = XDB::iterator('SELECT p.hrpid, pm.pid, pd.directory_name, GROUP_CONCAT(pm.field SEPARATOR \', \') AS field
1803 FROM profile_modifications AS pm
1804 INNER JOIN profiles AS p ON (pm.pid = p.pid)
1805 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1806 WHERE pm.type = \'self\'
1807 GROUP BY pd.directory_name
1808 ORDER BY pd.directory_name');
1809 $page->assign('updates', $res);
1810 }
86f0a6af 1811}
1812
a7de4ef7 1813// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
86f0a6af 1814?>