Keeping things in order...
[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 {
d25e0f0b 50 global $page;
51
09824164 52 $page->assign('formulaire',1);
3c640222 53 }
54
55 function get_diplomas($school = null)
56 {
57 if (is_null($school) && Env::has('school')) {
58 $school = Env::i('school');
59 }
09824164 60
3c640222 61 if (!is_null($school)) {
62 $sql = 'SELECT type FROM applis_def WHERE id=' . $school;
09824164 63 } else {
64 $sql = 'DESCRIBE applis_def type';
65 }
66
08cce2ff 67 $res = XDB::query($sql);
09824164 68 $row = $res->fetchOneRow();
3c640222 69 if (!is_null($school)) {
09824164 70 $types = $row[0];
71 } else {
72 $types = explode('(',$row[1]);
73 $types = str_replace("'","",substr($types[1],0,-1));
74 }
3c640222 75 global $page;
09824164 76 $page->assign('choix_diplomas', explode(',',$types));
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')) {
e31c1c3e
FB
93 $_SESSION['log']->log('search', 'quick=' . $quick);
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');
35fa92e8 134 $view->addMod('minifiche', 'Minifiches', true, array('with_score' => true));
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');
8c4a0c30 160 $page->assign('xorg_title','Polytechnique.org - 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),
f08062c3
FB
186 'school' => array('field' => 'id', 'table' => 'applis_def', 'text' => 'text', 'exact' => false),
187 'city' => array('table' => 'geoloc_city', 'text' => 'name', 'exact' => false)
137e819f 188 );
e31c1c3e
FB
189 if (!Env::has('page')) {
190 $_SESSION['log']->log('search', 'adv=' . var_export($_GET, true));
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');
205 $view->addMod('minifiche', 'Minifiches', 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
329 `auth_user_md5` ON(`geoloc_pays`.`a2` = `auth_user_md5`.`nationalite`)';
330 $field = 'IF(`geoloc_pays`.`nat`=\'\',
331 `geoloc_pays`.`pays`,
332 `geoloc_pays`.`nat`)';
333 $realid = '`geoloc_pays`.`a2`';
334 break;
335 case 'nickname':
336 $field = '`profile_nick`';
337 $db = '`auth_user_quick`';
ff3eb9b7 338 $beginwith = false;
339 break;
340 case 'poste':
341 $db = '`entreprises`';
342 $field = '`poste`';
343 $unique='`uid`';
344 break;
345 case 'schoolTxt':
346 $db = '`applis_def` INNER JOIN
347 `applis_ins` ON(`applis_def`.`id` = `applis_ins`.`aid`)';
348 $field='`applis_def`.`text`';
349 $unique = '`uid`';
350 $realid = '`applis_def`.`id`';
351 if (strlen($q) > 2)
352 $beginwith = false;
353 break;
354 case 'secteurTxt':
355 $db = '`emploi_secteur` INNER JOIN
356 `entreprises` ON(`entreprises`.`secteur` = `emploi_secteur`.`id`)';
357 $field = '`emploi_secteur`.`label`';
358 $realid = '`emploi_secteur`.`id`';
359 $unique = '`uid`';
360 $beginwith = false;
361 break;
362 case 'sectionTxt':
eaf30d86 363 $db = '`sections` INNER JOIN
ff3eb9b7 364 `auth_user_md5` ON(`auth_user_md5`.`section` = `sections`.`id`)';
365 $field = '`sections`.`text`';
366 $realid = '`sections`.`id`';
367 $beginwith = false;
368 break;
369 default: exit();
838cc16a 370 }
371
baa62e58
FB
372 function make_field_test($fields, $beginwith) {
373 $tests = array();
374 $tests[] = $fields . ' LIKE CONCAT({?}, \'%\')';
375 if (!$beginwith) {
376 $tests[] = $fields . ' LIKE CONCAT(\'% \', {?}, \'%\')';
377 $tests[] = $fields . ' LIKE CONCAT(\'%-\', {?}, \'%\')';
378 }
379 return '(' . implode(' OR ', $tests) . ')';
380 }
ff3eb9b7 381 $field_select = $field;
baa62e58 382 $field_t = make_field_test($field, $beginwith);
ff3eb9b7 383 if ($field2) {
baa62e58
FB
384 $field2_t = make_field_test($field2, $beginwith);
385 $field_select = 'IF(' . $field_t . ', ' . $field . ', ' . $field2. ')';
ff3eb9b7 386 }
baa62e58
FB
387 $list = XDB::iterator('SELECT ' . $field_select . ' AS field,
388 COUNT(DISTINCT ' . $unique . ') AS nb
389 ' . ($realid ? (', ' . $realid . ' AS id') : '') . '
390 FROM ' . $db . '
391 WHERE ' . $field_t .
392 ($field2 ? (' OR ' . $field2_t) : '') . '
393 GROUP BY ' . $field_select . '
ff3eb9b7 394 ORDER BY nb DESC
395 LIMIT 11',
7eb43a1d 396 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch,
011b438c 397 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch);
838cc16a 398 $nbResults = 0;
c15afc4e 399 $res = "";
2ab7a09f 400 while ($result = $list->next()) {
838cc16a 401 $nbResults++;
402 if ($nbResults == 11) {
b3ec63d5 403 $res .= $q."|-1\n";
838cc16a 404 } else {
f6818108 405 $res .= $result['field'].'|';
ff3eb9b7 406 $res .= $result['nb'];
407 if (isset($result['id'])) {
408 $res .= '|'.$result['id'];
409 }
410 $res .= "\n";
838cc16a 411 }
412 }
ff3eb9b7 413 XDB::query('REPLACE INTO `search_autocomplete`
414 VALUES ({?}, {?}, {?}, NOW())',
415 $type, $q, $res);
c15afc4e 416 echo $res;
838cc16a 417 exit();
418 }
eaf30d86 419
2ab7a09f 420 function handler_list(&$page, $type = null, $idVal = null)
421 {
ff3eb9b7 422 // Give the list of all values possible of type and builds a select input for it
423 $field = '`text`';
424 $id = '`id`';
425 $where = '';
426
427 switch ($type) {
428 case 'binet':
429 $db = '`binets_def`';
430 break;
92c3f9e5
GB
431 case 'networking_type':
432 $db = '`profile_networking_enum`';
433 $field = '`name`';
434 $id = '`network_type`';
435 break;
ff3eb9b7 436 case 'country':
437 $db = '`geoloc_pays`';
438 $field = '`pays`';
439 $id = '`a2`';
440 $page->assign('onchange', 'changeCountry(this.value)');
441 break;
442 case 'fonction':
443 $db = '`fonctions_def`';
444 $field = '`fonction_fr`';
445 break;
446 case 'diploma':
f6818108 447 header('Content-Type: text/xml; charset="UTF-8"');
ff3eb9b7 448 $this->get_diplomas();
449 $page->changeTpl('search/adv.grade.form.tpl', NO_SKIN);
450 return;
451 case 'groupex':
579a8c9a
FB
452 $db = 'groupex.asso';
453 $where = " WHERE (cat = 'GroupesX' OR cat = 'Institutions') AND pub = 'public'";
454 $field = 'nom';
ff3eb9b7 455 break;
456 case 'nationalite':
eaf30d86 457 $db = '`geoloc_pays` INNER JOIN
a85224e3 458 `auth_user_md5` ON (`geoloc_pays`.`a2` = `auth_user_md5`.`nationalite`)';
ff3eb9b7 459 $field = 'IF(`nat`=\'\', `pays`, `nat`)';
460 $id = '`a2`';
461 break;
462 case 'region':
463 $db = '`geoloc_region`';
464 $field = '`name`';
eaf30d86 465 $id = '`region`';
f6818108 466 if (isset($_REQUEST['country'])) {
467 $where .= ' WHERE `a2` = "'.$_REQUEST['country'].'"';
468 }
ff3eb9b7 469 break;
470 case 'school':
471 $db = '`applis_def`';
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?>