Fixes SQL error.
[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 'admin/phd' => $this->make_hook('phd', AUTH_MDP, 'admin'),
58 'admin/add_secondary_edu' => $this->make_hook('add_secondary_edu', AUTH_MDP, 'admin')
59 );
60 }
61
62 function handler_phpinfo($page)
63 {
64 phpinfo();
65 exit;
66 }
67
68 function handler_get_rights($page)
69 {
70 if (S::suid()) {
71 $page->kill('Déjà en SUID');
72 }
73 S::assert_xsrf_token();
74 $level = Post::s('account_type');
75 if ($level != 'admin') {
76 $user = User::getSilentWithUID(S::user()->id());
77 $user->is_admin = false;
78 $types = DirEnum::getOptions(DirEnum::ACCOUNTTYPES);
79 if (!empty($types[$level])) {
80 $user->setPerms($types[$level]);
81 }
82 S::set('suid_startpage', $_SERVER['HTTP_REFERER']);
83 Platal::session()->startSUID($user);
84 }
85 if (!empty($_SERVER['HTTP_REFERER'])) {
86 http_redirect($_SERVER['HTTP_REFERER']);
87 } else {
88 pl_redirect('/');
89 }
90 }
91
92 function handler_set_skin($page)
93 {
94 S::assert_xsrf_token();
95 S::set('skin', Post::s('change_skin'));
96 if (!empty($_SERVER['HTTP_REFERER'])) {
97 http_redirect($_SERVER['HTTP_REFERER']);
98 } else {
99 pl_redirect('/');
100 }
101 }
102
103 function handler_default($page)
104 {
105 $page->changeTpl('admin/index.tpl');
106 $page->setTitle('Administration');
107 }
108
109 function handler_postfix_delayed($page)
110 {
111 $page->changeTpl('admin/postfix_delayed.tpl');
112 $page->setTitle('Administration - Postfix : Retardés');
113
114 if (Env::has('del')) {
115 $crc = Env::v('crc');
116 XDB::execute("UPDATE postfix_mailseen SET release = 'del' WHERE crc = {?}", $crc);
117 $page->trigSuccess($crc . " verra tous ses emails supprimés&nbsp;!");
118 } elseif (Env::has('ok')) {
119 $crc = Env::v('crc');
120 XDB::execute("UPDATE postfix_mailseen SET release = 'ok' WHERE crc = {?}", $crc);
121 $page->trigSuccess($crc . " a le droit de passer&nbsp;!");
122 }
123
124 $sql = XDB::iterator(
125 "SELECT crc, nb, update_time, create_time,
126 FIND_IN_SET('del', p.release) AS del,
127 FIND_IN_SET('ok', p.release) AS ok
128 FROM postfix_mailseen AS p
129 WHERE nb >= 30
130 ORDER BY p.release != ''");
131
132 $page->assign_by_ref('mails', $sql);
133 }
134
135 // {{{ logger view
136
137 /** Retrieves the available days for a given year and month.
138 * Obtain a list of days of the given month in the given year
139 * that are within the range of dates that we have log entries for.
140 *
141 * @param integer year
142 * @param integer month
143 * @return array days in that month we have log entries covering.
144 * @private
145 */
146 function _getDays($year, $month)
147 {
148 // give a 'no filter' option
149 $days = array();
150 $days[0] = "----";
151
152 if ($year && $month) {
153 $day_max = Array(-1, 31, checkdate(2, 29, $year) ? 29 : 28 , 31,
154 30, 31, 30, 31, 31, 30, 31, 30, 31);
155 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
156 MONTH(MAX(start)), MONTH(MIN(start)),
157 DAYOFMONTH(MAX(start)),
158 DAYOFMONTH(MIN(start))
159 FROM log_sessions");
160 list($ymax, $ymin, $mmax, $mmin, $dmax, $dmin) = $res->fetchOneRow();
161
162 if (($year < $ymin) || ($year == $ymin && $month < $mmin)) {
163 return array();
164 }
165
166 if (($year > $ymax) || ($year == $ymax && $month > $mmax)) {
167 return array();
168 }
169
170 $min = ($year==$ymin && $month==$mmin) ? intval($dmin) : 1;
171 $max = ($year==$ymax && $month==$mmax) ? intval($dmax) : $day_max[$month];
172
173 for($i = $min; $i<=$max; $i++) {
174 $days[$i] = $i;
175 }
176 }
177 return $days;
178 }
179
180
181 /** Retrieves the available months for a given year.
182 * Obtains a list of month numbers that are within the timeframe that
183 * we have log entries for.
184 *
185 * @param integer year
186 * @return array List of month numbers we have log info for.
187 * @private
188 */
189 function _getMonths($year)
190 {
191 // give a 'no filter' option
192 $months = array();
193 $months[0] = "----";
194
195 if ($year) {
196 $res = XDB::query("SELECT YEAR (MAX(start)), YEAR (MIN(start)),
197 MONTH(MAX(start)), MONTH(MIN(start))
198 FROM log_sessions");
199 list($ymax, $ymin, $mmax, $mmin) = $res->fetchOneRow();
200
201 if (($year < $ymin) || ($year > $ymax)) {
202 return array();
203 }
204
205 $min = $year == $ymin ? intval($mmin) : 1;
206 $max = $year == $ymax ? intval($mmax) : 12;
207
208 for($i = $min; $i<=$max; $i++) {
209 $months[$i] = $i;
210 }
211 }
212 return $months;
213 }
214
215
216 /** Retrieves the available years.
217 * Obtains a list of years that we have log entries covering.
218 *
219 * @return array years we have log entries for.
220 * @private
221 */
222 function _getYears()
223 {
224 // give a 'no filter' option
225 $years = array();
226 $years[0] = "----";
227
228 // retrieve available years
229 $res = XDB::query("select YEAR(MAX(start)), YEAR(MIN(start)) FROM log_sessions");
230 list($max, $min) = $res->fetchOneRow();
231
232 for($i = intval($min); $i<=$max; $i++) {
233 $years[$i] = $i;
234 }
235 return $years;
236 }
237
238
239 /** Make a where clause to get a user's sessions.
240 * Prepare the where clause request that will retrieve the sessions.
241 *
242 * @param $year INTEGER Only get log entries made during the given year.
243 * @param $month INTEGER Only get log entries made during the given month.
244 * @param $day INTEGER Only get log entries made during the given day.
245 * @param $uid INTEGER Only get log entries referring to the given user ID.
246 *
247 * @return STRING the WHERE clause of a query, including the 'WHERE' keyword
248 * @private
249 */
250 function _makeWhere($year, $month, $day, $uid)
251 {
252 // start constructing the "where" clause
253 $where = array();
254
255 if ($uid)
256 array_push($where, "s.uid='$uid'");
257
258 // we were given at least a year
259 if ($year) {
260 if ($day) {
261 $dmin = mktime(0, 0, 0, $month, $day, $year);
262 $dmax = mktime(0, 0, 0, $month, $day+1, $year);
263 } elseif ($month) {
264 $dmin = mktime(0, 0, 0, $month, 1, $year);
265 $dmax = mktime(0, 0, 0, $month+1, 1, $year);
266 } else {
267 $dmin = mktime(0, 0, 0, 1, 1, $year);
268 $dmax = mktime(0, 0, 0, 1, 1, $year+1);
269 }
270 $where[] = "start >= " . date("Ymd000000", $dmin);
271 $where[] = "start < " . date("Ymd000000", $dmax);
272 }
273
274 if (!empty($where)) {
275 return ' WHERE ' . implode($where, " AND ");
276 } else {
277 return '';
278 }
279 // WE know it's totally reversed, so better use array_reverse than a SORT BY start DESC
280 }
281
282 // }}}
283
284 function handler_logger($page, $action = null, $arg = null) {
285 if ($action == 'session') {
286
287 // we are viewing a session
288 $res = XDB::query("SELECT ls.*, a.hruid AS username, sa.hruid AS suer
289 FROM log_sessions AS ls
290 INNER JOIN accounts AS a ON (a.uid = ls.uid)
291 LEFT JOIN accounts AS sa ON (sa.uid = ls.suid)
292 WHERE ls.id = {?}", $arg);
293
294 $page->assign('session', $a = $res->fetchOneAssoc());
295
296 $res = XDB::iterator('SELECT a.text, e.data, e.stamp
297 FROM log_events AS e
298 LEFT JOIN log_actions AS a ON e.action=a.id
299 WHERE e.session={?}', $arg);
300 while ($myarr = $res->next()) {
301 $page->append('events', $myarr);
302 }
303
304 } else {
305 $loguser = $action == 'user' ? $arg : Env::v('loguser');
306
307 if ($loguser) {
308 $user = User::get($loguser);
309 $loguid = $user->id();
310 } else {
311 $loguid = null;
312 }
313
314 if ($loguid) {
315 $year = Env::i('year');
316 $month = Env::i('month');
317 $day = Env::i('day');
318 } else {
319 $year = Env::i('year', intval(date('Y')));
320 $month = Env::i('month', intval(date('m')));
321 $day = Env::i('day', intval(date('d')));
322 }
323
324 if (!$year)
325 $month = 0;
326 if (!$month)
327 $day = 0;
328
329 // smarty assignments
330 // retrieve available years
331 $page->assign('years', $this->_getYears());
332 $page->assign('year', $year);
333
334 // retrieve available months for the current year
335 $page->assign('months', $this->_getMonths($year));
336 $page->assign('month', $month);
337
338 // retrieve available days for the current year and month
339 $page->assign('days', $this->_getDays($year, $month));
340 $page->assign('day', $day);
341
342 $page->assign('loguser', $loguser);
343 // smarty assignments
344
345 if ($loguid || $year) {
346
347 // get the requested sessions
348 $where = $this->_makeWhere($year, $month, $day, $loguid);
349 $select = "SELECT s.id, s.start, s.uid,
350 a.hruid as username
351 FROM log_sessions AS s
352 INNER JOIN accounts AS a ON (a.uid = s.uid)
353 $where
354 ORDER BY start DESC";
355 $res = XDB::iterator($select);
356
357 $sessions = array();
358 while ($mysess = $res->next()) {
359 $mysess['events'] = array();
360 $sessions[$mysess['id']] = $mysess;
361 }
362 array_reverse($sessions);
363
364 // attach events
365 $sql = "SELECT s.id, a.text
366 FROM log_sessions AS s
367 LEFT JOIN log_events AS e ON(e.session=s.id)
368 INNER JOIN log_actions AS a ON(a.id=e.action)
369 $where";
370
371 $res = XDB::iterator($sql);
372 while ($event = $res->next()) {
373 array_push($sessions[$event['id']]['events'], $event['text']);
374 }
375 $page->assign_by_ref('sessions', $sessions);
376 } else {
377 $page->assign('msg_nofilters', "Sélectionner une année et/ou un utilisateur");
378 }
379 }
380
381 $page->changeTpl('admin/logger-view.tpl');
382
383 $page->setTitle('Administration - Logs des sessions');
384 }
385
386 function handler_user($page, $login = false)
387 {
388 global $globals;
389 $page->changeTpl('admin/user.tpl');
390 $page->setTitle('Administration - Compte');
391
392 if (S::suid()) {
393 $page->kill("Déjà en SUID&nbsp;!!!");
394 }
395
396 // Loads the user identity using the environment.
397 if ($login) {
398 $user = User::get($login);
399 }
400 if (empty($user)) {
401 pl_redirect('admin/accounts');
402 }
403
404 $listClient = new MMList(S::user());
405 $login = $user->login();
406 $registered = ($user->state != 'pending');
407
408 // Form processing
409 if (!empty($_POST)) {
410 S::assert_xsrf_token();
411 if (Post::has('uid') && Post::i('uid') != $user->id()) {
412 $page->kill('Une erreur s\'est produite');
413 }
414 }
415
416 // Handles specific requests (AX sync, su, ...).
417 if(Post::has('log_account')) {
418 pl_redirect("admin/logger?loguser=$login&year=".date('Y')."&month=".date('m'));
419 }
420
421 if(Post::has('su_account') && $registered) {
422 if (!Platal::session()->startSUID($user)) {
423 $page->trigError('Impossible d\'effectuer un SUID sur ' . $user->login());
424 } else {
425 pl_redirect("");
426 }
427 }
428
429 // Handles account deletion.
430 if (Post::has('account_deletion_confirmation')) {
431 $uid = $user->id();
432 $name = $user->fullName();
433 $profile = $user->profile();
434 if ($profile && Post::b('clear_profile')) {
435 $user->profile()->clear();
436 }
437 $user->clear(true);
438 $page->trigSuccess("L'utilisateur $name ($uid) a bien été désinscrit.");
439 if (Post::b('erase_account')) {
440 XDB::execute('DELETE FROM accounts
441 WHERE uid = {?}',
442 $uid);
443 $page->trigSuccess("L'utilisateur $name ($uid) a été supprimé de la base de données");
444 }
445 }
446
447 // Account Form {{{
448 require_once 'emails.inc.php';
449 $to_update = array();
450 if (Post::has('disable_weak_access')) {
451 $to_update['weak_password'] = null;
452 } else if (Post::has('update_account')) {
453 if (!$user->hasProfile()) {
454 $name_update = false;
455 if (Post::s('lastname') != $user->lastname) {
456 $to_update['lastname'] = Post::s('lastname');
457 $name_update = true;
458 }
459 if (Post::s('type') != 'virtual' && Post::s('firstname') != $user->firstname) {
460 $to_update['firstname'] = Post::s('firstname');
461 $name_update = true;
462 }
463 if ($name_update) {
464 if (Post::s('type') != 'virtual') {
465 $to_update['full_name'] = Post::s('firstname') . ' ' . Post::s('lastname');
466 $to_update['directory_name'] = mb_strtoupper(Post::s('lastname')) . ' ' . Post::s('firstname');
467 } else {
468 $to_update['full_name'] = Post::s('lastname');
469 $to_update['directory_name'] = mb_strtoupper(Post::s('lastname'));
470 }
471 }
472 if (Post::s('display_name') != $user->displayName()) {
473 $to_update['display_name'] = Post::s('display_name');
474 }
475 }
476 if (Post::s('sex') != ($user->isFemale() ? 'female' : 'male')) {
477 $to_update['sex'] = Post::s('sex');
478 if ($user->hasProfile()) {
479 XDB::execute('UPDATE profiles
480 SET sex = {?}
481 WHERE pid = {?}',
482 Post::s('sex'), $user->profile()->id());
483 }
484 }
485 if (!Post::blank('pwhash')) {
486 $to_update['password'] = Post::s('pwhash');
487 require_once 'googleapps.inc.php';
488 $account = new GoogleAppsAccount($user);
489 if ($account->active() && $account->sync_password) {
490 $account->set_password(Post::s('pwhash'));
491 }
492 }
493 if (!Post::blank('weak_password')) {
494 $to_update['weak_password'] = Post::s('weak_password');
495 }
496 if (Post::i('token_access', 0) != ($user->token_access ? 1 : 0)) {
497 $to_update['token'] = Post::i('token_access') ? rand_url_id(16) : null;
498 }
499 if (Post::i('skin') != $user->skin) {
500 $to_update['skin'] = Post::i('skin');
501 if ($to_update['skin'] == 0) {
502 $to_update['skin'] = null;
503 }
504 }
505 if (Post::s('state') != $user->state) {
506 $to_update['state'] = Post::s('state');
507 }
508 if (Post::i('is_admin', 0) != ($user->is_admin ? 1 : 0)) {
509 $to_update['is_admin'] = Post::b('is_admin');
510 }
511 if (Post::s('type') != $user->type) {
512 $to_update['type'] = Post::s('type');
513 }
514 if (Post::i('watch', 0) != ($user->watch ? 1 : 0)) {
515 $to_update['flags'] = new PlFlagset();
516 $to_update['flags']->addFlag('watch', Post::i('watch'));
517 }
518 if (Post::t('comment') != $user->comment) {
519 $to_update['comment'] = Post::blank('comment') ? null : Post::t('comment');
520 }
521 if (require_email_update($user, Post::t('email'))) {
522 $to_update['email'] = Post::t('email');
523 $listClient->change_user_email($user->forlifeEmail(), Post::t('email'));
524 update_alias_user($user->forlifeEmail(), Post::t('email'));
525 }
526 }
527 if (!empty($to_update)) {
528 $res = XDB::query('SELECT *
529 FROM accounts
530 WHERE uid = {?}', $user->id());
531 $oldValues = $res->fetchAllAssoc();
532 $oldValues = $oldValues[0];
533
534 $set = array();
535 $diff = array();
536 foreach ($to_update as $k => $value) {
537 $value = XDB::format('{?}', $value);
538 $set[] = $k . ' = ' . $value;
539 $diff[$k] = array($oldValues[$k], trim($value, "'"));
540 unset($oldValues[$k]);
541 }
542 XDB::rawExecute('UPDATE accounts
543 SET ' . implode(', ', $set) . '
544 WHERE uid = ' . XDB::format('{?}', $user->id()));
545 $page->trigSuccess('Données du compte mise à jour avec succès');
546 $user = User::getWithUID($user->id());
547
548 /* Formats the $diff and send it to the site administrators. The rules are the folowing:
549 * -formats: password, token, weak_password
550 */
551 foreach (array('password', 'token', 'weak_password') as $key) {
552 if (isset($diff[$key])) {
553 $diff[$key] = array('old value', 'new value');
554 } else {
555 $oldValues[$key] = 'old value';
556 }
557 }
558
559 $mail = new PlMailer('admin/useredit.mail.tpl');
560 $mail->assign('admin', S::user()->hruid);
561 $mail->assign('hruid', $user->hruid);
562 $mail->assign('diff', $diff);
563 $mail->assign('oldValues', $oldValues);
564 $mail->send();
565 }
566 // }}}
567
568 // Profile form {{{
569 if (Post::has('add_profile') || Post::has('del_profile') || Post::has('owner')) {
570 if (Post::i('del_profile', 0) != 0) {
571 XDB::execute('DELETE FROM account_profiles
572 WHERE uid = {?} AND pid = {?}',
573 $user->id(), Post::i('del_profile'));
574 } else if (!Post::blank('new_profile')) {
575 $profile = Profile::get(Post::t('new_profile'));
576 if (!$profile) {
577 $page->trigError('Le profil ' . Post::t('new_profile') . ' n\'existe pas');
578 } else {
579 XDB::execute('INSERT IGNORE INTO account_profiles (uid, pid)
580 VALUES ({?}, {?})',
581 $user->id(), $profile->id());
582 }
583 }
584 XDB::execute('UPDATE account_profiles
585 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
586 WHERE uid = {?}',
587 Post::i('owner'), $user->id());
588 }
589 // }}}
590
591 // Email forwards form {{{
592 $redirect = ($registered ? new Redirect($user) : null);
593 if (Post::has('add_fwd')) {
594 $email = Post::t('email');
595 if (!isvalid_email_redirection($email)) {
596 $page->trigError("Email non valide: $email");
597 } else {
598 $redirect->add_email($email);
599 $page->trigSuccess("Ajout de $email effectué");
600 }
601 } else if (!Post::blank('del_fwd')) {
602 $redirect->delete_email(Post::t('del_fwd'));
603 } else if (!Post::blank('activate_fwd')) {
604 $redirect->modify_one_email(Post::t('activate_fwd'), true);
605 } else if (!Post::blank('deactivate_fwd')) {
606 $redirect->modify_one_email(Post::t('deactivate_fwd'), false);
607 } else if (Post::has('disable_fwd')) {
608 $redirect->disable();
609 } else if (Post::has('enable_fwd')) {
610 $redirect->enable();
611 } else if (!Post::blank('clean_fwd')) {
612 $redirect->clean_errors(Post::t('clean_fwd'));
613 }
614 // }}}
615
616 // Email alias form {{{
617 if (Post::has('add_alias')) {
618 // Splits new alias in user and fqdn.
619 $alias = Env::t('email');
620 if (strpos($alias, '@') !== false) {
621 list($alias, $domain) = explode('@', $alias);
622 } else {
623 $domain = $user->mainEmailDomain();
624 }
625
626 // Checks for alias' user validity.
627 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
628 $page->trigError("'$alias' n'est pas un alias valide");
629 }
630
631 // Eventually adds the alias to the right domain.
632 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
633 $req = new AliasReq($user, $alias, 'Admin request', false);
634 if ($req->commit()) {
635 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué.");
636 } else {
637 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué.");
638 }
639 } elseif ($domain == $user->mainEmailDomain()) {
640 XDB::execute('INSERT INTO email_source_account (email, uid, domain, type, flags)
641 SELECT {?}, {?}, id, \'alias\', \'\'
642 FROM email_virtual_domains
643 WHERE name = {?}',
644 $alias, $user->id(), $domain);
645 $page->trigSuccess("Nouvel alias '$alias' ajouté");
646 } else {
647 $page->trigError("Le domaine '$domain' n'est pas valide pour cet utilisateur.");
648 }
649 } else if (!Post::blank('del_alias')) {
650 $delete_alias = Post::t('del_alias');
651 list($email, $domain) = explode('@', $delete_alias);
652 XDB::execute('DELETE s
653 FROM email_source_account AS s
654 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
655 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
656 WHERE s.email = {?} AND s.uid = {?} AND d.name = {?} AND type != \'forlife\'',
657 $email, $user->id(), $domain);
658 XDB::execute('UPDATE email_redirect_account AS r
659 INNER JOIN email_virtual_domains AS m ON (m.name = {?})
660 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
661 SET r.rewrite = \'\'
662 WHERE r.uid = {?} AND r.rewrite = CONCAT({?}, \'@\', d.name)',
663 $domain, $user->id(), $email);
664 fix_bestalias($user);
665 $page->trigSuccess("L'alias '$delete_alias' a été supprimé");
666 } else if (!Post::blank('best')) {
667 $best_alias = Post::t('best');
668 // First delete the bestalias flag from all this user's emails.
669 XDB::execute("UPDATE email_source_account
670 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
671 WHERE uid = {?}", $user->id());
672 // Then gives the bestalias flag to the given email.
673 list($email, $domain) = explode('@', $best_alias);
674 XDB::execute("UPDATE email_source_account
675 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
676 WHERE uid = {?} AND email = {?}", $user->id(), $email);
677
678 // As having a non-null bestalias value is critical in
679 // plat/al's code, we do an a posteriori check on the
680 // validity of the bestalias.
681 fix_bestalias($user);
682 }
683 // }}}
684
685 // OpenId form {{{
686 if (Post::has('del_openid')) {
687 XDB::execute('DELETE FROM account_auth_openid
688 WHERE id = {?}', Post::i('del_openid'));
689 }
690 // }}}
691
692 // Forum form {{{
693 if (Post::has('b_edit')) {
694 XDB::execute("DELETE FROM forum_innd
695 WHERE uid = {?}", $user->id());
696 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
697 XDB::execute("INSERT INTO forum_innd
698 SET ipmin = '0', ipmax = '4294967295',
699 write_perm = {?}, read_perm = {?},
700 comment = {?}, priority = '200', uid = {?}",
701 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
702 }
703 }
704 // }}}
705
706
707 $page->addJsLink('jquery.ui.xorg.js');
708
709 // Displays last login and last host information.
710 $res = XDB::query("SELECT start, host
711 FROM log_sessions
712 WHERE uid = {?} AND suid = 0
713 ORDER BY start DESC
714 LIMIT 1", $user->id());
715 list($lastlogin,$host) = $res->fetchOneRow();
716 $page->assign('lastlogin', $lastlogin);
717 $page->assign('host', $host);
718
719 // Display mailing lists
720 $page->assign('mlists', $listClient->get_all_user_lists($user->forlifeEmail()));
721
722 // Display active aliases.
723 $page->assign('virtuals', $user->emailGroupAliases());
724 $aliases = XDB::iterator("SELECT CONCAT(s.email, '@', d.name) AS email, (s.type = 'forlife') AS forlife,
725 (s.email REGEXP '\\\\.[0-9]{2}$') AS hundred_year,
726 FIND_IN_SET('bestalias', s.flags) AS bestalias, s.expire,
727 (s.type = 'alias_aux') AS alias
728 FROM email_source_account AS s
729 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
730 WHERE s.uid = {?}
731 ORDER BY !alias, s.email",
732 $user->id());
733 $page->assign('aliases', $aliases);
734 $page->assign('account_types', XDB::iterator('SELECT * FROM account_types ORDER BY type'));
735 $page->assign('skins', XDB::iterator('SELECT id, name FROM skins ORDER BY name'));
736 $page->assign('profiles', XDB::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
737 FROM account_profiles AS ap
738 INNER JOIN profiles AS p ON (ap.pid = p.pid)
739 WHERE ap.uid = {?}', $user->id()));
740 $page->assign('openid', XDB::iterator('SELECT id, url
741 FROM account_auth_openid
742 WHERE uid = {?}', $user->id()));
743
744 // Displays email redirection and the general profile.
745 if ($registered && $redirect) {
746 $page->assign('emails', $redirect->emails);
747 }
748
749 $page->assign('user', $user);
750 $page->assign('hasProfile', $user->hasProfile());
751
752 // Displays forum bans.
753 $res = XDB::query("SELECT write_perm, read_perm, comment
754 FROM forum_innd
755 WHERE uid = {?}", $user->id());
756 $bans = $res->fetchOneAssoc();
757 $page->assign('bans', $bans);
758 }
759
760 private static function getHrid($firstname, $lastname, $promo)
761 {
762 if ($firstname != null && $lastname != null && $promo != null) {
763 return User::makeHrid($firstname, $lastname, $promo);
764 }
765 return null;
766 }
767
768 private static function formatNewUser($page, $infosLine, $separator, $promo, $size)
769 {
770 $infos = explode($separator, $infosLine);
771 if (sizeof($infos) > $size || sizeof($infos) < 2) {
772 $page->trigError("La ligne $infosLine n'a pas été ajoutée.");
773 return false;
774 }
775
776 $infos = array_map('trim', $infos);
777 $hrid = self::getHrid($infos[1], $infos[0], $promo);
778 $res1 = XDB::query('SELECT COUNT(*)
779 FROM accounts
780 WHERE hruid = {?}', $hrid);
781 $res2 = XDB::query('SELECT COUNT(*)
782 FROM profiles
783 WHERE hrpid = {?}', $hrid);
784 if (is_null($hrid) || $res1->fetchOneCell() > 0 || $res2->fetchOneCell() > 0) {
785 $page->trigError("La ligne $infosLine n'a pas été ajoutée: une entrée similaire existe déjà");
786 return false;
787 }
788 $infos['hrid'] = $hrid;
789 return $infos;
790 }
791
792 private static function formatSex($page, $sex, $line)
793 {
794 switch ($sex) {
795 case 'F':
796 return 'female';
797 case 'M':
798 return 'male';
799 default:
800 $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
801 return null;
802 }
803 }
804
805 private static function formatBirthDate($birthDate)
806 {
807 // strtotime believes dd/mm/yyyy to be an US date (i.e mm/dd/yyyy), and
808 // dd-mm-yyyy to be a normal date (i.e dd-mm-yyyy)...
809 return date("Y-m-d", strtotime(str_replace('/', '-', $birthDate)));
810 }
811
812 function handler_add_accounts($page, $action = null, $promo = null)
813 {
814 $page->changeTpl('admin/add_accounts.tpl');
815
816 if (Env::has('add_type') && Env::has('people')) {
817 $lines = explode("\n", Env::t('people'));
818 $separator = Env::t('separator');
819 $promotion = Env::i('promotion');
820
821 if (Env::t('add_type') == 'promo') {
822 $eduSchools = DirEnum::getOptions(DirEnum::EDUSCHOOLS);
823 $eduSchools = array_flip($eduSchools);
824 $eduDegrees = DirEnum::getOptions(DirEnum::EDUDEGREES);
825 $eduDegrees = array_flip($eduDegrees);
826 switch (Env::t('edu_type')) {
827 case 'X':
828 $degreeid = $eduDegrees[Profile::DEGREE_X];
829 $entry_year = $promotion;
830 $grad_year = $promotion + 3;
831 $promo = 'X' . $promotion;
832 $hrpromo = $promotion;
833 $type = 'x';
834 break;
835 case 'M':
836 $degreeid = $eduDegrees[Profile::DEGREE_M];
837 $grad_year = $promotion;
838 $entry_year = $promotion - 2;
839 $promo = 'M' . $promotion;
840 $hrpromo = $promo;
841 $type = 'master';
842 break;
843 case 'D':
844 $degreeid = $eduDegrees[Profile::DEGREE_D];
845 $grad_year = $promotion;
846 $entry_year = $promotion - 3;
847 $promo = 'D (en cours)';
848 $hrpromo = 'D' . $promotion;
849 $type = 'phd';
850 break;
851 default:
852 $page->killError("La formation n'est pas reconnue : " . Env::t('edu_type') . '.');
853 }
854
855 XDB::startTransaction();
856 foreach ($lines as $line) {
857 if ($infos = self::formatNewUser($page, $line, $separator, $hrpromo, 6)) {
858 $sex = self::formatSex($page, $infos[3], $line);
859 if (!is_null($sex)) {
860 $fullName = $infos[1] . ' ' . $infos[0];
861 $directoryName = $infos[0] . ' ' . $infos[1];
862 $birthDate = self::formatBirthDate($infos[2]);
863 if ($type == 'x') {
864 $xorgId = Profile::getXorgId($infos[4]);
865 } elseif (isset($infos[4])) {
866 $xorgId = trim($infos[4]);
867 } else {
868 $xorgId = 0;
869 }
870 if (is_null($xorgId)) {
871 $page->trigError("La ligne $line n'a pas été ajoutée car le matricule École est mal renseigné.");
872 continue;
873 }
874
875 XDB::execute('INSERT INTO profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex)
876 VALUES ({?}, {?}, {?}, {?}, {?})',
877 $infos['hrid'], $xorgId, (isset($infos[5]) ? $infos[5] : null), $birthDate, $sex);
878 $pid = XDB::insertId();
879 XDB::execute('INSERT INTO profile_public_names (pid, lastname_initial, lastname_main, firstname_initial, firstname_main)
880 VALUES ({?}, {?}, {?}, {?}, {?})',
881 $pid, $infos[0], $infos[0], $infos[1], $infos[1]);
882 XDB::execute('INSERT INTO profile_display (pid, yourself, public_name, private_name,
883 directory_name, short_name, sort_name, promo)
884 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
885 $pid, $infos[1], $fullName, $fullName, $directoryName, $fullName, $directoryName, $promo);
886 XDB::execute('INSERT INTO profile_education (id, pid, eduid, degreeid, entry_year, grad_year, promo_year, flags)
887 VALUES (100, {?}, {?}, {?}, {?}, {?}, {?}, \'primary\')',
888 $pid, $eduSchools[Profile::EDU_X], $degreeid, $entry_year, $grad_year, $promotion);
889 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, full_name, directory_name,
890 display_name, lastname, firstname, sex)
891 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
892 $infos['hrid'], $type, 0, 'pending', $fullName, $directoryName,
893 $infos[1], $infos[0], $infos[1], $sex);
894 $uid = XDB::insertId();
895 XDB::execute('INSERT INTO account_profiles (uid, pid, perms)
896 VALUES ({?}, {?}, {?})',
897 $uid, $pid, 'owner');
898 Profile::rebuildSearchTokens($pid, false);
899 }
900 }
901 }
902 XDB::commit();
903 } else if (Env::t('add_type') == 'account') {
904 $type = Env::t('type');
905 $newAccounts = array();
906 foreach ($lines as $line) {
907 if ($infos = self::formatNewUser($page, $line, $separator, $type, 4)) {
908 $sex = self::formatSex($page, $infos[3], $line);
909 if (!is_null($sex)) {
910 $fullName = $infos[1] . ' ' . $infos[0];
911 $directoryName = $infos[0] . ' ' . $infos[1];
912 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, email, full_name, directory_name,
913 display_name, lastname, firstname, sex)
914 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
915 $infos['hrid'], $type, 0, 'pending', $infos[2], $fullName, $directoryName,
916 $infos[1], $infos[0], $infos[1], $sex);
917 $newAccounts[$infos['hrid']] = $infos[1] . ' ' . $infos[0];
918 }
919 }
920 }
921 if (!empty($newAccounts)) {
922 $page->assign('newAccounts', $newAccounts);
923 }
924 } else if (Env::t('add_type') == 'ax_id') {
925 $type = 'x';
926 foreach ($lines as $line) {
927 if ($infos = self::formatNewUser($page, $line, $separator, $promotion, 3)) {
928 XDB::execute('UPDATE profiles
929 SET ax_id = {?}
930 WHERE hrpid = {?}',
931 $infos[2], $infos['hrid']);
932 }
933 }
934 }
935
936 $errors = $page->nb_errs();
937 if ($errors == 0) {
938 $page->trigSuccess("L'opération a été effectuée avec succès.");
939 } else {
940 $page->trigSuccess('L\'opération a été effectuée avec succès, sauf pour '
941 . (($errors == 1) ? 'l\'erreur signalée' : "les $errors erreurs signalées") . ' ci-dessus.');
942 }
943 } else if (Env::has('add_type')) {
944 $res = XDB::query('SELECT type
945 FROM account_types');
946 $page->assign('account_types', $res->fetchColumn());
947 $page->assign('add_type', Env::s('add_type'));
948 }
949 }
950
951 function handler_homonyms($page, $op = 'list', $target = null)
952 {
953 $page->changeTpl('admin/homonymes.tpl');
954 $page->setTitle('Administration - Homonymes');
955 $this->load("homonyms.inc.php");
956
957 if ($target) {
958 $user = User::getSilentWithUID($target);
959 if (!$user || !($loginbis = select_if_homonym($user))) {
960 $target = 0;
961 } else {
962 $page->assign('user', $user);
963 $page->assign('loginbis',$loginbis);
964 }
965 }
966
967 $page->assign('op', $op);
968 $page->assign('target', $target);
969
970 // When we have a valid target, prepare emails.
971 if ($target) {
972 // Examine what operation needs to be performed.
973 switch ($op) {
974 case 'mail':
975 S::assert_xsrf_token();
976
977 send_warning_homonym($user, $loginbis);
978 $op = 'list';
979 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
980 break;
981
982 case 'correct':
983 S::assert_xsrf_token();
984
985 fix_homonym($user, $loginbis);
986 send_robot_homonym($user, $loginbis);
987 $op = 'list';
988 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
989 break;
990 }
991 }
992
993 if ($op == 'list') {
994 // Retrieves homonyms that are already been fixed.
995 $res = XDB::iterator('SELECT o.email AS homonym, f.email AS forlife, o.expire, f.uid
996 FROM email_source_other AS o
997 INNER JOIN homonyms_list AS h ON (o.hrmid = h.hrmid)
998 INNER JOIN email_source_account AS f ON (h.uid = f.uid AND f.type = \'forlife\')
999 WHERE o.expire IS NOT NULL
1000 ORDER BY homonym, forlife');
1001 $homonyms = array();
1002 while ($item = $res->next()) {
1003 $homonyms[$item['homonym']][] = $item;
1004 }
1005 $page->assign_by_ref('homonyms', $homonyms);
1006
1007 // Retrieves homonyms that needs to be fixed.
1008 $res = XDB::iterator('SELECT e.email AS homonym, f.email AS forlife, e.expire, e.uid, (e.expire < NOW()) AS urgent
1009 FROM email_source_account AS e
1010 INNER JOIN homonyms_list AS l ON (e.uid = l.uid)
1011 INNER JOIN homonyms_list AS h ON (l.hrmid = h.hrmid)
1012 INNER JOIN email_source_account AS f ON (h.uid = f.uid AND f.type = \'forlife\')
1013 WHERE e.expire IS NOT NULL
1014 ORDER BY homonym, forlife');
1015 $homonyms_to_fix = array();
1016 while ($item = $res->next()) {
1017 $homonyms_to_fix[$item['homonym']][] = $item;
1018 }
1019 $page->assign_by_ref('homonyms_to_fix', $homonyms_to_fix);
1020 }
1021
1022 if ($op == 'correct-conf') {
1023 $page->assign('robot_mail_text', get_robot_mail_text($user, $loginbis));
1024 }
1025
1026 if ($op == 'mail-conf') {
1027 $page->assign('warning_mail_text', get_warning_mail_text($user, $loginbis));
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, true);
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, true);
1176 $table_editor->describe('comment','commentaire',true);
1177 $table_editor->describe('date','date',false, true);
1178 $table_editor->describe('ext','extension du screenshot',false, true);
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, true);
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, true);
1229 $table_editor->describe('resume','résumé',true);
1230 $table_editor->describe('services','services affectés',true);
1231 $table_editor->describe('description','description',false, true);
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 = mb_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 lastname, firstname)
1481 VALUES ({?}, {?}, 'active', {?}, NOW(), {?}, {?}, {?}, {?}, {?}, {?}, {?})",
1482 $login, $type, Post::s('pwhash'), $email, $full_name, $full_name, $sex,
1483 $directory_name, $lastname, $firstname);
1484 }
1485 }
1486
1487 $uf = new UserFilter(new UFC_AccountType('ax', 'school', 'fx'));
1488 $page->assign('users', $uf->iterUsers());
1489
1490 }
1491
1492 function handler_account_types($page, $action = 'list', $id = null)
1493 {
1494 $page->setTitle('Administration - Types de comptes');
1495 $page->assign('title', 'Gestion des types de comptes');
1496 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true);
1497 $table_editor->describe('type', 'Catégorie', true);
1498 $table_editor->describe('perms', 'Permissions associées', true);
1499 $table_editor->apply($page, $action, $id);
1500 }
1501
1502 function handler_wiki($page, $action = 'list', $wikipage = null, $wikipage2 = null)
1503 {
1504 if (S::hasAuthToken()) {
1505 $page->setRssLink('Changement Récents',
1506 '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::user()->token);
1507 }
1508
1509 // update wiki perms
1510 if ($action == 'update') {
1511 S::assert_xsrf_token();
1512
1513 $perms_read = Post::v('read');
1514 $perms_edit = Post::v('edit');
1515 if ($perms_read || $perms_edit) {
1516 foreach ($_POST as $wiki_page => $val) {
1517 if ($val == 'on') {
1518 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1519 if ($wp->setPerms($perms_read ? $perms_read : $wp->readPerms(),
1520 $perms_edit ? $perms_edit : $wp->writePerms())) {
1521 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1522 } else {
1523 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1524 }
1525 }
1526 }
1527 }
1528 } else if ($action != 'list' && !empty($wikipage)) {
1529 $wp = new PlWikiPage($wikipage);
1530 S::assert_xsrf_token();
1531
1532 if ($action == 'delete') {
1533 if ($wp->delete()) {
1534 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1535 } else {
1536 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1537 }
1538 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1539 if ($changedLinks = $wp->rename($wikipage2)) {
1540 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1541 if (is_numeric($changedLinks)) {
1542 $s .= $changedLinks.' lien'.(($changedLinks>1)?'s ont été modifiés.':' a été modifié.');
1543 }
1544 $page->trigSuccess($s);
1545 } else {
1546 $page->trigError("Impossible de déplacer la page ".$wikipage);
1547 }
1548 }
1549 }
1550
1551 $perms = PlWikiPage::permOptions();
1552
1553 // list wiki pages and their perms
1554 $wiki_pages = PlWikiPage::listPages();
1555 ksort($wiki_pages);
1556 $wiki_tree = array();
1557 foreach ($wiki_pages as $file => $desc) {
1558 list($cat, $name) = explode('.', $file);
1559 if (!isset($wiki_tree[$cat])) {
1560 $wiki_tree[$cat] = array();
1561 }
1562 $wiki_tree[$cat][$name] = $desc;
1563 }
1564
1565 $page->changeTpl('admin/wiki.tpl');
1566 $page->assign('wiki_pages', $wiki_tree);
1567 $page->assign('perms_opts', $perms);
1568 }
1569
1570 function handler_ipwatch($page, $action = 'list', $ip = null)
1571 {
1572 $page->changeTpl('admin/ipwatcher.tpl');
1573
1574 $states = array('safe' => 'Ne pas surveiller',
1575 'unsafe' => 'Surveiller les inscriptions',
1576 'dangerous' => 'Surveiller tous les accès',
1577 'ban' => 'Bannir cette adresse');
1578 $page->assign('states', $states);
1579
1580 switch (Post::v('action')) {
1581 case 'create':
1582 if (trim(Post::v('ipN')) != '') {
1583 S::assert_xsrf_token();
1584 Xdb::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1585 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1586 ip_to_uint(trim(Post::v('ipN'))), ip_to_uint(trim(Post::v('maskN'))),
1587 Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
1588 };
1589 break;
1590
1591 case 'edit':
1592 S::assert_xsrf_token();
1593 Xdb::execute('UPDATE ip_watch
1594 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1595 WHERE ip = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'),
1596 ip_to_uint(Post::v('maskN')), ip_to_uint(Post::v('ipN')));
1597 break;
1598
1599 default:
1600 if ($action == 'delete' && !is_null($ip)) {
1601 S::assert_xsrf_token();
1602 Xdb::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1603 }
1604 }
1605 if ($action != 'create' && $action != 'edit') {
1606 $action = 'list';
1607 }
1608 $page->assign('action', $action);
1609
1610 if ($action == 'list') {
1611 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1612 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1613 IF(w.ip = s.ip, s.host, s.forward_host)),
1614 w.mask, w.detection, w.state, a.hruid
1615 FROM ip_watch AS w
1616 LEFT JOIN log_sessions AS s ON (s.ip = w.ip)
1617 LEFT JOIN log_sessions AS s2 ON (s2.forward_ip = w.ip)
1618 LEFT JOIN accounts AS a ON (a.uid = s.uid)
1619 GROUP BY w.ip, a.hruid
1620 ORDER BY w.state, w.ip, a.hruid";
1621 $it = Xdb::iterRow($sql);
1622
1623 $table = array();
1624 $props = array();
1625 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1626 $ip = uint_to_ip($ip);
1627 $mask = uint_to_ip($mask);
1628 if (count($props) == 0 || $props['ip'] != $ip) {
1629 if (count($props) > 0) {
1630 $table[] = $props;
1631 }
1632 $props = array('ip' => $ip,
1633 'mask' => $mask,
1634 'host' => $host,
1635 'detection' => $date,
1636 'state' => $state,
1637 'users' => array($hruid));
1638 } else {
1639 $props['users'][] = $hruid;
1640 }
1641 }
1642 if (count($props) > 0) {
1643 $table[] = $props;
1644 }
1645 $page->assign('table', $table);
1646 } elseif ($action == 'edit') {
1647 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1648 a1.hruid AS edit, a2.hruid AS hruid, s.host
1649 FROM ip_watch AS w
1650 LEFT JOIN accounts AS a1 ON (a1.uid = w.uid)
1651 LEFT JOIN log_sessions AS s ON (w.ip = s.ip)
1652 LEFT JOIN accounts AS a2 ON (a2.uid = s.uid)
1653 WHERE w.ip = {?}
1654 GROUP BY a2.hruid
1655 ORDER BY a2.hruid";
1656 $it = Xdb::iterRow($sql, ip_to_uint($ip));
1657
1658 $props = array();
1659 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1660 if (count($props) == 0) {
1661 $props = array('ip' => $ip,
1662 'mask' => uint_to_ip($mask),
1663 'host' => $host,
1664 'detection' => $detection,
1665 'state' => $state,
1666 'last' => $last,
1667 'description' => $description,
1668 'edit' => $edit,
1669 'users' => array($hruid));
1670 } else {
1671 $props['users'][] = $hruid;
1672 }
1673 }
1674 $page->assign('ip', $props);
1675 }
1676 }
1677
1678 function handler_icons($page)
1679 {
1680 $page->changeTpl('admin/icons.tpl');
1681 $dh = opendir('../htdocs/images/icons');
1682 if (!$dh) {
1683 $page->trigError('Dossier des icones introuvables.');
1684 }
1685 $icons = array();
1686 while (($file = readdir($dh)) !== false) {
1687 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1688 array_push($icons, substr($file, 0, -4));
1689 }
1690 }
1691 sort($icons);
1692 $page->assign('icons', $icons);
1693 }
1694
1695 function handler_account_watch($page)
1696 {
1697 $page->changeTpl('admin/accounts.tpl');
1698 $page->assign('disabled', XDB::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1699 a.state = \'disabled\' AS disabled, a.comment
1700 FROM accounts AS a
1701 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1702 ORDER BY a.hruid'));
1703 $page->assign('admins', XDB::iterator('SELECT a.hruid
1704 FROM accounts AS a
1705 WHERE a.is_admin
1706 ORDER BY a.hruid'));
1707 }
1708
1709 function handler_xnet_without_group($page)
1710 {
1711 $page->changeTpl('admin/xnet_without_group.tpl');
1712 $page->assign('accounts', XDB::iterator('SELECT a.hruid, a.state
1713 FROM accounts AS a
1714 LEFT JOIN group_members AS m ON (a.uid = m.uid)
1715 WHERE a.type = \'xnet\' AND m.uid IS NULL
1716 ORDER BY a.state, a.hruid'));
1717 }
1718
1719 function handler_jobs($page, $id = -1)
1720 {
1721 $page->changeTpl('admin/jobs.tpl');
1722
1723 if (Env::has('search')) {
1724 $res = XDB::query("SELECT id, name, acronym
1725 FROM profile_job_enum
1726 WHERE name LIKE CONCAT('%', {?}, '%') OR acronym LIKE CONCAT('%', {?}, '%')",
1727 Env::t('job'), Env::t('job'));
1728
1729 if ($res->numRows() <= 20) {
1730 $page->assign('jobs', $res->fetchAllAssoc());
1731 } else {
1732 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1733 }
1734
1735 $page->assign('askedJob', Env::v('job'));
1736 return;
1737 }
1738
1739 if (Env::has('edit')) {
1740 S::assert_xsrf_token();
1741 $selectedJob = Env::has('selectedJob');
1742
1743 Phone::deletePhones(0, Phone::LINK_COMPANY, $id);
1744 Address::deleteAddresses(null, Address::LINK_COMPANY, $id);
1745 if (Env::has('change')) {
1746 if (Env::has('newJobId') && Env::i('newJobId') > 0) {
1747 XDB::execute('UPDATE profile_job
1748 SET jobid = {?}
1749 WHERE jobid = {?}',
1750 Env::i('newJobId'), $id);
1751 XDB::execute('DELETE FROM profile_job_enum
1752 WHERE id = {?}',
1753 $id);
1754
1755 $page->trigSuccess("L'entreprise a bien été remplacée.");
1756 } else {
1757 $page->trigError("L'entreprise n'a pas été remplacée car l'identifiant fourni n'est pas valide.");
1758 }
1759 } else {
1760 XDB::execute('UPDATE profile_job_enum
1761 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1762 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1763 WHERE id = {?}',
1764 Env::t('name'), Env::t('acronym'), Env::t('url'), Env::t('email'),
1765 (Env::t('NAF_code') == 0 ? null : Env::t('NAF_code')),
1766 (Env::i('AX_code') == 0 ? null : Env::t('AX_code')),
1767 (Env::i('holdingId') == 0 ? null : Env::t('holdingId')), $id);
1768
1769 $phone = new Phone(array('display' => Env::v('tel'), 'link_id' => $id, 'id' => 0, 'type' => 'fixed',
1770 'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
1771 $fax = new Phone(array('display' => Env::v('fax'), 'link_id' => $id, 'id' => 1, 'type' => 'fax',
1772 'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
1773 $address = new Address(array('jobid' => $id, 'type' => Address::LINK_COMPANY, 'text' => Env::t('address')));
1774 $phone->save();
1775 $fax->save();
1776 $address->save();
1777
1778 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1779 }
1780 }
1781
1782 if (!Env::has('change') && $id != -1) {
1783 $res = XDB::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1784 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1785 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1786 FROM profile_job_enum AS e
1787 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
1788 LEFT JOIN profile_phones AS t ON (t.pid = e.id AND t.link_type = 'hq' AND t.tel_id = 0)
1789 LEFT JOIN profile_phones AS f ON (f.pid = e.id AND f.link_type = 'hq' AND f.tel_id = 1)
1790 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1791 WHERE e.id = {?}",
1792 $id);
1793
1794 if ($res->numRows() == 0) {
1795 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1796 } else {
1797 $page->assign('selectedJob', $res->fetchOneAssoc());
1798 }
1799 }
1800 }
1801
1802 function handler_profile($page)
1803 {
1804 $page->changeTpl('admin/profile.tpl');
1805
1806 if (Post::has('checked')) {
1807 S::assert_xsrf_token();
1808 $res = XDB::iterator('SELECT DISTINCT(pm.pid), pd.public_name
1809 FROM profile_modifications AS pm
1810 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1811 WHERE pm.type = \'self\'');
1812
1813 while ($profile = $res->next()) {
1814 if (Post::has('checked_' . $profile['pid'])) {
1815 XDB::execute('DELETE FROM profile_modifications
1816 WHERE type = \'self\' AND pid = {?}', $profile['pid']);
1817
1818 $page->trigSuccess('Profil de ' . $profile['public_name'] . ' vérifié.');
1819 }
1820 }
1821 }
1822
1823 $res = XDB::iterator('SELECT p.hrpid, pm.pid, pd.directory_name, GROUP_CONCAT(pm.field SEPARATOR \', \') AS field
1824 FROM profile_modifications AS pm
1825 INNER JOIN profiles AS p ON (pm.pid = p.pid)
1826 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1827 WHERE pm.type = \'self\'
1828 GROUP BY pd.directory_name
1829 ORDER BY pd.directory_name');
1830 $page->assign('updates', $res);
1831 }
1832
1833 function handler_phd($page, $promo = null, $validate = false)
1834 {
1835 $page->changeTpl('admin/phd.tpl');
1836 $eduDegrees = DirEnum::getOptions(DirEnum::EDUDEGREES);
1837 $eduDegrees = array_flip($eduDegrees);
1838
1839 if (is_null($promo)) {
1840 $promo_list = XDB::fetchColumn('SELECT DISTINCT(grad_year)
1841 FROM profile_education
1842 WHERE FIND_IN_SET(\'primary\', flags) AND NOT FIND_IN_SET(\'completed\', flags) AND degreeid = {?}
1843 ORDER BY grad_year',
1844 $eduDegrees[Profile::DEGREE_D]);
1845 $page->assign('promo_list', $promo_list);
1846 $page->assign('nothing', count($promo_list) == 0);
1847 return;
1848 }
1849
1850 if ($validate) {
1851 S::assert_xsrf_token();
1852
1853 $list = XDB::iterator('SELECT pe.pid, pd.directory_name
1854 FROM profile_education AS pe
1855 INNER JOIN profile_display AS pd ON (pe.pid = pd.pid)
1856 WHERE FIND_IN_SET(\'primary\', pe.flags) AND NOT FIND_IN_SET(\'completed\', pe.flags)
1857 AND pe.degreeid = {?} AND pe.grad_year = {?}',
1858 $eduDegrees[Profile::DEGREE_D], $promo);
1859 while ($res = $list->next()) {
1860 $pid = $res['pid'];
1861 $name = $res['directory_name'];
1862 if (Post::b('completed_' . $pid)) {
1863 $grad_year = Post::t('grad_year_' . $pid);
1864 XDB::execute('UPDATE profile_education
1865 SET flags = \'primary,completed\', grad_year = {?}
1866 WHERE FIND_IN_SET(\'primary\', flags) AND pid = {?}',
1867 $grad_year, $pid);
1868 XDB::execute('UPDATE profile_display
1869 SET promo = {?}
1870 WHERE pid = {?}',
1871 'D' . $grad_year, $pid);
1872 $page->trigSuccess("Promotion de $name validée.");
1873 }
1874 }
1875 }
1876
1877 $list = XDB::iterator('SELECT pe.pid, pd.directory_name
1878 FROM profile_education AS pe
1879 INNER JOIN profile_display AS pd ON (pe.pid = pd.pid)
1880 WHERE FIND_IN_SET(\'primary\', pe.flags) AND NOT FIND_IN_SET(\'completed\', pe.flags)
1881 AND pe.degreeid = {?} AND pe.grad_year = {?}
1882 ORDER BY pd.directory_name',
1883 $eduDegrees[Profile::DEGREE_D], $promo);
1884 $page->assign('list', $list);
1885 $page->assign('promo', $promo);
1886 }
1887
1888 function handler_add_secondary_edu($page)
1889 {
1890 $page->changeTpl('admin/add_secondary_edu.tpl');
1891
1892 if (!(Post::has('verify') || Post::has('add'))) {
1893 return;
1894 } elseif (!Post::has('people')) {
1895 $page->trigWarning("Aucune information n'a été fournie.");
1896 return;
1897 }
1898
1899 require_once 'name.func.inc.php';
1900 $lines = explode("\n", Post::t('people'));
1901 $separator = Post::t('separator');
1902 $degree = Post::v('degree');
1903 $promotion = Post::i('promotion');
1904 $schoolsList = array_flip(DirEnum::getOptions(DirEnum::EDUSCHOOLS));
1905 $degreesList = array_flip(DirEnum::getOptions(DirEnum::EDUDEGREES));
1906 $edu_id = $schoolsList[Profile::EDU_X];
1907 $degree_id = $degreesList[$degree];
1908
1909 $res = array(
1910 'incomplete' => array(),
1911 'empty' => array(),
1912 'multiple' => array(),
1913 'already' => array(),
1914 'new' => array()
1915 );
1916 $old_pids = array();
1917 $new_pids = array();
1918 foreach ($lines as $line) {
1919 $line = trim($line);
1920 $line_array = explode($separator, $line);
1921 array_walk($line_array, 'trim');
1922 if (count($line_array) != 3) {
1923 $page->trigError("La ligne « $line » est incomplète.");
1924 $res['incomplete'][] = $line;
1925 continue;
1926 }
1927 $cond = new PFC_And(new UFC_NameTokens(split_name_for_search($line_array[0]), array(), false, false, Profile::LASTNAME));
1928 $cond->addChild(new UFC_NameTokens(split_name_for_search($line_array[1]), array(), false, false, Profile::FIRSTNAME));
1929 $cond->addChild(new UFC_Promo('=', UserFilter::DISPLAY, $line_array[2]));
1930 $uf = new UserFilter($cond);
1931 $pid = $uf->getPIDs();
1932 $count = count($pid);
1933 if ($count == 0) {
1934 $page->trigError("La ligne « $line » ne correspond à aucun profil existant.");
1935 $res['empty'][] = $line;
1936 continue;
1937 } elseif ($count > 1) {
1938 $page->trigError("La ligne « $line » correspond à plusieurs profils existant.");
1939 $res['multiple'][] = $line;
1940 continue;
1941 } else {
1942 $count = XDB::fetchOneCell('SELECT COUNT(*) AS count
1943 FROM profile_education
1944 WHERE pid = {?} AND eduid = {?} AND degreeid = {?}',
1945 $pid, $edu_id, $degree_id);
1946 if ($count == 1) {
1947 $res['already'][] = $line;
1948 $old_pids[] = $pid[0];
1949 } else {
1950 $res['new'][] = $line;
1951 $new_pids[] = $pid[0];
1952 }
1953 }
1954 }
1955
1956 $display = array();
1957 foreach ($res as $type => $res_type) {
1958 if (count($res_type) > 0) {
1959 $display = array_merge($display, array('--------------------' . $type . ':'), $res_type);
1960 }
1961 }
1962 $page->assign('people', implode("\n", $display));
1963 $page->assign('promotion', $promotion);
1964 $page->assign('degree', $degree);
1965
1966 if (Post::has('add')) {
1967 $entry_year = $promotion - Profile::educationDuration($degree);
1968
1969 if (Post::b('force_addition')) {
1970 $pids = array_unique(array_merge($old_pids, $new_pids));
1971 } else {
1972 $pids = array_unique($new_pids);
1973
1974 // Updates years.
1975 if (count($old_pids)) {
1976 XDB::execute('UPDATE profile_education
1977 SET entry_year = {?}, grad_year = {?}, promo_year = {?}
1978 WHERE pid IN {?} AND eduid = {?} AND degreeid = {?}',
1979 $entry_year, $promotion, $promotion, $old_pids, $edu_id, $degree_id);
1980 }
1981 }
1982
1983 // Precomputes values common to all users.
1984 $select = XDB::format('MAX(id) + 1, pid, {?}, {?}, {?}, {?}, {?}, \'secondary\'',
1985 $edu_id, $degree_id, $entry_year, $promotion, $promotion );
1986 XDB::startTransaction();
1987 foreach ($pids as $pid) {
1988 XDB::execute('INSERT INTO profile_education (id, pid, eduid, degreeid, entry_year, grad_year, promo_year, flags)
1989 SELECT ' . $select . '
1990 FROM profile_education
1991 WHERE pid = {?}
1992 GROUP BY pid',
1993 $pid);
1994 }
1995 XDB::commit();
1996 }
1997
1998 }
1999 }
2000
2001 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
2002 ?>