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