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