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