cache autocomplete requests in MySQL
[platal.git] / modules / search.php
CommitLineData
09824164 1<?php
2/***************************************************************************
5ddeb07c 3 * Copyright (C) 2003-2007 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),
9ed396c0 29 'search/ajax/region' => $this->make_hook('region', AUTH_COOKIE, 'user', NO_AUTH),
30 'search/ajax/grade' => $this->make_hook('grade', AUTH_COOKIE, 'user', NO_AUTH),
ba2afb88 31 'advanced_search.php' => $this->make_hook('redir_advanced', AUTH_PUBLIC),
2ab7a09f 32 'search/autocomplete' => $this->make_hook('autocomplete', AUTH_COOKIE, 'user', NO_AUTH),
33 'search/list' => $this->make_hook('list', AUTH_COOKIE, 'user', NO_AUTH),
09824164 34 );
35 }
36
ba2afb88 37 function handler_redir_advanced(&$page, $mode = null)
38 {
39 pl_redirect('search/adv');
40 exit;
41 }
42
8d8f7607 43 function on_subscribe($forlife, $uid, $promo, $pass)
44 {
45 require_once 'user.func.inc.php';
46 user_reindex($uid);
47 }
48
09824164 49 function get_quick($offset, $limit, $order)
50 {
51 global $globals;
393137f9 52 if (!S::logged()) {
53 Env::kill('with_soundex');
54 }
09824164 55 $qSearch = new QuickSearch('quick');
56 $fields = new SFieldGroup(true, array($qSearch));
57
58 if ($qSearch->isempty()) {
a7de4ef7 59 new ThrowError('Recherche trop générale.');
09824164 60 }
61
62 $sql = 'SELECT SQL_CALC_FOUND_ROWS
63 UPPER(IF(u.nom!="",u.nom,u.nom_ini)) AS nom,
64 IF(u.prenom!="",u.prenom,u.prenom_ini) AS prenom,
65 '.$globals->search->result_fields.'
66 c.uid AS contact, w.ni_id AS watch,
67 '.$qSearch->get_score_statement().'
68 FROM auth_user_md5 AS u
69 '.$fields->get_select_statement().'
70 LEFT JOIN auth_user_quick AS q ON (u.user_id = q.user_id)
71 LEFT JOIN aliases AS a ON (u.user_id = a.id AND a.type="a_vie")
6b590724 72 LEFT JOIN contacts AS c ON (c.uid='.S::i('uid', -1).'
09824164 73 AND c.contact=u.user_id)
74 LEFT JOIN watch_nonins AS w ON (w.ni_id=u.user_id
6b590724 75 AND w.uid='.S::i('uid', -1).')
09824164 76 '.$globals->search->result_where_statement.'
77 WHERE '.$fields->get_where_statement()
cab08090 78 .(S::logged() && Env::has('nonins') ? ' AND u.perms="pending" AND u.deces=0' : '')
09824164 79 .'
80 GROUP BY u.user_id
81 ORDER BY '.($order?($order.', '):'')
82 .implode(',',array_filter(array($fields->get_order_statement(),
83 'u.promo DESC, NomSortKey, prenom'))).'
84 LIMIT '.$offset * $globals->search->per_page.','
85 .$globals->search->per_page;
08cce2ff 86 $list = XDB::iterator($sql);
87 $res = XDB::query("SELECT FOUND_ROWS()");
09824164 88 $nb_tot = $res->fetchOneCell();
89 return array($list, $nb_tot);
90 }
91
92 function form_prepare()
93 {
d25e0f0b 94 global $page;
95
09824164 96 $page->assign('formulaire',1);
09824164 97 $page->assign('choix_schools',
08cce2ff 98 XDB::iterator('SELECT id,text FROM applis_def ORDER BY text'));
3c640222 99 $this->get_diplomas();
100 }
101
102 function get_diplomas($school = null)
103 {
104 if (is_null($school) && Env::has('school')) {
105 $school = Env::i('school');
106 }
09824164 107
3c640222 108 if (!is_null($school)) {
109 $sql = 'SELECT type FROM applis_def WHERE id=' . $school;
09824164 110 } else {
111 $sql = 'DESCRIBE applis_def type';
112 }
113
08cce2ff 114 $res = XDB::query($sql);
09824164 115 $row = $res->fetchOneRow();
3c640222 116 if (!is_null($school)) {
09824164 117 $types = $row[0];
118 } else {
119 $types = explode('(',$row[1]);
120 $types = str_replace("'","",substr($types[1],0,-1));
121 }
3c640222 122 global $page;
09824164 123 $page->assign('choix_diplomas', explode(',',$types));
124 }
125
126 function get_advanced($offset, $limit, $order)
127 {
128 $fields = new SFieldGroup(true, advancedSearchFromInput());
129 if ($fields->too_large()) {
130 $this->form_prepare();
a7de4ef7 131 new ThrowError('Recherche trop générale.');
09824164 132 }
133 global $globals, $page;
134
135 $page->assign('search_vars', $fields->get_url());
136
137 $where = $fields->get_where_statement();
138 if ($where) {
139 $where = "WHERE $where";
140 }
141 $sql = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT
142 u.nom, u.prenom,
143 '.$globals->search->result_fields.'
144 c.uid AS contact,
145 w.ni_id AS watch
146 FROM auth_user_md5 AS u
147 LEFT JOIN auth_user_quick AS q USING(user_id)
148 '.$fields->get_select_statement().'
149 '.(Env::has('only_referent') ? ' INNER JOIN mentor AS m ON (m.uid = u.user_id)' : '').'
150 LEFT JOIN aliases AS a ON (u.user_id = a.id AND a.type="a_vie")
cab08090 151 LEFT JOIN contacts AS c ON (c.uid='.S::v('uid').'
09824164 152 AND c.contact=u.user_id)
153 LEFT JOIN watch_nonins AS w ON (w.ni_id=u.user_id
cab08090 154 AND w.uid='.S::v('uid').')
09824164 155 '.$globals->search->result_where_statement."
156 $where
1f17ab93 157 GROUP BY u.user_id
09824164 158 ORDER BY ".($order?($order.', '):'')
159 .implode(',',array_filter(array($fields->get_order_statement(),
160 'promo DESC, NomSortKey, prenom'))).'
161 LIMIT '.($offset * $limit).','.$limit;
08cce2ff 162 $liste = XDB::iterator($sql);
163 $res = XDB::query("SELECT FOUND_ROWS()");
09824164 164 $nb_tot = $res->fetchOneCell();
165 return Array($liste, $nb_tot);
166 }
167
8c4a0c30 168 function handler_quick(&$page, $action = null, $subaction = null)
09824164 169 {
170 global $globals;
171
8c4a0c30 172 if (Env::has('quick') || $action == 'geoloc') {
09824164 173 $page->assign('formulaire', 0);
174
8c4a0c30 175 require_once 'userset.inc.php';
176 $view = new SearchSet(true, $action == 'geoloc' && substr($subaction, -3) == 'swf');
177 $view->addMod('minifiche', 'Minifiches', true);
178 $view->addMod('trombi', 'Trombinoscope');
179 $view->addMod('geoloc', 'Planishpère');
180 $view->apply('search', $page, $action, $subaction);
09824164 181
8c4a0c30 182 $nb_tot = $view->count();
183 if ($subaction) {
184 return;
185 }
cab08090 186 if (!S::logged() && $nb_tot > $globals->search->public_max) {
a7de4ef7 187 new ThrowError('Votre recherche a généré trop de résultats pour un affichage public.');
09824164 188 } elseif ($nb_tot > $globals->search->private_max) {
a7de4ef7 189 new ThrowError('Recherche trop générale');
09824164 190 } elseif (empty($nb_tot)) {
a7de4ef7 191 new ThrowError('il n\'existe personne correspondant à ces critères dans la base !');
09824164 192 }
193 } else {
70a55e68 194 $res = XDB::query("SELECT MIN(diminutif), MAX(diminutif)
195 FROM groupex.asso
196 WHERE cat = 'Promotions'");
197 list($min, $max) = $res->fetchOneRow();
198 $page->assign('promo_min', $min);
199 $page->assign('promo_max', $max);
09824164 200 $page->assign('formulaire',1);
e654517d 201 $page->addJsLink('ajax.js');
09824164 202 }
203
8c4a0c30 204 $page->changeTpl('search/index.tpl');
205 $page->assign('xorg_title','Polytechnique.org - Annuaire');
206 $page->assign('baseurl', $globals->baseurl);
09824164 207 }
208
209 function handler_advanced(&$page, $mode = null)
210 {
211 global $globals;
09824164 212 if (!Env::has('rechercher')) {
213 $this->form_prepare();
214 } else {
8c4a0c30 215 require_once 'userset.inc.php';
216 $view = new SearchSet(false, $action == 'geoloc' && substr($subaction, -3) == 'swf');
217 $view->addMod('minifiche', 'Minifiches', true);
218 $view->addMod('trombi', 'Trombinoscope');
219 $view->addMod('geoloc', 'Planishpère');
220 $view->apply('search', $page, $action, $subaction);
221
222 if ($subaction) {
223 return;
09824164 224 }
8c4a0c30 225 $nb_tot = $view->count();
09824164 226 if ($nb_tot > $globals->search->private_max) {
227 $this->form_prepare();
a7de4ef7 228 new ThrowError('Recherche trop générale');
09824164 229 }
09824164 230 }
231
8c4a0c30 232 $page->changeTpl('search/index.tpl', $mode == 'mini' ? SIMPLE : SKINNED);
3c640222 233 $page->addJsLink('ajax.js');
8c4a0c30 234 $page->assign('advanced',1);
235 $page->assign('public_directory',0);
09824164 236 }
3c640222 237
238 function handler_region(&$page, $country = null)
239 {
493b6abe 240 header('Content-Type: text/html; charset="UTF-8"');
3c640222 241 require_once("geoloc.inc.php");
242 $page->ChangeTpl('search/adv.region.form.tpl', NO_SKIN);
243 $page->assign('region', "");
244 $page->assign('country', $country);
245 }
246
247 function handler_grade(&$page, $school = null)
248 {
493b6abe 249 header('Content-Type: text/html; charset="UTF-8"');
3c640222 250 $page->ChangeTpl('search/adv.grade.form.tpl', NO_SKIN);
251 $page->assign('grade', '');
252 $this->get_diplomas($school);
253 }
838cc16a 254
255 function handler_autocomplete(&$page, $type = null)
256 {
257 // Autocompletion : according to type required, return
258 // a list of results matching with the number of matches.
259 // The output format is :
260 // result1|nb1
261 // result2|nb2
262 // ...
263 header('Content-Type: text/plain; charset="UTF-8"');
c15afc4e 264 $q = preg_replace('/\*+$/','',$_REQUEST['q']);
838cc16a 265 if (!$q) exit();
c15afc4e 266
267 // try to look in cached results
268 $cache = XDB::query('SELECT result FROM search_autocomplete WHERE name = {?} AND query = {?} AND generated > NOW() - INTERVAL 1 DAY',
269 $type, $q);
270 if ($res = $cache->fetchOneCell()) {
271 echo $res;
272 die();
273 }
274
2ab7a09f 275 // default search
838cc16a 276 $unique = 'user_id';
277 $db = 'auth_user_md5';
2ab7a09f 278 $realid = false;
279 $contains = false;
280
838cc16a 281 switch ($type) {
2ab7a09f 282 case 'binetTxt':
283 $db = 'binets_def INNER JOIN binets_ins ON(binets_def.id = binets_ins.binet_id)';
284 $field='binets_def.text';
285 if (strlen($q) > 2)
286 $contains = true;
287 $realid = 'binets_def.id';
288 break;
289 case 'city': $db = 'geoloc_city INNER JOIN adresses ON(geoloc_city.id = adresses.cityid)'; $unique='uid'; $field='geoloc_city.name'; break;
290 case 'entreprise': $db = 'entreprises'; $field = 'entreprise'; $unique='uid'; break;
838cc16a 291 case 'firstname': $field = 'prenom'; break;
2ab7a09f 292 case 'fonctionTxt':
293 $db = 'fonctions_def INNER JOIN entreprises ON(entreprises.fonction = fonctions_def.id)';
294 $field = 'fonction_fr';
295 $unique = 'uid';
296 $realid = 'fonctions_def.id';
297 break;
298 case 'groupexTxt':
299 $db = 'groupesx_def INNER JOIN groupesx_ins ON(groupesx_def.id = groupesx_ins.gid)';
300 $field='groupesx_def.text';
301 if (strlen($q) > 2)
302 $contains = true;
303 $realid = 'groupesx_def.id';
304 $unique = 'guid';
305 break;
838cc16a 306 case 'name': $field = 'nom'; break;
2ab7a09f 307 case 'nationaliteTxt':
308 $db = 'geoloc_pays INNER JOIN auth_user_md5 ON(geoloc_pays.a2 = auth_user_md5.nationalite)';
309 $field = 'IF(geoloc_pays.nat=\'\', geoloc_pays.pays, geoloc_pays.nat)';
310 $realid = 'geoloc_pays.a2';
311 break;
baa8a594 312 case 'nickname': $field = 'profile_nick'; $db = 'auth_user_quick'; break;
df87518a 313 case 'poste': $db = 'entreprises'; $field = 'poste'; $unique='uid'; break;
2ab7a09f 314 case 'secteurTxt':
315 $db = 'emploi_secteur INNER JOIN entreprises ON(entreprises.secteur = emploi_secteur.id)';
316 $field = 'emploi_secteur.label';
317 $realid = 'emploi_secteur.id';
318 $unique = 'uid';
319 break;
320 case 'sectionTxt':
321 $db = 'sections INNER JOIN auth_user_md5 ON(auth_user_md5.section = sections.id)';
322 $field = 'sections.text';
323 $realid = 'sections.id';
324 break;
838cc16a 325 default: exit();
326 }
327
2ab7a09f 328 $list = XDB::iterator('
329 SELECT
330 '.$field.' AS field,
331 COUNT(DISTINCT '.$unique.') AS nb
332 '.($realid?(', '.$realid.' AS id'):'').'
333 FROM '.$db.'
334 WHERE '.$field.' LIKE {?}
335 GROUP BY '.$field.'
336 ORDER BY nb DESC
337 LIMIT 11',
338 ($contains?'%':'').str_replace('*','%',$q).'%');
838cc16a 339 $nbResults = 0;
c15afc4e 340 $res = "";
2ab7a09f 341 while ($result = $list->next()) {
838cc16a 342 $nbResults++;
343 if ($nbResults == 11) {
c15afc4e 344 $res .= '...|1'."\n";
838cc16a 345 } else {
c15afc4e 346 $res .= $result['field'].'|'.$result['nb'].(isset($result['id'])?('|'.$result['id']):'')."\n";
838cc16a 347 }
348 }
c15afc4e 349 XDB::query('REPLACE INTO search_autocomplete VALUES ({?}, {?}, {?}, NOW())',
350 $type, $q, $res);
351 echo $res;
838cc16a 352 exit();
353 }
2ab7a09f 354
355 function handler_list(&$page, $type = null, $idVal = null)
356 {
357 // Give the list of all values possible of type and builds a select input for it
358 $field = 'text';
359 $id = 'id';
360 switch ($type) {
361 case 'binet':
362 $db = 'binets_def';
363 break;
364 case 'fonction':
365 $db = 'fonctions_def';
366 $field = 'fonction_fr';
367 break;
368 case 'groupex':
369 $db = 'groupesx_def';
370 break;
371 case 'nationalite':
372 $db = 'geoloc_pays';
373 $field = 'IF(nat=\'\', pays, nat)';
374 $id = 'a2';
375 break;
376 case 'section':
377 $db = 'sections';
378 break;
379 case 'secteur':
380 $db = 'emploi_secteur';
381 $field = 'label';
382 break;
383 default: exit();
384 }
385 if (isset($idVal)) {
386 header('Content-Type: text/plain; charset="UTF-8"');
387 $result = XDB::query('SELECT '.$field.' AS field FROM '.$db.' WHERE '.$id.' = {?} LIMIT 1',$idVal);
388 echo $result->fetchOneCell();
389 } else {
390 header('Content-Type: text/xml; charset="UTF-8"');
391 $list = XDB::iterator('
392 SELECT
393 '.$field.' AS field,
394 '.$id.' AS id
395 FROM '.$db.'
396 ORDER BY '.$field);
397 echo '<select name="'.$type.'">';
398 while ($result = $list->next()) {
399 echo '<option value="'.$result['id'].'">'.htmlspecialchars($result['field']).'</option>';
400 }
401 echo '</select>';
402 }
403
404 exit();
405 }
09824164 406}
407
a7de4ef7 408// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
09824164 409?>