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