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