2 /***************************************************************************
3 * Copyright (C) 2003-2004 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\') 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 // hide private information if not logged
41 $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,
48 $globals->search
->result_fields
.="
49 IF(q.profile_web_pub='public', q.profile_web, '') AS web,
50 IF(q.profile_mobile_pub='public', q.profile_mobile, '') AS mobile,
51 IF(q.profile_freetext_pub='public', q.profile_freetext, '') AS freetext,
52 IF(adr.pub='public', adr.city, '') AS city,
53 IF(adr.pub='public', gp.pays, '') AS countrytxt,
54 IF(adr.pub='public', gr.name, '') AS region,
55 IF(e.pub='public', e.entreprise, '') AS entreprise,";
56 $globals->search
->result_where_statement
= '
57 LEFT JOIN applis_ins AS ai0 ON (u.user_id = ai0.uid AND ai0.ordre = 0)
58 LEFT JOIN applis_def AS ad0 ON (ad0.id = ai0.aid)
59 LEFT JOIN applis_ins AS ai1 ON (u.user_id = ai1.uid AND ai1.ordre = 1)
60 LEFT JOIN applis_def AS ad1 ON (ad1.id = ai1.aid)
61 LEFT JOIN entreprises AS e ON (e.entrid = 0 AND e.uid = u.user_id)
62 LEFT JOIN emploi_secteur AS es ON (e.secteur = es.id)
63 LEFT JOIN fonctions_def AS ef ON (e.fonction = ef.id)
64 LEFT JOIN geoloc_pays AS n ON (u.nationalite = n.a2)
65 LEFT JOIN adresses AS adr ON (u.user_id = adr.uid AND FIND_IN_SET(\'active\',adr.statut))
66 LEFT JOIN geoloc_pays AS gp ON (adr.country = gp.a2)
67 LEFT JOIN geoloc_region AS gr ON (adr.country = gr.a2 AND adr.region = gr.region)';
70 // {{{ function display_lines()
73 * This function is a heuristic that approximatively tells
74 * how many lines of output the contact list will use.
76 function display_lines($text)
79 $tokens = Array('<tr>', '<div class="nom">');
80 foreach ($tokens as $t) {
82 while ( ($i = strpos($text,$t,$i+
1))!==false
) { $n++
; }
88 // {{{ class ThrowError
90 /** handle errors for end-users queries
91 * assign the error message and runs the templates
93 * @author Jean-Sebastien Bedo
98 * @param $explain string the error (in natural language)
100 function ThrowError($explain)
103 $page->trig_run('Erreur : '.$explain);
108 // {{{ class SField [Base class]
110 /** classe de base représentant un champ de recherche
111 * (correspond à un champ du formulaire mais peut être à plusieurs champs de la bdd)
112 * interface étendue pour chaque type de champ particulier
118 /** le nom du champ dans le formulaire HTML */
120 /** champs de la bdd correspondant à ce champ sous forme d'un tableau */
122 /** champ résultat dans la requête MySQL correspondant à ce champ
123 * (alias utilisé pour la clause ORDER BY) */
124 var $fieldResultName;
125 /** valeur du champ instanciée par l'utilisateur */
132 * (récupère la requête de l'utilisateur pour ce champ) */
133 function SField($_fieldFormName, $_fieldDbName='', $_fieldResultName='')
135 $this->fieldFormName
= $_fieldFormName;
136 $this->fieldDbName
= $_fieldDbName;
137 $this->fieldResultName
= $_fieldResultName;
138 $this->get_request();
142 // {{{ function get_request()
144 /** récupérer la requête de l'utilisateur
145 * on met une chaîne vide si le champ n'a pas été complété */
146 function get_request()
148 $this->value
= trim(Env
::get($this->fieldFormName
));
152 // {{{ function get_where_statement()
154 /** récupérer la clause correspondant au champ dans la clause WHERE de la requête
155 * on parcourt l'ensemble des champs de la bdd de $fieldDbName et on associe
156 * à chacun d'entre eux une clause spécifique
157 * la clause totale et la disjonction de ces clauses spécifiques */
158 function get_where_statement()
160 if ($this->value
=='') {
163 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_where_statement'), $this->fieldDbName
)));
164 return empty($res) ?
'' : "($res)";
168 // {{{ function get_order_statement()
170 /** récupérer la clause correspondant au champ dans la clause ORDER BY de la requête
171 * utilisé par exemple pour placer d'abord le nom égal à la requête avant les approximations */
172 function get_order_statement()
178 // {{{ function get_select_statement()
180 function get_select_statement()
186 // {{{ function get_url()
188 /** récupérer le bout d'URL correspondant aux paramètres permettant d'imiter une requête d'un
189 * utilisateur assignant la valeur $this->value à ce champ */
192 if (empty($this->value
)) {
195 return $this->fieldFormName
.'='.urlencode($this->value
);
203 // {{{ class QuickSearch [Google Like]
205 class QuickSearch
extends SField
211 /** stores numerical ranges */
217 function QuickSearch($_fieldFormName)
219 $this->fieldFormName
= $_fieldFormName;
220 $this->get_request();
221 if (preg_match(":[\]\[{}~/§_`|%$^=+]|\*\*:", $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
);
235 // {{{ function get_request()
237 function get_request()
239 parent
::get_request();
240 $s = replace_accent(trim($this->value
));
241 $s = preg_replace('!\d+!', ' ', $s);
242 $s = str_replace('*','%',$s);
243 $this->strings
= preg_split("![^a-zA-Z%]+!",$s, -1, PREG_SPLIT_NO_EMPTY
);
245 $s = trim($this->value
);
246 $s = preg_replace('! *- *!', '-', $s);
247 $s = preg_replace('!([<>]) *!', ' \1', $s);
248 $s = preg_replace('![^0-9\-><]!', ' ', $s);
249 $s = preg_replace('![<>\-] !', '', $s);
250 $ranges = preg_split('! +!', $s, -1, PREG_SPLIT_NO_EMPTY
);
251 $this->ranges
=Array();
252 foreach ($ranges as $r) {
253 if (preg_match('!^([<>]\d{4}|\d{4}(-\d{4})?)$!', $r)) $this->ranges
[] = $r;
258 // {{{ function get_where_statement()
260 function get_where_statement()
263 foreach ($this->strings
as $i => $s) {
264 $t = str_replace('*', '%', $s).'%';
265 $t = str_replace('%%', '%', $t);
266 $where[] = "sn$i.token LIKE '$t'";
270 foreach ($this->ranges
as $r) {
271 if (preg_match('!^\d{4}$!', $r)) {
272 $wherep[] = "u.promo=$r";
273 } elseif (preg_match('!^(\d{4})-(\d{4})$!', $r, $matches)) {
274 $p1=min(intval($matches[1]), intval($matches[2]));
275 $p2=max(intval($matches[1]), intval($matches[2]));
276 $wherep[] = "(u.promo>=$p1 AND u.promo<=$p2)";
277 } elseif (preg_match('!^<(\d{4})!', $r, $matches)) {
278 $wherep[] = "u.promo<={$matches[1]}";
279 } elseif (preg_match('!^>(\d{4})!', $r, $matches)) {
280 $wherep[] = "u.promo>={$matches[1]}";
283 if (!empty($wherep)) {
284 $where[] = '('.join(' OR ',$wherep).')';
286 return join(" AND ", $where);
290 // {{{ get_select_statement
291 function get_select_statement()
294 foreach ($this->strings
as $i => $s) {
295 $join .= "INNER JOIN search_name AS sn$i ON (u.user_id = sn$i.uid)\n";
300 // {{{ function get_order_statement()
302 function get_order_statement()
308 // {{{ function get_score_statement
310 function get_score_statement()
313 foreach ($this->strings
as $i => $s) {
314 $sum[] .= "SUM(sn$i.score + IF('$s'=sn$i.token,5,0))";
316 return join('+', $sum).' AS score';
323 // {{{ class NumericSField [Integer fields]
325 /** classe de champ numérique entier (offset par exemple)
327 class NumericSField
extends SField
332 * (récupère la requête de l'utilisateur pour ce champ) */
333 function NumericSField($_fieldFormName)
335 $this->fieldFormName
= $_fieldFormName;
336 $this->get_request();
340 // {{{ function get_request()
342 /** récupère la requête de l'utilisateur et échoue s'il ne s'agit pas d'un entier */
343 function get_request()
345 parent
::get_request();
346 if (empty($this->value
)) {
349 if (!preg_match("/^[0-9]+$/", $this->value
)) {
350 new ThrowError('Un champ numérique contient des caractères alphanumériques.');
358 // {{{ class RefSField [ ??? ]
360 class RefSField
extends SField
372 function RefSField($_fieldFormName, $_fieldDbName='', $_refTable, $_refAlias, $_refCondition, $_exact=true
)
374 $this->fieldFormName
= $_fieldFormName;
375 $this->fieldDbName
= $_fieldDbName;
376 $this->refTable
= $_refTable;
377 $this->refAlias
= $_refAlias;
378 $this->refCondition
= $_refCondition;
379 $this->exact
= $_exact;
380 $this->get_request();
384 // {{{ function get_request()
386 function get_request() {
387 parent
::get_request();
388 if ($this->value
=='00' ||
$this->value
=='0') {
394 // {{{ function too_large()
398 return ($this->value
=='');
402 // {{{ function compare()
406 $val = addslashes($this->value
);
407 return $this->exact ?
"='$val'" : " LIKE '%$val%'";
411 // {{{ function get_single_match_statement()
413 function get_single_match_statement($field)
415 return $field.$this->compare();
419 // {{{ function get_single_where_statement()
421 function get_single_where_statement($field)
423 return $this->refTable
=='' ?
$this->get_single_match_statement($field) : false
;
427 // {{{ function get_select_statement()
429 function get_select_statement()
431 if ($this->value
=='' ||
$this->refTable
=='') {
434 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_match_statement'), $this->fieldDbName
)));
435 return "INNER JOIN {$this->refTable} AS {$this->refAlias} ON ({$this->refCondition} AND ($res) )";
442 // {{{ class RefWithSoundexSField [ ??? ]
444 class RefWithSoundexSField
extends RefSField
446 // {{{ function compare()
450 return "='".soundex_fr($this->value
)."'";
457 // {{{ class StringSField [String fields]
459 /** classe de champ texte (nom par exemple)
461 class StringSField
extends SField
463 // {{{ function get_request()
465 /** récupère la requête de l'utilisateur et échoue si la chaîne contient des caractères
467 function get_request()
469 parent
::get_request();
470 if (preg_match(":[\]\[<>{}~/§_`|%$^=+]|\*\*:", $this->value
)) {
471 new ThrowError('Un champ contient un caractère interdit rendant la recherche impossible.');
476 // {{{ function length()
478 /** donne la longueur de la requête de l'utilisateur
479 * (au sens strict i.e. pas d'* ni d'espace ou de trait d'union -> les contraintes réellement
480 * imposées par l'utilisateur) */
483 global $lc_accent,$uc_accent;
484 return strlen($this->value
) - strlen(ereg_replace('[a-z'.$lc_accent.$uc_accent.']', '', strtolower($this->value
)));
488 // {{{ function too_large()
492 return ($this->length()<2);
496 // {{{ function get_single_where_statement()
498 /** clause WHERE correspondant à un champ de la bdd et à ce champ de formulaire
499 * @param field nom de champ de la bdd concerné par la clause */
500 function get_single_where_statement($field)
502 $regexp = strtr(addslashes($this->value
), '-*', '_%');
503 return "$field LIKE '$regexp%'";
507 // {{{ function get_order_statement()
509 /** clause ORDER BY correspondant à ce champ de formulaire */
510 function get_order_statement()
512 if ($this->value
!='' && $this->fieldResultName
!='') {
513 return "{$this->fieldResultName}!='".addslashes($this->value
)."'";
523 // {{{ class NameSField [Names : serach 'n%' + '% b']
525 /** classe pour les noms : on cherche en plus du like 'foo%' le like '% foo' (particules)
527 class NameSField
extends StringSField
529 // {{{ function get_single_where_statement()
531 function get_single_where_statement($field)
533 $regexp = strtr(addslashes($this->value
), '-*', '_%');
534 return "$field LIKE '$regexp%' OR $field LIKE '% $regexp%' OR $field LIKE '%-$regexp%'";
538 // {{{ function get_order_statement()
540 function get_order_statement()
542 if ($this->value
!='' && $this->fieldResultName
!='') {
543 return "{$this->fieldResultName} NOT LIKE '".addslashes($this->value
)."'";
553 // {{{ class StringWithSoundexSField [Strings + soundex]
555 /** classe de champ texte avec soundex (nom par exemple)
557 class StringWithSoundexSField
extends StringSField
559 // {{{ function get_single_where_statement()
561 /** clause WHERE correspondant à un champ de la bdd et à ce champ de formulaire
562 * @param field nom de champ de la bdd concerné par la clause */
563 function get_single_where_statement($field) {
564 return $field.'="'.soundex_fr($this->value
).'"';
571 // {{{ class PromoSField [Prom field]
573 /** classe de champ de promotion */
574 class PromoSField
extends SField
578 /** opérateur de comparaison (<,>,=) de la promo utilisé pour ce champ de formulaire */
585 * compareField est un champ de formulaire très simple qui ne sert qu'à la construction de la
586 * clause WHERE de la promo */
587 function PromoSField($_fieldFormName, $_compareFieldFormName, $_fieldDbName, $_fieldResultName)
589 parent
::SField($_fieldFormName, $_fieldDbName, $_fieldResultName);
590 $this->compareField
= new SField($_compareFieldFormName);
594 // {{{ function get_request()
596 /** récupère la requête utilisateur et échoue si le champ du formulaire ne représente pas une
597 * promotion (nombre à 4 chiffres) */
598 function get_request()
600 parent
::get_request();
601 if (preg_match('/^[0-9]{2}$/', $this->value
)){
602 $this->value
= intval($this->value
) +
1900;
604 if (!(empty($this->value
) or preg_match('/^[0-9]{4}$/', $this->value
))) {
605 new ThrowError('La promotion est une année à quatre chiffres.');
610 // {{{ function is_a_single_promo()
612 /** teste si la requête est de la forme =promotion -> contrainte forte imposée -> elle suffit
613 * pour autoriser un affichage des résultats alors que <promotion est insuffisant */
614 function is_a_single_promo()
616 return ($this->compareField
->value
=='=' && $this->value
!='');
620 // {{{ function too_large()
624 return !$this->is_a_single_promo();
628 // {{{ function get_single_where_statement()
630 /** clause WHERE correspondant à ce champ */
631 function get_single_where_statement($field)
633 return $field.$this->compareField
->value
.$this->value
;
637 // {{{ function get_url()
639 /** récupérer le bout d'URL correspondant aux paramètres permettant d'imiter une requête
640 * d'un utilisateur assignant la valeur $this->value à ce champ et assignant l'opérateur de
641 * comparaison adéquat */
644 if (!($u=parent
::get_url())) {
647 return $u.'&'.$this->compareField
->get_url();
654 // {{{ class SFieldGroup [Group fields]
656 /** classe groupant des champs de formulaire de recherche */
661 /** tableau des classes correspondant aux champs groupés */
663 /** type de groupe : ET ou OU */
670 function SFieldGroup($_and, $_fields)
672 $this->fields
= $_fields;
677 // {{{ function too_large()
682 for ($i=0; $b && $i<count($this->fields
); $i++
) {
683 $b &= $this->fields
[$i]->too_large();
689 // {{{ function field_get_select()
691 function field_get_select($f)
693 return $f->get_select_statement();
697 // {{{ function field_get_where()
699 /** récupérer la clause WHERE d'un objet champ de recherche */
700 function field_get_where($f)
702 return $f->get_where_statement();
706 // {{{ function field_get_order()
708 /** récupérer la clause ORDER BY d'un objet champ de recherche */
709 function field_get_order($f)
711 return $f->get_order_statement();
715 // {{{ function field_get_url()
717 /** récupérer le bout d'URL correspondant à un objet champ de recherche */
718 function field_get_url($f)
720 return $f->get_url();
724 // {{{ function get_select_statement()
726 function get_select_statement()
728 return implode(' ', array_filter(array_map(array($this, 'field_get_select'), $this->fields
)));
732 // {{{ function get_where_statement()
734 /** récupérer la clause WHERE du groupe de champs = conjonction (ET) ou disjonction (OU) de
735 * clauses des champs élémentaires */
736 function get_where_statement()
738 $joinText = $this->and ?
' AND ' : ' OR ';
739 $res = implode($joinText, array_filter(array_map(array($this, 'field_get_where'), $this->fields
)));
740 return $res == '' ?
'' : "($res)";
744 // {{{ function get_order_statement()
746 /** récupérer la clause ORDER BY du groupe de champs = conjonction (ET) ou disjonction (OU) de
747 * clauses des champs élémentaires */
748 function get_order_statement()
750 $order = array_filter(array_map(array($this, 'field_get_order'), $this->fields
));
751 return count($order)>0 ?
implode(',', $order) : false
;
755 // {{{ function get_url()
757 /** récupérer le bout d'URL correspondant à ce groupe de champs = concaténation des bouts d'URL
758 * des champs élémentaires */
759 function get_url($others=Array())
761 $url = array_filter(array_map(array($this, 'field_get_url'), $this->fields
));
762 foreach ($url as $key=>$val) {
767 foreach ($others as $key=>$val) {
769 $url[] = "$key=$val";
772 return count($url)>0 ?
implode('&', $url) : false
;