8113380b48b3ccb0b959ab0dce04c0636795f71f
[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 IndexSField extends RefSField
519 {
520 function IndexSField($_fieldFormName, $_fieldDbName='', $_refTable, $_refAlias, $_refCondition)
521 {
522 $this->RefSField($_fieldFormName, $_fieldDbName, $_refTable, $_refAlias, $_refCondition, true);
523 }
524
525 function get_request()
526 {
527 $this->value = trim(Env::v($this->fieldFormName));
528 }
529 }
530
531 class MapSField extends RefSField
532 {
533 var $mapId;
534
535 function MapSField($_fieldFormName, $_fieldDbName='', $_refTable, $_refAlias, $_refCondition, $_mapId=false)
536 {
537 if ($_mapId === false)
538 $this->mapId = Env::v($_fieldFormName, '');
539 else
540 $this->mapId = $_mapId;
541 $this->value = $this->mapId;
542 $this->RefSField($_fieldFormName, $_fieldDbName, $_refTable, $_refAlias, $_refCondition, true, false);
543 }
544
545 function get_select_statement()
546 {
547 if ($this->mapId === '') return false;
548 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_match_statement'), $this->fieldDbName)));
549 foreach ($this->refTable as $i => $refT)
550 $last = $i;
551 $inner = "";
552 foreach ($this->refTable as $i => $refT)
553 $inner .= " INNER JOIN {$refT} AS {$this->refAlias[$i]} ON ({$this->refCondition[$i]} ".(($i == $last)?"AND ($res) ":"").")";
554 return $inner;
555 }
556 function get_request()
557 {
558 $this->value = $this->mapId;
559 }
560 }
561
562 // {{{ class RefWithSoundexSField [ ??? ]
563
564 class RefWithSoundexSField extends RefSField
565 {
566 // {{{ function compare()
567
568 function compare()
569 {
570 return "='".soundex_fr($this->value)."'";
571 }
572
573 // }}}
574 }
575
576 // }}}
577 // {{{ class StringSField [String fields]
578
579 /** classe de champ texte (nom par exemple)
580 */
581 class StringSField extends SField
582 {
583 // {{{ function get_request()
584
585 /** récupère la requête de l'utilisateur et échoue si la chaîne contient des caractères
586 * interdits */
587 function get_request()
588 {
589 parent::get_request();
590 if (preg_match(":[\]\[<>{}~/§_`|%$^=+]|\*\*:u", $this->value)) {
591 new ThrowError('Un champ contient un caractère interdit rendant la recherche impossible.');
592 }
593 }
594
595 // }}}
596 // {{{ function length()
597
598 /** donne la longueur de la requête de l'utilisateur
599 * (au sens strict i.e. pas d'* ni d'espace ou de trait d'union -> les contraintes réellement
600 * imposées par l'utilisateur) */
601 function length()
602 {
603 $cleaned = replace_accent(strtolower($this->value));
604 $length = strlen(ereg_replace('[a-z0-9]', '', $cleaned));
605 return strlen($this->value) - $length;
606 }
607
608 // }}}
609 // {{{ function too_large()
610
611 function too_large()
612 {
613 return ($this->length()<2);
614 }
615
616 // }}}
617 // {{{ function get_single_where_statement()
618
619 /** clause WHERE correspondant à un champ de la bdd et à ce champ de formulaire
620 * @param field nom de champ de la bdd concerné par la clause */
621 function get_single_where_statement($field)
622 {
623 $regexp = strtr(addslashes($this->value), '-*', '_%');
624 return "$field LIKE '$regexp%'";
625 }
626
627 // }}}
628 // {{{ function get_order_statement()
629
630 /** clause ORDER BY correspondant à ce champ de formulaire */
631 function get_order_statement()
632 {
633 if ($this->value!='' && $this->fieldResultName!='') {
634 return "{$this->fieldResultName}!='".addslashes($this->value)."'";
635 } else {
636 return false;
637 }
638 }
639
640 // }}}
641 }
642
643 // }}}
644 // {{{ class NameSField [Names : serach 'n%' + '% b']
645
646 /** classe pour les noms : on cherche en plus du like 'foo%' le like '% foo' (particules)
647 +*/
648 class NameSField extends StringSField
649 {
650 // {{{ function get_single_where_statement()
651
652 function get_single_where_statement($field)
653 {
654 $regexp = strtr(addslashes($this->value), '-*', '_%');
655 return "$field LIKE '$regexp%' OR $field LIKE '% $regexp%' OR $field LIKE '%-$regexp%'";
656 }
657
658 // }}}
659 // {{{ function get_order_statement()
660
661 function get_order_statement()
662 {
663 if ($this->value!='' && $this->fieldResultName!='') {
664 return "{$this->fieldResultName} NOT LIKE '".addslashes($this->value)."'";
665 } else {
666 return false;
667 }
668 }
669
670 // }}}
671 }
672
673 // }}}
674 // {{{ class StringWithSoundexSField [Strings + soundex]
675
676 /** classe de champ texte avec soundex (nom par exemple)
677 */
678 class StringWithSoundexSField extends StringSField
679 {
680 // {{{ function get_single_where_statement()
681
682 /** clause WHERE correspondant à un champ de la bdd et à ce champ de formulaire
683 * @param field nom de champ de la bdd concerné par la clause */
684 function get_single_where_statement($field) {
685 return $field.'="'.soundex_fr($this->value).'"';
686 }
687
688 // }}}
689 }
690
691 // }}}
692 // {{{ class PromoSField [Prom field]
693
694 /** classe de champ de promotion */
695 class PromoSField extends SField
696 {
697 // {{{ properties
698
699 /** opérateur de comparaison (<,>,=) de la promo utilisé pour ce champ de formulaire */
700 var $compareField;
701
702 // }}}
703 // {{{ constructor
704
705 /** constructeur
706 * compareField est un champ de formulaire très simple qui ne sert qu'à la construction de la
707 * clause WHERE de la promo */
708 function PromoSField($_fieldFormName, $_compareFieldFormName, $_fieldDbName, $_fieldResultName)
709 {
710 parent::SField($_fieldFormName, $_fieldDbName, $_fieldResultName);
711 $this->compareField = new SField($_compareFieldFormName);
712 }
713
714 // }}}
715 // {{{ function get_request()
716
717 /** récupère la requête utilisateur et échoue si le champ du formulaire ne représente pas une
718 * promotion (nombre à 4 chiffres) */
719 function get_request()
720 {
721 parent::get_request();
722 if (preg_match('/^[0-9]{2}$/', $this->value)){
723 $this->value = intval($this->value) + 1900;
724 }
725 if (!(empty($this->value) or preg_match('/^[0-9]{4}$/', $this->value))) {
726 new ThrowError('La promotion est une année à quatre chiffres.');
727 }
728 }
729
730 // }}}
731 // {{{ function is_a_single_promo()
732
733 /** teste si la requête est de la forme =promotion -> contrainte forte imposée -> elle suffit
734 * pour autoriser un affichage des résultats alors que <promotion est insuffisant */
735 function is_a_single_promo()
736 {
737 return ($this->compareField->value=='=' && $this->value!='');
738 }
739
740 // }}}
741 // {{{ function too_large()
742
743 function too_large()
744 {
745 return !$this->is_a_single_promo();
746 }
747
748 // }}}
749 // {{{ function get_single_where_statement()
750
751 /** clause WHERE correspondant à ce champ */
752 function get_single_where_statement($field)
753 {
754 return $field.$this->compareField->value.$this->value;
755 }
756
757 // }}}
758 // {{{ function get_url()
759
760 /** récupérer le bout d'URL correspondant aux paramètres permettant d'imiter une requête
761 * d'un utilisateur assignant la valeur $this->value à ce champ et assignant l'opérateur de
762 * comparaison adéquat */
763 function get_url()
764 {
765 if (!($u=parent::get_url())) {
766 return false;
767 }
768 return $u.'&amp;'.$this->compareField->get_url();
769 }
770
771 // }}}
772 }
773
774 // }}}
775 // {{{ class SFieldGroup [Group fields]
776
777 /** classe groupant des champs de formulaire de recherche */
778 class SFieldGroup
779 {
780 // {{{ properties
781
782 /** tableau des classes correspondant aux champs groupés */
783 var $fields;
784 /** type de groupe : ET ou OU */
785 var $and;
786
787 // }}}
788 // {{{ constuctor
789
790 /** constructeur */
791 function SFieldGroup($_and, $_fields)
792 {
793 $this->fields = $_fields;
794 $this->and = $_and;
795 foreach ($this->fields as $key=>&$field) {
796 if (is_null($field)) {
797 unset($this->fields[$key]);
798 }
799 }
800 }
801
802 // }}}
803 // {{{ function too_large()
804
805 function too_large()
806 {
807 $b = true;
808 for ($i=0 ; $b && $i<count($this->fields) ; $i++) {
809 if (!is_null($this->fields[$i])) {
810 $b = $b && $this->fields[$i]->too_large();
811 }
812 }
813 return $b;
814 }
815
816 // }}}
817 // {{{ function field_get_select()
818
819 function field_get_select($f)
820 {
821 return $f->get_select_statement();
822 }
823
824 // }}}
825 // {{{ function field_get_where()
826
827 /** récupérer la clause WHERE d'un objet champ de recherche */
828 function field_get_where($f)
829 {
830 return $f->get_where_statement();
831 }
832
833 // }}}
834 // {{{ function field_get_order()
835
836 /** récupérer la clause ORDER BY d'un objet champ de recherche */
837 function field_get_order($f)
838 {
839 return $f->get_order_statement();
840 }
841
842 // }}}
843 // {{{ function field_get_url()
844
845 /** récupérer le bout d'URL correspondant à un objet champ de recherche */
846 function field_get_url($f)
847 {
848 return $f->get_url();
849 }
850
851 // }}}
852 // {{{ function get_select_statement()
853
854 function get_select_statement()
855 {
856 return implode(' ', array_filter(array_map(array($this, 'field_get_select'), $this->fields)));
857 }
858
859 // }}}
860 // {{{ function get_where_statement()
861
862 /** récupérer la clause WHERE du groupe de champs = conjonction (ET) ou disjonction (OU) de
863 * clauses des champs élémentaires */
864 function get_where_statement()
865 {
866 $joinText = $this->and ? ' AND ' : ' OR ';
867 $res = implode($joinText, array_filter(array_map(array($this, 'field_get_where'), $this->fields)));
868 return $res == '' ? '' : "($res)";
869 }
870
871 // }}}
872 // {{{ function get_order_statement()
873
874 /** récupérer la clause ORDER BY du groupe de champs = conjonction (ET) ou disjonction (OU) de
875 * clauses des champs élémentaires */
876 function get_order_statement()
877 {
878 $order = array_filter(array_map(array($this, 'field_get_order'), $this->fields));
879 return count($order)>0 ? implode(',', $order) : false;
880 }
881
882 // }}}
883 // {{{ function get_url()
884
885 /** récupérer le bout d'URL correspondant à ce groupe de champs = concaténation des bouts d'URL
886 * des champs élémentaires */
887 function get_url($others=Array())
888 {
889 $url = array_filter(array_map(array($this, 'field_get_url'), $this->fields));
890 foreach ($url as $key=>$val) {
891 if (empty($val)) {
892 unset($url[$key]);
893 }
894 }
895 foreach ($others as $key=>$val) {
896 if (!empty($val)) {
897 $url[] = "$key=$val";
898 }
899 }
900 return count($url)>0 ? implode('&amp;', $url) : false;
901 }
902
903 // }}}
904 }
905
906 // }}}
907
908 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
909 ?>