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