6eab490cd379fdf9a8beb139870aea4e264575b2
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 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 OR FIND_IN_SET("googleapps", u.mail_storage) > 0) AS actif,';
40 // hide private information if not logged
42 $globals->search
->result_fields
.='
43 q.profile_mobile AS mobile,
44 q.profile_freetext AS freetext,
45 adr.city, gp.pays AS countrytxt, gr.name AS region,
47 nw.address AS networking_address,
48 nwe.name AS networking_name,';
50 $globals->search
->result_fields
.="
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 IF(nw.pub='public', nw.address, '') AS networking_address,
58 IF(nw.pub='public', nwe.name, '') AS networking_name,";
59 @$globals->search
->result_where_statement
= '
60 LEFT JOIN applis_ins AS ai0 ON (u.user_id = ai0.uid AND ai0.ordre = 0)
61 LEFT JOIN applis_def AS ad0 ON (ad0.id = ai0.aid)
62 LEFT JOIN applis_ins AS ai1 ON (u.user_id = ai1.uid AND ai1.ordre = 1)
63 LEFT JOIN applis_def AS ad1 ON (ad1.id = ai1.aid)
64 LEFT JOIN entreprises AS e ON (e.entrid = 0 AND e.uid = u.user_id)
65 LEFT JOIN emploi_secteur AS es ON (e.secteur = es.id)
66 LEFT JOIN fonctions_def AS ef ON (e.fonction = ef.id)
67 LEFT JOIN geoloc_pays AS n ON (u.nationalite = n.a2)
68 LEFT JOIN adresses AS adr ON (u.user_id = adr.uid AND FIND_IN_SET(\'active\',adr.statut))
69 LEFT JOIN geoloc_pays AS gp ON (adr.country = gp.a2)
70 LEFT JOIN geoloc_region AS gr ON (adr.country = gr.a2 AND adr.region = gr.region)
71 LEFT JOIN emails AS em ON (em.uid = u.user_id AND em.flags = \'active\')
72 LEFT JOIN profile_networking AS nw ON (nw.uid = u.user_id)
73 LEFT JOIN profile_networking_enum AS nwe ON (nwe.network_type = nw.network_type)';
76 // {{{ class ThrowError
78 /** handle errors for end-users queries
79 * assign the error message and runs the templates
81 * @author Jean-Sebastien Bedo
85 public static $throwHook = array('ThrowError', 'defaultHandler');
88 * @param $explain string the error (in natural language)
90 public function __construct($explain)
92 call_user_func(ThrowError
::$throwHook, $explain);
95 /** defaut error handler
97 private static function defaultHandler($explain)
99 global $page, $globals;
100 $page->changeTpl('search/index.tpl');
101 $page->assign('xorg_title','Polytechnique.org - Annuaire');
102 $page->assign('baseurl', $globals->baseurl
);
103 $page->trigError($explain);
109 // {{{ class SField [Base class]
111 /** classe de base représentant un champ de recherche
112 * (correspond à un champ du formulaire mais peut être à plusieurs champs de la bdd)
113 * interface étendue pour chaque type de champ particulier
119 /** le nom du champ dans le formulaire HTML */
121 /** champs de la bdd correspondant à ce champ sous forme d'un tableau */
123 /** champ résultat dans la requête MySQL correspondant à ce champ
124 * (alias utilisé pour la clause ORDER BY) */
125 var $fieldResultName;
126 /** valeur du champ instanciée par l'utilisateur */
133 * (récupère la requête de l'utilisateur pour ce champ) */
134 function SField($_fieldFormName, $_fieldDbName='', $_fieldResultName='')
136 $this->fieldFormName
= $_fieldFormName;
137 $this->fieldDbName
= $_fieldDbName;
138 $this->fieldResultName
= $_fieldResultName;
139 $this->get_request();
143 // {{{ function get_request()
145 /** récupérer la requête de l'utilisateur
146 * on met une chaîne vide si le champ n'a pas été complété */
147 function get_request()
149 $this->value
= trim(Env
::v($this->fieldFormName
));
153 // {{{ function get_where_statement()
155 /** récupérer la clause correspondant au champ dans la clause WHERE de la requête
156 * on parcourt l'ensemble des champs de la bdd de $fieldDbName et on associe
157 * à chacun d'entre eux une clause spécifique
158 * la clause totale et la disjonction de ces clauses spécifiques */
159 function get_where_statement()
161 if ($this->value
=='') {
164 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_where_statement'), $this->fieldDbName
)));
165 return empty($res) ?
'' : "($res)";
169 // {{{ function get_order_statement()
171 /** récupérer la clause correspondant au champ dans la clause ORDER BY de la requête
172 * utilisé par exemple pour placer d'abord le nom égal à la requête avant les approximations */
173 function get_order_statement()
179 // {{{ function get_select_statement()
181 function get_select_statement()
187 // {{{ function get_url()
189 /** récupérer le bout d'URL correspondant aux paramètres permettant d'imiter une requête d'un
190 * utilisateur assignant la valeur $this->value à ce champ */
193 if (empty($this->value
)) {
196 return $this->fieldFormName
.'='.urlencode($this->value
);
204 // {{{ class QuickSearch [Google Like]
206 class QuickSearch
extends SField
212 /** stores numerical ranges */
214 /** stores admin searches */
221 function QuickSearch($_fieldFormName)
223 $this->fieldFormName
= $_fieldFormName;
224 $this->get_request();
225 if (preg_match(":[\]\[{}~/§_`|%$^=+]|\*\*:u", $this->value
)) {
226 new ThrowError('Un champ contient un caractère interdit rendant la recherche impossible.');
231 // {{{ function isempty()
235 return empty($this->strings
) && empty($this->ranges
) && empty($this->email
) && empty($this->ip
);
239 // {{{ function get_request()
241 function get_request()
243 parent
::get_request();
244 $s = replace_accent(trim($this->value
));
245 $r = $s = str_replace('*','%',$s);
247 if (S
::has_perms() && strpos($s, '@') !== false
) {
249 } else if (S
::has_perms() && preg_match('/[0-9]+\.([0-9]+|%)\.([0-9]+|%)\.([0-9]+|%)/', $s)) {
252 if ($this->email ||
$this->ip
) {
253 $this->strings
= $this->ranges
= array();
257 $s = preg_replace('!\d+!', ' ', $s);
258 $this->strings
= preg_split("![^a-zA-Z%]+!",$s, -1, PREG_SPLIT_NO_EMPTY
);
259 if (count($this->strings
) > 5) {
261 $page->trigWarning("Tu as indiqué trop d'éléments dans ta recherche, seuls les 5 premiers seront pris en compte");
262 $this->strings
= array_slice($this->strings
, 0, 5);
265 $s = preg_replace('! *- *!', '-', $r);
266 $s = preg_replace('!([<>]) *!', ' \1', $s);
267 $s = preg_replace('![^0-9\-><]!', ' ', $s);
268 $s = preg_replace('![<>\-] !', '', $s);
269 $ranges = preg_split('! +!', $s, -1, PREG_SPLIT_NO_EMPTY
);
270 $this->ranges
=Array();
271 foreach ($ranges as $r) {
272 if (preg_match('!^([<>]\d{4}|\d{4}(-\d{4})?)$!', $r)) $this->ranges
[] = $r;
277 // {{{ function get_where_statement()
279 function get_where_statement()
282 foreach ($this->strings
as $i => $s) {
283 if (Env
::i('with_soundex') && strlen($s) > 1) {
285 $where[] = "sn$i.soundex = '$t'";
287 $t = str_replace('*', '%', $s).'%';
288 $t = str_replace('%%', '%', $t);
289 $where[] = "sn$i.token LIKE '$t'";
294 foreach ($this->ranges
as $r) {
295 if (preg_match('!^\d{4}$!', $r)) {
296 $wherep[] = "u.promo=$r";
297 } elseif (preg_match('!^(\d{4})-(\d{4})$!', $r, $matches)) {
298 $p1=min(intval($matches[1]), intval($matches[2]));
299 $p2=max(intval($matches[1]), intval($matches[2]));
300 $wherep[] = "(u.promo>=$p1 AND u.promo<=$p2)";
301 } elseif (preg_match('!^<(\d{4})!', $r, $matches)) {
302 $wherep[] = "u.promo<={$matches[1]}";
303 } elseif (preg_match('!^>(\d{4})!', $r, $matches)) {
304 $wherep[] = "u.promo>={$matches[1]}";
307 if (!empty($wherep)) {
308 $where[] = '('.join(' OR ',$wherep).')';
310 if (!empty($this->email
)) {
311 $where[] = 'ems.email = ' . XDB
::escape($this->email
);
313 if (!empty($this->ip
)) {
314 $ip = ip_to_uint($this->ip
);
315 $where[] = "( ls.ip = $ip OR ls.forward_ip = $ip ) AND ls.suid = 0";
318 return join(" AND ", $where);
322 // {{{ get_select_statement
323 function get_select_statement()
328 foreach ($this->strings
as $i => $s) {
330 $and = "AND FIND_IN_SET('public', sn$i.flags)";
332 $myu = str_replace('snv', "sn$i", $uniq);
333 $join .= "INNER JOIN search_name AS sn$i ON (u.user_id = sn$i.uid $and$myu)\n";
334 $uniq .= " AND sn$i.token != snv.token";
336 if (!empty($this->email
)) {
337 $join .= "LEFT JOIN emails AS ems ON (ems.uid = u.user_id)";
339 if (!empty($this->ip
)) {
340 $join .= "INNER JOIN logger.sessions AS ls ON (ls.uid = u.user_id)\n";
345 // {{{ function get_order_statement()
347 function get_order_statement()
353 // {{{ function get_score_statement
355 function get_score_statement()
358 foreach ($this->strings
as $i => $s) {
359 $sum[] .= "SUM(sn$i.score + IF('$s'=sn$i.token,5,0))";
361 return join('+', $sum).' AS score';
368 // {{{ class NumericSField [Integer fields]
370 /** classe de champ numérique entier (offset par exemple)
372 class NumericSField
extends SField
377 * (récupère la requête de l'utilisateur pour ce champ) */
378 function NumericSField($_fieldFormName)
380 $this->fieldFormName
= $_fieldFormName;
381 $this->get_request();
385 // {{{ function get_request()
387 /** récupère la requête de l'utilisateur et échoue s'il ne s'agit pas d'un entier */
388 function get_request()
390 parent
::get_request();
391 if (empty($this->value
)) {
394 if (!preg_match("/^[0-9]+$/", $this->value
)) {
395 new ThrowError('Un champ numérique contient des caractères alphanumériques.');
403 // {{{ class RefSField [ ??? ]
405 class RefSField
extends SField
417 function RefSField($_fieldFormName, $_fieldDbName='', $_refTable, $_refAlias, $_refCondition, $_exact=true
)
419 $this->fieldFormName
= $_fieldFormName;
420 $this->fieldDbName
= $_fieldDbName;
421 $this->refTable
= $_refTable;
422 $this->refAlias
= $_refAlias;
423 $this->refCondition
= $_refCondition;
424 $this->exact
= $_exact;
425 $this->get_request();
429 // {{{ function get_request()
431 function get_request() {
432 parent
::get_request();
433 if ($this->value
=='00' ||
$this->value
=='0') {
439 // {{{ function too_large()
443 return ($this->value
=='');
447 // {{{ function compare()
451 $val = addslashes($this->value
);
452 return $this->exact ?
"='$val'" : " LIKE '%$val%'";
456 // {{{ function get_single_match_statement()
458 function get_single_match_statement($field)
460 return $field.$this->compare();
464 // {{{ function get_single_where_statement()
466 function get_single_where_statement($field)
468 return $this->refTable
=='' ?
$this->get_single_match_statement($field) : false
;
472 // {{{ function get_select_statement()
474 function get_select_statement()
476 if ($this->value
=='' ||
$this->refTable
=='') {
479 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_match_statement'), $this->fieldDbName
)));
480 if (is_array($this->refTable
)) {
481 foreach ($this->refTable
as $i => $refT)
484 foreach ($this->refTable
as $i => $refT)
485 $inner .= " INNER JOIN {$refT} AS {$this->refAlias[$i]} ON ({$this->refCondition[$i]} ".(($i == $last)?
"AND ($res) ":"").")\n";
488 return "INNER JOIN {$this->refTable} AS {$this->refAlias} ON ({$this->refCondition} AND ($res) )";
497 // {{{ class RefSFieldMultipleTable
498 class PhoneSField
extends RefSField
500 function PhoneSField($_fieldFormName, $_fieldDbName='', $_refTable, $_refAlias, $_refCondition)
502 $this->RefSField($_fieldFormName, $_fieldDbName, $_refTable, $_refAlias, $_refCondition, true
);
505 function get_request()
507 require_once("profil.func.inc.php");
508 $this->value
= trim(Env
::v($this->fieldFormName
));
509 $this->value
= format_phone_number($this->value
);
514 return " LIKE '" . addslashes($this->value
) . "%'";
518 class MapSField
extends RefSField
522 function MapSField($_fieldFormName, $_fieldDbName='', $_refTable, $_refAlias, $_refCondition, $_mapId=false
)
524 if ($_mapId === false
)
525 $this->mapId
= Env
::v($_fieldFormName, '');
527 $this->mapId
= $_mapId;
528 $this->value
= $this->mapId
;
529 $this->RefSField($_fieldFormName, $_fieldDbName, $_refTable, $_refAlias, $_refCondition, true
, false
);
532 function get_select_statement()
534 if ($this->mapId
=== '') return false
;
535 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_match_statement'), $this->fieldDbName
)));
536 foreach ($this->refTable
as $i => $refT)
539 foreach ($this->refTable
as $i => $refT)
540 $inner .= " INNER JOIN {$refT} AS {$this->refAlias[$i]} ON ({$this->refCondition[$i]} ".(($i == $last)?
"AND ($res) ":"").")";
543 function get_request()
545 $this->value
= $this->mapId
;
549 // {{{ class RefWithSoundexSField [ ??? ]
551 class RefWithSoundexSField
extends RefSField
553 // {{{ function compare()
557 return "='".soundex_fr($this->value
)."'";
564 // {{{ class StringSField [String fields]
566 /** classe de champ texte (nom par exemple)
568 class StringSField
extends SField
570 // {{{ function get_request()
572 /** récupère la requête de l'utilisateur et échoue si la chaîne contient des caractères
574 function get_request()
576 parent
::get_request();
577 if (preg_match(":[\]\[<>{}~/§_`|%$^=+]|\*\*:u", $this->value
)) {
578 new ThrowError('Un champ contient un caractère interdit rendant la recherche impossible.');
583 // {{{ function length()
585 /** donne la longueur de la requête de l'utilisateur
586 * (au sens strict i.e. pas d'* ni d'espace ou de trait d'union -> les contraintes réellement
587 * imposées par l'utilisateur) */
590 $cleaned = replace_accent(strtolower($this->value
));
591 $length = strlen(ereg_replace('[a-z0-9]', '', $cleaned));
592 return strlen($this->value
) - $length;
596 // {{{ function too_large()
600 return ($this->length()<2);
604 // {{{ function get_single_where_statement()
606 /** clause WHERE correspondant à un champ de la bdd et à ce champ de formulaire
607 * @param field nom de champ de la bdd concerné par la clause */
608 function get_single_where_statement($field)
610 $regexp = strtr(addslashes($this->value
), '-*', '_%');
611 return "$field LIKE '$regexp%'";
615 // {{{ function get_order_statement()
617 /** clause ORDER BY correspondant à ce champ de formulaire */
618 function get_order_statement()
620 if ($this->value
!='' && $this->fieldResultName
!='') {
621 return "{$this->fieldResultName}!='".addslashes($this->value
)."'";
631 // {{{ class NameSField [Names : serach 'n%' + '% b']
633 /** classe pour les noms : on cherche en plus du like 'foo%' le like '% foo' (particules)
635 class NameSField
extends StringSField
637 // {{{ function get_single_where_statement()
639 function get_single_where_statement($field)
641 $regexp = strtr(addslashes($this->value
), '-*', '_%');
642 return "$field LIKE '$regexp%' OR $field LIKE '% $regexp%' OR $field LIKE '%-$regexp%'";
646 // {{{ function get_order_statement()
648 function get_order_statement()
650 if ($this->value
!='' && $this->fieldResultName
!='') {
651 return "{$this->fieldResultName} NOT LIKE '".addslashes($this->value
)."'";
661 // {{{ class StringWithSoundexSField [Strings + soundex]
663 /** classe de champ texte avec soundex (nom par exemple)
665 class StringWithSoundexSField
extends StringSField
667 // {{{ function get_single_where_statement()
669 /** clause WHERE correspondant à un champ de la bdd et à ce champ de formulaire
670 * @param field nom de champ de la bdd concerné par la clause */
671 function get_single_where_statement($field) {
672 return $field.'="'.soundex_fr($this->value
).'"';
679 // {{{ class PromoSField [Prom field]
681 /** classe de champ de promotion */
682 class PromoSField
extends SField
686 /** opérateur de comparaison (<,>,=) de la promo utilisé pour ce champ de formulaire */
693 * compareField est un champ de formulaire très simple qui ne sert qu'à la construction de la
694 * clause WHERE de la promo */
695 function PromoSField($_fieldFormName, $_compareFieldFormName, $_fieldDbName, $_fieldResultName)
697 parent
::SField($_fieldFormName, $_fieldDbName, $_fieldResultName);
698 $this->compareField
= new SField($_compareFieldFormName);
702 // {{{ function get_request()
704 /** récupère la requête utilisateur et échoue si le champ du formulaire ne représente pas une
705 * promotion (nombre à 4 chiffres) */
706 function get_request()
708 parent
::get_request();
709 if (preg_match('/^[0-9]{2}$/', $this->value
)){
710 $this->value
= intval($this->value
) +
1900;
712 if (!(empty($this->value
) or preg_match('/^[0-9]{4}$/', $this->value
))) {
713 new ThrowError('La promotion est une année à quatre chiffres.');
718 // {{{ function is_a_single_promo()
720 /** teste si la requête est de la forme =promotion -> contrainte forte imposée -> elle suffit
721 * pour autoriser un affichage des résultats alors que <promotion est insuffisant */
722 function is_a_single_promo()
724 return ($this->compareField
->value
=='=' && $this->value
!='');
728 // {{{ function too_large()
732 return !$this->is_a_single_promo();
736 // {{{ function get_single_where_statement()
738 /** clause WHERE correspondant à ce champ */
739 function get_single_where_statement($field)
741 return $field.$this->compareField
->value
.$this->value
;
745 // {{{ function get_url()
747 /** récupérer le bout d'URL correspondant aux paramètres permettant d'imiter une requête
748 * d'un utilisateur assignant la valeur $this->value à ce champ et assignant l'opérateur de
749 * comparaison adéquat */
752 if (!($u=parent
::get_url())) {
755 return $u.'&'.$this->compareField
->get_url();
762 // {{{ class SFieldGroup [Group fields]
764 /** classe groupant des champs de formulaire de recherche */
769 /** tableau des classes correspondant aux champs groupés */
771 /** type de groupe : ET ou OU */
778 function SFieldGroup($_and, $_fields)
780 $this->fields
= $_fields;
782 foreach ($this->fields
as $key=>&$field) {
783 if (is_null($field)) {
784 unset($this->fields
[$key]);
790 // {{{ function too_large()
795 for ($i=0 ; $b && $i<count($this->fields
) ; $i++
) {
796 if (!is_null($this->fields
[$i])) {
797 $b = $b && $this->fields
[$i]->too_large();
804 // {{{ function field_get_select()
806 function field_get_select($f)
808 return $f->get_select_statement();
812 // {{{ function field_get_where()
814 /** récupérer la clause WHERE d'un objet champ de recherche */
815 function field_get_where($f)
817 return $f->get_where_statement();
821 // {{{ function field_get_order()
823 /** récupérer la clause ORDER BY d'un objet champ de recherche */
824 function field_get_order($f)
826 return $f->get_order_statement();
830 // {{{ function field_get_url()
832 /** récupérer le bout d'URL correspondant à un objet champ de recherche */
833 function field_get_url($f)
835 return $f->get_url();
839 // {{{ function get_select_statement()
841 function get_select_statement()
843 return implode(' ', array_filter(array_map(array($this, 'field_get_select'), $this->fields
)));
847 // {{{ function get_where_statement()
849 /** récupérer la clause WHERE du groupe de champs = conjonction (ET) ou disjonction (OU) de
850 * clauses des champs élémentaires */
851 function get_where_statement()
853 $joinText = $this->and ?
' AND ' : ' OR ';
854 $res = implode($joinText, array_filter(array_map(array($this, 'field_get_where'), $this->fields
)));
855 return $res == '' ?
'' : "($res)";
859 // {{{ function get_order_statement()
861 /** récupérer la clause ORDER BY du groupe de champs = conjonction (ET) ou disjonction (OU) de
862 * clauses des champs élémentaires */
863 function get_order_statement()
865 $order = array_filter(array_map(array($this, 'field_get_order'), $this->fields
));
866 return count($order)>0 ?
implode(',', $order) : false
;
870 // {{{ function get_url()
872 /** récupérer le bout d'URL correspondant à ce groupe de champs = concaténation des bouts d'URL
873 * des champs élémentaires */
874 function get_url($others=Array())
876 $url = array_filter(array_map(array($this, 'field_get_url'), $this->fields
));
877 foreach ($url as $key=>$val) {
882 foreach ($others as $key=>$val) {
884 $url[] = "$key=$val";
887 return count($url)>0 ?
implode('&', $url) : false
;
895 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: