Merge branch 'platal-0.9.17'
[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 // {{{ Global variables used for the search Queries
23
24 @$globals->search->result_fields = '
25 u.user_id, u.promo, u.matricule, u.matricule_ax,
26 if(u.nom_usage=\'\', u.nom, u.nom_usage) AS NomSortKey,
27 u.nom_usage,u.date,
28 u.deces!=0 AS dcd,u.deces,
29 u.perms IN (\'admin\',\'user\', \'disabled\') AS inscrit,
30 u.perms != \'pending\' AS wasinscrit,
31 FIND_IN_SET(\'femme\', u.flags) AS sexe,
32 a.alias AS forlife,
33 ad0.text AS app0text, ad0.url AS app0url, ai0.type AS app0type,
34 ad1.text AS app1text, ad1.url AS app1url, ai1.type AS app1type,
35 es.label AS secteur, ef.fonction_fr AS fonction,
36 IF(n.nat=\'\',n.pays,n.nat) AS nat, n.a2 AS iso3166,
37 (COUNT(em.email) > 0 OR FIND_IN_SET("googleapps", u.mail_storage) > 0) AS actif,';
38 // hide private information if not logged
39 if (S::logged())
40 $globals->search->result_fields .='
41 q.profile_web AS web,
42 q.profile_mobile AS mobile,
43 q.profile_freetext AS freetext,
44 adr.city, gp.pays AS countrytxt, gr.name AS region,
45 e.entreprise,';
46 else
47 $globals->search->result_fields .="
48 IF(q.profile_web_pub='public', q.profile_web, '') AS web,
49 IF(q.profile_mobile_pub='public', q.profile_mobile, '') AS mobile,
50 IF(q.profile_freetext_pub='public', q.profile_freetext, '') AS freetext,
51 IF(adr.pub='public', adr.city, '') AS city,
52 IF(adr.pub='public', gp.pays, '') AS countrytxt,
53 IF(adr.pub='public', gr.name, '') AS region,
54 IF(e.pub='public', e.entreprise, '') AS entreprise,";
55 @$globals->search->result_where_statement = '
56 LEFT JOIN applis_ins AS ai0 ON (u.user_id = ai0.uid AND ai0.ordre = 0)
57 LEFT JOIN applis_def AS ad0 ON (ad0.id = ai0.aid)
58 LEFT JOIN applis_ins AS ai1 ON (u.user_id = ai1.uid AND ai1.ordre = 1)
59 LEFT JOIN applis_def AS ad1 ON (ad1.id = ai1.aid)
60 LEFT JOIN entreprises AS e ON (e.entrid = 0 AND e.uid = u.user_id)
61 LEFT JOIN emploi_secteur AS es ON (e.secteur = es.id)
62 LEFT JOIN fonctions_def AS ef ON (e.fonction = ef.id)
63 LEFT JOIN geoloc_pays AS n ON (u.nationalite = n.a2)
64 LEFT JOIN adresses AS adr ON (u.user_id = adr.uid AND FIND_IN_SET(\'active\',adr.statut))
65 LEFT JOIN geoloc_pays AS gp ON (adr.country = gp.a2)
66 LEFT JOIN geoloc_region AS gr ON (adr.country = gr.a2 AND adr.region = gr.region)
67 LEFT JOIN emails AS em ON (em.uid = u.user_id AND em.flags = \'active\')';
68
69 // }}}
70 // {{{ class ThrowError
71
72 /** handle errors for end-users queries
73 * assign the error message and runs the templates
74 *
75 * @author Jean-Sebastien Bedo
76 */
77 class ThrowError
78 {
79 public static $throwHook = array('ThrowError', 'defaultHandler');
80
81 /** constuctor
82 * @param $explain string the error (in natural language)
83 */
84 public function __construct($explain)
85 {
86 call_user_func(ThrowError::$throwHook, $explain);
87 }
88
89 /** defaut error handler
90 */
91 private static function defaultHandler($explain)
92 {
93 global $globals;
94 $page =& Platal::page();
95 $page->changeTpl('search/index.tpl');
96 $page->setTitle('Polytechnique.org - Annuaire');
97 $page->assign('baseurl', $globals->baseurl);
98 $page->trigError($explain);
99 $page->run();
100 }
101 }
102
103 // }}}
104 // {{{ class SField [Base class]
105
106 /** classe de base représentant un champ de recherche
107 * (correspond à un champ du formulaire mais peut être à plusieurs champs de la bdd)
108 * interface étendue pour chaque type de champ particulier
109 */
110 class SField
111 {
112 // {{{ properties
113
114 /** le nom du champ dans le formulaire HTML */
115 var $fieldFormName;
116 /** champs de la bdd correspondant à ce champ sous forme d'un tableau */
117 var $fieldDbName;
118 /** champ résultat dans la requête MySQL correspondant à ce champ
119 * (alias utilisé pour la clause ORDER BY) */
120 var $fieldResultName;
121 /** valeur du champ instanciée par l'utilisateur */
122 var $value;
123
124 // }}}
125 // {{{ constructor
126
127 /** constructeur
128 * (récupère la requête de l'utilisateur pour ce champ) */
129 function SField($_fieldFormName, $_fieldDbName='', $_fieldResultName='')
130 {
131 $this->fieldFormName = $_fieldFormName;
132 $this->fieldDbName = $_fieldDbName;
133 $this->fieldResultName = $_fieldResultName;
134 $this->get_request();
135 }
136
137 // }}}
138 // {{{ function get_request()
139
140 /** récupérer la requête de l'utilisateur
141 * on met une chaîne vide si le champ n'a pas été complété */
142 function get_request()
143 {
144 $this->value = trim(Env::v($this->fieldFormName));
145 }
146
147 // }}}
148 // {{{ function get_where_statement()
149
150 /** récupérer la clause correspondant au champ dans la clause WHERE de la requête
151 * on parcourt l'ensemble des champs de la bdd de $fieldDbName et on associe
152 * à chacun d'entre eux une clause spécifique
153 * la clause totale et la disjonction de ces clauses spécifiques */
154 function get_where_statement()
155 {
156 if ($this->value=='') {
157 return false;
158 }
159 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_where_statement'), $this->fieldDbName)));
160 return empty($res) ? '' : "($res)";
161 }
162
163 // }}}
164 // {{{ function get_order_statement()
165
166 /** récupérer la clause correspondant au champ dans la clause ORDER BY de la requête
167 * utilisé par exemple pour placer d'abord le nom égal à la requête avant les approximations */
168 function get_order_statement()
169 {
170 return false;
171 }
172
173 // }}}
174 // {{{ function get_select_statement()
175
176 function get_select_statement()
177 {
178 return false;
179 }
180
181 // }}}
182 // {{{ function get_url()
183
184 /** récupérer le bout d'URL correspondant aux paramètres permettant d'imiter une requête d'un
185 * utilisateur assignant la valeur $this->value à ce champ */
186 function get_url()
187 {
188 if (empty($this->value)) {
189 return false;
190 } else {
191 return $this->fieldFormName.'='.urlencode($this->value);
192 }
193 }
194
195 // }}}
196 }
197
198 // }}}
199 // {{{ class QuickSearch [Google Like]
200
201 class QuickSearch extends SField
202 {
203 // {{{ properties
204
205 /** stores tokens */
206 var $strings;
207 /** stores numerical ranges */
208 var $ranges;
209 /** stores admin searches */
210 var $email;
211 var $ip;
212
213 // }}}
214 // {{{ constructor
215
216 function QuickSearch($_fieldFormName)
217 {
218 $this->fieldFormName = $_fieldFormName;
219 $this->get_request();
220 if (preg_match(":[\]\[{}~/§_`|%$^=+]|\*\*:u", $this->value)) {
221 new ThrowError('Un champ contient un caractère interdit rendant la recherche impossible.');
222 }
223 }
224
225 // }}}
226 // {{{ function isempty()
227
228 function isempty()
229 {
230 return empty($this->strings) && empty($this->ranges) && empty($this->email) && empty($this->ip);
231 }
232
233 // }}}
234 // {{{ function get_request()
235
236 function get_request()
237 {
238 parent::get_request();
239 $s = replace_accent(trim($this->value));
240 $r = $s = str_replace('*','%',$s);
241
242 if (S::has_perms() && strpos($s, '@') !== false) {
243 $this->email = $s;
244 } else if (S::has_perms() && preg_match('/[0-9]+\.([0-9]+|%)\.([0-9]+|%)\.([0-9]+|%)/', $s)) {
245 $this->ip = $s;
246 }
247 if ($this->email || $this->ip) {
248 $this->strings = $this->ranges = array();
249 return;
250 }
251
252 $s = preg_replace('!\d+!', ' ', $s);
253 $this->strings = preg_split("![^a-zA-Z%]+!",$s, -1, PREG_SPLIT_NO_EMPTY);
254 if (count($this->strings) > 5) {
255 Platal::page()->trigWarning("Tu as indiqué trop d'éléments dans ta recherche, seuls les 5 premiers seront pris en compte");
256 $this->strings = array_slice($this->strings, 0, 5);
257 }
258
259 $s = preg_replace('! *- *!', '-', $r);
260 $s = preg_replace('!([<>]) *!', ' \1', $s);
261 $s = preg_replace('![^0-9\-><]!', ' ', $s);
262 $s = preg_replace('![<>\-] !', '', $s);
263 $ranges = preg_split('! +!', $s, -1, PREG_SPLIT_NO_EMPTY);
264 $this->ranges=Array();
265 foreach ($ranges as $r) {
266 if (preg_match('!^([<>]\d{4}|\d{4}(-\d{4})?)$!', $r)) $this->ranges[] = $r;
267 }
268 }
269
270 // }}}
271 // {{{ function get_where_statement()
272
273 function get_where_statement()
274 {
275 $where = Array();
276 foreach ($this->strings as $i => $s) {
277 if (Env::i('with_soundex') && strlen($s) > 1) {
278 $t = soundex_fr($s);
279 $where[] = "sn$i.soundex = '$t'";
280 } else {
281 $t = str_replace('*', '%', $s).'%';
282 $t = str_replace('%%', '%', $t);
283 $where[] = "sn$i.token LIKE '$t'";
284 }
285 }
286
287 $wherep = Array();
288 foreach ($this->ranges as $r) {
289 if (preg_match('!^\d{4}$!', $r)) {
290 $wherep[] = "u.promo=$r";
291 } elseif (preg_match('!^(\d{4})-(\d{4})$!', $r, $matches)) {
292 $p1=min(intval($matches[1]), intval($matches[2]));
293 $p2=max(intval($matches[1]), intval($matches[2]));
294 $wherep[] = "(u.promo>=$p1 AND u.promo<=$p2)";
295 } elseif (preg_match('!^<(\d{4})!', $r, $matches)) {
296 $wherep[] = "u.promo<={$matches[1]}";
297 } elseif (preg_match('!^>(\d{4})!', $r, $matches)) {
298 $wherep[] = "u.promo>={$matches[1]}";
299 }
300 }
301 if (!empty($wherep)) {
302 $where[] = '('.join(' OR ',$wherep).')';
303 }
304 if (!empty($this->email)) {
305 $where[] = 'ems.email = ' . XDB::escape($this->email);
306 }
307 if (!empty($this->ip)) {
308 $ip = ip_to_uint($this->ip);
309 $where[] = "( ls.ip = $ip OR ls.forward_ip = $ip ) AND ls.suid = 0";
310 }
311
312 return join(" AND ", $where);
313 }
314
315 // }}}
316 // {{{ get_select_statement
317 function get_select_statement()
318 {
319 $join = "";
320 $and = '';
321 $uniq = '';
322 foreach ($this->strings as $i => $s) {
323 if (!S::logged()) {
324 $and = "AND FIND_IN_SET('public', sn$i.flags)";
325 }
326 $myu = str_replace('snv', "sn$i", $uniq);
327 $join .= "INNER JOIN search_name AS sn$i ON (u.user_id = sn$i.uid $and$myu)\n";
328 $uniq .= " AND sn$i.token != snv.token";
329 }
330 if (!empty($this->email)) {
331 $join .= "LEFT JOIN emails AS ems ON (ems.uid = u.user_id)";
332 }
333 if (!empty($this->ip)) {
334 $join .= "INNER JOIN logger.sessions AS ls ON (ls.uid = u.user_id)\n";
335 }
336 return $join;
337 }
338 // }}}
339 // {{{ function get_order_statement()
340
341 function get_order_statement()
342 {
343 return false;
344 }
345
346 // }}}
347 // {{{ function get_score_statement
348
349 function get_score_statement()
350 {
351 $sum = array('0');
352 foreach ($this->strings as $i => $s) {
353 $sum[] .= "SUM(sn$i.score + IF('$s'=sn$i.token,5,0))";
354 }
355 return join('+', $sum).' AS score';
356 }
357
358 // }}}
359 }
360
361 // }}}
362 // {{{ class NumericSField [Integer fields]
363
364 /** classe de champ numérique entier (offset par exemple)
365 */
366 class NumericSField extends SField
367 {
368 // {{{ constructor
369
370 /** constructeur
371 * (récupère la requête de l'utilisateur pour ce champ) */
372 function NumericSField($_fieldFormName)
373 {
374 $this->fieldFormName = $_fieldFormName;
375 $this->get_request();
376 }
377
378 // }}}
379 // {{{ function get_request()
380
381 /** récupère la requête de l'utilisateur et échoue s'il ne s'agit pas d'un entier */
382 function get_request()
383 {
384 parent::get_request();
385 if (empty($this->value)) {
386 $this->value = 0;
387 }
388 if (!preg_match("/^[0-9]+$/", $this->value)) {
389 new ThrowError('Un champ numérique contient des caractères alphanumériques.');
390 }
391 }
392
393 // }}}
394 }
395
396 // }}}
397 // {{{ class RefSField [ ??? ]
398
399 class RefSField extends SField
400 {
401 // {{{ properties
402
403 var $refTable;
404 var $refAlias;
405 var $refCondition;
406 var $exact = true;
407
408 // }}}
409 // {{{ constructor
410
411 function RefSField($_fieldFormName, $_fieldDbName='', $_refTable, $_refAlias, $_refCondition, $_exact=true)
412 {
413 $this->fieldFormName = $_fieldFormName;
414 $this->fieldDbName = $_fieldDbName;
415 $this->refTable = $_refTable;
416 $this->refAlias = $_refAlias;
417 $this->refCondition = $_refCondition;
418 $this->exact = $_exact;
419 $this->get_request();
420 }
421
422 // }}}
423 // {{{ function get_request()
424
425 function get_request() {
426 parent::get_request();
427 if ($this->value=='00' || $this->value=='0') {
428 $this->value='';
429 }
430 }
431
432 // }}}
433 // {{{ function too_large()
434
435 function too_large()
436 {
437 return ($this->value=='');
438 }
439
440 // }}}
441 // {{{ function compare()
442
443 function compare()
444 {
445 $val = addslashes($this->value);
446 return $this->exact ? "='$val'" : " LIKE '%$val%'";
447 }
448
449 // }}}
450 // {{{ function get_single_match_statement()
451
452 function get_single_match_statement($field)
453 {
454 return $field.$this->compare();
455 }
456
457 // }}}
458 // {{{ function get_single_where_statement()
459
460 function get_single_where_statement($field)
461 {
462 return $this->refTable=='' ? $this->get_single_match_statement($field) : false;
463 }
464
465 // }}}
466 // {{{ function get_select_statement()
467
468 function get_select_statement()
469 {
470 if ($this->value=='' || $this->refTable=='') {
471 return false;
472 }
473 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_match_statement'), $this->fieldDbName)));
474 if (is_array($this->refTable)) {
475 foreach ($this->refTable as $i => $refT)
476 $last = $i;
477 $inner = "";
478 foreach ($this->refTable as $i => $refT)
479 $inner .= " INNER JOIN {$refT} AS {$this->refAlias[$i]} ON ({$this->refCondition[$i]} ".(($i == $last)?"AND ($res) ":"").")\n";
480 return $inner;
481 } else {
482 return "INNER JOIN {$this->refTable} AS {$this->refAlias} ON ({$this->refCondition} AND ($res) )";
483 }
484 }
485
486 // }}}
487 }
488
489 // }}}
490
491 // {{{ class RefSFieldMultipleTable
492 class MapSField extends RefSField
493 {
494 var $mapId;
495
496 function MapSField($_fieldFormName, $_fieldDbName='', $_refTable, $_refAlias, $_refCondition, $_mapId=false)
497 {
498 if ($_mapId === false)
499 $this->mapId = Env::v($_fieldFormName, '');
500 else
501 $this->mapId = $_mapId;
502 $this->value = $this->mapId;
503 $this->RefSField($_fieldFormName, $_fieldDbName, $_refTable, $_refAlias, $_refCondition, true, false);
504 }
505
506 function get_select_statement()
507 {
508 if ($this->mapId === '') return false;
509 $res = implode(' OR ', array_filter(array_map(array($this, 'get_single_match_statement'), $this->fieldDbName)));
510 foreach ($this->refTable as $i => $refT)
511 $last = $i;
512 $inner = "";
513 foreach ($this->refTable as $i => $refT)
514 $inner .= " INNER JOIN {$refT} AS {$this->refAlias[$i]} ON ({$this->refCondition[$i]} ".(($i == $last)?"AND ($res) ":"").")";
515 return $inner;
516 }
517 function get_request()
518 {
519 $this->value = $this->mapId;
520 }
521 }
522
523 // {{{ class RefWithSoundexSField [ ??? ]
524
525 class RefWithSoundexSField extends RefSField
526 {
527 // {{{ function compare()
528
529 function compare()
530 {
531 return "='".soundex_fr($this->value)."'";
532 }
533
534 // }}}
535 }
536
537 // }}}
538 // {{{ class StringSField [String fields]
539
540 /** classe de champ texte (nom par exemple)
541 */
542 class StringSField extends SField
543 {
544 // {{{ function get_request()
545
546 /** récupère la requête de l'utilisateur et échoue si la chaîne contient des caractères
547 * interdits */
548 function get_request()
549 {
550 parent::get_request();
551 if (preg_match(":[\]\[<>{}~/§_`|%$^=+]|\*\*:u", $this->value)) {
552 new ThrowError('Un champ contient un caractère interdit rendant la recherche impossible.');
553 }
554 }
555
556 // }}}
557 // {{{ function length()
558
559 /** donne la longueur de la requête de l'utilisateur
560 * (au sens strict i.e. pas d'* ni d'espace ou de trait d'union -> les contraintes réellement
561 * imposées par l'utilisateur) */
562 function length()
563 {
564 $cleaned = replace_accent(strtolower($this->value));
565 $length = strlen(ereg_replace('[a-z0-9]', '', $cleaned));
566 return strlen($this->value) - $length;
567 }
568
569 // }}}
570 // {{{ function too_large()
571
572 function too_large()
573 {
574 return ($this->length()<2);
575 }
576
577 // }}}
578 // {{{ function get_single_where_statement()
579
580 /** clause WHERE correspondant à un champ de la bdd et à ce champ de formulaire
581 * @param field nom de champ de la bdd concerné par la clause */
582 function get_single_where_statement($field)
583 {
584 $regexp = strtr(addslashes($this->value), '-*', '_%');
585 return "$field LIKE '$regexp%'";
586 }
587
588 // }}}
589 // {{{ function get_order_statement()
590
591 /** clause ORDER BY correspondant à ce champ de formulaire */
592 function get_order_statement()
593 {
594 if ($this->value!='' && $this->fieldResultName!='') {
595 return "{$this->fieldResultName}!='".addslashes($this->value)."'";
596 } else {
597 return false;
598 }
599 }
600
601 // }}}
602 }
603
604 // }}}
605 // {{{ class NameSField [Names : serach 'n%' + '% b']
606
607 /** classe pour les noms : on cherche en plus du like 'foo%' le like '% foo' (particules)
608 +*/
609 class NameSField extends StringSField
610 {
611 // {{{ function get_single_where_statement()
612
613 function get_single_where_statement($field)
614 {
615 $regexp = strtr(addslashes($this->value), '-*', '_%');
616 return "$field LIKE '$regexp%' OR $field LIKE '% $regexp%' OR $field LIKE '%-$regexp%'";
617 }
618
619 // }}}
620 // {{{ function get_order_statement()
621
622 function get_order_statement()
623 {
624 if ($this->value!='' && $this->fieldResultName!='') {
625 return "{$this->fieldResultName} NOT LIKE '".addslashes($this->value)."'";
626 } else {
627 return false;
628 }
629 }
630
631 // }}}
632 }
633
634 // }}}
635 // {{{ class StringWithSoundexSField [Strings + soundex]
636
637 /** classe de champ texte avec soundex (nom par exemple)
638 */
639 class StringWithSoundexSField extends StringSField
640 {
641 // {{{ function get_single_where_statement()
642
643 /** clause WHERE correspondant à un champ de la bdd et à ce champ de formulaire
644 * @param field nom de champ de la bdd concerné par la clause */
645 function get_single_where_statement($field) {
646 return $field.'="'.soundex_fr($this->value).'"';
647 }
648
649 // }}}
650 }
651
652 // }}}
653 // {{{ class PromoSField [Prom field]
654
655 /** classe de champ de promotion */
656 class PromoSField extends SField
657 {
658 // {{{ properties
659
660 /** opérateur de comparaison (<,>,=) de la promo utilisé pour ce champ de formulaire */
661 var $compareField;
662
663 // }}}
664 // {{{ constructor
665
666 /** constructeur
667 * compareField est un champ de formulaire très simple qui ne sert qu'à la construction de la
668 * clause WHERE de la promo */
669 function PromoSField($_fieldFormName, $_compareFieldFormName, $_fieldDbName, $_fieldResultName)
670 {
671 parent::SField($_fieldFormName, $_fieldDbName, $_fieldResultName);
672 $this->compareField = new SField($_compareFieldFormName);
673 }
674
675 // }}}
676 // {{{ function get_request()
677
678 /** récupère la requête utilisateur et échoue si le champ du formulaire ne représente pas une
679 * promotion (nombre à 4 chiffres) */
680 function get_request()
681 {
682 parent::get_request();
683 if (preg_match('/^[0-9]{2}$/', $this->value)){
684 $this->value = intval($this->value) + 1900;
685 }
686 if (!(empty($this->value) or preg_match('/^[0-9]{4}$/', $this->value))) {
687 new ThrowError('La promotion est une année à quatre chiffres.');
688 }
689 }
690
691 // }}}
692 // {{{ function is_a_single_promo()
693
694 /** teste si la requête est de la forme =promotion -> contrainte forte imposée -> elle suffit
695 * pour autoriser un affichage des résultats alors que <promotion est insuffisant */
696 function is_a_single_promo()
697 {
698 return ($this->compareField->value=='=' && $this->value!='');
699 }
700
701 // }}}
702 // {{{ function too_large()
703
704 function too_large()
705 {
706 return !$this->is_a_single_promo();
707 }
708
709 // }}}
710 // {{{ function get_single_where_statement()
711
712 /** clause WHERE correspondant à ce champ */
713 function get_single_where_statement($field)
714 {
715 return $field.$this->compareField->value.$this->value;
716 }
717
718 // }}}
719 // {{{ function get_url()
720
721 /** récupérer le bout d'URL correspondant aux paramètres permettant d'imiter une requête
722 * d'un utilisateur assignant la valeur $this->value à ce champ et assignant l'opérateur de
723 * comparaison adéquat */
724 function get_url()
725 {
726 if (!($u=parent::get_url())) {
727 return false;
728 }
729 return $u.'&amp;'.$this->compareField->get_url();
730 }
731
732 // }}}
733 }
734
735 // }}}
736 // {{{ class SFieldGroup [Group fields]
737
738 /** classe groupant des champs de formulaire de recherche */
739 class SFieldGroup
740 {
741 // {{{ properties
742
743 /** tableau des classes correspondant aux champs groupés */
744 var $fields;
745 /** type de groupe : ET ou OU */
746 var $and;
747
748 // }}}
749 // {{{ constuctor
750
751 /** constructeur */
752 function SFieldGroup($_and, $_fields)
753 {
754 $this->fields = $_fields;
755 $this->and = $_and;
756 foreach ($this->fields as $key=>&$field) {
757 if (is_null($field)) {
758 unset($this->fields[$key]);
759 }
760 }
761 }
762
763 // }}}
764 // {{{ function too_large()
765
766 function too_large()
767 {
768 $b = true;
769 for ($i=0 ; $b && $i<count($this->fields) ; $i++) {
770 if (!is_null($this->fields[$i])) {
771 $b = $b && $this->fields[$i]->too_large();
772 }
773 }
774 return $b;
775 }
776
777 // }}}
778 // {{{ function field_get_select()
779
780 function field_get_select($f)
781 {
782 return $f->get_select_statement();
783 }
784
785 // }}}
786 // {{{ function field_get_where()
787
788 /** récupérer la clause WHERE d'un objet champ de recherche */
789 function field_get_where($f)
790 {
791 return $f->get_where_statement();
792 }
793
794 // }}}
795 // {{{ function field_get_order()
796
797 /** récupérer la clause ORDER BY d'un objet champ de recherche */
798 function field_get_order($f)
799 {
800 return $f->get_order_statement();
801 }
802
803 // }}}
804 // {{{ function field_get_url()
805
806 /** récupérer le bout d'URL correspondant à un objet champ de recherche */
807 function field_get_url($f)
808 {
809 return $f->get_url();
810 }
811
812 // }}}
813 // {{{ function get_select_statement()
814
815 function get_select_statement()
816 {
817 return implode(' ', array_filter(array_map(array($this, 'field_get_select'), $this->fields)));
818 }
819
820 // }}}
821 // {{{ function get_where_statement()
822
823 /** récupérer la clause WHERE du groupe de champs = conjonction (ET) ou disjonction (OU) de
824 * clauses des champs élémentaires */
825 function get_where_statement()
826 {
827 $joinText = $this->and ? ' AND ' : ' OR ';
828 $res = implode($joinText, array_filter(array_map(array($this, 'field_get_where'), $this->fields)));
829 return $res == '' ? '' : "($res)";
830 }
831
832 // }}}
833 // {{{ function get_order_statement()
834
835 /** récupérer la clause ORDER BY du groupe de champs = conjonction (ET) ou disjonction (OU) de
836 * clauses des champs élémentaires */
837 function get_order_statement()
838 {
839 $order = array_filter(array_map(array($this, 'field_get_order'), $this->fields));
840 return count($order)>0 ? implode(',', $order) : false;
841 }
842
843 // }}}
844 // {{{ function get_url()
845
846 /** récupérer le bout d'URL correspondant à ce groupe de champs = concaténation des bouts d'URL
847 * des champs élémentaires */
848 function get_url($others=Array())
849 {
850 $url = array_filter(array_map(array($this, 'field_get_url'), $this->fields));
851 foreach ($url as $key=>$val) {
852 if (empty($val)) {
853 unset($url[$key]);
854 }
855 }
856 foreach ($others as $key=>$val) {
857 if (!empty($val)) {
858 $url[] = "$key=$val";
859 }
860 }
861 return count($url)>0 ? implode('&amp;', $url) : false;
862 }
863
864 // }}}
865 }
866
867 // }}}
868
869 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
870 ?>