Merge commit 'origin/master' into fusionax
[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)) {
4514bea3 93 $login = $matches[2];
383bcdec 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 108
4514bea3
VZ
109 $user = User::getSilent($login);
110 if ($user) {
111 pl_redirect($base . $user->login());
7511200d 112 }
90c614cd
VZ
113 $_REQUEST['quick'] = $login;
114 $_GET['quick'] = $login;
8fee4fbd 115 } elseif (strpos($quick, 'doc:') === 0) {
116 $url = 'Docs/Recherche?';
117 $url .= 'action=search&q=' . urlencode(substr($quick, 4));
7511200d 118 $url .= '&group=' . urlencode('-Equipe,-Main,-PmWiki,-Site,-Review');
8fee4fbd 119 pl_redirect($url);
383bcdec 120 }
8fee4fbd 121
09824164 122 $page->assign('formulaire', 0);
123
8c4a0c30 124 require_once 'userset.inc.php';
125 $view = new SearchSet(true, $action == 'geoloc' && substr($subaction, -3) == 'swf');
1fae7605 126 $view->addMod('minifiche', 'Mini-fiches', true, array('with_score' => true));
35fa92e8 127 if (S::logged() && !Env::i('nonins')) {
128 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true, 'with_score' => true));
a2aa8436 129 $view->addMod('geoloc', 'Planisphère', false, array('with_annu' => 'search/adv'));
35fa92e8 130 }
8c4a0c30 131 $view->apply('search', $page, $action, $subaction);
09824164 132
8c4a0c30 133 $nb_tot = $view->count();
e35882be 134 $page->assign('search_results_nb', $nb_tot);
8c4a0c30 135 if ($subaction) {
136 return;
137 }
cab08090 138 if (!S::logged() && $nb_tot > $globals->search->public_max) {
a7de4ef7 139 new ThrowError('Votre recherche a généré trop de résultats pour un affichage public.');
09824164 140 } elseif ($nb_tot > $globals->search->private_max) {
8d118e58 141 new ThrowError('Recherche trop générale. Une <a href="search/adv">recherche avancée</a> permet de préciser la recherche.');
09824164 142 } elseif (empty($nb_tot)) {
8d118e58 143 new ThrowError('Il n\'existe personne correspondant à ces critères dans la base !');
09824164 144 }
145 } else {
146 $page->assign('formulaire',1);
e654517d 147 $page->addJsLink('ajax.js');
09824164 148 }
149
460d8f55 150 $this->load('search.inc.php');
eaf30d86 151 $page->changeTpl('search/index.tpl');
46f272fe 152 $page->setTitle('Annuaire');
09824164 153 }
154
90ccb062 155 function handler_advanced(&$page, $action = null, $subaction = null)
09824164 156 {
157 global $globals;
bc67c37c 158 require_once 'geoloc.inc.php';
460d8f55 159 $this->load('search.inc.php');
bc67c37c 160 $page->assign('advanced',1);
4b4b4b67 161 $page->addJsLink('jquery.autocomplete.js');
bc67c37c 162
90ccb062 163 if (!Env::has('rechercher') && $action != 'geoloc') {
09824164 164 $this->form_prepare();
165 } else {
137e819f 166 $textFields = array(
2398e553
SJ
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' => 'emploi_secteur', 'text' => 'label', '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),
92c3f9e5
GB
172 'networking_type' => array('field' => 'network_type', 'table' => 'profile_networking_enum',
173 'text' => 'name', 'exact' => false),
2398e553
SJ
174 'groupex' => array('field' => 'id', 'table' => 'groupex.asso',
175 'text' => "(a.cat = 'GroupesX' OR a.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)
137e819f 180 );
e31c1c3e 181 if (!Env::has('page')) {
732e5855 182 S::logger()->log('search', 'adv=' . var_export($_GET, true));
e31c1c3e 183 }
137e819f
FB
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']}
579a8c9a
FB
188 WHERE {$query['text']} " . ($query['exact'] ? " = {?}" :
189 " LIKE CONCAT('%', {?}, '%')"),
137e819f
FB
190 Env::v($field . 'Txt'));
191 $_REQUEST[$field] = $res->fetchOneCell();
192 }
193 }
194
8c4a0c30 195 require_once 'userset.inc.php';
196 $view = new SearchSet(false, $action == 'geoloc' && substr($subaction, -3) == 'swf');
1fae7605 197 $view->addMod('minifiche', 'Mini-fiches', true);
35fa92e8 198 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true));
8ddd48c3 199 //$view->addMod('geoloc', 'Planisphère', false, array('with_annu' => 'search/adv'));
86b5c8f0 200 $view->apply('search/adv', $page, $action, $subaction);
eaf30d86 201
8c4a0c30 202 if ($subaction) {
203 return;
09824164 204 }
8c4a0c30 205 $nb_tot = $view->count();
09824164 206 if ($nb_tot > $globals->search->private_max) {
207 $this->form_prepare();
8d118e58 208 new ThrowError('Recherche trop générale.');
09824164 209 }
09824164 210 }
211
90ccb062 212 $page->changeTpl('search/index.tpl', $action == 'mini' ? SIMPLE : SKINNED);
3c640222 213 $page->addJsLink('ajax.js');
8c4a0c30 214 $page->assign('public_directory',0);
09824164 215 }
3c640222 216
838cc16a 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"');
ff3eb9b7 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']);
838cc16a 233 if (!$q) exit();
c15afc4e 234
eaf30d86 235 // try to look in cached results
ff3eb9b7 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);
c15afc4e 242 if ($res = $cache->fetchOneCell()) {
ff3eb9b7 243 echo $res;
244 die();
c15afc4e 245 }
eaf30d86 246
2ab7a09f 247 // default search
f6818108 248 $unique = '`user_id`';
249 $db = '`auth_user_md5`';
2ab7a09f 250 $realid = false;
f3da6d81 251 $beginwith = true;
f6818108 252 $field2 = false;
baa62e58 253 $qsearch = str_replace(array('%', '_'), '', $q);
eaf30d86 254
838cc16a 255 switch ($type) {
ff3eb9b7 256 case 'binetTxt':
257 $db = '`binets_def` INNER JOIN
258 `binets_ins` ON(`binets_def`.`id` = `binets_ins`.`binet_id`)';
2398e553 259 $field = '`binets_def`.`text`';
ff3eb9b7 260 if (strlen($q) > 2)
261 $beginwith = false;
262 $realid = '`binets_def`.`id`';
263 break;
92c3f9e5
GB
264 case 'networking_typeTxt':
265 $db = '`profile_networking_enum` INNER JOIN
266 `profile_networking` ON(`profile_networking`.`network_type` = `profile_networking_enum`.`network_type`)';
267 $field = '`profile_networking_enum`.`name`';
268 $unique = 'uid';
269 $realid = '`profile_networking_enum`.`network_type`';
270 break;
ff3eb9b7 271 case 'city':
272 $db = '`geoloc_city` INNER JOIN
273 `adresses` ON(`geoloc_city`.`id` = `adresses`.`cityid`)';
274 $unique='`uid`';
275 $field='`geoloc_city`.`name`';
276 break;
277 case 'countryTxt':
278 $db = '`geoloc_pays` INNER JOIN
279 `adresses` ON(`geoloc_pays`.`a2` = `adresses`.`country`)';
2398e553 280 $unique = '`uid`';
ff3eb9b7 281 $field = '`geoloc_pays`.`pays`';
282 $field2 = '`geoloc_pays`.`country`';
2398e553 283 $realid = '`geoloc_pays`.`a2`';
ff3eb9b7 284 break;
285 case 'entreprise':
286 $db = '`entreprises`';
287 $field = '`entreprise`';
2398e553 288 $unique = '`uid`';
ff3eb9b7 289 break;
07c4f9cc 290 case 'firstname':
ff3eb9b7 291 $field = '`prenom`';
ff3eb9b7 292 $beginwith = false;
293 break;
294 case 'fonctionTxt':
295 $db = '`fonctions_def` INNER JOIN
296 `entreprises` ON(`entreprises`.`fonction` = `fonctions_def`.`id`)';
297 $field = '`fonction_fr`';
298 $unique = '`uid`';
299 $realid = '`fonctions_def`.`id`';
ff3eb9b7 300 $beginwith = false;
301 break;
302 case 'groupexTxt':
579a8c9a
FB
303 $db = "groupex.asso AS a INNER JOIN
304 groupex.membres AS m ON(a.id = m.asso_id
305 AND (a.cat = 'GroupesX' OR a.cat = 'Institutions')
306 AND a.pub = 'public')";
307 $field='a.nom';
308 $field2 = 'a.diminutif';
ff3eb9b7 309 if (strlen($q) > 2)
310 $beginwith = false;
579a8c9a
FB
311 $realid = 'a.id';
312 $unique = 'm.uid';
ff3eb9b7 313 break;
314 case 'name':
315 $field = '`nom`';
316 $field2 = '`nom_usage`';
ff3eb9b7 317 $beginwith = false;
318 break;
319 case 'nationaliteTxt':
320 $db = '`geoloc_pays` INNER JOIN
f781871c
SJ
321 `auth_user_md5` ON (`geoloc_pays`.`a2` = `auth_user_md5`.`nationalite` OR
322 `geoloc_pays`.`a2` = `auth_user_md5`.`nationalite2` OR
323 `geoloc_pays`.`a2` = `auth_user_md5`.`nationalite3`)';
ff3eb9b7 324 $field = 'IF(`geoloc_pays`.`nat`=\'\',
325 `geoloc_pays`.`pays`,
326 `geoloc_pays`.`nat`)';
327 $realid = '`geoloc_pays`.`a2`';
328 break;
329 case 'nickname':
330 $field = '`profile_nick`';
331 $db = '`auth_user_quick`';
ff3eb9b7 332 $beginwith = false;
333 break;
334 case 'poste':
335 $db = '`entreprises`';
336 $field = '`poste`';
2398e553 337 $unique = '`uid`';
ff3eb9b7 338 break;
339 case 'schoolTxt':
043bbacf
SJ
340 $db = 'profile_education_enum INNER JOIN
341 profile_education ON (profile_education_enum.id = profile_education.eduid)';
342 $field = 'profile_education_enum.name';
343 $unique = 'uid';
344 $realid = 'profile_education_enum.id';
ff3eb9b7 345 if (strlen($q) > 2)
346 $beginwith = false;
347 break;
348 case 'secteurTxt':
349 $db = '`emploi_secteur` INNER JOIN
350 `entreprises` ON(`entreprises`.`secteur` = `emploi_secteur`.`id`)';
351 $field = '`emploi_secteur`.`label`';
352 $realid = '`emploi_secteur`.`id`';
353 $unique = '`uid`';
354 $beginwith = false;
355 break;
356 case 'sectionTxt':
eaf30d86 357 $db = '`sections` INNER JOIN
ff3eb9b7 358 `auth_user_md5` ON(`auth_user_md5`.`section` = `sections`.`id`)';
359 $field = '`sections`.`text`';
360 $realid = '`sections`.`id`';
361 $beginwith = false;
362 break;
363 default: exit();
838cc16a 364 }
365
baa62e58
FB
366 function make_field_test($fields, $beginwith) {
367 $tests = array();
368 $tests[] = $fields . ' LIKE CONCAT({?}, \'%\')';
369 if (!$beginwith) {
370 $tests[] = $fields . ' LIKE CONCAT(\'% \', {?}, \'%\')';
371 $tests[] = $fields . ' LIKE CONCAT(\'%-\', {?}, \'%\')';
372 }
373 return '(' . implode(' OR ', $tests) . ')';
374 }
ff3eb9b7 375 $field_select = $field;
baa62e58 376 $field_t = make_field_test($field, $beginwith);
ff3eb9b7 377 if ($field2) {
baa62e58
FB
378 $field2_t = make_field_test($field2, $beginwith);
379 $field_select = 'IF(' . $field_t . ', ' . $field . ', ' . $field2. ')';
ff3eb9b7 380 }
baa62e58
FB
381 $list = XDB::iterator('SELECT ' . $field_select . ' AS field,
382 COUNT(DISTINCT ' . $unique . ') AS nb
383 ' . ($realid ? (', ' . $realid . ' AS id') : '') . '
384 FROM ' . $db . '
385 WHERE ' . $field_t .
386 ($field2 ? (' OR ' . $field2_t) : '') . '
387 GROUP BY ' . $field_select . '
ff3eb9b7 388 ORDER BY nb DESC
389 LIMIT 11',
7eb43a1d 390 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch,
011b438c 391 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch);
f781871c 392
838cc16a 393 $nbResults = 0;
c15afc4e 394 $res = "";
2ab7a09f 395 while ($result = $list->next()) {
838cc16a 396 $nbResults++;
397 if ($nbResults == 11) {
b3ec63d5 398 $res .= $q."|-1\n";
838cc16a 399 } else {
f6818108 400 $res .= $result['field'].'|';
ff3eb9b7 401 $res .= $result['nb'];
402 if (isset($result['id'])) {
403 $res .= '|'.$result['id'];
404 }
405 $res .= "\n";
838cc16a 406 }
407 }
ff3eb9b7 408 XDB::query('REPLACE INTO `search_autocomplete`
409 VALUES ({?}, {?}, {?}, NOW())',
410 $type, $q, $res);
c15afc4e 411 echo $res;
838cc16a 412 exit();
413 }
eaf30d86 414
2ab7a09f 415 function handler_list(&$page, $type = null, $idVal = null)
416 {
ff3eb9b7 417 // Give the list of all values possible of type and builds a select input for it
418 $field = '`text`';
419 $id = '`id`';
420 $where = '';
421
422 switch ($type) {
423 case 'binet':
424 $db = '`binets_def`';
425 break;
92c3f9e5
GB
426 case 'networking_type':
427 $db = '`profile_networking_enum`';
428 $field = '`name`';
429 $id = '`network_type`';
430 break;
ff3eb9b7 431 case 'country':
432 $db = '`geoloc_pays`';
433 $field = '`pays`';
434 $id = '`a2`';
435 $page->assign('onchange', 'changeCountry(this.value)');
436 break;
437 case 'fonction':
438 $db = '`fonctions_def`';
439 $field = '`fonction_fr`';
440 break;
441 case 'diploma':
f6818108 442 header('Content-Type: text/xml; charset="UTF-8"');
ff3eb9b7 443 $this->get_diplomas();
444 $page->changeTpl('search/adv.grade.form.tpl', NO_SKIN);
445 return;
446 case 'groupex':
579a8c9a
FB
447 $db = 'groupex.asso';
448 $where = " WHERE (cat = 'GroupesX' OR cat = 'Institutions') AND pub = 'public'";
449 $field = 'nom';
ff3eb9b7 450 break;
451 case 'nationalite':
eaf30d86 452 $db = '`geoloc_pays` INNER JOIN
f781871c
SJ
453 `auth_user_md5` ON (`geoloc_pays`.`a2` = `auth_user_md5`.`nationalite` OR
454 `geoloc_pays`.`a2` = `auth_user_md5`.`nationalite2` OR
455 `geoloc_pays`.`a2` = `auth_user_md5`.`nationalite3`)';
ff3eb9b7 456 $field = 'IF(`nat`=\'\', `pays`, `nat`)';
457 $id = '`a2`';
458 break;
459 case 'region':
460 $db = '`geoloc_region`';
461 $field = '`name`';
eaf30d86 462 $id = '`region`';
f6818108 463 if (isset($_REQUEST['country'])) {
464 $where .= ' WHERE `a2` = "'.$_REQUEST['country'].'"';
465 }
ff3eb9b7 466 break;
467 case 'school':
043bbacf 468 $db = 'profile_education_enum';
f9817768
SJ
469 $field = 'name';
470 $id = 'id';
ff3eb9b7 471 $page->assign('onchange', 'changeSchool(this.value)');
472 break;
473 case 'section':
474 $db = '`sections`';
475 break;
476 case 'secteur':
477 $db = '`emploi_secteur`';
478 $field = '`label`';
479 break;
480 default: exit();
481 }
482 if (isset($idVal)) {
483 header('Content-Type: text/plain; charset="UTF-8"');
484 $result = XDB::query('SELECT '.$field.' AS field FROM '.$db.' WHERE '.$id.' = {?} LIMIT 1',$idVal);
485 echo $result->fetchOneCell();
486 exit();
487 }
f6818108 488 header('Content-Type: text/xml; charset="UTF-8"');
05cb05c0 489 $page->changeTpl('include/field.select.tpl', NO_SKIN);
f6818108 490 $page->assign('name', $type);
ff3eb9b7 491 $page->assign('list', XDB::iterator('SELECT '.$field.' AS field,
492 '.$id.' AS id
493 FROM '.$db.$where.'
a85224e3 494 GROUP BY '.$field.'
ff3eb9b7 495 ORDER BY '.$field));
b0691e10
FB
496 $page->assign('with_text_value', true);
497 $page->assign('onchange', "document.forms.recherche.{$type}Txt.value = this.options[this.selectedIndex].text");
2ab7a09f 498 }
09824164 499}
500
a7de4ef7 501// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
09824164 502?>