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