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