Fixes best_domain initialization.
[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_PASSWD, '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_PASSWD, 'admin'),
31 'admin/dead-but-active' => $this->make_hook('dead_but_active', AUTH_PASSWD, 'admin'),
32 'admin/deaths' => $this->make_hook('deaths', AUTH_PASSWD, 'admin'),
33 'admin/downtime' => $this->make_hook('downtime', AUTH_PASSWD, 'admin'),
34 'admin/homonyms' => $this->make_hook('homonyms', AUTH_PASSWD, 'admin'),
35 'admin/logger' => $this->make_hook('logger', AUTH_PASSWD, 'admin'),
36 'admin/logger/actions' => $this->make_hook('logger_actions', AUTH_PASSWD, 'admin'),
37 'admin/postfix/blacklist' => $this->make_hook('postfix_blacklist', AUTH_PASSWD, 'admin'),
38 'admin/postfix/delayed' => $this->make_hook('postfix_delayed', AUTH_PASSWD, 'admin'),
39 'admin/postfix/regexp_bounces' => $this->make_hook('postfix_regexpsbounces', AUTH_PASSWD, 'admin'),
40 'admin/postfix/whitelist' => $this->make_hook('postfix_whitelist', AUTH_PASSWD, 'admin'),
41 'admin/mx/broken' => $this->make_hook('mx_broken', AUTH_PASSWD, 'admin'),
42 'admin/skins' => $this->make_hook('skins', AUTH_PASSWD, 'admin'),
43 'admin/user' => $this->make_hook('user', AUTH_PASSWD, 'admin'),
44 'admin/add_accounts' => $this->make_hook('add_accounts', AUTH_PASSWD, 'admin'),
45 'admin/validate' => $this->make_hook('validate', AUTH_PASSWD, 'admin,edit_directory'),
46 'admin/validate/answers' => $this->make_hook('validate_answers', AUTH_PASSWD, 'admin'),
47 'admin/wiki' => $this->make_hook('wiki', AUTH_PASSWD, 'admin'),
48 'admin/ipwatch' => $this->make_hook('ipwatch', AUTH_PASSWD, 'admin'),
49 'admin/icons' => $this->make_hook('icons', AUTH_PASSWD, 'admin'),
50 'admin/geocoding' => $this->make_hook('geocoding', AUTH_PASSWD, 'admin'),
51 'admin/accounts' => $this->make_hook('accounts', AUTH_PASSWD, 'admin'),
52 'admin/account/watch' => $this->make_hook('account_watch', AUTH_PASSWD, 'admin'),
53 'admin/account/types' => $this->make_hook('account_types', AUTH_PASSWD, 'admin'),
54 'admin/xnet_without_group' => $this->make_hook('xnet_without_group', AUTH_PASSWD, 'admin'),
55 'admin/jobs' => $this->make_hook('jobs', AUTH_PASSWD, 'admin,edit_directory'),
56 'admin/profile' => $this->make_hook('profile', AUTH_PASSWD, 'admin,edit_directory'),
57 'admin/phd' => $this->make_hook('phd', AUTH_PASSWD, 'admin'),
58 'admin/add_secondary_edu' => $this->make_hook('add_secondary_edu', AUTH_PASSWD, '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 require_once 'name.func.inc.php';
455 $name_update = false;
456 $lastname = capitalize_name(Post::t('lastname'));
457 $firstname = capitalize_name(Post::t('firstname'));
458 if ($lastname != $user->lastname) {
459 $to_update['lastname'] = $lastname;
460 $name_update = true;
461 }
462 if (Post::s('type') != 'virtual' && $firstname != $user->firstname) {
463 $to_update['firstname'] = $firstname;
464 $name_update = true;
465 }
466 if ($name_update) {
467 if (Post::s('type') == 'virtual') {
468 $firstname = '';
469 }
470 $to_update['full_name'] = build_full_name($firstname, $lastname);
471 $to_update['directory_name'] = build_directory_name($firstname, $lastname);
472 $to_update['sort_name'] = build_sort_name($firstname, $lastname);
473 }
474 if (Post::s('display_name') != $user->displayName()) {
475 $to_update['display_name'] = Post::s('display_name');
476 }
477 }
478 if (Post::s('sex') != ($user->isFemale() ? 'female' : 'male')) {
479 $to_update['sex'] = Post::s('sex');
480 if ($user->hasProfile()) {
481 XDB::execute('UPDATE profiles
482 SET sex = {?}
483 WHERE pid = {?}',
484 Post::s('sex'), $user->profile()->id());
485 }
486 }
487 if (!Post::blank('pwhash')) {
488 $to_update['password'] = Post::s('pwhash');
489 require_once 'googleapps.inc.php';
490 $account = new GoogleAppsAccount($user);
491 if ($account->active() && $account->sync_password) {
492 $account->set_password(Post::s('pwhash'));
493 }
494 }
495 if (!Post::blank('weak_password')) {
496 $to_update['weak_password'] = Post::s('weak_password');
497 }
498 if (Post::i('token_access', 0) != ($user->token_access ? 1 : 0)) {
499 $to_update['token'] = Post::i('token_access') ? rand_url_id(16) : null;
500 }
501 if (Post::i('skin') != $user->skin) {
502 $to_update['skin'] = Post::i('skin');
503 if ($to_update['skin'] == 0) {
504 $to_update['skin'] = null;
505 }
506 }
507 if (Post::s('state') != $user->state) {
508 $to_update['state'] = Post::s('state');
509 }
510 if (Post::i('is_admin', 0) != ($user->is_admin ? 1 : 0)) {
511 $to_update['is_admin'] = Post::b('is_admin');
512 }
513 if (Post::s('type') != $user->type) {
514 $to_update['type'] = Post::s('type');
515 }
516 if (Post::i('watch', 0) != ($user->watch ? 1 : 0)) {
517 $to_update['flags'] = new PlFlagset();
518 $to_update['flags']->addFlag('watch', Post::i('watch'));
519 }
520 if (Post::t('comment') != $user->comment) {
521 $to_update['comment'] = Post::blank('comment') ? null : Post::t('comment');
522 }
523 $new_email = strtolower(Post::t('email'));
524 if (require_email_update($user, $new_email)) {
525 $to_update['email'] = $new_email;
526 $listClient->change_user_email($user->forlifeEmail(), $new_email);
527 update_alias_user($user->forlifeEmail(), $new_email);
528 }
529 }
530 if (!empty($to_update)) {
531 $res = XDB::query('SELECT *
532 FROM accounts
533 WHERE uid = {?}', $user->id());
534 $oldValues = $res->fetchAllAssoc();
535 $oldValues = $oldValues[0];
536
537 $set = array();
538 $diff = array();
539 foreach ($to_update as $k => $value) {
540 $value = XDB::format('{?}', $value);
541 $set[] = $k . ' = ' . $value;
542 $diff[$k] = array($oldValues[$k], trim($value, "'"));
543 unset($oldValues[$k]);
544 }
545 XDB::rawExecute('UPDATE accounts
546 SET ' . implode(', ', $set) . '
547 WHERE uid = ' . XDB::format('{?}', $user->id()));
548 $page->trigSuccess('Données du compte mise à jour avec succès');
549 $user = User::getWithUID($user->id());
550
551 /* Formats the $diff and send it to the site administrators. The rules are the folowing:
552 * -formats: password, token, weak_password
553 */
554 foreach (array('password', 'token', 'weak_password') as $key) {
555 if (isset($diff[$key])) {
556 $diff[$key] = array('old value', 'new value');
557 } else {
558 $oldValues[$key] = 'old value';
559 }
560 }
561
562 $mail = new PlMailer('admin/useredit.mail.tpl');
563 $mail->assign('admin', S::user()->hruid);
564 $mail->assign('hruid', $user->hruid);
565 $mail->assign('diff', $diff);
566 $mail->assign('oldValues', $oldValues);
567 $mail->send();
568 }
569 // }}}
570
571 // Profile form {{{
572 if (Post::has('add_profile') || Post::has('del_profile') || Post::has('owner')) {
573 if (Post::i('del_profile', 0) != 0) {
574 XDB::execute('DELETE FROM account_profiles
575 WHERE uid = {?} AND pid = {?}',
576 $user->id(), Post::i('del_profile'));
577 } else if (!Post::blank('new_profile')) {
578 $profile = Profile::get(Post::t('new_profile'));
579 if (!$profile) {
580 $page->trigError('Le profil ' . Post::t('new_profile') . ' n\'existe pas');
581 } else {
582 XDB::execute('INSERT IGNORE INTO account_profiles (uid, pid)
583 VALUES ({?}, {?})',
584 $user->id(), $profile->id());
585 }
586 }
587 XDB::execute('UPDATE account_profiles
588 SET perms = IF(pid = {?}, CONCAT(perms, \',owner\'), REPLACE(perms, \'owner\', \'\'))
589 WHERE uid = {?}',
590 Post::i('owner'), $user->id());
591 }
592 // }}}
593
594 // Email forwards form {{{
595 $redirect = ($registered ? new Redirect($user) : null);
596 if (Post::has('add_fwd')) {
597 $email = Post::t('email');
598 if (!isvalid_email_redirection($email, $user)) {
599 $page->trigError("Email non valide: $email");
600 } else {
601 $redirect->add_email($email);
602 $page->trigSuccess("Ajout de $email effectué");
603 }
604 } else if (!Post::blank('del_fwd')) {
605 $redirect->delete_email(Post::t('del_fwd'));
606 } else if (!Post::blank('activate_fwd')) {
607 $redirect->modify_one_email(Post::t('activate_fwd'), true);
608 } else if (!Post::blank('deactivate_fwd')) {
609 $redirect->modify_one_email(Post::t('deactivate_fwd'), false);
610 } else if (Post::has('disable_fwd')) {
611 $redirect->disable();
612 } else if (Post::has('enable_fwd')) {
613 $redirect->enable();
614 } else if (!Post::blank('clean_fwd')) {
615 $redirect->clean_errors(Post::t('clean_fwd'));
616 }
617 // }}}
618
619 // Email alias form {{{
620 if (Post::has('add_alias')) {
621 // Splits new alias in user and fqdn.
622 $alias = Env::t('email');
623 if (strpos($alias, '@') !== false) {
624 list($alias, $domain) = explode('@', $alias);
625 } else {
626 $domain = $user->mainEmailDomain();
627 }
628
629 // Checks for alias' user validity.
630 if (!preg_match('/[-a-z0-9\.]+/s', $alias)) {
631 $page->trigError("'$alias' n'est pas un alias valide");
632 }
633
634 // Eventually adds the alias to the right domain.
635 if ($domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2) {
636 $req = new AliasReq($user, $alias, 'Admin request', false);
637 if ($req->commit()) {
638 $page->trigSuccess("Nouvel alias '$alias@$domain' attribué.");
639 } else {
640 $page->trigError("Impossible d'ajouter l'alias '$alias@$domain', il est probablement déjà attribué.");
641 }
642 } elseif ($domain == $user->mainEmailDomain()) {
643 XDB::execute('INSERT INTO email_source_account (email, uid, domain, type, flags)
644 SELECT {?}, {?}, id, \'alias\', \'\'
645 FROM email_virtual_domains
646 WHERE name = {?}',
647 $alias, $user->id(), $domain);
648 $page->trigSuccess("Nouvel alias '$alias' ajouté");
649 } else {
650 $page->trigError("Le domaine '$domain' n'est pas valide pour cet utilisateur.");
651 }
652 } else if (!Post::blank('del_alias')) {
653 $delete_alias = Post::t('del_alias');
654 list($email, $domain) = explode('@', $delete_alias);
655 XDB::execute('DELETE s
656 FROM email_source_account AS s
657 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
658 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
659 WHERE s.email = {?} AND s.uid = {?} AND d.name = {?} AND type != \'forlife\'',
660 $email, $user->id(), $domain);
661 XDB::execute('UPDATE email_redirect_account AS r
662 INNER JOIN email_virtual_domains AS m ON (m.name = {?})
663 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
664 SET r.rewrite = \'\'
665 WHERE r.uid = {?} AND r.rewrite = CONCAT({?}, \'@\', d.name)',
666 $domain, $user->id(), $email);
667 fix_bestalias($user);
668 $page->trigSuccess("L'alias '$delete_alias' a été supprimé");
669 } else if (!Post::blank('best')) {
670 $best_alias = Post::t('best');
671 // First delete the bestalias flag from all this user's emails.
672 XDB::execute("UPDATE email_source_account
673 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
674 WHERE uid = {?}", $user->id());
675 // Then gives the bestalias flag to the given email.
676 list($email, $domain) = explode('@', $best_alias);
677 XDB::execute("UPDATE email_source_account
678 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
679 WHERE uid = {?} AND email = {?}", $user->id(), $email);
680
681 // As having a non-null bestalias value is critical in
682 // plat/al's code, we do an a posteriori check on the
683 // validity of the bestalias.
684 fix_bestalias($user);
685 }
686 // }}}
687
688 // OpenId form {{{
689 if (Post::has('del_openid')) {
690 XDB::execute('DELETE FROM account_auth_openid
691 WHERE id = {?}', Post::i('del_openid'));
692 }
693 // }}}
694
695 // Forum form {{{
696 if (Post::has('b_edit')) {
697 XDB::execute("DELETE FROM forum_innd
698 WHERE uid = {?}", $user->id());
699 if (Env::v('write_perm') != "" || Env::v('read_perm') != "" || Env::v('commentaire') != "" ) {
700 XDB::execute("INSERT INTO forum_innd
701 SET ipmin = '0', ipmax = '4294967295',
702 write_perm = {?}, read_perm = {?},
703 comment = {?}, priority = '200', uid = {?}",
704 Env::v('write_perm'), Env::v('read_perm'), Env::v('comment'), $user->id());
705 }
706 }
707 // }}}
708
709
710 $page->addJsLink('jquery.ui.xorg.js');
711
712 // Displays last login and last host information.
713 $res = XDB::query("SELECT start, host
714 FROM log_sessions
715 WHERE uid = {?} AND suid = 0
716 ORDER BY start DESC
717 LIMIT 1", $user->id());
718 list($lastlogin,$host) = $res->fetchOneRow();
719 $page->assign('lastlogin', $lastlogin);
720 $page->assign('host', $host);
721
722 // Display mailing lists
723 $page->assign('mlists', $listClient->get_all_user_lists($user->forlifeEmail()));
724
725 // Display active aliases.
726 $page->assign('virtuals', $user->emailGroupAliases());
727 $aliases = XDB::iterator("SELECT CONCAT(s.email, '@', d.name) AS email, (s.type = 'forlife') AS forlife,
728 (s.email REGEXP '\\\\.[0-9]{2}$') AS hundred_year,
729 FIND_IN_SET('bestalias', s.flags) AS bestalias, s.expire,
730 (s.type = 'alias_aux') AS alias
731 FROM email_source_account AS s
732 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
733 WHERE s.uid = {?}
734 ORDER BY !alias, s.email",
735 $user->id());
736 $page->assign('aliases', $aliases);
737 $page->assign('account_types', XDB::iterator('SELECT * FROM account_types ORDER BY type'));
738 $page->assign('skins', XDB::iterator('SELECT id, name FROM skins ORDER BY name'));
739 $page->assign('profiles', XDB::iterator('SELECT p.pid, p.hrpid, FIND_IN_SET(\'owner\', ap.perms) AS owner
740 FROM account_profiles AS ap
741 INNER JOIN profiles AS p ON (ap.pid = p.pid)
742 WHERE ap.uid = {?}', $user->id()));
743 $page->assign('openid', XDB::iterator('SELECT id, url
744 FROM account_auth_openid
745 WHERE uid = {?}', $user->id()));
746
747 // Displays email redirection and the general profile.
748 if ($registered && $redirect) {
749 $page->assign('emails', $redirect->emails);
750 }
751
752 $page->assign('user', $user);
753 $page->assign('hasProfile', $user->hasProfile());
754
755 // Displays forum bans.
756 $res = XDB::query("SELECT write_perm, read_perm, comment
757 FROM forum_innd
758 WHERE uid = {?}", $user->id());
759 $bans = $res->fetchOneAssoc();
760 $page->assign('bans', $bans);
761 }
762
763 private static function getHrid($firstname, $lastname, $promo)
764 {
765 if ($firstname != null && $lastname != null && $promo != null) {
766 return User::makeHrid($firstname, $lastname, $promo);
767 }
768 return null;
769 }
770
771 private static function formatNewUser($page, $infosLine, $separator, $promo, $size)
772 {
773 $infos = explode($separator, $infosLine);
774 if (sizeof($infos) > $size || sizeof($infos) < 2) {
775 $page->trigError("La ligne $infosLine n'a pas été ajoutée.");
776 return false;
777 }
778
779 $infos = array_map('trim', $infos);
780 $hrid = self::getHrid($infos[1], $infos[0], $promo);
781 $res1 = XDB::query('SELECT COUNT(*)
782 FROM accounts
783 WHERE hruid = {?}', $hrid);
784 $res2 = XDB::query('SELECT COUNT(*)
785 FROM profiles
786 WHERE hrpid = {?}', $hrid);
787 if (is_null($hrid) || $res1->fetchOneCell() > 0 || $res2->fetchOneCell() > 0) {
788 $page->trigError("La ligne $infosLine n'a pas été ajoutée: une entrée similaire existe déjà");
789 return false;
790 }
791 $infos['hrid'] = $hrid;
792 return $infos;
793 }
794
795 private static function formatSex($page, $sex, $line)
796 {
797 switch ($sex) {
798 case 'F':
799 return 'female';
800 case 'M':
801 return 'male';
802 default:
803 $page->trigError("La ligne $line n'a pas été ajoutée car le sexe $sex n'est pas pris en compte.");
804 return null;
805 }
806 }
807
808 private static function formatBirthDate($birthDate)
809 {
810 // strtotime believes dd/mm/yyyy to be an US date (i.e mm/dd/yyyy), and
811 // dd-mm-yyyy to be a normal date (i.e dd-mm-yyyy)...
812 return date("Y-m-d", strtotime(str_replace('/', '-', $birthDate)));
813 }
814
815 function handler_add_accounts($page, $action = null, $promo = null)
816 {
817 require_once 'name.func.inc.php';
818 $page->changeTpl('admin/add_accounts.tpl');
819
820 if (Env::has('add_type') && Env::has('people')) {
821 static $titles = array('male' => 'M', 'female' => 'MLLE');
822 $lines = explode("\n", Env::t('people'));
823 $separator = Env::t('separator');
824 $promotion = Env::i('promotion');
825
826 if (Env::t('add_type') == 'promo') {
827 $eduSchools = DirEnum::getOptions(DirEnum::EDUSCHOOLS);
828 $eduSchools = array_flip($eduSchools);
829 $eduDegrees = DirEnum::getOptions(DirEnum::EDUDEGREES);
830 $eduDegrees = array_flip($eduDegrees);
831 switch (Env::t('edu_type')) {
832 case 'X':
833 $degreeid = $eduDegrees[Profile::DEGREE_X];
834 $entry_year = $promotion;
835 $grad_year = $promotion + 3;
836 $promo = 'X' . $promotion;
837 $hrpromo = $promotion;
838 $type = 'x';
839 break;
840 case 'M':
841 $degreeid = $eduDegrees[Profile::DEGREE_M];
842 $grad_year = $promotion;
843 $entry_year = $promotion - 2;
844 $promo = 'M' . $promotion;
845 $hrpromo = $promo;
846 $type = 'master';
847 break;
848 case 'D':
849 $degreeid = $eduDegrees[Profile::DEGREE_D];
850 $grad_year = $promotion;
851 $entry_year = $promotion - 3;
852 $promo = 'D (en cours)';
853 $hrpromo = 'D' . $promotion;
854 $type = 'phd';
855 break;
856 default:
857 $page->killError("La formation n'est pas reconnue : " . Env::t('edu_type') . '.');
858 }
859 $best_domain = XDB::fetchOneCell('SELECT id
860 FROM email_virtual_domains
861 WHERE name = {?}',
862 User::$sub_mail_domains[$type] . Platal::globals()->mail->domain);
863
864 XDB::startTransaction();
865 foreach ($lines as $line) {
866 if ($infos = self::formatNewUser($page, $line, $separator, $hrpromo, 6)) {
867 $sex = self::formatSex($page, $infos[3], $line);
868 $lastname = capitalize_name($infos[0]);
869 $firstname = capitalize_name($infos[1]);
870 if (!is_null($sex)) {
871 $fullName = build_full_name($firstname, $lastname);
872 $directoryName = build_directory_name($firstname, $lastname);
873 $sortName = build_sort_name($firstname, $lastname);
874 $birthDate = self::formatBirthDate($infos[2]);
875 if ($type == 'x') {
876 $xorgId = Profile::getXorgId($infos[4]);
877 } elseif (isset($infos[4])) {
878 $xorgId = trim($infos[4]);
879 } else {
880 $xorgId = 0;
881 }
882 if (is_null($xorgId)) {
883 $page->trigError("La ligne $line n'a pas été ajoutée car le matricule École est mal renseigné.");
884 continue;
885 }
886
887 XDB::execute('INSERT INTO profiles (hrpid, xorg_id, ax_id, birthdate_ref, sex, title)
888 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
889 $infos['hrid'], $xorgId, (isset($infos[5]) ? $infos[5] : null),
890 $birthDate, $sex, $titles[$sex]);
891 $pid = XDB::insertId();
892 XDB::execute('INSERT INTO profile_public_names (pid, lastname_initial, lastname_main, firstname_initial, firstname_main)
893 VALUES ({?}, {?}, {?}, {?}, {?})',
894 $pid, $lastname, $lastname, $firstname, $firstname);
895 XDB::execute('INSERT INTO profile_display (pid, yourself, public_name, private_name,
896 directory_name, short_name, sort_name, promo)
897 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
898 $pid, $firstname, $fullName, $fullName, $directoryName, $fullName, $sortName, $promo);
899 XDB::execute('INSERT INTO profile_education (id, pid, eduid, degreeid, entry_year, grad_year, promo_year, flags)
900 VALUES (100, {?}, {?}, {?}, {?}, {?}, {?}, \'primary\')',
901 $pid, $eduSchools[Profile::EDU_X], $degreeid, $entry_year, $grad_year, $promotion);
902 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, full_name, directory_name,
903 display_name, sort_name, lastname, firstname, sex, best_domain)
904 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
905 $infos['hrid'], $type, 0, 'pending', $fullName, $directoryName, $sortName,
906 $firstname, $lastname, $firstname, $sex, $best_domain);
907 $uid = XDB::insertId();
908 XDB::execute('INSERT INTO account_profiles (uid, pid, perms)
909 VALUES ({?}, {?}, {?})',
910 $uid, $pid, 'owner');
911 Profile::rebuildSearchTokens($pid, false);
912 }
913 }
914 }
915 XDB::commit();
916 } else if (Env::t('add_type') == 'account') {
917 $type = Env::t('type');
918 $newAccounts = array();
919 foreach ($lines as $line) {
920 if ($infos = self::formatNewUser($page, $line, $separator, $type, 4)) {
921 $sex = self::formatSex($page, $infos[3], $line);
922 if (!is_null($sex)) {
923 $lastname = capitalize_name($infos[0]);
924 $firstname = capitalize_name($infos[1]);
925 $fullName = build_full_name($firstname, $lastname);
926 $directoryName = build_directory_name($firstname, $lastname);
927 $sortName = build_sort_name($firstname, $lastname);
928 XDB::execute('INSERT INTO accounts (hruid, type, is_admin, state, email, full_name, directory_name,
929 sort_name, display_name, lastname, firstname, sex)
930 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
931 $infos['hrid'], $type, 0, 'pending', $infos[2], $fullName, $directoryName,
932 $sortName ,$firstname, $lastname, $firstname, $sex);
933 $newAccounts[$infos['hrid']] = $fullName;
934 }
935 }
936 }
937 if (!empty($newAccounts)) {
938 $page->assign('newAccounts', $newAccounts);
939 }
940 } else if (Env::t('add_type') == 'ax_id') {
941 $type = 'x';
942 foreach ($lines as $line) {
943 if ($infos = self::formatNewUser($page, $line, $separator, $promotion, 3)) {
944 XDB::execute('UPDATE profiles
945 SET ax_id = {?}
946 WHERE hrpid = {?}',
947 $infos[2], $infos['hrid']);
948 }
949 }
950 }
951
952 $errors = $page->nb_errs();
953 if ($errors == 0) {
954 $page->trigSuccess("L'opération a été effectuée avec succès.");
955 } else {
956 $page->trigSuccess('L\'opération a été effectuée avec succès, sauf pour '
957 . (($errors == 1) ? 'l\'erreur signalée' : "les $errors erreurs signalées") . ' ci-dessus.');
958 }
959 } else if (Env::has('add_type')) {
960 $res = XDB::query('SELECT type
961 FROM account_types');
962 $page->assign('account_types', $res->fetchColumn());
963 $page->assign('add_type', Env::s('add_type'));
964 }
965 }
966
967 function handler_homonyms($page, $op = 'list', $target = null)
968 {
969 $page->changeTpl('admin/homonymes.tpl');
970 $page->setTitle('Administration - Homonymes');
971 $this->load("homonyms.inc.php");
972
973 if ($target) {
974 $user = User::getSilentWithUID($target);
975 if (!$user || !($loginbis = select_if_homonym($user))) {
976 $target = 0;
977 } else {
978 $page->assign('user', $user);
979 $page->assign('loginbis',$loginbis);
980 }
981 }
982
983 $page->assign('op', $op);
984 $page->assign('target', $target);
985
986 // When we have a valid target, prepare emails.
987 if ($target) {
988 // Examine what operation needs to be performed.
989 switch ($op) {
990 case 'mail':
991 S::assert_xsrf_token();
992
993 send_warning_homonym($user, $loginbis);
994 $op = 'list';
995 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . '.');
996 break;
997
998 case 'correct':
999 S::assert_xsrf_token();
1000
1001 fix_homonym($user, $loginbis);
1002 send_robot_homonym($user, $loginbis);
1003 $op = 'list';
1004 $page->trigSuccess('Email envoyé à ' . $user->forlifeEmail() . ', alias supprimé.');
1005 break;
1006 }
1007 }
1008
1009 if ($op == 'list') {
1010 // Retrieves homonyms that are already been fixed.
1011 $res = XDB::iterator('SELECT o.email AS homonym, f.email AS forlife, o.expire, f.uid
1012 FROM email_source_other AS o
1013 INNER JOIN homonyms_list AS h ON (o.hrmid = h.hrmid)
1014 INNER JOIN email_source_account AS f ON (h.uid = f.uid AND f.type = \'forlife\')
1015 WHERE o.expire IS NOT NULL
1016 ORDER BY homonym, forlife');
1017 $homonyms = array();
1018 while ($item = $res->next()) {
1019 $homonyms[$item['homonym']][] = $item;
1020 }
1021 $page->assign_by_ref('homonyms', $homonyms);
1022
1023 // Retrieves homonyms that needs to be fixed.
1024 $res = XDB::iterator('SELECT e.email AS homonym, f.email AS forlife, e.expire, e.uid, (e.expire < NOW()) AS urgent
1025 FROM email_source_account AS e
1026 INNER JOIN homonyms_list AS l ON (e.uid = l.uid)
1027 INNER JOIN homonyms_list AS h ON (l.hrmid = h.hrmid)
1028 INNER JOIN email_source_account AS f ON (h.uid = f.uid AND f.type = \'forlife\')
1029 WHERE e.expire IS NOT NULL
1030 ORDER BY homonym, forlife');
1031 $homonyms_to_fix = array();
1032 while ($item = $res->next()) {
1033 $homonyms_to_fix[$item['homonym']][] = $item;
1034 }
1035 $page->assign_by_ref('homonyms_to_fix', $homonyms_to_fix);
1036 }
1037
1038 if ($op == 'correct-conf') {
1039 $page->assign('robot_mail_text', get_robot_mail_text($user, $loginbis));
1040 }
1041
1042 if ($op == 'mail-conf') {
1043 $page->assign('warning_mail_text', get_warning_mail_text($user, $loginbis));
1044 }
1045 }
1046
1047 function handler_deaths($page, $promo = 0, $validate = false)
1048 {
1049 $page->changeTpl('admin/deces_promo.tpl');
1050 $page->setTitle('Administration - Deces');
1051
1052 if (!$promo) {
1053 $promo = Env::t('promo', 'X1923');
1054 }
1055 $page->assign('promo', $promo);
1056 if (!$promo) {
1057 return;
1058 }
1059
1060 if ($validate) {
1061 S::assert_xsrf_token();
1062
1063 $res = XDB::iterRow('SELECT p.pid, pd.directory_name, p.deathdate
1064 FROM profiles AS p
1065 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1066 WHERE pd.promo = {?}', $promo);
1067 while (list($pid, $name, $death) = $res->next()) {
1068 $val = Env::v('death_' . $pid);
1069 if ($val == $death) {
1070 continue;
1071 }
1072
1073 if (empty($val)) {
1074 $val = null;
1075 }
1076 XDB::execute('UPDATE profiles
1077 SET deathdate = {?}, deathdate_rec = NOW()
1078 WHERE pid = {?}', $val, $pid);
1079
1080 $page->trigSuccess('Édition du décès de ' . $name . ' (' . ($val ? $val : 'ressuscité') . ').');
1081 if ($val && ($death == '0000-00-00' || empty($death))) {
1082 $profile = Profile::get($pid);
1083 $profile->clear();
1084 $profile->owner()->clear(false);
1085 }
1086 }
1087 }
1088
1089 $res = XDB::iterator('SELECT p.pid, pd.directory_name, p.deathdate
1090 FROM profiles AS p
1091 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
1092 WHERE pd.promo = {?}
1093 ORDER BY pd.sort_name', $promo);
1094 $page->assign('profileList', $res);
1095 }
1096
1097 function handler_dead_but_active($page)
1098 {
1099 $page->changeTpl('admin/dead_but_active.tpl');
1100 $page->setTitle('Administration - Décédés');
1101
1102 $res = XDB::iterator(
1103 "SELECT a.hruid, pd.promo, p.ax_id, pd.directory_name, p.deathdate, DATE(MAX(s.start)) AS last
1104 FROM accounts AS a
1105 INNER JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET('owner', ap.perms))
1106 INNER JOIN profiles AS p ON (p.pid = ap.pid)
1107 INNER JOIN profile_display AS pd ON (pd.pid = p.pid)
1108 LEFT JOIN log_sessions AS s ON (s.uid = a.uid AND suid = 0)
1109 WHERE a.state = 'active' AND p.deathdate IS NOT NULL
1110 GROUP BY a.uid
1111 ORDER BY pd.promo, pd.sort_name");
1112 $page->assign('dead', $res);
1113 }
1114
1115 function handler_validate($page, $action = 'list', $id = null)
1116 {
1117 $page->changeTpl('admin/validation.tpl');
1118 $page->setTitle('Administration - Valider une demande');
1119 $page->addCssLink('nl.Polytechnique.org.css');
1120
1121 if ($action == 'edit' && !is_null($id)) {
1122 $page->assign('preview_id', $id);
1123 } else {
1124 $page->assign('preview_id', null);
1125 }
1126
1127 if(Env::has('uid') && Env::has('type') && Env::has('stamp')) {
1128 S::assert_xsrf_token();
1129
1130 $req = Validate::get_typed_request(Env::v('uid'), Env::v('type'), Env::v('stamp'));
1131 if ($req) {
1132 $req->handle_formu();
1133 } else {
1134 $page->trigWarning('La validation a déjà été effectuée.');
1135 }
1136 }
1137
1138 $r = XDB::iterator('SHOW COLUMNS FROM requests_answers');
1139 while (($a = $r->next()) && $a['Field'] != 'category');
1140 $page->assign('categories', $categories = explode(',', str_replace("'", '', substr($a['Type'], 5, -1))));
1141
1142 $hidden = array();
1143 $res = XDB::query('SELECT hidden_requests
1144 FROM requests_hidden
1145 WHERE uid = {?}', S::v('uid'));
1146 $hide_requests = $res->fetchOneCell();
1147 if (Post::has('hide')) {
1148 $hide = array();
1149 foreach ($categories as $cat)
1150 if (!Post::v($cat)) {
1151 $hidden[$cat] = 1;
1152 $hide[] = $cat;
1153 }
1154 $hide_requests = join(',', $hide);
1155 XDB::query('INSERT INTO requests_hidden (uid, hidden_requests)
1156 VALUES ({?}, {?})
1157 ON DUPLICATE KEY UPDATE hidden_requests = VALUES(hidden_requests)',
1158 S::v('uid'), $hide_requests);
1159 } elseif ($hide_requests) {
1160 foreach (explode(',', $hide_requests) as $hide_type)
1161 $hidden[$hide_type] = true;
1162 }
1163 $page->assign('hide_requests', $hidden);
1164
1165 // Update the count of item to validate here... useful in development configuration
1166 // where several copies of the site use the same DB, but not the same "dynamic configuration"
1167 global $globals;
1168 $globals->updateNbValid();
1169 $page->assign('vit', Validate::iterate());
1170 $page->assign('isAdmin', S::admin());
1171 }
1172
1173 function handler_validate_answers($page, $action = 'list', $id = null)
1174 {
1175 $page->setTitle('Administration - Réponses automatiques de validation');
1176 $page->assign('title', 'Gestion des réponses automatiques');
1177 $table_editor = new PLTableEditor('admin/validate/answers','requests_answers','id');
1178 $table_editor->describe('category','catégorie',true);
1179 $table_editor->describe('title','titre',true);
1180 $table_editor->describe('answer','texte',false, true);
1181 $table_editor->apply($page, $action, $id);
1182 }
1183
1184 function handler_skins($page, $action = 'list', $id = null)
1185 {
1186 $page->setTitle('Administration - Skins');
1187 $page->assign('title', 'Gestion des skins');
1188 $table_editor = new PLTableEditor('admin/skins','skins','id');
1189 $table_editor->describe('name','nom',true);
1190 $table_editor->describe('skin_tpl','nom du template',true);
1191 $table_editor->describe('auteur','auteur',false, true);
1192 $table_editor->describe('comment','commentaire',true);
1193 $table_editor->describe('date','date',false, true);
1194 $table_editor->describe('ext','extension du screenshot',false, true);
1195 $table_editor->apply($page, $action, $id);
1196 }
1197
1198 function handler_postfix_blacklist($page, $action = 'list', $id = null)
1199 {
1200 $page->setTitle('Administration - Postfix : Blacklist');
1201 $page->assign('title', 'Blacklist de postfix');
1202 $table_editor = new PLTableEditor('admin/postfix/blacklist','postfix_blacklist','email', true);
1203 $table_editor->describe('reject_text','Texte de rejet',true);
1204 $table_editor->describe('email','email',true);
1205 $table_editor->apply($page, $action, $id);
1206 }
1207
1208 function handler_postfix_whitelist($page, $action = 'list', $id = null)
1209 {
1210 $page->setTitle('Administration - Postfix : Whitelist');
1211 $page->assign('title', 'Whitelist de postfix');
1212 $table_editor = new PLTableEditor('admin/postfix/whitelist','postfix_whitelist','email', true);
1213 $table_editor->describe('email','email',true);
1214 $table_editor->apply($page, $action, $id);
1215 }
1216
1217 function handler_mx_broken($page, $action = 'list', $id = null)
1218 {
1219 $page->setTitle('Administration - MX Défaillants');
1220 $page->assign('title', 'MX Défaillant');
1221 $table_editor = new PLTableEditor('admin/mx/broken', 'mx_watch', 'host', true);
1222 $table_editor->describe('host', 'Masque', true);
1223 $table_editor->describe('state', 'Niveau', true);
1224 $table_editor->describe('text', 'Description du problème', false, true);
1225 $table_editor->apply($page, $action, $id);
1226 }
1227
1228 function handler_logger_actions($page, $action = 'list', $id = null)
1229 {
1230 $page->setTitle('Administration - Actions');
1231 $page->assign('title', 'Gestion des actions de logger');
1232 $table_editor = new PLTableEditor('admin/logger/actions','log_actions','id');
1233 $table_editor->describe('text','intitulé',true);
1234 $table_editor->describe('description','description',true);
1235 $table_editor->apply($page, $action, $id);
1236 }
1237
1238 function handler_downtime($page, $action = 'list', $id = null)
1239 {
1240 $page->setTitle('Administration - Coupures');
1241 $page->assign('title', 'Gestion des coupures');
1242 $table_editor = new PLTableEditor('admin/downtime','downtimes','id');
1243 $table_editor->describe('debut','date',true);
1244 $table_editor->describe('duree','durée',false, true);
1245 $table_editor->describe('resume','résumé',true);
1246 $table_editor->describe('services','services affectés',true);
1247 $table_editor->describe('description','description',false, true);
1248 $table_editor->apply($page, $action, $id);
1249 }
1250
1251 private static function isCountryIncomplete(array &$item)
1252 {
1253 $warning = false;
1254 foreach (array('worldRegion', 'country', 'capital', 'phonePrefix', 'licensePlate', 'countryPlain') as $field) {
1255 if ($item[$field] == '') {
1256 $item[$field . '_warning'] = true;
1257 $warning = true;
1258 }
1259 }
1260 if (is_null($item['belongsTo'])) {
1261 foreach (array('nationality', 'nationalityEn') as $field) {
1262 if ($item[$field] == '') {
1263 $item[$field . '_warning'] = true;
1264 $warning = true;
1265 }
1266 }
1267 }
1268 return $warning;
1269 }
1270
1271 private static function updateCountry(array $item)
1272 {
1273 XDB::execute('UPDATE geoloc_countries
1274 SET countryPlain = {?}
1275 WHERE iso_3166_1_a2 = {?}',
1276 mb_strtoupper(replace_accent($item['country'])), $item['iso_3166_1_a2']);
1277 }
1278
1279 private static function isLanguageIncomplete(array &$item)
1280 {
1281 if ($item['language'] == '') {
1282 $item['language_warning'] = true;
1283 return true;
1284 }
1285 return false;
1286 }
1287
1288 private static function updateLanguage(array $item) {}
1289
1290 function handler_geocoding($page, $category = null, $action = null, $id = null)
1291 {
1292 // Warning, this handler requires the following packages:
1293 // * pkg-isocodes
1294 // * isoquery
1295
1296 static $properties = array(
1297 'country' => array(
1298 'name' => 'pays',
1299 'isocode' => '3166',
1300 'table' => 'geoloc_countries',
1301 'id' => 'iso_3166_1_a2',
1302 'main_fields' => array('iso_3166_1_a3', 'iso_3166_1_num', 'countryEn'),
1303 'other_fields' => array('worldRegion', 'country', 'capital', 'nationality', 'nationalityEn',
1304 'phonePrefix', 'phoneFormat', 'licensePlate', 'belongsTo')
1305 ),
1306 'language' => array(
1307 'name' => 'langages',
1308 'isocode' => '639',
1309 'table' => 'profile_langskill_enum',
1310 'id' => 'iso_639_2b',
1311 'main_fields' => array('iso_639_2t', 'iso_639_1', 'language_en'),
1312 'other_fields' => array('language')
1313
1314 )
1315 );
1316
1317 if (is_null($category) || !array_key_exists($category, $properties)) {
1318 pl_redirect('admin');
1319 }
1320
1321 $data = $properties[$category];
1322
1323 if ($action == 'edit' || $action == 'add') {
1324 $main_fields = array_merge(array($data['id']), $data['main_fields']);
1325 $all_fields = array_merge($main_fields, $data['other_fields']);
1326
1327 if (is_null($id)) {
1328 if (Post::has('new_id')) {
1329 $id = Post::v('new_id');
1330 } else {
1331 pl_redirect('admin/geocoding/' . $category);
1332 }
1333 }
1334
1335 $list = array();
1336 exec('isoquery --iso=' . $data['isocode'] . ' ' . $id, $list);
1337 if (count($list) == 1) {
1338 $array = explode("\t", $list[0]);
1339 foreach ($main_fields as $i => $field) {
1340 $iso[$field] = $array[$i];
1341 }
1342 } else {
1343 $iso = array();
1344 }
1345
1346 if ($action == 'add') {
1347 if (Post::has('new_id')) {
1348 S::assert_xsrf_token();
1349 }
1350
1351 if (count($iso)) {
1352 $item = $iso;
1353 } else {
1354 $item = array($data['id'] => $id);
1355 }
1356 XDB::execute('INSERT INTO ' . $data['table'] . '(' . implode(', ', array_keys($item)) . ')
1357 VALUES ' . XDB::formatArray($item));
1358 $page->trigSuccess($id . ' a bien été ajouté à la base.');
1359 } elseif ($action == 'edit') {
1360 if (Post::has('edit')) {
1361 S::assert_xsrf_token();
1362
1363 $item = array();
1364 $set = array();
1365 foreach ($all_fields as $field) {
1366 $item[$field] = Post::t($field);
1367 $set[] = $field . XDB::format(' = {?}', ($item[$field] ? $item[$field] : null));
1368 }
1369 XDB::execute('UPDATE ' . $data['table'] . '
1370 SET ' . implode(', ', $set) . '
1371 WHERE ' . $data['id'] . ' = {?}',
1372 $id);
1373 call_user_func_array(array('self', 'update' . ucfirst($category)), array($item));
1374 $page->trigSuccess($id . ' a bien été mis à jour.');
1375 } elseif (Post::has('del')) {
1376 S::assert_xsrf_token();
1377
1378 XDB::execute('DELETE FROM ' . $data['table'] . '
1379 WHERE ' . $data['id'] . ' = {?}',
1380 $id);
1381 $page->trigSuccessRedirect($id . ' a bien été supprimé.', 'admin/geocoding/' . $category);
1382 } else {
1383 $item = XDB::fetchOneAssoc('SELECT *
1384 FROM ' . $data['table'] . '
1385 WHERE ' . $data['id'] . ' = {?}',
1386 $id);
1387 }
1388 }
1389
1390 $page->changeTpl('admin/geocoding_edit.tpl');
1391 $page->setTitle('Administration - ' . ucfirst($data['name']));
1392 $page->assign('category', $category);
1393 $page->assign('name', $data['name']);
1394 $page->assign('all_fields', $all_fields);
1395 $page->assign('id', $id);
1396 $page->assign('iso', $iso);
1397 $page->assign('item', $item);
1398 return;
1399 }
1400
1401 $page->changeTpl('admin/geocoding.tpl');
1402 $page->setTitle('Administration - ' . ucfirst($data['name']));
1403 $page->assign('category', $category);
1404 $page->assign('name', $data['name']);
1405 $page->assign('id', $data['id']);
1406 $page->assign('main_fields', $data['main_fields']);
1407 $page->assign('all_fields', array_merge($data['main_fields'], $data['other_fields']));
1408
1409 // First build the list provided by the iso codes.
1410 $list = array();
1411 exec('isoquery --iso=' . $data['isocode'], $list);
1412
1413 foreach ($list as $key => $item) {
1414 $array = explode("\t", $item);
1415 unset($list[$key]);
1416 $list[$array[0]] = array();
1417 foreach ($data['main_fields'] as $i => $field) {
1418 $list[$array[0]][$field] = $array[$i + 1];
1419 }
1420 }
1421 ksort($list);
1422
1423 // Retrieve all data from the database.
1424 $db_list = XDB::rawFetchAllAssoc('SELECT *
1425 FROM ' . $data['table'] . '
1426 ORDER BY ' . $data['id'],
1427 $data['id']);
1428
1429 // Sort both iso and database data into 5 categories:
1430 // $missing: data from the iso list not in the database,
1431 // $non_existing: data from the database not in the iso list,
1432 // $erroneous: data that differ on main fields,
1433 // $incomplete: data with empty fields in the data base,
1434 // $remaining: remaining correct and complete data from the database.
1435
1436 $missing = $non_existing = $erroneous = $incomplete = $remaining = array();
1437 foreach (array_keys($list) as $id) {
1438 if (!array_key_exists($id, $db_list)) {
1439 $missing[$id] = $list[$id];
1440 }
1441 }
1442
1443 foreach ($db_list as $id => $item) {
1444 if (!array_key_exists($id, $list)) {
1445 $non_existing[$id] = $item;
1446 } else {
1447 $error = false;
1448 foreach ($data['main_fields'] as $field) {
1449 if ($item[$field] != $list[$id][$field]) {
1450 $item[$field . '_error'] = true;
1451 $error = true;
1452 }
1453 }
1454 if ($error == true) {
1455 $erroneous[$id] = $item;
1456 } elseif (call_user_func_array(array('self', 'is' . ucfirst($category) . 'Incomplete'), array(&$item))) {
1457 $incomplete[$id] = $item;
1458 } else {
1459 $remaining[$id] = $item;
1460 }
1461 }
1462 }
1463
1464 $page->assign('lists', array(
1465 'manquant' => $missing,
1466 'disparu' => $non_existing,
1467 'erroné' => $erroneous,
1468 'incomplet' => $incomplete,
1469 'restant' => $remaining
1470 ));
1471 }
1472
1473 function handler_accounts(PlPage $page)
1474 {
1475 $page->changeTpl('admin/accounts.tpl');
1476 $page->setTitle('Administration - Comptes');
1477
1478 if (Post::has('create_account')) {
1479 S::assert_xsrf_token();
1480 $firstname = Post::t('firstname');
1481 $lastname = mb_strtoupper(Post::t('lastname'));
1482 $sex = Post::s('sex');
1483 $email = Post::t('email');
1484 $type = Post::s('type');
1485 $login = PlUser::makeHrid($firstname, $lastname, $type);
1486 if (!isvalid_email($email)) {
1487 $page->trigError("Invalid email address: $email");
1488 } else if (strlen(Post::s('pwhash')) != 40) {
1489 $page->trigError("Invalid password hash");
1490 } else {
1491 $full_name = $firstname . ' ' . $lastname;
1492 $directory_name = $lastname . ' ' . $firstname;
1493 XDB::execute("INSERT INTO accounts (hruid, type, state, password,
1494 registration_date, email, full_name,
1495 display_name, sex, directory_name,
1496 lastname, firstname)
1497 VALUES ({?}, {?}, 'active', {?}, NOW(), {?}, {?}, {?}, {?}, {?}, {?}, {?})",
1498 $login, $type, Post::s('pwhash'), $email, $full_name, $full_name, $sex,
1499 $directory_name, $lastname, $firstname);
1500 }
1501 }
1502
1503 $uf = new UserFilter(new UFC_AccountType('ax', 'school', 'fx'));
1504 $page->assign('users', $uf->iterUsers());
1505
1506 }
1507
1508 function handler_account_types($page, $action = 'list', $id = null)
1509 {
1510 $page->setTitle('Administration - Types de comptes');
1511 $page->assign('title', 'Gestion des types de comptes');
1512 $table_editor = new PLTableEditor('admin/account/types', 'account_types', 'type', true);
1513 $table_editor->describe('type', 'Catégorie', true);
1514 $table_editor->describe('perms', 'Permissions associées', true);
1515 $table_editor->apply($page, $action, $id);
1516 }
1517
1518 function handler_wiki($page, $action = 'list', $wikipage = null, $wikipage2 = null)
1519 {
1520 if (S::hasAuthToken()) {
1521 $page->setRssLink('Changement Récents',
1522 '/Site/AllRecentChanges?action=rss&user=' . S::v('hruid') . '&hash=' . S::user()->token);
1523 }
1524
1525 // update wiki perms
1526 if ($action == 'update') {
1527 S::assert_xsrf_token();
1528
1529 $perms_read = Post::v('read');
1530 $perms_edit = Post::v('edit');
1531 if ($perms_read || $perms_edit) {
1532 foreach ($_POST as $wiki_page => $val) {
1533 if ($val == 'on') {
1534 $wp = new PlWikiPage(str_replace(array('_', '/'), '.', $wiki_page));
1535 if ($wp->setPerms($perms_read ? $perms_read : $wp->readPerms(),
1536 $perms_edit ? $perms_edit : $wp->writePerms())) {
1537 $page->trigSuccess("Permission de la page $wiki_page mises à jour");
1538 } else {
1539 $page->trigError("Impossible de mettre les permissions de la page $wiki_page à jour");
1540 }
1541 }
1542 }
1543 }
1544 } else if ($action != 'list' && !empty($wikipage)) {
1545 $wp = new PlWikiPage($wikipage);
1546 S::assert_xsrf_token();
1547
1548 if ($action == 'delete') {
1549 if ($wp->delete()) {
1550 $page->trigSuccess("La page ".$wikipage." a été supprimée.");
1551 } else {
1552 $page->trigError("Impossible de supprimer la page ".$wikipage.".");
1553 }
1554 } else if ($action == 'rename' && !empty($wikipage2) && $wikipage != $wikipage2) {
1555 if ($changedLinks = $wp->rename($wikipage2)) {
1556 $s = 'La page <em>'.$wikipage.'</em> a été déplacée en <em>'.$wikipage2.'</em>.';
1557 if (is_numeric($changedLinks)) {
1558 $s .= $changedLinks.' lien'.(($changedLinks>1)?'s ont été modifiés.':' a été modifié.');
1559 }
1560 $page->trigSuccess($s);
1561 } else {
1562 $page->trigError("Impossible de déplacer la page ".$wikipage);
1563 }
1564 }
1565 }
1566
1567 $perms = PlWikiPage::permOptions();
1568
1569 // list wiki pages and their perms
1570 $wiki_pages = PlWikiPage::listPages();
1571 ksort($wiki_pages);
1572 $wiki_tree = array();
1573 foreach ($wiki_pages as $file => $desc) {
1574 list($cat, $name) = explode('.', $file);
1575 if (!isset($wiki_tree[$cat])) {
1576 $wiki_tree[$cat] = array();
1577 }
1578 $wiki_tree[$cat][$name] = $desc;
1579 }
1580
1581 $page->changeTpl('admin/wiki.tpl');
1582 $page->assign('wiki_pages', $wiki_tree);
1583 $page->assign('perms_opts', $perms);
1584 }
1585
1586 function handler_ipwatch($page, $action = 'list', $ip = null)
1587 {
1588 $page->changeTpl('admin/ipwatcher.tpl');
1589
1590 $states = array('safe' => 'Ne pas surveiller',
1591 'unsafe' => 'Surveiller les inscriptions',
1592 'dangerous' => 'Surveiller tous les accès',
1593 'ban' => 'Bannir cette adresse');
1594 $page->assign('states', $states);
1595
1596 switch (Post::v('action')) {
1597 case 'create':
1598 if (trim(Post::v('ipN')) != '') {
1599 S::assert_xsrf_token();
1600 Xdb::execute('INSERT IGNORE INTO ip_watch (ip, mask, state, detection, last, uid, description)
1601 VALUES ({?}, {?}, {?}, CURDATE(), NOW(), {?}, {?})',
1602 ip_to_uint(trim(Post::v('ipN'))), ip_to_uint(trim(Post::v('maskN'))),
1603 Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
1604 };
1605 break;
1606
1607 case 'edit':
1608 S::assert_xsrf_token();
1609 Xdb::execute('UPDATE ip_watch
1610 SET state = {?}, last = NOW(), uid = {?}, description = {?}, mask = {?}
1611 WHERE ip = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'),
1612 ip_to_uint(Post::v('maskN')), ip_to_uint(Post::v('ipN')));
1613 break;
1614
1615 default:
1616 if ($action == 'delete' && !is_null($ip)) {
1617 S::assert_xsrf_token();
1618 Xdb::execute('DELETE FROM ip_watch WHERE ip = {?}', ip_to_uint($ip));
1619 }
1620 }
1621 if ($action != 'create' && $action != 'edit') {
1622 $action = 'list';
1623 }
1624 $page->assign('action', $action);
1625
1626 if ($action == 'list') {
1627 $sql = "SELECT w.ip, IF(s.ip IS NULL,
1628 IF(w.ip = s2.ip, s2.host, s2.forward_host),
1629 IF(w.ip = s.ip, s.host, s.forward_host)),
1630 w.mask, w.detection, w.state, a.hruid
1631 FROM ip_watch AS w
1632 LEFT JOIN log_sessions AS s ON (s.ip = w.ip)
1633 LEFT JOIN log_sessions AS s2 ON (s2.forward_ip = w.ip)
1634 LEFT JOIN accounts AS a ON (a.uid = s.uid)
1635 GROUP BY w.ip, a.hruid
1636 ORDER BY w.state, w.ip, a.hruid";
1637 $it = Xdb::iterRow($sql);
1638
1639 $table = array();
1640 $props = array();
1641 while (list($ip, $host, $mask, $date, $state, $hruid) = $it->next()) {
1642 $ip = uint_to_ip($ip);
1643 $mask = uint_to_ip($mask);
1644 if (count($props) == 0 || $props['ip'] != $ip) {
1645 if (count($props) > 0) {
1646 $table[] = $props;
1647 }
1648 $props = array('ip' => $ip,
1649 'mask' => $mask,
1650 'host' => $host,
1651 'detection' => $date,
1652 'state' => $state,
1653 'users' => array($hruid));
1654 } else {
1655 $props['users'][] = $hruid;
1656 }
1657 }
1658 if (count($props) > 0) {
1659 $table[] = $props;
1660 }
1661 $page->assign('table', $table);
1662 } elseif ($action == 'edit') {
1663 $sql = "SELECT w.detection, w.state, w.last, w.description, w.mask,
1664 a1.hruid AS edit, a2.hruid AS hruid, s.host
1665 FROM ip_watch AS w
1666 LEFT JOIN accounts AS a1 ON (a1.uid = w.uid)
1667 LEFT JOIN log_sessions AS s ON (w.ip = s.ip)
1668 LEFT JOIN accounts AS a2 ON (a2.uid = s.uid)
1669 WHERE w.ip = {?}
1670 GROUP BY a2.hruid
1671 ORDER BY a2.hruid";
1672 $it = Xdb::iterRow($sql, ip_to_uint($ip));
1673
1674 $props = array();
1675 while (list($detection, $state, $last, $description, $mask, $edit, $hruid, $host) = $it->next()) {
1676 if (count($props) == 0) {
1677 $props = array('ip' => $ip,
1678 'mask' => uint_to_ip($mask),
1679 'host' => $host,
1680 'detection' => $detection,
1681 'state' => $state,
1682 'last' => $last,
1683 'description' => $description,
1684 'edit' => $edit,
1685 'users' => array($hruid));
1686 } else {
1687 $props['users'][] = $hruid;
1688 }
1689 }
1690 $page->assign('ip', $props);
1691 }
1692 }
1693
1694 function handler_icons($page)
1695 {
1696 $page->changeTpl('admin/icons.tpl');
1697 $dh = opendir('../htdocs/images/icons');
1698 if (!$dh) {
1699 $page->trigError('Dossier des icones introuvables.');
1700 }
1701 $icons = array();
1702 while (($file = readdir($dh)) !== false) {
1703 if (strlen($file) > 4 && substr($file,-4) == '.gif') {
1704 array_push($icons, substr($file, 0, -4));
1705 }
1706 }
1707 sort($icons);
1708 $page->assign('icons', $icons);
1709 }
1710
1711 function handler_account_watch($page)
1712 {
1713 $page->changeTpl('admin/accounts.tpl');
1714 $page->assign('disabled', XDB::iterator('SELECT a.hruid, FIND_IN_SET(\'watch\', a.flags) AS watch,
1715 a.state = \'disabled\' AS disabled, a.comment
1716 FROM accounts AS a
1717 WHERE a.state = \'disabled\' OR FIND_IN_SET(\'watch\', a.flags)
1718 ORDER BY a.hruid'));
1719 $page->assign('admins', XDB::iterator('SELECT a.hruid
1720 FROM accounts AS a
1721 WHERE a.is_admin
1722 ORDER BY a.hruid'));
1723 }
1724
1725 function handler_xnet_without_group($page)
1726 {
1727 $page->changeTpl('admin/xnet_without_group.tpl');
1728 $page->assign('accounts', XDB::iterator('SELECT a.hruid, a.state
1729 FROM accounts AS a
1730 LEFT JOIN group_members AS m ON (a.uid = m.uid)
1731 WHERE a.type = \'xnet\' AND m.uid IS NULL
1732 ORDER BY a.state, a.hruid'));
1733 }
1734
1735 function handler_jobs($page, $id = -1)
1736 {
1737 $page->changeTpl('admin/jobs.tpl');
1738
1739 if (Env::has('search')) {
1740 $res = XDB::query("SELECT id, name, acronym
1741 FROM profile_job_enum
1742 WHERE name LIKE CONCAT('%', {?}, '%') OR acronym LIKE CONCAT('%', {?}, '%')",
1743 Env::t('job'), Env::t('job'));
1744
1745 if ($res->numRows() <= 20) {
1746 $page->assign('jobs', $res->fetchAllAssoc());
1747 } else {
1748 $page->trigError("Il y a trop d'entreprises correspondant à ton choix. Affine-le !");
1749 }
1750
1751 $page->assign('askedJob', Env::v('job'));
1752 return;
1753 }
1754
1755 if (Env::has('edit')) {
1756 S::assert_xsrf_token();
1757 $selectedJob = Env::has('selectedJob');
1758
1759 Phone::deletePhones(0, Phone::LINK_COMPANY, $id);
1760 Address::deleteAddresses(null, Address::LINK_COMPANY, $id);
1761 if (Env::has('change')) {
1762 if (Env::has('newJobId') && Env::i('newJobId') > 0) {
1763 XDB::execute('UPDATE profile_job
1764 SET jobid = {?}
1765 WHERE jobid = {?}',
1766 Env::i('newJobId'), $id);
1767 XDB::execute('DELETE FROM profile_job_enum
1768 WHERE id = {?}',
1769 $id);
1770
1771 $page->trigSuccess("L'entreprise a bien été remplacée.");
1772 } else {
1773 $page->trigError("L'entreprise n'a pas été remplacée car l'identifiant fourni n'est pas valide.");
1774 }
1775 } else {
1776 XDB::execute('UPDATE profile_job_enum
1777 SET name = {?}, acronym = {?}, url = {?}, email = {?},
1778 NAF_code = {?}, AX_code = {?}, holdingid = {?}
1779 WHERE id = {?}',
1780 Env::t('name'), Env::t('acronym'), Env::t('url'), Env::t('email'),
1781 (Env::t('NAF_code') == 0 ? null : Env::t('NAF_code')),
1782 (Env::i('AX_code') == 0 ? null : Env::t('AX_code')),
1783 (Env::i('holdingId') == 0 ? null : Env::t('holdingId')), $id);
1784
1785 $phone = new Phone(array('display' => Env::v('tel'), 'link_id' => $id, 'id' => 0, 'type' => 'fixed',
1786 'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
1787 $fax = new Phone(array('display' => Env::v('fax'), 'link_id' => $id, 'id' => 1, 'type' => 'fax',
1788 'link_type' => Phone::LINK_COMPANY, 'pub' => 'public'));
1789 $address = new Address(array('jobid' => $id, 'type' => Address::LINK_COMPANY, 'text' => Env::t('address')));
1790 $phone->save();
1791 $fax->save();
1792 $address->save();
1793
1794 $page->trigSuccess("L'entreprise a bien été mise à jour.");
1795 }
1796 }
1797
1798 if (!Env::has('change') && $id != -1) {
1799 $res = XDB::query("SELECT e.id, e.name, e.acronym, e.url, e.email, e.NAF_code, e.AX_code,
1800 h.id AS holdingId, h.name AS holdingName, h.acronym AS holdingAcronym,
1801 t.display_tel AS tel, f.display_tel AS fax, a.text AS address
1802 FROM profile_job_enum AS e
1803 LEFT JOIN profile_job_enum AS h ON (e.holdingid = h.id)
1804 LEFT JOIN profile_phones AS t ON (t.pid = e.id AND t.link_type = 'hq' AND t.tel_id = 0)
1805 LEFT JOIN profile_phones AS f ON (f.pid = e.id AND f.link_type = 'hq' AND f.tel_id = 1)
1806 LEFT JOIN profile_addresses AS a ON (a.jobid = e.id AND a.type = 'hq')
1807 WHERE e.id = {?}",
1808 $id);
1809
1810 if ($res->numRows() == 0) {
1811 $page->trigError('Auncune entreprise ne correspond à cet identifiant.');
1812 } else {
1813 $page->assign('selectedJob', $res->fetchOneAssoc());
1814 }
1815 }
1816 }
1817
1818 function handler_profile($page)
1819 {
1820 $page->changeTpl('admin/profile.tpl');
1821
1822 if (Post::has('checked')) {
1823 S::assert_xsrf_token();
1824 $res = XDB::iterator('SELECT DISTINCT(pm.pid), pd.public_name
1825 FROM profile_modifications AS pm
1826 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1827 WHERE pm.type = \'self\'');
1828
1829 while ($profile = $res->next()) {
1830 if (Post::has('checked_' . $profile['pid'])) {
1831 XDB::execute('DELETE FROM profile_modifications
1832 WHERE type = \'self\' AND pid = {?}', $profile['pid']);
1833
1834 $page->trigSuccess('Profil de ' . $profile['public_name'] . ' vérifié.');
1835 }
1836 }
1837 }
1838
1839 $res = XDB::iterator('SELECT p.hrpid, pm.pid, pd.directory_name, GROUP_CONCAT(pm.field SEPARATOR \', \') AS field
1840 FROM profile_modifications AS pm
1841 INNER JOIN profiles AS p ON (pm.pid = p.pid)
1842 INNER JOIN profile_display AS pd ON (pm.pid = pd.pid)
1843 WHERE pm.type = \'self\'
1844 GROUP BY pd.directory_name
1845 ORDER BY pd.directory_name');
1846 $page->assign('updates', $res);
1847 }
1848
1849 function handler_phd($page, $promo = null, $validate = false)
1850 {
1851 $page->changeTpl('admin/phd.tpl');
1852 $eduDegrees = DirEnum::getOptions(DirEnum::EDUDEGREES);
1853 $eduDegrees = array_flip($eduDegrees);
1854
1855 if (is_null($promo)) {
1856 $promo_list = XDB::fetchColumn('SELECT DISTINCT(grad_year)
1857 FROM profile_education
1858 WHERE FIND_IN_SET(\'primary\', flags) AND NOT FIND_IN_SET(\'completed\', flags) AND degreeid = {?}
1859 ORDER BY grad_year',
1860 $eduDegrees[Profile::DEGREE_D]);
1861 $page->assign('promo_list', $promo_list);
1862 $page->assign('nothing', count($promo_list) == 0);
1863 return;
1864 }
1865
1866 if ($validate) {
1867 S::assert_xsrf_token();
1868
1869 $list = XDB::iterator('SELECT pe.pid, pd.directory_name
1870 FROM profile_education AS pe
1871 INNER JOIN profile_display AS pd ON (pe.pid = pd.pid)
1872 WHERE FIND_IN_SET(\'primary\', pe.flags) AND NOT FIND_IN_SET(\'completed\', pe.flags)
1873 AND pe.degreeid = {?} AND pe.grad_year = {?}',
1874 $eduDegrees[Profile::DEGREE_D], $promo);
1875 while ($res = $list->next()) {
1876 $pid = $res['pid'];
1877 $name = $res['directory_name'];
1878 if (Post::b('completed_' . $pid)) {
1879 $grad_year = Post::t('grad_year_' . $pid);
1880 XDB::execute('UPDATE profile_education
1881 SET flags = \'primary,completed\', grad_year = {?}
1882 WHERE FIND_IN_SET(\'primary\', flags) AND pid = {?}',
1883 $grad_year, $pid);
1884 XDB::execute('UPDATE profile_display
1885 SET promo = {?}
1886 WHERE pid = {?}',
1887 'D' . $grad_year, $pid);
1888 $page->trigSuccess("Promotion de $name validée.");
1889 }
1890 }
1891 }
1892
1893 $list = XDB::iterator('SELECT pe.pid, pd.directory_name
1894 FROM profile_education AS pe
1895 INNER JOIN profile_display AS pd ON (pe.pid = pd.pid)
1896 WHERE FIND_IN_SET(\'primary\', pe.flags) AND NOT FIND_IN_SET(\'completed\', pe.flags)
1897 AND pe.degreeid = {?} AND pe.grad_year = {?}
1898 ORDER BY pd.directory_name',
1899 $eduDegrees[Profile::DEGREE_D], $promo);
1900 $page->assign('list', $list);
1901 $page->assign('promo', $promo);
1902 }
1903
1904 function handler_add_secondary_edu($page)
1905 {
1906 $page->changeTpl('admin/add_secondary_edu.tpl');
1907
1908 if (!(Post::has('verify') || Post::has('add'))) {
1909 return;
1910 } elseif (!Post::has('people')) {
1911 $page->trigWarning("Aucune information n'a été fournie.");
1912 return;
1913 }
1914
1915 require_once 'name.func.inc.php';
1916 $lines = explode("\n", Post::t('people'));
1917 $separator = Post::t('separator');
1918 $degree = Post::v('degree');
1919 $promotion = Post::i('promotion');
1920 $schoolsList = array_flip(DirEnum::getOptions(DirEnum::EDUSCHOOLS));
1921 $degreesList = array_flip(DirEnum::getOptions(DirEnum::EDUDEGREES));
1922 $edu_id = $schoolsList[Profile::EDU_X];
1923 $degree_id = $degreesList[$degree];
1924
1925 $res = array(
1926 'incomplete' => array(),
1927 'empty' => array(),
1928 'multiple' => array(),
1929 'already' => array(),
1930 'new' => array()
1931 );
1932 $old_pids = array();
1933 $new_pids = array();
1934 foreach ($lines as $line) {
1935 $line = trim($line);
1936 $line_array = explode($separator, $line);
1937 array_walk($line_array, 'trim');
1938 if (count($line_array) != 3) {
1939 $page->trigError("La ligne « $line » est incomplète.");
1940 $res['incomplete'][] = $line;
1941 continue;
1942 }
1943 $cond = new PFC_And(new UFC_NameTokens(split_name_for_search($line_array[0]), array(), false, false, Profile::LASTNAME));
1944 $cond->addChild(new UFC_NameTokens(split_name_for_search($line_array[1]), array(), false, false, Profile::FIRSTNAME));
1945 $cond->addChild(new UFC_Promo('=', UserFilter::DISPLAY, $line_array[2]));
1946 $uf = new UserFilter($cond);
1947 $pid = $uf->getPIDs();
1948 $count = count($pid);
1949 if ($count == 0) {
1950 $page->trigError("La ligne « $line » ne correspond à aucun profil existant.");
1951 $res['empty'][] = $line;
1952 continue;
1953 } elseif ($count > 1) {
1954 $page->trigError("La ligne « $line » correspond à plusieurs profils existant.");
1955 $res['multiple'][] = $line;
1956 continue;
1957 } else {
1958 $count = XDB::fetchOneCell('SELECT COUNT(*) AS count
1959 FROM profile_education
1960 WHERE pid = {?} AND eduid = {?} AND degreeid = {?}',
1961 $pid, $edu_id, $degree_id);
1962 if ($count == 1) {
1963 $res['already'][] = $line;
1964 $old_pids[] = $pid[0];
1965 } else {
1966 $res['new'][] = $line;
1967 $new_pids[] = $pid[0];
1968 }
1969 }
1970 }
1971
1972 $display = array();
1973 foreach ($res as $type => $res_type) {
1974 if (count($res_type) > 0) {
1975 $display = array_merge($display, array('--------------------' . $type . ':'), $res_type);
1976 }
1977 }
1978 $page->assign('people', implode("\n", $display));
1979 $page->assign('promotion', $promotion);
1980 $page->assign('degree', $degree);
1981
1982 if (Post::has('add')) {
1983 $entry_year = $promotion - Profile::educationDuration($degree);
1984
1985 if (Post::b('force_addition')) {
1986 $pids = array_unique(array_merge($old_pids, $new_pids));
1987 } else {
1988 $pids = array_unique($new_pids);
1989
1990 // Updates years.
1991 if (count($old_pids)) {
1992 XDB::execute('UPDATE profile_education
1993 SET entry_year = {?}, grad_year = {?}, promo_year = {?}
1994 WHERE pid IN {?} AND eduid = {?} AND degreeid = {?}',
1995 $entry_year, $promotion, $promotion, $old_pids, $edu_id, $degree_id);
1996 }
1997 }
1998
1999 // Precomputes values common to all users.
2000 $select = XDB::format('MAX(id) + 1, pid, {?}, {?}, {?}, {?}, {?}, \'secondary\'',
2001 $edu_id, $degree_id, $entry_year, $promotion, $promotion );
2002 XDB::startTransaction();
2003 foreach ($pids as $pid) {
2004 XDB::execute('INSERT INTO profile_education (id, pid, eduid, degreeid, entry_year, grad_year, promo_year, flags)
2005 SELECT ' . $select . '
2006 FROM profile_education
2007 WHERE pid = {?}
2008 GROUP BY pid',
2009 $pid);
2010 }
2011 XDB::commit();
2012 }
2013
2014 }
2015 }
2016
2017 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
2018 ?>