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