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