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