Some clean up.
[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 on_subscribe($forlife, $uid, $promo, $pass)
42 {
43 require_once 'user.func.inc.php';
44 user_reindex($uid);
45 }
46
47
48 function form_prepare()
49 {
50 Platal::page()->assign('formulaire',1);
51 }
52
53 function get_diplomas($school = null)
54 {
55 if (is_null($school) && Env::has('school')) {
56 $school = Env::i('school');
57 }
58
59 if ((!is_null($school)) && ($school != '')) {
60 $sql = 'SELECT degreeid
61 FROM profile_education_degree
62 WHERE eduid=' . $school;
63 } else {
64 $sql = 'SELECT id
65 FROM profile_education_degree_enum
66 ORDER BY id';
67 }
68
69 $res = XDB::query($sql);
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());
77 }
78
79 function handler_quick(&$page, $action = null, $subaction = null)
80 {
81 global $globals;
82
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
90 if (Env::has('quick') || $action == 'geoloc') {
91 $quick = trim(Env::v('quick'));
92 if (S::logged() && !Env::has('page')) {
93 S::logger()->log('search', 'quick=' . $quick);
94 }
95 $list = 'profile|prf|fiche|fic|referent|ref|mentor';
96 if (S::has_perms()) {
97 $list .= '|admin|adm|ax';
98 }
99 if (preg_match('/^(' . $list . '):([-a-z]+(\.[-a-z]+(\.\d{2,4})?)?)$/', replace_accent($quick), $matches)) {
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 }
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;
123 } elseif (strpos($quick, 'doc:') === 0) {
124 $url = 'Docs/Recherche?';
125 $url .= 'action=search&q=' . urlencode(substr($quick, 4));
126 $url .= '&group=' . urlencode('-Equipe,-Main,-PmWiki,-Site,-Review');
127 pl_redirect($url);
128 }
129
130 $page->assign('formulaire', 0);
131
132 require_once 'userset.inc.php';
133 $view = new SearchSet(true, $action == 'geoloc' && substr($subaction, -3) == 'swf');
134 $view->addMod('minifiche', 'Mini-fiches', 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));
137 $view->addMod('geoloc', 'Planisphère', false, array('with_annu' => 'search/adv'));
138 }
139 $view->apply('search', $page, $action, $subaction);
140
141 $nb_tot = $view->count();
142 $page->assign('search_results_nb', $nb_tot);
143 if ($subaction) {
144 return;
145 }
146 if (!S::logged() && $nb_tot > $globals->search->public_max) {
147 new ThrowError('Votre recherche a généré trop de résultats pour un affichage public.');
148 } elseif ($nb_tot > $globals->search->private_max) {
149 new ThrowError('Recherche trop générale. Une <a href="search/adv">recherche avancée</a> permet de préciser la recherche.');
150 } elseif (empty($nb_tot)) {
151 new ThrowError('Il n\'existe personne correspondant à ces critères dans la base !');
152 }
153 } else {
154 $page->assign('formulaire',1);
155 $page->addJsLink('ajax.js');
156 }
157
158 require_once dirname(__FILE__) . '/search/search.inc.php';
159 $page->changeTpl('search/index.tpl');
160 $page->setTitle('Annuaire');
161 }
162
163 function handler_advanced(&$page, $action = null, $subaction = null)
164 {
165 global $globals;
166 require_once 'geoloc.inc.php';
167 require_once dirname(__FILE__) . '/search/search.inc.php';
168 $page->assign('advanced',1);
169 $page->addJsLink('jquery.autocomplete.js');
170
171 if (!Env::has('rechercher') && $action != 'geoloc') {
172 $this->form_prepare();
173 } else {
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),
180 'networking_type' => array('field' => 'network_type', 'table' => 'profile_networking_enum',
181 'text' => 'name', 'exact' => false),
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),
185 'section' => array('field' => 'id', 'table' => 'sections', 'text' => 'text', 'exact' => false),
186 'school' => array('field' => 'id', 'table' => 'profile_education_enum', 'text' => 'name', 'exact' => false),
187 'city' => array('table' => 'geoloc_city', 'text' => 'name', 'exact' => false)
188 );
189 if (!Env::has('page')) {
190 S::logger()->log('search', 'adv=' . var_export($_GET, true));
191 }
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']}
196 WHERE {$query['text']} " . ($query['exact'] ? " = {?}" :
197 " LIKE CONCAT('%', {?}, '%')"),
198 Env::v($field . 'Txt'));
199 $_REQUEST[$field] = $res->fetchOneCell();
200 }
201 }
202
203 require_once 'userset.inc.php';
204 $view = new SearchSet(false, $action == 'geoloc' && substr($subaction, -3) == 'swf');
205 $view->addMod('minifiche', 'Mini-fiches', true);
206 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true));
207 //$view->addMod('geoloc', 'Planisphère', false, array('with_annu' => 'search/adv'));
208 $view->apply('search/adv', $page, $action, $subaction);
209
210 if ($subaction) {
211 return;
212 }
213 $nb_tot = $view->count();
214 if ($nb_tot > $globals->search->private_max) {
215 $this->form_prepare();
216 new ThrowError('Recherche trop générale.');
217 }
218 }
219
220 $page->changeTpl('search/index.tpl', $action == 'mini' ? SIMPLE : SKINNED);
221 $page->addJsLink('ajax.js');
222 $page->assign('public_directory',0);
223 }
224
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"');
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']);
241 if (!$q) exit();
242
243 // try to look in cached results
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);
250 if ($res = $cache->fetchOneCell()) {
251 echo $res;
252 die();
253 }
254
255 // default search
256 $unique = '`user_id`';
257 $db = '`auth_user_md5`';
258 $realid = false;
259 $beginwith = true;
260 $field2 = false;
261 $qsearch = str_replace(array('%', '_'), '', $q);
262
263 switch ($type) {
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;
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;
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;
298 case 'firstname':
299 $field = '`prenom`';
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`';
308 $beginwith = false;
309 break;
310 case 'groupexTxt':
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';
317 if (strlen($q) > 2)
318 $beginwith = false;
319 $realid = 'a.id';
320 $unique = 'm.uid';
321 break;
322 case 'name':
323 $field = '`nom`';
324 $field2 = '`nom_usage`';
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` OR
330 `geoloc_pays`.`a2` = `auth_user_md5`.`nationalite2` OR
331 `geoloc_pays`.`a2` = `auth_user_md5`.`nationalite3`)';
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`';
340 $beginwith = false;
341 break;
342 case 'poste':
343 $db = '`entreprises`';
344 $field = '`poste`';
345 $unique = '`uid`';
346 break;
347 case 'schoolTxt':
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';
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':
365 $db = '`sections` INNER JOIN
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();
372 }
373
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 }
383 $field_select = $field;
384 $field_t = make_field_test($field, $beginwith);
385 if ($field2) {
386 $field2_t = make_field_test($field2, $beginwith);
387 $field_select = 'IF(' . $field_t . ', ' . $field . ', ' . $field2. ')';
388 }
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 . '
396 ORDER BY nb DESC
397 LIMIT 11',
398 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch,
399 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch);
400
401 $nbResults = 0;
402 $res = "";
403 while ($result = $list->next()) {
404 $nbResults++;
405 if ($nbResults == 11) {
406 $res .= $q."|-1\n";
407 } else {
408 $res .= $result['field'].'|';
409 $res .= $result['nb'];
410 if (isset($result['id'])) {
411 $res .= '|'.$result['id'];
412 }
413 $res .= "\n";
414 }
415 }
416 XDB::query('REPLACE INTO `search_autocomplete`
417 VALUES ({?}, {?}, {?}, NOW())',
418 $type, $q, $res);
419 echo $res;
420 exit();
421 }
422
423 function handler_list(&$page, $type = null, $idVal = null)
424 {
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;
434 case 'networking_type':
435 $db = '`profile_networking_enum`';
436 $field = '`name`';
437 $id = '`network_type`';
438 break;
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':
450 header('Content-Type: text/xml; charset="UTF-8"');
451 $this->get_diplomas();
452 $page->changeTpl('search/adv.grade.form.tpl', NO_SKIN);
453 return;
454 case 'groupex':
455 $db = 'groupex.asso';
456 $where = " WHERE (cat = 'GroupesX' OR cat = 'Institutions') AND pub = 'public'";
457 $field = 'nom';
458 break;
459 case 'nationalite':
460 $db = '`geoloc_pays` INNER JOIN
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`)';
464 $field = 'IF(`nat`=\'\', `pays`, `nat`)';
465 $id = '`a2`';
466 break;
467 case 'region':
468 $db = '`geoloc_region`';
469 $field = '`name`';
470 $id = '`region`';
471 if (isset($_REQUEST['country'])) {
472 $where .= ' WHERE `a2` = "'.$_REQUEST['country'].'"';
473 }
474 break;
475 case 'school':
476 $db = 'profile_education_enum';
477 $field = 'name';
478 $id = 'id';
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 }
496 header('Content-Type: text/xml; charset="UTF-8"');
497 $page->changeTpl('include/field.select.tpl', NO_SKIN);
498 $page->assign('name', $type);
499 $page->assign('list', XDB::iterator('SELECT '.$field.' AS field,
500 '.$id.' AS id
501 FROM '.$db.$where.'
502 GROUP BY '.$field.'
503 ORDER BY '.$field));
504 $page->assign('with_text_value', true);
505 $page->assign('onchange', "document.forms.recherche.{$type}Txt.value = this.options[this.selectedIndex].text");
506 }
507 }
508
509 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
510 ?>