2 /***************************************************************************
3 * Copyright (C) 2003-2008 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
22 // {{{ Global variables used for the search Queries
24 @$globals->search
->result_fields
= '
25 u.user_id, u.promo, u.matricule, u.matricule_ax,
26 if(u.nom_usage=\'\', u.nom, u.nom_usage) AS NomSortKey,
28 u.deces!=0 AS dcd,u.deces,
29 u.perms IN (\'admin\',\'user\', \'disabled\') AS inscrit,
30 u.perms != \'pending\' AS wasinscrit,
31 FIND_IN_SET(\'femme\', u.flags) AS sexe,
33 ad0.text AS app0text, ad0.url AS app0url, ai0.type AS app0type,
34 ad1.text AS app1text, ad1.url AS app1url, ai1.type AS app1type,
35 es.label AS secteur, ef.fonction_fr AS fonction,
36 IF(n.nat=\'\',n.pays,n.nat) AS nat, n.a2 AS iso3166,
37 (COUNT(em.email) > 0 OR FIND_IN_SET("googleapps", u.mail_storage) > 0) AS actif,';
38 // hide private information if not logged
40 $globals->search
->result_fields
.='
42 q.profile_mobile AS mobile,
43 q.profile_freetext AS freetext,
44 adr.city, gp.pays AS countrytxt, gr.name AS region,
47 $globals->search
->result_fields
.="
48 IF(q.profile_web_pub='public', q.profile_web, '') AS web,
49 IF(q.profile_mobile_pub='public', q.profile_mobile, '') AS mobile,
50 IF(q.profile_freetext_pub='public', q.profile_freetext, '') AS freetext,
51 IF(adr.pub='public', adr.city, '') AS city,
52 IF(adr.pub='public', gp.pays, '') AS countrytxt,
53 IF(adr.pub='public', gr.name, '') AS region,
54 IF(e.pub='public', e.entreprise, '') AS entreprise,";
55 @$globals->search
->result_where_statement
= '
56 LEFT JOIN applis_ins AS ai0 ON (u.user_id = ai0.uid AND ai0.ordre = 0)
57 LEFT JOIN applis_def AS ad0 ON (ad0.id = ai0.aid)
58 LEFT JOIN applis_ins AS ai1 ON (u.user_id = ai1.uid AND ai1.ordre = 1)
59 LEFT JOIN applis_def AS ad1 ON (ad1.id = ai1.aid)
60 LEFT JOIN entreprises AS e ON (e.entrid = 0 AND e.uid = u.user_id)
61 LEFT JOIN emploi_secteur AS es ON (e.secteur = es.id)
62 LEFT JOIN fonctions_def AS ef ON (e.fonction = ef.id)
63 LEFT JOIN geoloc_pays AS n ON (u.nationalite = n.a2)
64 LEFT JOIN adresses AS adr ON (u.user_id = adr.uid AND FIND_IN_SET(\'active\',adr.statut))
65 LEFT JOIN geoloc_pays AS gp ON (adr.country = gp.a2)
66 LEFT JOIN geoloc_region AS gr ON (adr.country = gr.a2 AND adr.region = gr.region)
67 LEFT JOIN emails AS em ON (em.uid = u.user_id AND em.flags = \'active\')';
70 // {{{ class ThrowError
72 /** handle errors for end-users queries
73 * assign the error message and runs the templates
75 * @author Jean-Sebastien Bedo
79 public static $throwHook = array('ThrowError', 'defaultHandler');
82 * @param $explain string the error (in natural language)
84 public function __construct($explain)
86 call_user_func(ThrowError
::$throwHook, $explain);
89 /** defaut error handler
91 private static function defaultHandler($explain)
94 $page =& Platal
::page();
95 $page->changeTpl('search/index.tpl');
96 $page->setTitle('Polytechnique.org - Annuaire');
97 $page->assign('baseurl', $globals->baseurl
);
98 $page->trigError($explain);
104 // {{{ class SField [Base class]
106 /** classe de base représentant un champ de recherche
107 * (correspond à un champ du formulaire mais peut être à plusieurs champs de la bdd)
108 * interface étendue pour chaque type de champ particulier
114 /** le nom du champ dans le formulaire HTML */
116 /** champs de la bdd correspondant à ce champ sous forme d'un tableau */
118 /** champ résultat dans la requête MySQL correspondant à ce champ
119 * (alias utilisé pour la clause ORDER BY) */
120 var $fieldResultName;
121 /** valeur du champ instanciée par l'utilisateur */
128 * (récupère la requête de l'utilisateur pour ce champ) */
129 function SField($_fieldFormName, $_fieldDbName='', $_fieldResultName='')
131 $this->fieldFormName
= $_fieldFormName;
132 $this->fieldDbName
= $_fieldDbName;
133 $this->fieldResultName
= $_fieldResultName;
134 $this->get_request();
138 // {{{ function get_request()
140 /** récupérer la requête de l'utilisateur
141 * on met une chaîne vide si le champ n'a pas été complété */
142 function get_request()
144 $this->value
= trim(Env
::v($this->fieldFormName
));
148 // {{{ function get_where_statement()
150 /** récupérer la clause correspondant au champ dans la clause WHERE de la requête
151 * on parcourt l'ensemble des champs de la bdd de $fieldDbName et on associe
152 * à chacun d'entre eux une clause spécifique
153 * la clause totale et la disjonction de ces clauses spécifiques */
154 function get_where_statement()
156 if ($this->value
=='') {
159 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_where_statement'), $this->fieldDbName
)));
160 return empty($res) ?
'' : "($res)";
164 // {{{ function get_order_statement()
166 /** récupérer la clause correspondant au champ dans la clause ORDER BY de la requête
167 * utilisé par exemple pour placer d'abord le nom égal à la requête avant les approximations */
168 function get_order_statement()
174 // {{{ function get_select_statement()
176 function get_select_statement()
182 // {{{ function get_url()
184 /** récupérer le bout d'URL correspondant aux paramètres permettant d'imiter une requête d'un
185 * utilisateur assignant la valeur $this->value à ce champ */
188 if (empty($this->value
)) {
191 return $this->fieldFormName
.'='.urlencode($this->value
);
199 // {{{ class QuickSearch [Google Like]
201 class QuickSearch
extends SField
207 /** stores numerical ranges */
209 /** stores admin searches */
216 function QuickSearch($_fieldFormName)
218 $this->fieldFormName
= $_fieldFormName;
219 $this->get_request();
220 if (preg_match(":[\]\[{}~/§_`|%$^=+]|\*\*:u", $this->value
)) {
221 new ThrowError('Un champ contient un caractère interdit rendant la recherche impossible.');
226 // {{{ function isempty()
230 return empty($this->strings
) && empty($this->ranges
) && empty($this->email
) && empty($this->ip
);
234 // {{{ function get_request()
236 function get_request()
238 parent
::get_request();
239 $s = replace_accent(trim($this->value
));
240 $r = $s = str_replace('*','%',$s);
242 if (S
::has_perms() && strpos($s, '@') !== false
) {
244 } else if (S
::has_perms() && preg_match('/[0-9]+\.([0-9]+|%)\.([0-9]+|%)\.([0-9]+|%)/', $s)) {
247 if ($this->email ||
$this->ip
) {
248 $this->strings
= $this->ranges
= array();
252 $s = preg_replace('!\d+!', ' ', $s);
253 $this->strings
= preg_split("![^a-zA-Z%]+!",$s, -1, PREG_SPLIT_NO_EMPTY
);
254 if (count($this->strings
) > 5) {
255 Platal
::page()->trigWarning("Tu as indiqué trop d'éléments dans ta recherche, seuls les 5 premiers seront pris en compte");
256 $this->strings
= array_slice($this->strings
, 0, 5);
259 $s = preg_replace('! *- *!', '-', $r);
260 $s = preg_replace('!([<>]) *!', ' \1', $s);
261 $s = preg_replace('![^0-9\-><]!', ' ', $s);
262 $s = preg_replace('![<>\-] !', '', $s);
263 $ranges = preg_split('! +!', $s, -1, PREG_SPLIT_NO_EMPTY
);
264 $this->ranges
=Array();
265 foreach ($ranges as $r) {
266 if (preg_match('!^([<>]\d{4}|\d{4}(-\d{4})?)$!', $r)) $this->ranges
[] = $r;
271 // {{{ function get_where_statement()
273 function get_where_statement()
276 foreach ($this->strings
as $i => $s) {
277 if (Env
::i('with_soundex') && strlen($s) > 1) {
279 $where[] = "sn$i.soundex = '$t'";
280 } elseif (Env
::i('exact')) {
281 $where[] = "sn$i.token = '$s'";
283 $t = str_replace('*', '%', $s).'%';
284 $t = str_replace('%%', '%', $t);
285 $where[] = "sn$i.token LIKE '$t'";
290 foreach ($this->ranges
as $r) {
291 if (preg_match('!^\d{4}$!', $r)) {
292 $wherep[] = "u.promo=$r";
293 } elseif (preg_match('!^(\d{4})-(\d{4})$!', $r, $matches)) {
294 $p1=min(intval($matches[1]), intval($matches[2]));
295 $p2=max(intval($matches[1]), intval($matches[2]));
296 $wherep[] = "(u.promo>=$p1 AND u.promo<=$p2)";
297 } elseif (preg_match('!^<(\d{4})!', $r, $matches)) {
298 $wherep[] = "u.promo<={$matches[1]}";
299 } elseif (preg_match('!^>(\d{4})!', $r, $matches)) {
300 $wherep[] = "u.promo>={$matches[1]}";
303 if (!empty($wherep)) {
304 $where[] = '('.join(' OR ',$wherep).')';
306 if (!empty($this->email
)) {
307 $where[] = 'ems.email = ' . XDB
::escape($this->email
);
309 if (!empty($this->ip
)) {
310 $ip = ip_to_uint($this->ip
);
311 $where[] = "( ls.ip = $ip OR ls.forward_ip = $ip ) AND ls.suid = 0";
314 return join(" AND ", $where);
318 // {{{ get_select_statement
319 function get_select_statement()
324 foreach ($this->strings
as $i => $s) {
326 $and = "AND FIND_IN_SET('public', sn$i.flags)";
328 $myu = str_replace('snv', "sn$i", $uniq);
329 $join .= "INNER JOIN search_name AS sn$i ON (u.user_id = sn$i.uid $and$myu)\n";
330 $uniq .= " AND sn$i.token != snv.token";
332 if (!empty($this->email
)) {
333 $join .= "LEFT JOIN emails AS ems ON (ems.uid = u.user_id)";
335 if (!empty($this->ip
)) {
336 $join .= "INNER JOIN logger.sessions AS ls ON (ls.uid = u.user_id)\n";
341 // {{{ function get_order_statement()
343 function get_order_statement()
349 // {{{ function get_score_statement
351 function get_score_statement()
354 foreach ($this->strings
as $i => $s) {
355 $sum[] .= "SUM(sn$i.score + IF('$s'=sn$i.token,5,0))";
357 return join('+', $sum).' AS score';
364 // {{{ class NumericSField [Integer fields]
366 /** classe de champ numérique entier (offset par exemple)
368 class NumericSField
extends SField
373 * (récupère la requête de l'utilisateur pour ce champ) */
374 function NumericSField($_fieldFormName)
376 $this->fieldFormName
= $_fieldFormName;
377 $this->get_request();
381 // {{{ function get_request()
383 /** récupère la requête de l'utilisateur et échoue s'il ne s'agit pas d'un entier */
384 function get_request()
386 parent
::get_request();
387 if (empty($this->value
)) {
390 if (!preg_match("/^[0-9]+$/", $this->value
)) {
391 new ThrowError('Un champ numérique contient des caractères alphanumériques.');
399 // {{{ class RefSField [ ??? ]
401 class RefSField
extends SField
413 function RefSField($_fieldFormName, $_fieldDbName='', $_refTable, $_refAlias, $_refCondition, $_exact=true
)
415 $this->fieldFormName
= $_fieldFormName;
416 $this->fieldDbName
= $_fieldDbName;
417 $this->refTable
= $_refTable;
418 $this->refAlias
= $_refAlias;
419 $this->refCondition
= $_refCondition;
420 $this->exact
= $_exact;
421 $this->get_request();
425 // {{{ function get_request()
427 function get_request() {
428 parent
::get_request();
429 if ($this->value
=='00' ||
$this->value
=='0') {
435 // {{{ function too_large()
439 return ($this->value
=='');
443 // {{{ function compare()
447 $val = addslashes($this->value
);
448 if (Env
::i('exact')) return "='$val'";
449 return $this->exact ?
"='$val'" : " LIKE '%$val%'";
453 // {{{ function get_single_match_statement()
455 function get_single_match_statement($field)
457 return $field.$this->compare();
461 // {{{ function get_single_where_statement()
463 function get_single_where_statement($field)
465 return $this->refTable
=='' ?
$this->get_single_match_statement($field) : false
;
469 // {{{ function get_select_statement()
471 function get_select_statement()
473 if ($this->value
=='' ||
$this->refTable
=='') {
476 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_match_statement'), $this->fieldDbName
)));
477 if (is_array($this->refTable
)) {
478 foreach ($this->refTable
as $i => $refT)
481 foreach ($this->refTable
as $i => $refT)
482 $inner .= " INNER JOIN {$refT} AS {$this->refAlias[$i]} ON ({$this->refCondition[$i]} ".(($i == $last)?
"AND ($res) ":"").")\n";
485 return "INNER JOIN {$this->refTable} AS {$this->refAlias} ON ({$this->refCondition} AND ($res) )";
494 // {{{ class RefSFieldMultipleTable
495 class MapSField
extends RefSField
499 function MapSField($_fieldFormName, $_fieldDbName='', $_refTable, $_refAlias, $_refCondition, $_mapId=false
)
501 if ($_mapId === false
)
502 $this->mapId
= Env
::v($_fieldFormName, '');
504 $this->mapId
= $_mapId;
505 $this->value
= $this->mapId
;
506 $this->RefSField($_fieldFormName, $_fieldDbName, $_refTable, $_refAlias, $_refCondition, true
, false
);
509 function get_select_statement()
511 if ($this->mapId
=== '') return false
;
512 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_match_statement'), $this->fieldDbName
)));
513 foreach ($this->refTable
as $i => $refT)
516 foreach ($this->refTable
as $i => $refT)
517 $inner .= " INNER JOIN {$refT} AS {$this->refAlias[$i]} ON ({$this->refCondition[$i]} ".(($i == $last)?
"AND ($res) ":"").")";
520 function get_request()
522 $this->value
= $this->mapId
;
526 // {{{ class RefWithSoundexSField [ ??? ]
528 class RefWithSoundexSField
extends RefSField
530 // {{{ function compare()
534 return "='".soundex_fr($this->value
)."'";
541 // {{{ class StringSField [String fields]
543 /** classe de champ texte (nom par exemple)
545 class StringSField
extends SField
547 // {{{ function get_request()
549 /** récupère la requête de l'utilisateur et échoue si la chaîne contient des caractères
551 function get_request()
553 parent
::get_request();
554 if (preg_match(":[\]\[<>{}~/§_`|%$^=+]|\*\*:u", $this->value
)) {
555 new ThrowError('Un champ contient un caractère interdit rendant la recherche impossible.');
560 // {{{ function length()
562 /** donne la longueur de la requête de l'utilisateur
563 * (au sens strict i.e. pas d'* ni d'espace ou de trait d'union -> les contraintes réellement
564 * imposées par l'utilisateur) */
567 $cleaned = replace_accent(strtolower($this->value
));
568 $length = strlen(ereg_replace('[a-z0-9]', '', $cleaned));
569 return strlen($this->value
) - $length;
573 // {{{ function too_large()
577 return ($this->length()<2);
581 // {{{ function get_single_where_statement()
583 /** clause WHERE correspondant à un champ de la bdd et à ce champ de formulaire
584 * @param field nom de champ de la bdd concerné par la clause */
585 function get_single_where_statement($field)
587 $val = addslashes($this->value
);
588 if (Env
::i('exact')) return "$field = '$val'";
589 $regexp = strtr($val, '-*', '_%');
590 return "$field LIKE '$regexp%'";
594 // {{{ function get_order_statement()
596 /** clause ORDER BY correspondant à ce champ de formulaire */
597 function get_order_statement()
599 if ($this->value
!='' && $this->fieldResultName
!='') {
600 return "{$this->fieldResultName}!='".addslashes($this->value
)."'";
610 // {{{ class NameSField [Names : serach 'n%' + '% b']
612 /** classe pour les noms : on cherche en plus du like 'foo%' le like '% foo' (particules)
614 class NameSField
extends StringSField
616 // {{{ function get_single_where_statement()
618 function get_single_where_statement($field)
620 $val = addslashes($this->value
);
621 if (Env
::i('exact')) return "$field = '$val'";
622 $regexp = strtr($val, '-*', '_%');
623 return "$field LIKE '$regexp%' OR $field LIKE '% $regexp%' OR $field LIKE '%-$regexp%'";
627 // {{{ function get_order_statement()
629 function get_order_statement()
631 if ($this->value
!='' && $this->fieldResultName
!='') {
632 return "{$this->fieldResultName} NOT LIKE '".addslashes($this->value
)."'";
642 // {{{ class StringWithSoundexSField [Strings + soundex]
644 /** classe de champ texte avec soundex (nom par exemple)
646 class StringWithSoundexSField
extends StringSField
648 // {{{ function get_single_where_statement()
650 /** clause WHERE correspondant à un champ de la bdd et à ce champ de formulaire
651 * @param field nom de champ de la bdd concerné par la clause */
652 function get_single_where_statement($field) {
653 return $field.'="'.soundex_fr($this->value
).'"';
660 // {{{ class PromoSField [Prom field]
662 /** classe de champ de promotion */
663 class PromoSField
extends SField
667 /** opérateur de comparaison (<,>,=) de la promo utilisé pour ce champ de formulaire */
674 * compareField est un champ de formulaire très simple qui ne sert qu'à la construction de la
675 * clause WHERE de la promo */
676 function PromoSField($_fieldFormName, $_compareFieldFormName, $_fieldDbName, $_fieldResultName)
678 parent
::SField($_fieldFormName, $_fieldDbName, $_fieldResultName);
679 $this->compareField
= new SField($_compareFieldFormName);
683 // {{{ function get_request()
685 /** récupère la requête utilisateur et échoue si le champ du formulaire ne représente pas une
686 * promotion (nombre à 4 chiffres) */
687 function get_request()
689 parent
::get_request();
690 if (preg_match('/^[0-9]{2}$/', $this->value
)){
691 $this->value
= intval($this->value
) +
1900;
693 if (!(empty($this->value
) or preg_match('/^[0-9]{4}$/', $this->value
))) {
694 new ThrowError('La promotion est une année à quatre chiffres.');
699 // {{{ function is_a_single_promo()
701 /** teste si la requête est de la forme =promotion -> contrainte forte imposée -> elle suffit
702 * pour autoriser un affichage des résultats alors que <promotion est insuffisant */
703 function is_a_single_promo()
705 return ($this->compareField
->value
=='=' && $this->value
!='');
709 // {{{ function too_large()
713 return !$this->is_a_single_promo();
717 // {{{ function get_single_where_statement()
719 /** clause WHERE correspondant à ce champ */
720 function get_single_where_statement($field)
722 return $field.$this->compareField
->value
.$this->value
;
726 // {{{ function get_url()
728 /** récupérer le bout d'URL correspondant aux paramètres permettant d'imiter une requête
729 * d'un utilisateur assignant la valeur $this->value à ce champ et assignant l'opérateur de
730 * comparaison adéquat */
733 if (!($u=parent
::get_url())) {
736 return $u.'&'.$this->compareField
->get_url();
743 // {{{ class SFieldGroup [Group fields]
745 /** classe groupant des champs de formulaire de recherche */
750 /** tableau des classes correspondant aux champs groupés */
752 /** type de groupe : ET ou OU */
759 function SFieldGroup($_and, $_fields)
761 $this->fields
= $_fields;
763 foreach ($this->fields
as $key=>&$field) {
764 if (is_null($field)) {
765 unset($this->fields
[$key]);
771 // {{{ function too_large()
776 for ($i=0 ; $b && $i<count($this->fields
) ; $i++
) {
777 if (!is_null($this->fields
[$i])) {
778 $b = $b && $this->fields
[$i]->too_large();
785 // {{{ function field_get_select()
787 function field_get_select($f)
789 return $f->get_select_statement();
793 // {{{ function field_get_where()
795 /** récupérer la clause WHERE d'un objet champ de recherche */
796 function field_get_where($f)
798 return $f->get_where_statement();
802 // {{{ function field_get_order()
804 /** récupérer la clause ORDER BY d'un objet champ de recherche */
805 function field_get_order($f)
807 return $f->get_order_statement();
811 // {{{ function field_get_url()
813 /** récupérer le bout d'URL correspondant à un objet champ de recherche */
814 function field_get_url($f)
816 return $f->get_url();
820 // {{{ function get_select_statement()
822 function get_select_statement()
824 return implode(' ', array_filter(array_map(array($this, 'field_get_select'), $this->fields
)));
828 // {{{ function get_where_statement()
830 /** récupérer la clause WHERE du groupe de champs = conjonction (ET) ou disjonction (OU) de
831 * clauses des champs élémentaires */
832 function get_where_statement()
834 $joinText = $this->and ?
' AND ' : ' OR ';
835 $res = implode($joinText, array_filter(array_map(array($this, 'field_get_where'), $this->fields
)));
836 return $res == '' ?
'' : "($res)";
840 // {{{ function get_order_statement()
842 /** récupérer la clause ORDER BY du groupe de champs = conjonction (ET) ou disjonction (OU) de
843 * clauses des champs élémentaires */
844 function get_order_statement()
846 $order = array_filter(array_map(array($this, 'field_get_order'), $this->fields
));
847 return count($order)>0 ?
implode(',', $order) : false
;
851 // {{{ function get_url()
853 /** récupérer le bout d'URL correspondant à ce groupe de champs = concaténation des bouts d'URL
854 * des champs élémentaires */
855 function get_url($others=Array())
857 $url = array_filter(array_map(array($this, 'field_get_url'), $this->fields
));
858 foreach ($url as $key=>$val) {
863 foreach ($others as $key=>$val) {
865 $url[] = "$key=$val";
868 return count($url)>0 ?
implode('&', $url) : false
;
876 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: