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