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