Switches autocomplete to jQuery UI.
[platal.git] / modules / search.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 SearchModule extends PLModule
23 {
24 function handlers()
25 {
26 return array(
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),
32 'search/list/count' => $this->make_hook('list_count', AUTH_COOKIE, 'directory_ax', NO_AUTH),
33 'jobs' => $this->make_hook('referent', AUTH_COOKIE, 'user'),
34 'emploi' => $this->make_hook('referent', AUTH_COOKIE, 'user'),
35 'referent/search' => $this->make_hook('referent', AUTH_COOKIE, 'user'),
36 'search/referent/countries' => $this->make_hook('referent_countries', AUTH_COOKIE, 'user'),
37 );
38 }
39
40 function handler_redir_advanced($page, $mode = null)
41 {
42 pl_redirect('search/adv');
43 exit;
44 }
45
46 function form_prepare()
47 {
48 Platal::page()->assign('formulaire',1);
49 }
50
51 /**
52 * $model: The way of presenting the results: minifiche, trombi, geoloc.
53 * $byletter: Show only names beginning with this letter
54 */
55 function handler_quick($page, $model = null, $byletter = null)
56 {
57 global $globals;
58
59 if (Env::has('quick') || $model == 'geoloc') {
60 $quick = Env::t('quick');
61 if (S::logged() && !Env::has('page')) {
62 S::logger()->log('search', 'quick=' . $quick);
63 }
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);
70 return;
71 }
72
73 $list = 'profile|prf|fiche|fic|referent|ref|mentor';
74 if (S::admin()) {
75 $list .= '|admin|adm|ax';
76 }
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)) {
80 $login = $matches[2];
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 }
95
96 $user = User::getSilent($login);
97 if ($user) {
98 pl_redirect($base . $user->login());
99 }
100 Get::set('quick', $login);
101 } elseif (strpos($quick, 'doc:') === 0) {
102 $url = 'Docs/Recherche?';
103 $url .= 'action=search&q=' . urlencode(substr($quick, 4));
104 $url .= '&group=' . urlencode('-Equipe,-Main,-PmWiki,-Site,-Review');
105 pl_redirect($url);
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 }
117 }
118
119 $page->assign('formulaire', 0);
120
121 require_once 'userset.inc.php';
122 $view = new QuickSearchSet();
123 $view->addMod('minifiche', 'Mini-fiches', true, array('with_score' => true, 'starts_with' => $byletter));
124 $view->addMod('map', 'Planisphère');
125 if (S::logged() && !Env::i('nonins')) {
126 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true, 'with_score' => true));
127 }
128 $view->apply('search', $page, $model);
129
130 $nb_tot = $view->count();
131 $page->assign('search_results_nb', $nb_tot);
132 if (!S::logged() && $nb_tot > $globals->search->public_max) {
133 $page->trigError('Votre recherche a généré trop de résultats pour un affichage public.');
134 } elseif ($nb_tot > $globals->search->private_max) {
135 $page->trigError('Recherche trop générale. Une <a href="search/adv">recherche avancée</a> permet de préciser la recherche.');
136 } elseif (empty($nb_tot)) {
137 $page->trigError('Il n\'existe personne correspondant à ces critères dans la base !');
138 }
139 } else {
140 $page->assign('formulaire',1);
141 }
142
143 $page->changeTpl('search/index.tpl');
144 $page->setTitle('Annuaire');
145 }
146
147 /** $model is the way of presenting the results: minifiche, trombi, geoloc.
148 */
149 function handler_advanced($page, $model = null, $byletter = null)
150 {
151 global $globals;
152 $page->addJsLink('jquery.ui.xorg.js');
153 $page->addJsLink('search.js');
154 $page->assign('advanced',1);
155
156 $networks = DirEnum::getOptions(DirEnum::NETWORKS);
157 $networks[-1] = 'Tous types';
158 $networks[0] = '-';
159 ksort($networks);
160 $page->assign('networking_types', $networks);
161 $origin_corps_list = DirEnum::getOptions(DirEnum::CURRENTCORPS);
162 $current_corps_list = DirEnum::getOptions(DirEnum::ORIGINCORPS);
163 $corps_rank_list = DirEnum::getOptions(DirEnum::CORPSRANKS);
164 $origin_corps_list[0] = '-';
165 $current_corps_list[0] = '-';
166 $corps_rank_list[0] = '-';
167 ksort($origin_corps_list);
168 ksort($current_corps_list);
169 ksort($corps_rank_list);
170 $page->assign('origin_corps_list', $origin_corps_list);
171 $page->assign('current_corps_list', $current_corps_list);
172 $page->assign('corps_rank_list', $corps_rank_list);
173
174 if (!Env::has('rechercher') && $model != 'geoloc') {
175 $this->form_prepare();
176 } else {
177 if (!Env::has('page')) {
178 S::logger()->log('search', 'adv=' . var_export($_GET, true));
179 }
180
181 require_once 'userset.inc.php';
182 // Enable X.org fields for X.org admins, and AX fields for AX secretaries.
183 $view = new AdvancedSearchSet(S::admin(),
184 S::user()->checkPerms(User::PERM_EDIT_DIRECTORY));
185
186 if (!$view->isValid()) {
187 $this->form_prepare();
188 $page->trigError('Recherche invalide.');
189 } else {
190 $view->addMod('minifiche', 'Mini-fiches', true, array('starts_with' => $byletter));
191 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true));
192 $view->addMod('map', 'Planisphère');
193 if (S::user()->checkPerms(User::PERM_EDIT_DIRECTORY) || S::admin()) {
194 $view->addMod('addresses', 'Adresses postales', false);
195 }
196 $view->apply('search/adv', $page, $model);
197
198 $nb_tot = $view->count();
199 if ($nb_tot > $globals->search->private_max) {
200 $this->form_prepare();
201 if ($model != 'addresses' && (S::user()->checkPerms(User::PERM_EDIT_DIRECTORY) || S::admin())) {
202 $page->assign('suggestAddresses', true);
203 }
204 $page->trigError('Recherche trop générale.');
205 } else if ($nb_tot == 0) {
206 $this->form_prepare();
207 $page->trigError('Il n\'existe personne correspondant à ces critères dans la base !');
208 }
209 }
210 }
211
212 $page->changeTpl('search/index.tpl', $model == 'mini' ? SIMPLE : SKINNED);
213 $page->assign('public_directory',0);
214 }
215
216 private function format_autocomplete(array $item)
217 {
218 return $item['field'] . ' (' . $item['nb'] . ' camarade' . ($item['nb'] > 1 ? 's' : '') . ')';
219 }
220
221 function handler_autocomplete($page, $type = null)
222 {
223 // Autocompletion : according to type required, return
224 // a list of results matching with the number of matches.
225 // The output format is :
226 // result1|nb1
227 // result2|nb2
228 // ...
229 pl_content_headers("text/plain");
230 $q = preg_replace(array('/\*+$/', // always look for $q*
231 '/([\^\$\[\]])/', // escape special regexp char
232 '/\*/'), // replace joker by regexp joker
233 array('',
234 '\\\\\1',
235 '.*'),
236 Get::t('term'));
237 if (!$q) {
238 exit();
239 }
240
241 // Try to look in cached results.
242 $cached = false;
243 $cache = XDB::query('SELECT result
244 FROM search_autocomplete
245 WHERE name = {?} AND query = {?} AND generated > NOW() - INTERVAL 1 DAY',
246 $type, $q);
247
248 if ($cache->numRows() > 0) {
249 $cached = true;
250 $data = explode("\n", $cache->fetchOneCell());
251 $list = array();
252 foreach ($data as $line) {
253 if ($line != '') {
254 $aux = explode("\t", $line);
255 $item = array(
256 'field' => $aux[0],
257 'nb' => $aux[1],
258 'id' => $aux[2]
259 );
260 $item['value'] = $this->format_autocomplete($item);
261 array_push($list, $item);
262 }
263 }
264 } else {
265 $enums = array(
266 'binet_text' => DirEnum::BINETS,
267 'groupex_text' => DirEnum::GROUPESX,
268 'section_text' => DirEnum::SECTIONS,
269 'networking_type_text' => DirEnum::NETWORKS,
270 'locality_text' => DirEnum::LOCALITIES,
271 'country_text' => DirEnum::COUNTRIES,
272 'entreprise' => DirEnum::COMPANIES,
273 'jobterm_text' => DirEnum::JOBTERMS,
274 'description' => DirEnum::JOBDESCRIPTION,
275 'nationalite_text' => DirEnum::NATIONALITIES,
276 'school_text' => DirEnum::EDUSCHOOLS,
277 );
278 if (!array_key_exists($type, $enums)) {
279 exit();
280 }
281
282 $list = DirEnum::getAutoComplete($enums[$type], $q);
283 $to_cache = '';
284 foreach ($list as &$item) {
285 $to_cache .= $item['field'] . "\t" . $item['nb'] . "\t" . $item['id'] . "\n";
286 $item['value'] = $this->format_autocomplete($item);
287 }
288 }
289
290 $count = count($list);
291 if ($count == DirEnumeration::AUTOCOMPLETE_LIMIT) {
292 $list[] = array(
293 'value' => '…',
294 'field' => '',
295 'nb' => 0,
296 'id' => -1
297 );
298 } elseif ($count == 0) {
299 $list[] = array(
300 'value' => 'Aucun camarade trouvé pour ' . $q . '.',
301 'field' => '',
302 'nb' => 0,
303 'id' => -1
304 );
305 }
306
307 if (!$cached) {
308 XDB::query('INSERT INTO search_autocomplete (name, query, result, generated)
309 VALUES ({?}, {?}, {?}, NOW())
310 ON DUPLICATE KEY UPDATE result = VALUES(result), generated = VALUES(generated)',
311 $type, $q, $to_cache);
312 }
313 echo json_encode($list);
314 exit();
315 }
316
317 function handler_list($page, $type = null, $idVal = null)
318 {
319 $page->assign('name', $type);
320 $page->assign('with_text_value', true);
321 $page->assign('onchange', "document.forms.recherche.{$type}Txt.value = this.options[this.selectedIndex].text");
322
323 // Give the list of all values possible of type and builds a select input for it
324 $ids = null;
325
326 switch ($type) {
327 case 'binet':
328 $ids = DirEnum::getOptionsIter(DirEnum::BINETS);
329 break;
330 case 'networking_type':
331 $ids = DirEnum::getOptionsIter(DirEnum::NETWORKS);
332 break;
333 case 'country':
334 $ids = DirEnum::getOptionsIter(DirEnum::COUNTRIES);
335 $page->assign('onchange', 'changeAddressComponents(\'' . $type . '\', this.value)');
336 break;
337 case 'administrative_area_level_1':
338 case 'administrative_area_level_2':
339 case 'locality':
340 $page->assign('onchange', 'changeAddressComponents(\'' . $type . '\', this.value)');
341 case 'postal_code':
342 $ids = XDB::iterator("SELECT pace1.id, pace1.long_name AS field
343 FROM profile_addresses_components_enum AS pace1
344 INNER JOIN profile_addresses_components AS pac1 ON (pac1.component_id = pace1.id)
345 INNER JOIN profile_addresses_components AS pac2 ON (pac1.pid = pac2.pid AND pac1.jobid = pac2.jobid AND pac1.id = pac2.id
346 AND pac1.groupid = pac2.groupid AND pac1.type = pac2.type)
347 INNER JOIN profile_addresses_components_enum AS pace2 ON (pac2.component_id = pace2.id AND FIND_IN_SET({?}, pace2.types))
348 WHERE pace2.id = {?} AND FIND_IN_SET({?}, pace1.types) AND pac1.type = 'home'
349 GROUP BY pace1.long_name",
350 Env::v('previous'), Env::v('value'), $type);
351 break;
352 case 'diploma':
353 if (Env::has('school') && Env::i('school') != 0) {
354 $ids = DirEnum::getOptionsIter(DirEnum::EDUDEGREES, Env::i('school'));
355 } else {
356 $ids = DirEnum::getOptionsIter(DirEnum::EDUDEGREES);
357 }
358 break;
359 case 'groupex':
360 $ids = DirEnum::getOptionsIter(DirEnum::GROUPESX);
361 break;
362 case 'nationalite':
363 $ids = DirEnum::getOptionsIter(DirEnum::NATIONALITIES);
364 break;
365 case 'school':
366 $ids = DirEnum::getOptionsIter(DirEnum::EDUSCHOOLS);
367 $page->assign('onchange', 'changeSchool(this.value)');
368 break;
369 case 'section':
370 $ids = DirEnum::getOptionsIter(DirEnum::SECTIONS);
371 break;
372 case 'jobterm':
373 if (Env::has('jtid')) {
374 JobTerms::ajaxGetBranch($page, JobTerms::ONLY_JOBS);
375 return;
376 } else {
377 pl_content_headers('text/xml');
378 echo '<div>'; // global container so that response is valid xml
379 echo '<input name="jobtermTxt" type="text" style="display:none" size="32" />';
380 echo '<input name="jobterm" type="hidden"/>';
381 echo '<div class="term_tree"></div>'; // container where to create the tree
382 echo '<script type="text/javascript" src="javascript/jquery.jstree.js"></script>';
383 echo '<script type="text/javascript" src="javascript/jobtermstree.js"></script>';
384 echo '<script type="text/javascript">createJobTermsTree(".term_tree", "search/list/jobterm", "search", "searchForJobTerm");</script>';
385 echo '</div>';
386 exit();
387 }
388 default: exit();
389 }
390 if (isset($idVal)) {
391 pl_content_headers("text/plain");
392 echo $ids[$idVal];
393 exit();
394 }
395 pl_content_headers("text/xml");
396 $page->changeTpl('include/field.select.tpl', NO_SKIN);
397 $page->assign('list', $ids);
398 }
399
400 function handler_referent($page, $action = null, $subaction = null)
401 {
402 global $globals;
403
404 $wp = new PlWikiPage('Docs.Emploi');
405 $wp->buildCache();
406
407 $page->setTitle('Emploi et Carrières');
408
409 // Count mentors
410 $res = XDB::query("SELECT count(distinct pid) FROM profile_mentor_term");
411 $page->assign('mentors_number', $res->fetchOneCell());
412
413 // Search for mentors matching filters
414 require_once 'ufbuilder.inc.php';
415 $ufb = new UFB_MentorSearch();
416 if (!$ufb->isEmpty()) {
417 require_once 'userset.inc.php';
418 $ufc = $ufb->getUFC();
419 $set = new ProfileSet($ufc);
420 $set->addMod('mentor', 'Référents');
421 $set->apply('referent/search', $page, $action, $subaction);
422 $nb_tot = $set->count();
423 if ($nb_tot > $globals->search->private_max) {
424 $this->form_prepare();
425 $page->trigError('Recherche trop générale.');
426 $page->assign('plset_count', 0);
427 } else if ($nb_tot == 0) {
428 $this->form_prepare();
429 $page->trigError('Il n\'existe personne correspondant à ces critères dans la base.');
430 }
431 }
432
433 $page->changeTpl('search/referent.tpl');
434 }
435
436 /**
437 * Builds a select field to choose among countries that referents
438 * know about. Only referents linked to term (jtid) are displayed.
439 * @param $jtid id of job term to restrict referents
440 */
441 function handler_referent_countries($page, $jtid = null)
442 {
443 pl_content_headers("text/xml");
444 $page->changeTpl('include/field.select.tpl', NO_SKIN);
445 $page->assign('name', 'country');
446 $it = XDB::iterator("SELECT gc.iso_3166_1_a2 AS id, gc.country AS field
447 FROM geoloc_countries AS gc
448 INNER JOIN profile_mentor_country AS mp ON (mp.country = gc.iso_3166_1_a2)
449 INNER JOIN profile_mentor_term AS mt ON (mt.pid = mp.pid)
450 INNER JOIN profile_job_term_relation AS jtr ON (jtr.jtid_2 = mt.jtid)
451 WHERE jtr.jtid_1 = {?}
452 GROUP BY gc.iso_3166_1_a2
453 ORDER BY gc.country", $jtid);
454 $page->assign('list', $it);
455 }
456 }
457
458 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
459 ?>