b364b3b705ba02eae11e22be2cf2a44f2c34ed9e
[platal.git] / modules / admin.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 Polytechnique.org *
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
22 class AdminModule extends PLModule
23 {
24 function handlers()
25 {
26 return array(
27 'phpinfo' => $this->make_hook('phpinfo', AUTH_MDP, 'admin'),
28 'get_rights' => $this->make_hook('get_rights', AUTH_MDP, 'admin'),
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'),
39 'admin/postfix/regexp_bounces' => $this->make_hook('postfix_regexpsbounces', AUTH_MDP, 'admin'),
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/add_accounts' => $this->make_hook('add_accounts', 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'),
52 'admin/account/types' => $this->make_hook('account_types', AUTH_MDP, 'admin'),
53 'admin/jobs' => $this->make_hook('jobs', AUTH_MDP, 'admin'),
54 );
55 }
56
57 function handler_phpinfo(&$page)
58 {
59 phpinfo();
60 exit;
61 }
62
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
74 function handler_default(&$page)
75 {
76 $page->changeTpl('admin/index.tpl');
77 $page->setTitle('Administration');
78 }
79
80 function handler_postfix_delayed(&$page)
81 {
82 $page->changeTpl('admin/postfix_delayed.tpl');
83 $page->setTitle('Administration - Postfix : Retardés');
84
85 if (Env::has('del')) {
86 $crc = Env::v('crc');
87 XDB::execute("UPDATE postfix_mailseen SET release = 'del' WHERE crc = {?}", $crc);
88 $page->trigSuccess($crc . " verra tous ses emails supprimés&nbsp;!");
89 } elseif (Env::has('ok')) {
90 $crc = Env::v('crc');
91 XDB::execute("UPDATE postfix_mailseen SET release = 'ok' WHERE crc = {?}", $crc);
92 $page->trigSuccess($crc . " a le droit de passer&nbsp;!");
93 }
94
95 $sql = XDB::iterator(
96 "SELECT crc, nb, update_time, create_time,
97 FIND_IN_SET('del', p.release) AS del,
98 FIND_IN_SET('ok', p.release) AS ok
99 FROM postfix_mailseen AS p
100 WHERE nb >= 30
101 ORDER BY p.release != ''");
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');
108 $page->setTitle('Administration - Postfix : Regexps Bounces');
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
123 // {{{ logger view
124
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 log_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 log_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 log_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 log_sessions AS ls
275 LEFT JOIN #x4dat#.aliases AS a ON (a.id = ls.uid AND a.type='a_vie')
276 LEFT JOIN #x4dat#.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
281 $res = XDB::iterator('SELECT a.text, e.data, e.stamp
282 FROM log_events AS e
283 LEFT JOIN log_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);
331 $select = "SELECT s.id, s.start, s.uid,
332 a.alias as username
333 FROM log_sessions AS s
334 LEFT JOIN #x4dat#.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 log_sessions AS s
349 LEFT JOIN log_events AS e ON(e.session=s.id)
350 INNER JOIN log_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 {
359 $page->assign('msg_nofilters', "Sélectionner une annuée et/ou un utilisateur");
360 }
361 }
362
363 $page->changeTpl('admin/logger-view.tpl');
364
365 $page->setTitle('Administration - Logs des sessions');
366 }
367
368 function handler_user(&$page, $login = false)
369 {
370 global $globals;
371 $page->changeTpl('admin/user.tpl');
372 $page->setTitle('Administration - Compte');
373
374 if (S::suid()) {
375 $page->kill("Déjà en SUID&nbsp;!!!");
376 }
377
378 // Loads the user identity using the environment.
379 $user = User::get($login);
380 if (!$user) {
381 return;
382 }
383
384 $login = $user->login();
385 $registered = ($user->state != 'pending');
386
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 }
393 }
394
395 // Handles specific requests (AX sync, su, ...).
396 if(Post::has('logs_account')) {
397 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
398 }
399
400 if(Post::has('su_button') && $registered) {
401 if (!Platal::session()->startSUID($user)) {
402 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->login());
403 } else {
404 pl_redirect("");
405 }
406 }
407
408 // Account Form {{{
409 $to_update = array();
410 if (Post::has('disable_weak_access')) {
411 $to_update['weak_password'] = null;
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');
416 }
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');
420 }
421 if (Post::s('sex') != ($user->isFemale() ? 'female' : 'male')) {
422 $to_update['sex'] = Post::s('sex');
423 }
424 if (!Post::blank('hashpass')) {
425 $to_update['password'] = Post::s('hashpass');
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 // }
431 }
432 if (!Post::blank('weak_password')) {
433 $to_update['weak_password'] = Post::s('weak_password');
434 }
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;
437 }
438 if (Post::i('skin', 0) != $user->skin) {
439 $to_update['skin'] = Post::i('skin', 0);
440 if ($to_update['skin'] == 0) {
441 $to_update['skin'] = null;
442 }
443 }
444 if (Post::s('state') != $user->state) {
445 $to_update['state'] = Post::s('state');
446 }
447 if (Post::i('is_admin', 0) != ($user->is_admin ? 1 : 0)) {
448 $to_update['is_admin'] = Post::b('is_admin');
449 }
450 if (Post::s('type') != $user->type) {
451 $to_update['type'] = Post::s('type');
452 }
453 if (Post::i('watch', 0) != ($user->watch ? 1 : 0)) {
454 $to_update['flags'] = new PlFlagset();
455 $to_update['flags']->addFlag('watch', Post::i('watch'));
456 }
457 if (Post::t('comment') != $user->comment) {
458 $to_update['comment'] = Post::blank('comment') ? null : Post::t('comment');
459 }
460 }
461 if (!empty($to_update)) {
462 // TODO: fetch the initial values of the fields, and eventually send
463 // a summary of the changes to an admin.
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 }
474 // }}}
475
476 // Profile form {{{
477 if (Post::has('add_profile') || Post::has('del_profile') || Post::has('owner')) {
478 if (Post::i('del_profile', 0) != 0) {
479 XDB::execute('DELETE FROM account_profiles
480 WHERE uid = {?} AND pid = {?}',
481 $user->id(), Post::i('del_profile'));
482 } else if (!Post::blank('new_profile')) {
483 $profile = Profile::get(Post::t('new_profile'));
484 if (!$profile) {
485 $page->trigError('Le profil ' . Post::t('new_profile') . ' n\'existe pas');
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 = {?}',
495 Post::i('owner'), $user->id());
496 }
497 // }}}
498
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 // }}}
524
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 }
534
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 }
539
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 // }}}
580
581 // OpenId form {{{
582 if (Post::has('del_openid')) {
583 XDB::execute('DELETE FROM openid_trusted
584 WHERE id = {?}', Post::i('del_openid'));
585 }
586 // }}}
587
588 // Forum form {{{
589 if (Post::has('b_edit')) {
590 XDB::execute("DELETE FROM forum_innd
591 WHERE uid = {?}", $user->id());
592 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
593 XDB::execute("INSERT INTO forum_innd
594 SET ipmin = '0', ipmax = '4294967295',
595 write_perm = {?}, read_perm = {?},
596 comment = {?}, priority = '200', uid = {?}",
597 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
598 }
599 }
600 // }}}
601
602
603 $page->addJsLink('ui.core.js');
604 $page->addJsLink('ui.tabs.js');
605
606 // Displays last login and last host information.
607 $res = XDB::query("SELECT start, host
608 FROM log_sessions
609 WHERE uid = {?} AND suid = 0
610 ORDER BY start DESC
611 LIMIT 1", $user->id());
612 list($lastlogin,$host) = $res->fetchOneRow();
613 $page->assign('lastlogin', $lastlogin);
614 $page->assign('host', $host);
615
616 // Display active aliases.
617 $page->assign('virtuals', $user->emailAliases());
618 $page->assign('aliases', XDB::iterator("SELECT alias, type='a_vie' AS for_life,
619 FIND_IN_SET('bestalias',flags) AS best, expire
620 FROM aliases
621 WHERE id = {?} AND type != 'homonyme'
622 ORDER BY type != 'a_vie'", $user->id()));
623 $page->assign('account_types', XDB::iterator('SELECT * FROM account_types ORDER BY type'));
624 $page->assign('skins', XDB::iterator('SELECT id, name FROM skins ORDER BY name'));
625 $page->assign('profiles', XDB::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
626 FROM account_profiles AS ap
627 INNER JOIN profiles AS p ON (ap.pid = p.pid)
628 WHERE ap.uid = {?}', $user->id()));
629 $page->assign('openid', XDB::iterator('SELECT id, url
630 FROM openid_trusted
631 WHERE user_id = {?}', $user->id()));
632
633 // Displays email redirection and the general profile.
634 if ($registered && $redirect) {
635 $page->assign('emails', $redirect->emails);
636 }
637
638 $page->assign('user', $user);
639
640 // Displays forum bans.
641 $res = XDB::query("SELECT write_perm, read_perm, comment
642 FROM forum_innd
643 WHERE uid = {?}", $user->id());
644 $bans = $res->fetchOneAssoc();
645 $page->assign('bans', $bans);
646 }
647
648 private static function getHrid($firstname, $lastname, $promo)
649 {
650 if ($firstname != null && $lastname != null && $promo != null) {
651 return User::makeForlife($firstname, $lastname, $promo);
652 }
653 return null;
654 }
655
656 private static function formatNewUser($infosLine, $separator, $promo, $size)
657 {
658 $infos = explode($separator, $infosLine);
659 if (sizeof($infos) != $size) {
660 return false;
661 }
662
663 array_map('trim', $infos);
664 $hrid = self::getHrid($infos[1], $infos[0], $promo);
665 $res1 = XDB::query('SELECT COUNT(*)
666 FROM accounts
667 WHERE hruid = {?}', $hrid);
668 $res2 = XDB::query('SELECT COUNT(*)
669 FROM profiles
670 WHERE hrpid = {?}', $hrid);
671 if (is_null($hrid) || $res1->fetchOneCell() > 0 || $res2->fetchOneCell() > 0) {
672 $page->trigError("La ligne $line n'a pas été ajoutée.");
673 return false;
674 }
675 $infos['hrid'] = $hrid;
676 return $infos;
677 }
678
679 private static function formatSex(&$page, $sex, $line)
680 {
681 switch ($sex) {
682 case 'F':
683 return PlUser::GENDER_FEMALE;
684 case 'M':
685 return PlUser::GENDER_MALE;
686 default:
687 $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
688 return null;
689 }
690 }
691
692 private static function formatBirthDate($birthDate)
693 {
694 return date("Y-m-d", strtotime($birthDate));
695 }
696
697 function handler_add_accounts(&$page, $action = null, $promo = null)
698 {
699 $page->changeTpl('admin/add_accounts.tpl');
700
701 if (Env::has('add_type') && Env::has('people')) {
702 require_once 'directory.enums.inc.php';
703 $lines = explode("\n", Env::t('people'));
704 $separator = Env::t('separator');
705 $promotion = Env::i('promotion');
706 $nameTypes = DirEnum::getOptionsArray(DirEnum::NAMETYPES);
707 $nameTypes = array_flip($nameTypes);
708
709 if (Env::t('add_type') == 'promo') {
710 $type = 'x';
711 $eduSchools = DirEnum::getOptionsArray(DirEnum::EDUSCHOOLS);
712 $eduSchools = array_flip($eduSchools);
713 $eduDegrees = DirEnum::getOptionsArray(DirEnum::EDUDEGREES);
714 $eduDegrees = array_flip($eduDegrees);
715 var_dump($eduDegrees);
716 switch (Env::t('edu_type')) {
717 case 'X':
718 $degreeid = $eduDegrees[Profile::DEGREE_X];
719 $entry_year = $promotion;
720 $grad_year = $promotion + 3;
721 $promo = 'X' . $promotion;
722 break;
723 case 'M':
724 $degreeid = $eduDegrees[Profile::DEGREE_M];
725 $grad_year = $promotion;
726 $entry_year = $promotion - 2;
727 $promo = 'M' . $promotion;
728 break;
729 case 'D':
730 $degreeid = $eduDegrees[Profile::DEGREE_D];
731 $grad_year = $promotion;
732 $entry_year = $promotion - 3;
733 $promo = 'D' . $promotion;
734 break;
735 default:
736 $page->killError("La formation n'est pas reconnue:" . Env::t('edu_type') . '.');
737 }
738
739 foreach ($lines as $line) {
740 if (($infos = self::formatNewUser($line, $separator, $promotion, 6))
741 && ($sex = self::formatSex($page, $infos[3], $line))) {
742 $name = $infos[1] . ' ' . $infos[0];
743 $birthDate = self::formatBirthDate($infos[2]);
744 $xorgId = Profile::getXorgId($infos[4]);
745
746 XDB::execute('INSERT INTO profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex)
747 VALUES ({?}, {?}, {?}, {?})',
748 $infos['hrid'], $xorgId, $infos[5], $birthDate, $sex);
749 $pid = XDB::insertId();
750 XDB::execute('INSERT INTO profile_name (pid, name, typeid)
751 VALUES ({?}, {?}, {?})',
752 $pid, $infos[0], $nameTypes['name_ini']);
753 XDB::execute('INSERT INTO profile_name (pid, name, typeid)
754 VALUES ({?}, {?}, {?})',
755 $pid, $infos[1], $nameTypes['firstname_ini']);
756 XDB::execute('INSERT INTO profile_display (pid, yourself, public_name, private_name,
757 directory_name, short_name, sort_name, promo)
758 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
759 $pid, $infos[1], $name, $name, $name, $name, $infos[0] . ' ' . $infos[1], $promo);
760 XDB::execute('INSERT INTO profile_education (pid, eduid, degreeid, entry_year, grad_year, flags)
761 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
762 $pid, $eduSchools[Profile::EDU_X], $degreeid, $entry_year, $grad_year, 'primary');
763 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, full_name, display_name, sex)
764 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
765 $infos['hrid'], $type, 0, 'active', $name, $infos[1], $sex);
766 $uid = XDB::insertId();
767 XDB::execute('INSERT INTO account_profiles (uid, pid, perms)
768 VALUES ({?}, {?}, {?})',
769 $uid, $pid, 'owner');
770 }
771 }
772 } else if (Env::t('add_type') == 'account') {
773 $type = Env::t('type');
774 foreach ($lines as $line) {
775 if (($infos = self::formatNewUser($line, $separator, $type, 4))
776 && ($sex = self::formatSex(&$page, $infos[3], $line))) {
777 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, email, full_name, display_name, sex)
778 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
779 $infos['hrid'], $type, 0, 'active', $infos[2], $infos[1] . ' ' . $infos[0], $infos[1], $sex);
780 }
781 }
782 } else if (Env::t('add_type') == 'ax_id') {
783 $type = 'x';
784 foreach ($lines as $line) {
785 if ($infos = self::formatNewUser($line, $separator, $promotion, 3)) {
786 XDB::execute('UPDATE profiles
787 SET ax_id = {?}
788 WHERE hrpid = {?}',
789 $infos[2], $infos['hrid']);
790 }
791 }
792 }
793
794 if ($page->nb_errs == 0) {
795 $page->trigSuccess("L'opération a été effectuée avec succès.");
796 } else {
797 $page->trigSuccess("L'opération a été effectuée avec succès, sauf pour les "
798 . $page->nb_errs . 'erreurs signalées ci-dessus.');
799 }
800 } else if (Env::has('add_type')) {
801 $res = XDB::query('SELECT type
802 FROM account_types');
803 $page->assign('account_types', $res->fetchColumn());
804 $page->assign('add_type', Env::s('add_type'));
805 }
806 }
807
808 function handler_homonyms(&$page, $op = 'list', $target = null)
809 {
810 $page->changeTpl('admin/homonymes.tpl');
811 $page->setTitle('Administration - Homonymes');
812 $this->load("homonyms.inc.php");
813
814 if ($target) {
815 $user = User::getSilent($target);
816 if (!$user || !($loginbis = select_if_homonyme($user))) {
817 $target = 0;
818 } else {
819 $page->assign('user', $user);
820 $page->assign('loginbis',$loginbis);
821 }
822 }
823
824 $page->assign('op', $op);
825 $page->assign('target', $target);
826
827 // on a un $target valide, on prepare les mails
828 if ($target) {
829 // on examine l'op a effectuer
830 switch ($op) {
831 case 'mail':
832 S::assert_xsrf_token();
833
834 send_warning_homonyme($user, $loginbis);
835 switch_bestalias($user, $loginbis);
836 $op = 'list';
837 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
838 break;
839
840 case 'correct':
841 S::assert_xsrf_token();
842
843 switch_bestalias($user, $loginbis);
844 XDB::execute("UPDATE aliases
845 SET type = 'homonyme', expire=NOW()
846 WHERE alias = {?}", $loginbis);
847 XDB::execute("REPLACE INTO homonymes (homonyme_id,user_id)
848 VALUES ({?}, {?})", $target, $target);
849 send_robot_homonyme($user, $loginbis);
850 $op = 'list';
851 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
852 break;
853 }
854 }
855
856 if ($op == 'list') {
857 $res = XDB::iterator(
858 "SELECT a.alias AS homonyme, s.alias AS forlife,
859 IF(h.homonyme_id = s.id, a.expire, NULL) AS expire,
860 IF(h.homonyme_id = s.id, a.type, NULL) AS type,
861 ac.uid AS user_id
862 FROM aliases AS a
863 LEFT JOIN homonymes AS h ON (h.homonyme_id = a.id)
864 INNER JOIN aliases AS s ON (s.id = h.user_id AND s.type='a_vie')
865 INNER JOIN accounts AS ac ON (ac.uid = a.id)
866 WHERE a.type = 'homonyme' OR a.expire != ''
867 ORDER BY a.alias, forlife");
868 $hnymes = Array();
869 while ($tab = $res->next()) {
870 $hnymes[$tab['homonyme']][] = $tab;
871 }
872 $page->assign_by_ref('hnymes',$hnymes);
873 }
874 }
875
876 function handler_deaths(&$page, $promo = 0, $validate = false)
877 {
878 $page->changeTpl('admin/deces_promo.tpl');
879 $page->setTitle('Administration - Deces');
880
881 if (!$promo) {
882 $promo = Env::t('promo', 'X1923');
883 }
884 $page->assign('promo', $promo);
885 if (!$promo) {
886 return;
887 }
888
889 if ($validate) {
890 S::assert_xsrf_token();
891
892 $res = XDB::iterRow('SELECT p.hrpid, pd.directory_name, p.deathdate
893 FROM profiles AS p
894 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
895 WHERE pd.promo = {?}', $promo);
896 while (list($pid, $name, $death) = $res->next()) {
897 $val = Env::v($pid);
898 if($val == $deces || empty($val)) {
899 continue;
900 }
901
902 XDB::execute('UPDATE profiles
903 SET deathdate = {?}, deathdate_rec = NOW()
904 WHERE hrpid = {?}', $val, $pid);
905 $page->trigSuccess('Ajout du décès de ' . $name . ' le ' . $val . '.');
906 if($death == '0000-00-00' || empty($death)) {
907 // TODO: FIX THIS DEPRECATED CALL
908 require_once('user.func.inc.php');
909 user_clear_all_subs($uid, false); // by default, dead ppl do not loose their email
910 }
911 }
912 }
913
914 $res = XDB::iterator('SELECT p.hrpid, pd.directory_name, p.deathdate
915 FROM profiles AS p
916 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
917 WHERE pd.promo = {?}
918 ORDER BY pd.sort_name', $promo);
919 $page->assign('decedes', $res);
920 }
921
922 function handler_dead_but_active(&$page)
923 {
924 $page->changeTpl('admin/dead_but_active.tpl');
925 $page->setTitle('Administration - Décédés');
926
927 $res = XDB::iterator(
928 "SELECT a.hruid, pd.promo, p.ax_id, pd.directory_name, p.deathdate, DATE(MAX(s.start)) AS last
929 FROM #x4dat#.accounts AS a
930 INNER JOIN #x4dat#.account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET('owner', ap.perms))
931 INNER JOIN #x4dat#.profiles AS p ON (p.pid = ap.pid)
932 INNER JOIN #x4dat#.profile_display AS pd ON (pd.pid = p.pid)
933 LEFT JOIN log_sessions AS s ON (s.uid = a.uid AND suid = 0)
934 WHERE a.state = 'active' AND p.deathdate IS NOT NULL
935 GROUP BY a.uid
936 ORDER BY pd.promo, pd.sort_name");
937 $page->assign('dead', $res);
938 }
939
940 function handler_validate(&$page, $action = 'list', $id = null)
941 {
942 $page->changeTpl('admin/valider.tpl');
943 $page->setTitle('Administration - Valider une demande');
944 $page->addCssLink('nl.css');
945 $page->addJsLink('ajax.js');
946 require_once("validations.inc.php");
947
948
949 if ($action == 'edit' and !is_null($id)) {
950 $page->assign('preview_id', $id);
951 }
952
953 if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
954 S::assert_xsrf_token();
955
956 $req = Validate::get_typed_request(Env::v('uid'), Env::v('type'), Env::v('stamp'));
957 if ($req) {
958 $req->handle_formu();
959 } else {
960 $page->trigWarning('La validation a déjà été effectuée.');
961 }
962 }
963
964 $r = XDB::iterator('SHOW COLUMNS FROM requests_answers');
965 while (($a = $r->next()) && $a['Field'] != 'category');
966 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
967
968 $hidden = array();
969 $res = XDB::query('SELECT hidden_requests FROM requests_hidden WHERE user_id = {?}', S::v('uid'));
970 $hide_requests = $res->fetchOneCell();
971 if (Post::has('hide')) {
972 $hide = array();
973 foreach ($categories as $cat)
974 if (!Post::v($cat)) {
975 $hidden[$cat] = 1;
976 $hide[] = $cat;
977 }
978 $hide_requests = join(',', $hide);
979 XDB::query('REPLACE INTO requests_hidden (user_id, hidden_requests) VALUES({?}, {?})',
980 S::v('uid'), $hide_requests);
981 } elseif ($hide_requests) {
982 foreach (explode(',', $hide_requests) as $hide_type)
983 $hidden[$hide_type] = true;
984 }
985 $page->assign('hide_requests', $hidden);
986
987 // Update the count of item to validate here... useful in development configuration
988 // where several copies of the site use the same DB, but not the same "dynamic configuration"
989 global $globals;
990 $globals->updateNbValid();
991 $page->assign('vit', new ValidateIterator());
992 }
993
994 function handler_validate_answers(&$page, $action = 'list', $id = null)
995 {
996 $page->setTitle('Administration - Réponses automatiques de validation');
997 $page->assign('title', 'Gestion des réponses automatiques');
998 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
999 $table_editor->describe('category','catégorie',true);
1000 $table_editor->describe('title','titre',true);
1001 $table_editor->describe('answer','texte',false);
1002 $table_editor->apply($page, $action, $id);
1003 }
1004
1005 function handler_skins(&$page, $action = 'list', $id = null)
1006 {
1007 $page->setTitle('Administration - Skins');
1008 $page->assign('title', 'Gestion des skins');
1009 $table_editor = new PLTableEditor('admin/skins','skins','id');
1010 $table_editor->describe('name','nom',true);
1011 $table_editor->describe('skin_tpl','nom du template',true);
1012 $table_editor->describe('auteur','auteur',false);
1013 $table_editor->describe('comment','commentaire',true);
1014 $table_editor->describe('date','date',false);
1015 $table_editor->describe('ext','extension du screenshot',false);
1016 $table_editor->apply($page, $action, $id);
1017 }
1018
1019 function handler_postfix_blacklist(&$page, $action = 'list', $id = null)
1020 {
1021 $page->setTitle('Administration - Postfix : Blacklist');
1022 $page->assign('title', 'Blacklist de postfix');
1023 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true);
1024 $table_editor->describe('reject_text','Texte de rejet',true);
1025 $table_editor->describe('email','email',true);
1026 $table_editor->apply($page, $action, $id);
1027 }
1028
1029 function handler_postfix_whitelist(&$page, $action = 'list', $id = null)
1030 {
1031 $page->setTitle('Administration - Postfix : Whitelist');
1032 $page->assign('title', 'Whitelist de postfix');
1033 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true);
1034 $table_editor->describe('email','email',true);
1035 $table_editor->apply($page, $action, $id);
1036 }
1037
1038 function handler_mx_broken(&$page, $action = 'list', $id = null)
1039 {
1040 $page->setTitle('Administration - MX Défaillants');
1041 $page->assign('title', 'MX Défaillant');
1042 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true);
1043 $table_editor->describe('host', 'Masque', true);
1044 $table_editor->describe('state', 'Niveau', true);
1045 $table_editor->describe('text', 'Description du problème', false);
1046 $table_editor->apply($page, $action, $id);
1047 }
1048
1049 function handler_logger_actions(&$page, $action = 'list', $id = null)
1050 {
1051 $page->setTitle('Administration - Actions');
1052 $page->assign('title', 'Gestion des actions de logger');
1053 $table_editor = new PLTableEditor('admin/logger/actions','log_actions','id');
1054 $table_editor->describe('text','intitulé',true);
1055 $table_editor->describe('description','description',true);
1056 $table_editor->apply($page, $action, $id);
1057 }
1058
1059 function handler_downtime(&$page, $action = 'list', $id = null)
1060 {
1061 $page->setTitle('Administration - Coupures');
1062 $page->assign('title', 'Gestion des coupures');
1063 $table_editor = new PLTableEditor('admin/downtime','coupures','id');
1064 $table_editor->describe('debut','date',true);
1065 $table_editor->describe('duree','durée',false);
1066 $table_editor->describe('resume','résumé',true);
1067 $table_editor->describe('services','services affectés',true);
1068 $table_editor->describe('description','description',false);
1069 $table_editor->apply($page, $action, $id);
1070 }
1071
1072 function handler_account_types(&$page, $action = 'list', $id = null)
1073 {
1074 $page->setTitle('Administration - Types de comptes');
1075 $page->assign('title', 'Gestion des types de comptes');
1076 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true);
1077 $table_editor->describe('type', 'Catégorie', true);
1078 $table_editor->describe('perms', 'Permissions associées', true);
1079 $table_editor->apply($page, $action, $id);
1080 }
1081
1082 function handler_wiki(&$page, $action = 'list', $wikipage = null, $wikipage2 = null)
1083 {
1084 if (S::hasAuthToken()) {
1085 $page->setRssLink('Changement Récents',
1086 '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::v('token'));
1087 }
1088
1089 // update wiki perms
1090 if ($action == 'update') {
1091 S::assert_xsrf_token();
1092
1093 $perms_read = Post::v('read');
1094 $perms_edit = Post::v('edit');
1095 if ($perms_read || $perms_edit) {
1096 foreach ($_POST as $wiki_page => $val) {
1097 if ($val == 'on') {
1098 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1099 if ($wp->setPerms($perms_read ? $perms_read : $wp->readPerms(),
1100 $perms_edit ? $perms_edit : $wp->writePerms())) {
1101 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1102 } else {
1103 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1104 }
1105 }
1106 }
1107 }
1108 } else if ($action != 'list' && !empty($wikipage)) {
1109 $wp = new PlWikiPage($wikipage);
1110 S::assert_xsrf_token();
1111
1112 if ($action == 'delete') {
1113 if ($wp->delete()) {
1114 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1115 } else {
1116 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1117 }
1118 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1119 if ($changedLinks = $wp->rename($wikipage2)) {
1120 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1121 if (is_numeric($changedLinks)) {
1122 $s .= $changedLinks.' lien'.(($changedLinks>1)?'s ont été modifiés.':' a été modifié.');
1123 }
1124 $page->trigSuccess($s);
1125 } else {
1126 $page->trigError("Impossible de déplacer la page ".$wikipage);
1127 }
1128 }
1129 }
1130
1131 $perms = PlWikiPage::permOptions();
1132
1133 // list wiki pages and their perms
1134 $wiki_pages = PlWikiPage::listPages();
1135 ksort($wiki_pages);
1136 $wiki_tree = array();
1137 foreach ($wiki_pages as $file => $desc) {
1138 list($cat, $name) = explode('.', $file);
1139 if (!isset($wiki_tree[$cat])) {
1140 $wiki_tree[$cat] = array();
1141 }
1142 $wiki_tree[$cat][$name] = $desc;
1143 }
1144
1145 $page->changeTpl('admin/wiki.tpl');
1146 $page->assign('wiki_pages', $wiki_tree);
1147 $page->assign('perms_opts', $perms);
1148 }
1149
1150 function handler_ipwatch(&$page, $action = 'list', $ip = null)
1151 {
1152 $page->changeTpl('admin/ipwatcher.tpl');
1153
1154 $states = array('safe' => 'Ne pas surveiller',
1155 'unsafe' => 'Surveiller les inscriptions',
1156 'dangerous' => 'Surveiller tous les accès',
1157 'ban' => 'Bannir cette adresse');
1158 $page->assign('states', $states);
1159
1160 switch (Post::v('action')) {
1161 case 'create':
1162 if (trim(Post::v('ipN')) != '') {
1163 S::assert_xsrf_token();
1164 Xdb::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1165 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1166 ip_to_uint(trim(Post::v('ipN'))), ip_to_uint(trim(Post::v('maskN'))),
1167 Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
1168 };
1169 break;
1170
1171 case 'edit':
1172 S::assert_xsrf_token();
1173 Xdb::execute('UPDATE ip_watch
1174 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1175 WHERE ip = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'),
1176 ip_to_uint(Post::v('maskN')), ip_to_uint(Post::v('ipN')));
1177 break;
1178
1179 default:
1180 if ($action == 'delete' && !is_null($ip)) {
1181 S::assert_xsrf_token();
1182 Xdb::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1183 }
1184 }
1185 if ($action != 'create' && $action != 'edit') {
1186 $action = 'list';
1187 }
1188 $page->assign('action', $action);
1189
1190 if ($action == 'list') {
1191 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1192 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1193 IF(w.ip = s.ip, s.host, s.forward_host)),
1194 w.mask, w.detection, w.state, a.hruid
1195 FROM #x4dat#.ip_watch AS w
1196 LEFT JOIN log_sessions AS s ON (s.ip = w.ip)
1197 LEFT JOIN log_sessions AS s2 ON (s2.forward_ip = w.ip)
1198 LEFT JOIN #x4dat#.accounts AS a ON (a.uid = s.uid)
1199 GROUP BY w.ip, a.hruid
1200 ORDER BY w.state, w.ip, a.hruid";
1201 $it = Xdb::iterRow($sql);
1202
1203 $table = array();
1204 $props = array();
1205 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1206 $ip = uint_to_ip($ip);
1207 $mask = uint_to_ip($mask);
1208 if (count($props) == 0 || $props['ip'] != $ip) {
1209 if (count($props) > 0) {
1210 $table[] = $props;
1211 }
1212 $props = array('ip' => $ip,
1213 'mask' => $mask,
1214 'host' => $host,
1215 'detection' => $date,
1216 'state' => $state,
1217 'users' => array($hruid));
1218 } else {
1219 $props['users'][] = $hruid;
1220 }
1221 }
1222 if (count($props) > 0) {
1223 $table[] = $props;
1224 }
1225 $page->assign('table', $table);
1226 } elseif ($action == 'edit') {
1227 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1228 a1.hruid AS edit, a2.hruid AS hruid, s.host
1229 FROM #x4dat#.ip_watch AS w
1230 LEFT JOIN #x4dat#.accounts AS a1 ON (a1.uid = w.uid)
1231 LEFT JOIN log_sessions AS s ON (w.ip = s.ip)
1232 LEFT JOIN #x4dat#.accounts AS a2 ON (a2.uid = s.uid)
1233 WHERE w.ip = {?}
1234 GROUP BY a2.hruid
1235 ORDER BY a2.hruid";
1236 $it = Xdb::iterRow($sql, ip_to_uint($ip));
1237
1238 $props = array();
1239 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1240 if (count($props) == 0) {
1241 $props = array('ip' => $ip,
1242 'mask' => uint_to_ip($mask),
1243 'host' => $host,
1244 'detection' => $detection,
1245 'state' => $state,
1246 'last' => $last,
1247 'description' => $description,
1248 'edit' => $edit,
1249 'users' => array($hruid));
1250 } else {
1251 $props['users'][] = $hruid;
1252 }
1253 }
1254 $page->assign('ip', $props);
1255 }
1256 }
1257
1258 function handler_icons(&$page)
1259 {
1260 $page->changeTpl('admin/icons.tpl');
1261 $dh = opendir('../htdocs/images/icons');
1262 if (!$dh) {
1263 $page->trigError('Dossier des icones introuvables.');
1264 }
1265 $icons = array();
1266 while (($file = readdir($dh)) !== false) {
1267 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1268 array_push($icons, substr($file, 0, -4));
1269 }
1270 }
1271 sort($icons);
1272 $page->assign('icons', $icons);
1273 }
1274
1275 function handler_accounts(&$page)
1276 {
1277 $page->changeTpl('admin/accounts.tpl');
1278 $page->assign('disabled', XDB::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1279 a.state = \'disabled\' AS disabled, a.comment
1280 FROM accounts AS a
1281 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1282 ORDER BY a.hruid'));
1283 $page->assign('admins', XDB::iterator('SELECT a.hruid
1284 FROM accounts AS a
1285 WHERE a.is_admin
1286 ORDER BY a.hruid'));
1287 }
1288
1289 function handler_jobs(&$page, $id = -1)
1290 {
1291 $page->changeTpl('admin/jobs.tpl');
1292
1293 if (Env::has('search')) {
1294 $res = XDB::query("SELECT e.id, e.name, e.acronym
1295 FROM profile_job_enum AS e
1296 WHERE e.name LIKE CONCAT('% ', {?}, '%') OR e.acronym LIKE CONCAT('% ', {?}, '%')",
1297 Env::t('job'), Env::t('job'));
1298
1299 if ($res->numRows() <= 20) {
1300 $page->assign('jobs', $res->fetchAllAssoc());
1301 } else {
1302 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1303 }
1304
1305 $page->assign('askedJob', Env::v('job'));
1306 return;
1307 }
1308
1309 if (Env::has('edit')) {
1310 // TODO: use address and phone classes to update profile_job_enum and profile_phones once they are done.
1311
1312 S::assert_xsrf_token();
1313 $selectedJob = Env::has('selectedJob');
1314
1315 XDB::execute("DELETE FROM profile_phones
1316 WHERE uid = {?} AND link_type = 'hq'",
1317 $id);
1318 XDB::execute("DELETE FROM profile_addresses
1319 WHERE jobid = {?} AND type = 'hq'",
1320 $id);
1321 XDB::execute('DELETE FROM profile_job_enum
1322 WHERE id = {?}',
1323 $id);
1324
1325 if (Env::has('change')) {
1326 XDB::execute('UPDATE profile_job
1327 SET jobid = {?}
1328 WHERE jobid = {?}',
1329 Env::i('newJobId'), $id);
1330
1331 $page->trigSuccess("L'entreprise a bien été remplacée.");
1332 } else {
1333 require_once 'profil.func.inc.php';
1334 require_once 'geocoding.inc.php';
1335
1336 $display_tel = format_display_number(Env::v('tel'), $error_tel);
1337 $display_fax = format_display_number(Env::v('fax'), $error_fax);
1338 $gmapsGeocoder = new GMapsGeocoder();
1339 $address = array('text' => Env::t('address'));
1340 $address = $gmapsGeocoder->getGeocodedAddress($address);
1341 Geocoder::getAreaId($address, 'administrativeArea');
1342 Geocoder::getAreaId($address, 'subAdministrativeArea');
1343 Geocoder::getAreaId($address, 'locality');
1344
1345 XDB::execute('UPDATE profile_job_enum
1346 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1347 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1348 WHERE id = {?}',
1349 Env::t('name'), Env::t('acronym'), Env::t('url'), Env::t('email'),
1350 Env::t('NAF_code'), Env::i('AX_code'), Env::i('holdingId'), $id);
1351
1352 XDB::execute("INSERT INTO profile_phones (uid, link_type, link_id, tel_id, tel_type,
1353 search_tel, display_tel, pub)
1354 VALUES ({?}, 'hq', 0, 0, 'fixed', {?}, {?}, 'public'),
1355 ({?}, 'hq', 0, 1, 'fax', {?}, {?}, 'public')",
1356 $id, format_phone_number(Env::v('tel')), $display_tel,
1357 $id, format_phone_number(Env::v('fax')), $display_fax);
1358
1359 XDB::execute("INSERT INTO profile_addresses (jobid, type, id, accuracy,
1360 text, postalText, postalCode, localityId,
1361 subAdministrativeAreaId, administrativeAreaId,
1362 countryId, latitude, longitude, updateTime,
1363 north, south, east, west)
1364 VALUES ({?}, 'hq', 0, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
1365 {?}, {?}, FROM_UNIXTIME({?}), {?}, {?}, {?}, {?})",
1366 $id, $address['accuracy'], $address['text'], $address['postalText'],
1367 $address['postalCode'], $address['localityId'],
1368 $address['subAdministrativeAreaId'], $address['administrativeAreaId'],
1369 $address['countryId'], $address['latitude'], $address['longitude'],
1370 $address['updateTime'], $address['north'], $address['south'],
1371 $address['east'], $address['west']);
1372
1373 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1374 }
1375 }
1376
1377 if (!Env::has('change') && $id != -1) {
1378 $res = XDB::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1379 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1380 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1381 FROM profile_job_enum AS e
1382 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
1383 LEFT JOIN profile_phones AS t ON (t.uid = e.id AND link_type = 'hq' AND tel_id = 0)
1384 LEFT JOIN profile_phones AS f ON (f.uid = e.id AND link_type = 'hq' AND tel_id = 1)
1385 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1386 WHERE e.id = {?}",
1387 $id);
1388
1389 if ($res->numRows() == 0) {
1390 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1391 } else {
1392 $page->assign('selectedJob', $res->fetchOneAssoc());
1393 }
1394 }
1395 }
1396 }
1397
1398 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1399 ?>