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