Switch to core-account
[platal.git] / modules / search.php
... / ...
CommitLineData
1<?php
2/***************************************************************************
3 * Copyright (C) 2003-2009 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
22class 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),
29 'advanced_search.php' => $this->make_hook('redir_advanced', AUTH_PUBLIC),
30 'search/autocomplete' => $this->make_hook('autocomplete', AUTH_COOKIE, 'user', NO_AUTH),
31 'search/list' => $this->make_hook('list', AUTH_COOKIE, 'user', NO_AUTH),
32 );
33 }
34
35 function handler_redir_advanced(&$page, $mode = null)
36 {
37 pl_redirect('search/adv');
38 exit;
39 }
40
41 function form_prepare()
42 {
43 Platal::page()->assign('formulaire',1);
44 }
45
46 function get_diplomas($school = null)
47 {
48 if (is_null($school) && Env::has('school')) {
49 $school = Env::i('school');
50 }
51
52 if ((!is_null($school)) && ($school != '')) {
53 $sql = 'SELECT degreeid
54 FROM profile_education_degree
55 WHERE eduid=' . $school;
56 } else {
57 $sql = 'SELECT id
58 FROM profile_education_degree_enum
59 ORDER BY id';
60 }
61
62 $res = XDB::query($sql);
63 Platal::page()->assign('choix_diplomas', $res->fetchColumn());
64
65 $sql = 'SELECT degree
66 FROM profile_education_degree_enum
67 ORDER BY id';
68 $res = XDB::query($sql);
69 Platal::page()->assign('name_diplomas', $res->fetchColumn());
70 }
71
72 function handler_quick(&$page, $action = null, $subaction = null)
73 {
74 global $globals;
75
76 $res = XDB::query("SELECT MIN(diminutif), MAX(diminutif)
77 FROM #groupex#.asso
78 WHERE cat = 'Promotions'");
79 list($min, $max) = $res->fetchOneRow();
80 $page->assign('promo_min', $min);
81 $page->assign('promo_max', $max);
82
83 if (Env::has('quick') || $action == 'geoloc') {
84 $quick = trim(Env::v('quick'));
85 if (S::logged() && !Env::has('page')) {
86 S::logger()->log('search', 'quick=' . $quick);
87 }
88 $list = 'profile|prf|fiche|fic|referent|ref|mentor';
89 if (S::admin()) {
90 $list .= '|admin|adm|ax';
91 }
92 if (preg_match('/^(' . $list . '):([-a-z]+(\.[-a-z]+(\.\d{2,4})?)?)$/', replace_accent($quick), $matches)) {
93 $login = $matches[2];
94 switch($matches[1]) {
95 case 'admin': case 'adm':
96 $base = 'admin/user/';
97 break;
98 case 'ax':
99 $base = 'profile/ax/';
100 break;
101 case 'profile': case 'prf': case 'fiche': case 'fic':
102 $base = 'profile/';
103 break;
104 case 'referent': case 'ref': case 'mentor':
105 $base = 'referent/';
106 break;
107 }
108
109 $user = User::getSilent($login);
110 if ($user) {
111 pl_redirect($base . $user->login());
112 }
113 $_REQUEST['quick'] = $login;
114 $_GET['quick'] = $login;
115 } elseif (strpos($quick, 'doc:') === 0) {
116 $url = 'Docs/Recherche?';
117 $url .= 'action=search&q=' . urlencode(substr($quick, 4));
118 $url .= '&group=' . urlencode('-Equipe,-Main,-PmWiki,-Site,-Review');
119 pl_redirect($url);
120 }
121
122 $page->assign('formulaire', 0);
123
124 require_once 'userset.inc.php';
125 $view = new SearchSet(true, $action == 'geoloc' && substr($subaction, -3) == 'swf');
126 $view->addMod('minifiche', 'Mini-fiches', true, array('with_score' => true));
127 if (S::logged() && !Env::i('nonins')) {
128 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true, 'with_score' => true));
129 // TODO: Reactivate when the new map is completed.
130 // $view->addMod('geoloc', 'Planisphère', false, array('with_annu' => 'search/adv'));
131 }
132 $view->apply('search', $page, $action, $subaction);
133
134 $nb_tot = $view->count();
135 $page->assign('search_results_nb', $nb_tot);
136 if ($subaction) {
137 return;
138 }
139 if (!S::logged() && $nb_tot > $globals->search->public_max) {
140 new ThrowError('Votre recherche a généré trop de résultats pour un affichage public.');
141 } elseif ($nb_tot > $globals->search->private_max) {
142 new ThrowError('Recherche trop générale. Une <a href="search/adv">recherche avancée</a> permet de préciser la recherche.');
143 } elseif (empty($nb_tot)) {
144 new ThrowError('Il n\'existe personne correspondant à ces critères dans la base !');
145 }
146 } else {
147 $page->assign('formulaire',1);
148 $page->addJsLink('ajax.js');
149 }
150
151 $this->load('search.inc.php');
152 $page->changeTpl('search/index.tpl');
153 $page->setTitle('Annuaire');
154 }
155
156 function handler_advanced(&$page, $action = null, $subaction = null)
157 {
158 global $globals;
159 require_once 'geocoding.inc.php';
160 $this->load('search.inc.php');
161 $page->assign('advanced',1);
162 $page->addJsLink('jquery.autocomplete.js');
163
164 if (!Env::has('rechercher') && $action != 'geoloc') {
165 $this->form_prepare();
166 } else {
167 $textFields = array(
168 'country' => array('field' => 'iso_3166_1_a2', 'table' => 'geoloc_countries', 'text' => 'countryFR',
169 'exact' => false),
170 'fonction' => array('field' => 'id', 'table' => 'fonctions_def', 'text' => 'fonction_fr', 'exact' => true),
171 'secteur' => array('field' => 'id', 'table' => 'profile_job_sector_enum', 'text' => 'name', 'exact' => false),
172 'nationalite' => array('field' => 'iso_3166_1_a2', 'table' => 'geoloc_countries',
173 'text' => 'nationalityFR', 'exact' => 'false'),
174 'binet' => array('field' => 'id', 'table' => 'binets_def', 'text' => 'text', 'exact' => false),
175 'networking_type' => array('field' => 'network_type', 'table' => 'profile_networking_enum',
176 'text' => 'name', 'exact' => false),
177 'groupex' => array('field' => 'id', 'table' => '#groupex#.asso',
178 'text' => "(cat = 'GroupesX' OR cat = 'Institutions') AND pub = 'public' AND nom",
179 'exact' => false),
180 'section' => array('field' => 'id', 'table' => 'sections', 'text' => 'text', 'exact' => false),
181 'school' => array('field' => 'id', 'table' => 'profile_education_enum', 'text' => 'name', 'exact' => false),
182 'city' => array('table' => 'geoloc_localities', 'text' => 'name', 'exact' => false)
183 );
184 if (!Env::has('page')) {
185 S::logger()->log('search', 'adv=' . var_export($_GET, true));
186 }
187 foreach ($textFields as $field=>&$query) {
188 if (!Env::v($field) && Env::v($field . 'Txt')) {
189 $res = XDB::query("SELECT {$query['field']}
190 FROM {$query['table']}
191 WHERE {$query['text']} " . ($query['exact'] ? " = {?}" :
192 " LIKE CONCAT('%', {?}, '%')"),
193 Env::v($field . 'Txt'));
194 $_REQUEST[$field] = $res->fetchOneCell();
195 }
196 }
197
198 require_once 'userset.inc.php';
199 $view = new SearchSet(false, $action == 'geoloc' && substr($subaction, -3) == 'swf');
200 $view->addMod('minifiche', 'Mini-fiches', true);
201 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true));
202 // TODO: Reactivate when the new map is completed.
203 // $view->addMod('geoloc', 'Planisphère', false, array('with_annu' => 'search/adv'));
204 $view->apply('search/adv', $page, $action, $subaction);
205
206 if ($subaction) {
207 return;
208 }
209 $nb_tot = $view->count();
210 if ($nb_tot > $globals->search->private_max) {
211 $this->form_prepare();
212 new ThrowError('Recherche trop générale.');
213 }
214 }
215
216 $page->changeTpl('search/index.tpl', $action == 'mini' ? SIMPLE : SKINNED);
217 $page->addJsLink('ajax.js');
218 $page->assign('public_directory',0);
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 Env::s('q'));
237 if (!$q) exit();
238
239 // try to look in cached results
240 $cache = XDB::query('SELECT result
241 FROM search_autocomplete
242 WHERE name = {?} AND
243 query = {?} AND
244 generated > NOW() - INTERVAL 1 DAY',
245 $type, $q);
246 if ($res = $cache->fetchOneCell()) {
247 echo $res;
248 die();
249 }
250
251 // default search
252 $unique = 'pid';
253 $db = 'profiles';
254 $realid = false;
255 $beginwith = true;
256 $field2 = false;
257 $qsearch = str_replace(array('%', '_'), '', $q);
258 $distinct = true;
259
260 switch ($type) {
261 case 'binetTxt':
262 $db = 'binets_def INNER JOIN
263 binets_ins ON(binets_def.id = binets_ins.binet_id)';
264 $field = 'binets_def.text';
265 if (strlen($q) > 2)
266 $beginwith = false;
267 $realid = 'binets_def.id';
268 break;
269 case 'networking_typeTxt':
270 $db = 'profile_networking_enum INNER JOIN
271 profile_networking ON(profile_networking.network_type = profile_networking_enum.network_type)';
272 $field = 'profile_networking_enum.name';
273 $unique = 'uid';
274 $realid = 'profile_networking_enum.network_type';
275 break;
276 case 'city':
277 $db = 'geoloc_localities INNER JOIN
278 profile_addresses ON (geoloc_localities.id = profile_addresses.localityId)';
279 $unique = 'uid';
280 $field ='geoloc_localities.name';
281 break;
282 case 'countryTxt':
283 $db = 'geoloc_countries INNER JOIN
284 profile_addresses ON (geoloc_countries.iso_3166_1_a2 = profile_addresses.countryId)';
285 $unique = 'pid';
286 $field = 'geoloc_countries.countryFR';
287 $realid = 'geoloc_countries.iso_3166_1_a2';
288 break;
289 case 'entreprise':
290 $db = 'profile_job_enum INNER JOIN
291 profile_job ON (profile_job.jobid = profile_job_enum.id)';
292 $field = 'profile_job_enum.name';
293 $unique = 'profile_job.uid';
294 break;
295 case 'fonctionTxt':
296 $db = 'fonctions_def INNER JOIN
297 profile_job ON (profile_job.fonctionid = fonctions_def.id)';
298 $field = 'fonction_fr';
299 $unique = 'uid';
300 $realid = 'fonctions_def.id';
301 $beginwith = false;
302 break;
303 case 'groupexTxt':
304 $db = "#groupex#.asso AS a INNER JOIN
305 #groupex#.membres AS m ON(a.id = m.asso_id
306 AND (a.cat = 'GroupesX' OR a.cat = 'Institutions')
307 AND a.pub = 'public')";
308 $field='a.nom';
309 $field2 = 'a.diminutif';
310 if (strlen($q) > 2)
311 $beginwith = false;
312 $realid = 'a.id';
313 $unique = 'm.uid';
314 break;
315 case 'nationaliteTxt':
316 $db = 'geoloc_countries INNER JOIN
317 profile ON (geoloc_countries.a2 IN (profile.nationality1, profile.nationality2, profile.nationality3))';
318 $field = 'geoloc_countries.nationalityFR';
319 $realid = 'geoloc_countries.iso_3166_1_a2';
320 break;
321 case 'description':
322 $db = 'profile_job';
323 $field = 'description';
324 $unique = 'uid';
325 break;
326 case 'schoolTxt':
327 $db = 'profile_education_enum INNER JOIN
328 profile_education ON (profile_education_enum.id = profile_education.eduid)';
329 $field = 'profile_education_enum.name';
330 $unique = 'uid';
331 $realid = 'profile_education_enum.id';
332 if (strlen($q) > 2)
333 $beginwith = false;
334 break;
335 case 'secteurTxt':
336 $db = 'profile_job_sector_enum INNER JOIN
337 profile_job ON (profile_job.sectorid = profile_job_sector_enum.id)';
338 $field = 'profile_job_sector_enum.name';
339 $realid = 'profile_job_sector_enum.id';
340 $unique = 'uid';
341 $beginwith = false;
342 break;
343 case 'subSubSector':
344 $db = 'profile_job_subsubsector_enum';
345 $field = 'name';
346 $beginwith = false;
347 $unique = 'name';
348 $distinct = false;
349 break;
350 case 'sectionTxt':
351 $db = 'sections AS acs
352 INNER JOIN profiles AS acp ON (acp.section = acs.id)';
353 $field = 'acs.text';
354 $realid = 'acs.id';
355 $beginwith = false;
356 break;
357 default: exit();
358 }
359
360 function make_field_test($fields, $beginwith) {
361 $tests = array();
362 $tests[] = $fields . ' LIKE CONCAT({?}, \'%\')';
363 if (!$beginwith) {
364 $tests[] = $fields . ' LIKE CONCAT(\'% \', {?}, \'%\')';
365 $tests[] = $fields . ' LIKE CONCAT(\'%-\', {?}, \'%\')';
366 }
367 return '(' . implode(' OR ', $tests) . ')';
368 }
369 $field_select = $field;
370 $field_t = make_field_test($field, $beginwith);
371 if ($field2) {
372 $field2_t = make_field_test($field2, $beginwith);
373 $field_select = 'IF(' . $field_t . ', ' . $field . ', ' . $field2. ')';
374 }
375 $list = XDB::iterator('SELECT ' . $field_select . ' AS field'
376 . ($distinct ? (', COUNT(DISTINCT ' . $unique . ') AS nb') : '')
377 . ($realid ? (', ' . $realid . ' AS id') : '') . '
378 FROM ' . $db . '
379 WHERE ' . $field_t .
380 ($field2 ? (' OR ' . $field2_t) : '') . '
381 GROUP BY ' . $field_select . '
382 ORDER BY ' . ($distinct ? 'nb DESC' : $field_select) . '
383 LIMIT 11',
384 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch,
385 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch);
386
387 $nbResults = 0;
388 $res = "";
389 while ($result = $list->next()) {
390 $nbResults++;
391 if ($nbResults == 11) {
392 $res .= $q."|-1\n";
393 } else {
394 $res .= $result['field'].'|';
395 if (isset($result['nb'])) {
396 $res .= $result['nb'];
397 }
398 if (isset($result['id'])) {
399 $res .= '|'.$result['id'];
400 }
401 $res .= "\n";
402 }
403 }
404 XDB::query('REPLACE INTO search_autocomplete
405 VALUES ({?}, {?}, {?}, NOW())',
406 $type, $q, $res);
407 echo $res;
408 exit();
409 }
410
411 function handler_list(&$page, $type = null, $idVal = null)
412 {
413 // Give the list of all values possible of type and builds a select input for it
414 $field = 'text';
415 $id = 'id';
416 $where = '';
417
418 switch ($type) {
419 case 'binet':
420 $db = 'binets_def';
421 break;
422 case 'networking_type':
423 $db = 'profile_networking_enum';
424 $field = 'name';
425 $id = 'network_type';
426 break;
427 case 'country':
428 $db = 'geoloc_countries';
429 $field = 'countryFR';
430 $id = 'iso_3166_1_a2';
431 $page->assign('onchange', 'changeCountry(this.value)');
432 break;
433 case 'fonction':
434 $db = 'fonctions_def';
435 $field = 'fonction_fr';
436 break;
437 case 'diploma':
438 pl_content_headers("text/xml");
439 $this->get_diplomas();
440 $page->changeTpl('search/adv.grade.form.tpl', NO_SKIN);
441 return;
442 case 'groupex':
443 $db = '#groupex#.asso';
444 $where = " WHERE (cat = 'GroupesX' OR cat = 'Institutions') AND pub = 'public'";
445 $field = 'nom';
446 break;
447 case 'nationalite':
448 $db = 'geoloc_countries INNER JOIN
449 profiles AS acp ON (acgp.a2 IN (acp.nationality1, acp.nationality2, acp.nationality3))';
450 $field = 'nationalityFR';
451 $id = 'iso_3166_1_a2';
452 break;
453 case 'region':
454 $db = 'geoloc_administrativeareas';
455 $field = 'name';
456 $id = 'id';
457 if (isset($_REQUEST['country'])) {
458 $where .= ' WHERE country = "' . $_REQUEST['country'] . '"';
459 }
460 break;
461 case 'school':
462 $db = 'profile_education_enum';
463 $field = 'name';
464 $id = 'id';
465 $page->assign('onchange', 'changeSchool(this.value)');
466 break;
467 case 'section':
468 $db = 'sections';
469 break;
470 case 'secteur':
471 $db = 'profile_job_sector_enum INNER JOIN
472 profile_job ON (profile_job.sectorid = profile_job_sector_enum.id)';
473 $field = 'profile_job_sector_enum.name';
474 $id = 'profile_job_sector_enum.id';
475 break;
476 default: exit();
477 }
478 if (isset($idVal)) {
479 pl_content_headers("text/plain");
480 $result = XDB::query('SELECT '.$field.' AS field FROM '.$db.' WHERE '.$id.' = {?} LIMIT 1',$idVal);
481 echo $result->fetchOneCell();
482 exit();
483 }
484 pl_content_headers("text/xml");
485 $page->changeTpl('include/field.select.tpl', NO_SKIN);
486 $page->assign('name', $type);
487 $page->assign('list', XDB::iterator('SELECT '.$field.' AS field,
488 '.$id.' AS id
489 FROM '.$db.$where.'
490 GROUP BY '.$field.'
491 ORDER BY '.$field));
492 $page->assign('with_text_value', true);
493 $page->assign('onchange', "document.forms.recherche.{$type}Txt.value = this.options[this.selectedIndex].text");
494 }
495}
496
497// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
498?>