Specifies we only display places where profiles live.
[platal.git] / modules / search.php
CommitLineData
09824164 1<?php
2/***************************************************************************
5e1513f6 3 * Copyright (C) 2003-2011 Polytechnique.org *
09824164 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
22class SearchModule extends PLModule
23{
24 function handlers()
25 {
26 return array(
5ae3e9a9
SJ
27 'search' => $this->make_hook('quick', AUTH_PUBLIC),
28 'search/adv' => $this->make_hook('advanced', AUTH_COOKIE, 'directory_ax'),
29 'advanced_search.php' => $this->make_hook('redir_advanced', AUTH_PUBLIC),
30 'search/autocomplete' => $this->make_hook('autocomplete', AUTH_COOKIE, 'directory_ax', NO_AUTH),
31 'search/list' => $this->make_hook('list', AUTH_COOKIE, 'directory_ax', NO_AUTH),
a67a14b4 32 'search/list/count' => $this->make_hook('list_count', AUTH_COOKIE, 'directory_ax', NO_AUTH),
5ae3e9a9
SJ
33 'jobs' => $this->make_hook('referent', AUTH_COOKIE),
34 'emploi' => $this->make_hook('referent', AUTH_COOKIE),
35 'referent/search' => $this->make_hook('referent', AUTH_COOKIE),
36 'search/referent/countries' => $this->make_hook('referent_countries', AUTH_COOKIE),
09824164 37 );
38 }
39
26ba053e 40 function handler_redir_advanced($page, $mode = null)
ba2afb88 41 {
42 pl_redirect('search/adv');
43 exit;
44 }
45
09824164 46 function form_prepare()
47 {
d7610c35 48 Platal::page()->assign('formulaire',1);
3c640222 49 }
50
8eb6931f
RB
51 /**
52 * $model: The way of presenting the results: minifiche, trombi, geoloc.
53 * $byletter: Show only names beginning with this letter
54 */
26ba053e 55 function handler_quick($page, $model = null, $byletter = null)
09824164 56 {
57 global $globals;
58
8eb6931f 59 if (Env::has('quick') || $model == 'geoloc') {
dd23c027 60 $quick = Env::t('quick');
85bb670b 61 if (S::logged() && !Env::has('page')) {
732e5855 62 S::logger()->log('search', 'quick=' . $quick);
e31c1c3e 63 }
dd23c027
SJ
64
65 if ($quick == '') {
66 $page->trigWarning('Aucun critère de recherche n\'est spécifié.');
67 $page->changeTpl('search/index.tpl');
68 $page->setTitle('Annuaire');
69 $page->assign('formulaire', 1);
dd23c027
SJ
70 return;
71 }
72
383bcdec 73 $list = 'profile|prf|fiche|fic|referent|ref|mentor';
dd70cd28 74 if (S::admin()) {
383bcdec 75 $list .= '|admin|adm|ax';
76 }
251ac585
FB
77 $suffixes = array_keys(DirEnum::getOptions(DirEnum::ACCOUNTTYPES));
78 $suffixes = implode('|', $suffixes);
79 if (preg_match('/^(' . $list . '):([-a-z]+(\.[-a-z]+(\.(?:[md]?\d{2,4}|' . $suffixes . '))?)?)$/', replace_accent($quick), $matches)) {
4514bea3 80 $login = $matches[2];
383bcdec 81 switch($matches[1]) {
82 case 'admin': case 'adm':
83 $base = 'admin/user/';
84 break;
85 case 'ax':
86 $base = 'profile/ax/';
87 break;
88 case 'profile': case 'prf': case 'fiche': case 'fic':
89 $base = 'profile/';
90 break;
91 case 'referent': case 'ref': case 'mentor':
92 $base = 'referent/';
93 break;
94 }
7511200d 95
4514bea3
VZ
96 $user = User::getSilent($login);
97 if ($user) {
98 pl_redirect($base . $user->login());
7511200d 99 }
ed06daba 100 Get::set('quick', $login);
8fee4fbd 101 } elseif (strpos($quick, 'doc:') === 0) {
102 $url = 'Docs/Recherche?';
103 $url .= 'action=search&q=' . urlencode(substr($quick, 4));
7511200d 104 $url .= '&group=' . urlencode('-Equipe,-Main,-PmWiki,-Site,-Review');
8fee4fbd 105 pl_redirect($url);
85b45717
FB
106 } elseif (strpos($quick, 'trombi:') === 0) {
107 $promo = substr($quick, 7);
108 $res = XDB::query("SELECT diminutif
109 FROM groups
110 WHERE cat = 'Promotions' AND diminutif = {?}",
111 $promo);
112 if ($res->numRows() == 0) {
113 $page->trigWarning("La promotion demandée n'est pas valide: $promo");
114 } else {
115 http_redirect('http://www.polytechnique.net/login/' . $promo . '/annuaire/trombi');
116 }
383bcdec 117 }
8fee4fbd 118
09824164 119 $page->assign('formulaire', 0);
120
8c4a0c30 121 require_once 'userset.inc.php';
78a47eb4 122 $view = new QuickSearchSet();
8eb6931f 123 $view->addMod('minifiche', 'Mini-fiches', true, array('with_score' => true, 'starts_with' => $byletter));
35fa92e8 124 if (S::logged() && !Env::i('nonins')) {
125 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true, 'with_score' => true));
0a928a2f 126 $view->addMod('map', 'Planisphère');
35fa92e8 127 }
8eb6931f 128 $view->apply('search', $page, $model);
09824164 129
8c4a0c30 130 $nb_tot = $view->count();
e35882be 131 $page->assign('search_results_nb', $nb_tot);
cab08090 132 if (!S::logged() && $nb_tot > $globals->search->public_max) {
825a13a4 133 $page->trigError('Votre recherche a généré trop de résultats pour un affichage public.');
09824164 134 } elseif ($nb_tot > $globals->search->private_max) {
825a13a4 135 $page->trigError('Recherche trop générale. Une <a href="search/adv">recherche avancée</a> permet de préciser la recherche.');
09824164 136 } elseif (empty($nb_tot)) {
825a13a4 137 $page->trigError('Il n\'existe personne correspondant à ces critères dans la base !');
09824164 138 }
139 } else {
140 $page->assign('formulaire',1);
141 }
142
eaf30d86 143 $page->changeTpl('search/index.tpl');
46f272fe 144 $page->setTitle('Annuaire');
09824164 145 }
146
8eb6931f
RB
147 /** $model is the way of presenting the results: minifiche, trombi, geoloc.
148 */
26ba053e 149 function handler_advanced($page, $model = null, $byletter = null)
09824164 150 {
151 global $globals;
bc67c37c 152 $page->assign('advanced',1);
153
1d364832
RB
154 $networks = DirEnum::getOptions(DirEnum::NETWORKS);
155 $networks[-1] = 'Tous types';
156 $networks[0] = '-';
157 ksort($networks);
158 $page->assign('networking_types', $networks);
00f25ab1
SJ
159 $origin_corps_list = DirEnum::getOptions(DirEnum::CURRENTCORPS);
160 $current_corps_list = DirEnum::getOptions(DirEnum::ORIGINCORPS);
161 $corps_rank_list = DirEnum::getOptions(DirEnum::CORPSRANKS);
162 $origin_corps_list[0] = '-';
163 $current_corps_list[0] = '-';
164 $corps_rank_list[0] = '-';
165 ksort($origin_corps_list);
166 ksort($current_corps_list);
167 ksort($corps_rank_list);
168 $page->assign('origin_corps_list', $origin_corps_list);
169 $page->assign('current_corps_list', $current_corps_list);
170 $page->assign('corps_rank_list', $corps_rank_list);
1d364832 171
8eb6931f 172 if (!Env::has('rechercher') && $model != 'geoloc') {
09824164 173 $this->form_prepare();
174 } else {
e31c1c3e 175 if (!Env::has('page')) {
732e5855 176 S::logger()->log('search', 'adv=' . var_export($_GET, true));
e31c1c3e 177 }
137e819f 178
8c4a0c30 179 require_once 'userset.inc.php';
0f567f55
RB
180 // Enable X.org fields for X.org admins, and AX fields for AX secretaries.
181 $view = new AdvancedSearchSet(S::admin(),
182 S::user()->checkPerms(User::PERM_EDIT_DIRECTORY));
183
51fcda84 184 if (!$view->isValid()) {
09824164 185 $this->form_prepare();
51fcda84
RB
186 $page->trigError('Recherche invalide.');
187 } else {
188 $view->addMod('minifiche', 'Mini-fiches', true, array('starts_with' => $byletter));
189 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true));
0a928a2f 190 $view->addMod('map', 'Planisphère');
39394cbf 191 if (S::user()->checkPerms(User::PERM_EDIT_DIRECTORY) || S::admin()) {
c442573a 192 $view->addMod('addresses', 'Adresses postales', false);
39394cbf 193 }
51fcda84
RB
194 $view->apply('search/adv', $page, $model);
195
196 $nb_tot = $view->count();
197 if ($nb_tot > $globals->search->private_max) {
198 $this->form_prepare();
39394cbf
SJ
199 if ($model != 'addresses' && (S::user()->checkPerms(User::PERM_EDIT_DIRECTORY) || S::admin())) {
200 $page->assign('suggestAddresses', true);
201 }
51fcda84
RB
202 $page->trigError('Recherche trop générale.');
203 } else if ($nb_tot == 0) {
204 $this->form_prepare();
205 $page->trigError('Il n\'existe personne correspondant à ces critères dans la base !');
206 }
09824164 207 }
09824164 208 }
209
8eb6931f 210 $page->changeTpl('search/index.tpl', $model == 'mini' ? SIMPLE : SKINNED);
8c4a0c30 211 $page->assign('public_directory',0);
09824164 212 }
3c640222 213
26ba053e 214 function handler_autocomplete($page, $type = null)
838cc16a 215 {
216 // Autocompletion : according to type required, return
217 // a list of results matching with the number of matches.
218 // The output format is :
219 // result1|nb1
220 // result2|nb2
221 // ...
3cb500d5 222 pl_content_headers("text/plain");
ff3eb9b7 223 $q = preg_replace(array('/\*+$/', // always look for $q*
224 '/([\^\$\[\]])/', // escape special regexp char
225 '/\*/'), // replace joker by regexp joker
226 array('',
227 '\\\\\1',
228 '.*'),
78e4b1f6 229 Env::s('q'));
838cc16a 230 if (!$q) exit();
c15afc4e 231
eaf30d86 232 // try to look in cached results
78e4b1f6
FB
233 $cache = XDB::query('SELECT result
234 FROM search_autocomplete
235 WHERE name = {?} AND
236 query = {?} AND
237 generated > NOW() - INTERVAL 1 DAY',
ff3eb9b7 238 $type, $q);
c15afc4e 239 if ($res = $cache->fetchOneCell()) {
ff3eb9b7 240 echo $res;
241 die();
c15afc4e 242 }
eaf30d86 243
8e720253
RB
244 $enums = array(
245 'binetTxt' => DirEnum::BINETS,
246 'groupexTxt' => DirEnum::GROUPESX,
247 'sectionTxt' => DirEnum::SECTIONS,
248 'networking_typeTxt' => DirEnum::NETWORKS,
a67a14b4 249 'localityTxt' => DirEnum::LOCALITIES,
8e720253
RB
250 'countryTxt' => DirEnum::COUNTRIES,
251 'entreprise' => DirEnum::COMPANIES,
3ac45f10 252 'jobtermTxt' => DirEnum::JOBTERMS,
8e720253
RB
253 'description' => DirEnum::JOBDESCRIPTION,
254 'nationaliteTxt' => DirEnum::NATIONALITIES,
fb3b6547 255 'schoolTxt' => DirEnum::EDUSCHOOLS,
8e720253 256 );
9d44d2c7 257 if (!array_key_exists($type, $enums)) {
8e720253 258 exit();
838cc16a 259 }
260
8e720253 261 $enum = $enums[$type];
f781871c 262
8e720253 263 $list = DirEnum::getAutoComplete($enum, $q);
838cc16a 264 $nbResults = 0;
c15afc4e 265 $res = "";
2ab7a09f 266 while ($result = $list->next()) {
838cc16a 267 $nbResults++;
268 if ($nbResults == 11) {
b3ec63d5 269 $res .= $q."|-1\n";
838cc16a 270 } else {
f6818108 271 $res .= $result['field'].'|';
c7139c07
SJ
272 if (isset($result['nb'])) {
273 $res .= $result['nb'];
274 }
ff3eb9b7 275 if (isset($result['id'])) {
276 $res .= '|'.$result['id'];
277 }
278 $res .= "\n";
838cc16a 279 }
280 }
fb6dc875
PC
281 if ($nbResults == 0) {
282 $res = $q."|-2\n";
283 }
00ba8a74
SJ
284 XDB::query('INSERT INTO search_autocomplete (name, query, result, generated)
285 VALUES ({?}, {?}, {?}, NOW())
a245a3e1 286 ON DUPLICATE KEY UPDATE result = VALUES(result), generated = VALUES(generated)',
00ba8a74 287 $type, $q, $res);
c15afc4e 288 echo $res;
838cc16a 289 exit();
290 }
eaf30d86 291
26ba053e 292 function handler_list($page, $type = null, $idVal = null)
2ab7a09f 293 {
ffd70398
PC
294 $page->assign('name', $type);
295 $page->assign('with_text_value', true);
296 $page->assign('onchange', "document.forms.recherche.{$type}Txt.value = this.options[this.selectedIndex].text");
297
ff3eb9b7 298 // Give the list of all values possible of type and builds a select input for it
8e720253 299 $ids = null;
ff3eb9b7 300
301 switch ($type) {
8e720253 302 case 'binet':
2998edf1 303 $ids = DirEnum::getOptionsIter(DirEnum::BINETS);
ff3eb9b7 304 break;
92c3f9e5 305 case 'networking_type':
2998edf1 306 $ids = DirEnum::getOptionsIter(DirEnum::NETWORKS);
92c3f9e5 307 break;
ff3eb9b7 308 case 'country':
2998edf1 309 $ids = DirEnum::getOptionsIter(DirEnum::COUNTRIES);
a67a14b4
SJ
310 $page->assign('onchange', 'changeAddressComponents(\'' . $type . '\', this.value)');
311 break;
312 case 'administrative_area_level_1':
313 case 'administrative_area_level_2':
314 case 'administrative_area_level_3':
315 case 'locality':
316 $page->assign('onchange', 'changeAddressComponents(\'' . $type . '\', this.value)');
317 case 'sublocality':
318 $ids = XDB::iterator("SELECT pace1.id, pace1.long_name AS field
319 FROM profile_addresses_components_enum AS pace1
320 INNER JOIN profile_addresses_components AS pac1 ON (pac1.component_id = pace1.id)
321 INNER JOIN profile_addresses_components AS pac2 ON (pac1.pid = pac2.pid AND pac1.jobid = pac2.jobid AND pac1.id = pac2.id
322 AND pac1.groupid = pac2.groupid AND pac1.type = pac2.type)
323 INNER JOIN profile_addresses_components_enum AS pace2 ON (pac2.component_id = pace2.id AND FIND_IN_SET({?}, pace2.types))
7757efd6 324 WHERE pace2.id = {?} AND FIND_IN_SET({?}, pace1.types) AND pac1.type = 'home'
a67a14b4
SJ
325 GROUP BY pace1.long_name",
326 Env::v('previous'), Env::v('value'), $type);
ff3eb9b7 327 break;
ff3eb9b7 328 case 'diploma':
8e720253 329 if (Env::has('school') && Env::i('school') != 0) {
2998edf1 330 $ids = DirEnum::getOptionsIter(DirEnum::EDUDEGREES, Env::i('school'));
8e720253 331 } else {
2998edf1 332 $ids = DirEnum::getOptionsIter(DirEnum::EDUDEGREES);
8e720253
RB
333 }
334 break;
ff3eb9b7 335 case 'groupex':
2998edf1 336 $ids = DirEnum::getOptionsIter(DirEnum::GROUPESX);
ff3eb9b7 337 break;
338 case 'nationalite':
2998edf1 339 $ids = DirEnum::getOptionsIter(DirEnum::NATIONALITIES);
ff3eb9b7 340 break;
ff3eb9b7 341 case 'school':
2998edf1 342 $ids = DirEnum::getOptionsIter(DirEnum::EDUSCHOOLS);
ff3eb9b7 343 $page->assign('onchange', 'changeSchool(this.value)');
344 break;
345 case 'section':
2998edf1 346 $ids = DirEnum::getOptionsIter(DirEnum::SECTIONS);
ff3eb9b7 347 break;
3ac45f10
PC
348 case 'jobterm':
349 if (Env::has('jtid')) {
26ba053e 350 JobTerms::ajaxGetBranch($page, JobTerms::ONLY_JOBS);
3ac45f10
PC
351 return;
352 } else {
353 pl_content_headers('text/xml');
354 echo '<div>'; // global container so that response is valid xml
355 echo '<input name="jobtermTxt" type="text" style="display:none" size="32" />';
356 echo '<input name="jobterm" type="hidden"/>';
357 echo '<div class="term_tree"></div>'; // container where to create the tree
358 echo '<script type="text/javascript" src="javascript/jquery.jstree.js"></script>';
359 echo '<script type="text/javascript" src="javascript/jobtermstree.js"></script>';
360 echo '<script type="text/javascript">createJobTermsTree(".term_tree", "search/list/jobterm", "search", "searchForJobTerm");</script>';
361 echo '</div>';
362 exit();
363 }
ff3eb9b7 364 default: exit();
365 }
366 if (isset($idVal)) {
3cb500d5 367 pl_content_headers("text/plain");
8e720253 368 echo $ids[$idVal];
ff3eb9b7 369 exit();
370 }
3cb500d5 371 pl_content_headers("text/xml");
05cb05c0 372 $page->changeTpl('include/field.select.tpl', NO_SKIN);
8e720253 373 $page->assign('list', $ids);
2ab7a09f 374 }
9dc65790 375
26ba053e 376 function handler_referent($page, $action = null, $subaction = null)
9dc65790 377 {
459e6f81
PC
378 global $globals;
379
9dc65790
PC
380 $wp = new PlWikiPage('Docs.Emploi');
381 $wp->buildCache();
382
383 $page->setTitle('Emploi et Carrières');
384
4ec03752 385 // Count mentors
9dc65790
PC
386 $res = XDB::query("SELECT count(distinct pid) FROM profile_mentor_term");
387 $page->assign('mentors_number', $res->fetchOneCell());
388
4ec03752 389 // Search for mentors matching filters
9dc65790
PC
390 require_once 'ufbuilder.inc.php';
391 $ufb = new UFB_MentorSearch();
392 if (!$ufb->isEmpty()) {
393 require_once 'userset.inc.php';
394 $ufc = $ufb->getUFC();
395 $set = new ProfileSet($ufc);
396 $set->addMod('mentor', 'Référents');
397 $set->apply('referent/search', $page, $action, $subaction);
459e6f81
PC
398 $nb_tot = $set->count();
399 if ($nb_tot > $globals->search->private_max) {
400 $this->form_prepare();
401 $page->trigError('Recherche trop générale.');
402 $page->assign('plset_count', 0);
403 } else if ($nb_tot == 0) {
404 $this->form_prepare();
405 $page->trigError('Il n\'existe personne correspondant à ces critères dans la base.');
9dc65790
PC
406 }
407 }
408
409 $page->changeTpl('search/referent.tpl');
410 }
411
459e6f81
PC
412 /**
413 * Builds a select field to choose among countries that referents
414 * know about. Only referents linked to term (jtid) are displayed.
415 * @param $jtid id of job term to restrict referents
416 */
26ba053e 417 function handler_referent_countries($page, $jtid = null)
459e6f81
PC
418 {
419 pl_content_headers("text/xml");
420 $page->changeTpl('include/field.select.tpl', NO_SKIN);
421 $page->assign('name', 'country');
1c305d4c 422 $it = XDB::iterator("SELECT gc.iso_3166_1_a2 AS id, gc.country AS field
459e6f81
PC
423 FROM geoloc_countries AS gc
424 INNER JOIN profile_mentor_country AS mp ON (mp.country = gc.iso_3166_1_a2)
425 INNER JOIN profile_mentor_term AS mt ON (mt.pid = mp.pid)
426 INNER JOIN profile_job_term_relation AS jtr ON (jtr.jtid_2 = mt.jtid)
427 WHERE jtr.jtid_1 = {?}
d6f2c926
SJ
428 GROUP BY gc.iso_3166_1_a2
429 ORDER BY gc.country", $jtid);
459e6f81
PC
430 $page->assign('list', $it);
431 }
09824164 432}
433
a7de4ef7 434// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
09824164 435?>