Removes calls to get_user_forlife in Search and XnetEvents modules.
[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)) {
60 $sql = 'SELECT type FROM applis_def WHERE id=' . $school;
61 } else {
62 $sql = 'DESCRIBE applis_def type';
63 }
64
65 $res = XDB::query($sql);
66 $row = $res->fetchOneRow();
67 if (!is_null($school)) {
68 $types = $row[0];
69 } else {
70 $types = explode('(',$row[1]);
71 $types = str_replace("'","",substr($types[1],0,-1));
72 }
73 Platal::page()->assign('choix_diplomas', explode(',',$types));
74 }
75
76 function handler_quick(&$page, $action = null, $subaction = null)
77 {
78 global $globals;
79
80 $res = XDB::query("SELECT MIN(`diminutif`), MAX(`diminutif`)
81 FROM `groupex`.`asso`
82 WHERE `cat` = 'Promotions'");
83 list($min, $max) = $res->fetchOneRow();
84 $page->assign('promo_min', $min);
85 $page->assign('promo_max', $max);
86
87 if (Env::has('quick') || $action == 'geoloc') {
88 $quick = trim(Env::v('quick'));
89 if (S::logged() && !Env::has('page')) {
90 S::logger()->log('search', 'quick=' . $quick);
91 }
92 $list = 'profile|prf|fiche|fic|referent|ref|mentor';
93 if (S::has_perms()) {
94 $list .= '|admin|adm|ax';
95 }
96 if (preg_match('/^(' . $list . '):([-a-z]+(\.[-a-z]+(\.\d{2,4})?)?)$/', replace_accent($quick), $matches)) {
97 $login = $matches[2];
98 switch($matches[1]) {
99 case 'admin': case 'adm':
100 $base = 'admin/user/';
101 break;
102 case 'ax':
103 $base = 'profile/ax/';
104 break;
105 case 'profile': case 'prf': case 'fiche': case 'fic':
106 $base = 'profile/';
107 break;
108 case 'referent': case 'ref': case 'mentor':
109 $base = 'referent/';
110 break;
111 }
112
113 $user = User::getSilent($login);
114 if ($user) {
115 pl_redirect($base . $user->login());
116 }
117 $_REQUEST['quick'] = $forlife;
118 $_GET['quick'] = $forlife;
119 } elseif (strpos($quick, 'doc:') === 0) {
120 $url = 'Docs/Recherche?';
121 $url .= 'action=search&q=' . urlencode(substr($quick, 4));
122 $url .= '&group=' . urlencode('-Equipe,-Main,-PmWiki,-Site,-Review');
123 pl_redirect($url);
124 }
125
126 $page->assign('formulaire', 0);
127
128 require_once 'userset.inc.php';
129 $view = new SearchSet(true, $action == 'geoloc' && substr($subaction, -3) == 'swf');
130 $view->addMod('minifiche', 'Mini-fiches', true, array('with_score' => true));
131 if (S::logged() && !Env::i('nonins')) {
132 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true, 'with_score' => true));
133 $view->addMod('geoloc', 'Planisphère', false, array('with_annu' => 'search/adv'));
134 }
135 $view->apply('search', $page, $action, $subaction);
136
137 $nb_tot = $view->count();
138 $page->assign('search_results_nb', $nb_tot);
139 if ($subaction) {
140 return;
141 }
142 if (!S::logged() && $nb_tot > $globals->search->public_max) {
143 new ThrowError('Votre recherche a généré trop de résultats pour un affichage public.');
144 } elseif ($nb_tot > $globals->search->private_max) {
145 new ThrowError('Recherche trop générale. Une <a href="search/adv">recherche avancée</a> permet de préciser la recherche.');
146 } elseif (empty($nb_tot)) {
147 new ThrowError('Il n\'existe personne correspondant à ces critères dans la base !');
148 }
149 } else {
150 $page->assign('formulaire',1);
151 $page->addJsLink('ajax.js');
152 }
153
154 require_once dirname(__FILE__) . '/search/search.inc.php';
155 $page->changeTpl('search/index.tpl');
156 $page->setTitle('Annuaire');
157 }
158
159 function handler_advanced(&$page, $action = null, $subaction = null)
160 {
161 global $globals;
162 require_once 'geoloc.inc.php';
163 require_once dirname(__FILE__) . '/search/search.inc.php';
164 $page->assign('advanced',1);
165 $page->addJsLink('jquery.autocomplete.js');
166
167 if (!Env::has('rechercher') && $action != 'geoloc') {
168 $this->form_prepare();
169 } else {
170 $textFields = array(
171 'country' => array('field' => 'a2', 'table' => 'geoloc_pays', 'text' => 'pays', 'exact' => false),
172 'fonction' => array('field' => 'id', 'table' => 'fonctions_def', 'text' => 'fonction_fr', 'exact' => true),
173 'secteur' => array('field' => 'id', 'table' => 'emploi_secteur', 'text' => 'label', 'exact' => false),
174 'nationalite' => array('field' => 'a2', 'table' => 'geoloc_pays', 'text' => 'nat', 'exact' => 'false'),
175 'binet' => array('field' => 'id', 'table' => 'binets_def', 'text' => 'text', 'exact' => false),
176 'groupex' => array('field' => 'id', 'table' => 'groupex.asso',
177 'text' => "(a.cat = 'GroupesX' OR a.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' => 'applis_def', 'text' => 'text', 'exact' => false),
181 'city' => array('table' => 'geoloc_city', '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 $_REQUEST['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 = '`user_id`';
251 $db = '`auth_user_md5`';
252 $realid = false;
253 $beginwith = true;
254 $field2 = false;
255 $qsearch = str_replace(array('%', '_'), '', $q);
256
257 switch ($type) {
258 case 'binetTxt':
259 $db = '`binets_def` INNER JOIN
260 `binets_ins` ON(`binets_def`.`id` = `binets_ins`.`binet_id`)';
261 $field='`binets_def`.`text`';
262 if (strlen($q) > 2)
263 $beginwith = false;
264 $realid = '`binets_def`.`id`';
265 break;
266 case 'city':
267 $db = '`geoloc_city` INNER JOIN
268 `adresses` ON(`geoloc_city`.`id` = `adresses`.`cityid`)';
269 $unique='`uid`';
270 $field='`geoloc_city`.`name`';
271 break;
272 case 'countryTxt':
273 $db = '`geoloc_pays` INNER JOIN
274 `adresses` ON(`geoloc_pays`.`a2` = `adresses`.`country`)';
275 $unique='`uid`';
276 $field = '`geoloc_pays`.`pays`';
277 $field2 = '`geoloc_pays`.`country`';
278 $realid='`geoloc_pays`.`a2`';
279 break;
280 case 'entreprise':
281 $db = '`entreprises`';
282 $field = '`entreprise`';
283 $unique='`uid`';
284 break;
285 case 'firstname':
286 $field = '`prenom`';
287 $beginwith = false;
288 break;
289 case 'fonctionTxt':
290 $db = '`fonctions_def` INNER JOIN
291 `entreprises` ON(`entreprises`.`fonction` = `fonctions_def`.`id`)';
292 $field = '`fonction_fr`';
293 $unique = '`uid`';
294 $realid = '`fonctions_def`.`id`';
295 $beginwith = false;
296 break;
297 case 'groupexTxt':
298 $db = "groupex.asso AS a INNER JOIN
299 groupex.membres AS m ON(a.id = m.asso_id
300 AND (a.cat = 'GroupesX' OR a.cat = 'Institutions')
301 AND a.pub = 'public')";
302 $field='a.nom';
303 $field2 = 'a.diminutif';
304 if (strlen($q) > 2)
305 $beginwith = false;
306 $realid = 'a.id';
307 $unique = 'm.uid';
308 break;
309 case 'name':
310 $field = '`nom`';
311 $field2 = '`nom_usage`';
312 $beginwith = false;
313 break;
314 case 'nationaliteTxt':
315 $db = '`geoloc_pays` INNER JOIN
316 `auth_user_md5` ON(`geoloc_pays`.`a2` = `auth_user_md5`.`nationalite`)';
317 $field = 'IF(`geoloc_pays`.`nat`=\'\',
318 `geoloc_pays`.`pays`,
319 `geoloc_pays`.`nat`)';
320 $realid = '`geoloc_pays`.`a2`';
321 break;
322 case 'nickname':
323 $field = '`profile_nick`';
324 $db = '`auth_user_quick`';
325 $beginwith = false;
326 break;
327 case 'poste':
328 $db = '`entreprises`';
329 $field = '`poste`';
330 $unique='`uid`';
331 break;
332 case 'schoolTxt':
333 $db = '`applis_def` INNER JOIN
334 `applis_ins` ON(`applis_def`.`id` = `applis_ins`.`aid`)';
335 $field='`applis_def`.`text`';
336 $unique = '`uid`';
337 $realid = '`applis_def`.`id`';
338 if (strlen($q) > 2)
339 $beginwith = false;
340 break;
341 case 'secteurTxt':
342 $db = '`emploi_secteur` INNER JOIN
343 `entreprises` ON(`entreprises`.`secteur` = `emploi_secteur`.`id`)';
344 $field = '`emploi_secteur`.`label`';
345 $realid = '`emploi_secteur`.`id`';
346 $unique = '`uid`';
347 $beginwith = false;
348 break;
349 case 'sectionTxt':
350 $db = '`sections` INNER JOIN
351 `auth_user_md5` ON(`auth_user_md5`.`section` = `sections`.`id`)';
352 $field = '`sections`.`text`';
353 $realid = '`sections`.`id`';
354 $beginwith = false;
355 break;
356 default: exit();
357 }
358
359 function make_field_test($fields, $beginwith) {
360 $tests = array();
361 $tests[] = $fields . ' LIKE CONCAT({?}, \'%\')';
362 if (!$beginwith) {
363 $tests[] = $fields . ' LIKE CONCAT(\'% \', {?}, \'%\')';
364 $tests[] = $fields . ' LIKE CONCAT(\'%-\', {?}, \'%\')';
365 }
366 return '(' . implode(' OR ', $tests) . ')';
367 }
368 $field_select = $field;
369 $field_t = make_field_test($field, $beginwith);
370 if ($field2) {
371 $field2_t = make_field_test($field2, $beginwith);
372 $field_select = 'IF(' . $field_t . ', ' . $field . ', ' . $field2. ')';
373 }
374 $list = XDB::iterator('SELECT ' . $field_select . ' AS field,
375 COUNT(DISTINCT ' . $unique . ') AS nb
376 ' . ($realid ? (', ' . $realid . ' AS id') : '') . '
377 FROM ' . $db . '
378 WHERE ' . $field_t .
379 ($field2 ? (' OR ' . $field2_t) : '') . '
380 GROUP BY ' . $field_select . '
381 ORDER BY nb DESC
382 LIMIT 11',
383 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch,
384 $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch, $qsearch);
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 $res .= $result['nb'];
394 if (isset($result['id'])) {
395 $res .= '|'.$result['id'];
396 }
397 $res .= "\n";
398 }
399 }
400 XDB::query('REPLACE INTO `search_autocomplete`
401 VALUES ({?}, {?}, {?}, NOW())',
402 $type, $q, $res);
403 echo $res;
404 exit();
405 }
406
407 function handler_list(&$page, $type = null, $idVal = null)
408 {
409 // Give the list of all values possible of type and builds a select input for it
410 $field = '`text`';
411 $id = '`id`';
412 $where = '';
413
414 switch ($type) {
415 case 'binet':
416 $db = '`binets_def`';
417 break;
418 case 'country':
419 $db = '`geoloc_pays`';
420 $field = '`pays`';
421 $id = '`a2`';
422 $page->assign('onchange', 'changeCountry(this.value)');
423 break;
424 case 'fonction':
425 $db = '`fonctions_def`';
426 $field = '`fonction_fr`';
427 break;
428 case 'diploma':
429 header('Content-Type: text/xml; charset="UTF-8"');
430 $this->get_diplomas();
431 $page->changeTpl('search/adv.grade.form.tpl', NO_SKIN);
432 return;
433 case 'groupex':
434 $db = 'groupex.asso';
435 $where = " WHERE (cat = 'GroupesX' OR cat = 'Institutions') AND pub = 'public'";
436 $field = 'nom';
437 break;
438 case 'nationalite':
439 $db = '`geoloc_pays` INNER JOIN
440 `auth_user_md5` ON (`geoloc_pays`.`a2` = `auth_user_md5`.`nationalite`)';
441 $field = 'IF(`nat`=\'\', `pays`, `nat`)';
442 $id = '`a2`';
443 break;
444 case 'region':
445 $db = '`geoloc_region`';
446 $field = '`name`';
447 $id = '`region`';
448 if (isset($_REQUEST['country'])) {
449 $where .= ' WHERE `a2` = "'.$_REQUEST['country'].'"';
450 }
451 break;
452 case 'school':
453 $db = '`applis_def`';
454 $page->assign('onchange', 'changeSchool(this.value)');
455 break;
456 case 'section':
457 $db = '`sections`';
458 break;
459 case 'secteur':
460 $db = '`emploi_secteur`';
461 $field = '`label`';
462 break;
463 default: exit();
464 }
465 if (isset($idVal)) {
466 header('Content-Type: text/plain; charset="UTF-8"');
467 $result = XDB::query('SELECT '.$field.' AS field FROM '.$db.' WHERE '.$id.' = {?} LIMIT 1',$idVal);
468 echo $result->fetchOneCell();
469 exit();
470 }
471 header('Content-Type: text/xml; charset="UTF-8"');
472 $page->changeTpl('include/field.select.tpl', NO_SKIN);
473 $page->assign('name', $type);
474 $page->assign('list', XDB::iterator('SELECT '.$field.' AS field,
475 '.$id.' AS id
476 FROM '.$db.$where.'
477 GROUP BY '.$field.'
478 ORDER BY '.$field));
479 $page->assign('with_text_value', true);
480 $page->assign('onchange', "document.forms.recherche.{$type}Txt.value = this.options[this.selectedIndex].text");
481 }
482 }
483
484 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
485 ?>