Adapts search to the new name management.
[platal.git] / modules / search.php
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
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),
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::has_perms()) {
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 $view->addMod('geoloc', 'Planisphère', false, array('with_annu' => 'search/adv'));
130 }
131 $view->apply('search', $page, $action, $subaction);
132
133 $nb_tot = $view->count();
134 $page->assign('search_results_nb', $nb_tot);
135 if ($subaction) {
136 return;
137 }
138 if (!S::logged() && $nb_tot > $globals->search->public_max) {
139 new ThrowError('Votre recherche a généré trop de résultats pour un affichage public.');
140 } elseif ($nb_tot > $globals->search->private_max) {
141 new ThrowError('Recherche trop générale. Une <a href="search/adv">recherche avancée</a> permet de préciser la recherche.');
142 } elseif (empty($nb_tot)) {
143 new ThrowError('Il n\'existe personne correspondant à ces critères dans la base !');
144 }
145 } else {
146 $page->assign('formulaire',1);
147 $page->addJsLink('ajax.js');
148 }
149
150 $this->load('search.inc.php');
151 $page->changeTpl('search/index.tpl');
152 $page->setTitle('Annuaire');
153 }
154
155 function handler_advanced(&$page, $action = null, $subaction = null)
156 {
157 global $globals;
158 require_once 'geoloc.inc.php';
159 $this->load('search.inc.php');
160 $page->assign('advanced',1);
161 $page->addJsLink('jquery.autocomplete.js');
162
163 if (!Env::has('rechercher') && $action != 'geoloc') {
164 $this->form_prepare();
165 } else {
166 $textFields = array(
167 'country' => array('field' => 'a2', 'table' => 'geoloc_pays', 'text' => 'pays', 'exact' => false),
168 'fonction' => array('field' => 'id', 'table' => 'fonctions_def', 'text' => 'fonction_fr', 'exact' => true),
169 'secteur' => array('field' => 'id', 'table' => 'profile_job_sector_enum', 'text' => 'name', 'exact' => false),
170 'nationalite' => array('field' => 'a2', 'table' => 'geoloc_pays', 'text' => 'nat', 'exact' => 'false'),
171 'binet' => array('field' => 'id', 'table' => 'binets_def', 'text' => 'text', 'exact' => false),
172 'networking_type' => array('field' => 'network_type', 'table' => 'profile_networking_enum',
173 'text' => 'name', 'exact' => false),
174 'groupex' => array('field' => 'id', 'table' => 'groupex.asso',
175 'text' => "(cat = 'GroupesX' OR cat = 'Institutions') AND pub = 'public' AND nom",
176 'exact' => false),
177 'section' => array('field' => 'id', 'table' => 'sections', 'text' => 'text', 'exact' => false),
178 'school' => array('field' => 'id', 'table' => 'profile_education_enum', 'text' => 'name', 'exact' => false),
179 'city' => array('table' => 'geoloc_city', 'text' => 'name', 'exact' => false)
180 );
181 if (!Env::has('page')) {
182 S::logger()->log('search', 'adv=' . var_export($_GET, true));
183 }
184 foreach ($textFields as $field=>&$query) {
185 if (!Env::v($field) && Env::v($field . 'Txt')) {
186 $res = XDB::query("SELECT {$query['field']}
187 FROM {$query['table']}
188 WHERE {$query['text']} " . ($query['exact'] ? " = {?}" :
189 " LIKE CONCAT('%', {?}, '%')"),
190 Env::v($field . 'Txt'));
191 $_REQUEST[$field] = $res->fetchOneCell();
192 }
193 }
194
195 require_once 'userset.inc.php';
196 $view = new SearchSet(false, $action == 'geoloc' && substr($subaction, -3) == 'swf');
197 $view->addMod('minifiche', 'Mini-fiches', true);
198 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true));
199 //$view->addMod('geoloc', 'Planisphère', false, array('with_annu' => 'search/adv'));
200 $view->apply('search/adv', $page, $action, $subaction);
201
202 if ($subaction) {
203 return;
204 }
205 $nb_tot = $view->count();
206 if ($nb_tot > $globals->search->private_max) {
207 $this->form_prepare();
208 new ThrowError('Recherche trop générale.');
209 }
210 }
211
212 $page->changeTpl('search/index.tpl', $action == 'mini' ? SIMPLE : SKINNED);
213 $page->addJsLink('ajax.js');
214 $page->assign('public_directory',0);
215 }
216
217 function handler_autocomplete(&$page, $type = null)
218 {
219 // Autocompletion : according to type required, return
220 // a list of results matching with the number of matches.
221 // The output format is :
222 // result1|nb1
223 // result2|nb2
224 // ...
225 header('Content-Type: text/plain; charset="UTF-8"');
226 $q = preg_replace(array('/\*+$/', // always look for $q*
227 '/([\^\$\[\]])/', // escape special regexp char
228 '/\*/'), // replace joker by regexp joker
229 array('',
230 '\\\\\1',
231 '.*'),
232 $_REQUEST['q']);
233 if (!$q) exit();
234
235 // try to look in cached results
236 $cache = XDB::query('SELECT `result`
237 FROM `search_autocomplete`
238 WHERE `name` = {?} AND
239 `query` = {?} AND
240 `generated` > NOW() - INTERVAL 1 DAY',
241 $type, $q);
242 if ($res = $cache->fetchOneCell()) {
243 echo $res;
244 die();
245 }
246
247 // default search
248 $unique = '`user_id`';
249 $db = '`auth_user_md5`';
250 $realid = false;
251 $beginwith = true;
252 $field2 = false;
253 $qsearch = str_replace(array('%', '_'), '', $q);
254 $distinct = true;
255
256 switch ($type) {
257 case 'binetTxt':
258 $db = '`binets_def` INNER JOIN
259 `binets_ins` ON(`binets_def`.`id` = `binets_ins`.`binet_id`)';
260 $field = '`binets_def`.`text`';
261 if (strlen($q) > 2)
262 $beginwith = false;
263 $realid = '`binets_def`.`id`';
264 break;
265 case 'networking_typeTxt':
266 $db = '`profile_networking_enum` INNER JOIN
267 `profile_networking` ON(`profile_networking`.`network_type` = `profile_networking_enum`.`network_type`)';
268 $field = '`profile_networking_enum`.`name`';
269 $unique = 'uid';
270 $realid = '`profile_networking_enum`.`network_type`';
271 break;
272 case 'city':
273 $db = '`geoloc_city` INNER JOIN
274 `adresses` ON(`geoloc_city`.`id` = `adresses`.`cityid`)';
275 $unique='`uid`';
276 $field='`geoloc_city`.`name`';
277 break;
278 case 'countryTxt':
279 $db = '`geoloc_pays` INNER JOIN
280 `adresses` ON(`geoloc_pays`.`a2` = `adresses`.`country`)';
281 $unique = '`uid`';
282 $field = '`geoloc_pays`.`pays`';
283 $field2 = '`geoloc_pays`.`country`';
284 $realid = '`geoloc_pays`.`a2`';
285 break;
286 case 'entreprise':
287 $db = 'profile_job_enum INNER JOIN
288 profile_job ON (profile_job.jobid = profile_job_enum.id)';
289 $field = 'profile_job_enum.name';
290 $unique = 'profile_job.uid';
291 break;
292 case 'fonctionTxt':
293 $db = 'fonctions_def INNER JOIN
294 profile_job ON (profile_job.fonctionid = fonctions_def.id)';
295 $field = 'fonction_fr';
296 $unique = 'uid';
297 $realid = 'fonctions_def.id';
298 $beginwith = false;
299 break;
300 case 'groupexTxt':
301 $db = "groupex.asso AS a INNER JOIN
302 groupex.membres AS m ON(a.id = m.asso_id
303 AND (a.cat = 'GroupesX' OR a.cat = 'Institutions')
304 AND a.pub = 'public')";
305 $field='a.nom';
306 $field2 = 'a.diminutif';
307 if (strlen($q) > 2)
308 $beginwith = false;
309 $realid = 'a.id';
310 $unique = 'm.uid';
311 break;
312 case 'nationaliteTxt':
313 $db = '`geoloc_pays` INNER JOIN
314 `auth_user_md5` ON (`geoloc_pays`.`a2` = `auth_user_md5`.`nationalite` OR
315 `geoloc_pays`.`a2` = `auth_user_md5`.`nationalite2` OR
316 `geoloc_pays`.`a2` = `auth_user_md5`.`nationalite3`)';
317 $field = 'IF(`geoloc_pays`.`nat`=\'\',
318 `geoloc_pays`.`pays`,
319 `geoloc_pays`.`nat`)';
320 $realid = '`geoloc_pays`.`a2`';
321 break;
322 case 'description':
323 $db = 'profile_job';
324 $field = 'description';
325 $unique = 'uid';
326 break;
327 case 'schoolTxt':
328 $db = 'profile_education_enum INNER JOIN
329 profile_education ON (profile_education_enum.id = profile_education.eduid)';
330 $field = 'profile_education_enum.name';
331 $unique = 'uid';
332 $realid = 'profile_education_enum.id';
333 if (strlen($q) > 2)
334 $beginwith = false;
335 break;
336 case 'secteurTxt':
337 $db = 'profile_job_sector_enum INNER JOIN
338 profile_job ON (profile_job.sectorid = profile_job_sector_enum.id)';
339 $field = 'profile_job_sector_enum.name';
340 $realid = 'profile_job_sector_enum.id';
341 $unique = 'uid';
342 $beginwith = false;
343 break;
344 case 'sss_secteur':
345 $db = 'profile_job_subsubsector_enum';
346 $field = 'name';
347 $beginwith = false;
348 $unique = 'name';
349 $distinct = false;
350 break;
351 case 'sectionTxt':
352 $db = '`sections` INNER JOIN
353 `auth_user_md5` ON(`auth_user_md5`.`section` = `sections`.`id`)';
354 $field = '`sections`.`text`';
355 $realid = '`sections`.`id`';
356 $beginwith = false;
357 break;
358 default: exit();
359 }
360
361 function make_field_test($fields, $beginwith) {
362 $tests = array();
363 $tests[] = $fields . ' LIKE CONCAT({?}, \'%\')';
364 if (!$beginwith) {
365 $tests[] = $fields . ' LIKE CONCAT(\'% \', {?}, \'%\')';
366 $tests[] = $fields . ' LIKE CONCAT(\'%-\', {?}, \'%\')';
367 }
368 return '(' . implode(' OR ', $tests) . ')';
369 }
370 $field_select = $field;
371 $field_t = make_field_test($field, $beginwith);
372 if ($field2) {
373 $field2_t = make_field_test($field2, $beginwith);
374 $field_select = 'IF(' . $field_t . ', ' . $field . ', ' . $field2. ')';
375 }
376 $list = XDB::iterator('SELECT ' . $field_select . ' AS field'
377 . ($distinct ? (', COUNT(DISTINCT ' . $unique . ') AS nb') : '')
378 . ($realid ? (', ' . $realid . ' AS id') : '') . '
379 FROM ' . $db . '
380 WHERE ' . $field_t .
381 ($field2 ? (' OR ' . $field2_t) : '') . '
382 GROUP BY ' . $field_select . '
383 ORDER BY ' . ($distinct ? 'nb DESC' : $field_select) . '
384 LIMIT 11',
385 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch,
386 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch);
387
388 $nbResults = 0;
389 $res = "";
390 while ($result = $list->next()) {
391 $nbResults++;
392 if ($nbResults == 11) {
393 $res .= $q."|-1\n";
394 } else {
395 $res .= $result['field'].'|';
396 if (isset($result['nb'])) {
397 $res .= $result['nb'];
398 }
399 if (isset($result['id'])) {
400 $res .= '|'.$result['id'];
401 }
402 $res .= "\n";
403 }
404 }
405 XDB::query('REPLACE INTO `search_autocomplete`
406 VALUES ({?}, {?}, {?}, NOW())',
407 $type, $q, $res);
408 echo $res;
409 exit();
410 }
411
412 function handler_list(&$page, $type = null, $idVal = null)
413 {
414 // Give the list of all values possible of type and builds a select input for it
415 $field = '`text`';
416 $id = '`id`';
417 $where = '';
418
419 switch ($type) {
420 case 'binet':
421 $db = '`binets_def`';
422 break;
423 case 'networking_type':
424 $db = '`profile_networking_enum`';
425 $field = '`name`';
426 $id = '`network_type`';
427 break;
428 case 'country':
429 $db = '`geoloc_pays`';
430 $field = '`pays`';
431 $id = '`a2`';
432 $page->assign('onchange', 'changeCountry(this.value)');
433 break;
434 case 'fonction':
435 $db = '`fonctions_def`';
436 $field = '`fonction_fr`';
437 break;
438 case 'diploma':
439 header('Content-Type: text/xml; charset="UTF-8"');
440 $this->get_diplomas();
441 $page->changeTpl('search/adv.grade.form.tpl', NO_SKIN);
442 return;
443 case 'groupex':
444 $db = 'groupex.asso';
445 $where = " WHERE (cat = 'GroupesX' OR cat = 'Institutions') AND pub = 'public'";
446 $field = 'nom';
447 break;
448 case 'nationalite':
449 $db = '`geoloc_pays` INNER JOIN
450 `auth_user_md5` ON (`geoloc_pays`.`a2` = `auth_user_md5`.`nationalite` OR
451 `geoloc_pays`.`a2` = `auth_user_md5`.`nationalite2` OR
452 `geoloc_pays`.`a2` = `auth_user_md5`.`nationalite3`)';
453 $field = 'IF(`nat`=\'\', `pays`, `nat`)';
454 $id = '`a2`';
455 break;
456 case 'region':
457 $db = '`geoloc_region`';
458 $field = '`name`';
459 $id = '`region`';
460 if (isset($_REQUEST['country'])) {
461 $where .= ' WHERE `a2` = "'.$_REQUEST['country'].'"';
462 }
463 break;
464 case 'school':
465 $db = 'profile_education_enum';
466 $field = 'name';
467 $id = 'id';
468 $page->assign('onchange', 'changeSchool(this.value)');
469 break;
470 case 'section':
471 $db = '`sections`';
472 break;
473 case 'secteur':
474 $db = 'profile_job_sector_enum INNER JOIN
475 profile_job ON (profile_job.sectorid = profile_job_sector_enum.id)';
476 $field = 'profile_job_sector_enum.name';
477 $id = 'profile_job_sector_enum.id';
478 break;
479 default: exit();
480 }
481 if (isset($idVal)) {
482 header('Content-Type: text/plain; charset="UTF-8"');
483 $result = XDB::query('SELECT '.$field.' AS field FROM '.$db.' WHERE '.$id.' = {?} LIMIT 1',$idVal);
484 echo $result->fetchOneCell();
485 exit();
486 }
487 header('Content-Type: text/xml; charset="UTF-8"');
488 $page->changeTpl('include/field.select.tpl', NO_SKIN);
489 $page->assign('name', $type);
490 $page->assign('list', XDB::iterator('SELECT '.$field.' AS field,
491 '.$id.' AS id
492 FROM '.$db.$where.'
493 GROUP BY '.$field.'
494 ORDER BY '.$field));
495 $page->assign('with_text_value', true);
496 $page->assign('onchange', "document.forms.recherche.{$type}Txt.value = this.options[this.selectedIndex].text");
497 }
498 }
499
500 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
501 ?>