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