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