Merge remote branch 'origin/xorg/1.0.2/master' into xorg/master
[platal.git] / modules / search.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 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, 'directory_ax'),
29 'advanced_search.php' => $this->make_hook('redir_advanced', AUTH_PUBLIC),
30 'search/autocomplete' => $this->make_hook('autocomplete', AUTH_COOKIE, 'directory_ax', NO_AUTH),
31 'search/list' => $this->make_hook('list', AUTH_COOKIE, 'directory_ax', NO_AUTH),
32 'jobs' => $this->make_hook('referent', AUTH_COOKIE),
33 'emploi' => $this->make_hook('referent', AUTH_COOKIE),
34 'referent/search' => $this->make_hook('referent', AUTH_COOKIE),
35 'search/referent/countries' => $this->make_hook('referent_countries', AUTH_COOKIE),
36 );
37 }
38
39 function handler_redir_advanced(&$page, $mode = null)
40 {
41 pl_redirect('search/adv');
42 exit;
43 }
44
45 function form_prepare()
46 {
47 Platal::page()->assign('formulaire',1);
48 }
49
50 /**
51 * $model: The way of presenting the results: minifiche, trombi, geoloc.
52 * $byletter: Show only names beginning with this letter
53 */
54 function handler_quick(&$page, $model = null, $byletter = null)
55 {
56 global $globals;
57
58 if (Env::has('quick') || $model == 'geoloc') {
59 $quick = Env::t('quick');
60 if (S::logged() && !Env::has('page')) {
61 S::logger()->log('search', 'quick=' . $quick);
62 }
63
64 if ($quick == '') {
65 $page->trigWarning('Aucun critère de recherche n\'est spécifié.');
66 $page->changeTpl('search/index.tpl');
67 $page->setTitle('Annuaire');
68 $page->assign('formulaire', 1);
69 return;
70 }
71
72 $list = 'profile|prf|fiche|fic|referent|ref|mentor';
73 if (S::admin()) {
74 $list .= '|admin|adm|ax';
75 }
76 $suffixes = array_keys(DirEnum::getOptions(DirEnum::ACCOUNTTYPES));
77 $suffixes = implode('|', $suffixes);
78 if (preg_match('/^(' . $list . '):([-a-z]+(\.[-a-z]+(\.(?:[md]?\d{2,4}|' . $suffixes . '))?)?)$/', replace_accent($quick), $matches)) {
79 $login = $matches[2];
80 switch($matches[1]) {
81 case 'admin': case 'adm':
82 $base = 'admin/user/';
83 break;
84 case 'ax':
85 $base = 'profile/ax/';
86 break;
87 case 'profile': case 'prf': case 'fiche': case 'fic':
88 $base = 'profile/';
89 break;
90 case 'referent': case 'ref': case 'mentor':
91 $base = 'referent/';
92 break;
93 }
94
95 $user = User::getSilent($login);
96 if ($user) {
97 pl_redirect($base . $user->login());
98 }
99 $_REQUEST['quick'] = $login;
100 $_GET['quick'] = $login;
101 } elseif (strpos($quick, 'doc:') === 0) {
102 $url = 'Docs/Recherche?';
103 $url .= 'action=search&q=' . urlencode(substr($quick, 4));
104 $url .= '&group=' . urlencode('-Equipe,-Main,-PmWiki,-Site,-Review');
105 pl_redirect($url);
106 } elseif (strpos($quick, 'trombi:') === 0) {
107 $promo = substr($quick, 7);
108 $res = XDB::query("SELECT diminutif
109 FROM groups
110 WHERE cat = 'Promotions' AND diminutif = {?}",
111 $promo);
112 if ($res->numRows() == 0) {
113 $page->trigWarning("La promotion demandée n'est pas valide: $promo");
114 } else {
115 http_redirect('http://www.polytechnique.net/login/' . $promo . '/annuaire/trombi');
116 }
117 }
118
119 $page->assign('formulaire', 0);
120
121 require_once 'userset.inc.php';
122 $view = new SearchSet(true);
123 $view->addMod('minifiche', 'Mini-fiches', true, array('with_score' => true, 'starts_with' => $byletter));
124 if (S::logged() && !Env::i('nonins')) {
125 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true, 'with_score' => true));
126 // TODO: Reactivate when the new map is completed.
127 // $view->addMod('geoloc', 'Planisphère', false, array('with_annu' => 'search/adv'));
128 }
129 $view->apply('search', $page, $model);
130
131 $nb_tot = $view->count();
132 $page->assign('search_results_nb', $nb_tot);
133 if (!S::logged() && $nb_tot > $globals->search->public_max) {
134 $page->trigError('Votre recherche a généré trop de résultats pour un affichage public.');
135 } elseif ($nb_tot > $globals->search->private_max) {
136 $page->trigError('Recherche trop générale. Une <a href="search/adv">recherche avancée</a> permet de préciser la recherche.');
137 } elseif (empty($nb_tot)) {
138 $page->trigError('Il n\'existe personne correspondant à ces critères dans la base !');
139 }
140 } else {
141 $page->assign('formulaire',1);
142 }
143
144 $page->changeTpl('search/index.tpl');
145 $page->setTitle('Annuaire');
146 }
147
148 /** $model is the way of presenting the results: minifiche, trombi, geoloc.
149 */
150 function handler_advanced(&$page, $model = null, $byletter = null)
151 {
152 global $globals;
153 $page->assign('advanced',1);
154 $page->addJsLink('jquery.autocomplete.js');
155
156 $networks = DirEnum::getOptions(DirEnum::NETWORKS);
157 $networks[-1] = 'Tous types';
158 $networks[0] = '-';
159 ksort($networks);
160 $page->assign('networking_types', $networks);
161
162 if (!Env::has('rechercher') && $model != 'geoloc') {
163 $this->form_prepare();
164 } else {
165 if (!Env::has('page')) {
166 S::logger()->log('search', 'adv=' . var_export($_GET, true));
167 }
168
169 require_once 'userset.inc.php';
170 $view = new SearchSet(false);
171 if (!$view->isValid()) {
172 $this->form_prepare();
173 $page->trigError('Recherche invalide.');
174 } else {
175 $view->addMod('minifiche', 'Mini-fiches', true, array('starts_with' => $byletter));
176 $view->addMod('trombi', 'Trombinoscope', false, array('with_promo' => true));
177 // TODO: Reactivate when the new map is completed.
178 // $view->addMod('geoloc', 'Planisphère', false, array('with_annu' => 'search/adv'));
179 $view->apply('search/adv', $page, $model);
180
181 $nb_tot = $view->count();
182 if ($nb_tot > $globals->search->private_max) {
183 $this->form_prepare();
184 $page->trigError('Recherche trop générale.');
185 } else if ($nb_tot == 0) {
186 $this->form_prepare();
187 $page->trigError('Il n\'existe personne correspondant à ces critères dans la base !');
188 }
189 }
190 }
191
192 $page->changeTpl('search/index.tpl', $model == 'mini' ? SIMPLE : SKINNED);
193 $page->assign('public_directory',0);
194 }
195
196 function handler_autocomplete(&$page, $type = null)
197 {
198 // Autocompletion : according to type required, return
199 // a list of results matching with the number of matches.
200 // The output format is :
201 // result1|nb1
202 // result2|nb2
203 // ...
204 pl_content_headers("text/plain");
205 $q = preg_replace(array('/\*+$/', // always look for $q*
206 '/([\^\$\[\]])/', // escape special regexp char
207 '/\*/'), // replace joker by regexp joker
208 array('',
209 '\\\\\1',
210 '.*'),
211 Env::s('q'));
212 if (!$q) exit();
213
214 // try to look in cached results
215 $cache = XDB::query('SELECT result
216 FROM search_autocomplete
217 WHERE name = {?} AND
218 query = {?} AND
219 generated > NOW() - INTERVAL 1 DAY',
220 $type, $q);
221 if ($res = $cache->fetchOneCell()) {
222 echo $res;
223 die();
224 }
225
226 $enums = array(
227 'binetTxt' => DirEnum::BINETS,
228 'groupexTxt' => DirEnum::GROUPESX,
229 'sectionTxt' => DirEnum::SECTIONS,
230 'networking_typeTxt' => DirEnum::NETWORKS,
231 'city' => DirEnum::LOCALITIES,
232 'countryTxt' => DirEnum::COUNTRIES,
233 'entreprise' => DirEnum::COMPANIES,
234 'jobtermTxt' => DirEnum::JOBTERMS,
235 'description' => DirEnum::JOBDESCRIPTION,
236 'nationaliteTxt' => DirEnum::NATIONALITIES,
237 'schoolTxt' => DirEnum::EDUSCHOOLS,
238 );
239 if (!array_key_exists($type, $enums)) {
240 exit();
241 }
242
243 $enum = $enums[$type];
244
245 $list = DirEnum::getAutoComplete($enum, $q);
246 $nbResults = 0;
247 $res = "";
248 while ($result = $list->next()) {
249 $nbResults++;
250 if ($nbResults == 11) {
251 $res .= $q."|-1\n";
252 } else {
253 $res .= $result['field'].'|';
254 if (isset($result['nb'])) {
255 $res .= $result['nb'];
256 }
257 if (isset($result['id'])) {
258 $res .= '|'.$result['id'];
259 }
260 $res .= "\n";
261 }
262 }
263 if ($nbResults == 0) {
264 $res = $q."|-2\n";
265 }
266 XDB::query('INSERT INTO search_autocomplete (name, query, result, generated)
267 VALUES ({?}, {?}, {?}, NOW())
268 ON DUPLICATE KEY UPDATE result = VALUES(result), generated = VALUES(generated)',
269 $type, $q, $res);
270 echo $res;
271 exit();
272 }
273
274 function handler_list(&$page, $type = null, $idVal = null)
275 {
276 $page->assign('name', $type);
277 $page->assign('with_text_value', true);
278 $page->assign('onchange', "document.forms.recherche.{$type}Txt.value = this.options[this.selectedIndex].text");
279
280 // Give the list of all values possible of type and builds a select input for it
281 $ids = null;
282
283 switch ($type) {
284 case 'binet':
285 $ids = DirEnum::getOptionsIter(DirEnum::BINETS);
286 break;
287 case 'networking_type':
288 $ids = DirEnum::getOptionsIter(DirEnum::NETWORKS);
289 break;
290 case 'country':
291 $ids = DirEnum::getOptionsIter(DirEnum::COUNTRIES);
292 $page->assign('onchange', 'changeCountry(this.value)');
293 break;
294 case 'diploma':
295 if (Env::has('school') && Env::i('school') != 0) {
296 $ids = DirEnum::getOptionsIter(DirEnum::EDUDEGREES, Env::i('school'));
297 } else {
298 $ids = DirEnum::getOptionsIter(DirEnum::EDUDEGREES);
299 }
300 break;
301 case 'groupex':
302 $ids = DirEnum::getOptionsIter(DirEnum::GROUPESX);
303 break;
304 case 'nationalite':
305 $ids = DirEnum::getOptionsIter(DirEnum::NATIONALITIES);
306 break;
307 case 'region':
308 if (Env::has('country')) {
309 $ids = DirEnum::getOptionsIter(DirEnum::ADMINAREAS, Env::v('country'));
310 } else {
311 $ids = DirEnum::getOptionsIter(DirEnum::ADMINAREAS);
312 }
313 break;
314 case 'school':
315 $ids = DirEnum::getOptionsIter(DirEnum::EDUSCHOOLS);
316 $page->assign('onchange', 'changeSchool(this.value)');
317 break;
318 case 'section':
319 $ids = DirEnum::getOptionsIter(DirEnum::SECTIONS);
320 break;
321 case 'jobterm':
322 if (Env::has('jtid')) {
323 JobTerms::ajaxGetBranch(&$page, JobTerms::ONLY_JOBS);
324 return;
325 } else {
326 pl_content_headers('text/xml');
327 echo '<div>'; // global container so that response is valid xml
328 echo '<input name="jobtermTxt" type="text" style="display:none" size="32" />';
329 echo '<input name="jobterm" type="hidden"/>';
330 echo '<div class="term_tree"></div>'; // container where to create the tree
331 echo '<script type="text/javascript" src="javascript/jquery.jstree.js"></script>';
332 echo '<script type="text/javascript" src="javascript/jobtermstree.js"></script>';
333 echo '<script type="text/javascript">createJobTermsTree(".term_tree", "search/list/jobterm", "search", "searchForJobTerm");</script>';
334 echo '</div>';
335 exit();
336 }
337 default: exit();
338 }
339 if (isset($idVal)) {
340 pl_content_headers("text/plain");
341 echo $ids[$idVal];
342 exit();
343 }
344 pl_content_headers("text/xml");
345 $page->changeTpl('include/field.select.tpl', NO_SKIN);
346 $page->assign('list', $ids);
347 }
348
349 function handler_referent(&$page, $action = null, $subaction = null)
350 {
351 global $globals;
352
353 $wp = new PlWikiPage('Docs.Emploi');
354 $wp->buildCache();
355
356 $page->setTitle('Emploi et Carrières');
357
358 // Count mentors
359 $res = XDB::query("SELECT count(distinct pid) FROM profile_mentor_term");
360 $page->assign('mentors_number', $res->fetchOneCell());
361
362 $page->addJsLink('jquery.autocomplete.js');
363
364 // Search for mentors matching filters
365 require_once 'ufbuilder.inc.php';
366 $ufb = new UFB_MentorSearch();
367 if (!$ufb->isEmpty()) {
368 require_once 'userset.inc.php';
369 $ufc = $ufb->getUFC();
370 $set = new ProfileSet($ufc);
371 $set->addMod('mentor', 'Référents');
372 $set->apply('referent/search', $page, $action, $subaction);
373 $nb_tot = $set->count();
374 if ($nb_tot > $globals->search->private_max) {
375 $this->form_prepare();
376 $page->trigError('Recherche trop générale.');
377 $page->assign('plset_count', 0);
378 } else if ($nb_tot == 0) {
379 $this->form_prepare();
380 $page->trigError('Il n\'existe personne correspondant à ces critères dans la base.');
381 }
382 }
383
384 $page->changeTpl('search/referent.tpl');
385 }
386
387 /**
388 * Builds a select field to choose among countries that referents
389 * know about. Only referents linked to term (jtid) are displayed.
390 * @param $jtid id of job term to restrict referents
391 */
392 function handler_referent_countries(&$page, $jtid = null)
393 {
394 pl_content_headers("text/xml");
395 $page->changeTpl('include/field.select.tpl', NO_SKIN);
396 $page->assign('name', 'country');
397 $it = XDB::iterator("SELECT gc.iso_3166_1_a2 AS id, gc.countryFR AS field
398 FROM geoloc_countries AS gc
399 INNER JOIN profile_mentor_country AS mp ON (mp.country = gc.iso_3166_1_a2)
400 INNER JOIN profile_mentor_term AS mt ON (mt.pid = mp.pid)
401 INNER JOIN profile_job_term_relation AS jtr ON (jtr.jtid_2 = mt.jtid)
402 WHERE jtr.jtid_1 = {?}
403 GROUP BY iso_3166_1_a2
404 ORDER BY countryFR", $jtid);
405 $page->assign('list', $it);
406 }
407 }
408
409 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
410 ?>