Add UFC_Corps
[platal.git] / classes / userfilter.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2009 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
23 /******************
24 * CONDITIONS
25 ******************/
26
27 interface UserFilterCondition
28 {
29 const COND_TRUE = 'TRUE';
30 const COND_FALSE = 'FALSE';
31
32 /** Check that the given user matches the rule.
33 */
34 public function buildCondition(UserFilter &$uf);
35 }
36
37 abstract class UFC_OneChild implements UserFilterCondition
38 {
39 protected $child;
40
41 public function __construct($child = null)
42 {
43 if (!is_null($child) && ($child instanceof UserFilterCondition)) {
44 $this->setChild($child);
45 }
46 }
47
48 public function setChild(UserFilterCondition &$cond)
49 {
50 $this->child =& $cond;
51 }
52 }
53
54 abstract class UFC_NChildren implements UserFilterCondition
55 {
56 protected $children = array();
57
58 public function __construct()
59 {
60 $children = func_get_args();
61 foreach ($children as &$child) {
62 if (!is_null($child) && ($child instanceof UserFilterCondition)) {
63 $this->addChild($child);
64 }
65 }
66 }
67
68 public function addChild(UserFilterCondition &$cond)
69 {
70 $this->children[] =& $cond;
71 }
72
73 protected function catConds(array $cond, $op, $fallback)
74 {
75 if (count($cond) == 0) {
76 return $fallback;
77 } else if (count($cond) == 1) {
78 return $cond[0];
79 } else {
80 return '(' . implode(') ' . $op . ' (', $cond) . ')';
81 }
82 }
83 }
84
85 class UFC_True implements UserFilterCondition
86 {
87 public function buildCondition(UserFilter &$uf)
88 {
89 return self::COND_TRUE;
90 }
91 }
92
93 class UFC_False implements UserFilterCondition
94 {
95 public function buildCondition(UserFilter &$uf)
96 {
97 return self::COND_FALSE;
98 }
99 }
100
101 class UFC_Not extends UFC_OneChild
102 {
103 public function buildCondition(UserFilter &$uf)
104 {
105 $val = $this->child->buildCondition($uf);
106 if ($val == self::COND_TRUE) {
107 return self::COND_FALSE;
108 } else if ($val == self::COND_FALSE) {
109 return self::COND_TRUE;
110 } else {
111 return 'NOT (' . $val . ')';
112 }
113 }
114 }
115
116 class UFC_And extends UFC_NChildren
117 {
118 public function buildCondition(UserFilter &$uf)
119 {
120 if (empty($this->children)) {
121 return self::COND_FALSE;
122 } else {
123 $true = self::COND_FALSE;
124 $conds = array();
125 foreach ($this->children as &$child) {
126 $val = $child->buildCondition($uf);
127 if ($val == self::COND_TRUE) {
128 $true = self::COND_TRUE;
129 } else if ($val == self::COND_FALSE) {
130 return self::COND_FALSE;
131 } else {
132 $conds[] = $val;
133 }
134 }
135 return $this->catConds($conds, 'AND', $true);
136 }
137 }
138 }
139
140 class UFC_Or extends UFC_NChildren
141 {
142 public function buildCondition(UserFilter &$uf)
143 {
144 if (empty($this->children)) {
145 return self::COND_TRUE;
146 } else {
147 $true = self::COND_TRUE;
148 $conds = array();
149 foreach ($this->children as &$child) {
150 $val = $child->buildCondition($uf);
151 if ($val == self::COND_TRUE) {
152 return self::COND_TRUE;
153 } else if ($val == self::COND_FALSE) {
154 $true = self::COND_FALSE;
155 } else {
156 $conds[] = $val;
157 }
158 }
159 return $this->catConds($conds, 'OR', $true);
160 }
161 }
162 }
163
164 /** Filters users who have a profile
165 */
166 class UFC_Profile implements UserFilterCondition
167 {
168 public function buildCondition(UserFilter &$uf)
169 {
170 return '$PID IS NOT NULL';
171 }
172 }
173
174 /** Filters users based on promo
175 * @param $comparison Comparison operator (>, =, ...)
176 * @param $grade Formation on which to restrict, UserFilter::DISPLAY for "any formation"
177 * @param $promo Promo on which the filter is based
178 */
179 class UFC_Promo implements UserFilterCondition
180 {
181
182 private $grade;
183 private $promo;
184 private $comparison;
185
186 public function __construct($comparison, $grade, $promo)
187 {
188 $this->grade = $grade;
189 $this->comparison = $comparison;
190 $this->promo = $promo;
191 if ($this->grade != UserFilter::DISPLAY) {
192 UserFilter::assertGrade($this->grade);
193 }
194 }
195
196 public function buildCondition(UserFilter &$uf)
197 {
198 if ($this->grade == UserFilter::DISPLAY) {
199 $sub = $uf->addDisplayFilter();
200 return XDB::format('pd' . $sub . '.promo = {?}', $this->promo);
201 } else {
202 $sub = $uf->addEducationFilter(true, $this->grade);
203 $field = 'pe' . $sub . '.' . UserFilter::promoYear($this->grade);
204 return $field . ' IS NOT NULL AND ' . $field . ' ' . $this->comparison . ' ' . XDB::format('{?}', $this->promo);
205 }
206 }
207 }
208
209 /** Filters users based on name
210 * @param $type Type of name field on which filtering is done (firstname, lastname, ...)
211 * @param $text Text on which to filter
212 * @param $mode flag indicating search type (prefix, suffix, with particule, ...)
213 */
214 class UFC_Name implements UserFilterCondition
215 {
216 const PREFIX = 1;
217 const SUFFIX = 2;
218 const PARTICLE = 7;
219 const VARIANTS = 8;
220 const CONTAINS = 3;
221
222 private $type;
223 private $text;
224 private $mode;
225
226 public function __construct($type, $text, $mode)
227 {
228 $this->type = $type;
229 $this->text = $text;
230 $this->mode = $mode;
231 }
232
233 private function buildNameQuery($type, $variant, $where, UserFilter &$uf)
234 {
235 $sub = $uf->addNameFilter($type, $variant);
236 return str_replace('$ME', 'pn' . $sub, $where);
237 }
238
239 public function buildCondition(UserFilter &$uf)
240 {
241 $left = '$ME.name';
242 $op = ' LIKE ';
243 if (($this->mode & self::PARTICLE) == self::PARTICLE) {
244 $left = 'CONCAT($ME.particle, \' \', $ME.name)';
245 }
246 if (($this->mode & self::CONTAINS) == 0) {
247 $right = XDB::format('{?}', $this->text);
248 $op = ' = ';
249 } else if (($this->mode & self::CONTAINS) == self::PREFIX) {
250 $right = XDB::format('CONCAT({?}, \'%\')', $this->text);
251 } else if (($this->mode & self::CONTAINS) == self::SUFFIX) {
252 $right = XDB::format('CONCAT(\'%\', {?})', $this->text);
253 } else {
254 $right = XDB::format('CONCAT(\'%\', {?}, \'%\')', $this->text);
255 }
256 $cond = $left . $op . $right;
257 $conds = array($this->buildNameQuery($this->type, null, $cond, $uf));
258 if (($this->mode & self::VARIANTS) != 0 && isset(UserFilter::$name_variants[$this->type])) {
259 foreach (UserFilter::$name_variants[$this->type] as $var) {
260 $conds[] = $this->buildNameQuery($this->type, $var, $cond, $uf);
261 }
262 }
263 return implode(' OR ', $conds);
264 }
265 }
266
267 /** Filters users based on death date
268 * @param $comparison Comparison operator
269 * @param $date Date to which death date should be compared
270 */
271 class UFC_Dead implements UserFilterCondition
272 {
273 private $comparison;
274 private $date;
275
276 public function __construct($comparison = null, $date = null)
277 {
278 $this->comparison = $comparison;
279 $this->date = $date;
280 }
281
282 public function buildCondition(UserFilter &$uf)
283 {
284 $str = 'p.deathdate IS NOT NULL';
285 if (!is_null($this->comparison)) {
286 $str .= ' AND p.deathdate ' . $this->comparison . ' ' . XDB::format('{?}', date('Y-m-d', $this->date));
287 }
288 return $str;
289 }
290 }
291
292 /** Filters users based on registration state
293 * @param $active Whether we want to use only "active" users (i.e with a valid redirection)
294 * @param $comparison Comparison operator
295 * @param $date Date to which users registration date should be compared
296 */
297 class UFC_Registered implements UserFilterCondition
298 {
299 private $active;
300 private $comparison;
301 private $date;
302
303 public function __construct($active = false, $comparison = null, $date = null)
304 {
305 $this->only_active = $active;
306 $this->comparison = $comparison;
307 $this->date = $date;
308 }
309
310 public function buildCondition(UserFilter &$uf)
311 {
312 if ($this->active) {
313 $date = 'a.uid IS NOT NULL AND a.state = \'active\'';
314 } else {
315 $date = 'a.uid IS NOT NULL AND a.state != \'pending\'';
316 }
317 if (!is_null($this->comparison)) {
318 $date .= ' AND a.registration_date ' . $this->comparison . ' ' . XDB::format('{?}', date('Y-m-d', $this->date));
319 }
320 return $date;
321 }
322 }
323
324 /** Filters users based on profile update date
325 * @param $comparison Comparison operator
326 * @param $date Date to which profile update date must be compared
327 */
328 class UFC_ProfileUpdated implements UserFilterCondition
329 {
330 private $comparison;
331 private $date;
332
333 public function __construct($comparison = null, $date = null)
334 {
335 $this->comparison = $comparison;
336 $this->date = $date;
337 }
338
339 public function buildCondition(UserFilter &$uf)
340 {
341 return 'p.last_change ' . $this->comparison . XDB::format(' {?}', date('Y-m-d H:i:s', $this->date));
342 }
343 }
344
345 /** Filters users based on next birthday date
346 * @param $comparison Comparison operator
347 * @param $date Date to which users next birthday date should be compared
348 */
349 class UFC_Birthday implements UserFilterCondition
350 {
351 private $comparison;
352 private $date;
353
354 public function __construct($comparison = null, $date = null)
355 {
356 $this->comparison = $comparison;
357 $this->date = $date;
358 }
359
360 public function buildCondition(UserFilter &$uf)
361 {
362 return 'p.next_birthday ' . $this->comparison . XDB::format(' {?}', date('Y-m-d', $this->date));
363 }
364 }
365
366 /** Filters users based on sex
367 * @parm $sex One of User::GENDER_MALE or User::GENDER_FEMALE, for selecting users
368 */
369 class UFC_Sex implements UserFilterCondition
370 {
371 private $sex;
372 public function __construct($sex)
373 {
374 $this->sex = $sex;
375 }
376
377 public function buildCondition(UserFilter &$uf)
378 {
379 if ($this->sex != User::GENDER_MALE && $this->sex != User::GENDER_FEMALE) {
380 return self::COND_FALSE;
381 } else {
382 return XDB::format('p.sex = {?}', $this->sex == User::GENDER_FEMALE ? 'female' : 'male');
383 }
384 }
385 }
386
387 /** Filters users based on group membership
388 * @param $group Group whose member we are selecting
389 * @param $admin Whether to restrict selection to admins of that group
390 */
391 class UFC_Group implements UserFilterCondition
392 {
393 private $group;
394 private $admin;
395 public function __construct($group, $admin = false)
396 {
397 $this->group = $group;
398 $this->admin = $admin;
399 }
400
401 public function buildCondition(UserFilter &$uf)
402 {
403 $sub = $uf->addGroupFilter($this->group);
404 $where = 'gpm' . $sub . '.perms IS NOT NULL';
405 if ($this->admin) {
406 $where .= ' AND gpm' . $sub . '.perms = \'admin\'';
407 }
408 return $where;
409 }
410 }
411
412 /** Filters users based on email address
413 * @param $email Email whose owner we are looking for
414 */
415 class UFC_Email implements UserFilterCondition
416 {
417 private $email;
418 public function __construct($email)
419 {
420 $this->email = $email;
421 }
422
423 public function buildCondition(UserFilter &$uf)
424 {
425 if (User::isForeignEmailAddress($this->email)) {
426 $sub = $uf->addEmailRedirectFilter($this->email);
427 return XDB::format('e' . $sub . '.email IS NOT NULL OR a.email = {?}', $this->email);
428 } else if (User::isVirtualEmailAddress($this->email)) {
429 $sub = $uf->addVirtualEmailFilter($this->email);
430 return 'vr' . $sub . '.redirect IS NOT NULL';
431 } else {
432 @list($user, $domain) = explode('@', $this->email);
433 $sub = $uf->addAliasFilter($user);
434 return 'al' . $sub . '.alias IS NOT NULL';
435 }
436 }
437 }
438
439 /** Filters users base on an email list
440 * @param $emails List of emails whose owner must be selected
441 */
442 class UFC_EmailList implements UserFilterCondition
443 {
444 private $emails;
445 public function __construct($emails)
446 {
447 $this->emails = $emails;
448 }
449
450 public function buildCondition(UserFilter &$uf)
451 {
452 $email = null;
453 $virtual = null;
454 $alias = null;
455 $cond = array();
456
457 if (count($this->emails) == 0) {
458 return UserFilterCondition::COND_TRUE;
459 }
460
461 foreach ($this->emails as $entry) {
462 if (User::isForeignEmailAddress($entry)) {
463 if (is_null($email)) {
464 $email = $uf->addEmailRedirectFilter();
465 }
466 $cond[] = XDB::format('e' . $email . '.email = {?} OR a.email = {?}', $entry, $entry);
467 } else if (User::isVirtualEmailAddress($entry)) {
468 if (is_null($virtual)) {
469 $virtual = $uf->addVirtualEmailFilter();
470 }
471 $cond[] = XDB::format('vr' . $virtual . '.redirect IS NOT NULL AND v' . $virtual . '.alias = {?}', $entry);
472 } else {
473 if (is_null($alias)) {
474 $alias = $uf->addAliasFilter();
475 }
476 @list($user, $domain) = explode('@', $entry);
477 $cond[] = XDB::format('al' . $alias . '.alias = {?}', $user);
478 }
479 }
480 return '(' . implode(') OR (', $cond) . ')';
481 }
482 }
483
484 /** Filters users based on their address
485 * @param $field Field of the address used for filtering (city, street, ...)
486 * @param $text Text for filter
487 * @param $mode Mode for search (PREFIX, SUFFIX, ...)
488 */
489 class UFC_Address implements UserFilterCondition
490 {
491 const PREFIX = 1;
492 const SUFFIX = 2;
493 const CONTAINS = 3;
494
495 private $field;
496 private $text;
497 private $mode;
498
499 public function __construct($field, $text, $mode)
500 {
501 $this->field = $field;
502 $this->text = $text;
503 $this->mode = $mode;
504 }
505
506 public function buildCondition(UserFilter &$uf)
507 {
508 $left = 'pa.' . $field;
509 $op = ' LIKE ';
510 if (($this->mode & self::CONTAINS) == 0) {
511 $right = XDB::format('{?}', $this->text);
512 $op = ' = ';
513 } else if (($this->mode & self::CONTAINS) == self::PREFIX) {
514 $right = XDB::format('CONCAT({?}, \'%\')', $this->text);
515 } else if (($this->mode & self::CONTAINS) == self::SUFFIX) {
516 $right = XDB::format('CONCAT(\'%\', {?})', $this->text);
517 } else {
518 $right = XDB::format('CONCAT(\'%\', {?}, \'%\')', $this->text);
519 }
520 $cond = $left . $op . $right;
521 $uf->addAddressFilter();
522 return $cond;
523 }
524 }
525
526 /** Filters users based on the corps they belong to
527 * @param $corps Corps we are looking for (abbreviation)
528 * @param $type Whether we search for original or current corps
529 */
530 class UFC_Corps implements UserFilterCondition
531 {
532 const CURRENT=1;
533 const ORIGIN=2;
534
535 private $corps;
536 private $type;
537
538 public function __construct($corps, $type = self::CURRENT)
539 {
540 $this->corps = $corps;
541 $this->type = $type;
542 }
543
544 public function buildCondition(UserFilter &$uf)
545 {
546 /** Tables shortcuts :
547 * pc for profile corps,
548 * pceo for profile_corps_enum - orginal
549 * pcec for profile_corps_enum - current
550 */
551 $sub = $uf->addCorpsFilter($this->type);
552 $cond = $sub . '.abbreviation = ' . $corps;
553 return $cond;
554 }
555 }
556
557 /** Filters users based on their rank in the corps
558 * @param $rank Rank we are looking for (abbreviation)
559 */
560 class UFC_Corps_Rank implements UserFilterCondition
561 {
562 private $rank;
563 public function __construct($rank)
564 {
565 $this->rank = $rank;
566 }
567
568 public function buildCondition(UserFilter &$uf)
569 {
570 /** Tables shortcuts :
571 * pcr for profile_corps_rank
572 */
573 $sub = $uf->addCorpsRankFilter();
574 $cond = $sub . '.abbreviation = ' . $rank;
575 return $cond;
576 }
577 }
578
579 /** Filters users based on a relation toward on user
580 * @param $user User to which searched users are related
581 */
582 abstract class UFC_UserRelated implements UserFilterCondition
583 {
584 protected $user;
585 public function __construct(PlUser &$user)
586 {
587 $this->user =& $user;
588 }
589 }
590
591 /** Filters users who belongs to selected user's contacts
592 */
593 class UFC_Contact extends UFC_UserRelated
594 {
595 public function buildCondition(UserFilter &$uf)
596 {
597 $sub = $uf->addContactFilter($this->user->id());
598 return 'c' . $sub . '.contact IS NOT NULL';
599 }
600 }
601
602 /** Filters users being watched by selected user
603 */
604 class UFC_WatchRegistration extends UFC_UserRelated
605 {
606 public function buildCondition(UserFilter &$uf)
607 {
608 if (!$this->user->watch('registration')) {
609 return UserFilterCondition::COND_FALSE;
610 }
611 $uids = $this->user->watchUsers();
612 if (count($uids) == 0) {
613 return UserFilterCondition::COND_FALSE;
614 } else {
615 return '$UID IN ' . XDB::formatArray($uids);
616 }
617 }
618 }
619
620 /** Filters users belonging to a promo watched by selected user
621 * @param $user Selected user (the one watching promo)
622 * @param $grade Formation the user is watching
623 */
624 class UFC_WatchPromo extends UFC_UserRelated
625 {
626 private $grade;
627 public function __construct(PlUser &$user, $grade = UserFilter::GRADE_ING)
628 {
629 parent::__construct($user);
630 $this->grade = $grade;
631 }
632
633 public function buildCondition(UserFilter &$uf)
634 {
635 $promos = $this->user->watchPromos();
636 if (count($promos) == 0) {
637 return UserFilterCondition::COND_FALSE;
638 } else {
639 $sube = $uf->addEducationFilter(true, $this->grade);
640 $field = 'pe' . $sube . '.' . UserFilter::promoYear($this->grade);
641 return $field . ' IN ' . XDB::formatArray($promos);
642 }
643 }
644 }
645
646 /** Filters users watched by selected user
647 */
648 class UFC_WatchContact extends UFC_Contact
649 {
650 public function buildCondition(UserFilter &$uf)
651 {
652 if (!$this->user->watchContacts()) {
653 return UserFilterCondition::COND_FALSE;
654 }
655 return parent::buildCondition($uf);
656 }
657 }
658
659
660 /******************
661 * ORDERS
662 ******************/
663
664 abstract class UserFilterOrder
665 {
666 protected $desc = false;
667 public function __construct($desc = false)
668 {
669 $this->desc = $desc;
670 }
671
672 public function buildSort(UserFilter &$uf)
673 {
674 $sel = $this->getSortTokens($uf);
675 if (!is_array($sel)) {
676 $sel = array($sel);
677 }
678 if ($this->desc) {
679 foreach ($sel as $k=>$s) {
680 $sel[$k] = $s . ' DESC';
681 }
682 }
683 return $sel;
684 }
685
686 abstract protected function getSortTokens(UserFilter &$uf);
687 }
688
689 /** Orders users by promo
690 * @param $grade Formation whose promo users should be sorted by (restricts results to users of that formation)
691 * @param $desc Whether sort is descending
692 */
693 class UFO_Promo extends UserFilterOrder
694 {
695 private $grade;
696
697 public function __construct($grade = null, $desc = false)
698 {
699 parent::__construct($desc);
700 $this->grade = $grade;
701 }
702
703 protected function getSortTokens(UserFilter &$uf)
704 {
705 if (UserFilter::isGrade($this->grade)) {
706 $sub = $uf->addEducationFilter($this->grade);
707 return 'pe' . $sub . '.' . UserFilter::promoYear($this->grade);
708 } else {
709 $sub = $uf->addDisplayFilter();
710 return 'pd' . $sub . '.promo';
711 }
712 }
713 }
714
715 /** Sorts users by name
716 * @param $type Type of name on which to sort (firstname, ...)
717 * @param $variant Variant of that name to user (marital, ordinary, ...)
718 * @param $particle Set to true if particles should be included in the sorting order
719 * @param $desc If sort order should be descending
720 */
721 class UFO_Name extends UserFilterOrder
722 {
723 private $type;
724 private $variant;
725 private $particle;
726
727 public function __construct($type, $variant = null, $particle = false, $desc = false)
728 {
729 parent::__construct($desc);
730 $this->type = $type;
731 $this->variant = $variant;
732 $this->particle = $particle;
733 }
734
735 protected function getSortTokens(UserFilter &$uf)
736 {
737 if (UserFilter::isDisplayName($this->type)) {
738 $sub = $uf->addDisplayFilter();
739 return 'pd' . $sub . '.' . $this->type;
740 } else {
741 $sub = $uf->addNameFilter($this->type, $this->variant);
742 if ($this->particle) {
743 return 'CONCAT(pn' . $sub . '.particle, \' \', pn' . $sub . '.name)';
744 } else {
745 return 'pn' . $sub . '.name';
746 }
747 }
748 }
749 }
750
751 /** Sorts users based on registration date
752 */
753 class UFO_Registration extends UserFilterOrder
754 {
755 protected function getSortTokens(UserFilter &$uf)
756 {
757 return 'a.registration_date';
758 }
759 }
760
761 /** Sorts users based on next birthday date
762 */
763 class UFO_Birthday extends UserFilterOrder
764 {
765 protected function getSortTokens(UserFilter &$uf)
766 {
767 return 'p.next_birthday';
768 }
769 }
770
771 /** Sorts users based on last profile update
772 */
773 class UFO_ProfileUpdate extends UserFilterOrder
774 {
775 protected function getSortTokens(UserFilter &$uf)
776 {
777 return 'p.last_change';
778 }
779 }
780
781 /** Sorts users based on death date
782 */
783 class UFO_Death extends UserFilterOrder
784 {
785 protected function getSortTokens(UserFilter &$uf)
786 {
787 return 'p.deathdate';
788 }
789 }
790
791
792 /***********************************
793 *********************************
794 USER FILTER CLASS
795 *********************************
796 ***********************************/
797
798 class UserFilter
799 {
800 static private $joinMethods = array();
801
802 private $root;
803 private $sort = array();
804 private $query = null;
805 private $orderby = null;
806
807 private $lastcount = null;
808
809 public function __construct($cond = null, $sort = null)
810 {
811 if (empty(self::$joinMethods)) {
812 $class = new ReflectionClass('UserFilter');
813 foreach ($class->getMethods() as $method) {
814 $name = $method->getName();
815 if (substr($name, -5) == 'Joins' && $name != 'buildJoins') {
816 self::$joinMethods[] = $name;
817 }
818 }
819 }
820 if (!is_null($cond)) {
821 if ($cond instanceof UserFilterCondition) {
822 $this->setCondition($cond);
823 }
824 }
825 if (!is_null($sort)) {
826 if ($sort instanceof UserFilterOrder) {
827 $this->addSort($sort);
828 } else if (is_array($sort)) {
829 foreach ($sort as $s) {
830 $this->addSort($s);
831 }
832 }
833 }
834 }
835
836 private function buildQuery()
837 {
838 if (is_null($this->orderby)) {
839 $orders = array();
840 foreach ($this->sort as $sort) {
841 $orders = array_merge($orders, $sort->buildSort($this));
842 }
843 if (count($orders) == 0) {
844 $this->orderby = '';
845 } else {
846 $this->orderby = 'ORDER BY ' . implode(', ', $orders);
847 }
848 }
849 if (is_null($this->query)) {
850 $where = $this->root->buildCondition($this);
851 $joins = $this->buildJoins();
852 $this->query = 'FROM accounts AS a
853 LEFT JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET(\'owner\', ap.perms))
854 LEFT JOIN profiles AS p ON (p.pid = ap.pid)
855 ' . $joins . '
856 WHERE (' . $where . ')';
857 }
858 }
859
860 private function formatJoin(array $joins)
861 {
862 $str = '';
863 foreach ($joins as $key => $infos) {
864 $mode = $infos[0];
865 $table = $infos[1];
866 if ($mode == 'inner') {
867 $str .= 'INNER JOIN ';
868 } else if ($mode == 'left') {
869 $str .= 'LEFT JOIN ';
870 } else {
871 Platal::page()->kill("Join mode error");
872 }
873 $str .= $table . ' AS ' . $key;
874 if (isset($infos[2])) {
875 $str .= ' ON (' . str_replace(array('$ME', '$PID', '$UID'), array($key, 'p.pid', 'a.uid'), $infos[2]) . ')';
876 }
877 $str .= "\n";
878 }
879 return $str;
880 }
881
882 private function buildJoins()
883 {
884 $joins = array();
885 foreach (self::$joinMethods as $method) {
886 $joins = array_merge($joins, $this->$method());
887 }
888 return $this->formatJoin($joins);
889 }
890
891 private function getUIDList($uids = null, $count = null, $offset = null)
892 {
893 $this->buildQuery();
894 $limit = '';
895 if (!is_null($count)) {
896 if (!is_null($offset)) {
897 $limit = XDB::format('LIMIT {?}, {?}', (int)$offset, (int)$count);
898 } else {
899 $limit = XDB::format('LIMIT {?}', (int)$count);
900 }
901 }
902 $cond = '';
903 if (!is_null($uids)) {
904 $cond = ' AND a.uid IN ' . XDB::formatArray($uids);
905 }
906 $fetched = XDB::fetchColumn('SELECT SQL_CALC_FOUND_ROWS a.uid
907 ' . $this->query . $cond . '
908 GROUP BY a.uid
909 ' . $this->orderby . '
910 ' . $limit);
911 $this->lastcount = (int)XDB::fetchOneCell('SELECT FOUND_ROWS()');
912 return $fetched;
913 }
914
915 /** Check that the user match the given rule.
916 */
917 public function checkUser(PlUser &$user)
918 {
919 $this->buildQuery();
920 $count = (int)XDB::fetchOneCell('SELECT COUNT(*)
921 ' . $this->query . XDB::format(' AND a.uid = {?}', $user->id()));
922 return $count == 1;
923 }
924
925 /** Filter a list of user to extract the users matching the rule.
926 */
927 public function filter(array $users, $count = null, $offset = null)
928 {
929 $this->buildQuery();
930 $table = array();
931 $uids = array();
932 foreach ($users as $user) {
933 if ($user instanceof PlUser) {
934 $uid = $user->id();
935 } else {
936 $uid = $user;
937 }
938 $uids[] = $uid;
939 $table[$uid] = $user;
940 }
941 $fetched = $this->getUIDList($uids, $count, $offset);
942 $output = array();
943 foreach ($fetched as $uid) {
944 $output[] = $table[$uid];
945 }
946 return $output;
947 }
948
949 public function getUIDs($count = null, $offset = null)
950 {
951 return $this->getUIDList(null, $count, $offset);
952 }
953
954 public function getUsers($count = null, $offset = null)
955 {
956 return User::getBulkUsersWithUIDs($this->getUIDs($count, $offset));
957 }
958
959 public function getTotalCount()
960 {
961 if (is_null($this->lastcount)) {
962 $this->buildQuery();
963 return (int)XDB::fetchOneCell('SELECT COUNT(DISTINCT a.uid)
964 ' . $this->query);
965 } else {
966 return $this->lastcount;
967 }
968 }
969
970 public function setCondition(UserFilterCondition &$cond)
971 {
972 $this->root =& $cond;
973 $this->query = null;
974 }
975
976 public function addSort(UserFilterOrder &$sort)
977 {
978 $this->sort[] = $sort;
979 $this->orderby = null;
980 }
981
982 static public function getLegacy($promo_min, $promo_max)
983 {
984 if ($promo_min != 0) {
985 $min = new UFC_Promo('>=', self::GRADE_ING, intval($promo_min));
986 } else {
987 $min = new UFC_True();
988 }
989 if ($promo_max != 0) {
990 $max = new UFC_Promo('<=', self::GRADE_ING, intval($promo_max));
991 } else {
992 $max = new UFC_True();
993 }
994 return new UserFilter(new UFC_And($min, $max));
995 }
996
997 static public function sortByName()
998 {
999 return array(new UFO_Name(self::LASTNAME), new UFO_Name(self::FIRSTNAME));
1000 }
1001
1002 static public function sortByPromo()
1003 {
1004 return array(new UFO_Promo(), new UFO_Name(self::LASTNAME), new UFO_Name(self::FIRSTNAME));
1005 }
1006
1007 static private function getDBSuffix($string)
1008 {
1009 return preg_replace('/[^a-z0-9]/i', '', $string);
1010 }
1011
1012
1013 private $option = 0;
1014 private function register_optional(array &$table, $val)
1015 {
1016 if (is_null($val)) {
1017 $sub = $this->option++;
1018 $index = null;
1019 } else {
1020 $sub = self::getDBSuffix($val);
1021 $index = $val;
1022 }
1023 $sub = '_' . $sub;
1024 $table[$sub] = $index;
1025 return $sub;
1026 }
1027
1028 /** DISPLAY
1029 */
1030 const DISPLAY = 'display';
1031 private $pd = false;
1032 public function addDisplayFilter()
1033 {
1034 $this->pd = true;
1035 return '';
1036 }
1037
1038 private function displayJoins()
1039 {
1040 if ($this->pd) {
1041 return array('pd' => array('left', 'profile_display', '$ME.pid = $PID'));
1042 } else {
1043 return array();
1044 }
1045 }
1046
1047 /** NAMES
1048 */
1049 /* name tokens */
1050 const LASTNAME = 'lastname';
1051 const FIRSTNAME = 'firstname';
1052 const NICKNAME = 'nickname';
1053 const PSEUDONYM = 'pseudonym';
1054 const NAME = 'name';
1055 /* name variants */
1056 const VN_MARITAL = 'marital';
1057 const VN_ORDINARY = 'ordinary';
1058 const VN_OTHER = 'other';
1059 const VN_INI = 'ini';
1060 /* display names */
1061 const DN_FULL = 'directory_name';
1062 const DN_DISPLAY = 'yourself';
1063 const DN_YOURSELF = 'yourself';
1064 const DN_DIRECTORY = 'directory_name';
1065 const DN_PRIVATE = 'private_name';
1066 const DN_PUBLIC = 'public_name';
1067 const DN_SHORT = 'short_name';
1068 const DN_SORT = 'sort_name';
1069
1070 static public $name_variants = array(
1071 self::LASTNAME => array(self::VN_MARITAL, self::VN_ORDINARY),
1072 self::FIRSTNAME => array(self::VN_ORDINARY, self::VN_INI, self::VN_OTHER)
1073 );
1074
1075 static public function assertName($name)
1076 {
1077 if (!Profile::getNameTypeId($name)) {
1078 Platal::page()->kill('Invalid name type');
1079 }
1080 }
1081
1082 static public function isDisplayName($name)
1083 {
1084 return $name == self::DN_FULL || $name == self::DN_DISPLAY
1085 || $name == self::DN_YOURSELF || $name == self::DN_DIRECTORY
1086 || $name == self::DN_PRIVATE || $name == self::DN_PUBLIC
1087 || $name == self::DN_SHORT || $name == self::DN_SORT;
1088 }
1089
1090 private $pn = array();
1091 public function addNameFilter($type, $variant = null)
1092 {
1093 if (!is_null($variant)) {
1094 $ft = $type . '_' . $variant;
1095 } else {
1096 $ft = $type;
1097 }
1098 $sub = '_' . $ft;
1099 self::assertName($ft);
1100
1101 if (!is_null($variant) && $variant == 'other') {
1102 $sub .= $this->option++;
1103 }
1104 $this->pn[$sub] = Profile::getNameTypeId($ft);
1105 return $sub;
1106 }
1107
1108 private function nameJoins()
1109 {
1110 $joins = array();
1111 foreach ($this->pn as $sub => $type) {
1112 $joins['pn' . $sub] = array('left', 'profile_name', '$ME.pid = $PID AND $ME.typeid = ' . $type);
1113 }
1114 return $joins;
1115 }
1116
1117
1118 /** EDUCATION
1119 */
1120 const GRADE_ING = 'Ing.';
1121 const GRADE_PHD = 'PhD';
1122 const GRADE_MST = 'M%';
1123 static public function isGrade($grade)
1124 {
1125 return $grade == self::GRADE_ING || $grade == self::GRADE_PHD || $grade == self::GRADE_MST;
1126 }
1127
1128 static public function assertGrade($grade)
1129 {
1130 if (!self::isGrade($grade)) {
1131 Platal::page()->killError("Diplôme non valide");
1132 }
1133 }
1134
1135 static public function promoYear($grade)
1136 {
1137 // XXX: Definition of promotion for phds and masters might change in near future.
1138 return ($grade == UserFilter::GRADE_ING) ? 'entry_year' : 'grad_year';
1139 }
1140
1141 private $pepe = array();
1142 private $with_pee = false;
1143 public function addEducationFilter($x = false, $grade = null)
1144 {
1145 if (!$x) {
1146 $index = $this->option;
1147 $sub = $this->option++;
1148 } else {
1149 self::assertGrade($grade);
1150 $index = $grade;
1151 $sub = $grade[0];
1152 $this->with_pee = true;
1153 }
1154 $sub = '_' . $sub;
1155 $this->pepe[$index] = $sub;
1156 return $sub;
1157 }
1158
1159 private function educationJoins()
1160 {
1161 $joins = array();
1162 if ($this->with_pee) {
1163 $joins['pee'] = array('inner', 'profile_education_enum', 'pee.abbreviation = \'X\'');
1164 }
1165 foreach ($this->pepe as $grade => $sub) {
1166 if ($this->isGrade($grade)) {
1167 $joins['pe' . $sub] = array('left', 'profile_education', '$ME.eduid = pee.id AND $ME.uid = $PID');
1168 $joins['pede' . $sub] = array('inner', 'profile_education_degree_enum', '$ME.id = pe' . $sub . '.degreeid AND $ME.abbreviation LIKE ' .
1169 XDB::format('{?}', $grade));
1170 } else {
1171 $joins['pe' . $sub] = array('left', 'profile_education', '$ME.uid = $PID');
1172 $joins['pee' . $sub] = array('inner', 'profile_education_enum', '$ME.id = pe' . $sub . '.eduid');
1173 $joins['pede' . $sub] = array('inner', 'profile_education_degree_enum', '$ME.id = pe' . $sub . '.degreeid');
1174 }
1175 }
1176 return $joins;
1177 }
1178
1179
1180 /** GROUPS
1181 */
1182 private $gpm = array();
1183 public function addGroupFilter($group = null)
1184 {
1185 if (!is_null($group)) {
1186 if (ctype_digit($group)) {
1187 $index = $sub = $group;
1188 } else {
1189 $index = $group;
1190 $sub = self::getDBSuffix($group);
1191 }
1192 } else {
1193 $sub = 'group_' . $this->option++;
1194 $index = null;
1195 }
1196 $sub = '_' . $sub;
1197 $this->gpm[$sub] = $index;
1198 return $sub;
1199 }
1200
1201 private function groupJoins()
1202 {
1203 $joins = array();
1204 foreach ($this->gpm as $sub => $key) {
1205 if (is_null($key)) {
1206 $joins['gpa' . $sub] = array('inner', 'groupex.asso');
1207 $joins['gpm' . $sub] = array('left', 'groupex.membres', '$ME.uid = $UID AND $ME.asso_id = gpa' . $sub . '.id');
1208 } else if (ctype_digit($key)) {
1209 $joins['gpm' . $sub] = array('left', 'groupex.membres', '$ME.uid = $UID AND $ME.asso_id = ' . $key);
1210 } else {
1211 $joins['gpa' . $sub] = array('inner', 'groupex.asso', XDB::format('$ME.diminutif = {?}', $key));
1212 $joins['gpm' . $sub] = array('left', 'groupex.membres', '$ME.uid = $UID AND $ME.asso_id = gpa' . $sub . '.id');
1213 }
1214 }
1215 return $joins;
1216 }
1217
1218 /** EMAILS
1219 */
1220 private $e = array();
1221 public function addEmailRedirectFilter($email = null)
1222 {
1223 return $this->register_optional($this->e, $email);
1224 }
1225
1226 private $ve = array();
1227 public function addVirtualEmailFilter($email = null)
1228 {
1229 $this->addAliasFilter(self::ALIAS_FORLIFE);
1230 return $this->register_optional($this->ve, $email);
1231 }
1232
1233 const ALIAS_BEST = 'bestalias';
1234 const ALIAS_FORLIFE = 'forlife';
1235 private $al = array();
1236 public function addAliasFilter($alias = null)
1237 {
1238 return $this->register_optional($this->al, $alias);
1239 }
1240
1241 private function emailJoins()
1242 {
1243 global $globals;
1244 $joins = array();
1245 foreach ($this->e as $sub=>$key) {
1246 if (is_null($key)) {
1247 $joins['e' . $sub] = array('left', 'emails', '$ME.uid = $UID AND $ME.flags != \'filter\'');
1248 } else {
1249 $joins['e' . $sub] = array('left', 'emails', XDB::format('$ME.uid = $UID AND $ME.flags != \'filter\' AND $ME.email = {?}', $key));
1250 }
1251 }
1252 foreach ($this->al as $sub=>$key) {
1253 if (is_null($key)) {
1254 $joins['al' . $sub] = array('left', 'aliases', '$ME.id = $UID AND $ME.type IN (\'alias\', \'a_vie\')');
1255 } else if ($key == self::ALIAS_BEST) {
1256 $joins['al' . $sub] = array('left', 'aliases', '$ME.id = $UID AND $ME.type IN (\'alias\', \'a_vie\') AND FIND_IN_SET(\'bestalias\', $ME.flags)');
1257 } else if ($key == self::ALIAS_FORLIFE) {
1258 $joins['al' . $sub] = array('left', 'aliases', '$ME.id = $UID AND $ME.type = \'a_vie\'');
1259 } else {
1260 $joins['al' . $sub] = array('left', 'aliases', XDB::format('$ME.id = $UID AND $ME.type IN (\'alias\', \'a_vie\') AND $ME.alias = {?}', $key));
1261 }
1262 }
1263 foreach ($this->ve as $sub=>$key) {
1264 if (is_null($key)) {
1265 $joins['v' . $sub] = array('left', 'virtual', '$ME.type = \'user\'');
1266 } else {
1267 $joins['v' . $sub] = array('left', 'virtual', XDB::format('$ME.type = \'user\' AND $ME.alias = {?}', $key));
1268 }
1269 $joins['vr' . $sub] = array('left', 'virtual_redirect', XDB::format('$ME.vid = v' . $sub . '.vid
1270 AND ($ME.redirect IN (CONCAT(al_forlife.alias, \'@\', {?}),
1271 CONCAT(al_forlife.alias, \'@\', {?}),
1272 a.email))',
1273 $globals->mail->domain, $globals->mail->domain2));
1274 }
1275 return $joins;
1276 }
1277
1278
1279 /** ADDRESSES
1280 */
1281 private $pa = false;
1282 public function addAddressFilter()
1283 {
1284 $this->pa = true;
1285 }
1286
1287 private function addressJoins()
1288 {
1289 $joins = array();
1290 if ($this->pa) {
1291 $joins['pa'] = array('left', 'profile_address', '$ME.PID = $PID');
1292 }
1293 return $joins;
1294 }
1295
1296
1297 /** CORPS
1298 */
1299
1300 private $pc = false;
1301 private $pce = array();
1302 private $pcr = false;
1303 public function addCorpsFilter($type)
1304 {
1305 $this->pc = true;
1306 if ($type == UFC_Corps::CURRENT) {
1307 $pce['pcec'] = 'current_corpsid';
1308 return 'pcec';
1309 } else if ($type == UFC_Corps::ORIGIN) {
1310 $pce['pceo'] = 'original_corpsid';
1311 return 'pceo';
1312 }
1313 }
1314
1315 public function addCorpsRankFilter()
1316 {
1317 $this->pc = true;
1318 $this->pcr = true;
1319 return 'pcr';
1320 }
1321
1322 private function corpsJoins()
1323 {
1324 $joins = array();
1325 if ($this->pc) {
1326 $joins['pc'] = array('left', 'profile_corps', '$ME.uid = $UID');
1327 }
1328 if ($this->pcr) {
1329 $joins['pcr'] = array('left', 'profile_corps_rank_enum', '$ME.id = pc.rankid');
1330 }
1331 foreach($this->pce as $sub => $field) {
1332 $joins[$sub] = array('left', 'profile_corps_enum', '$ME.id = pc.' . $field);
1333 }
1334 return $joins;
1335 }
1336
1337 /** CONTACTS
1338 */
1339 private $cts = array();
1340 public function addContactFilter($uid = null)
1341 {
1342 return $this->register_optional($this->cts, is_null($uid) ? null : 'user_' . $uid);
1343 }
1344
1345 private function contactJoins()
1346 {
1347 $joins = array();
1348 foreach ($this->cts as $sub=>$key) {
1349 if (is_null($key)) {
1350 $joins['c' . $sub] = array('left', 'contacts', '$ME.contact = $UID');
1351 } else {
1352 $joins['c' . $sub] = array('left', 'contacts', XDB::format('$ME.uid = {?} AND $ME.contact = $UID', substr($key, 5)));
1353 }
1354 }
1355 return $joins;
1356 }
1357
1358
1359 /** CARNET
1360 */
1361 private $wn = array();
1362 public function addWatchRegistrationFilter($uid = null)
1363 {
1364 return $this->register_optional($this->wn, is_null($uid) ? null : 'user_' . $uid);
1365 }
1366
1367 private $wp = array();
1368 public function addWatchPromoFilter($uid = null)
1369 {
1370 return $this->register_optional($this->wp, is_null($uid) ? null : 'user_' . $uid);
1371 }
1372
1373 private $w = array();
1374 public function addWatchFilter($uid = null)
1375 {
1376 return $this->register_optional($this->w, is_null($uid) ? null : 'user_' . $uid);
1377 }
1378
1379 private function watchJoins()
1380 {
1381 $joins = array();
1382 foreach ($this->w as $sub=>$key) {
1383 if (is_null($key)) {
1384 $joins['w' . $sub] = array('left', 'watch');
1385 } else {
1386 $joins['w' . $sub] = array('left', 'watch', XDB::format('$ME.uid = {?}', substr($key, 5)));
1387 }
1388 }
1389 foreach ($this->wn as $sub=>$key) {
1390 if (is_null($key)) {
1391 $joins['wn' . $sub] = array('left', 'watch_nonins', '$ME.ni_id = $UID');
1392 } else {
1393 $joins['wn' . $sub] = array('left', 'watch_nonins', XDB::format('$ME.uid = {?} AND $ME.ni_id = $UID', substr($key, 5)));
1394 }
1395 }
1396 foreach ($this->wn as $sub=>$key) {
1397 if (is_null($key)) {
1398 $joins['wn' . $sub] = array('left', 'watch_nonins', '$ME.ni_id = $UID');
1399 } else {
1400 $joins['wn' . $sub] = array('left', 'watch_nonins', XDB::format('$ME.uid = {?} AND $ME.ni_id = $UID', substr($key, 5)));
1401 }
1402 }
1403 foreach ($this->wp as $sub=>$key) {
1404 if (is_null($key)) {
1405 $joins['wp' . $sub] = array('left', 'watch_promo');
1406 } else {
1407 $joins['wp' . $sub] = array('left', 'watch_promo', XDB::format('$ME.uid = {?}', substr($key, 5)));
1408 }
1409 }
1410 return $joins;
1411 }
1412 }
1413
1414
1415 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1416 ?>