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