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