Port X.net session to the new schema.
[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')) {
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');
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),
579a8c9a
FB
180 'groupex' => array('field' => 'id', 'table' => 'groupex.asso',
181 'text' => "(a.cat = 'GroupesX' OR a.cat = 'Institutions') AND pub = 'public' AND nom",
182 'exact' => false),
137e819f 183 'section' => array('field' => 'id', 'table' => 'sections', 'text' => 'text', 'exact' => false),
f08062c3
FB
184 'school' => array('field' => 'id', 'table' => 'applis_def', 'text' => 'text', 'exact' => false),
185 'city' => array('table' => 'geoloc_city', 'text' => 'name', 'exact' => false)
137e819f 186 );
e31c1c3e 187 if (!Env::has('page')) {
732e5855 188 S::logger()->log('search', 'adv=' . var_export($_GET, true));
e31c1c3e 189 }
137e819f
FB
190 foreach ($textFields as $field=>&$query) {
191 if (!Env::v($field) && Env::v($field . 'Txt')) {
192 $res = XDB::query("SELECT {$query['field']}
193 FROM {$query['table']}
579a8c9a
FB
194 WHERE {$query['text']} " . ($query['exact'] ? " = {?}" :
195 " LIKE CONCAT('%', {?}, '%')"),
137e819f
FB
196 Env::v($field . 'Txt'));
197 $_REQUEST[$field] = $res->fetchOneCell();
198 }
199 }
200
8c4a0c30 201 require_once 'userset.inc.php';
202 $view = new SearchSet(false, $action == 'geoloc' && substr($subaction, -3) == 'swf');
203 $view->addMod('minifiche', 'Minifiches', true);
35fa92e8 204 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true));
8ddd48c3 205 //$view->addMod('geoloc', 'Planisphère', false, array('with_annu' => 'search/adv'));
86b5c8f0 206 $view->apply('search/adv', $page, $action, $subaction);
eaf30d86 207
8c4a0c30 208 if ($subaction) {
209 return;
09824164 210 }
8c4a0c30 211 $nb_tot = $view->count();
09824164 212 if ($nb_tot > $globals->search->private_max) {
213 $this->form_prepare();
8d118e58 214 new ThrowError('Recherche trop générale.');
09824164 215 }
09824164 216 }
217
90ccb062 218 $page->changeTpl('search/index.tpl', $action == 'mini' ? SIMPLE : SKINNED);
3c640222 219 $page->addJsLink('ajax.js');
8c4a0c30 220 $page->assign('public_directory',0);
09824164 221 }
3c640222 222
838cc16a 223 function handler_autocomplete(&$page, $type = null)
224 {
225 // Autocompletion : according to type required, return
226 // a list of results matching with the number of matches.
227 // The output format is :
228 // result1|nb1
229 // result2|nb2
230 // ...
231 header('Content-Type: text/plain; charset="UTF-8"');
ff3eb9b7 232 $q = preg_replace(array('/\*+$/', // always look for $q*
233 '/([\^\$\[\]])/', // escape special regexp char
234 '/\*/'), // replace joker by regexp joker
235 array('',
236 '\\\\\1',
237 '.*'),
238 $_REQUEST['q']);
838cc16a 239 if (!$q) exit();
c15afc4e 240
eaf30d86 241 // try to look in cached results
ff3eb9b7 242 $cache = XDB::query('SELECT `result`
243 FROM `search_autocomplete`
244 WHERE `name` = {?} AND
245 `query` = {?} AND
246 `generated` > NOW() - INTERVAL 1 DAY',
247 $type, $q);
c15afc4e 248 if ($res = $cache->fetchOneCell()) {
ff3eb9b7 249 echo $res;
250 die();
c15afc4e 251 }
eaf30d86 252
2ab7a09f 253 // default search
f6818108 254 $unique = '`user_id`';
255 $db = '`auth_user_md5`';
2ab7a09f 256 $realid = false;
f3da6d81 257 $beginwith = true;
f6818108 258 $field2 = false;
baa62e58 259 $qsearch = str_replace(array('%', '_'), '', $q);
eaf30d86 260
838cc16a 261 switch ($type) {
ff3eb9b7 262 case 'binetTxt':
263 $db = '`binets_def` INNER JOIN
264 `binets_ins` ON(`binets_def`.`id` = `binets_ins`.`binet_id`)';
265 $field='`binets_def`.`text`';
266 if (strlen($q) > 2)
267 $beginwith = false;
268 $realid = '`binets_def`.`id`';
269 break;
270 case 'city':
271 $db = '`geoloc_city` INNER JOIN
272 `adresses` ON(`geoloc_city`.`id` = `adresses`.`cityid`)';
273 $unique='`uid`';
274 $field='`geoloc_city`.`name`';
275 break;
276 case 'countryTxt':
277 $db = '`geoloc_pays` INNER JOIN
278 `adresses` ON(`geoloc_pays`.`a2` = `adresses`.`country`)';
279 $unique='`uid`';
280 $field = '`geoloc_pays`.`pays`';
281 $field2 = '`geoloc_pays`.`country`';
282 $realid='`geoloc_pays`.`a2`';
283 break;
284 case 'entreprise':
285 $db = '`entreprises`';
286 $field = '`entreprise`';
287 $unique='`uid`';
288 break;
07c4f9cc 289 case 'firstname':
ff3eb9b7 290 $field = '`prenom`';
ff3eb9b7 291 $beginwith = false;
292 break;
293 case 'fonctionTxt':
294 $db = '`fonctions_def` INNER JOIN
295 `entreprises` ON(`entreprises`.`fonction` = `fonctions_def`.`id`)';
296 $field = '`fonction_fr`';
297 $unique = '`uid`';
298 $realid = '`fonctions_def`.`id`';
ff3eb9b7 299 $beginwith = false;
300 break;
301 case 'groupexTxt':
579a8c9a
FB
302 $db = "groupex.asso AS a INNER JOIN
303 groupex.membres AS m ON(a.id = m.asso_id
304 AND (a.cat = 'GroupesX' OR a.cat = 'Institutions')
305 AND a.pub = 'public')";
306 $field='a.nom';
307 $field2 = 'a.diminutif';
ff3eb9b7 308 if (strlen($q) > 2)
309 $beginwith = false;
579a8c9a
FB
310 $realid = 'a.id';
311 $unique = 'm.uid';
ff3eb9b7 312 break;
313 case 'name':
314 $field = '`nom`';
315 $field2 = '`nom_usage`';
ff3eb9b7 316 $beginwith = false;
317 break;
318 case 'nationaliteTxt':
319 $db = '`geoloc_pays` INNER JOIN
320 `auth_user_md5` ON(`geoloc_pays`.`a2` = `auth_user_md5`.`nationalite`)';
321 $field = 'IF(`geoloc_pays`.`nat`=\'\',
322 `geoloc_pays`.`pays`,
323 `geoloc_pays`.`nat`)';
324 $realid = '`geoloc_pays`.`a2`';
325 break;
326 case 'nickname':
327 $field = '`profile_nick`';
328 $db = '`auth_user_quick`';
ff3eb9b7 329 $beginwith = false;
330 break;
331 case 'poste':
332 $db = '`entreprises`';
333 $field = '`poste`';
334 $unique='`uid`';
335 break;
336 case 'schoolTxt':
337 $db = '`applis_def` INNER JOIN
338 `applis_ins` ON(`applis_def`.`id` = `applis_ins`.`aid`)';
339 $field='`applis_def`.`text`';
340 $unique = '`uid`';
341 $realid = '`applis_def`.`id`';
342 if (strlen($q) > 2)
343 $beginwith = false;
344 break;
345 case 'secteurTxt':
346 $db = '`emploi_secteur` INNER JOIN
347 `entreprises` ON(`entreprises`.`secteur` = `emploi_secteur`.`id`)';
348 $field = '`emploi_secteur`.`label`';
349 $realid = '`emploi_secteur`.`id`';
350 $unique = '`uid`';
351 $beginwith = false;
352 break;
353 case 'sectionTxt':
eaf30d86 354 $db = '`sections` INNER JOIN
ff3eb9b7 355 `auth_user_md5` ON(`auth_user_md5`.`section` = `sections`.`id`)';
356 $field = '`sections`.`text`';
357 $realid = '`sections`.`id`';
358 $beginwith = false;
359 break;
360 default: exit();
838cc16a 361 }
362
baa62e58
FB
363 function make_field_test($fields, $beginwith) {
364 $tests = array();
365 $tests[] = $fields . ' LIKE CONCAT({?}, \'%\')';
366 if (!$beginwith) {
367 $tests[] = $fields . ' LIKE CONCAT(\'% \', {?}, \'%\')';
368 $tests[] = $fields . ' LIKE CONCAT(\'%-\', {?}, \'%\')';
369 }
370 return '(' . implode(' OR ', $tests) . ')';
371 }
ff3eb9b7 372 $field_select = $field;
baa62e58 373 $field_t = make_field_test($field, $beginwith);
ff3eb9b7 374 if ($field2) {
baa62e58
FB
375 $field2_t = make_field_test($field2, $beginwith);
376 $field_select = 'IF(' . $field_t . ', ' . $field . ', ' . $field2. ')';
ff3eb9b7 377 }
baa62e58
FB
378 $list = XDB::iterator('SELECT ' . $field_select . ' AS field,
379 COUNT(DISTINCT ' . $unique . ') AS nb
380 ' . ($realid ? (', ' . $realid . ' AS id') : '') . '
381 FROM ' . $db . '
382 WHERE ' . $field_t .
383 ($field2 ? (' OR ' . $field2_t) : '') . '
384 GROUP BY ' . $field_select . '
ff3eb9b7 385 ORDER BY nb DESC
386 LIMIT 11',
7eb43a1d 387 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch,
011b438c 388 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch);
838cc16a 389 $nbResults = 0;
c15afc4e 390 $res = "";
2ab7a09f 391 while ($result = $list->next()) {
838cc16a 392 $nbResults++;
393 if ($nbResults == 11) {
b3ec63d5 394 $res .= $q."|-1\n";
838cc16a 395 } else {
f6818108 396 $res .= $result['field'].'|';
ff3eb9b7 397 $res .= $result['nb'];
398 if (isset($result['id'])) {
399 $res .= '|'.$result['id'];
400 }
401 $res .= "\n";
838cc16a 402 }
403 }
ff3eb9b7 404 XDB::query('REPLACE INTO `search_autocomplete`
405 VALUES ({?}, {?}, {?}, NOW())',
406 $type, $q, $res);
c15afc4e 407 echo $res;
838cc16a 408 exit();
409 }
eaf30d86 410
2ab7a09f 411 function handler_list(&$page, $type = null, $idVal = null)
412 {
ff3eb9b7 413 // Give the list of all values possible of type and builds a select input for it
414 $field = '`text`';
415 $id = '`id`';
416 $where = '';
417
418 switch ($type) {
419 case 'binet':
420 $db = '`binets_def`';
421 break;
422 case 'country':
423 $db = '`geoloc_pays`';
424 $field = '`pays`';
425 $id = '`a2`';
426 $page->assign('onchange', 'changeCountry(this.value)');
427 break;
428 case 'fonction':
429 $db = '`fonctions_def`';
430 $field = '`fonction_fr`';
431 break;
432 case 'diploma':
f6818108 433 header('Content-Type: text/xml; charset="UTF-8"');
ff3eb9b7 434 $this->get_diplomas();
435 $page->changeTpl('search/adv.grade.form.tpl', NO_SKIN);
436 return;
437 case 'groupex':
579a8c9a
FB
438 $db = 'groupex.asso';
439 $where = " WHERE (cat = 'GroupesX' OR cat = 'Institutions') AND pub = 'public'";
440 $field = 'nom';
ff3eb9b7 441 break;
442 case 'nationalite':
eaf30d86 443 $db = '`geoloc_pays` INNER JOIN
a85224e3 444 `auth_user_md5` ON (`geoloc_pays`.`a2` = `auth_user_md5`.`nationalite`)';
ff3eb9b7 445 $field = 'IF(`nat`=\'\', `pays`, `nat`)';
446 $id = '`a2`';
447 break;
448 case 'region':
449 $db = '`geoloc_region`';
450 $field = '`name`';
eaf30d86 451 $id = '`region`';
f6818108 452 if (isset($_REQUEST['country'])) {
453 $where .= ' WHERE `a2` = "'.$_REQUEST['country'].'"';
454 }
ff3eb9b7 455 break;
456 case 'school':
457 $db = '`applis_def`';
458 $page->assign('onchange', 'changeSchool(this.value)');
459 break;
460 case 'section':
461 $db = '`sections`';
462 break;
463 case 'secteur':
464 $db = '`emploi_secteur`';
465 $field = '`label`';
466 break;
467 default: exit();
468 }
469 if (isset($idVal)) {
470 header('Content-Type: text/plain; charset="UTF-8"');
471 $result = XDB::query('SELECT '.$field.' AS field FROM '.$db.' WHERE '.$id.' = {?} LIMIT 1',$idVal);
472 echo $result->fetchOneCell();
473 exit();
474 }
f6818108 475 header('Content-Type: text/xml; charset="UTF-8"');
05cb05c0 476 $page->changeTpl('include/field.select.tpl', NO_SKIN);
f6818108 477 $page->assign('name', $type);
ff3eb9b7 478 $page->assign('list', XDB::iterator('SELECT '.$field.' AS field,
479 '.$id.' AS id
480 FROM '.$db.$where.'
a85224e3 481 GROUP BY '.$field.'
ff3eb9b7 482 ORDER BY '.$field));
b0691e10
FB
483 $page->assign('with_text_value', true);
484 $page->assign('onchange', "document.forms.recherche.{$type}Txt.value = this.options[this.selectedIndex].text");
2ab7a09f 485 }
09824164 486}
487
a7de4ef7 488// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
09824164 489?>