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