Requires address validation properly, ie when addresses are saved (and fixes a few...
[platal.git] / modules / profile.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 ProfileModule extends PLModule
23 {
24 function handlers()
25 {
26 return array(
27 'photo' => $this->make_hook('photo', AUTH_PUBLIC),
28 'photo/change' => $this->make_hook('photo_change', AUTH_MDP),
29
30 'fiche.php' => $this->make_hook('fiche', AUTH_PUBLIC),
31 'profile' => $this->make_hook('profile', AUTH_PUBLIC),
32 'profile/private' => $this->make_hook('profile', AUTH_COOKIE),
33 'profile/ax' => $this->make_hook('ax', AUTH_COOKIE, 'admin,edit_directory'),
34 'profile/edit' => $this->make_hook('p_edit', AUTH_MDP),
35 'profile/ajax/address' => $this->make_hook('ajax_address', AUTH_COOKIE, 'user', NO_AUTH),
36 'profile/ajax/address/del' => $this->make_hook('ajax_address_del', AUTH_MDP),
37 'profile/ajax/tel' => $this->make_hook('ajax_tel', AUTH_COOKIE, 'user', NO_AUTH),
38 'profile/ajax/edu' => $this->make_hook('ajax_edu', AUTH_COOKIE, 'user', NO_AUTH),
39 'profile/ajax/medal' => $this->make_hook('ajax_medal', AUTH_COOKIE, 'user', NO_AUTH),
40 'profile/networking' => $this->make_hook('networking', AUTH_PUBLIC),
41 'profile/ajax/job' => $this->make_hook('ajax_job', AUTH_COOKIE, 'user', NO_AUTH),
42 'profile/ajax/skill' => $this->make_hook('ajax_skill', AUTH_COOKIE, 'user', NO_AUTH),
43 'profile/ajax/deltaten' => $this->make_hook('ajax_deltaten', AUTH_COOKIE, 'user', NO_AUTH),
44 'profile/ajax/searchname' => $this->make_hook('ajax_searchname', AUTH_COOKIE, 'user', NO_AUTH),
45 'profile/ajax/buildnames' => $this->make_hook('ajax_buildnames', AUTH_COOKIE, 'user', NO_AUTH),
46 'profile/ajax/tree/jobterms' => $this->make_hook('ajax_tree_job_terms', AUTH_COOKIE, 'user', NO_AUTH),
47 'profile/jobterms' => $this->make_hook('jobterms', AUTH_COOKIE, 'user', NO_AUTH),
48 'javascript/education.js' => $this->make_hook('education_js', AUTH_COOKIE),
49 'javascript/grades.js' => $this->make_hook('grades_js', AUTH_COOKIE),
50 'profile/medal' => $this->make_hook('medal', AUTH_PUBLIC),
51 'profile/name_info' => $this->make_hook('name_info', AUTH_PUBLIC),
52
53 'referent' => $this->make_hook('referent', AUTH_COOKIE),
54 'referent/country' => $this->make_hook('ref_country', AUTH_COOKIE, 'user', NO_AUTH),
55 'referent/autocomplete' => $this->make_hook('ref_autocomplete', AUTH_COOKIE, 'user', NO_AUTH),
56
57 'groupes-x' => $this->make_hook('xnet', AUTH_COOKIE),
58 'groupes-x/logo' => $this->make_hook('xnetlogo', AUTH_PUBLIC),
59
60 'vcard' => $this->make_hook('vcard', AUTH_COOKIE, 'user', NO_HTTPS),
61 'admin/binets' => $this->make_hook('admin_binets', AUTH_MDP, 'admin'),
62 'admin/medals' => $this->make_hook('admin_medals', AUTH_MDP, 'admin'),
63 'admin/education' => $this->make_hook('admin_education', AUTH_MDP, 'admin'),
64 'admin/education_field' => $this->make_hook('admin_education_field', AUTH_MDP, 'admin'),
65 'admin/education_degree' => $this->make_hook('admin_education_degree', AUTH_MDP, 'admin'),
66 'admin/education_degree_set' => $this->make_hook('admin_education_degree_set', AUTH_MDP, 'admin'),
67 'admin/sections' => $this->make_hook('admin_sections', AUTH_MDP, 'admin'),
68 'admin/networking' => $this->make_hook('admin_networking', AUTH_MDP, 'admin'),
69 'admin/trombino' => $this->make_hook('admin_trombino', AUTH_MDP, 'admin'),
70 'admin/corps_enum' => $this->make_hook('admin_corps_enum', AUTH_MDP, 'admin'),
71 'admin/corps_rank' => $this->make_hook('admin_corps_rank', AUTH_MDP, 'admin'),
72 'admin/names' => $this->make_hook('admin_names', AUTH_MDP, 'admin'),
73 );
74 }
75
76 /* Function needed for compatibility reasons.
77 * TODO: removes calls to fiche.php?user=blah.machin.2083 and then removes this.
78 */
79 function handler_fiche($page)
80 {
81 return $this->handler_profile($page, Env::v('user'));
82 }
83
84 function handler_photo($page, $x = null, $req = null)
85 {
86 if (!$x || !($profile = Profile::get($x))) {
87 return PL_NOT_FOUND;
88 }
89
90 // Retrieve the photo and its mime type.
91 if ($req && S::logged()) {
92 $myphoto = PhotoReq::get_request($profile->id());
93 $photo = PlImage::fromData($myphoto->data, $myphoto->mimetype);
94 } else {
95 $photo = $profile->getPhoto(true, true);
96 }
97
98 // Display the photo, or a default one when not available.
99 $photo->send();
100 }
101
102 function handler_medal($page, $mid)
103 {
104 $thumb = ($mid == 'thumb');
105 $mid = $thumb ? @func_get_arg(2) : $mid;
106
107 $res = XDB::query("SELECT img
108 FROM profile_medal_enum
109 WHERE id = {?}",
110 $mid);
111 $img = $thumb ?
112 dirname(__FILE__).'/../htdocs/images/medals/thumb/' . $res->fetchOneCell() :
113 dirname(__FILE__).'/../htdocs/images/medals/' . $res->fetchOneCell();
114 pl_cached_content_headers(mime_content_type($img));
115 echo file_get_contents($img);
116 exit;
117 }
118
119 function handler_name_info($page)
120 {
121 pl_content_headers("text/html");
122 $page->changeTpl('profile/name_info.tpl', SIMPLE);
123 $res = XDB::iterator("SELECT name, explanations,
124 FIND_IN_SET('public', flags) AS public,
125 FIND_IN_SET('has_particle', flags) AS has_particle
126 FROM profile_name_enum
127 WHERE NOT FIND_IN_SET('not_displayed', flags)
128 ORDER BY NOT FIND_IN_SET('public', flags)");
129 $page->assign('types', $res);
130 }
131
132 function handler_networking($page, $mid)
133 {
134 $res = XDB::query("SELECT icon
135 FROM profile_networking_enum
136 WHERE nwid = {?}",
137 $mid);
138 $img = dirname(__FILE__) . '/../htdocs/images/networking/' . $res->fetchOneCell();
139 pl_cached_content_headers(mime_content_type($img));
140 echo file_get_contents($img);
141 exit;
142 }
143
144 /** Tries to return the correct profile from a given hrpid.
145 */
146 private function findProfile($hrpid = null)
147 {
148 if (is_null($hrpid)) {
149 $user = S::user();
150 if (!$user->hasProfile()) {
151 return PL_NOT_FOUND;
152 } else {
153 $profile = $user->profile();
154 }
155 } else {
156 $profile = Profile::get($hrpid);
157 }
158
159 if (!$profile) {
160 return PL_NOT_FOUND;
161 } else if (!S::user()->canEdit($profile) && Platal::notAllowed()) {
162 return PL_FORBIDDEN;
163 }
164 return $profile;
165 }
166
167 function handler_photo_change($page, $hrpid = null)
168 {
169 global $globals;
170 $profile = $this->findProfile($hrpid);
171 if (! ($profile instanceof Profile) && ($profile == PL_NOT_FOUND || $profile == PL_FORBIDDEN)) {
172 return $profile;
173 }
174 if (is_null($hrpid)) {
175 pl_redirect('photo/change/' . $profile->hrid());
176 }
177
178 $page->changeTpl('profile/trombino.tpl');
179 $page->assign('hrpid', $profile->hrid());
180
181 $trombi_x = '/home/web/trombino/photos' . $profile->promo() . '/' . $profile->hrid() . '.jpg';
182 if (Env::has('upload')) {
183 S::assert_xsrf_token();
184
185 $upload = new PlUpload($profile->hrid(), 'photo');
186 if (!$upload->upload($_FILES['userfile']) && !$upload->download(Env::v('photo'))) {
187 $page->trigError('Une erreur est survenue lors du téléchargement du fichier');
188 } else {
189 $myphoto = new PhotoReq(S::user(), $profile, $upload);
190 if ($myphoto->isValid()) {
191 $myphoto->submit();
192 }
193 }
194 } elseif (Env::has('trombi')) {
195 S::assert_xsrf_token();
196
197 $upload = new PlUpload($profile->hrid(), 'photo');
198 if ($upload->copyFrom($trombi_x)) {
199 $myphoto = new PhotoReq(S::user(), $profile, $upload);
200 if ($myphoto->isValid()) {
201 $myphoto->commit();
202 $myphoto->clean();
203 }
204 }
205 } elseif (Env::v('suppr')) {
206 S::assert_xsrf_token();
207
208 XDB::execute('DELETE FROM profile_photos
209 WHERE pid = {?}',
210 $profile->id());
211 XDB::execute("DELETE FROM requests
212 WHERE pid = {?} AND type = 'photo'",
213 $profile->id());
214 $globals->updateNbValid();
215 $page->trigSuccess("Ta photo a bien été supprimée. Elle ne sera plus visible sur le site dans au plus une heure.");
216 } elseif (Env::v('cancel')) {
217 S::assert_xsrf_token();
218
219 $sql = XDB::query("DELETE FROM requests
220 WHERE pid = {?} AND type = 'photo'",
221 $profile->id());
222 $globals->updateNbValid();
223 }
224
225 $sql = XDB::query("SELECT COUNT(*)
226 FROM requests
227 WHERE pid = {?} AND type = 'photo'",
228 $profile->id());
229 $page->assign('submited', $sql->fetchOneCell());
230 $page->assign('has_trombi_x', file_exists($trombi_x));
231 }
232
233 function handler_profile($page, $id = null)
234 {
235 // Checks if the identifier corresponds to an actual profile. Numeric
236 // identifiers canonly be user by logged users.
237 if (is_null($id)) {
238 return PL_NOT_FOUND;
239 }
240
241 // Determines the access level at which the profile will be displayed.
242 if (!S::logged() || !S::user()->checkPerms('directory_ax') || Env::v('view') == 'public') {
243 $view = 'public';
244 } else if (!S::user()->checkPerms('directory_private') || Env::v('view') == 'ax') {
245 $view = 'ax';
246 } else {
247 $view = 'private';
248 }
249
250 // Display pending picture
251 if (S::logged() && Env::v('modif') == 'new') {
252 $page->assign('with_pending_pic', true);
253 }
254
255 $pid = (!is_numeric($id) || S::admin()) ? Profile::getPID($id) : null;
256 if (is_null($pid)) {
257 $owner = User::getSilent($id);
258 if ($owner) {
259 $profile = $owner->profile(true, Profile::FETCH_ALL, $view);
260 if ($profile) {
261 $pid = $profile->id();
262 }
263 }
264 } else {
265 // Fetches profile's and profile's owner information and redirects to
266 // marketing if the owner has not subscribed and the requirer has logged in.
267 $profile = Profile::get($pid, Profile::FETCH_ALL, $view);
268 $owner = $profile->owner();
269 }
270 if (is_null($pid)) {
271 if (S::logged()) {
272 $page->kill($id . " inconnu dans l'annuaire.");
273 }
274 return PL_NOT_FOUND;
275 }
276 // Now that we know this is an existing profile, we can switch to the
277 // appropriate template.
278 $page->changeTpl('profile/profile.tpl', SIMPLE);
279
280 // Profile view are logged.
281 if (S::logged()) {
282 S::logger()->log('view_profile', $profile->hrid());
283 }
284
285 // Sets the title of the html page.
286 $page->setTitle($profile->fullName());
287
288 // Determines and displays the virtual alias.
289 if (!is_null($owner) && $profile->alias_pub == 'public') {
290 $page->assign('virtualalias', $owner->emailAlias());
291 }
292
293 $page->assign_by_ref('profile', $profile);
294 $page->assign_by_ref('owner', $owner);
295 $page->assign('view', $view);
296 $page->assign('logged', S::logged());
297
298 header('Last-Modified: ' . date('r', strtotime($profile->last_change)));
299 }
300
301 function handler_ax($page, $user = null)
302 {
303 $user = Profile::get($user);
304 if (!$user) {
305 return PL_NOT_FOUND;
306 }
307 if (!$user->ax_id) {
308 $page->kill("Le matricule AX de {$user->hrid()} est inconnu");
309 }
310 http_redirect("http://www.polytechniciens.com/?page=AX_FICHE_ANCIEN&ancc_id=" . $user->ax_id);
311 }
312
313 function handler_p_edit($page, $hrpid = null, $opened_tab = null, $mode = null, $success = null)
314 {
315 global $globals;
316
317 if (in_array($hrpid, array('general', 'adresses', 'emploi', 'poly', 'deco', 'skill', 'mentor', 'deltaten'))) {
318 $aux = $opened_tab;
319 $opened_tab = $hrpid;
320 $hrpid = $aux;
321 $url_error = true;
322 } else {
323 $url_error = false;
324 }
325 $profile = $this->findProfile($hrpid);
326 if (! ($profile instanceof Profile) && ($profile == PL_NOT_FOUND || $profile == PL_FORBIDDEN)) {
327 return $profile;
328 }
329 if (is_null($hrpid) || $url_error) {
330 pl_redirect('profile/edit/' . $profile->hrid() . (is_null($opened_tab) ? '' : '/' . $opened_tab));
331 }
332
333 // Build the page
334 $page->addJsLink('education.js', true, false); /* dynamic content */
335 $page->addJsLink('grades.js', true, false); /* dynamic content */
336 $page->addJsLink('profile.js');
337 $wiz = new PlWizard('Profil', PlPage::getCoreTpl('plwizard.tpl'), true, true, false);
338 $wiz->addUserData('profile', $profile);
339 $wiz->addUserData('owner', $profile->owner());
340 $this->load('page.inc.php');
341 $wiz->addPage('ProfilePageGeneral', 'Général', 'general');
342 $wiz->addPage('ProfilePageAddresses', 'Adresses personnelles', 'adresses');
343 $wiz->addPage('ProfilePageJobs', 'Informations professionnelles', 'emploi');
344 if (S::user()->checkPerms(User::PERM_DIRECTORY_PRIVATE)) {
345 $wiz->addPage('ProfilePageGroups', 'Groupes X - Binets', 'poly');
346 }
347 $wiz->addPage('ProfilePageDecos', 'Décorations - Medailles', 'deco');
348 if (S::user()->checkPerms(User::PERM_DIRECTORY_PRIVATE)) {
349 $wiz->addPage('ProfilePageSkills', 'Compétences diverses', 'skill');
350 $wiz->addPage('ProfilePageMentor', 'Mentoring', 'mentor');
351 }
352 if (S::user()->checkPerms(User::PERM_DIRECTORY_PRIVATE) && $profile->isDeltatenEnabled(Profile::DELTATEN_OLD)) {
353 $wiz->addPage('ProfilePageDeltaten', 'Opération N N-10', 'deltaten');
354 }
355 $wiz->apply($page, 'profile/edit/' . $profile->hrid(), $opened_tab, $mode);
356
357 if (!$profile->birthdate) {
358 $page->trigWarning("Ta date de naissance n'est pas renseignée, ce qui t'empêcheras de réaliser"
359 . " la procédure de récupération de mot de passe si un jour tu le perdais.");
360 }
361
362 $page->setTitle('Mon Profil');
363 $page->assign('hrpid', $profile->hrid());
364 if (isset($success) && $success) {
365 $page->trigSuccess('Ton profil a bien été mis à jour.');
366 }
367 }
368
369 function handler_education_js($page)
370 {
371 pl_cached_content_headers("text/javascript", "utf-8");
372 $page->changeTpl('profile/education.js.tpl', NO_SKIN);
373 require_once 'education.func.inc.php';
374 }
375
376 function handler_grades_js($page)
377 {
378 pl_cached_content_headers("text/javascript", "utf-8");
379 $page->changeTpl('profile/grades.js.tpl', NO_SKIN);
380 $res = XDB::iterator("SELECT *
381 FROM profile_medal_grade_enum
382 ORDER BY mid, pos");
383 $grades = array();
384 while ($tmp = $res->next()) {
385 $grades[$tmp['mid']][] = $tmp;
386 }
387 $page->assign('grades', $grades);
388
389 $res = XDB::iterator("SELECT *, FIND_IN_SET('validation', flags) AS validate
390 FROM profile_medal_enum
391 ORDER BY type, text");
392 $mlist = array();
393 while ($tmp = $res->next()) {
394 $mlist[$tmp['type']][] = $tmp;
395 }
396 $page->assign('medal_list', $mlist);
397 }
398
399 function handler_ajax_address($page, $id, $pid)
400 {
401 pl_content_headers("text/html");
402 $page->changeTpl('profile/adresses.address.tpl', NO_SKIN);
403 $page->assign('i', $id);
404 $page->assign('address', array());
405 $page->assign('profile', Profile::get($pid));
406 $page->assign('isMe', true);
407 $page->assign('geocoding_removal', true);
408 }
409
410 function handler_ajax_tel($page, $prefid, $prefname, $telid, $subField, $mainField, $mainId)
411 {
412 pl_content_headers("text/html");
413 $page->changeTpl('profile/phone.tpl', NO_SKIN);
414 $page->assign('prefid', $prefid);
415 $page->assign('prefname', $prefname);
416 $page->assign('telid', $telid);
417 $phone = new Phone();
418 $page->assign('tel', $phone->toFormArray());
419 if ($mainField) {
420 $page->assign('subField', $subField);
421 $page->assign('mainField', $mainField);
422 $page->assign('mainId', $mainId);
423 }
424 }
425
426 function handler_ajax_edu($page, $eduid, $class)
427 {
428 pl_content_headers("text/html");
429 $page->changeTpl('profile/general.edu.tpl', NO_SKIN);
430 $res = XDB::iterator("SELECT id, field
431 FROM profile_education_field_enum
432 ORDER BY field");
433 $page->assign('edu_fields', $res->fetchAllAssoc());
434 $page->assign('eduid', $eduid);
435 $page->assign('class', $class);
436 require_once "education.func.inc.php";
437 }
438
439 function handler_ajax_medal($page, $i, $id)
440 {
441 pl_content_headers("text/html");
442 $page->changeTpl('profile/deco.medal.tpl', NO_SKIN);
443 $page->assign('id', $i);
444 $page->assign('medal', array('id' => $id, 'grade' => 0, 'valid' => 0));
445 }
446
447 function handler_ajax_job($page, $id)
448 {
449 pl_content_headers("text/html");
450 $page->changeTpl('profile/jobs.job.tpl', NO_SKIN);
451 $page->assign('i', $id);
452 $page->assign('job', array());
453 $page->assign('new', true);
454 require_once "emails.combobox.inc.php";
455 fill_email_combobox($page, array('redirect', 'job', 'stripped_directory'));
456 }
457
458 /**
459 * Page for url "profile/ajax/tree/jobterms". Display a JSon page containing
460 * the sub-branches of a branch in the job terms tree.
461 * @param $page the Platal page
462 * @param $filter filter helps to display only jobterms that are contained in jobs or in mentors
463 *
464 * @param Env::i('jtid') job term id of the parent branch, if none trunk will be used
465 * @param Env::v('attrfunc') the name of a javascript function that will be called when a branch
466 * is chosen
467 * @param Env::v('treeid') tree id that will be given as first argument of attrfunc function
468 * the second argument will be the chosen job term id and the third one the chosen job full name.
469 */
470 function handler_ajax_tree_job_terms($page, $filter = JobTerms::ALL)
471 {
472 JobTerms::ajaxGetBranch($page, $filter);
473 }
474
475 function handler_ajax_skill($page, $cat, $id)
476 {
477 pl_content_headers("text/html");
478 $page->changeTpl('profile/skill.skill.tpl', NO_SKIN);
479 $page->assign('cat', $cat);
480 $page->assign('id', $id);
481 if ($cat == 'competences') {
482 $page->assign('levels', array('initié' => 'initié',
483 'bonne connaissance' => 'bonne connaissance',
484 'expert' => 'expert'));
485 } else {
486 $page->assign('levels', array(1 => 'connaissance basique',
487 2 => 'maîtrise des bases',
488 3 => 'maîtrise limitée',
489 4 => 'maîtrise générale',
490 5 => 'bonne maîtrise',
491 6 => 'maîtrise complète'));
492 }
493 }
494
495 function handler_ajax_searchname($page, $id, $isFemale)
496 {
497 pl_content_headers("text/html");
498 $page->changeTpl('profile/general.searchname.tpl', NO_SKIN);
499 $res = XDB::query("SELECT id, name, FIND_IN_SET('public', flags) AS pub
500 FROM profile_name_enum
501 WHERE NOT FIND_IN_SET('not_displayed', flags)
502 AND NOT FIND_IN_SET('always_displayed', flags)");
503 $page->assign('sn_type_list', $res->fetchAllAssoc());
504 $page->assign('isFemale', $isFemale);
505 $page->assign('i', $id);
506 }
507
508 function handler_ajax_buildnames($page, $data, $isFemale)
509 {
510 pl_content_headers("text/html");
511 $page->changeTpl('profile/general.buildnames.tpl', NO_SKIN);
512 require_once 'name.func.inc.php';
513 $page->assign('names', build_javascript_names($data, $isFemale));
514 }
515
516 function handler_referent($page, $pf)
517 {
518 $page->changeTpl('profile/fiche_referent.tpl', SIMPLE);
519
520 $pf = Profile::get($pf);
521 if (!$pf) {
522 return PL_NOT_FOUND;
523 }
524
525 $page->assign_by_ref('profile', $pf);
526
527 // Retrieves referents' countries.
528 $res = XDB::query(
529 "SELECT gc.country
530 FROM profile_mentor_country AS m
531 LEFT JOIN geoloc_countries AS gc ON (m.country = gc.iso_3166_1_a2)
532 WHERE pid = {?}", $pf->id());
533 $page->assign('pays', $res->fetchColumn());
534 }
535
536 function handler_ref_country($page)
537 {
538 pl_content_headers("text/html");
539 $page->changeTpl('include/field.select.tpl', NO_SKIN);
540 $page->assign('name', 'pays_sel');
541 $it = XDB::iterator("SELECT gc.iso_3166_1_a2 AS id, gc.country AS field
542 FROM geoloc_countries AS gc
543 INNER JOIN profile_mentor_country AS mp ON (mp.country = gc.iso_3166_1_a2)
544 GROUP BY iso_3166_1_a2
545 ORDER BY country");
546 $page->assign('list', $it);
547 }
548
549 /**
550 * Page for url "referent/autocomplete". Display an "autocomplete" page (plain/text with values
551 * separated by "|" chars) for jobterms in referent (mentor) search.
552 * @see handler_jobterms
553 */
554 function handler_ref_autocomplete($page)
555 {
556 $this->handler_jobterms($page, 'mentor');
557 }
558
559 /**
560 * Page for url "profile/jobterms" (function also used for "referent/autocomplete" @see
561 * handler_ref_autocomplete). Displays an "autocomplete" page (plain text with values
562 * separated by "|" chars) for jobterms to add in profile.
563 * @param $page the Platal page
564 * @param $type set to 'mentor' to display the number of mentors for each term and order
565 * by descending number of mentors.
566 *
567 * @param Env::v('q') the text that has been typed and to complete automatically
568 */
569 function handler_jobterms($page, $type = 'nomentor')
570 {
571 pl_content_headers("text/plain");
572
573 $q = Env::v('q').'%';
574 $tokens = JobTerms::tokenize($q);
575 if (count($tokens) == 0) {
576 exit;
577 }
578 sort($tokens);
579 $q_normalized = implode(' ', $tokens);
580
581 // try to look in cached results
582 $cache = XDB::query('SELECT result
583 FROM search_autocomplete
584 WHERE name = {?} AND
585 query = {?} AND
586 generated > NOW() - INTERVAL 1 DAY',
587 $type, $q_normalized);
588 if ($res = $cache->fetchOneCell()) {
589 echo $res;
590 die();
591 }
592
593 $joins = JobTerms::token_join_query($tokens, 'e');
594 if ($type == 'mentor') {
595 $count = ', COUNT(DISTINCT pid) AS nb';
596 $countjoin = ' INNER JOIN profile_job_term_relation AS r ON(r.jtid_1 = e.jtid) INNER JOIN profile_mentor_term AS m ON(r.jtid_2 = m.jtid)';
597 $countorder = 'nb DESC, ';
598 } else {
599 $count = $countjoin = $countorder = '';
600 }
601 $list = XDB::iterator('SELECT e.jtid AS id, e.full_name AS field'.$count.'
602 FROM profile_job_term_enum AS e '.$joins.$countjoin.'
603 GROUP BY e.jtid
604 ORDER BY '.$countorder.'field
605 LIMIT 11');
606 $nbResults = 0;
607 $res = '';
608 while ($result = $list->next()) {
609 $nbResults++;
610 if ($nbResults == 11) {
611 $res .= $q."|-1\n";
612 } else {
613 $res .= $result['field'].'|';
614 if ($count) {
615 $res .= $result['nb'].'|';
616 }
617 $res .= $result['id'];
618 }
619 $res .= "\n";
620 }
621 XDB::query('INSERT INTO search_autocomplete (name, query, result, generated)
622 VALUES ({?}, {?}, {?}, NOW())
623 ON DUPLICATE KEY UPDATE result = VALUES(result), generated = VALUES(generated)',
624 $type, $q_normalized, $res);
625 echo $res;
626 exit();
627 }
628
629 function handler_xnet($page)
630 {
631 $page->changeTpl('profile/groupesx.tpl');
632 $page->setTitle('Promo, Groupes X, Binets');
633
634 $req = XDB::query('
635 SELECT m.asso_id, a.nom, diminutif, a.logo IS NOT NULL AS has_logo,
636 COUNT(e.eid) AS events, mail_domain AS lists
637 FROM group_members AS m
638 INNER JOIN groups AS a ON(m.asso_id = a.id)
639 LEFT JOIN group_events AS e ON(e.asso_id = m.asso_id AND e.archive = 0)
640 WHERE m.uid = {?} GROUP BY m.asso_id ORDER BY a.nom', S::i('uid'));
641 $page->assign('assos', $req->fetchAllAssoc());
642 }
643
644 function handler_xnetlogo($page, $id)
645 {
646 if (is_null($id)) {
647 return PL_NOT_FOUND;
648 }
649
650 $res = XDB::query('SELECT logo, logo_mime
651 FROM groups
652 WHERE id = {?}', $id);
653 list($logo, $logo_mime) = $res->fetchOneRow();
654
655 if (!empty($logo)) {
656 pl_cached_dynamic_content_headers($logo_mime);
657 echo $logo;
658 } else {
659 pl_cached_dynamic_content_headers("image/jpeg");
660 readfile(dirname(__FILE__) . '/../htdocs/images/dflt_carre.jpg');
661 }
662
663 exit;
664 }
665
666 function handler_vcard($page, $x = null)
667 {
668 if (is_null($x)) {
669 return PL_NOT_FOUND;
670 }
671
672 global $globals;
673
674 if (substr($x, -4) == '.vcf') {
675 $x = substr($x, 0, strlen($x) - 4);
676 }
677
678 $vcard = new VCard();
679 $vcard->addProfile(Profile::get($x, Profile::FETCH_ALL));
680 $vcard->show();
681 }
682
683 function handler_admin_trombino($page, $login = null, $action = null) {
684 $page->changeTpl('profile/admin_trombino.tpl');
685 $page->setTitle('Administration - Trombino');
686
687 if (!$login || !($user = User::get($login))) {
688 return PL_NOT_FOUND;
689 } else {
690 $page->assign_by_ref('user', $user);
691 }
692
693 switch ($action) {
694 case "original":
695 PlImage::fromFile("/home/web/trombino/photos" . $user->promo() . "/" . $user->login() . ".jpg", "image/jpeg")->send();
696 exit;
697
698 case "new":
699 S::assert_xsrf_token();
700
701 $data = file_get_contents($_FILES['userfile']['tmp_name']);
702 list($x, $y) = getimagesize($_FILES['userfile']['tmp_name']);
703 $mimetype = substr($_FILES['userfile']['type'], 6);
704 unlink($_FILES['userfile']['tmp_name']);
705 XDB::execute('INSERT INTO profile_photos (pid, attachmime, attach, x, y)
706 VALUES ({?}, {?}, {?}, {?}, {?})
707 ON DUPLICATE KEY UPDATE attachmime = VALUES(attachmime), attach = VALUES(attach), x = VALUES(x), y = VALUES(y)',
708 $user->profile()->id(), $mimetype, $data, $x, $y);
709 break;
710
711 case "delete":
712 S::assert_xsrf_token();
713
714 XDB::execute('DELETE FROM profile_photos WHERE pid = {?}', $user->profile()->id());
715 break;
716 }
717 }
718 function handler_admin_names($page, $action = 'list', $id = null) {
719 $page->setTitle('Administration - Types de noms');
720 $page->assign('title', 'Gestion des types de noms');
721 $table_editor = new PLTableEditor('admin/names', 'profile_name_enum', 'id', true);
722 $table_editor->describe('name', 'Nom', true);
723 $table_editor->describe('explanations', 'Explications', true);
724 $table_editor->describe('type', 'Type', true);
725 $table_editor->describe('flags', 'Flags', true);
726 $table_editor->describe('score', 'Score', true);
727 $table_editor->apply($page, $action, $id);
728 }
729 function handler_admin_binets($page, $action = 'list', $id = null) {
730 $page->setTitle('Administration - Binets');
731 $page->assign('title', 'Gestion des binets');
732 $table_editor = new PLTableEditor('admin/binets', 'profile_binet_enum', 'id');
733 $table_editor->add_join_table('profile_binets','binet_id',true);
734 $table_editor->describe('text','intitulé',true);
735 $table_editor->apply($page, $action, $id);
736 }
737 function handler_admin_education($page, $action = 'list', $id = null) {
738 $page->setTitle('Administration - Formations');
739 $page->assign('title', 'Gestion des formations');
740 $table_editor = new PLTableEditor('admin/education', 'profile_education_enum', 'id');
741 $table_editor->add_join_table('profile_education', 'eduid', true);
742 $table_editor->add_join_table('profile_education_degree', 'eduid', true);
743 $table_editor->describe('name', 'intitulé', true);
744 $table_editor->describe('url', 'site web', false);
745 $table_editor->apply($page, $action, $id);
746 }
747 function handler_admin_education_field($page, $action = 'list', $id = null) {
748 $page->setTitle('Administration - Domaines de formation');
749 $page->assign('title', 'Gestion des domaines de formation');
750 $table_editor = new PLTableEditor('admin/education_field', 'profile_education_field_enum', 'id', true);
751 $table_editor->add_join_table('profile_education', 'fieldid', true);
752 $table_editor->describe('field', 'domaine', true);
753 $table_editor->apply($page, $action, $id);
754 }
755 function handler_admin_education_degree($page, $action = 'list', $id = null) {
756 $page->setTitle('Administration - Niveau de formation');
757 $page->assign('title', 'Gestion des niveau de formation');
758 $table_editor = new PLTableEditor('admin/education_degree', 'profile_education_degree_enum', 'id');
759 $table_editor->add_join_table('profile_education_degree', 'degreeid', true);
760 $table_editor->add_join_table('profile_education', 'degreeid', true);
761 $table_editor->describe('degree', 'niveau', true);
762 $table_editor->apply($page, $action, $id);
763 }
764 function handler_admin_education_degree_set($page, $action = 'list', $id = null, $id2 = null) {
765 $page->setTitle('Administration - Correspondances formations - niveau de formation');
766 $page->assign('title', 'Gestion des correspondances formations - niveau de formation');
767 $table_editor = new PLTableEditor('admin/education_degree_set', 'profile_education_degree', 'eduid', true, 'degreeid');
768 $table_editor->describe('eduid', 'id formation', true);
769 $table_editor->describe('degreeid', 'id niveau', true);
770
771 // Adds fields to show the names of education
772 $table_editor->add_option_table('profile_education_enum','profile_education_enum.id = eduid');
773 $table_editor->add_option_field('profile_education_enum.name', 'edu_name', 'formation', null, 'degreeid');
774 // Adds fields to show the names of degrees
775 $table_editor->add_option_table('profile_education_degree_enum','profile_education_degree_enum.id = t.degreeid');
776 $table_editor->add_option_field('profile_education_degree_enum.degree', 'degree_name', 'niveau');
777
778 $table_editor->apply($page, $action, $id, $id2);
779 }
780 function handler_admin_sections($page, $action = 'list', $id = null) {
781 $page->setTitle('Administration - Sections');
782 $page->assign('title', 'Gestion des sections');
783 $table_editor = new PLTableEditor('admin/sections','profile_section_enum','id');
784 $table_editor->describe('text','intitulé',true);
785 $table_editor->apply($page, $action, $id);
786 }
787 function handler_admin_networking($page, $action = 'list', $id = null) {
788 $page->assign('xorg_title', 'Polytechnique.org - Administration - Networking');
789 $page->assign('title', 'Gestion des types de networking');
790 $table_editor = new PLTableEditor('admin/networking', 'profile_networking_enum', 'nwid');
791 $table_editor->describe('name', 'intitulé', true);
792 $table_editor->describe('icon', 'nom de l\'icône', false);
793 $table_editor->describe('filter', 'filtre', true);
794 $table_editor->describe('link', 'lien web', true);
795 $table_editor->apply($page, $action, $id);
796 }
797 function handler_admin_corps_enum($page, $action = 'list', $id = null) {
798 $page->setTitle('Administration - Corps');
799 $page->assign('title', 'Gestion des Corps');
800 $table_editor = new PLTableEditor('admin/corps_enum', 'profile_corps_enum', 'id');
801 $table_editor->describe('name', 'intitulé', true);
802 $table_editor->describe('abbreviation', 'abbréviation', true);
803 $table_editor->describe('still_exists', 'existe encore ?', true);
804 $table_editor->apply($page, $action, $id);
805 }
806 function handler_admin_corps_rank($page, $action = 'list', $id = null) {
807 $page->setTitle('Administration - Grade dans les Corps');
808 $page->assign('title', 'Gestion des grade dans les Corps');
809 $table_editor = new PLTableEditor('admin/corps_rank', 'profile_corps_rank_enum', 'id');
810 $table_editor->describe('name', 'intitulé', true);
811 $table_editor->describe('abbreviation', 'abbréviation', true);
812 $table_editor->apply($page, $action, $id);
813 }
814 function handler_admin_medals($page, $action = 'list', $id = null) {
815 $page->setTitle('Administration - Distinctions');
816 $page->assign('title', 'Gestion des Distinctions');
817 $table_editor = new PLTableEditor('admin/medals','profile_medal_enum','id');
818 $table_editor->describe('text', 'intitulé', true);
819 $table_editor->describe('img', 'nom de l\'image', false);
820 $table_editor->describe('flags', 'valider', true);
821 $table_editor->apply($page, $action, $id);
822 if ($id && $action == 'edit') {
823 $page->changeTpl('profile/admin_decos.tpl');
824
825 $mid = $id;
826
827 if (Post::v('act') == 'del') {
828 XDB::execute('DELETE FROM profile_medal_grade_enum
829 WHERE mid={?} AND gid={?}', $mid, Post::i('gid'));
830 } else {
831 foreach (Post::v('grades', array()) as $gid=>$text) {
832 if ($gid === 0) {
833 if (!empty($text)) {
834 $res = XDB::query('SELECT MAX(gid)
835 FROM profile_medal_grade_enum
836 WHERE mid = {?}', $mid);
837 $gid = $res->fetchOneCell() + 1;
838
839 XDB::execute('INSERT INTO profile_medal_grade_enum (mid, gid, text, pos)
840 VALUES ({?}, {?}, {?}, {?})',
841 $mid, $gid, $text, $_POST['pos']['0']);
842 }
843 } else {
844 XDB::execute('UPDATE profile_medal_grade_enum
845 SET pos={?}, text={?}
846 WHERE gid={?} AND mid={?}', $_POST['pos'][$gid], $text, $gid, $mid);
847 }
848 }
849 }
850 $res = XDB::iterator('SELECT gid, text, pos FROM profile_medal_grade_enum WHERE mid={?} ORDER BY pos', $mid);
851 $page->assign('grades', $res);
852 }
853 }
854 }
855
856 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
857 ?>