Some fixes and updates.
[platal.git] / modules / search.php
CommitLineData
09824164 1<?php
2/***************************************************************************
179afa7f 3 * Copyright (C) 2003-2008 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(
abed2826
SJ
27 'search' => $this->make_hook('quick', AUTH_PUBLIC),
28 'search/adv' => $this->make_hook('advanced', AUTH_COOKIE),
ba2afb88 29 'advanced_search.php' => $this->make_hook('redir_advanced', AUTH_PUBLIC),
abed2826
SJ
30 'search/autocomplete' => $this->make_hook('autocomplete', AUTH_COOKIE, 'user', NO_AUTH),
31 'search/list' => $this->make_hook('list', AUTH_COOKIE, 'user', NO_AUTH),
09824164 32 );
33 }
34
ba2afb88 35 function handler_redir_advanced(&$page, $mode = null)
36 {
37 pl_redirect('search/adv');
38 exit;
39 }
40
09824164 41 function form_prepare()
42 {
d7610c35 43 Platal::page()->assign('formulaire',1);
3c640222 44 }
45
46 function get_diplomas($school = null)
47 {
48 if (is_null($school) && Env::has('school')) {
49 $school = Env::i('school');
50 }
09824164 51
f9817768
SJ
52 if ((!is_null($school)) && ($school != '')) {
53 $sql = 'SELECT degreeid
54 FROM profile_education_degree
55 WHERE eduid=' . $school;
09824164 56 } else {
f9817768
SJ
57 $sql = 'SELECT id
58 FROM profile_education_degree_enum
59 ORDER BY id';
09824164 60 }
61
08cce2ff 62 $res = XDB::query($sql);
f9817768
SJ
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());
09824164 70 }
71
8c4a0c30 72 function handler_quick(&$page, $action = null, $subaction = null)
09824164 73 {
74 global $globals;
75
97eff0ff 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
8c4a0c30 83 if (Env::has('quick') || $action == 'geoloc') {
383bcdec 84 $quick = trim(Env::v('quick'));
85bb670b 85 if (S::logged() && !Env::has('page')) {
732e5855 86 S::logger()->log('search', 'quick=' . $quick);
e31c1c3e 87 }
383bcdec 88 $list = 'profile|prf|fiche|fic|referent|ref|mentor';
89 if (S::has_perms()) {
90 $list .= '|admin|adm|ax';
91 }
11647113 92 if (preg_match('/^(' . $list . '):([-a-z]+(\.[-a-z]+(\.\d{2,4})?)?)$/', replace_accent($quick), $matches)) {
383bcdec 93 $forlife = $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 }
7511200d
FB
108
109 require_once 'user.func.inc.php';
110 $login = get_user_forlife($forlife, '_silent_user_callback');
111 if ($login) {
112 pl_redirect($base . $login);
113 }
114 $_REQUEST['quick'] = $forlife;
115 $_GET['quick'] = $forlife;
8fee4fbd 116 } elseif (strpos($quick, 'doc:') === 0) {
117 $url = 'Docs/Recherche?';
118 $url .= 'action=search&q=' . urlencode(substr($quick, 4));
7511200d 119 $url .= '&group=' . urlencode('-Equipe,-Main,-PmWiki,-Site,-Review');
8fee4fbd 120 pl_redirect($url);
383bcdec 121 }
8fee4fbd 122
09824164 123 $page->assign('formulaire', 0);
124
8c4a0c30 125 require_once 'userset.inc.php';
126 $view = new SearchSet(true, $action == 'geoloc' && substr($subaction, -3) == 'swf');
1fae7605 127 $view->addMod('minifiche', 'Mini-fiches', true, array('with_score' => true));
35fa92e8 128 if (S::logged() && !Env::i('nonins')) {
129 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true, 'with_score' => true));
a2aa8436 130 $view->addMod('geoloc', 'Planisphère', false, array('with_annu' => 'search/adv'));
35fa92e8 131 }
8c4a0c30 132 $view->apply('search', $page, $action, $subaction);
09824164 133
8c4a0c30 134 $nb_tot = $view->count();
e35882be 135 $page->assign('search_results_nb', $nb_tot);
8c4a0c30 136 if ($subaction) {
137 return;
138 }
cab08090 139 if (!S::logged() && $nb_tot > $globals->search->public_max) {
a7de4ef7 140 new ThrowError('Votre recherche a généré trop de résultats pour un affichage public.');
09824164 141 } elseif ($nb_tot > $globals->search->private_max) {
8d118e58 142 new ThrowError('Recherche trop générale. Une <a href="search/adv">recherche avancée</a> permet de préciser la recherche.');
09824164 143 } elseif (empty($nb_tot)) {
8d118e58 144 new ThrowError('Il n\'existe personne correspondant à ces critères dans la base !');
09824164 145 }
146 } else {
147 $page->assign('formulaire',1);
e654517d 148 $page->addJsLink('ajax.js');
09824164 149 }
150
460d8f55 151 $this->load('search.inc.php');
eaf30d86 152 $page->changeTpl('search/index.tpl');
46f272fe 153 $page->setTitle('Annuaire');
09824164 154 }
155
90ccb062 156 function handler_advanced(&$page, $action = null, $subaction = null)
09824164 157 {
158 global $globals;
bc67c37c 159 require_once 'geoloc.inc.php';
460d8f55 160 $this->load('search.inc.php');
bc67c37c 161 $page->assign('advanced',1);
4b4b4b67 162 $page->addJsLink('jquery.autocomplete.js');
bc67c37c 163
90ccb062 164 if (!Env::has('rechercher') && $action != 'geoloc') {
09824164 165 $this->form_prepare();
166 } else {
137e819f 167 $textFields = array(
2398e553
SJ
168 'country' => array('field' => 'a2', 'table' => 'geoloc_pays', 'text' => 'pays', 'exact' => false),
169 'fonction' => array('field' => 'id', 'table' => 'fonctions_def', 'text' => 'fonction_fr', 'exact' => true),
170 'secteur' => array('field' => 'id', 'table' => 'emploi_secteur', 'text' => 'label', 'exact' => false),
171 'nationalite' => array('field' => 'a2', 'table' => 'geoloc_pays', 'text' => 'nat', 'exact' => 'false'),
172 'binet' => array('field' => 'id', 'table' => 'binets_def', 'text' => 'text', 'exact' => false),
92c3f9e5
GB
173 'networking_type' => array('field' => 'network_type', 'table' => 'profile_networking_enum',
174 'text' => 'name', 'exact' => false),
2398e553
SJ
175 'groupex' => array('field' => 'id', 'table' => 'groupex.asso',
176 'text' => "(a.cat = 'GroupesX' OR a.cat = 'Institutions') AND pub = 'public' AND nom",
177 'exact' => false),
178 'section' => array('field' => 'id', 'table' => 'sections', 'text' => 'text', 'exact' => false),
179 'school' => array('field' => 'id', 'table' => 'profile_education_enum', 'text' => 'name', 'exact' => false),
180 'city' => array('table' => 'geoloc_city', 'text' => 'name', 'exact' => false)
137e819f 181 );
e31c1c3e 182 if (!Env::has('page')) {
732e5855 183 S::logger()->log('search', 'adv=' . var_export($_GET, true));
e31c1c3e 184 }
137e819f
FB
185 foreach ($textFields as $field=>&$query) {
186 if (!Env::v($field) && Env::v($field . 'Txt')) {
187 $res = XDB::query("SELECT {$query['field']}
188 FROM {$query['table']}
579a8c9a
FB
189 WHERE {$query['text']} " . ($query['exact'] ? " = {?}" :
190 " LIKE CONCAT('%', {?}, '%')"),
137e819f
FB
191 Env::v($field . 'Txt'));
192 $_REQUEST[$field] = $res->fetchOneCell();
193 }
194 }
195
8c4a0c30 196 require_once 'userset.inc.php';
197 $view = new SearchSet(false, $action == 'geoloc' && substr($subaction, -3) == 'swf');
1fae7605 198 $view->addMod('minifiche', 'Mini-fiches', true);
35fa92e8 199 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true));
8ddd48c3 200 //$view->addMod('geoloc', 'Planisphère', false, array('with_annu' => 'search/adv'));
86b5c8f0 201 $view->apply('search/adv', $page, $action, $subaction);
eaf30d86 202
8c4a0c30 203 if ($subaction) {
204 return;
09824164 205 }
8c4a0c30 206 $nb_tot = $view->count();
09824164 207 if ($nb_tot > $globals->search->private_max) {
208 $this->form_prepare();
8d118e58 209 new ThrowError('Recherche trop générale.');
09824164 210 }
09824164 211 }
212
90ccb062 213 $page->changeTpl('search/index.tpl', $action == 'mini' ? SIMPLE : SKINNED);
3c640222 214 $page->addJsLink('ajax.js');
8c4a0c30 215 $page->assign('public_directory',0);
09824164 216 }
3c640222 217
838cc16a 218 function handler_autocomplete(&$page, $type = null)
219 {
220 // Autocompletion : according to type required, return
221 // a list of results matching with the number of matches.
222 // The output format is :
223 // result1|nb1
224 // result2|nb2
225 // ...
226 header('Content-Type: text/plain; charset="UTF-8"');
ff3eb9b7 227 $q = preg_replace(array('/\*+$/', // always look for $q*
228 '/([\^\$\[\]])/', // escape special regexp char
229 '/\*/'), // replace joker by regexp joker
230 array('',
231 '\\\\\1',
232 '.*'),
233 $_REQUEST['q']);
838cc16a 234 if (!$q) exit();
c15afc4e 235
eaf30d86 236 // try to look in cached results
ff3eb9b7 237 $cache = XDB::query('SELECT `result`
238 FROM `search_autocomplete`
239 WHERE `name` = {?} AND
240 `query` = {?} AND
241 `generated` > NOW() - INTERVAL 1 DAY',
242 $type, $q);
c15afc4e 243 if ($res = $cache->fetchOneCell()) {
ff3eb9b7 244 echo $res;
245 die();
c15afc4e 246 }
eaf30d86 247
2ab7a09f 248 // default search
f6818108 249 $unique = '`user_id`';
250 $db = '`auth_user_md5`';
2ab7a09f 251 $realid = false;
f3da6d81 252 $beginwith = true;
f6818108 253 $field2 = false;
baa62e58 254 $qsearch = str_replace(array('%', '_'), '', $q);
eaf30d86 255
838cc16a 256 switch ($type) {
ff3eb9b7 257 case 'binetTxt':
258 $db = '`binets_def` INNER JOIN
259 `binets_ins` ON(`binets_def`.`id` = `binets_ins`.`binet_id`)';
2398e553 260 $field = '`binets_def`.`text`';
ff3eb9b7 261 if (strlen($q) > 2)
262 $beginwith = false;
263 $realid = '`binets_def`.`id`';
264 break;
92c3f9e5
GB
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;
ff3eb9b7 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`)';
2398e553 281 $unique = '`uid`';
ff3eb9b7 282 $field = '`geoloc_pays`.`pays`';
283 $field2 = '`geoloc_pays`.`country`';
2398e553 284 $realid = '`geoloc_pays`.`a2`';
ff3eb9b7 285 break;
286 case 'entreprise':
287 $db = '`entreprises`';
288 $field = '`entreprise`';
2398e553 289 $unique = '`uid`';
ff3eb9b7 290 break;
07c4f9cc 291 case 'firstname':
ff3eb9b7 292 $field = '`prenom`';
ff3eb9b7 293 $beginwith = false;
294 break;
295 case 'fonctionTxt':
296 $db = '`fonctions_def` INNER JOIN
297 `entreprises` ON(`entreprises`.`fonction` = `fonctions_def`.`id`)';
298 $field = '`fonction_fr`';
299 $unique = '`uid`';
300 $realid = '`fonctions_def`.`id`';
ff3eb9b7 301 $beginwith = false;
302 break;
303 case 'groupexTxt':
579a8c9a
FB
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';
ff3eb9b7 310 if (strlen($q) > 2)
311 $beginwith = false;
579a8c9a
FB
312 $realid = 'a.id';
313 $unique = 'm.uid';
ff3eb9b7 314 break;
315 case 'name':
316 $field = '`nom`';
317 $field2 = '`nom_usage`';
ff3eb9b7 318 $beginwith = false;
319 break;
320 case 'nationaliteTxt':
321 $db = '`geoloc_pays` INNER JOIN
f781871c
SJ
322 `auth_user_md5` ON (`geoloc_pays`.`a2` = `auth_user_md5`.`nationalite` OR
323 `geoloc_pays`.`a2` = `auth_user_md5`.`nationalite2` OR
324 `geoloc_pays`.`a2` = `auth_user_md5`.`nationalite3`)';
ff3eb9b7 325 $field = 'IF(`geoloc_pays`.`nat`=\'\',
326 `geoloc_pays`.`pays`,
327 `geoloc_pays`.`nat`)';
328 $realid = '`geoloc_pays`.`a2`';
329 break;
330 case 'nickname':
331 $field = '`profile_nick`';
332 $db = '`auth_user_quick`';
ff3eb9b7 333 $beginwith = false;
334 break;
335 case 'poste':
336 $db = '`entreprises`';
337 $field = '`poste`';
2398e553 338 $unique = '`uid`';
ff3eb9b7 339 break;
340 case 'schoolTxt':
043bbacf
SJ
341 $db = 'profile_education_enum INNER JOIN
342 profile_education ON (profile_education_enum.id = profile_education.eduid)';
343 $field = 'profile_education_enum.name';
344 $unique = 'uid';
345 $realid = 'profile_education_enum.id';
ff3eb9b7 346 if (strlen($q) > 2)
347 $beginwith = false;
348 break;
349 case 'secteurTxt':
350 $db = '`emploi_secteur` INNER JOIN
351 `entreprises` ON(`entreprises`.`secteur` = `emploi_secteur`.`id`)';
352 $field = '`emploi_secteur`.`label`';
353 $realid = '`emploi_secteur`.`id`';
354 $unique = '`uid`';
355 $beginwith = false;
356 break;
357 case 'sectionTxt':
eaf30d86 358 $db = '`sections` INNER JOIN
ff3eb9b7 359 `auth_user_md5` ON(`auth_user_md5`.`section` = `sections`.`id`)';
360 $field = '`sections`.`text`';
361 $realid = '`sections`.`id`';
362 $beginwith = false;
363 break;
364 default: exit();
838cc16a 365 }
366
baa62e58
FB
367 function make_field_test($fields, $beginwith) {
368 $tests = array();
369 $tests[] = $fields . ' LIKE CONCAT({?}, \'%\')';
370 if (!$beginwith) {
371 $tests[] = $fields . ' LIKE CONCAT(\'% \', {?}, \'%\')';
372 $tests[] = $fields . ' LIKE CONCAT(\'%-\', {?}, \'%\')';
373 }
374 return '(' . implode(' OR ', $tests) . ')';
375 }
ff3eb9b7 376 $field_select = $field;
baa62e58 377 $field_t = make_field_test($field, $beginwith);
ff3eb9b7 378 if ($field2) {
baa62e58
FB
379 $field2_t = make_field_test($field2, $beginwith);
380 $field_select = 'IF(' . $field_t . ', ' . $field . ', ' . $field2. ')';
ff3eb9b7 381 }
baa62e58
FB
382 $list = XDB::iterator('SELECT ' . $field_select . ' AS field,
383 COUNT(DISTINCT ' . $unique . ') AS nb
384 ' . ($realid ? (', ' . $realid . ' AS id') : '') . '
385 FROM ' . $db . '
386 WHERE ' . $field_t .
387 ($field2 ? (' OR ' . $field2_t) : '') . '
388 GROUP BY ' . $field_select . '
ff3eb9b7 389 ORDER BY nb DESC
390 LIMIT 11',
7eb43a1d 391 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch,
011b438c 392 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch);
f781871c 393
838cc16a 394 $nbResults = 0;
c15afc4e 395 $res = "";
2ab7a09f 396 while ($result = $list->next()) {
838cc16a 397 $nbResults++;
398 if ($nbResults == 11) {
b3ec63d5 399 $res .= $q."|-1\n";
838cc16a 400 } else {
f6818108 401 $res .= $result['field'].'|';
ff3eb9b7 402 $res .= $result['nb'];
403 if (isset($result['id'])) {
404 $res .= '|'.$result['id'];
405 }
406 $res .= "\n";
838cc16a 407 }
408 }
ff3eb9b7 409 XDB::query('REPLACE INTO `search_autocomplete`
410 VALUES ({?}, {?}, {?}, NOW())',
411 $type, $q, $res);
c15afc4e 412 echo $res;
838cc16a 413 exit();
414 }
eaf30d86 415
2ab7a09f 416 function handler_list(&$page, $type = null, $idVal = null)
417 {
ff3eb9b7 418 // Give the list of all values possible of type and builds a select input for it
419 $field = '`text`';
420 $id = '`id`';
421 $where = '';
422
423 switch ($type) {
424 case 'binet':
425 $db = '`binets_def`';
426 break;
92c3f9e5
GB
427 case 'networking_type':
428 $db = '`profile_networking_enum`';
429 $field = '`name`';
430 $id = '`network_type`';
431 break;
ff3eb9b7 432 case 'country':
433 $db = '`geoloc_pays`';
434 $field = '`pays`';
435 $id = '`a2`';
436 $page->assign('onchange', 'changeCountry(this.value)');
437 break;
438 case 'fonction':
439 $db = '`fonctions_def`';
440 $field = '`fonction_fr`';
441 break;
442 case 'diploma':
f6818108 443 header('Content-Type: text/xml; charset="UTF-8"');
ff3eb9b7 444 $this->get_diplomas();
445 $page->changeTpl('search/adv.grade.form.tpl', NO_SKIN);
446 return;
447 case 'groupex':
579a8c9a
FB
448 $db = 'groupex.asso';
449 $where = " WHERE (cat = 'GroupesX' OR cat = 'Institutions') AND pub = 'public'";
450 $field = 'nom';
ff3eb9b7 451 break;
452 case 'nationalite':
eaf30d86 453 $db = '`geoloc_pays` INNER JOIN
f781871c
SJ
454 `auth_user_md5` ON (`geoloc_pays`.`a2` = `auth_user_md5`.`nationalite` OR
455 `geoloc_pays`.`a2` = `auth_user_md5`.`nationalite2` OR
456 `geoloc_pays`.`a2` = `auth_user_md5`.`nationalite3`)';
ff3eb9b7 457 $field = 'IF(`nat`=\'\', `pays`, `nat`)';
458 $id = '`a2`';
459 break;
460 case 'region':
461 $db = '`geoloc_region`';
462 $field = '`name`';
eaf30d86 463 $id = '`region`';
f6818108 464 if (isset($_REQUEST['country'])) {
465 $where .= ' WHERE `a2` = "'.$_REQUEST['country'].'"';
466 }
ff3eb9b7 467 break;
468 case 'school':
043bbacf 469 $db = 'profile_education_enum';
f9817768
SJ
470 $field = 'name';
471 $id = 'id';
ff3eb9b7 472 $page->assign('onchange', 'changeSchool(this.value)');
473 break;
474 case 'section':
475 $db = '`sections`';
476 break;
477 case 'secteur':
478 $db = '`emploi_secteur`';
479 $field = '`label`';
480 break;
481 default: exit();
482 }
483 if (isset($idVal)) {
484 header('Content-Type: text/plain; charset="UTF-8"');
485 $result = XDB::query('SELECT '.$field.' AS field FROM '.$db.' WHERE '.$id.' = {?} LIMIT 1',$idVal);
486 echo $result->fetchOneCell();
487 exit();
488 }
f6818108 489 header('Content-Type: text/xml; charset="UTF-8"');
05cb05c0 490 $page->changeTpl('include/field.select.tpl', NO_SKIN);
f6818108 491 $page->assign('name', $type);
ff3eb9b7 492 $page->assign('list', XDB::iterator('SELECT '.$field.' AS field,
493 '.$id.' AS id
494 FROM '.$db.$where.'
a85224e3 495 GROUP BY '.$field.'
ff3eb9b7 496 ORDER BY '.$field));
b0691e10
FB
497 $page->assign('with_text_value', true);
498 $page->assign('onchange', "document.forms.recherche.{$type}Txt.value = this.options[this.selectedIndex].text");
2ab7a09f 499 }
09824164 500}
501
a7de4ef7 502// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
09824164 503?>