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