5eb630a72c20d116fb3476579d3005277dbede59
[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/dead-but-active' => $this->make_hook('dead_but_active', AUTH_MDP, 'admin'),
31 'admin/deaths' => $this->make_hook('deaths', AUTH_MDP, 'admin'),
32 'admin/downtime' => $this->make_hook('downtime', AUTH_MDP, 'admin'),
33 'admin/homonyms' => $this->make_hook('homonyms', AUTH_MDP, 'admin'),
34 'admin/logger' => $this->make_hook('logger', AUTH_MDP, 'admin'),
35 'admin/logger/actions' => $this->make_hook('logger_actions', AUTH_MDP, 'admin'),
36 'admin/postfix/blacklist' => $this->make_hook('postfix_blacklist', AUTH_MDP, 'admin'),
37 'admin/postfix/delayed' => $this->make_hook('postfix_delayed', AUTH_MDP, 'admin'),
38 'admin/postfix/regexp_bounces' => $this->make_hook('postfix_regexpsbounces', AUTH_MDP, 'admin'),
39 'admin/postfix/whitelist' => $this->make_hook('postfix_whitelist', AUTH_MDP, 'admin'),
40 'admin/mx/broken' => $this->make_hook('mx_broken', AUTH_MDP, 'admin'),
41 'admin/skins' => $this->make_hook('skins', AUTH_MDP, 'admin'),
42 'admin/user' => $this->make_hook('user', AUTH_MDP, 'admin'),
43 'admin/add_accounts' => $this->make_hook('add_accounts', AUTH_MDP, 'admin'),
44 'admin/validate' => $this->make_hook('validate', AUTH_MDP, 'admin'),
45 'admin/validate/answers' => $this->make_hook('validate_answers', AUTH_MDP, 'admin'),
46 'admin/wiki' => $this->make_hook('wiki', AUTH_MDP, 'admin'),
47 'admin/ipwatch' => $this->make_hook('ipwatch', AUTH_MDP, 'admin'),
48 'admin/icons' => $this->make_hook('icons', AUTH_MDP, 'admin'),
49 'admin/accounts' => $this->make_hook('accounts', AUTH_MDP, 'admin'),
50 'admin/account/types' => $this->make_hook('account_types', AUTH_MDP, 'admin'),
51 'admin/jobs' => $this->make_hook('jobs', AUTH_MDP, 'admin'),
52 );
53 }
54
55 function handler_phpinfo(&$page)
56 {
57 phpinfo();
58 exit;
59 }
60
61 function handler_get_rights(&$page, $level)
62 {
63 if (S::suid()) {
64 $page->kill('Déjà en SUID');
65 }
66 $user =& S::user();
67 Platal::session()->startSUID($user, $level);
68
69 pl_redirect('/');
70 }
71
72 function handler_default(&$page)
73 {
74 $page->changeTpl('admin/index.tpl');
75 $page->setTitle('Administration');
76 }
77
78 function handler_postfix_delayed(&$page)
79 {
80 $page->changeTpl('admin/postfix_delayed.tpl');
81 $page->setTitle('Administration - Postfix : Retardés');
82
83 if (Env::has('del')) {
84 $crc = Env::v('crc');
85 XDB::execute("UPDATE postfix_mailseen SET release = 'del' WHERE crc = {?}", $crc);
86 $page->trigSuccess($crc . " verra tous ses emails supprimés&nbsp;!");
87 } elseif (Env::has('ok')) {
88 $crc = Env::v('crc');
89 XDB::execute("UPDATE postfix_mailseen SET release = 'ok' WHERE crc = {?}", $crc);
90 $page->trigSuccess($crc . " a le droit de passer&nbsp;!");
91 }
92
93 $sql = XDB::iterator(
94 "SELECT crc, nb, update_time, create_time,
95 FIND_IN_SET('del', p.release) AS del,
96 FIND_IN_SET('ok', p.release) AS ok
97 FROM postfix_mailseen AS p
98 WHERE nb >= 30
99 ORDER BY p.release != ''");
100
101 $page->assign_by_ref('mails', $sql);
102 }
103
104 function handler_postfix_regexpsbounces(&$page, $new = null) {
105 $page->changeTpl('admin/emails_bounces_re.tpl');
106 $page->setTitle('Administration - Postfix : Regexps Bounces');
107 $page->assign('new', $new);
108
109 if (Post::has('submit')) {
110 foreach (Env::v('lvl') as $id=>$val) {
111 XDB::query(
112 "REPLACE INTO emails_bounces_re (id,pos,lvl,re,text) VALUES ({?}, {?}, {?}, {?}, {?})",
113 $id, $_POST['pos'][$id], $_POST['lvl'][$id], $_POST['re'][$id], $_POST['text'][$id]
114 );
115 }
116 }
117
118 $page->assign('bre', XDB::iterator("SELECT * FROM emails_bounces_re ORDER BY pos"));
119 }
120
121 // {{{ logger view
122
123 /** Retrieves the available days for a given year and month.
124 * Obtain a list of days of the given month in the given year
125 * that are within the range of dates that we have log entries for.
126 *
127 * @param integer year
128 * @param integer month
129 * @return array days in that month we have log entries covering.
130 * @private
131 */
132 function _getDays($year, $month)
133 {
134 // give a 'no filter' option
135 $months[0] = "----";
136
137 if ($year && $month) {
138 $day_max = Array(-1, 31, checkdate(2, 29, $year) ? 29 : 28 , 31,
139 30, 31, 30, 31, 31, 30, 31, 30, 31);
140 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
141 MONTH(MAX(start)), MONTH(MIN(start)),
142 DAYOFMONTH(MAX(start)),
143 DAYOFMONTH(MIN(start))
144 FROM log_sessions");
145 list($ymax, $ymin, $mmax, $mmin, $dmax, $dmin) = $res->fetchOneRow();
146
147 if (($year < $ymin) || ($year == $ymin && $month < $mmin)) {
148 return array();
149 }
150
151 if (($year > $ymax) || ($year == $ymax && $month > $mmax)) {
152 return array();
153 }
154
155 $min = ($year==$ymin && $month==$mmin) ? intval($dmin) : 1;
156 $max = ($year==$ymax && $month==$mmax) ? intval($dmax) : $day_max[$month];
157
158 for($i = $min; $i<=$max; $i++) {
159 $days[$i] = $i;
160 }
161 }
162 return $days;
163 }
164
165
166 /** Retrieves the available months for a given year.
167 * Obtains a list of month numbers that are within the timeframe that
168 * we have log entries for.
169 *
170 * @param integer year
171 * @return array List of month numbers we have log info for.
172 * @private
173 */
174 function _getMonths($year)
175 {
176 // give a 'no filter' option
177 $months[0] = "----";
178
179 if ($year) {
180 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
181 MONTH(MAX(start)), MONTH(MIN(start))
182 FROM log_sessions");
183 list($ymax, $ymin, $mmax, $mmin) = $res->fetchOneRow();
184
185 if (($year < $ymin) || ($year > $ymax)) {
186 return array();
187 }
188
189 $min = $year == $ymin ? intval($mmin) : 1;
190 $max = $year == $ymax ? intval($mmax) : 12;
191
192 for($i = $min; $i<=$max; $i++) {
193 $months[$i] = $i;
194 }
195 }
196 return $months;
197 }
198
199
200 /** Retrieves the available years.
201 * Obtains a list of years that we have log entries covering.
202 *
203 * @return array years we have log entries for.
204 * @private
205 */
206 function _getYears()
207 {
208 // give a 'no filter' option
209 $years[0] = "----";
210
211 // retrieve available years
212 $res = XDB::query("select YEAR(MAX(start)), YEAR(MIN(start)) FROM log_sessions");
213 list($max, $min) = $res->fetchOneRow();
214
215 for($i = intval($min); $i<=$max; $i++) {
216 $years[$i] = $i;
217 }
218 return $years;
219 }
220
221
222 /** Make a where clause to get a user's sessions.
223 * Prepare the where clause request that will retrieve the sessions.
224 *
225 * @param $year INTEGER Only get log entries made during the given year.
226 * @param $month INTEGER Only get log entries made during the given month.
227 * @param $day INTEGER Only get log entries made during the given day.
228 * @param $uid INTEGER Only get log entries referring to the given user ID.
229 *
230 * @return STRING the WHERE clause of a query, including the 'WHERE' keyword
231 * @private
232 */
233 function _makeWhere($year, $month, $day, $uid)
234 {
235 // start constructing the "where" clause
236 $where = array();
237
238 if ($uid)
239 array_push($where, "uid='$uid'");
240
241 // we were given at least a year
242 if ($year) {
243 if ($day) {
244 $dmin = mktime(0, 0, 0, $month, $day, $year);
245 $dmax = mktime(0, 0, 0, $month, $day+1, $year);
246 } elseif ($month) {
247 $dmin = mktime(0, 0, 0, $month, 1, $year);
248 $dmax = mktime(0, 0, 0, $month+1, 1, $year);
249 } else {
250 $dmin = mktime(0, 0, 0, 1, 1, $year);
251 $dmax = mktime(0, 0, 0, 1, 1, $year+1);
252 }
253 $where[] = "start >= " . date("Ymd000000", $dmin);
254 $where[] = "start < " . date("Ymd000000", $dmax);
255 }
256
257 if (!empty($where)) {
258 return ' WHERE ' . implode($where, " AND ");
259 } else {
260 return '';
261 }
262 // WE know it's totally reversed, so better use array_reverse than a SORT BY start DESC
263 }
264
265 // }}}
266
267 function handler_logger(&$page, $action = null, $arg = null) {
268 if ($action == 'session') {
269
270 // we are viewing a session
271 $res = XDB::query("SELECT ls.*, a.alias AS username, sa.alias AS suer
272 FROM log_sessions AS ls
273 LEFT JOIN aliases AS a ON (a.uid = ls.uid AND a.type='a_vie')
274 LEFT JOIN aliases AS sa ON (sa.uid = ls.suid AND sa.type='a_vie')
275 WHERE ls.id = {?}", $arg);
276
277 $page->assign('session', $a = $res->fetchOneAssoc());
278
279 $res = XDB::iterator('SELECT a.text, e.data, e.stamp
280 FROM log_events AS e
281 LEFT JOIN log_actions AS a ON e.action=a.id
282 WHERE e.session={?}', $arg);
283 while ($myarr = $res->next()) {
284 $page->append('events', $myarr);
285 }
286
287 } else {
288 $loguser = $action == 'user' ? $arg : Env::v('loguser');
289
290 $res = XDB::query('SELECT uid FROM aliases WHERE alias={?}',
291 $loguser);
292 $loguid = $res->fetchOneCell();
293
294 if ($loguid) {
295 $year = Env::i('year');
296 $month = Env::i('month');
297 $day = Env::i('day');
298 } else {
299 $year = Env::i('year', intval(date('Y')));
300 $month = Env::i('month', intval(date('m')));
301 $day = Env::i('day', intval(date('d')));
302 }
303
304 if (!$year)
305 $month = 0;
306 if (!$month)
307 $day = 0;
308
309 // smarty assignments
310 // retrieve available years
311 $page->assign('years', $this->_getYears());
312 $page->assign('year', $year);
313
314 // retrieve available months for the current year
315 $page->assign('months', $this->_getMonths($year));
316 $page->assign('month', $month);
317
318 // retrieve available days for the current year and month
319 $page->assign('days', $this->_getDays($year, $month));
320 $page->assign('day', $day);
321
322 $page->assign('loguser', $loguser);
323 // smarty assignments
324
325 if ($loguid || $year) {
326
327 // get the requested sessions
328 $where = $this->_makeWhere($year, $month, $day, $loguid);
329 $select = "SELECT s.id, s.start, s.uid,
330 a.alias as username
331 FROM log_sessions AS s
332 LEFT JOIN aliases AS a ON (a.uid = s.uid AND a.type='a_vie')
333 $where
334 ORDER BY start DESC";
335 $res = XDB::iterator($select);
336
337 $sessions = array();
338 while ($mysess = $res->next()) {
339 $mysess['events'] = array();
340 $sessions[$mysess['id']] = $mysess;
341 }
342 array_reverse($sessions);
343
344 // attach events
345 $sql = "SELECT s.id, a.text
346 FROM log_sessions AS s
347 LEFT JOIN log_events AS e ON(e.session=s.id)
348 INNER JOIN log_actions AS a ON(a.id=e.action)
349 $where";
350
351 $res = XDB::iterator($sql);
352 while ($event = $res->next()) {
353 array_push($sessions[$event['id']]['events'], $event['text']);
354 }
355 $page->assign_by_ref('sessions', $sessions);
356 } else {
357 $page->assign('msg_nofilters', "Sélectionner une annuée et/ou un utilisateur");
358 }
359 }
360
361 $page->changeTpl('admin/logger-view.tpl');
362
363 $page->setTitle('Administration - Logs des sessions');
364 }
365
366 function handler_user(&$page, $login = false)
367 {
368 global $globals;
369 $page->changeTpl('admin/user.tpl');
370 $page->setTitle('Administration - Compte');
371
372 if (S::suid()) {
373 $page->kill("Déjà en SUID&nbsp;!!!");
374 }
375
376 // Loads the user identity using the environment.
377 $user = User::get($login);
378 if (!$user) {
379 return;
380 }
381
382 $login = $user->login();
383 $registered = ($user->state != 'pending');
384
385 // Form processing
386 if (!empty($_POST)) {
387 S::assert_xsrf_token();
388 if (Post::has('uid') && Post::i('uid') != $user->id()) {
389 $page->kill('Une erreur s\'est produite');
390 }
391 }
392
393 // Handles specific requests (AX sync, su, ...).
394 if(Post::has('logs_account')) {
395 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
396 }
397
398 if(Post::has('su_button') && $registered) {
399 if (!Platal::session()->startSUID($user)) {
400 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->login());
401 } else {
402 pl_redirect("");
403 }
404 }
405
406 // Account Form {{{
407 $to_update = array();
408 if (Post::has('disable_weak_access')) {
409 $to_update['weak_password'] = null;
410 } else if (Post::has('update_account')) {
411 if (Post::s('full_name') != $user->fullName()) {
412 // XXX: Update profile if a profile is associated
413 $to_update['full_name'] = Post::s('full_name');
414 }
415 if (Post::s('display_name') != $user->displayName()) {
416 // XXX: Update profile if a profile is associated
417 $to_update['display_name'] = Post::s('display_name');
418 }
419 if (Post::s('sex') != ($user->isFemale() ? 'female' : 'male')) {
420 $to_update['sex'] = Post::s('sex');
421 }
422 if (!Post::blank('hashpass')) {
423 $to_update['password'] = Post::s('hashpass');
424 // TODO: Propagate the password update to GoogleApps, when required. Eg:
425 // $account = new GoogleAppsAccount($user);
426 // if ($account->active() && $account->sync_password) {
427 // $account->set_password($pass_encrypted);
428 // }
429 }
430 if (!Post::blank('weak_password')) {
431 $to_update['weak_password'] = Post::s('weak_password');
432 }
433 if (Post::i('token_access', 0) != ($user->token_access ? 1 : 0)) {
434 $to_update['token'] = Post::i('token_access') ? rand_url_id(16) : null;
435 }
436 if (Post::i('skin', 0) != $user->skin) {
437 $to_update['skin'] = Post::i('skin', 0);
438 if ($to_update['skin'] == 0) {
439 $to_update['skin'] = null;
440 }
441 }
442 if (Post::s('state') != $user->state) {
443 $to_update['state'] = Post::s('state');
444 }
445 if (Post::i('is_admin', 0) != ($user->is_admin ? 1 : 0)) {
446 $to_update['is_admin'] = Post::b('is_admin');
447 }
448 if (Post::s('type') != $user->type) {
449 $to_update['type'] = Post::s('type');
450 }
451 if (Post::i('watch', 0) != ($user->watch ? 1 : 0)) {
452 $to_update['flags'] = new PlFlagset();
453 $to_update['flags']->addFlag('watch', Post::i('watch'));
454 }
455 if (Post::t('comment') != $user->comment) {
456 $to_update['comment'] = Post::blank('comment') ? null : Post::t('comment');
457 }
458 }
459 if (!empty($to_update)) {
460 // TODO: fetch the initial values of the fields, and eventually send
461 // a summary of the changes to an admin.
462 $set = array();
463 foreach ($to_update as $k => $value) {
464 $set[] = XDB::format($k . ' = {?}', $value);
465 }
466 XDB::execute('UPDATE accounts
467 SET ' . implode(', ', $set) . '
468 WHERE uid = ' . XDB::format('{?}', $user->id()));
469 $page->trigSuccess('Données du compte mise à jour avec succès');
470 $user = User::getWithUID($user->id());
471 }
472 // }}}
473
474 // Profile form {{{
475 if (Post::has('add_profile') || Post::has('del_profile') || Post::has('owner')) {
476 if (Post::i('del_profile', 0) != 0) {
477 XDB::execute('DELETE FROM account_profiles
478 WHERE uid = {?} AND pid = {?}',
479 $user->id(), Post::i('del_profile'));
480 } else if (!Post::blank('new_profile')) {
481 $profile = Profile::get(Post::t('new_profile'));
482 if (!$profile) {
483 $page->trigError('Le profil ' . Post::t('new_profile') . ' n\'existe pas');
484 } else {
485 XDB::execute('INSERT IGNORE INTO account_profiles (uid, pid)
486 VALUES ({?}, {?})',
487 $user->id(), $profile->id());
488 }
489 }
490 XDB::execute('UPDATE account_profiles
491 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
492 WHERE uid = {?}',
493 Post::i('owner'), $user->id());
494 }
495 // }}}
496
497 // Email forwards form {{{
498 require_once("emails.inc.php");
499 $redirect = ($registered ? new Redirect($user) : null);
500 if (Post::has('add_fwd')) {
501 $email = Post::t('email');
502 if (!isvalid_email_redirection($email)) {
503 $page->trigError("Email non valide: $email");
504 } else {
505 $redirect->add_email($email);
506 $page->trigSuccess("Ajout de $email effectué");
507 }
508 } else if (!Post::blank('del_fwd')) {
509 $redirect->delete_email(Post::t('del_fwd'));
510 } else if (!Post::blank('activate_fwd')) {
511 $redirect->modify_one_email(Post::t('activate_fwd', true));
512 } else if (!Post::blank('deactivate_fwd')) {
513 $redirect->modify_one_email(Post::t('deactivate_fwd', false));
514 } else if (Post::has('disable_fwd')) {
515 $redirect->disable();
516 } else if (Post::has('enable_fwd')) {
517 $redirect->enable();
518 } else if (!Post::blank('clean_fwd')) {
519 $redirect->clean_errors(Post::t('clean_fwd'));
520 }
521 // }}}
522
523 // Email alias form {{{
524 if (Post::has('add_alias')) {
525 // Splits new alias in user and fqdn.
526 $alias = Env::t('email');
527 if (strpos($alias, '@') !== false) {
528 list($alias, $domain) = explode('@', $alias);
529 } else {
530 $domain = $globals->mail->domain;
531 }
532
533 // Checks for alias' user validity.
534 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
535 $page->trigError("'$alias' n'est pas un alias valide");
536 }
537
538 // Eventually adds the alias to the right domain.
539 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
540 $req = new AliasReq($user, $alias, 'Admin request', false);
541 if ($req->commit()) {
542 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué");
543 } else {
544 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué");
545 }
546 } elseif ($domain == $globals->mail->domain || $domain == $globals->mail->domain2) {
547 $res = XDB::execute("INSERT INTO aliases (uid, alias, type)
548 VALUES ({?}, {?}, 'alias')",
549 $user->id(), $alias);
550 $page->trigSuccess("Nouvel alias '$alias' ajouté");
551 } else {
552 $page->trigError("Le domaine '$domain' n'est pas valide");
553 }
554 } else if (!Post::blank('del_alias')) {
555 XDB::execute("DELETE FROM aliases
556 WHERE uid = {?} AND alias = {?} AND
557 type NOT IN ('a_vie', 'homonyme')",
558 $user->id(), $val);
559 XDB::execute("UPDATE emails
560 SET rewrite = ''
561 WHERE uid = {?} AND rewrite LIKE CONCAT({?}, '@%')",
562 $user->id(), $val);
563 fix_bestalias($user);
564 $page->trigSuccess("L'alias '$val' a été supprimé");
565 } else if (!Post::blank('best')) {
566 XDB::execute("UPDATE aliases
567 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
568 WHERE uid = {?}", $user->id());
569 XDB::execute("UPDATE aliases
570 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
571 WHERE uid = {?} AND alias = {?}", $user->id(), $val);
572 // As having a non-null bestalias value is critical in
573 // plat/al's code, we do an a posteriori check on the
574 // validity of the bestalias.
575 fix_bestalias($user);
576 }
577 // }}}
578
579 // OpenId form {{{
580 if (Post::has('del_openid')) {
581 XDB::execute('DELETE FROM account_auth_openid
582 WHERE id = {?}', Post::i('del_openid'));
583 }
584 // }}}
585
586 // Forum form {{{
587 if (Post::has('b_edit')) {
588 XDB::execute("DELETE FROM forum_innd
589 WHERE uid = {?}", $user->id());
590 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
591 XDB::execute("INSERT INTO forum_innd
592 SET ipmin = '0', ipmax = '4294967295',
593 write_perm = {?}, read_perm = {?},
594 comment = {?}, priority = '200', uid = {?}",
595 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
596 }
597 }
598 // }}}
599
600
601 $page->addJsLink('ui.core.js');
602 $page->addJsLink('ui.tabs.js');
603
604 // Displays last login and last host information.
605 $res = XDB::query("SELECT start, host
606 FROM log_sessions
607 WHERE uid = {?} AND suid = 0
608 ORDER BY start DESC
609 LIMIT 1", $user->id());
610 list($lastlogin,$host) = $res->fetchOneRow();
611 $page->assign('lastlogin', $lastlogin);
612 $page->assign('host', $host);
613
614 // Display active aliases.
615 $page->assign('virtuals', $user->emailAliases());
616 $page->assign('aliases', XDB::iterator("SELECT alias, type='a_vie' AS for_life,
617 FIND_IN_SET('bestalias',flags) AS best, expire
618 FROM aliases
619 WHERE uid = {?} AND type != 'homonyme'
620 ORDER BY type != 'a_vie'", $user->id()));
621 $page->assign('account_types', XDB::iterator('SELECT * FROM account_types ORDER BY type'));
622 $page->assign('skins', XDB::iterator('SELECT id, name FROM skins ORDER BY name'));
623 $page->assign('profiles', XDB::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
624 FROM account_profiles AS ap
625 INNER JOIN profiles AS p ON (ap.pid = p.pid)
626 WHERE ap.uid = {?}', $user->id()));
627 $page->assign('openid', XDB::iterator('SELECT id, url
628 FROM account_auth_openid
629 WHERE uid = {?}', $user->id()));
630
631 // Displays email redirection and the general profile.
632 if ($registered && $redirect) {
633 $page->assign('emails', $redirect->emails);
634 }
635
636 $page->assign('user', $user);
637
638 // Displays forum bans.
639 $res = XDB::query("SELECT write_perm, read_perm, comment
640 FROM forum_innd
641 WHERE uid = {?}", $user->id());
642 $bans = $res->fetchOneAssoc();
643 $page->assign('bans', $bans);
644 }
645
646 private static function getHrid($firstname, $lastname, $promo)
647 {
648 if ($firstname != null && $lastname != null && $promo != null) {
649 return User::makeHrid($firstname, $lastname, $promo);
650 }
651 return null;
652 }
653
654 private static function formatNewUser($infosLine, $separator, $promo, $size)
655 {
656 $infos = explode($separator, $infosLine);
657 if (sizeof($infos) != $size) {
658 return false;
659 }
660
661 array_map('trim', $infos);
662 $hrid = self::getHrid($infos[1], $infos[0], $promo);
663 $res1 = XDB::query('SELECT COUNT(*)
664 FROM accounts
665 WHERE hruid = {?}', $hrid);
666 $res2 = XDB::query('SELECT COUNT(*)
667 FROM profiles
668 WHERE hrpid = {?}', $hrid);
669 if (is_null($hrid) || $res1->fetchOneCell() > 0 || $res2->fetchOneCell() > 0) {
670 $page->trigError("La ligne $line n'a pas été ajoutée.");
671 return false;
672 }
673 $infos['hrid'] = $hrid;
674 return $infos;
675 }
676
677 private static function formatSex(&$page, $sex, $line)
678 {
679 switch ($sex) {
680 case 'F':
681 return PlUser::GENDER_FEMALE;
682 case 'M':
683 return PlUser::GENDER_MALE;
684 default:
685 $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
686 return null;
687 }
688 }
689
690 private static function formatBirthDate($birthDate)
691 {
692 return date("Y-m-d", strtotime($birthDate));
693 }
694
695 function handler_add_accounts(&$page, $action = null, $promo = null)
696 {
697 $page->changeTpl('admin/add_accounts.tpl');
698
699 if (Env::has('add_type') && Env::has('people')) {
700 require_once 'directory.enums.inc.php';
701 $lines = explode("\n", Env::t('people'));
702 $separator = Env::t('separator');
703 $promotion = Env::i('promotion');
704 $nameTypes = DirEnum::getOptions(DirEnum::NAMETYPES);
705 $nameTypes = array_flip($nameTypes);
706
707 if (Env::t('add_type') == 'promo') {
708 $type = 'x';
709 $eduSchools = DirEnum::getOptions(DirEnum::EDUSCHOOLS);
710 $eduSchools = array_flip($eduSchools);
711 $eduDegrees = DirEnum::getOptions(DirEnum::EDUDEGREES);
712 $eduDegrees = array_flip($eduDegrees);
713 var_dump($eduDegrees);
714 switch (Env::t('edu_type')) {
715 case 'X':
716 $degreeid = $eduDegrees[Profile::DEGREE_X];
717 $entry_year = $promotion;
718 $grad_year = $promotion + 3;
719 $promo = 'X' . $promotion;
720 break;
721 case 'M':
722 $degreeid = $eduDegrees[Profile::DEGREE_M];
723 $grad_year = $promotion;
724 $entry_year = $promotion - 2;
725 $promo = 'M' . $promotion;
726 break;
727 case 'D':
728 $degreeid = $eduDegrees[Profile::DEGREE_D];
729 $grad_year = $promotion;
730 $entry_year = $promotion - 3;
731 $promo = 'D' . $promotion;
732 break;
733 default:
734 $page->killError("La formation n'est pas reconnue:" . Env::t('edu_type') . '.');
735 }
736
737 foreach ($lines as $line) {
738 if (($infos = self::formatNewUser($line, $separator, $promotion, 6))
739 && ($sex = self::formatSex($page, $infos[3], $line))) {
740 $name = $infos[1] . ' ' . $infos[0];
741 $birthDate = self::formatBirthDate($infos[2]);
742 $xorgId = Profile::getXorgId($infos[4]);
743
744 XDB::execute('INSERT INTO profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex)
745 VALUES ({?}, {?}, {?}, {?})',
746 $infos['hrid'], $xorgId, $infos[5], $birthDate, $sex);
747 $pid = XDB::insertId();
748 XDB::execute('INSERT INTO profile_name (pid, name, typeid)
749 VALUES ({?}, {?}, {?})',
750 $pid, $infos[0], $nameTypes['name_ini']);
751 XDB::execute('INSERT INTO profile_name (pid, name, typeid)
752 VALUES ({?}, {?}, {?})',
753 $pid, $infos[1], $nameTypes['firstname_ini']);
754 XDB::execute('INSERT INTO profile_display (pid, yourself, public_name, private_name,
755 directory_name, short_name, sort_name, promo)
756 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
757 $pid, $infos[1], $name, $name, $name, $name, $infos[0] . ' ' . $infos[1], $promo);
758 XDB::execute('INSERT INTO profile_education (pid, eduid, degreeid, entry_year, grad_year, flags)
759 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
760 $pid, $eduSchools[Profile::EDU_X], $degreeid, $entry_year, $grad_year, 'primary');
761 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, full_name, display_name, sex)
762 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
763 $infos['hrid'], $type, 0, 'active', $name, $infos[1], $sex);
764 $uid = XDB::insertId();
765 XDB::execute('INSERT INTO account_profiles (uid, pid, perms)
766 VALUES ({?}, {?}, {?})',
767 $uid, $pid, 'owner');
768 }
769 }
770 } else if (Env::t('add_type') == 'account') {
771 $type = Env::t('type');
772 foreach ($lines as $line) {
773 if (($infos = self::formatNewUser($line, $separator, $type, 4))
774 && ($sex = self::formatSex(&$page, $infos[3], $line))) {
775 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, email, full_name, display_name, sex)
776 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
777 $infos['hrid'], $type, 0, 'active', $infos[2], $infos[1] . ' ' . $infos[0], $infos[1], $sex);
778 }
779 }
780 } else if (Env::t('add_type') == 'ax_id') {
781 $type = 'x';
782 foreach ($lines as $line) {
783 if ($infos = self::formatNewUser($line, $separator, $promotion, 3)) {
784 XDB::execute('UPDATE profiles
785 SET ax_id = {?}
786 WHERE hrpid = {?}',
787 $infos[2], $infos['hrid']);
788 }
789 }
790 }
791
792 if ($page->nb_errs == 0) {
793 $page->trigSuccess("L'opération a été effectuée avec succès.");
794 } else {
795 $page->trigSuccess("L'opération a été effectuée avec succès, sauf pour les "
796 . $page->nb_errs . 'erreurs signalées ci-dessus.');
797 }
798 } else if (Env::has('add_type')) {
799 $res = XDB::query('SELECT type
800 FROM account_types');
801 $page->assign('account_types', $res->fetchColumn());
802 $page->assign('add_type', Env::s('add_type'));
803 }
804 }
805
806 function handler_homonyms(&$page, $op = 'list', $target = null)
807 {
808 $page->changeTpl('admin/homonymes.tpl');
809 $page->setTitle('Administration - Homonymes');
810 $this->load("homonyms.inc.php");
811
812 if ($target) {
813 $user = User::getSilent($target);
814 if (!$user || !($loginbis = select_if_homonyme($user))) {
815 $target = 0;
816 } else {
817 $page->assign('user', $user);
818 $page->assign('loginbis',$loginbis);
819 }
820 }
821
822 $page->assign('op', $op);
823 $page->assign('target', $target);
824
825 // on a un $target valide, on prepare les mails
826 if ($target) {
827 // on examine l'op a effectuer
828 switch ($op) {
829 case 'mail':
830 S::assert_xsrf_token();
831
832 send_warning_homonyme($user, $loginbis);
833 switch_bestalias($user, $loginbis);
834 $op = 'list';
835 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
836 break;
837
838 case 'correct':
839 S::assert_xsrf_token();
840
841 switch_bestalias($user, $loginbis);
842 XDB::execute("UPDATE aliases
843 SET type = 'homonyme', expire=NOW()
844 WHERE alias = {?}", $loginbis);
845 XDB::execute("REPLACE INTO homonyms (homonyme_id, uid)
846 VALUES ({?}, {?})", $target, $target);
847 send_robot_homonyme($user, $loginbis);
848 $op = 'list';
849 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
850 break;
851 }
852 }
853
854 if ($op == 'list') {
855 $res = XDB::iterator(
856 "SELECT a.alias AS homonyme, s.alias AS forlife,
857 IF(h.homonyme_id = s.id, a.expire, NULL) AS expire,
858 IF(h.homonyme_id = s.id, a.type, NULL) AS type, ac.uid
859 FROM aliases AS a
860 LEFT JOIN homonyms AS h ON (h.homonyme_id = a.uid)
861 INNER JOIN aliases AS s ON (s.uid = h.uid AND s.type = 'a_vie')
862 INNER JOIN accounts AS ac ON (ac.uid = a.uid)
863 WHERE a.type = 'homonyme' OR a.expire != ''
864 ORDER BY a.alias, forlife");
865 $hnymes = Array();
866 while ($tab = $res->next()) {
867 $hnymes[$tab['homonyme']][] = $tab;
868 }
869 $page->assign_by_ref('hnymes', $hnymes);
870 }
871 }
872
873 function handler_deaths(&$page, $promo = 0, $validate = false)
874 {
875 $page->changeTpl('admin/deces_promo.tpl');
876 $page->setTitle('Administration - Deces');
877
878 if (!$promo) {
879 $promo = Env::t('promo', 'X1923');
880 }
881 $page->assign('promo', $promo);
882 if (!$promo) {
883 return;
884 }
885
886 if ($validate) {
887 S::assert_xsrf_token();
888
889 $res = XDB::iterRow('SELECT p.hrpid, pd.directory_name, p.deathdate
890 FROM profiles AS p
891 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
892 WHERE pd.promo = {?}', $promo);
893 while (list($pid, $name, $death) = $res->next()) {
894 $val = Env::v($pid);
895 if($val == $deces || empty($val)) {
896 continue;
897 }
898
899 XDB::execute('UPDATE profiles
900 SET deathdate = {?}, deathdate_rec = NOW()
901 WHERE hrpid = {?}', $val, $pid);
902 $page->trigSuccess('Ajout du décès de ' . $name . ' le ' . $val . '.');
903 if($death == '0000-00-00' || empty($death)) {
904 // TODO: FIX THIS DEPRECATED CALL
905 require_once('user.func.inc.php');
906 user_clear_all_subs($uid, false); // by default, dead ppl do not loose their email
907 }
908 }
909 }
910
911 $res = XDB::iterator('SELECT p.hrpid, pd.directory_name, p.deathdate
912 FROM profiles AS p
913 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
914 WHERE pd.promo = {?}
915 ORDER BY pd.sort_name', $promo);
916 $page->assign('decedes', $res);
917 }
918
919 function handler_dead_but_active(&$page)
920 {
921 $page->changeTpl('admin/dead_but_active.tpl');
922 $page->setTitle('Administration - Décédés');
923
924 $res = XDB::iterator(
925 "SELECT a.hruid, pd.promo, p.ax_id, pd.directory_name, p.deathdate, DATE(MAX(s.start)) AS last
926 FROM accounts AS a
927 INNER JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET('owner', ap.perms))
928 INNER JOIN profiles AS p ON (p.pid = ap.pid)
929 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
930 LEFT JOIN log_sessions AS s ON (s.uid = a.uid AND suid = 0)
931 WHERE a.state = 'active' AND p.deathdate IS NOT NULL
932 GROUP BY a.uid
933 ORDER BY pd.promo, pd.sort_name");
934 $page->assign('dead', $res);
935 }
936
937 function handler_validate(&$page, $action = 'list', $id = null)
938 {
939 $page->changeTpl('admin/valider.tpl');
940 $page->setTitle('Administration - Valider une demande');
941 $page->addCssLink('nl.css');
942 $page->addJsLink('ajax.js');
943 require_once("validations.inc.php");
944
945
946 if ($action == 'edit' and !is_null($id)) {
947 $page->assign('preview_id', $id);
948 }
949
950 if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
951 S::assert_xsrf_token();
952
953 $req = Validate::get_typed_request(Env::v('uid'), Env::v('type'), Env::v('stamp'));
954 if ($req) {
955 $req->handle_formu();
956 } else {
957 $page->trigWarning('La validation a déjà été effectuée.');
958 }
959 }
960
961 $r = XDB::iterator('SHOW COLUMNS FROM requests_answers');
962 while (($a = $r->next()) && $a['Field'] != 'category');
963 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
964
965 $hidden = array();
966 $res = XDB::query('SELECT hidden_requests
967 FROM requests_hidden
968 WHERE uid = {?}', S::v('uid'));
969 $hide_requests = $res->fetchOneCell();
970 if (Post::has('hide')) {
971 $hide = array();
972 foreach ($categories as $cat)
973 if (!Post::v($cat)) {
974 $hidden[$cat] = 1;
975 $hide[] = $cat;
976 }
977 $hide_requests = join(',', $hide);
978 XDB::query('REPLACE INTO requests_hidden (uid, hidden_requests)
979 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','downtimes','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 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 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 ip_watch AS w
1230 LEFT JOIN accounts AS a1 ON (a1.uid = w.uid)
1231 LEFT JOIN log_sessions AS s ON (w.ip = s.ip)
1232 LEFT JOIN 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 pid = {?} 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 (pid, 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.pid = e.id AND link_type = 'hq' AND tel_id = 0)
1384 LEFT JOIN profile_phones AS f ON (f.pid = 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 ?>