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