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