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