Adds phone number search
[platal.git] / modules / search / classes.inc.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2008 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 require_once("xorg.misc.inc.php");
23
24 // {{{ Global variables used for the search Queries
25
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,
29 u.nom_usage,u.date,
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,
34 a.alias AS forlife,
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
41 if (S::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,
46 e.entreprise,
47 nw.address AS networking_address,
48 nwe.name AS networking_name,';
49 else
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)';
74
75 // }}}
76 // {{{ class ThrowError
77
78 /** handle errors for end-users queries
79 * assign the error message and runs the templates
80 *
81 * @author Jean-Sebastien Bedo
82 */
83 class ThrowError
84 {
85 public static $throwHook = array('ThrowError', 'defaultHandler');
86
87 /** constuctor
88 * @param $explain string the error (in natural language)
89 */
90 public function __construct($explain)
91 {
92 call_user_func(ThrowError::$throwHook, $explain);
93 }
94
95 /** defaut error handler
96 */
97 private static function defaultHandler($explain)
98 {
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);
104 $page->run();
105 }
106 }
107
108 // }}}
109 // {{{ class SField [Base class]
110
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
114 */
115 class SField
116 {
117 // {{{ properties
118
119 /** le nom du champ dans le formulaire HTML */
120 var $fieldFormName;
121 /** champs de la bdd correspondant à ce champ sous forme d'un tableau */
122 var $fieldDbName;
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 */
127 var $value;
128
129 // }}}
130 // {{{ constructor
131
132 /** constructeur
133 * (récupère la requête de l'utilisateur pour ce champ) */
134 function SField($_fieldFormName, $_fieldDbName='', $_fieldResultName='')
135 {
136 $this->fieldFormName = $_fieldFormName;
137 $this->fieldDbName = $_fieldDbName;
138 $this->fieldResultName = $_fieldResultName;
139 $this->get_request();
140 }
141
142 // }}}
143 // {{{ function get_request()
144
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()
148 {
149 $this->value = trim(Env::v($this->fieldFormName));
150 }
151
152 // }}}
153 // {{{ function get_where_statement()
154
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()
160 {
161 if ($this->value=='') {
162 return false;
163 }
164 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_where_statement'), $this->fieldDbName)));
165 return empty($res) ? '' : "($res)";
166 }
167
168 // }}}
169 // {{{ function get_order_statement()
170
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()
174 {
175 return false;
176 }
177
178 // }}}
179 // {{{ function get_select_statement()
180
181 function get_select_statement()
182 {
183 return false;
184 }
185
186 // }}}
187 // {{{ function get_url()
188
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 */
191 function get_url()
192 {
193 if (empty($this->value)) {
194 return false;
195 } else {
196 return $this->fieldFormName.'='.urlencode($this->value);
197 }
198 }
199
200 // }}}
201 }
202
203 // }}}
204 // {{{ class QuickSearch [Google Like]
205
206 class QuickSearch extends SField
207 {
208 // {{{ properties
209
210 /** stores tokens */
211 var $strings;
212 /** stores numerical ranges */
213 var $ranges;
214 /** stores admin searches */
215 var $email;
216 var $ip;
217
218 // }}}
219 // {{{ constructor
220
221 function QuickSearch($_fieldFormName)
222 {
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.');
227 }
228 }
229
230 // }}}
231 // {{{ function isempty()
232
233 function isempty()
234 {
235 return empty($this->strings) && empty($this->ranges) && empty($this->email) && empty($this->ip);
236 }
237
238 // }}}
239 // {{{ function get_request()
240
241 function get_request()
242 {
243 parent::get_request();
244 $s = replace_accent(trim($this->value));
245 $r = $s = str_replace('*','%',$s);
246
247 if (S::has_perms() && strpos($s, '@') !== false) {
248 $this->email = $s;
249 } else if (S::has_perms() && preg_match('/[0-9]+\.([0-9]+|%)\.([0-9]+|%)\.([0-9]+|%)/', $s)) {
250 $this->ip = $s;
251 }
252 if ($this->email || $this->ip) {
253 $this->strings = $this->ranges = array();
254 return;
255 }
256
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) {
260 global $page;
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);
263 }
264
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;
273 }
274 }
275
276 // }}}
277 // {{{ function get_where_statement()
278
279 function get_where_statement()
280 {
281 $where = Array();
282 foreach ($this->strings as $i => $s) {
283 if (Env::i('with_soundex') && strlen($s) > 1) {
284 $t = soundex_fr($s);
285 $where[] = "sn$i.soundex = '$t'";
286 } else {
287 $t = str_replace('*', '%', $s).'%';
288 $t = str_replace('%%', '%', $t);
289 $where[] = "sn$i.token LIKE '$t'";
290 }
291 }
292
293 $wherep = Array();
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]}";
305 }
306 }
307 if (!empty($wherep)) {
308 $where[] = '('.join(' OR ',$wherep).')';
309 }
310 if (!empty($this->email)) {
311 $where[] = 'ems.email = ' . XDB::escape($this->email);
312 }
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";
316 }
317
318 return join(" AND ", $where);
319 }
320
321 // }}}
322 // {{{ get_select_statement
323 function get_select_statement()
324 {
325 $join = "";
326 $and = '';
327 $uniq = '';
328 foreach ($this->strings as $i => $s) {
329 if (!S::logged()) {
330 $and = "AND FIND_IN_SET('public', sn$i.flags)";
331 }
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";
335 }
336 if (!empty($this->email)) {
337 $join .= "LEFT JOIN emails AS ems ON (ems.uid = u.user_id)";
338 }
339 if (!empty($this->ip)) {
340 $join .= "INNER JOIN logger.sessions AS ls ON (ls.uid = u.user_id)\n";
341 }
342 return $join;
343 }
344 // }}}
345 // {{{ function get_order_statement()
346
347 function get_order_statement()
348 {
349 return false;
350 }
351
352 // }}}
353 // {{{ function get_score_statement
354
355 function get_score_statement()
356 {
357 $sum = array('0');
358 foreach ($this->strings as $i => $s) {
359 $sum[] .= "SUM(sn$i.score + IF('$s'=sn$i.token,5,0))";
360 }
361 return join('+', $sum).' AS score';
362 }
363
364 // }}}
365 }
366
367 // }}}
368 // {{{ class NumericSField [Integer fields]
369
370 /** classe de champ numérique entier (offset par exemple)
371 */
372 class NumericSField extends SField
373 {
374 // {{{ constructor
375
376 /** constructeur
377 * (récupère la requête de l'utilisateur pour ce champ) */
378 function NumericSField($_fieldFormName)
379 {
380 $this->fieldFormName = $_fieldFormName;
381 $this->get_request();
382 }
383
384 // }}}
385 // {{{ function get_request()
386
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()
389 {
390 parent::get_request();
391 if (empty($this->value)) {
392 $this->value = 0;
393 }
394 if (!preg_match("/^[0-9]+$/", $this->value)) {
395 new ThrowError('Un champ numérique contient des caractères alphanumériques.');
396 }
397 }
398
399 // }}}
400 }
401
402 // }}}
403 // {{{ class RefSField [ ??? ]
404
405 class RefSField extends SField
406 {
407 // {{{ properties
408
409 var $refTable;
410 var $refAlias;
411 var $refCondition;
412 var $exact = true;
413
414 // }}}
415 // {{{ constructor
416
417 function RefSField($_fieldFormName, $_fieldDbName='', $_refTable, $_refAlias, $_refCondition, $_exact=true)
418 {
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();
426 }
427
428 // }}}
429 // {{{ function get_request()
430
431 function get_request() {
432 parent::get_request();
433 if ($this->value=='00' || $this->value=='0') {
434 $this->value='';
435 }
436 }
437
438 // }}}
439 // {{{ function too_large()
440
441 function too_large()
442 {
443 return ($this->value=='');
444 }
445
446 // }}}
447 // {{{ function compare()
448
449 function compare()
450 {
451 $val = addslashes($this->value);
452 return $this->exact ? "='$val'" : " LIKE '%$val%'";
453 }
454
455 // }}}
456 // {{{ function get_single_match_statement()
457
458 function get_single_match_statement($field)
459 {
460 return $field.$this->compare();
461 }
462
463 // }}}
464 // {{{ function get_single_where_statement()
465
466 function get_single_where_statement($field)
467 {
468 return $this->refTable=='' ? $this->get_single_match_statement($field) : false;
469 }
470
471 // }}}
472 // {{{ function get_select_statement()
473
474 function get_select_statement()
475 {
476 if ($this->value=='' || $this->refTable=='') {
477 return false;
478 }
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)
482 $last = $i;
483 $inner = "";
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";
486 return $inner;
487 } else {
488 return "INNER JOIN {$this->refTable} AS {$this->refAlias} ON ({$this->refCondition} AND ($res) )";
489 }
490 }
491
492 // }}}
493 }
494
495 // }}}
496
497 // {{{ class RefSFieldMultipleTable
498 class PhoneSField extends RefSField
499 {
500 function PhoneSField($_fieldFormName, $_fieldDbName='', $_refTable, $_refAlias, $_refCondition)
501 {
502 $this->RefSField($_fieldFormName, $_fieldDbName, $_refTable, $_refAlias, $_refCondition, true);
503 }
504
505 function get_request()
506 {
507 require_once("profil.func.inc.php");
508 $this->value = trim(Env::v($this->fieldFormName));
509 $this->value = format_phone_number($this->value);
510 }
511
512 function compare()
513 {
514 return " LIKE '" . addslashes($this->value) . "%'";
515 }
516 }
517
518 class MapSField extends RefSField
519 {
520 var $mapId;
521
522 function MapSField($_fieldFormName, $_fieldDbName='', $_refTable, $_refAlias, $_refCondition, $_mapId=false)
523 {
524 if ($_mapId === false)
525 $this->mapId = Env::v($_fieldFormName, '');
526 else
527 $this->mapId = $_mapId;
528 $this->value = $this->mapId;
529 $this->RefSField($_fieldFormName, $_fieldDbName, $_refTable, $_refAlias, $_refCondition, true, false);
530 }
531
532 function get_select_statement()
533 {
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)
537 $last = $i;
538 $inner = "";
539 foreach ($this->refTable as $i => $refT)
540 $inner .= " INNER JOIN {$refT} AS {$this->refAlias[$i]} ON ({$this->refCondition[$i]} ".(($i == $last)?"AND ($res) ":"").")";
541 return $inner;
542 }
543 function get_request()
544 {
545 $this->value = $this->mapId;
546 }
547 }
548
549 // {{{ class RefWithSoundexSField [ ??? ]
550
551 class RefWithSoundexSField extends RefSField
552 {
553 // {{{ function compare()
554
555 function compare()
556 {
557 return "='".soundex_fr($this->value)."'";
558 }
559
560 // }}}
561 }
562
563 // }}}
564 // {{{ class StringSField [String fields]
565
566 /** classe de champ texte (nom par exemple)
567 */
568 class StringSField extends SField
569 {
570 // {{{ function get_request()
571
572 /** récupère la requête de l'utilisateur et échoue si la chaîne contient des caractères
573 * interdits */
574 function get_request()
575 {
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.');
579 }
580 }
581
582 // }}}
583 // {{{ function length()
584
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) */
588 function length()
589 {
590 $cleaned = replace_accent(strtolower($this->value));
591 $length = strlen(ereg_replace('[a-z0-9]', '', $cleaned));
592 return strlen($this->value) - $length;
593 }
594
595 // }}}
596 // {{{ function too_large()
597
598 function too_large()
599 {
600 return ($this->length()<2);
601 }
602
603 // }}}
604 // {{{ function get_single_where_statement()
605
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)
609 {
610 $regexp = strtr(addslashes($this->value), '-*', '_%');
611 return "$field LIKE '$regexp%'";
612 }
613
614 // }}}
615 // {{{ function get_order_statement()
616
617 /** clause ORDER BY correspondant à ce champ de formulaire */
618 function get_order_statement()
619 {
620 if ($this->value!='' && $this->fieldResultName!='') {
621 return "{$this->fieldResultName}!='".addslashes($this->value)."'";
622 } else {
623 return false;
624 }
625 }
626
627 // }}}
628 }
629
630 // }}}
631 // {{{ class NameSField [Names : serach 'n%' + '% b']
632
633 /** classe pour les noms : on cherche en plus du like 'foo%' le like '% foo' (particules)
634 +*/
635 class NameSField extends StringSField
636 {
637 // {{{ function get_single_where_statement()
638
639 function get_single_where_statement($field)
640 {
641 $regexp = strtr(addslashes($this->value), '-*', '_%');
642 return "$field LIKE '$regexp%' OR $field LIKE '% $regexp%' OR $field LIKE '%-$regexp%'";
643 }
644
645 // }}}
646 // {{{ function get_order_statement()
647
648 function get_order_statement()
649 {
650 if ($this->value!='' && $this->fieldResultName!='') {
651 return "{$this->fieldResultName} NOT LIKE '".addslashes($this->value)."'";
652 } else {
653 return false;
654 }
655 }
656
657 // }}}
658 }
659
660 // }}}
661 // {{{ class StringWithSoundexSField [Strings + soundex]
662
663 /** classe de champ texte avec soundex (nom par exemple)
664 */
665 class StringWithSoundexSField extends StringSField
666 {
667 // {{{ function get_single_where_statement()
668
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).'"';
673 }
674
675 // }}}
676 }
677
678 // }}}
679 // {{{ class PromoSField [Prom field]
680
681 /** classe de champ de promotion */
682 class PromoSField extends SField
683 {
684 // {{{ properties
685
686 /** opérateur de comparaison (<,>,=) de la promo utilisé pour ce champ de formulaire */
687 var $compareField;
688
689 // }}}
690 // {{{ constructor
691
692 /** constructeur
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)
696 {
697 parent::SField($_fieldFormName, $_fieldDbName, $_fieldResultName);
698 $this->compareField = new SField($_compareFieldFormName);
699 }
700
701 // }}}
702 // {{{ function get_request()
703
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()
707 {
708 parent::get_request();
709 if (preg_match('/^[0-9]{2}$/', $this->value)){
710 $this->value = intval($this->value) + 1900;
711 }
712 if (!(empty($this->value) or preg_match('/^[0-9]{4}$/', $this->value))) {
713 new ThrowError('La promotion est une année à quatre chiffres.');
714 }
715 }
716
717 // }}}
718 // {{{ function is_a_single_promo()
719
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()
723 {
724 return ($this->compareField->value=='=' && $this->value!='');
725 }
726
727 // }}}
728 // {{{ function too_large()
729
730 function too_large()
731 {
732 return !$this->is_a_single_promo();
733 }
734
735 // }}}
736 // {{{ function get_single_where_statement()
737
738 /** clause WHERE correspondant à ce champ */
739 function get_single_where_statement($field)
740 {
741 return $field.$this->compareField->value.$this->value;
742 }
743
744 // }}}
745 // {{{ function get_url()
746
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 */
750 function get_url()
751 {
752 if (!($u=parent::get_url())) {
753 return false;
754 }
755 return $u.'&amp;'.$this->compareField->get_url();
756 }
757
758 // }}}
759 }
760
761 // }}}
762 // {{{ class SFieldGroup [Group fields]
763
764 /** classe groupant des champs de formulaire de recherche */
765 class SFieldGroup
766 {
767 // {{{ properties
768
769 /** tableau des classes correspondant aux champs groupés */
770 var $fields;
771 /** type de groupe : ET ou OU */
772 var $and;
773
774 // }}}
775 // {{{ constuctor
776
777 /** constructeur */
778 function SFieldGroup($_and, $_fields)
779 {
780 $this->fields = $_fields;
781 $this->and = $_and;
782 foreach ($this->fields as $key=>&$field) {
783 if (is_null($field)) {
784 unset($this->fields[$key]);
785 }
786 }
787 }
788
789 // }}}
790 // {{{ function too_large()
791
792 function too_large()
793 {
794 $b = true;
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();
798 }
799 }
800 return $b;
801 }
802
803 // }}}
804 // {{{ function field_get_select()
805
806 function field_get_select($f)
807 {
808 return $f->get_select_statement();
809 }
810
811 // }}}
812 // {{{ function field_get_where()
813
814 /** récupérer la clause WHERE d'un objet champ de recherche */
815 function field_get_where($f)
816 {
817 return $f->get_where_statement();
818 }
819
820 // }}}
821 // {{{ function field_get_order()
822
823 /** récupérer la clause ORDER BY d'un objet champ de recherche */
824 function field_get_order($f)
825 {
826 return $f->get_order_statement();
827 }
828
829 // }}}
830 // {{{ function field_get_url()
831
832 /** récupérer le bout d'URL correspondant à un objet champ de recherche */
833 function field_get_url($f)
834 {
835 return $f->get_url();
836 }
837
838 // }}}
839 // {{{ function get_select_statement()
840
841 function get_select_statement()
842 {
843 return implode(' ', array_filter(array_map(array($this, 'field_get_select'), $this->fields)));
844 }
845
846 // }}}
847 // {{{ function get_where_statement()
848
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()
852 {
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)";
856 }
857
858 // }}}
859 // {{{ function get_order_statement()
860
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()
864 {
865 $order = array_filter(array_map(array($this, 'field_get_order'), $this->fields));
866 return count($order)>0 ? implode(',', $order) : false;
867 }
868
869 // }}}
870 // {{{ function get_url()
871
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())
875 {
876 $url = array_filter(array_map(array($this, 'field_get_url'), $this->fields));
877 foreach ($url as $key=>$val) {
878 if (empty($val)) {
879 unset($url[$key]);
880 }
881 }
882 foreach ($others as $key=>$val) {
883 if (!empty($val)) {
884 $url[] = "$key=$val";
885 }
886 }
887 return count($url)>0 ? implode('&amp;', $url) : false;
888 }
889
890 // }}}
891 }
892
893 // }}}
894
895 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
896 ?>