2 /***************************************************************************
3 * Copyright (C) 2003-2007 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 require_once("xorg.misc.inc.php");
24 // {{{ Global variables used for the search Queries
26 @$globals->search
->result_fields
= '
27 u.user_id, u.promo, u.matricule, u.matricule_ax,
28 if(u.nom_usage=\'\', u.nom, u.nom_usage) AS NomSortKey,
30 u.deces!=0 AS dcd,u.deces,
31 u.perms IN (\'admin\',\'user\', \'disabled\') AS inscrit,
32 u.perms != \'pending\' AS wasinscrit,
33 FIND_IN_SET(\'femme\', u.flags) AS sexe,
35 ad0.text AS app0text, ad0.url AS app0url, ai0.type AS app0type,
36 ad1.text AS app1text, ad1.url AS app1url, ai1.type AS app1type,
37 es.label AS secteur, ef.fonction_fr AS fonction,
38 IF(n.nat=\'\',n.pays,n.nat) AS nat, n.a2 AS iso3166,
39 COUNT(em.email) > 0 AS actif,';
40 // hide private information if not logged
42 $globals->search
->result_fields
.='
44 q.profile_mobile AS mobile,
45 q.profile_freetext AS freetext,
46 adr.city, gp.pays AS countrytxt, gr.name AS region,
49 $globals->search
->result_fields
.="
50 IF(q.profile_web_pub='public', q.profile_web, '') AS web,
51 IF(q.profile_mobile_pub='public', q.profile_mobile, '') AS mobile,
52 IF(q.profile_freetext_pub='public', q.profile_freetext, '') AS freetext,
53 IF(adr.pub='public', adr.city, '') AS city,
54 IF(adr.pub='public', gp.pays, '') AS countrytxt,
55 IF(adr.pub='public', gr.name, '') AS region,
56 IF(e.pub='public', e.entreprise, '') AS entreprise,";
57 @$globals->search
->result_where_statement
= '
58 LEFT JOIN applis_ins AS ai0 ON (u.user_id = ai0.uid AND ai0.ordre = 0)
59 LEFT JOIN applis_def AS ad0 ON (ad0.id = ai0.aid)
60 LEFT JOIN applis_ins AS ai1 ON (u.user_id = ai1.uid AND ai1.ordre = 1)
61 LEFT JOIN applis_def AS ad1 ON (ad1.id = ai1.aid)
62 LEFT JOIN entreprises AS e ON (e.entrid = 0 AND e.uid = u.user_id)
63 LEFT JOIN emploi_secteur AS es ON (e.secteur = es.id)
64 LEFT JOIN fonctions_def AS ef ON (e.fonction = ef.id)
65 LEFT JOIN geoloc_pays AS n ON (u.nationalite = n.a2)
66 LEFT JOIN adresses AS adr ON (u.user_id = adr.uid AND FIND_IN_SET(\'active\',adr.statut))
67 LEFT JOIN geoloc_pays AS gp ON (adr.country = gp.a2)
68 LEFT JOIN geoloc_region AS gr ON (adr.country = gr.a2 AND adr.region = gr.region)
69 LEFT JOIN emails AS em ON (em.uid = u.user_id AND em.flags = \'active\')';
72 // {{{ class ThrowError
74 /** handle errors for end-users queries
75 * assign the error message and runs the templates
77 * @author Jean-Sebastien Bedo
81 public static $throwHook = array('ThrowError', 'defaultHandler');
84 * @param $explain string the error (in natural language)
86 public function __construct($explain)
88 call_user_func(ThrowError
::$throwHook, $explain);
91 /** defaut error handler
93 private static function defaultHandler($explain)
95 global $page, $globals;
96 $page->changeTpl('search/index.tpl');
97 $page->assign('xorg_title','Polytechnique.org - Annuaire');
98 $page->assign('baseurl', $globals->baseurl
);
99 $page->trig('Erreur : '.$explain);
105 // {{{ class SField [Base class]
107 /** classe de base représentant un champ de recherche
108 * (correspond à un champ du formulaire mais peut être à plusieurs champs de la bdd)
109 * interface étendue pour chaque type de champ particulier
115 /** le nom du champ dans le formulaire HTML */
117 /** champs de la bdd correspondant à ce champ sous forme d'un tableau */
119 /** champ résultat dans la requête MySQL correspondant à ce champ
120 * (alias utilisé pour la clause ORDER BY) */
121 var $fieldResultName;
122 /** valeur du champ instanciée par l'utilisateur */
129 * (récupère la requête de l'utilisateur pour ce champ) */
130 function SField($_fieldFormName, $_fieldDbName='', $_fieldResultName='')
132 $this->fieldFormName
= $_fieldFormName;
133 $this->fieldDbName
= $_fieldDbName;
134 $this->fieldResultName
= $_fieldResultName;
135 $this->get_request();
139 // {{{ function get_request()
141 /** récupérer la requête de l'utilisateur
142 * on met une chaîne vide si le champ n'a pas été complété */
143 function get_request()
145 $this->value
= trim(Env
::v($this->fieldFormName
));
149 // {{{ function get_where_statement()
151 /** récupérer la clause correspondant au champ dans la clause WHERE de la requête
152 * on parcourt l'ensemble des champs de la bdd de $fieldDbName et on associe
153 * à chacun d'entre eux une clause spécifique
154 * la clause totale et la disjonction de ces clauses spécifiques */
155 function get_where_statement()
157 if ($this->value
=='') {
160 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_where_statement'), $this->fieldDbName
)));
161 return empty($res) ?
'' : "($res)";
165 // {{{ function get_order_statement()
167 /** récupérer la clause correspondant au champ dans la clause ORDER BY de la requête
168 * utilisé par exemple pour placer d'abord le nom égal à la requête avant les approximations */
169 function get_order_statement()
175 // {{{ function get_select_statement()
177 function get_select_statement()
183 // {{{ function get_url()
185 /** récupérer le bout d'URL correspondant aux paramètres permettant d'imiter une requête d'un
186 * utilisateur assignant la valeur $this->value à ce champ */
189 if (empty($this->value
)) {
192 return $this->fieldFormName
.'='.urlencode($this->value
);
200 // {{{ class QuickSearch [Google Like]
202 class QuickSearch
extends SField
208 /** stores numerical ranges */
210 /** stores admin searches */
217 function QuickSearch($_fieldFormName)
219 $this->fieldFormName
= $_fieldFormName;
220 $this->get_request();
221 if (preg_match(":[\]\[{}~/§_`|%$^=+]|\*\*:u", $this->value
)) {
222 new ThrowError('Un champ contient un caractère interdit rendant la recherche impossible.');
227 // {{{ function isempty()
231 return empty($this->strings
) && empty($this->ranges
) && empty($this->email
) && empty($this->ip
);
235 // {{{ function get_request()
237 function get_request()
239 parent
::get_request();
240 $s = replace_accent(trim($this->value
));
241 $r = $s = str_replace('*','%',$s);
243 if (S
::has_perms() && strpos($s, '@') !== false
) {
245 } else if (S
::has_perms() && preg_match('/[0-9]+\.([0-9]+|%)\.([0-9]+|%)\.([0-9]+|%)/', $s)) {
248 if ($this->email ||
$this->ip
) {
249 $this->strings
= $this->ranges
= array();
253 $s = preg_replace('!\d+!', ' ', $s);
254 $this->strings
= preg_split("![^a-zA-Z%]+!",$s, -1, PREG_SPLIT_NO_EMPTY
);
256 $s = preg_replace('! *- *!', '-', $r);
257 $s = preg_replace('!([<>]) *!', ' \1', $s);
258 $s = preg_replace('![^0-9\-><]!', ' ', $s);
259 $s = preg_replace('![<>\-] !', '', $s);
260 $ranges = preg_split('! +!', $s, -1, PREG_SPLIT_NO_EMPTY
);
261 $this->ranges
=Array();
262 foreach ($ranges as $r) {
263 if (preg_match('!^([<>]\d{4}|\d{4}(-\d{4})?)$!', $r)) $this->ranges
[] = $r;
268 // {{{ function get_where_statement()
270 function get_where_statement()
273 foreach ($this->strings
as $i => $s) {
274 if (Env
::i('with_soundex') && strlen($s) > 1) {
276 $where[] = "sn$i.soundex = '$t'";
278 $t = str_replace('*', '%', $s).'%';
279 $t = str_replace('%%', '%', $t);
280 $where[] = "sn$i.token LIKE '$t'";
285 foreach ($this->ranges
as $r) {
286 if (preg_match('!^\d{4}$!', $r)) {
287 $wherep[] = "u.promo=$r";
288 } elseif (preg_match('!^(\d{4})-(\d{4})$!', $r, $matches)) {
289 $p1=min(intval($matches[1]), intval($matches[2]));
290 $p2=max(intval($matches[1]), intval($matches[2]));
291 $wherep[] = "(u.promo>=$p1 AND u.promo<=$p2)";
292 } elseif (preg_match('!^<(\d{4})!', $r, $matches)) {
293 $wherep[] = "u.promo<={$matches[1]}";
294 } elseif (preg_match('!^>(\d{4})!', $r, $matches)) {
295 $wherep[] = "u.promo>={$matches[1]}";
298 if (!empty($wherep)) {
299 $where[] = '('.join(' OR ',$wherep).')';
301 if (!empty($this->email
)) {
302 $where[] = 'ems.email = ' . XDB
::escape($this->email
);
304 if (!empty($this->ip
)) {
305 $ip = XDB
::escape($this->ip
);
306 $where[] = "( ls.ip = $ip OR ls.forward_ip = $ip )";
309 return join(" AND ", $where);
313 // {{{ get_select_statement
314 function get_select_statement()
319 foreach ($this->strings
as $i => $s) {
321 $and = "AND FIND_IN_SET('public', sn$i.flags)";
323 $myu = str_replace('snv', "sn$i", $uniq);
324 $join .= "INNER JOIN search_name AS sn$i ON (u.user_id = sn$i.uid $and$myu)\n";
325 $uniq .= " AND sn$i.token != snv.token";
327 if (!empty($this->email
)) {
328 $join .= "LEFT JOIN emails AS ems ON (ems.uid = u.user_id)";
330 if (!empty($this->ip
)) {
331 $join .= "INNER JOIN logger.sessions AS ls ON (ls.uid = u.user_id)\n";
336 // {{{ function get_order_statement()
338 function get_order_statement()
344 // {{{ function get_score_statement
346 function get_score_statement()
349 foreach ($this->strings
as $i => $s) {
350 $sum[] .= "SUM(sn$i.score + IF('$s'=sn$i.token,5,0))";
352 return join('+', $sum).' AS score';
359 // {{{ class NumericSField [Integer fields]
361 /** classe de champ numérique entier (offset par exemple)
363 class NumericSField
extends SField
368 * (récupère la requête de l'utilisateur pour ce champ) */
369 function NumericSField($_fieldFormName)
371 $this->fieldFormName
= $_fieldFormName;
372 $this->get_request();
376 // {{{ function get_request()
378 /** récupère la requête de l'utilisateur et échoue s'il ne s'agit pas d'un entier */
379 function get_request()
381 parent
::get_request();
382 if (empty($this->value
)) {
385 if (!preg_match("/^[0-9]+$/", $this->value
)) {
386 new ThrowError('Un champ numérique contient des caractères alphanumériques.');
394 // {{{ class RefSField [ ??? ]
396 class RefSField
extends SField
408 function RefSField($_fieldFormName, $_fieldDbName='', $_refTable, $_refAlias, $_refCondition, $_exact=true
)
410 $this->fieldFormName
= $_fieldFormName;
411 $this->fieldDbName
= $_fieldDbName;
412 $this->refTable
= $_refTable;
413 $this->refAlias
= $_refAlias;
414 $this->refCondition
= $_refCondition;
415 $this->exact
= $_exact;
416 $this->get_request();
420 // {{{ function get_request()
422 function get_request() {
423 parent
::get_request();
424 if ($this->value
=='00' ||
$this->value
=='0') {
430 // {{{ function too_large()
434 return ($this->value
=='');
438 // {{{ function compare()
442 $val = addslashes($this->value
);
443 return $this->exact ?
"='$val'" : " LIKE '%$val%'";
447 // {{{ function get_single_match_statement()
449 function get_single_match_statement($field)
451 return $field.$this->compare();
455 // {{{ function get_single_where_statement()
457 function get_single_where_statement($field)
459 return $this->refTable
=='' ?
$this->get_single_match_statement($field) : false
;
463 // {{{ function get_select_statement()
465 function get_select_statement()
467 if ($this->value
=='' ||
$this->refTable
=='') {
470 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_match_statement'), $this->fieldDbName
)));
471 return "INNER JOIN {$this->refTable} AS {$this->refAlias} ON ({$this->refCondition} AND ($res) )";
479 // {{{ class RefSFieldMultipleTable
480 class MapSField
extends RefSField
484 function MapSField($_fieldFormName, $_fieldDbName='', $_refTable, $_refAlias, $_refCondition, $_mapId=false
)
486 if ($_mapId === false
)
487 $this->mapId
= Env
::v($_fieldFormName, '');
489 $this->mapId
= $_mapId;
490 $this->value
= $this->mapId
;
491 $this->RefSField($_fieldFormName, $_fieldDbName, $_refTable, $_refAlias, $_refCondition, true
, false
);
494 function get_select_statement()
496 if ($this->mapId
=== '') return false
;
497 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_match_statement'), $this->fieldDbName
)));
498 foreach ($this->refTable
as $i => $refT)
501 foreach ($this->refTable
as $i => $refT)
502 $inner .= " INNER JOIN {$refT} AS {$this->refAlias[$i]} ON ({$this->refCondition[$i]} ".(($i == $last)?
"AND ($res) ":"").")";
505 function get_request()
507 $this->value
= $this->mapId
;
511 // {{{ class RefWithSoundexSField [ ??? ]
513 class RefWithSoundexSField
extends RefSField
515 // {{{ function compare()
519 return "='".soundex_fr($this->value
)."'";
526 // {{{ class StringSField [String fields]
528 /** classe de champ texte (nom par exemple)
530 class StringSField
extends SField
532 // {{{ function get_request()
534 /** récupère la requête de l'utilisateur et échoue si la chaîne contient des caractères
536 function get_request()
538 parent
::get_request();
539 if (preg_match(":[\]\[<>{}~/§_`|%$^=+]|\*\*:u", $this->value
)) {
540 new ThrowError('Un champ contient un caractère interdit rendant la recherche impossible.');
545 // {{{ function length()
547 /** donne la longueur de la requête de l'utilisateur
548 * (au sens strict i.e. pas d'* ni d'espace ou de trait d'union -> les contraintes réellement
549 * imposées par l'utilisateur) */
552 $cleaned = replace_accent(strtolower($this->value
));
553 $length = strlen(ereg_replace('[a-z0-9]', '', $cleaned));
554 return strlen($this->value
) - $length;
558 // {{{ function too_large()
562 return ($this->length()<2);
566 // {{{ function get_single_where_statement()
568 /** clause WHERE correspondant à un champ de la bdd et à ce champ de formulaire
569 * @param field nom de champ de la bdd concerné par la clause */
570 function get_single_where_statement($field)
572 $regexp = strtr(addslashes($this->value
), '-*', '_%');
573 return "$field LIKE '$regexp%'";
577 // {{{ function get_order_statement()
579 /** clause ORDER BY correspondant à ce champ de formulaire */
580 function get_order_statement()
582 if ($this->value
!='' && $this->fieldResultName
!='') {
583 return "{$this->fieldResultName}!='".addslashes($this->value
)."'";
593 // {{{ class NameSField [Names : serach 'n%' + '% b']
595 /** classe pour les noms : on cherche en plus du like 'foo%' le like '% foo' (particules)
597 class NameSField
extends StringSField
599 // {{{ function get_single_where_statement()
601 function get_single_where_statement($field)
603 $regexp = strtr(addslashes($this->value
), '-*', '_%');
604 return "$field LIKE '$regexp%' OR $field LIKE '% $regexp%' OR $field LIKE '%-$regexp%'";
608 // {{{ function get_order_statement()
610 function get_order_statement()
612 if ($this->value
!='' && $this->fieldResultName
!='') {
613 return "{$this->fieldResultName} NOT LIKE '".addslashes($this->value
)."'";
623 // {{{ class StringWithSoundexSField [Strings + soundex]
625 /** classe de champ texte avec soundex (nom par exemple)
627 class StringWithSoundexSField
extends StringSField
629 // {{{ function get_single_where_statement()
631 /** clause WHERE correspondant à un champ de la bdd et à ce champ de formulaire
632 * @param field nom de champ de la bdd concerné par la clause */
633 function get_single_where_statement($field) {
634 return $field.'="'.soundex_fr($this->value
).'"';
641 // {{{ class PromoSField [Prom field]
643 /** classe de champ de promotion */
644 class PromoSField
extends SField
648 /** opérateur de comparaison (<,>,=) de la promo utilisé pour ce champ de formulaire */
655 * compareField est un champ de formulaire très simple qui ne sert qu'à la construction de la
656 * clause WHERE de la promo */
657 function PromoSField($_fieldFormName, $_compareFieldFormName, $_fieldDbName, $_fieldResultName)
659 parent
::SField($_fieldFormName, $_fieldDbName, $_fieldResultName);
660 $this->compareField
= new SField($_compareFieldFormName);
664 // {{{ function get_request()
666 /** récupère la requête utilisateur et échoue si le champ du formulaire ne représente pas une
667 * promotion (nombre à 4 chiffres) */
668 function get_request()
670 parent
::get_request();
671 if (preg_match('/^[0-9]{2}$/', $this->value
)){
672 $this->value
= intval($this->value
) +
1900;
674 if (!(empty($this->value
) or preg_match('/^[0-9]{4}$/', $this->value
))) {
675 new ThrowError('La promotion est une année à quatre chiffres.');
680 // {{{ function is_a_single_promo()
682 /** teste si la requête est de la forme =promotion -> contrainte forte imposée -> elle suffit
683 * pour autoriser un affichage des résultats alors que <promotion est insuffisant */
684 function is_a_single_promo()
686 return ($this->compareField
->value
=='=' && $this->value
!='');
690 // {{{ function too_large()
694 return !$this->is_a_single_promo();
698 // {{{ function get_single_where_statement()
700 /** clause WHERE correspondant à ce champ */
701 function get_single_where_statement($field)
703 return $field.$this->compareField
->value
.$this->value
;
707 // {{{ function get_url()
709 /** récupérer le bout d'URL correspondant aux paramètres permettant d'imiter une requête
710 * d'un utilisateur assignant la valeur $this->value à ce champ et assignant l'opérateur de
711 * comparaison adéquat */
714 if (!($u=parent
::get_url())) {
717 return $u.'&'.$this->compareField
->get_url();
724 // {{{ class SFieldGroup [Group fields]
726 /** classe groupant des champs de formulaire de recherche */
731 /** tableau des classes correspondant aux champs groupés */
733 /** type de groupe : ET ou OU */
740 function SFieldGroup($_and, $_fields)
742 $this->fields
= $_fields;
747 // {{{ function too_large()
752 for ($i=0 ; $b && $i<count($this->fields
) ; $i++
) {
753 $b = $b && $this->fields
[$i]->too_large();
759 // {{{ function field_get_select()
761 function field_get_select($f)
763 return $f->get_select_statement();
767 // {{{ function field_get_where()
769 /** récupérer la clause WHERE d'un objet champ de recherche */
770 function field_get_where($f)
772 return $f->get_where_statement();
776 // {{{ function field_get_order()
778 /** récupérer la clause ORDER BY d'un objet champ de recherche */
779 function field_get_order($f)
781 return $f->get_order_statement();
785 // {{{ function field_get_url()
787 /** récupérer le bout d'URL correspondant à un objet champ de recherche */
788 function field_get_url($f)
790 return $f->get_url();
794 // {{{ function get_select_statement()
796 function get_select_statement()
798 return implode(' ', array_filter(array_map(array($this, 'field_get_select'), $this->fields
)));
802 // {{{ function get_where_statement()
804 /** récupérer la clause WHERE du groupe de champs = conjonction (ET) ou disjonction (OU) de
805 * clauses des champs élémentaires */
806 function get_where_statement()
808 $joinText = $this->and ?
' AND ' : ' OR ';
809 $res = implode($joinText, array_filter(array_map(array($this, 'field_get_where'), $this->fields
)));
810 return $res == '' ?
'' : "($res)";
814 // {{{ function get_order_statement()
816 /** récupérer la clause ORDER BY du groupe de champs = conjonction (ET) ou disjonction (OU) de
817 * clauses des champs élémentaires */
818 function get_order_statement()
820 $order = array_filter(array_map(array($this, 'field_get_order'), $this->fields
));
821 return count($order)>0 ?
implode(',', $order) : false
;
825 // {{{ function get_url()
827 /** récupérer le bout d'URL correspondant à ce groupe de champs = concaténation des bouts d'URL
828 * des champs élémentaires */
829 function get_url($others=Array())
831 $url = array_filter(array_map(array($this, 'field_get_url'), $this->fields
));
832 foreach ($url as $key=>$val) {
837 foreach ($others as $key=>$val) {
839 $url[] = "$key=$val";
842 return count($url)>0 ?
implode('&', $url) : false
;
850 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: