Prevents notices.
[platal.git] / modules / admin.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 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_COOKIE, 'admin'),
29 'set_skin' => $this->make_hook('set_skin', AUTH_COOKIE, 'admin'),
30 'admin' => $this->make_hook('default', AUTH_MDP, 'admin'),
31 'admin/dead-but-active' => $this->make_hook('dead_but_active', AUTH_MDP, 'admin'),
32 'admin/deaths' => $this->make_hook('deaths', AUTH_MDP, 'admin'),
33 'admin/downtime' => $this->make_hook('downtime', AUTH_MDP, 'admin'),
34 'admin/homonyms' => $this->make_hook('homonyms', AUTH_MDP, 'admin'),
35 'admin/logger' => $this->make_hook('logger', AUTH_MDP, 'admin'),
36 'admin/logger/actions' => $this->make_hook('logger_actions', AUTH_MDP, 'admin'),
37 'admin/postfix/blacklist' => $this->make_hook('postfix_blacklist', AUTH_MDP, 'admin'),
38 'admin/postfix/delayed' => $this->make_hook('postfix_delayed', AUTH_MDP, 'admin'),
39 'admin/postfix/regexp_bounces' => $this->make_hook('postfix_regexpsbounces', AUTH_MDP, 'admin'),
40 'admin/postfix/whitelist' => $this->make_hook('postfix_whitelist', AUTH_MDP, 'admin'),
41 'admin/mx/broken' => $this->make_hook('mx_broken', AUTH_MDP, 'admin'),
42 'admin/skins' => $this->make_hook('skins', AUTH_MDP, 'admin'),
43 'admin/user' => $this->make_hook('user', AUTH_MDP, 'admin'),
44 'admin/add_accounts' => $this->make_hook('add_accounts', AUTH_MDP, 'admin'),
45 'admin/validate' => $this->make_hook('validate', AUTH_MDP, 'admin,edit_directory'),
46 'admin/validate/answers' => $this->make_hook('validate_answers', AUTH_MDP, 'admin'),
47 'admin/wiki' => $this->make_hook('wiki', AUTH_MDP, 'admin'),
48 'admin/ipwatch' => $this->make_hook('ipwatch', AUTH_MDP, 'admin'),
49 'admin/icons' => $this->make_hook('icons', AUTH_MDP, 'admin'),
50 'admin/geocoding' => $this->make_hook('geocoding', AUTH_MDP, 'admin'),
51 'admin/accounts' => $this->make_hook('accounts', AUTH_MDP, 'admin'),
52 'admin/account/watch' => $this->make_hook('account_watch', AUTH_MDP, 'admin'),
53 'admin/account/types' => $this->make_hook('account_types', AUTH_MDP, 'admin'),
54 'admin/xnet_without_group' => $this->make_hook('xnet_without_group', AUTH_MDP, 'admin'),
55 'admin/jobs' => $this->make_hook('jobs', AUTH_MDP, 'admin,edit_directory'),
56 'admin/profile' => $this->make_hook('profile', AUTH_MDP, 'admin,edit_directory')
57 );
58 }
59
60 function handler_phpinfo($page)
61 {
62 phpinfo();
63 exit;
64 }
65
66 function handler_get_rights($page)
67 {
68 if (S::suid()) {
69 $page->kill('Déjà en SUID');
70 }
71 S::assert_xsrf_token();
72 $level = Post::s('account_type');
73 if ($level != 'admin') {
74 $user = User::getSilentWithUID(S::user()->id());
75 $user->is_admin = false;
76 $types = DirEnum::getOptions(DirEnum::ACCOUNTTYPES);
77 if (!empty($types[$level])) {
78 $user->setPerms($types[$level]);
79 }
80 S::set('suid_startpage', $_SERVER['HTTP_REFERER']);
81 Platal::session()->startSUID($user);
82 }
83 if (!empty($_SERVER['HTTP_REFERER'])) {
84 http_redirect($_SERVER['HTTP_REFERER']);
85 } else {
86 pl_redirect('/');
87 }
88 }
89
90 function handler_set_skin($page)
91 {
92 S::assert_xsrf_token();
93 S::set('skin', Post::s('change_skin'));
94 if (!empty($_SERVER['HTTP_REFERER'])) {
95 http_redirect($_SERVER['HTTP_REFERER']);
96 } else {
97 pl_redirect('/');
98 }
99 }
100
101 function handler_default($page)
102 {
103 $page->changeTpl('admin/index.tpl');
104 $page->setTitle('Administration');
105 }
106
107 function handler_postfix_delayed($page)
108 {
109 $page->changeTpl('admin/postfix_delayed.tpl');
110 $page->setTitle('Administration - Postfix : Retardés');
111
112 if (Env::has('del')) {
113 $crc = Env::v('crc');
114 XDB::execute("UPDATE postfix_mailseen SET release = 'del' WHERE crc = {?}", $crc);
115 $page->trigSuccess($crc . " verra tous ses emails supprimés&nbsp;!");
116 } elseif (Env::has('ok')) {
117 $crc = Env::v('crc');
118 XDB::execute("UPDATE postfix_mailseen SET release = 'ok' WHERE crc = {?}", $crc);
119 $page->trigSuccess($crc . " a le droit de passer&nbsp;!");
120 }
121
122 $sql = XDB::iterator(
123 "SELECT crc, nb, update_time, create_time,
124 FIND_IN_SET('del', p.release) AS del,
125 FIND_IN_SET('ok', p.release) AS ok
126 FROM postfix_mailseen AS p
127 WHERE nb >= 30
128 ORDER BY p.release != ''");
129
130 $page->assign_by_ref('mails', $sql);
131 }
132
133 // {{{ logger view
134
135 /** Retrieves the available days for a given year and month.
136 * Obtain a list of days of the given month in the given year
137 * that are within the range of dates that we have log entries for.
138 *
139 * @param integer year
140 * @param integer month
141 * @return array days in that month we have log entries covering.
142 * @private
143 */
144 function _getDays($year, $month)
145 {
146 // give a 'no filter' option
147 $days = array();
148 $days[0] = "----";
149
150 if ($year && $month) {
151 $day_max = Array(-1, 31, checkdate(2, 29, $year) ? 29 : 28 , 31,
152 30, 31, 30, 31, 31, 30, 31, 30, 31);
153 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
154 MONTH(MAX(start)), MONTH(MIN(start)),
155 DAYOFMONTH(MAX(start)),
156 DAYOFMONTH(MIN(start))
157 FROM log_sessions");
158 list($ymax, $ymin, $mmax, $mmin, $dmax, $dmin) = $res->fetchOneRow();
159
160 if (($year < $ymin) || ($year == $ymin && $month < $mmin)) {
161 return array();
162 }
163
164 if (($year > $ymax) || ($year == $ymax && $month > $mmax)) {
165 return array();
166 }
167
168 $min = ($year==$ymin && $month==$mmin) ? intval($dmin) : 1;
169 $max = ($year==$ymax && $month==$mmax) ? intval($dmax) : $day_max[$month];
170
171 for($i = $min; $i<=$max; $i++) {
172 $days[$i] = $i;
173 }
174 }
175 return $days;
176 }
177
178
179 /** Retrieves the available months for a given year.
180 * Obtains a list of month numbers that are within the timeframe that
181 * we have log entries for.
182 *
183 * @param integer year
184 * @return array List of month numbers we have log info for.
185 * @private
186 */
187 function _getMonths($year)
188 {
189 // give a 'no filter' option
190 $months = array();
191 $months[0] = "----";
192
193 if ($year) {
194 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
195 MONTH(MAX(start)), MONTH(MIN(start))
196 FROM log_sessions");
197 list($ymax, $ymin, $mmax, $mmin) = $res->fetchOneRow();
198
199 if (($year < $ymin) || ($year > $ymax)) {
200 return array();
201 }
202
203 $min = $year == $ymin ? intval($mmin) : 1;
204 $max = $year == $ymax ? intval($mmax) : 12;
205
206 for($i = $min; $i<=$max; $i++) {
207 $months[$i] = $i;
208 }
209 }
210 return $months;
211 }
212
213
214 /** Retrieves the available years.
215 * Obtains a list of years that we have log entries covering.
216 *
217 * @return array years we have log entries for.
218 * @private
219 */
220 function _getYears()
221 {
222 // give a 'no filter' option
223 $years = array();
224 $years[0] = "----";
225
226 // retrieve available years
227 $res = XDB::query("select YEAR(MAX(start)), YEAR(MIN(start)) FROM log_sessions");
228 list($max, $min) = $res->fetchOneRow();
229
230 for($i = intval($min); $i<=$max; $i++) {
231 $years[$i] = $i;
232 }
233 return $years;
234 }
235
236
237 /** Make a where clause to get a user's sessions.
238 * Prepare the where clause request that will retrieve the sessions.
239 *
240 * @param $year INTEGER Only get log entries made during the given year.
241 * @param $month INTEGER Only get log entries made during the given month.
242 * @param $day INTEGER Only get log entries made during the given day.
243 * @param $uid INTEGER Only get log entries referring to the given user ID.
244 *
245 * @return STRING the WHERE clause of a query, including the 'WHERE' keyword
246 * @private
247 */
248 function _makeWhere($year, $month, $day, $uid)
249 {
250 // start constructing the "where" clause
251 $where = array();
252
253 if ($uid)
254 array_push($where, "s.uid='$uid'");
255
256 // we were given at least a year
257 if ($year) {
258 if ($day) {
259 $dmin = mktime(0, 0, 0, $month, $day, $year);
260 $dmax = mktime(0, 0, 0, $month, $day+1, $year);
261 } elseif ($month) {
262 $dmin = mktime(0, 0, 0, $month, 1, $year);
263 $dmax = mktime(0, 0, 0, $month+1, 1, $year);
264 } else {
265 $dmin = mktime(0, 0, 0, 1, 1, $year);
266 $dmax = mktime(0, 0, 0, 1, 1, $year+1);
267 }
268 $where[] = "start >= " . date("Ymd000000", $dmin);
269 $where[] = "start < " . date("Ymd000000", $dmax);
270 }
271
272 if (!empty($where)) {
273 return ' WHERE ' . implode($where, " AND ");
274 } else {
275 return '';
276 }
277 // WE know it's totally reversed, so better use array_reverse than a SORT BY start DESC
278 }
279
280 // }}}
281
282 function handler_logger($page, $action = null, $arg = null) {
283 if ($action == 'session') {
284
285 // we are viewing a session
286 $res = XDB::query("SELECT ls.*, a.hruid AS username, sa.hruid AS suer
287 FROM log_sessions AS ls
288 INNER JOIN accounts AS a ON (a.uid = ls.uid)
289 LEFT JOIN accounts AS sa ON (sa.uid = ls.suid)
290 WHERE ls.id = {?}", $arg);
291
292 $page->assign('session', $a = $res->fetchOneAssoc());
293
294 $res = XDB::iterator('SELECT a.text, e.data, e.stamp
295 FROM log_events AS e
296 LEFT JOIN log_actions AS a ON e.action=a.id
297 WHERE e.session={?}', $arg);
298 while ($myarr = $res->next()) {
299 $page->append('events', $myarr);
300 }
301
302 } else {
303 $loguser = $action == 'user' ? $arg : Env::v('loguser');
304
305 if ($loguser) {
306 $user = User::get($loguser);
307 $loguid = $user->id();
308 } else {
309 $loguid = null;
310 }
311
312 if ($loguid) {
313 $year = Env::i('year');
314 $month = Env::i('month');
315 $day = Env::i('day');
316 } else {
317 $year = Env::i('year', intval(date('Y')));
318 $month = Env::i('month', intval(date('m')));
319 $day = Env::i('day', intval(date('d')));
320 }
321
322 if (!$year)
323 $month = 0;
324 if (!$month)
325 $day = 0;
326
327 // smarty assignments
328 // retrieve available years
329 $page->assign('years', $this->_getYears());
330 $page->assign('year', $year);
331
332 // retrieve available months for the current year
333 $page->assign('months', $this->_getMonths($year));
334 $page->assign('month', $month);
335
336 // retrieve available days for the current year and month
337 $page->assign('days', $this->_getDays($year, $month));
338 $page->assign('day', $day);
339
340 $page->assign('loguser', $loguser);
341 // smarty assignments
342
343 if ($loguid || $year) {
344
345 // get the requested sessions
346 $where = $this->_makeWhere($year, $month, $day, $loguid);
347 $select = "SELECT s.id, s.start, s.uid,
348 a.hruid as username
349 FROM log_sessions AS s
350 INNER JOIN accounts AS a ON (a.uid = s.uid)
351 $where
352 ORDER BY start DESC";
353 $res = XDB::iterator($select);
354
355 $sessions = array();
356 while ($mysess = $res->next()) {
357 $mysess['events'] = array();
358 $sessions[$mysess['id']] = $mysess;
359 }
360 array_reverse($sessions);
361
362 // attach events
363 $sql = "SELECT s.id, a.text
364 FROM log_sessions AS s
365 LEFT JOIN log_events AS e ON(e.session=s.id)
366 INNER JOIN log_actions AS a ON(a.id=e.action)
367 $where";
368
369 $res = XDB::iterator($sql);
370 while ($event = $res->next()) {
371 array_push($sessions[$event['id']]['events'], $event['text']);
372 }
373 $page->assign_by_ref('sessions', $sessions);
374 } else {
375 $page->assign('msg_nofilters', "Sélectionner une année et/ou un utilisateur");
376 }
377 }
378
379 $page->changeTpl('admin/logger-view.tpl');
380
381 $page->setTitle('Administration - Logs des sessions');
382 }
383
384 function handler_user($page, $login = false)
385 {
386 global $globals;
387 $page->changeTpl('admin/user.tpl');
388 $page->setTitle('Administration - Compte');
389
390 if (S::suid()) {
391 $page->kill("Déjà en SUID&nbsp;!!!");
392 }
393
394 // Loads the user identity using the environment.
395 if ($login) {
396 $user = User::get($login);
397 }
398 if (empty($user)) {
399 pl_redirect('admin/accounts');
400 }
401
402 $listClient = new MMList(S::user());
403 $login = $user->login();
404 $registered = ($user->state != 'pending');
405
406 // Form processing
407 if (!empty($_POST)) {
408 S::assert_xsrf_token();
409 if (Post::has('uid') && Post::i('uid') != $user->id()) {
410 $page->kill('Une erreur s\'est produite');
411 }
412 }
413
414 // Handles specific requests (AX sync, su, ...).
415 if(Post::has('log_account')) {
416 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
417 }
418
419 if(Post::has('su_account') && $registered) {
420 if (!Platal::session()->startSUID($user)) {
421 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->login());
422 } else {
423 pl_redirect("");
424 }
425 }
426
427 // Handles account deletion.
428 if (Post::has('account_deletion_confirmation')) {
429 $uid = $user->id();
430 $name = $user->fullName();
431 $profile = $user->profile();
432 if ($profile && Post::b('clear_profile')) {
433 $user->profile()->clear();
434 }
435 $user->clear(true);
436 $page->trigSuccess("L'utilisateur $name ($uid) a bien été désinscrit.");
437 if (Post::b('erase_account')) {
438 XDB::execute('DELETE FROM accounts
439 WHERE uid = {?}',
440 $uid);
441 $page->trigSuccess("L'utilisateur $name ($uid) a été supprimé de la base de données");
442 }
443 }
444
445 // Account Form {{{
446 $to_update = array();
447 if (Post::has('disable_weak_access')) {
448 $to_update['weak_password'] = null;
449 } else if (Post::has('update_account')) {
450 if (!$user->hasProfile()) {
451 if (Post::s('full_name') != $user->fullName()) {
452 $to_update['full_name'] = Post::s('full_name');
453 }
454 if (Post::s('display_name') != $user->displayName()) {
455 $to_update['display_name'] = Post::s('display_name');
456 }
457 if (Post::s('directory_name') != $user->directoryName()) {
458 $to_update['directory_name'] = Post::s('directory_name');
459 }
460 }
461 if (Post::s('sex') != ($user->isFemale() ? 'female' : 'male')) {
462 $to_update['sex'] = Post::s('sex');
463 if ($user->hasProfile()) {
464 XDB::execute('UPDATE profiles
465 SET sex = {?}
466 WHERE pid = {?}',
467 Post::s('sex'), $user->profile()->id());
468 }
469 }
470 if (!Post::blank('pwhash')) {
471 $to_update['password'] = Post::s('pwhash');
472 require_once 'googleapps.inc.php';
473 $account = new GoogleAppsAccount($user);
474 if ($account->active() && $account->sync_password) {
475 $account->set_password(Post::s('pwhash'));
476 }
477 }
478 if (!Post::blank('weak_password')) {
479 $to_update['weak_password'] = Post::s('weak_password');
480 }
481 if (Post::i('token_access', 0) != ($user->token_access ? 1 : 0)) {
482 $to_update['token'] = Post::i('token_access') ? rand_url_id(16) : null;
483 }
484 if (Post::i('skin') != $user->skin) {
485 $to_update['skin'] = Post::i('skin');
486 if ($to_update['skin'] == 0) {
487 $to_update['skin'] = null;
488 }
489 }
490 if (Post::s('state') != $user->state) {
491 $to_update['state'] = Post::s('state');
492 }
493 if (Post::i('is_admin', 0) != ($user->is_admin ? 1 : 0)) {
494 $to_update['is_admin'] = Post::b('is_admin');
495 }
496 if (Post::s('type') != $user->type) {
497 $to_update['type'] = Post::s('type');
498 }
499 if (Post::i('watch', 0) != ($user->watch ? 1 : 0)) {
500 $to_update['flags'] = new PlFlagset();
501 $to_update['flags']->addFlag('watch', Post::i('watch'));
502 }
503 if (Post::t('comment') != $user->comment) {
504 $to_update['comment'] = Post::blank('comment') ? null : Post::t('comment');
505 }
506 if (!$user->checkPerms(User::PERM_MAIL) && Post::t('email') != $user->forlifeEmail()) {
507 $to_update['email'] = Post::t('email');
508 $listClient->change_user_email($user->forlifeEmail(), Post::t('email'));
509 }
510 }
511 if (!empty($to_update)) {
512 $res = XDB::query('SELECT *
513 FROM accounts
514 WHERE uid = {?}', $user->id());
515 $oldValues = $res->fetchAllAssoc();
516 $oldValues = $oldValues[0];
517
518 $set = array();
519 $diff = array();
520 foreach ($to_update as $k => $value) {
521 $value = XDB::format('{?}', $value);
522 $set[] = $k . ' = ' . $value;
523 $diff[$k] = array($oldValues[$k], trim($value, "'"));
524 unset($oldValues[$k]);
525 }
526 XDB::rawExecute('UPDATE accounts
527 SET ' . implode(', ', $set) . '
528 WHERE uid = ' . XDB::format('{?}', $user->id()));
529 $page->trigSuccess('Données du compte mise à jour avec succès');
530 $user = User::getWithUID($user->id());
531
532 /* Formats the $diff and send it to the site administrators. The rules are the folowing:
533 * -formats: password, token, weak_password
534 */
535 foreach (array('password', 'token', 'weak_password') as $key) {
536 if (isset($diff[$key])) {
537 $diff[$key] = array('old value', 'new value');
538 } else {
539 $oldValues[$key] = 'old value';
540 }
541 }
542
543 $mail = new PlMailer('admin/useredit.mail.tpl');
544 $mail->assign('admin', S::user()->hruid);
545 $mail->assign('hruid', $user->hruid);
546 $mail->assign('diff', $diff);
547 $mail->assign('oldValues', $oldValues);
548 $mail->send();
549 }
550 // }}}
551
552 // Profile form {{{
553 if (Post::has('add_profile') || Post::has('del_profile') || Post::has('owner')) {
554 if (Post::i('del_profile', 0) != 0) {
555 XDB::execute('DELETE FROM account_profiles
556 WHERE uid = {?} AND pid = {?}',
557 $user->id(), Post::i('del_profile'));
558 } else if (!Post::blank('new_profile')) {
559 $profile = Profile::get(Post::t('new_profile'));
560 if (!$profile) {
561 $page->trigError('Le profil ' . Post::t('new_profile') . ' n\'existe pas');
562 } else {
563 XDB::execute('INSERT IGNORE INTO account_profiles (uid, pid)
564 VALUES ({?}, {?})',
565 $user->id(), $profile->id());
566 }
567 }
568 XDB::execute('UPDATE account_profiles
569 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
570 WHERE uid = {?}',
571 Post::i('owner'), $user->id());
572 }
573 // }}}
574
575 // Email forwards form {{{
576 require_once("emails.inc.php");
577 $redirect = ($registered ? new Redirect($user) : null);
578 if (Post::has('add_fwd')) {
579 $email = Post::t('email');
580 if (!isvalid_email_redirection($email)) {
581 $page->trigError("Email non valide: $email");
582 } else {
583 $redirect->add_email($email);
584 $page->trigSuccess("Ajout de $email effectué");
585 }
586 } else if (!Post::blank('del_fwd')) {
587 $redirect->delete_email(Post::t('del_fwd'));
588 } else if (!Post::blank('activate_fwd')) {
589 $redirect->modify_one_email(Post::t('activate_fwd'), true);
590 } else if (!Post::blank('deactivate_fwd')) {
591 $redirect->modify_one_email(Post::t('deactivate_fwd'), false);
592 } else if (Post::has('disable_fwd')) {
593 $redirect->disable();
594 } else if (Post::has('enable_fwd')) {
595 $redirect->enable();
596 } else if (!Post::blank('clean_fwd')) {
597 $redirect->clean_errors(Post::t('clean_fwd'));
598 }
599 // }}}
600
601 // Email alias form {{{
602 if (Post::has('add_alias')) {
603 // Splits new alias in user and fqdn.
604 $alias = Env::t('email');
605 if (strpos($alias, '@') !== false) {
606 list($alias, $domain) = explode('@', $alias);
607 } else {
608 $domain = $user->mainEmailDomain();
609 }
610
611 // Checks for alias' user validity.
612 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
613 $page->trigError("'$alias' n'est pas un alias valide");
614 }
615
616 // Eventually adds the alias to the right domain.
617 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
618 $req = new AliasReq($user, $alias, 'Admin request', false);
619 if ($req->commit()) {
620 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué.");
621 } else {
622 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué.");
623 }
624 } elseif ($domain == $user->mainEmailDomain()) {
625 XDB::execute('INSERT INTO email_source_account (email, uid, domain, type, flags)
626 SELECT {?}, {?}, id, \'alias\', \'\'
627 FROM email_virtual_domains
628 WHERE name = {?}',
629 $alias, $user->id(), $domain);
630 $page->trigSuccess("Nouvel alias '$alias' ajouté");
631 } else {
632 $page->trigError("Le domaine '$domain' n'est pas valide pour cet utilisateur.");
633 }
634 } else if (!Post::blank('del_alias')) {
635 $delete_alias = Post::t('del_alias');
636 list($email, $domain) = explode('@', $delete_alias);
637 XDB::execute('DELETE s
638 FROM email_source_account AS s
639 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
640 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
641 WHERE s.email = {?} AND s.uid = {?} AND d.name = {?} AND type != \'forlife\'',
642 $email, $user->id(), $domain);
643 XDB::execute('UPDATE email_redirect_account AS r
644 INNER JOIN email_virtual_domains AS m ON (m.name = {?})
645 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
646 SET r.rewrite = \'\'
647 WHERE r.uid = {?} AND r.rewrite = CONCAT({?}, \'@\', d.name)',
648 $domain, $user->id(), $email);
649 fix_bestalias($user);
650 $page->trigSuccess("L'alias '$delete_alias' a été supprimé");
651 } else if (!Post::blank('best')) {
652 $best_alias = Post::t('best');
653 // First delete the bestalias flag from all this user's emails.
654 XDB::execute("UPDATE email_source_account
655 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
656 WHERE uid = {?}", $user->id());
657 // Then gives the bestalias flag to the given email.
658 list($email, $domain) = explode('@', $best_alias);
659 XDB::execute("UPDATE email_source_account
660 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
661 WHERE uid = {?} AND email = {?}", $user->id(), $email);
662
663 // As having a non-null bestalias value is critical in
664 // plat/al's code, we do an a posteriori check on the
665 // validity of the bestalias.
666 fix_bestalias($user);
667 }
668 // }}}
669
670 // OpenId form {{{
671 if (Post::has('del_openid')) {
672 XDB::execute('DELETE FROM account_auth_openid
673 WHERE id = {?}', Post::i('del_openid'));
674 }
675 // }}}
676
677 // Forum form {{{
678 if (Post::has('b_edit')) {
679 XDB::execute("DELETE FROM forum_innd
680 WHERE uid = {?}", $user->id());
681 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
682 XDB::execute("INSERT INTO forum_innd
683 SET ipmin = '0', ipmax = '4294967295',
684 write_perm = {?}, read_perm = {?},
685 comment = {?}, priority = '200', uid = {?}",
686 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
687 }
688 }
689 // }}}
690
691
692 $page->addJsLink('jquery.ui.xorg.js');
693
694 // Displays last login and last host information.
695 $res = XDB::query("SELECT start, host
696 FROM log_sessions
697 WHERE uid = {?} AND suid = 0
698 ORDER BY start DESC
699 LIMIT 1", $user->id());
700 list($lastlogin,$host) = $res->fetchOneRow();
701 $page->assign('lastlogin', $lastlogin);
702 $page->assign('host', $host);
703
704 // Display mailing lists
705 $page->assign('mlists', $listClient->get_all_user_lists($user->forlifeEmail()));
706
707 // Display active aliases.
708 $page->assign('virtuals', $user->emailGroupAliases());
709 $aliases = XDB::iterator("SELECT CONCAT(s.email, '@', d.name) AS email, (s.type = 'forlife') AS forlife,
710 (s.email REGEXP '\\\\.[0-9]{2}$') AS hundred_year,
711 FIND_IN_SET('bestalias', s.flags) AS bestalias, s.expire,
712 (s.type = 'alias_aux') AS alias
713 FROM email_source_account AS s
714 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
715 WHERE s.uid = {?}
716 ORDER BY !alias, s.email",
717 $user->id());
718 $page->assign('aliases', $aliases);
719 $page->assign('account_types', XDB::iterator('SELECT * FROM account_types ORDER BY type'));
720 $page->assign('skins', XDB::iterator('SELECT id, name FROM skins ORDER BY name'));
721 $page->assign('profiles', XDB::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
722 FROM account_profiles AS ap
723 INNER JOIN profiles AS p ON (ap.pid = p.pid)
724 WHERE ap.uid = {?}', $user->id()));
725 $page->assign('openid', XDB::iterator('SELECT id, url
726 FROM account_auth_openid
727 WHERE uid = {?}', $user->id()));
728
729 // Displays email redirection and the general profile.
730 if ($registered && $redirect) {
731 $page->assign('emails', $redirect->emails);
732 }
733
734 $page->assign('user', $user);
735 $page->assign('hasProfile', $user->hasProfile());
736
737 // Displays forum bans.
738 $res = XDB::query("SELECT write_perm, read_perm, comment
739 FROM forum_innd
740 WHERE uid = {?}", $user->id());
741 $bans = $res->fetchOneAssoc();
742 $page->assign('bans', $bans);
743 }
744
745 private static function getHrid($firstname, $lastname, $promo)
746 {
747 if ($firstname != null && $lastname != null && $promo != null) {
748 return User::makeHrid($firstname, $lastname, $promo);
749 }
750 return null;
751 }
752
753 private static function formatNewUser($page, $infosLine, $separator, $promo, $size)
754 {
755 $infos = explode($separator, $infosLine);
756 if (sizeof($infos) > $size || sizeof($infos) < 2) {
757 $page->trigError("La ligne $infosLine n'a pas été ajoutée.");
758 return false;
759 }
760
761 $infos = array_map('trim', $infos);
762 $hrid = self::getHrid($infos[1], $infos[0], $promo);
763 $res1 = XDB::query('SELECT COUNT(*)
764 FROM accounts
765 WHERE hruid = {?}', $hrid);
766 $res2 = XDB::query('SELECT COUNT(*)
767 FROM profiles
768 WHERE hrpid = {?}', $hrid);
769 if (is_null($hrid) || $res1->fetchOneCell() > 0 || $res2->fetchOneCell() > 0) {
770 $page->trigError("La ligne $infosLine n'a pas été ajoutée: une entrée similaire existe déjà");
771 return false;
772 }
773 $infos['hrid'] = $hrid;
774 return $infos;
775 }
776
777 private static function formatSex($page, $sex, $line)
778 {
779 switch ($sex) {
780 case 'F':
781 return 'female';
782 case 'M':
783 return 'male';
784 default:
785 $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
786 return null;
787 }
788 }
789
790 private static function formatBirthDate($birthDate)
791 {
792 // strtotime believes dd/mm/yyyy to be an US date (i.e mm/dd/yyyy), and
793 // dd-mm-yyyy to be a normal date (i.e dd-mm-yyyy)...
794 return date("Y-m-d", strtotime(str_replace('/', '-', $birthDate)));
795 }
796
797 function handler_add_accounts($page, $action = null, $promo = null)
798 {
799 $page->changeTpl('admin/add_accounts.tpl');
800
801 if (Env::has('add_type') && Env::has('people')) {
802 $lines = explode("\n", Env::t('people'));
803 $separator = Env::t('separator');
804 $promotion = Env::i('promotion');
805 $nameTypes = DirEnum::getOptions(DirEnum::NAMETYPES);
806 $nameTypes = array_flip($nameTypes);
807
808 if (Env::t('add_type') == 'promo') {
809 $eduSchools = DirEnum::getOptions(DirEnum::EDUSCHOOLS);
810 $eduSchools = array_flip($eduSchools);
811 $eduDegrees = DirEnum::getOptions(DirEnum::EDUDEGREES);
812 $eduDegrees = array_flip($eduDegrees);
813 switch (Env::t('edu_type')) {
814 case 'X':
815 $degreeid = $eduDegrees[Profile::DEGREE_X];
816 $entry_year = $promotion;
817 $grad_year = $promotion + 3;
818 $promo = 'X' . $promotion;
819 $hrpromo = $promotion;
820 $type = 'x';
821 break;
822 case 'M':
823 $degreeid = $eduDegrees[Profile::DEGREE_M];
824 $grad_year = $promotion;
825 $entry_year = $promotion - 2;
826 $promo = 'M' . $promotion;
827 $hrpromo = $promo;
828 $type = 'master';
829 break;
830 case 'D':
831 $degreeid = $eduDegrees[Profile::DEGREE_D];
832 $grad_year = $promotion;
833 $entry_year = $promotion - 3;
834 $promo = 'D' . $promotion;
835 $hrpromo = $promo;
836 $type = 'phd';
837 break;
838 default:
839 $page->killError("La formation n'est pas reconnue:" . Env::t('edu_type') . '.');
840 }
841
842 XDB::startTransaction();
843 foreach ($lines as $line) {
844 if ($infos = self::formatNewUser($page, $line, $separator, $hrpromo, 6)) {
845 $sex = self::formatSex($page, $infos[3], $line);
846 if (!is_null($sex)) {
847 $fullName = $infos[1] . ' ' . $infos[0];
848 $directoryName = $infos[0] . ' ' . $infos[1];
849 $birthDate = self::formatBirthDate($infos[2]);
850 if ($type == 'x') {
851 $xorgId = Profile::getXorgId($infos[4]);
852 } elseif (isset($infos[4])) {
853 $xorgId = trim($infos[4]);
854 } else {
855 $xorgId = 0;
856 }
857 if (is_null($xorgId)) {
858 $page->trigError("La ligne $line n'a pas été ajoutée car le matricule École est mal renseigné.");
859 continue;
860 }
861
862 XDB::execute('INSERT INTO profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex)
863 VALUES ({?}, {?}, {?}, {?}, {?})',
864 $infos['hrid'], $xorgId, (isset($infos[5]) ? $infos[5] : null), $birthDate, $sex);
865 $pid = XDB::insertId();
866 XDB::execute('INSERT INTO profile_name (pid, name, typeid)
867 VALUES ({?}, {?}, {?}),
868 ({?}, {?}, {?}),
869 ({?}, {?}, {?}),
870 ({?}, {?}, {?})',
871 $pid, $infos[0], $nameTypes['name_ini'],
872 $pid, $infos[0], $nameTypes['lastname'],
873 $pid, $infos[1], $nameTypes['firstname_ini'],
874 $pid, $infos[1], $nameTypes['firstname']);
875 XDB::execute('INSERT INTO profile_display (pid, yourself, public_name, private_name,
876 directory_name, short_name, sort_name, promo)
877 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
878 $pid, $infos[1], $fullName, $fullName, $directoryName, $fullName, $directoryName, $promo);
879 XDB::execute('INSERT INTO profile_education (id, pid, eduid, degreeid, entry_year, grad_year, flags)
880 VALUES (100, {?}, {?}, {?}, {?}, {?}, \'primary\')',
881 $pid, $eduSchools[Profile::EDU_X], $degreeid, $entry_year, $grad_year);
882 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, full_name, directory_name, display_name, sex)
883 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
884 $infos['hrid'], $type, 0, 'pending', $fullName, $directoryName, $infos[1], $sex);
885 $uid = XDB::insertId();
886 XDB::execute('INSERT INTO account_profiles (uid, pid, perms)
887 VALUES ({?}, {?}, {?})',
888 $uid, $pid, 'owner');
889 Profile::rebuildSearchTokens($pid, false);
890 }
891 }
892 }
893 XDB::commit();
894 } else if (Env::t('add_type') == 'account') {
895 $type = Env::t('type');
896 $newAccounts = array();
897 foreach ($lines as $line) {
898 if ($infos = self::formatNewUser($page, $line, $separator, $type, 4)) {
899 $sex = self::formatSex($page, $infos[3], $line);
900 if (!is_null($sex)) {
901 $fullName = $infos[1] . ' ' . $infos[0];
902 $directoryName = $infos[0] . ' ' . $infos[1];
903 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state,
904 email, full_name, directory_name,
905 display_name, sex)
906 VALUES ({?}, {?}, {?}, {?},
907 {?}, {?}, {?}, {?}, {?})',
908 $infos['hrid'], $type, 0, 'pending',
909 $infos[2], $fullName, $directoryName,
910 $infos[1], $sex);
911 $newAccounts[$infos['hrid']] = $infos[1] . ' ' . $infos[0];
912 }
913 }
914 }
915 if (!empty($newAccounts)) {
916 $page->assign('newAccounts', $newAccounts);
917 }
918 } else if (Env::t('add_type') == 'ax_id') {
919 $type = 'x';
920 foreach ($lines as $line) {
921 if ($infos = self::formatNewUser($page, $line, $separator, $promotion, 3)) {
922 XDB::execute('UPDATE profiles
923 SET ax_id = {?}
924 WHERE hrpid = {?}',
925 $infos[2], $infos['hrid']);
926 }
927 }
928 }
929
930 $errors = $page->nb_errs();
931 if ($errors == 0) {
932 $page->trigSuccess("L'opération a été effectuée avec succès.");
933 } else {
934 $page->trigSuccess('L\'opération a été effectuée avec succès, sauf pour '
935 . (($errors == 1) ? 'l\'erreur signalée' : "les $errors erreurs signalées") . ' ci-dessus.');
936 }
937 } else if (Env::has('add_type')) {
938 $res = XDB::query('SELECT type
939 FROM account_types');
940 $page->assign('account_types', $res->fetchColumn());
941 $page->assign('add_type', Env::s('add_type'));
942 }
943 }
944
945 function handler_homonyms($page, $op = 'list', $target = null)
946 {
947 $page->changeTpl('admin/homonymes.tpl');
948 $page->setTitle('Administration - Homonymes');
949 $this->load("homonyms.inc.php");
950
951 if ($target) {
952 $user = User::getSilentWithUID($target);
953 if (!$user || !($loginbis = select_if_homonym($user))) {
954 $target = 0;
955 } else {
956 $page->assign('user', $user);
957 $page->assign('loginbis',$loginbis);
958 }
959 }
960
961 $page->assign('op', $op);
962 $page->assign('target', $target);
963
964 // When we have a valid target, prepare emails.
965 if ($target) {
966 require_once 'emails.inc.php';
967 // Examine what operation needs to be performed.
968 switch ($op) {
969 case 'mail':
970 S::assert_xsrf_token();
971
972 send_warning_homonyme($user, $loginbis);
973 fix_bestalias($user);
974 $op = 'list';
975 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
976 break;
977
978 case 'correct':
979 S::assert_xsrf_token();
980
981 XDB::execute('DELETE FROM email_source_account
982 WHERE email = {?} AND type = \'alias\'',
983 $loginbis);
984 XDB::execute('INSERT INTO email_source_other (hrmid, email, domain, type, expire)
985 SELECT {?}, {?}, id, \'homonym\', NOW()
986 FROM email_virtual_domains
987 WHERE name = {?}',
988 User::makeHomonymHrmid($loginbis), $loginbis, $user->mainEmailDomain());
989 fix_bestalias($user);
990 send_robot_homonyme($user, $loginbis);
991 $op = 'list';
992 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
993 break;
994 }
995 }
996
997 if ($op == 'list') {
998 // Retrieves homonyms that are already been fixed.
999 $res = XDB::iterator('SELECT o.email AS homonym, f.email AS forlife, o.expire, f.uid
1000 FROM email_source_other AS o
1001 INNER JOIN homonyms_list AS h ON (o.hrmid = h.hrmid)
1002 INNER JOIN email_source_account AS f ON (h.uid = f.uid AND f.type = \'forlife\')
1003 WHERE o.expire IS NOT NULL
1004 ORDER BY homonym, forlife');
1005 $homonyms = array();
1006 while ($item = $res->next()) {
1007 $homonyms[$item['homonym']][] = $item;
1008 }
1009 $page->assign_by_ref('homonyms', $homonyms);
1010
1011 // Retrieves homonyms that needs to be fixed.
1012 $res = XDB::iterator('SELECT e.email AS homonym, f.email AS forlife, e.expire, e.uid, (e.expire < NOW()) AS urgent
1013 FROM email_source_account AS e
1014 INNER JOIN homonyms_list AS l ON (e.uid = l.uid)
1015 INNER JOIN homonyms_list AS h ON (l.hrmid = h.hrmid)
1016 INNER JOIN email_source_account AS f ON (h.uid = f.uid AND f.type = \'forlife\')
1017 WHERE e.expire IS NOT NULL
1018 ORDER BY homonym, forlife');
1019 $homonyms_to_fix = array();
1020 while ($item = $res->next()) {
1021 $homonyms_to_fix[$item['homonym']][] = $item;
1022 }
1023 $page->assign_by_ref('homonyms_to_fix', $homonyms_to_fix);
1024 }
1025 }
1026
1027 function handler_deaths($page, $promo = 0, $validate = false)
1028 {
1029 $page->changeTpl('admin/deces_promo.tpl');
1030 $page->setTitle('Administration - Deces');
1031
1032 if (!$promo) {
1033 $promo = Env::t('promo', 'X1923');
1034 }
1035 $page->assign('promo', $promo);
1036 if (!$promo) {
1037 return;
1038 }
1039
1040 if ($validate) {
1041 S::assert_xsrf_token();
1042
1043 $res = XDB::iterRow('SELECT p.pid, pd.directory_name, p.deathdate
1044 FROM profiles AS p
1045 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1046 WHERE pd.promo = {?}', $promo);
1047 while (list($pid, $name, $death) = $res->next()) {
1048 $val = Env::v('death_' . $pid);
1049 if ($val == $death) {
1050 continue;
1051 }
1052
1053 if (empty($val)) {
1054 $val = null;
1055 }
1056 XDB::execute('UPDATE profiles
1057 SET deathdate = {?}, deathdate_rec = NOW()
1058 WHERE pid = {?}', $val, $pid);
1059
1060 $page->trigSuccess('Édition du décès de ' . $name . ' (' . ($val ? $val : 'ressuscité') . ').');
1061 if ($val && ($death == '0000-00-00' || empty($death))) {
1062 $profile = Profile::get($pid);
1063 $profile->clear();
1064 $profile->owner()->clear(false);
1065 }
1066 }
1067 }
1068
1069 $res = XDB::iterator('SELECT p.pid, pd.directory_name, p.deathdate
1070 FROM profiles AS p
1071 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1072 WHERE pd.promo = {?}
1073 ORDER BY pd.sort_name', $promo);
1074 $page->assign('profileList', $res);
1075 }
1076
1077 function handler_dead_but_active($page)
1078 {
1079 $page->changeTpl('admin/dead_but_active.tpl');
1080 $page->setTitle('Administration - Décédés');
1081
1082 $res = XDB::iterator(
1083 "SELECT a.hruid, pd.promo, p.ax_id, pd.directory_name, p.deathdate, DATE(MAX(s.start)) AS last
1084 FROM accounts AS a
1085 INNER JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET('owner', ap.perms))
1086 INNER JOIN profiles AS p ON (p.pid = ap.pid)
1087 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
1088 LEFT JOIN log_sessions AS s ON (s.uid = a.uid AND suid = 0)
1089 WHERE a.state = 'active' AND p.deathdate IS NOT NULL
1090 GROUP BY a.uid
1091 ORDER BY pd.promo, pd.sort_name");
1092 $page->assign('dead', $res);
1093 }
1094
1095 function handler_validate($page, $action = 'list', $id = null)
1096 {
1097 $page->changeTpl('admin/validation.tpl');
1098 $page->setTitle('Administration - Valider une demande');
1099 $page->addCssLink('nl.Polytechnique.org.css');
1100
1101 if ($action == 'edit' && !is_null($id)) {
1102 $page->assign('preview_id', $id);
1103 } else {
1104 $page->assign('preview_id', null);
1105 }
1106
1107 if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
1108 S::assert_xsrf_token();
1109
1110 $req = Validate::get_typed_request(Env::v('uid'), Env::v('type'), Env::v('stamp'));
1111 if ($req) {
1112 $req->handle_formu();
1113 } else {
1114 $page->trigWarning('La validation a déjà été effectuée.');
1115 }
1116 }
1117
1118 $r = XDB::iterator('SHOW COLUMNS FROM requests_answers');
1119 while (($a = $r->next()) && $a['Field'] != 'category');
1120 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
1121
1122 $hidden = array();
1123 $res = XDB::query('SELECT hidden_requests
1124 FROM requests_hidden
1125 WHERE uid = {?}', S::v('uid'));
1126 $hide_requests = $res->fetchOneCell();
1127 if (Post::has('hide')) {
1128 $hide = array();
1129 foreach ($categories as $cat)
1130 if (!Post::v($cat)) {
1131 $hidden[$cat] = 1;
1132 $hide[] = $cat;
1133 }
1134 $hide_requests = join(',', $hide);
1135 XDB::query('INSERT INTO requests_hidden (uid, hidden_requests)
1136 VALUES ({?}, {?})
1137 ON DUPLICATE KEY UPDATE hidden_requests = VALUES(hidden_requests)',
1138 S::v('uid'), $hide_requests);
1139 } elseif ($hide_requests) {
1140 foreach (explode(',', $hide_requests) as $hide_type)
1141 $hidden[$hide_type] = true;
1142 }
1143 $page->assign('hide_requests', $hidden);
1144
1145 // Update the count of item to validate here... useful in development configuration
1146 // where several copies of the site use the same DB, but not the same "dynamic configuration"
1147 global $globals;
1148 $globals->updateNbValid();
1149 $page->assign('vit', Validate::iterate());
1150 $page->assign('isAdmin', S::admin());
1151 }
1152
1153 function handler_validate_answers($page, $action = 'list', $id = null)
1154 {
1155 $page->setTitle('Administration - Réponses automatiques de validation');
1156 $page->assign('title', 'Gestion des réponses automatiques');
1157 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
1158 $table_editor->describe('category','catégorie',true);
1159 $table_editor->describe('title','titre',true);
1160 $table_editor->describe('answer','texte',false);
1161 $table_editor->apply($page, $action, $id);
1162 }
1163
1164 function handler_skins($page, $action = 'list', $id = null)
1165 {
1166 $page->setTitle('Administration - Skins');
1167 $page->assign('title', 'Gestion des skins');
1168 $table_editor = new PLTableEditor('admin/skins','skins','id');
1169 $table_editor->describe('name','nom',true);
1170 $table_editor->describe('skin_tpl','nom du template',true);
1171 $table_editor->describe('auteur','auteur',false);
1172 $table_editor->describe('comment','commentaire',true);
1173 $table_editor->describe('date','date',false);
1174 $table_editor->describe('ext','extension du screenshot',false);
1175 $table_editor->apply($page, $action, $id);
1176 }
1177
1178 function handler_postfix_blacklist($page, $action = 'list', $id = null)
1179 {
1180 $page->setTitle('Administration - Postfix : Blacklist');
1181 $page->assign('title', 'Blacklist de postfix');
1182 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true);
1183 $table_editor->describe('reject_text','Texte de rejet',true);
1184 $table_editor->describe('email','email',true);
1185 $table_editor->apply($page, $action, $id);
1186 }
1187
1188 function handler_postfix_whitelist($page, $action = 'list', $id = null)
1189 {
1190 $page->setTitle('Administration - Postfix : Whitelist');
1191 $page->assign('title', 'Whitelist de postfix');
1192 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true);
1193 $table_editor->describe('email','email',true);
1194 $table_editor->apply($page, $action, $id);
1195 }
1196
1197 function handler_mx_broken($page, $action = 'list', $id = null)
1198 {
1199 $page->setTitle('Administration - MX Défaillants');
1200 $page->assign('title', 'MX Défaillant');
1201 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true);
1202 $table_editor->describe('host', 'Masque', true);
1203 $table_editor->describe('state', 'Niveau', true);
1204 $table_editor->describe('text', 'Description du problème', false);
1205 $table_editor->apply($page, $action, $id);
1206 }
1207
1208 function handler_logger_actions($page, $action = 'list', $id = null)
1209 {
1210 $page->setTitle('Administration - Actions');
1211 $page->assign('title', 'Gestion des actions de logger');
1212 $table_editor = new PLTableEditor('admin/logger/actions','log_actions','id');
1213 $table_editor->describe('text','intitulé',true);
1214 $table_editor->describe('description','description',true);
1215 $table_editor->apply($page, $action, $id);
1216 }
1217
1218 function handler_downtime($page, $action = 'list', $id = null)
1219 {
1220 $page->setTitle('Administration - Coupures');
1221 $page->assign('title', 'Gestion des coupures');
1222 $table_editor = new PLTableEditor('admin/downtime','downtimes','id');
1223 $table_editor->describe('debut','date',true);
1224 $table_editor->describe('duree','durée',false);
1225 $table_editor->describe('resume','résumé',true);
1226 $table_editor->describe('services','services affectés',true);
1227 $table_editor->describe('description','description',false);
1228 $table_editor->apply($page, $action, $id);
1229 }
1230
1231 private static function isCountryIncomplete(array &$item)
1232 {
1233 $warning = false;
1234 foreach (array('worldRegion', 'country', 'capital', 'phonePrefix', 'licensePlate', 'countryPlain') as $field) {
1235 if ($item[$field] == '') {
1236 $item[$field . '_warning'] = true;
1237 $warning = true;
1238 }
1239 }
1240 if (is_null($item['belongsTo'])) {
1241 foreach (array('nationality', 'nationalityEn') as $field) {
1242 if ($item[$field] == '') {
1243 $item[$field . '_warning'] = true;
1244 $warning = true;
1245 }
1246 }
1247 }
1248 return $warning;
1249 }
1250
1251 private static function updateCountry(array $item)
1252 {
1253 XDB::execute('UPDATE geoloc_countries
1254 SET countryPlain = {?}
1255 WHERE iso_3166_1_a2 = {?}',
1256 mb_strtoupper(replace_accent($item['country'])), $item['iso_3166_1_a2']);
1257 }
1258
1259 private static function isLanguageIncomplete(array &$item)
1260 {
1261 if ($item['language'] == '') {
1262 $item['language_warning'] = true;
1263 return true;
1264 }
1265 return false;
1266 }
1267
1268 private static function updateLanguage(array $item) {}
1269
1270 function handler_geocoding($page, $category = null, $action = null, $id = null)
1271 {
1272 // Warning, this handler requires the following packages:
1273 // * pkg-isocodes
1274 // * isoquery
1275
1276 static $properties = array(
1277 'country' => array(
1278 'name' => 'pays',
1279 'isocode' => '3166',
1280 'table' => 'geoloc_countries',
1281 'id' => 'iso_3166_1_a2',
1282 'main_fields' => array('iso_3166_1_a3', 'iso_3166_1_num', 'countryEn'),
1283 'other_fields' => array('worldRegion', 'country', 'capital', 'nationality', 'nationalityEn',
1284 'phonePrefix', 'phoneFormat', 'licensePlate', 'belongsTo')
1285 ),
1286 'language' => array(
1287 'name' => 'langages',
1288 'isocode' => '639',
1289 'table' => 'profile_langskill_enum',
1290 'id' => 'iso_639_2b',
1291 'main_fields' => array('iso_639_2t', 'iso_639_1', 'language_en'),
1292 'other_fields' => array('language')
1293
1294 )
1295 );
1296
1297 if (is_null($category) || !array_key_exists($category, $properties)) {
1298 pl_redirect('admin');
1299 }
1300
1301 $data = $properties[$category];
1302
1303 if ($action == 'edit' || $action == 'add') {
1304 $main_fields = array_merge(array($data['id']), $data['main_fields']);
1305 $all_fields = array_merge($main_fields, $data['other_fields']);
1306
1307 if (is_null($id)) {
1308 if (Post::has('new_id')) {
1309 $id = Post::v('new_id');
1310 } else {
1311 pl_redirect('admin/geocoding/' . $category);
1312 }
1313 }
1314
1315 $list = array();
1316 exec('isoquery --iso=' . $data['isocode'] . ' ' . $id, $list);
1317 if (count($list) == 1) {
1318 $array = explode("\t", $list[0]);
1319 foreach ($main_fields as $i => $field) {
1320 $iso[$field] = $array[$i];
1321 }
1322 } else {
1323 $iso = array();
1324 }
1325
1326 if ($action == 'add') {
1327 if (Post::has('new_id')) {
1328 S::assert_xsrf_token();
1329 }
1330
1331 if (count($iso)) {
1332 $item = $iso;
1333 } else {
1334 $item = array($data['id'] => $id);
1335 }
1336 XDB::execute('INSERT INTO ' . $data['table'] . '(' . implode(', ', array_keys($item)) . ')
1337 VALUES ' . XDB::formatArray($item));
1338 $page->trigSuccess($id . ' a bien été ajouté à la base.');
1339 } elseif ($action == 'edit') {
1340 if (Post::has('edit')) {
1341 S::assert_xsrf_token();
1342
1343 $item = array();
1344 $set = array();
1345 foreach ($all_fields as $field) {
1346 $item[$field] = Post::t($field);
1347 $set[] = $field . XDB::format(' = {?}', ($item[$field] ? $item[$field] : null));
1348 }
1349 XDB::execute('UPDATE ' . $data['table'] . '
1350 SET ' . implode(', ', $set) . '
1351 WHERE ' . $data['id'] . ' = {?}',
1352 $id);
1353 call_user_func_array(array('self', 'update' . ucfirst($category)), array($item));
1354 $page->trigSuccess($id . ' a bien été mis à jour.');
1355 } elseif (Post::has('del')) {
1356 S::assert_xsrf_token();
1357
1358 XDB::execute('DELETE FROM ' . $data['table'] . '
1359 WHERE ' . $data['id'] . ' = {?}',
1360 $id);
1361 $page->trigSuccessRedirect($id . ' a bien été supprimé.', 'admin/geocoding/' . $category);
1362 } else {
1363 $item = XDB::fetchOneAssoc('SELECT *
1364 FROM ' . $data['table'] . '
1365 WHERE ' . $data['id'] . ' = {?}',
1366 $id);
1367 }
1368 }
1369
1370 $page->changeTpl('admin/geocoding_edit.tpl');
1371 $page->setTitle('Administration - ' . ucfirst($data['name']));
1372 $page->assign('category', $category);
1373 $page->assign('name', $data['name']);
1374 $page->assign('all_fields', $all_fields);
1375 $page->assign('id', $id);
1376 $page->assign('iso', $iso);
1377 $page->assign('item', $item);
1378 return;
1379 }
1380
1381 $page->changeTpl('admin/geocoding.tpl');
1382 $page->setTitle('Administration - ' . ucfirst($data['name']));
1383 $page->assign('category', $category);
1384 $page->assign('name', $data['name']);
1385 $page->assign('id', $data['id']);
1386 $page->assign('main_fields', $data['main_fields']);
1387 $page->assign('all_fields', array_merge($data['main_fields'], $data['other_fields']));
1388
1389 // First build the list provided by the iso codes.
1390 $list = array();
1391 exec('isoquery --iso=' . $data['isocode'], $list);
1392
1393 foreach ($list as $key => $item) {
1394 $array = explode("\t", $item);
1395 unset($list[$key]);
1396 $list[$array[0]] = array();
1397 foreach ($data['main_fields'] as $i => $field) {
1398 $list[$array[0]][$field] = $array[$i + 1];
1399 }
1400 }
1401 ksort($list);
1402
1403 // Retrieve all data from the database.
1404 $db_list = XDB::rawFetchAllAssoc('SELECT *
1405 FROM ' . $data['table'] . '
1406 ORDER BY ' . $data['id'],
1407 $data['id']);
1408
1409 // Sort both iso and database data into 5 categories:
1410 // $missing: data from the iso list not in the database,
1411 // $non_existing: data from the database not in the iso list,
1412 // $erroneous: data that differ on main fields,
1413 // $incomplete: data with empty fields in the data base,
1414 // $remaining: remaining correct and complete data from the database.
1415
1416 $missing = $non_existing = $erroneous = $incomplete = $remaining = array();
1417 foreach (array_keys($list) as $id) {
1418 if (!array_key_exists($id, $db_list)) {
1419 $missing[$id] = $list[$id];
1420 }
1421 }
1422
1423 foreach ($db_list as $id => $item) {
1424 if (!array_key_exists($id, $list)) {
1425 $non_existing[$id] = $item;
1426 } else {
1427 $error = false;
1428 foreach ($data['main_fields'] as $field) {
1429 if ($item[$field] != $list[$id][$field]) {
1430 $item[$field . '_error'] = true;
1431 $error = true;
1432 }
1433 }
1434 if ($error == true) {
1435 $erroneous[$id] = $item;
1436 } elseif (call_user_func_array(array('self', 'is' . ucfirst($category) . 'Incomplete'), array(&$item))) {
1437 $incomplete[$id] = $item;
1438 } else {
1439 $remaining[$id] = $item;
1440 }
1441 }
1442 }
1443
1444 $page->assign('lists', array(
1445 'manquant' => $missing,
1446 'disparu' => $non_existing,
1447 'erroné' => $erroneous,
1448 'incomplet' => $incomplete,
1449 'restant' => $remaining
1450 ));
1451 }
1452
1453 function handler_accounts(PlPage $page)
1454 {
1455 $page->changeTpl('admin/accounts.tpl');
1456 $page->setTitle('Administration - Comptes');
1457
1458 if (Post::has('create_account')) {
1459 S::assert_xsrf_token();
1460 $firstname = Post::t('firstname');
1461 $lastname = strtoupper(Post::t('lastname'));
1462 $sex = Post::s('sex');
1463 $email = Post::t('email');
1464 $type = Post::s('type');
1465 $login = PlUser::makeHrid($firstname, $lastname, $type);
1466 if (!isvalid_email($email)) {
1467 $page->trigError("Invalid email address: $email");
1468 } else if (strlen(Post::s('pwhash')) != 40) {
1469 $page->trigError("Invalid password hash");
1470 } else {
1471 $full_name = $firstname . ' ' . $lastname;
1472 $directory_name = $lastname . ' ' . $firstname;
1473 XDB::execute("INSERT INTO accounts (hruid, type, state, password,
1474 registration_date, email, full_name,
1475 display_name, sex, directory_name)
1476 VALUES ({?}, {?}, 'active', {?}, NOW(), {?}, {?}, {?}, {?}, {?})",
1477 $login, $type, Post::s('pwhash'), $email, $full_name, $full_name, $sex,
1478 $directory_name);
1479 }
1480 }
1481
1482 $uf = new UserFilter(new UFC_AccountType('ax', 'school', 'fx'));
1483 $page->assign('users', $uf->iterUsers());
1484
1485 }
1486
1487 function handler_account_types($page, $action = 'list', $id = null)
1488 {
1489 $page->setTitle('Administration - Types de comptes');
1490 $page->assign('title', 'Gestion des types de comptes');
1491 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true);
1492 $table_editor->describe('type', 'Catégorie', true);
1493 $table_editor->describe('perms', 'Permissions associées', true);
1494 $table_editor->apply($page, $action, $id);
1495 }
1496
1497 function handler_wiki($page, $action = 'list', $wikipage = null, $wikipage2 = null)
1498 {
1499 if (S::hasAuthToken()) {
1500 $page->setRssLink('Changement Récents',
1501 '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::user()->token);
1502 }
1503
1504 // update wiki perms
1505 if ($action == 'update') {
1506 S::assert_xsrf_token();
1507
1508 $perms_read = Post::v('read');
1509 $perms_edit = Post::v('edit');
1510 if ($perms_read || $perms_edit) {
1511 foreach ($_POST as $wiki_page => $val) {
1512 if ($val == 'on') {
1513 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1514 if ($wp->setPerms($perms_read ? $perms_read : $wp->readPerms(),
1515 $perms_edit ? $perms_edit : $wp->writePerms())) {
1516 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1517 } else {
1518 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1519 }
1520 }
1521 }
1522 }
1523 } else if ($action != 'list' && !empty($wikipage)) {
1524 $wp = new PlWikiPage($wikipage);
1525 S::assert_xsrf_token();
1526
1527 if ($action == 'delete') {
1528 if ($wp->delete()) {
1529 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1530 } else {
1531 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1532 }
1533 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1534 if ($changedLinks = $wp->rename($wikipage2)) {
1535 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1536 if (is_numeric($changedLinks)) {
1537 $s .= $changedLinks.' lien'.(($changedLinks>1)?'s ont été modifiés.':' a été modifié.');
1538 }
1539 $page->trigSuccess($s);
1540 } else {
1541 $page->trigError("Impossible de déplacer la page ".$wikipage);
1542 }
1543 }
1544 }
1545
1546 $perms = PlWikiPage::permOptions();
1547
1548 // list wiki pages and their perms
1549 $wiki_pages = PlWikiPage::listPages();
1550 ksort($wiki_pages);
1551 $wiki_tree = array();
1552 foreach ($wiki_pages as $file => $desc) {
1553 list($cat, $name) = explode('.', $file);
1554 if (!isset($wiki_tree[$cat])) {
1555 $wiki_tree[$cat] = array();
1556 }
1557 $wiki_tree[$cat][$name] = $desc;
1558 }
1559
1560 $page->changeTpl('admin/wiki.tpl');
1561 $page->assign('wiki_pages', $wiki_tree);
1562 $page->assign('perms_opts', $perms);
1563 }
1564
1565 function handler_ipwatch($page, $action = 'list', $ip = null)
1566 {
1567 $page->changeTpl('admin/ipwatcher.tpl');
1568
1569 $states = array('safe' => 'Ne pas surveiller',
1570 'unsafe' => 'Surveiller les inscriptions',
1571 'dangerous' => 'Surveiller tous les accès',
1572 'ban' => 'Bannir cette adresse');
1573 $page->assign('states', $states);
1574
1575 switch (Post::v('action')) {
1576 case 'create':
1577 if (trim(Post::v('ipN')) != '') {
1578 S::assert_xsrf_token();
1579 Xdb::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1580 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1581 ip_to_uint(trim(Post::v('ipN'))), ip_to_uint(trim(Post::v('maskN'))),
1582 Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
1583 };
1584 break;
1585
1586 case 'edit':
1587 S::assert_xsrf_token();
1588 Xdb::execute('UPDATE ip_watch
1589 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1590 WHERE ip = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'),
1591 ip_to_uint(Post::v('maskN')), ip_to_uint(Post::v('ipN')));
1592 break;
1593
1594 default:
1595 if ($action == 'delete' && !is_null($ip)) {
1596 S::assert_xsrf_token();
1597 Xdb::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1598 }
1599 }
1600 if ($action != 'create' && $action != 'edit') {
1601 $action = 'list';
1602 }
1603 $page->assign('action', $action);
1604
1605 if ($action == 'list') {
1606 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1607 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1608 IF(w.ip = s.ip, s.host, s.forward_host)),
1609 w.mask, w.detection, w.state, a.hruid
1610 FROM ip_watch AS w
1611 LEFT JOIN log_sessions AS s ON (s.ip = w.ip)
1612 LEFT JOIN log_sessions AS s2 ON (s2.forward_ip = w.ip)
1613 LEFT JOIN accounts AS a ON (a.uid = s.uid)
1614 GROUP BY w.ip, a.hruid
1615 ORDER BY w.state, w.ip, a.hruid";
1616 $it = Xdb::iterRow($sql);
1617
1618 $table = array();
1619 $props = array();
1620 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1621 $ip = uint_to_ip($ip);
1622 $mask = uint_to_ip($mask);
1623 if (count($props) == 0 || $props['ip'] != $ip) {
1624 if (count($props) > 0) {
1625 $table[] = $props;
1626 }
1627 $props = array('ip' => $ip,
1628 'mask' => $mask,
1629 'host' => $host,
1630 'detection' => $date,
1631 'state' => $state,
1632 'users' => array($hruid));
1633 } else {
1634 $props['users'][] = $hruid;
1635 }
1636 }
1637 if (count($props) > 0) {
1638 $table[] = $props;
1639 }
1640 $page->assign('table', $table);
1641 } elseif ($action == 'edit') {
1642 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1643 a1.hruid AS edit, a2.hruid AS hruid, s.host
1644 FROM ip_watch AS w
1645 LEFT JOIN accounts AS a1 ON (a1.uid = w.uid)
1646 LEFT JOIN log_sessions AS s ON (w.ip = s.ip)
1647 LEFT JOIN accounts AS a2 ON (a2.uid = s.uid)
1648 WHERE w.ip = {?}
1649 GROUP BY a2.hruid
1650 ORDER BY a2.hruid";
1651 $it = Xdb::iterRow($sql, ip_to_uint($ip));
1652
1653 $props = array();
1654 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1655 if (count($props) == 0) {
1656 $props = array('ip' => $ip,
1657 'mask' => uint_to_ip($mask),
1658 'host' => $host,
1659 'detection' => $detection,
1660 'state' => $state,
1661 'last' => $last,
1662 'description' => $description,
1663 'edit' => $edit,
1664 'users' => array($hruid));
1665 } else {
1666 $props['users'][] = $hruid;
1667 }
1668 }
1669 $page->assign('ip', $props);
1670 }
1671 }
1672
1673 function handler_icons($page)
1674 {
1675 $page->changeTpl('admin/icons.tpl');
1676 $dh = opendir('../htdocs/images/icons');
1677 if (!$dh) {
1678 $page->trigError('Dossier des icones introuvables.');
1679 }
1680 $icons = array();
1681 while (($file = readdir($dh)) !== false) {
1682 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1683 array_push($icons, substr($file, 0, -4));
1684 }
1685 }
1686 sort($icons);
1687 $page->assign('icons', $icons);
1688 }
1689
1690 function handler_account_watch($page)
1691 {
1692 $page->changeTpl('admin/accounts.tpl');
1693 $page->assign('disabled', XDB::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1694 a.state = \'disabled\' AS disabled, a.comment
1695 FROM accounts AS a
1696 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1697 ORDER BY a.hruid'));
1698 $page->assign('admins', XDB::iterator('SELECT a.hruid
1699 FROM accounts AS a
1700 WHERE a.is_admin
1701 ORDER BY a.hruid'));
1702 }
1703
1704 function handler_xnet_without_group($page)
1705 {
1706 $page->changeTpl('admin/xnet_without_group.tpl');
1707 $page->assign('accounts', XDB::iterator('SELECT a.hruid, a.state
1708 FROM accounts AS a
1709 LEFT JOIN group_members AS m ON (a.uid = m.uid)
1710 WHERE a.type = \'xnet\' AND m.uid IS NULL
1711 ORDER BY a.state, a.hruid'));
1712 }
1713
1714 function handler_jobs($page, $id = -1)
1715 {
1716 $page->changeTpl('admin/jobs.tpl');
1717
1718 if (Env::has('search')) {
1719 $res = XDB::query("SELECT id, name, acronym
1720 FROM profile_job_enum
1721 WHERE name LIKE CONCAT('%', {?}, '%') OR acronym LIKE CONCAT('%', {?}, '%')",
1722 Env::t('job'), Env::t('job'));
1723
1724 if ($res->numRows() <= 20) {
1725 $page->assign('jobs', $res->fetchAllAssoc());
1726 } else {
1727 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1728 }
1729
1730 $page->assign('askedJob', Env::v('job'));
1731 return;
1732 }
1733
1734 if (Env::has('edit')) {
1735 S::assert_xsrf_token();
1736 $selectedJob = Env::has('selectedJob');
1737
1738 Phone::deletePhones(0, Phone::LINK_COMPANY, $id);
1739 Address::deleteAddresses(null, Address::LINK_COMPANY, $id);
1740 if (Env::has('change')) {
1741 if (Env::has('newJobId') && Env::i('newJobId') > 0) {
1742 XDB::execute('UPDATE profile_job
1743 SET jobid = {?}
1744 WHERE jobid = {?}',
1745 Env::i('newJobId'), $id);
1746 XDB::execute('DELETE FROM profile_job_enum
1747 WHERE id = {?}',
1748 $id);
1749
1750 $page->trigSuccess("L'entreprise a bien été remplacée.");
1751 } else {
1752 $page->trigError("L'entreprise n'a pas été remplacée car l'identifiant fourni n'est pas valide.");
1753 }
1754 } else {
1755 XDB::execute('UPDATE profile_job_enum
1756 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1757 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1758 WHERE id = {?}',
1759 Env::t('name'), Env::t('acronym'), Env::t('url'), Env::t('email'),
1760 (Env::t('NAF_code') == 0 ? null : Env::t('NAF_code')),
1761 (Env::i('AX_code') == 0 ? null : Env::t('AX_code')),
1762 (Env::i('holdingId') == 0 ? null : Env::t('holdingId')), $id);
1763
1764 $phone = new Phone(array('display' => Env::v('tel'), 'link_id' => $id, 'id' => 0, 'type' => 'fixed',
1765 'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
1766 $fax = new Phone(array('display' => Env::v('fax'), 'link_id' => $id, 'id' => 1, 'type' => 'fax',
1767 'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
1768 $address = new Address(array('jobid' => $id, 'type' => Address::LINK_COMPANY, 'text' => Env::t('address')));
1769 $phone->save();
1770 $fax->save();
1771 $address->save();
1772
1773 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1774 }
1775 }
1776
1777 if (!Env::has('change') && $id != -1) {
1778 $res = XDB::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1779 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1780 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1781 FROM profile_job_enum AS e
1782 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
1783 LEFT JOIN profile_phones AS t ON (t.pid = e.id AND t.link_type = 'hq' AND t.tel_id = 0)
1784 LEFT JOIN profile_phones AS f ON (f.pid = e.id AND f.link_type = 'hq' AND f.tel_id = 1)
1785 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1786 WHERE e.id = {?}",
1787 $id);
1788
1789 if ($res->numRows() == 0) {
1790 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1791 } else {
1792 $page->assign('selectedJob', $res->fetchOneAssoc());
1793 }
1794 }
1795 }
1796
1797 function handler_profile($page)
1798 {
1799 $page->changeTpl('admin/profile.tpl');
1800
1801 if (Post::has('checked')) {
1802 S::assert_xsrf_token();
1803 $res = XDB::iterator('SELECT DISTINCT(pm.pid), pd.public_name
1804 FROM profile_modifications AS pm
1805 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1806 WHERE pm.type = \'self\'');
1807
1808 while ($profile = $res->next()) {
1809 if (Post::has('checked_' . $profile['pid'])) {
1810 XDB::execute('DELETE FROM profile_modifications
1811 WHERE type = \'self\' AND pid = {?}', $profile['pid']);
1812
1813 $page->trigSuccess('Profil de ' . $profile['public_name'] . ' vérifié.');
1814 }
1815 }
1816 }
1817
1818 $res = XDB::iterator('SELECT p.hrpid, pm.pid, pd.directory_name, GROUP_CONCAT(pm.field SEPARATOR \', \') AS field
1819 FROM profile_modifications AS pm
1820 INNER JOIN profiles AS p ON (pm.pid = p.pid)
1821 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1822 WHERE pm.type = \'self\'
1823 GROUP BY pd.directory_name
1824 ORDER BY pd.directory_name');
1825 $page->assign('updates', $res);
1826 }
1827 }
1828
1829 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1830 ?>