1c757b707be883e90ce2a589656bfd412ee4ed71
[platal.git] / classes / userfilter.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 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 /** This interface describe objects which filter users based
29 * on various parameters.
30 * The parameters of the filter must be given to the constructor.
31 * The buildCondition function is called by UserFilter when
32 * actually building the query. That function must call
33 * $uf->addWheteverFilter so that the UserFilter makes
34 * adequate joins. It must return the 'WHERE' condition to use
35 * with the filter.
36 */
37 interface UserFilterCondition extends PlFilterCondition
38 {
39 }
40 // }}}
41
42 // {{{ class UFC_HasProfile
43 /** Filters users who have a profile
44 */
45 class UFC_HasProfile implements UserFilterCondition
46 {
47 public function buildCondition(PlFilter &$uf)
48 {
49 $uf->requireProfiles();
50 return '$PID IS NOT NULL';
51 }
52 }
53 // }}}
54
55 // {{{ class UFC_Hruid
56 /** Filters users based on their hruid
57 * @param $val Either an hruid, or a list of those
58 */
59 class UFC_Hruid implements UserFilterCondition
60 {
61 private $hruids;
62
63 public function __construct()
64 {
65 $this->hruids = pl_flatten(func_get_args());
66 }
67
68 public function buildCondition(PlFilter &$uf)
69 {
70 $uf->requireAccounts();
71 return XDB::format('a.hruid IN {?}', $this->hruids);
72 }
73 }
74 // }}}
75
76 // {{{ class UFC_Hrpid
77 /** Filters users based on the hrpid of their profiles
78 * @param $val Either an hrpid, or a list of those
79 */
80 class UFC_Hrpid implements UserFilterCondition
81 {
82 private $hrpids;
83
84 public function __construct()
85 {
86 $this->hrpids = pl_flatten(func_get_args());
87 }
88
89 public function buildCondition(PlFilter &$uf)
90 {
91 $uf->requireProfiles();
92 return XDB::format('p.hrpid IN {?}', $this->hrpids);
93 }
94 }
95 // }}}
96
97 // {{{ class UFC_Ip
98 /** Filters users based on one of their last IPs
99 * @param $ip IP from which connection are checked
100 */
101 class UFC_Ip implements UserFilterCondition
102 {
103 private $ip;
104
105 public function __construct($ip)
106 {
107 $this->ip = $ip;
108 }
109
110 public function buildCondition(PlFilter &$uf)
111 {
112 $sub = $uf->addLoggerFilter();
113 $ip = ip_to_uint($this->ip);
114 return XDB::format($sub . '.ip = {?} OR ' . $sub . '.forward_ip = {?}', $ip, $ip);
115 }
116 }
117 // }}}
118
119 // {{{ class UFC_Comment
120 class UFC_Comment implements UserFilterCondition
121 {
122 private $text;
123
124 public function __construct($text)
125 {
126 $this->text = $text;
127 }
128
129 public function buildCondition(PlFilter &$uf)
130 {
131 $uf->requireProfiles();
132 return $uf->getVisibilityCondition('p.freetext_pub') . ' AND p.freetext ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->text);
133 }
134 }
135 // }}}
136
137 // {{{ class UFC_Promo
138 /** Filters users based on promotion
139 * @param $comparison Comparison operator (>, =, ...)
140 * @param $grade Formation on which to restrict, UserFilter::DISPLAY for "any formation"
141 * @param $promo Promotion on which the filter is based
142 */
143 class UFC_Promo implements UserFilterCondition
144 {
145
146 private $grade;
147 private $promo;
148 private $comparison;
149
150 public function __construct($comparison, $grade, $promo)
151 {
152 $this->grade = $grade;
153 $this->comparison = $comparison;
154 $this->promo = $promo;
155 if ($this->grade != UserFilter::DISPLAY) {
156 UserFilter::assertGrade($this->grade);
157 }
158 if ($this->grade == UserFilter::DISPLAY && $this->comparison != '=') {
159 // XXX: we might try to guess the grade from the first char of the promo and forbid only '<= 2004', but allow '<= X2004'
160 Platal::page()->killError("Il n'est pas possible d'appliquer la comparaison '" . $this->comparison . "' aux promotions sans spécifier de formation (X/M/D)");
161 }
162 }
163
164 public function buildCondition(PlFilter &$uf)
165 {
166 if ($this->grade == UserFilter::DISPLAY) {
167 $sub = $uf->addDisplayFilter();
168 return XDB::format('pd' . $sub . '.promo ' . $this->comparison . ' {?}', $this->promo);
169 } else {
170 $sub = $uf->addEducationFilter(true, $this->grade);
171 $field = 'pe' . $sub . '.' . UserFilter::promoYear($this->grade);
172 return $field . ' IS NOT NULL AND ' . $field . ' ' . $this->comparison . ' ' . XDB::format('{?}', $this->promo);
173 }
174 }
175 }
176 // }}}
177
178 // {{{ class UFC_SchoolId
179 /** Filters users based on their shoold identifier
180 * @param type Parameter type (Xorg, AX, School)
181 * @param value School id value
182 */
183 class UFC_SchoolId implements UserFilterCondition
184 {
185 const AX = 'ax';
186 const Xorg = 'xorg';
187 const School = 'school';
188
189 private $type;
190 private $id;
191
192 static public function assertType($type)
193 {
194 if ($type != self::AX && $type != self::Xorg && $type != self::School) {
195 Platal::page()->killError("Type de matricule invalide: $type");
196 }
197 }
198
199 public function __construct($type, $id)
200 {
201 $this->type = $type;
202 $this->id = $id;
203 self::assertType($type);
204 }
205
206 public function buildCondition(PlFilter &$uf)
207 {
208 $uf->requireProfiles();
209 $id = $this->id;
210 $type = $this->type;
211 if ($type == self::School) {
212 $type = self::Xorg;
213 $id = Profile::getXorgId($id);
214 }
215 return XDB::format('p.' . $type . '_id = {?}', $id);
216 }
217 }
218 // }}}
219
220 // {{{ class UFC_EducationSchool
221 /** Filters users by formation
222 * @param $val The formation to search (either ID or array of IDs)
223 */
224 class UFC_EducationSchool implements UserFilterCondition
225 {
226 private $val;
227
228 public function __construct()
229 {
230 $this->val = pl_flatten(func_get_args());
231 }
232
233 public function buildCondition(PlFilter &$uf)
234 {
235 $sub = $uf->addEducationFilter();
236 return XDB::format('pe' . $sub . '.eduid IN {?}', $this->val);
237 }
238 }
239 // }}}
240
241 // {{{ class UFC_EducationDegree
242 class UFC_EducationDegree implements UserFilterCondition
243 {
244 private $diploma;
245
246 public function __construct()
247 {
248 $this->diploma = pl_flatten(func_get_args());
249 }
250
251 public function buildCondition(PlFilter &$uf)
252 {
253 $sub = $uf->addEducationFilter();
254 return XDB::format('pe' . $sub . '.degreeid IN {?}', $this->diploma);
255 }
256 }
257 // }}}
258
259 // {{{ class UFC_EducationField
260 class UFC_EducationField implements UserFilterCondition
261 {
262 private $val;
263
264 public function __construct()
265 {
266 $this->val = pl_flatten(func_get_args());
267 }
268
269 public function buildCondition(PlFilter &$uf)
270 {
271 $sub = $uf->addEducationFilter();
272 return XDB::format('pe' . $sub . '.fieldid IN {?}', $this->val);
273 }
274 }
275 // }}}
276
277 // {{{ class UFC_Name
278 /** Filters users based on name
279 * @param $type Type of name field on which filtering is done (firstname, lastname...)
280 * @param $text Text on which to filter
281 * @param $mode Flag indicating search type (prefix, suffix, with particule...)
282 */
283 class UFC_Name implements UserFilterCondition
284 {
285 const EXACT = XDB::WILDCARD_EXACT; // 0x000
286 const PREFIX = XDB::WILDCARD_PREFIX; // 0x001
287 const SUFFIX = XDB::WILDCARD_SUFFIX; // 0x002
288 const CONTAINS = XDB::WILDCARD_CONTAINS; // 0x003
289 const PARTICLE = 0x004;
290 const VARIANTS = 0x008;
291
292 private $type;
293 private $text;
294 private $mode;
295
296 public function __construct($type, $text, $mode)
297 {
298 $this->type = $type;
299 $this->text = $text;
300 $this->mode = $mode;
301 }
302
303 private function buildNameQuery($type, $variant, $where, UserFilter &$uf)
304 {
305 $sub = $uf->addNameFilter($type, $variant);
306 return str_replace('$ME', 'pn' . $sub, $where);
307 }
308
309 public function buildCondition(PlFilter &$uf)
310 {
311 $left = '$ME.name';
312 if (($this->mode & self::PARTICLE) == self::PARTICLE) {
313 $left = 'CONCAT($ME.particle, \' \', $ME.name)';
314 }
315 $right = XDB::formatWildcards($this->mode & self::CONTAINS, $this->text);
316
317 $cond = $left . $right;
318 $conds = array($this->buildNameQuery($this->type, null, $cond, $uf));
319 if (($this->mode & self::VARIANTS) != 0 && isset(Profile::$name_variants[$this->type])) {
320 foreach (Profile::$name_variants[$this->type] as $var) {
321 $conds[] = $this->buildNameQuery($this->type, $var, $cond, $uf);
322 }
323 }
324 return implode(' OR ', $conds);
325 }
326 }
327 // }}}
328
329 // {{{ class UFC_NameTokens
330 /** Selects users based on tokens in their name (for quicksearch)
331 * @param $tokens An array of tokens to search
332 * @param $flags Flags the tokens must have (e.g 'public' for public search)
333 * @param $soundex (bool) Whether those tokens are fulltext or soundex
334 */
335 class UFC_NameTokens implements UserFilterCondition
336 {
337 /* Flags */
338 const FLAG_PUBLIC = 'public';
339
340 private $tokens;
341 private $flags;
342 private $soundex;
343 private $exact;
344
345 public function __construct($tokens, $flags = array(), $soundex = false, $exact = false)
346 {
347 if (is_array($tokens)) {
348 $this->tokens = $tokens;
349 } else {
350 $this->tokens = array($tokens);
351 }
352 if (is_array($flags)) {
353 $this->flags = $flags;
354 } else {
355 $this->flags = array($flags);
356 }
357 $this->soundex = $soundex;
358 $this->exact = $exact;
359 }
360
361 public function buildCondition(PlFilter &$uf)
362 {
363 $conds = array();
364 foreach ($this->tokens as $i => $token) {
365 $sub = $uf->addNameTokensFilter($token);
366 if ($this->soundex) {
367 $c = XDB::format($sub . '.soundex = {?}', $token);
368 } else if ($this->exact) {
369 $c = XDB::format($sub . '.token = {?}', $token);
370 } else {
371 $c = $sub . '.token ' . XDB::formatWildcards(XDB::WILDCARD_PREFIX, $token);
372 }
373 if ($this->flags != null) {
374 $c .= XDB::format(' AND ' . $sub . '.flags IN {?}', $this->flags);
375 }
376 $conds[] = $c;
377 }
378
379 return implode(' AND ', $conds);
380 }
381 }
382 // }}}
383
384 // {{{ class UFC_Nationality
385 class UFC_Nationality implements UserFilterCondition
386 {
387 private $val;
388
389 public function __construct()
390 {
391 $this->val = pl_flatten(func_get_args());
392 }
393
394 public function buildCondition(PlFilter &$uf)
395 {
396 $uf->requireProfiles();
397 $nat = XDB::formatArray($this->val);
398 $conds = array(
399 'p.nationality1 IN ' . $nat,
400 'p.nationality2 IN ' . $nat,
401 'p.nationality3 IN ' . $nat,
402 );
403 return implode(' OR ', $conds);
404 }
405 }
406 // }}}
407
408 // {{{ class UFC_Dead
409 /** Filters users based on death date
410 * @param $comparison Comparison operator
411 * @param $date Date to which death date should be compared (DateTime object, string or timestamp)
412 */
413 class UFC_Dead implements UserFilterCondition
414 {
415 private $comparison;
416 private $date;
417
418 public function __construct($comparison = null, $date = null)
419 {
420 $this->comparison = $comparison;
421 $this->date = make_datetime($date);
422 }
423
424 public function buildCondition(PlFilter &$uf)
425 {
426 $uf->requireProfiles();
427 $str = 'p.deathdate IS NOT NULL';
428 if (!is_null($this->comparison)) {
429 $str .= ' AND p.deathdate ' . $this->comparison . ' ' . XDB::format('{?}', $this->date->format('Y-m-d'));
430 }
431 return $str;
432 }
433 }
434 // }}}
435
436 // {{{ class UFC_Registered
437 /** Filters users based on registration state
438 * @param $active Whether we want to use only "active" users (i.e with a valid redirection)
439 * @param $comparison Comparison operator
440 * @param $date Date to which users registration date should be compared
441 */
442 class UFC_Registered implements UserFilterCondition
443 {
444 private $active;
445 private $comparison;
446 private $date;
447
448 public function __construct($active = false, $comparison = null, $date = null)
449 {
450 $this->active = $active;
451 $this->comparison = $comparison;
452 $this->date = make_datetime($date);
453 }
454
455 public function buildCondition(PlFilter &$uf)
456 {
457 $uf->requireAccounts();
458 if ($this->active) {
459 $date = '$UID IS NOT NULL AND a.state = \'active\'';
460 } else {
461 $date = '$UID IS NOT NULL AND a.state != \'pending\'';
462 }
463 if (!is_null($this->comparison)) {
464 $date .= ' AND a.registration_date != \'0000-00-00 00:00:00\' AND a.registration_date ' . $this->comparison . ' ' . XDB::format('{?}', $this->date->format('Y-m-d'));
465 }
466 return $date;
467 }
468 }
469 // }}}
470
471 // {{{ class UFC_ProfileUpdated
472 /** Filters users based on profile update date
473 * @param $comparison Comparison operator
474 * @param $date Date to which profile update date must be compared
475 */
476 class UFC_ProfileUpdated implements UserFilterCondition
477 {
478 private $comparison;
479 private $date;
480
481 public function __construct($comparison = null, $date = null)
482 {
483 $this->comparison = $comparison;
484 $this->date = $date;
485 }
486
487 public function buildCondition(PlFilter &$uf)
488 {
489 $uf->requireProfiles();
490 return 'p.last_change ' . $this->comparison . XDB::format(' {?}', date('Y-m-d H:i:s', $this->date));
491 }
492 }
493 // }}}
494
495 // {{{ class UFC_Birthday
496 /** Filters users based on next birthday date
497 * @param $comparison Comparison operator
498 * @param $date Date to which users next birthday date should be compared
499 */
500 class UFC_Birthday implements UserFilterCondition
501 {
502 private $comparison;
503 private $date;
504
505 public function __construct($comparison = null, $date = null)
506 {
507 $this->comparison = $comparison;
508 $this->date = $date;
509 }
510
511 public function buildCondition(PlFilter &$uf)
512 {
513 $uf->requireProfiles();
514 return 'p.next_birthday ' . $this->comparison . XDB::format(' {?}', date('Y-m-d', $this->date));
515 }
516 }
517 // }}}
518
519 // {{{ class UFC_Sex
520 /** Filters users based on sex
521 * @parm $sex One of User::GENDER_MALE or User::GENDER_FEMALE, for selecting users
522 */
523 class UFC_Sex implements UserFilterCondition
524 {
525 private $sex;
526 public function __construct($sex)
527 {
528 $this->sex = $sex;
529 }
530
531 public function buildCondition(PlFilter &$uf)
532 {
533 if ($this->sex != User::GENDER_MALE && $this->sex != User::GENDER_FEMALE) {
534 return self::COND_FALSE;
535 } else {
536 $uf->requireProfiles();
537 return XDB::format('p.sex = {?}', $this->sex == User::GENDER_FEMALE ? 'female' : 'male');
538 }
539 }
540 }
541 // }}}
542
543 // {{{ class UFC_Group
544 /** Filters users based on group membership
545 * @param $group Group whose members we are selecting
546 * @param $anim Whether to restrict selection to animators of that group
547 */
548 class UFC_Group implements UserFilterCondition
549 {
550 private $group;
551 private $anim;
552 public function __construct($group, $anim = false)
553 {
554 $this->group = $group;
555 $this->anim = $anim;
556 }
557
558 public function buildCondition(PlFilter &$uf)
559 {
560 // Groups have AX visibility.
561 if ($uf->getVisibilityLevel() == ProfileVisibility::VIS_PUBLIC) {
562 return PlFilter::COND_TRUE;
563 }
564 $sub = $uf->addGroupFilter($this->group);
565 $where = 'gpm' . $sub . '.perms IS NOT NULL';
566 if ($this->anim) {
567 $where .= ' AND gpm' . $sub . '.perms = \'admin\'';
568 }
569 return $where;
570 }
571 }
572 // }}}
573
574 // {{{ class UFC_Binet
575 /** Selects users based on their belonging to a given (list of) binet
576 * @param $binet either a binet_id or an array of binet_ids
577 */
578 class UFC_Binet implements UserFilterCondition
579 {
580 private $val;
581
582 public function __construct()
583 {
584 $this->val = pl_flatten(func_get_args());
585 }
586
587 public function buildCondition(PlFilter &$uf)
588 {
589 // Binets are private.
590 if ($uf->getVisibilityLevel() != ProfileVisibility::VIS_PRIVATE) {
591 return PlFilter::COND_TRUE;
592 }
593 $sub = $uf->addBinetsFilter();
594 return XDB::format($sub . '.binet_id IN {?}', $this->val);
595 }
596 }
597 // }}}
598
599 // {{{ class UFC_Section
600 /** Selects users based on section
601 * @param $section ID of the section
602 */
603 class UFC_Section implements UserFilterCondition
604 {
605 private $section;
606
607 public function __construct()
608 {
609 $this->section = pl_flatten(func_get_args());
610 }
611
612 public function buildCondition(PlFilter &$uf)
613 {
614 // Sections are private.
615 if ($uf->getVisibilityLevel() != ProfileVisibility::VIS_PRIVATE) {
616 return PlFilter::COND_TRUE;
617 }
618 $uf->requireProfiles();
619 return XDB::format('p.section IN {?}', $this->section);
620 }
621 }
622 // }}}
623
624 // {{{ class UFC_Email
625 /** Filters users based on an email or a list of emails
626 * @param $emails List of emails whose owner must be selected
627 */
628 class UFC_Email implements UserFilterCondition
629 {
630 private $emails;
631 public function __construct()
632 {
633 $this->emails = pl_flatten(func_get_args());
634 }
635
636 public function buildCondition(PlFilter &$uf)
637 {
638 $foreign = array();
639 $virtual = array();
640 $aliases = array();
641 $cond = array();
642
643 if (count($this->emails) == 0) {
644 return PlFilterCondition::COND_TRUE;
645 }
646
647 foreach ($this->emails as $entry) {
648 if (User::isForeignEmailAddress($entry)) {
649 $foreign[] = $entry;
650 } else if (User::isVirtualEmailAddress($entry)) {
651 $virtual[] = $entry;
652 } else {
653 @list($user, $domain) = explode('@', $entry);
654 $aliases[] = $user;
655 }
656 }
657
658 if (count($foreign) > 0) {
659 $sub = $uf->addEmailRedirectFilter($foreign);
660 $cond[] = XDB::format('e' . $sub . '.email IS NOT NULL OR a.email IN {?}', $foreign);
661 }
662 if (count($virtual) > 0) {
663 $sub = $uf->addVirtualEmailFilter($virtual);
664 $cond[] = 'vr' . $sub . '.redirect IS NOT NULL';
665 }
666 if (count($aliases) > 0) {
667 $sub = $uf->addAliasFilter($aliases);
668 $cond[] = 'al' . $sub . '.alias IS NOT NULL';
669 }
670 return '(' . implode(') OR (', $cond) . ')';
671 }
672 }
673 // }}}
674
675 // {{{ class UFC_Address
676 abstract class UFC_Address implements UserFilterCondition
677 {
678 /** Valid address type ('hq' is reserved for company addresses)
679 */
680 const TYPE_HOME = 1;
681 const TYPE_PRO = 2;
682 const TYPE_ANY = 3;
683
684 /** Text for these types
685 */
686 protected static $typetexts = array(
687 self::TYPE_HOME => 'home',
688 self::TYPE_PRO => 'pro',
689 );
690
691 protected $type;
692
693 /** Flags for addresses
694 */
695 const FLAG_CURRENT = 0x0001;
696 const FLAG_TEMP = 0x0002;
697 const FLAG_SECOND = 0x0004;
698 const FLAG_MAIL = 0x0008;
699 const FLAG_CEDEX = 0x0010;
700
701 // Binary OR of those flags
702 const FLAG_ANY = 0x001F;
703
704 /** Text of these flags
705 */
706 protected static $flagtexts = array(
707 self::FLAG_CURRENT => 'current',
708 self::FLAG_TEMP => 'temporary',
709 self::FLAG_SECOND => 'secondary',
710 self::FLAG_MAIL => 'mail',
711 self::FLAG_CEDEX => 'cedex',
712 );
713
714 protected $flags;
715
716 public function __construct($type = null, $flags = null)
717 {
718 $this->type = $type;
719 $this->flags = $flags;
720 }
721
722 protected function initConds($sub, $vis_cond)
723 {
724 $conds = array($vis_cond);
725
726 $types = array();
727 foreach (self::$typetexts as $flag => $type) {
728 if ($flag & $this->type) {
729 $types[] = $type;
730 }
731 }
732 if (count($types)) {
733 $conds[] = XDB::format($sub . '.type IN {?}', $types);
734 }
735
736 if ($this->flags != self::FLAG_ANY) {
737 foreach(self::$flagtexts as $flag => $text) {
738 if ($flag & $this->flags) {
739 $conds[] = 'FIND_IN_SET(' . XDB::format('{?}', $text) . ', ' . $sub . '.flags)';
740 }
741 }
742 }
743 return $conds;
744 }
745
746 }
747 // }}}
748
749 // {{{ class UFC_AddressText
750 /** Select users based on their address, using full text search
751 * @param $text Text for filter in fulltext search
752 * @param $textSearchMode Mode for search (one of XDB::WILDCARD_*)
753 * @param $type Filter on address type
754 * @param $flags Filter on address flags
755 * @param $country Filter on address country
756 * @param $locality Filter on address locality
757 */
758 class UFC_AddressText extends UFC_Address
759 {
760
761 private $text;
762 private $textSearchMode;
763
764 public function __construct($text = null, $textSearchMode = XDB::WILDCARD_CONTAINS,
765 $type = null, $flags = self::FLAG_ANY, $country = null, $locality = null)
766 {
767 parent::__construct($type, $flags);
768 $this->text = $text;
769 $this->textSearchMode = $textSearchMode;
770 $this->country = $country;
771 $this->locality = $locality;
772 }
773
774 private function mkMatch($txt)
775 {
776 return XDB::formatWildcards($this->textSearchMode, $txt);
777 }
778
779 public function buildCondition(PlFilter &$uf)
780 {
781 $sub = $uf->addAddressFilter();
782 $conds = $this->initConds($sub, $uf->getVisibilityCondition($sub . '.pub'));
783 if ($this->text != null) {
784 $conds[] = $sub . '.text' . $this->mkMatch($this->text);
785 }
786
787 if ($this->country != null) {
788 $subc = $uf->addAddressCountryFilter();
789 $subconds = array();
790 $subconds[] = $subc . '.country' . $this->mkMatch($this->country);
791 $subconds[] = $subc . '.countryFR' . $this->mkMatch($this->country);
792 $conds[] = implode(' OR ', $subconds);
793 }
794
795 if ($this->locality != null) {
796 $subl = $uf->addAddressLocalityFilter();
797 $conds[] = $subl . '.name' . $this->mkMatch($this->locality);
798 }
799
800 return implode(' AND ', $conds);
801 }
802 }
803 // }}}
804
805 // {{{ class UFC_AddressField
806 /** Filters users based on their address,
807 * @param $val Either a code for one of the fields, or an array of such codes
808 * @param $fieldtype The type of field to look for
809 * @param $type Filter on address type
810 * @param $flags Filter on address flags
811 */
812 class UFC_AddressField extends UFC_Address
813 {
814 const FIELD_COUNTRY = 1;
815 const FIELD_ADMAREA = 2;
816 const FIELD_SUBADMAREA = 3;
817 const FIELD_LOCALITY = 4;
818 const FIELD_ZIPCODE = 5;
819
820 /** Data of the filter
821 */
822 private $val;
823 private $fieldtype;
824
825 public function __construct($val, $fieldtype, $type = null, $flags = self::FLAG_ANY)
826 {
827 parent::__construct($type, $flags);
828
829 if (!is_array($val)) {
830 $val = array($val);
831 }
832 $this->val = $val;
833 $this->fieldtype = $fieldtype;
834 }
835
836 public function buildCondition(PlFilter &$uf)
837 {
838 $sub = $uf->addAddressFilter();
839 $conds = $this->initConds($sub, $uf->getVisibilityCondition($sub . '.pub'));
840
841 switch ($this->fieldtype) {
842 case self::FIELD_COUNTRY:
843 $field = 'countryId';
844 break;
845 case self::FIELD_ADMAREA:
846 $field = 'administrativeAreaId';
847 break;
848 case self::FIELD_SUBADMAREA:
849 $field = 'subAdministrativeAreaId';
850 break;
851 case self::FIELD_LOCALITY:
852 $field = 'localityId';
853 break;
854 case self::FIELD_ZIPCODE:
855 $field = 'postalCode';
856 break;
857 default:
858 Platal::page()->killError('Invalid address field type: ' . $this->fieldtype);
859 }
860 $conds[] = XDB::format($sub . '.' . $field . ' IN {?}', $this->val);
861
862 return implode(' AND ', $conds);
863 }
864 }
865 // }}}
866
867 // {{{ class UFC_Corps
868 /** Filters users based on the corps they belong to
869 * @param $corps Corps we are looking for (abbreviation)
870 * @param $type Whether we search for original or current corps
871 */
872 class UFC_Corps implements UserFilterCondition
873 {
874 const CURRENT = 1;
875 const ORIGIN = 2;
876
877 private $corps;
878 private $type;
879
880 public function __construct($corps, $type = self::CURRENT)
881 {
882 $this->corps = $corps;
883 $this->type = $type;
884 }
885
886 public function buildCondition(PlFilter &$uf)
887 {
888 /** Tables shortcuts:
889 * pc for profile_corps,
890 * pceo for profile_corps_enum - orginal
891 * pcec for profile_corps_enum - current
892 */
893 $sub = $uf->addCorpsFilter($this->type);
894 $cond = $sub . '.abbreviation = ' . $corps;
895 $cond .= ' AND ' . $uf->getVisibilityCondition($sub . '.corps_pub');
896 return $cond;
897 }
898 }
899 // }}}
900
901 // {{{ class UFC_Corps_Rank
902 /** Filters users based on their rank in the corps
903 * @param $rank Rank we are looking for (abbreviation)
904 */
905 class UFC_Corps_Rank implements UserFilterCondition
906 {
907 private $rank;
908 public function __construct($rank)
909 {
910 $this->rank = $rank;
911 }
912
913 public function buildCondition(PlFilter &$uf)
914 {
915 /** Tables shortcuts:
916 * pc for profile_corps
917 * pcr for profile_corps_rank
918 */
919 $sub = $uf->addCorpsRankFilter();
920 $cond = $sub . '.abbreviation = ' . $rank;
921 // XXX(x2006barrois): find a way to get rid of that hardcoded
922 // reference to 'pc'.
923 $cond .= ' AND ' . $uf->getVisibilityCondition('pc.corps_pub');
924 return $cond;
925 }
926 }
927 // }}}
928
929 // {{{ class UFC_Job_Company
930 /** Filters users based on the company they belong to
931 * @param $type The field being searched (self::JOBID, self::JOBNAME or self::JOBACRONYM)
932 * @param $value The searched value
933 */
934 class UFC_Job_Company implements UserFilterCondition
935 {
936 const JOBID = 'id';
937 const JOBNAME = 'name';
938 const JOBACRONYM = 'acronym';
939
940 private $type;
941 private $value;
942
943 public function __construct($type, $value)
944 {
945 $this->assertType($type);
946 $this->type = $type;
947 $this->value = $value;
948 }
949
950 private function assertType($type)
951 {
952 if ($type != self::JOBID && $type != self::JOBNAME && $type != self::JOBACRONYM) {
953 Platal::page()->killError("Type de recherche non valide.");
954 }
955 }
956
957 public function buildCondition(PlFilter &$uf)
958 {
959 $sub = $uf->addJobCompanyFilter();
960 $cond = $sub . '.' . $this->type . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->value);
961 $jsub = $uf->addJobFilter();
962 $cond .= ' AND ' . $uf->getVisibilityCondition($jsub . '.pub');
963 return $cond;
964 }
965 }
966 // }}}
967
968 // {{{ class UFC_Job_Sectorization
969 /** Filters users based on the ((sub)sub)sector they work in
970 * @param $val The ID of the sector, or an array of such IDs
971 * @param $type The kind of search (subsubsector/subsector/sector)
972 */
973 class UFC_Job_Sectorization implements UserFilterCondition
974 {
975 private $val;
976 private $type;
977
978 public function __construct($val, $type = UserFilter::JOB_SECTOR)
979 {
980 self::assertType($type);
981 if (!is_array($val)) {
982 $val = array($val);
983 }
984 $this->val = $val;
985 $this->type = $type;
986 }
987
988 private static function assertType($type)
989 {
990 if ($type != UserFilter::JOB_SECTOR && $type != UserFilter::JOB_SUBSECTOR && $type != UserFilter::JOB_SUBSUBSECTOR) {
991 Platal::page()->killError("Type de secteur non valide.");
992 }
993 }
994
995 public function buildCondition(PlFilter &$uf)
996 {
997 $sub = $uf->addJobSectorizationFilter($this->type);
998 $cond = $sub . '.id = ' . XDB::format('{?}', $this->val);
999 $jsub = $uf->addJobFilter();
1000 $cond .= ' AND ' . $uf->getVisibilityCondition($jsub . '.pub');
1001 return $cond;
1002 }
1003 }
1004 // }}}
1005
1006 // {{{ class UFC_Job_Terms
1007 /** Filters users based on the job terms they assigned to one of their
1008 * jobs.
1009 * @param $val The ID of the job term, or an array of such IDs
1010 */
1011 class UFC_Job_Terms implements UserFilterCondition
1012 {
1013 private $val;
1014
1015 public function __construct($val)
1016 {
1017 if (!is_array($val)) {
1018 $val = array($val);
1019 }
1020 $this->val = $val;
1021 }
1022
1023 public function buildCondition(PlFilter &$uf)
1024 {
1025 $sub = $uf->addJobTermsFilter(count($this->val));
1026 $conditions = array();
1027 foreach ($this->val as $i => $jtid) {
1028 $conditions[] = $sub[$i] . ' = ' . XDB::escape($jtid);
1029 }
1030 $jsub = $uf->addJobFilter();
1031 $conditions[] = $uf->getVisibilityCondition($jsub . '.pub');
1032 return implode(' AND ', $conditions);
1033 }
1034 }
1035 // }}}
1036
1037 // {{{ class UFC_Job_Description
1038 /** Filters users based on their job description
1039 * @param $description The text being searched for
1040 * @param $fields The fields to search for (user-defined, ((sub|)sub|)sector)
1041 */
1042 class UFC_Job_Description implements UserFilterCondition
1043 {
1044
1045 private $description;
1046 private $fields;
1047
1048 public function __construct($description, $fields)
1049 {
1050 $this->fields = $fields;
1051 $this->description = $description;
1052 }
1053
1054 public function buildCondition(PlFilter &$uf)
1055 {
1056 $conds = array();
1057
1058 $jsub = $uf->addJobFilter();
1059 // CV is private => if only CV requested, and not private,
1060 // don't do anything. Otherwise restrict to standard job visibility.
1061 if ($this->fields == UserFilter::JOB_CV) {
1062 if ($uf->getVisibilityLevel() != ProfileVisibility::VIS_PRIVATE) {
1063 return PlFilter::COND_TRUE;
1064 }
1065 } else {
1066 $conds[] = $uf->getVisibilityCondition($jsub . '.pub');
1067 }
1068
1069 if ($this->fields & UserFilter::JOB_USERDEFINED) {
1070 $conds[] = $jsub . '.description ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->description);
1071 }
1072 if ($this->fields & UserFilter::JOB_CV && $uf->getVisibilityLevel == ProfileVisibility::VIS_PRIVATE) {
1073 $uf->requireProfiles();
1074 $conds[] = 'p.cv ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->description);
1075 }
1076 if ($this->fields & UserFilter::JOB_SECTOR) {
1077 $sub = $uf->addJobSectorizationFilter(UserFilter::JOB_SECTOR);
1078 $conds[] = $sub . '.name ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->description);
1079 }
1080 if ($this->fields & UserFilter::JOB_SUBSECTOR) {
1081 $sub = $uf->addJobSectorizationFilter(UserFilter::JOB_SUBSECTOR);
1082 $conds[] = $sub . '.name ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->description);
1083 }
1084 if ($this->fields & UserFilter::JOB_SUBSUBSECTOR) {
1085 $sub = $uf->addJobSectorizationFilter(UserFilter::JOB_SUBSUBSECTOR);
1086 $conds[] = $sub . '.name ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->description);
1087 $sub = $uf->addJobSectorizationFilter(UserFilter::JOB_ALTERNATES);
1088 $conds[] = $sub . '.name ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->description);
1089 }
1090 return implode(' OR ', $conds);
1091 }
1092 }
1093 // }}}
1094
1095 // {{{ class UFC_Networking
1096 /** Filters users based on network identity (IRC, ...)
1097 * @param $type Type of network (-1 for any)
1098 * @param $value Value to search
1099 */
1100 class UFC_Networking implements UserFilterCondition
1101 {
1102 private $type;
1103 private $value;
1104
1105 public function __construct($type, $value)
1106 {
1107 $this->type = $type;
1108 $this->value = $value;
1109 }
1110
1111 public function buildCondition(PlFilter &$uf)
1112 {
1113 $sub = $uf->addNetworkingFilter();
1114 $conds = array();
1115 $conds[] = $uf->getVisibilityCondition($sub . '.pub');
1116 $conds[] = $sub . '.address ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->value);
1117 if ($this->type != -1) {
1118 $conds[] = $sub . '.nwid = ' . XDB::format('{?}', $this->type);
1119 }
1120 return implode(' AND ', $conds);
1121 }
1122 }
1123 // }}}
1124
1125 // {{{ class UFC_Phone
1126 /** Filters users based on their phone number
1127 * @param $num_type Type of number (pro/user/home)
1128 * @param $phone_type Type of phone (fixed/mobile/fax)
1129 * @param $number Phone number
1130 */
1131 class UFC_Phone implements UserFilterCondition
1132 {
1133 const NUM_PRO = 'pro';
1134 const NUM_USER = 'user';
1135 const NUM_HOME = 'address';
1136 const NUM_ANY = 'any';
1137
1138 const PHONE_FIXED = 'fixed';
1139 const PHONE_MOBILE = 'mobile';
1140 const PHONE_FAX = 'fax';
1141 const PHONE_ANY = 'any';
1142
1143 private $num_type;
1144 private $phone_type;
1145 private $number;
1146
1147 public function __construct($number, $num_type = self::NUM_ANY, $phone_type = self::PHONE_ANY)
1148 {
1149 $phone = new Phone(array('display' => $number));
1150 $phone->format();
1151 $this->number = $phone->search();
1152 $this->num_type = $num_type;
1153 $this->phone_type = $phone_type;
1154 }
1155
1156 public function buildCondition(PlFilter &$uf)
1157 {
1158 $sub = $uf->addPhoneFilter();
1159 $conds = array();
1160
1161 $conds[] = $uf->getVisibilityCondition($sub . '.pub');
1162
1163 $conds[] = $sub . '.search_tel = ' . XDB::format('{?}', $this->number);
1164 if ($this->num_type != self::NUM_ANY) {
1165 $conds[] = $sub . '.link_type = ' . XDB::format('{?}', $this->num_type);
1166 }
1167 if ($this->phone_type != self::PHONE_ANY) {
1168 $conds[] = $sub . '.tel_type = ' . XDB::format('{?}', $this->phone_type);
1169 }
1170 return implode(' AND ', $conds);
1171 }
1172 }
1173 // }}}
1174
1175 // {{{ class UFC_Medal
1176 /** Filters users based on their medals
1177 * @param $medal ID of the medal
1178 * @param $grade Grade of the medal (null for 'any')
1179 */
1180 class UFC_Medal implements UserFilterCondition
1181 {
1182 private $medal;
1183 private $grade;
1184
1185 public function __construct($medal, $grade = null)
1186 {
1187 $this->medal = $medal;
1188 $this->grade = $grade;
1189 }
1190
1191 public function buildCondition(PlFilter &$uf)
1192 {
1193 $conds = array();
1194
1195 // This will require profiles => table 'p' will be available.
1196 $sub = $uf->addMedalFilter();
1197
1198 $conds[] = $uf->getVisibilityCondition('p.medals_pub');
1199
1200 $conds[] = $sub . '.mid = ' . XDB::format('{?}', $this->medal);
1201 if ($this->grade != null) {
1202 $conds[] = $sub . '.gid = ' . XDB::format('{?}', $this->grade);
1203 }
1204 return implode(' AND ', $conds);
1205 }
1206 }
1207 // }}}
1208
1209 // {{{ class UFC_Photo
1210 /** Filters profiles with photo
1211 */
1212 class UFC_Photo implements UserFilterCondition
1213 {
1214 public function buildCondition(PlFilter &$uf)
1215 {
1216 $sub = $uf->addPhotoFilter();
1217 return $sub . '.attach IS NOT NULL AND ' . $uf->getVisibilityCondition($sub . '.pub');
1218 }
1219 }
1220 // }}}
1221
1222 // {{{ class UFC_Mentor_Expertise
1223 /** Filters users by mentoring expertise
1224 * @param $expertise Domain of expertise
1225 */
1226 class UFC_Mentor_Expertise implements UserFilterCondition
1227 {
1228 private $expertise;
1229
1230 public function __construct($expertise)
1231 {
1232 $this->expertise = $expertise;
1233 }
1234
1235 public function buildCondition(PlFilter &$uf)
1236 {
1237 $sub = $uf->addMentorFilter(UserFilter::MENTOR_EXPERTISE);
1238 return $sub . '.expertise ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->expertise);
1239 }
1240 }
1241 // }}}
1242
1243 // {{{ class UFC_Mentor_Country
1244 /** Filters users by mentoring country
1245 * @param $country Two-letters code of country being searched
1246 */
1247 class UFC_Mentor_Country implements UserFilterCondition
1248 {
1249 private $country;
1250
1251 public function __construct()
1252 {
1253 $this->country = pl_flatten(func_get_args());
1254 }
1255
1256 public function buildCondition(PlFilter &$uf)
1257 {
1258 $sub = $uf->addMentorFilter(UserFilter::MENTOR_COUNTRY);
1259 return $sub . '.country IN ' . XDB::format('{?}', $this->country);
1260 }
1261 }
1262 // }}}
1263
1264 // {{{ class UFC_Mentor_Terms
1265 /** Filters users based on the job terms they used in mentoring.
1266 * @param $val The ID of the job term, or an array of such IDs
1267 */
1268 class UFC_Mentor_Terms implements UserFilterCondition
1269 {
1270 private $val;
1271
1272 public function __construct($val)
1273 {
1274 $this->val = $val;
1275 }
1276
1277 public function buildCondition(PlFilter &$uf)
1278 {
1279 $sub = $uf->addMentorFilter(UserFilter::MENTOR_TERM);
1280 return $sub . '.jtid_1 = ' . XDB::escape($this->val);
1281 }
1282 }
1283 // }}}
1284
1285 // {{{ class UFC_Mentor_Sectorization
1286 /** Filters users based on mentoring (sub|)sector
1287 * @param $sector ID of (sub)sector
1288 * @param $type Whether we are looking for a sector or a subsector
1289 */
1290 class UFC_Mentor_Sectorization implements UserFilterCondition
1291 {
1292 const SECTOR = 1;
1293 const SUBSECTOR = 2;
1294 private $sector;
1295 private $type;
1296
1297 public function __construct($sector, $type = self::SECTOR)
1298 {
1299 $this->sector = $sector;
1300 $this->type = $type;
1301 }
1302
1303 public function buildCondition(PlFilter &$uf)
1304 {
1305 $sub = $uf->addMentorFilter(UserFilter::MENTOR_SECTOR);
1306 if ($this->type == self::SECTOR) {
1307 $field = 'sectorid';
1308 } else {
1309 $field = 'subsectorid';
1310 }
1311 return $sub . '.' . $field . ' = ' . XDB::format('{?}', $this->sector);
1312 }
1313 }
1314 // }}}
1315
1316 // {{{ class UFC_UserRelated
1317 /** Filters users based on a relation toward a user
1318 * @param $user User to which searched users are related
1319 */
1320 abstract class UFC_UserRelated implements UserFilterCondition
1321 {
1322 protected $user;
1323 public function __construct(PlUser &$user)
1324 {
1325 $this->user =& $user;
1326 }
1327 }
1328 // }}}
1329
1330 // {{{ class UFC_Contact
1331 /** Filters users who belong to selected user's contacts
1332 */
1333 class UFC_Contact extends UFC_UserRelated
1334 {
1335 public function buildCondition(PlFilter &$uf)
1336 {
1337 $sub = $uf->addContactFilter($this->user->id());
1338 return 'c' . $sub . '.contact IS NOT NULL';
1339 }
1340 }
1341 // }}}
1342
1343 // {{{ class UFC_WatchRegistration
1344 /** Filters users being watched by selected user
1345 */
1346 class UFC_WatchRegistration extends UFC_UserRelated
1347 {
1348 public function buildCondition(PlFilter &$uf)
1349 {
1350 if (!$this->user->watchType('registration')) {
1351 return PlFilterCondition::COND_FALSE;
1352 }
1353 $uids = $this->user->watchUsers();
1354 if (count($uids) == 0) {
1355 return PlFilterCondition::COND_FALSE;
1356 } else {
1357 return XDB::format('$UID IN {?}', $uids);
1358 }
1359 }
1360 }
1361 // }}}
1362
1363 // {{{ class UFC_WatchPromo
1364 /** Filters users belonging to a promo watched by selected user
1365 * @param $user Selected user (the one watching promo)
1366 * @param $grade Formation the user is watching
1367 */
1368 class UFC_WatchPromo extends UFC_UserRelated
1369 {
1370 private $grade;
1371 public function __construct(PlUser &$user, $grade = UserFilter::GRADE_ING)
1372 {
1373 parent::__construct($user);
1374 $this->grade = $grade;
1375 }
1376
1377 public function buildCondition(PlFilter &$uf)
1378 {
1379 $promos = $this->user->watchPromos();
1380 if (count($promos) == 0) {
1381 return PlFilterCondition::COND_FALSE;
1382 } else {
1383 $sube = $uf->addEducationFilter(true, $this->grade);
1384 $field = 'pe' . $sube . '.' . UserFilter::promoYear($this->grade);
1385 return XDB::format($field . ' IN {?}', $promos);
1386 }
1387 }
1388 }
1389 // }}}
1390
1391 // {{{ class UFC_WatchContact
1392 /** Filters users watched by selected user
1393 */
1394 class UFC_WatchContact extends UFC_Contact
1395 {
1396 public function buildCondition(PlFilter &$uf)
1397 {
1398 if (!$this->user->watchContacts()) {
1399 return PlFilterCondition::COND_FALSE;
1400 }
1401 return parent::buildCondition($uf);
1402 }
1403 }
1404 // }}}
1405
1406 // {{{ class UFC_MarketingHash
1407 /** Filters users using the hash generated
1408 * to send marketing emails to him.
1409 */
1410 class UFC_MarketingHash implements UserFilterCondition
1411 {
1412 private $hash;
1413
1414 public function __construct($hash)
1415 {
1416 $this->hash = $hash;
1417 }
1418
1419 public function buildCondition(PlFilter &$uf)
1420 {
1421 $table = $uf->addMarketingHash();
1422 return XDB::format('rm.hash = {?}', $this->hash);
1423 }
1424 }
1425 // }}}
1426
1427 /******************
1428 * ORDERS
1429 ******************/
1430
1431 // {{{ class UFO_Promo
1432 /** Orders users by promotion
1433 * @param $grade Formation whose promotion users should be sorted by (restricts results to users of that formation)
1434 * @param $desc Whether sort is descending
1435 */
1436 class UFO_Promo extends PlFilterGroupableOrder
1437 {
1438 private $grade;
1439
1440 public function __construct($grade = null, $desc = false)
1441 {
1442 parent::__construct($desc);
1443 $this->grade = $grade;
1444 }
1445
1446 protected function getSortTokens(PlFilter &$uf)
1447 {
1448 if (UserFilter::isGrade($this->grade)) {
1449 $sub = $uf->addEducationFilter($this->grade);
1450 return 'pe' . $sub . '.' . UserFilter::promoYear($this->grade);
1451 } else {
1452 $sub = $uf->addDisplayFilter();
1453 return 'pd' . $sub . '.promo';
1454 }
1455 }
1456 }
1457 // }}}
1458
1459 // {{{ class UFO_Name
1460 /** Sorts users by name
1461 * @param $type Type of name on which to sort (firstname...)
1462 * @param $variant Variant of that name to use (marital, ordinary...)
1463 * @param $particle Set to true if particles should be included in the sorting order
1464 * @param $desc If sort order should be descending
1465 */
1466 class UFO_Name extends PlFilterOrder
1467 {
1468 private $type;
1469 private $variant;
1470 private $particle;
1471
1472 public function __construct($type, $variant = null, $particle = false, $desc = false)
1473 {
1474 parent::__construct($desc);
1475 $this->type = $type;
1476 $this->variant = $variant;
1477 $this->particle = $particle;
1478 }
1479
1480 protected function getSortTokens(PlFilter &$uf)
1481 {
1482 if (Profile::isDisplayName($this->type)) {
1483 $sub = $uf->addDisplayFilter();
1484 $token = 'pd' . $sub . '.' . $this->type;
1485 if ($uf->accountsRequired()) {
1486 $account_token = Profile::getAccountEquivalentName($this->type);
1487 return 'IFNULL(' . $token . ', a.' . $account_token . ')';
1488 } else {
1489 return $token;
1490 }
1491 } else {
1492 $sub = $uf->addNameFilter($this->type, $this->variant);
1493 if ($this->particle) {
1494 return 'CONCAT(pn' . $sub . '.particle, \' \', pn' . $sub . '.name)';
1495 } else {
1496 return 'pn' . $sub . '.name';
1497 }
1498 }
1499 }
1500 }
1501 // }}}
1502
1503 // {{{ class UFO_Score
1504 class UFO_Score extends PlFilterOrder
1505 {
1506 protected function getSortTokens(PlFilter &$uf)
1507 {
1508 $toks = $uf->getNameTokens();
1509 $scores = array();
1510
1511 // If there weren't any sort tokens, we shouldn't sort by score, sort by NULL instead
1512 if (count($toks) == 0) {
1513 return 'NULL';
1514 }
1515
1516 foreach ($toks as $sub => $token) {
1517 $scores[] = XDB::format('SUM(' . $sub . '.score + IF (' . $sub . '.token = {?}, 5, 0) )', $token);
1518 }
1519 return implode(' + ', $scores);
1520 }
1521 }
1522 // }}}
1523
1524 // {{{ class UFO_Registration
1525 /** Sorts users based on registration date
1526 */
1527 class UFO_Registration extends PlFilterOrder
1528 {
1529 protected function getSortTokens(PlFilter &$uf)
1530 {
1531 $uf->requireAccounts();
1532 return 'a.registration_date';
1533 }
1534 }
1535 // }}}
1536
1537 // {{{ class UFO_Birthday
1538 /** Sorts users based on next birthday date
1539 */
1540 class UFO_Birthday extends PlFilterOrder
1541 {
1542 protected function getSortTokens(PlFilter &$uf)
1543 {
1544 $uf->requireProfiles();
1545 return 'p.next_birthday';
1546 }
1547 }
1548 // }}}
1549
1550 // {{{ class UFO_ProfileUpdate
1551 /** Sorts users based on last profile update
1552 */
1553 class UFO_ProfileUpdate extends PlFilterOrder
1554 {
1555 protected function getSortTokens(PlFilter &$uf)
1556 {
1557 $uf->requireProfiles();
1558 return 'p.last_change';
1559 }
1560 }
1561 // }}}
1562
1563 // {{{ class UFO_Death
1564 /** Sorts users based on death date
1565 */
1566 class UFO_Death extends PlFilterOrder
1567 {
1568 protected function getSortTokens(PlFilter &$uf)
1569 {
1570 $uf->requireProfiles();
1571 return 'p.deathdate';
1572 }
1573 }
1574 // }}}
1575
1576 // {{{ class UFO_Uid
1577 /** Sorts users based on their uid
1578 */
1579 class UFO_Uid extends PlFilterOrder
1580 {
1581 protected function getSortTokens(PlFilter &$uf)
1582 {
1583 $uf->requireAccounts();
1584 return '$UID';
1585 }
1586 }
1587 // }}}
1588
1589 // {{{ class UFO_Hruid
1590 /** Sorts users based on their hruid
1591 */
1592 class UFO_Hruid extends PlFilterOrder
1593 {
1594 protected function getSortTokens(PlFilter &$uf)
1595 {
1596 $uf->requireAccounts();
1597 return 'a.hruid';
1598 }
1599 }
1600 // }}}
1601
1602 // {{{ class UFO_Pid
1603 /** Sorts users based on their pid
1604 */
1605 class UFO_Pid extends PlFilterOrder
1606 {
1607 protected function getSortTokens(PlFilter &$uf)
1608 {
1609 $uf->requireProfiles();
1610 return '$PID';
1611 }
1612 }
1613 // }}}
1614
1615 // {{{ class UFO_Hrpid
1616 /** Sorts users based on their hrpid
1617 */
1618 class UFO_Hrpid extends PlFilterOrder
1619 {
1620 protected function getSortTokens(PlFilter &$uf)
1621 {
1622 $uf->requireProfiles();
1623 return 'p.hrpid';
1624 }
1625 }
1626 // }}}
1627
1628
1629 /***********************************
1630 *********************************
1631 USER FILTER CLASS
1632 *********************************
1633 ***********************************/
1634
1635 // {{{ class UserFilter
1636 /** This class provides a convenient and centralized way of filtering users.
1637 *
1638 * Usage:
1639 * $uf = new UserFilter(new UFC_Blah($x, $y), new UFO_Coin($z, $t));
1640 *
1641 * Resulting UserFilter can be used to:
1642 * - get a list of User objects matching the filter
1643 * - get a list of UIDs matching the filter
1644 * - get the number of users matching the filter
1645 * - check whether a given User matches the filter
1646 * - filter a list of User objects depending on whether they match the filter
1647 *
1648 * Usage for UFC and UFO objects:
1649 * A UserFilter will call all private functions named XXXJoins.
1650 * These functions must return an array containing the list of join
1651 * required by the various UFC and UFO associated to the UserFilter.
1652 * Entries in those returned array are of the following form:
1653 * 'join_tablealias' => array('join_type', 'joined_table', 'join_criter')
1654 * which will be translated into :
1655 * join_type JOIN joined_table AS join_tablealias ON (join_criter)
1656 * in the final query.
1657 *
1658 * In the join_criter text, $ME is replaced with 'join_tablealias', $PID with
1659 * profile.pid, and $UID with accounts.uid.
1660 *
1661 * For each kind of "JOIN" needed, a function named addXXXFilter() should be defined;
1662 * its parameter will be used to set various private vars of the UserFilter describing
1663 * the required joins ; such a function shall return the "join_tablealias" to use
1664 * when referring to the joined table.
1665 *
1666 * For example, if data from profile_job must be available to filter results,
1667 * the UFC object will call $uf-addJobFilter(), which will set the 'with_pj' var and
1668 * return 'pj', the short name to use when referring to profile_job; when building
1669 * the query, calling the jobJoins function will return an array containing a single
1670 * row:
1671 * 'pj' => array('left', 'profile_job', '$ME.pid = $UID');
1672 *
1673 * The 'register_optional' function can be used to generate unique table aliases when
1674 * the same table has to be joined several times with different aliases.
1675 */
1676 class UserFilter extends PlFilter
1677 {
1678 protected $joinMethods = array();
1679
1680 protected $joinMetas = array(
1681 '$PID' => 'p.pid',
1682 '$UID' => 'a.uid',
1683 );
1684
1685 private $root;
1686 private $sort = array();
1687 private $grouper = null;
1688 private $query = null;
1689 private $orderby = null;
1690
1691 // Store the current 'search' visibility.
1692 private $profile_visibility = null;
1693
1694 private $lastusercount = null;
1695 private $lastprofilecount = null;
1696
1697 public function __construct($cond = null, $sort = null)
1698 {
1699 if (empty($this->joinMethods)) {
1700 $class = new ReflectionClass('UserFilter');
1701 foreach ($class->getMethods() as $method) {
1702 $name = $method->getName();
1703 if (substr($name, -5) == 'Joins' && $name != 'buildJoins') {
1704 $this->joinMethods[] = $name;
1705 }
1706 }
1707 }
1708 if (!is_null($cond)) {
1709 if ($cond instanceof PlFilterCondition) {
1710 $this->setCondition($cond);
1711 }
1712 }
1713 if (!is_null($sort)) {
1714 if ($sort instanceof PlFilterOrder) {
1715 $this->addSort($sort);
1716 } else if (is_array($sort)) {
1717 foreach ($sort as $s) {
1718 $this->addSort($s);
1719 }
1720 }
1721 }
1722
1723 // This will set the visibility to the default correct level.
1724 $this->profile_visibility = new ProfileVisibility();
1725 }
1726
1727 public function getVisibilityLevels()
1728 {
1729 return $this->profile_visibility->levels();
1730 }
1731
1732 public function getVisibilityLevel()
1733 {
1734 return $this->profile_visibility->level();
1735 }
1736
1737 public function restrictVisibilityTo($level)
1738 {
1739 $this->profile_visibility->setLevel($level);
1740 }
1741
1742 public function getVisibilityCondition($field)
1743 {
1744 return $field . ' IN ' . XDB::formatArray($this->getVisibilityLevels());
1745 }
1746
1747 private function buildQuery()
1748 {
1749 // The root condition is built first because some orders need info
1750 // available only once all UFC have set their conditions (UFO_Score)
1751 if (is_null($this->query)) {
1752 $where = $this->root->buildCondition($this);
1753 $where = str_replace(array_keys($this->joinMetas),
1754 $this->joinMetas,
1755 $where);
1756 }
1757 if (is_null($this->orderby)) {
1758 $orders = array();
1759 foreach ($this->sort as $sort) {
1760 $orders = array_merge($orders, $sort->buildSort($this));
1761 }
1762 if (count($orders) == 0) {
1763 $this->orderby = '';
1764 } else {
1765 $this->orderby = 'ORDER BY ' . implode(', ', $orders);
1766 }
1767 $this->orderby = str_replace(array_keys($this->joinMetas),
1768 $this->joinMetas,
1769 $this->orderby);
1770 }
1771 if (is_null($this->query)) {
1772 if ($this->with_accounts) {
1773 $from = 'accounts AS a';
1774 } else {
1775 $this->requireProfiles();
1776 $from = 'profiles AS p';
1777 }
1778 $joins = $this->buildJoins();
1779 $this->query = 'FROM ' . $from . '
1780 ' . $joins . '
1781 WHERE (' . $where . ')';
1782 }
1783 }
1784
1785 public function hasGroups()
1786 {
1787 return $this->grouper != null;
1788 }
1789
1790 public function getGroups()
1791 {
1792 return $this->getUIDGroups();
1793 }
1794
1795 public function getUIDGroups()
1796 {
1797 $this->requireAccounts();
1798 $this->buildQuery();
1799 $token = $this->grouper->getGroupToken($this);
1800
1801 $groups = XDB::fetchAllRow('SELECT ' . $token . ', COUNT(a.uid)
1802 ' . $this->query . '
1803 GROUP BY ' . $token,
1804 0);
1805 return $groups;
1806 }
1807
1808 public function getPIDGroups()
1809 {
1810 $this->requireProfiles();
1811 $this->buildQuery();
1812 $token = $this->grouper->getGroupToken($this);
1813
1814 $groups = XDB::fetchAllRow('SELECT ' . $token . ', COUNT(p.pid)
1815 ' . $this->query . '
1816 GROUP BY ' . $token,
1817 0);
1818 return $groups;
1819 }
1820
1821 private function getUIDList($uids = null, PlLimit &$limit)
1822 {
1823 $this->requireAccounts();
1824 $this->buildQuery();
1825 $lim = $limit->getSql();
1826 $cond = '';
1827 if (!empty($uids)) {
1828 $cond = XDB::format(' AND a.uid IN {?}', $uids);
1829 }
1830 $fetched = XDB::fetchColumn('SELECT SQL_CALC_FOUND_ROWS a.uid
1831 ' . $this->query . $cond . '
1832 GROUP BY a.uid
1833 ' . $this->orderby . '
1834 ' . $lim);
1835 $this->lastusercount = (int)XDB::fetchOneCell('SELECT FOUND_ROWS()');
1836 return $fetched;
1837 }
1838
1839 private function getPIDList($pids = null, PlLimit &$limit)
1840 {
1841 $this->requireProfiles();
1842 $this->buildQuery();
1843 $lim = $limit->getSql();
1844 $cond = '';
1845 if (!is_null($pids)) {
1846 $cond = XDB::format(' AND p.pid IN {?}', $pids);
1847 }
1848 $fetched = XDB::fetchColumn('SELECT SQL_CALC_FOUND_ROWS p.pid
1849 ' . $this->query . $cond . '
1850 GROUP BY p.pid
1851 ' . $this->orderby . '
1852 ' . $lim);
1853 $this->lastprofilecount = (int)XDB::fetchOneCell('SELECT FOUND_ROWS()');
1854 return $fetched;
1855 }
1856
1857 private static function defaultLimit($limit) {
1858 if ($limit == null) {
1859 return new PlLimit();
1860 } else {
1861 return $limit;
1862 }
1863 }
1864
1865 /** Check that the user match the given rule.
1866 */
1867 public function checkUser(PlUser &$user)
1868 {
1869 $this->requireAccounts();
1870 $this->buildQuery();
1871 $count = (int)XDB::fetchOneCell('SELECT COUNT(*)
1872 ' . $this->query . XDB::format(' AND a.uid = {?}', $user->id()));
1873 return $count == 1;
1874 }
1875
1876 /** Check that the profile match the given rule.
1877 */
1878 public function checkProfile(Profile &$profile)
1879 {
1880 $this->requireProfiles();
1881 $this->buildQuery();
1882 $count = (int)XDB::fetchOneCell('SELECT COUNT(*)
1883 ' . $this->query . XDB::format(' AND p.pid = {?}', $profile->id()));
1884 return $count == 1;
1885 }
1886
1887 /** Default filter is on users
1888 */
1889 public function filter(array $users, $limit = null)
1890 {
1891 return $this->filterUsers($users, self::defaultLimit($limit));
1892 }
1893
1894 /** Filter a list of users to extract the users matching the rule.
1895 */
1896 public function filterUsers(array $users, $limit = null)
1897 {
1898 $limit = self::defaultLimit($limit);
1899 $this->requireAccounts();
1900 $this->buildQuery();
1901 $table = array();
1902 $uids = array();
1903 foreach ($users as $user) {
1904 if ($user instanceof PlUser) {
1905 $uid = $user->id();
1906 } else {
1907 $uid = $user;
1908 }
1909 $uids[] = $uid;
1910 $table[$uid] = $user;
1911 }
1912 $fetched = $this->getUIDList($uids, $limit);
1913 $output = array();
1914 foreach ($fetched as $uid) {
1915 $output[] = $table[$uid];
1916 }
1917 return $output;
1918 }
1919
1920 /** Filter a list of profiles to extract the users matching the rule.
1921 */
1922 public function filterProfiles(array $profiles, $limit = null)
1923 {
1924 $limit = self::defaultLimit($limit);
1925 $this->requireProfiles();
1926 $this->buildQuery();
1927 $table = array();
1928 $pids = array();
1929 foreach ($profiles as $profile) {
1930 if ($profile instanceof Profile) {
1931 $pid = $profile->id();
1932 } else {
1933 $pid = $profile;
1934 }
1935 $pids[] = $pid;
1936 $table[$pid] = $profile;
1937 }
1938 $fetched = $this->getPIDList($pids, $limit);
1939 $output = array();
1940 foreach ($fetched as $pid) {
1941 $output[] = $table[$pid];
1942 }
1943 return $output;
1944 }
1945
1946 public function getUIDs($limit = null)
1947 {
1948 $limit = self::defaultLimit($limit);
1949 return $this->getUIDList(null, $limit);
1950 }
1951
1952 public function getUID($pos = 0)
1953 {
1954 $uids =$this->getUIDList(null, new PlLimit(1, $pos));
1955 if (count($uids) == 0) {
1956 return null;
1957 } else {
1958 return $uids[0];
1959 }
1960 }
1961
1962 public function getPIDs($limit = null)
1963 {
1964 $limit = self::defaultLimit($limit);
1965 return $this->getPIDList(null, $limit);
1966 }
1967
1968 public function getPID($pos = 0)
1969 {
1970 $pids =$this->getPIDList(null, new PlLimit(1, $pos));
1971 if (count($pids) == 0) {
1972 return null;
1973 } else {
1974 return $pids[0];
1975 }
1976 }
1977
1978 public function getUsers($limit = null)
1979 {
1980 return User::getBulkUsersWithUIDs($this->getUIDs($limit));
1981 }
1982
1983 public function getUser($pos = 0)
1984 {
1985 $uid = $this->getUID($pos);
1986 if ($uid == null) {
1987 return null;
1988 } else {
1989 return User::getWithUID($uid);
1990 }
1991 }
1992
1993 public function iterUsers($limit = null)
1994 {
1995 return User::iterOverUIDs($this->getUIDs($limit));
1996 }
1997
1998 public function getProfiles($limit = null, $fields = 0x0000, $visibility = null)
1999 {
2000 return Profile::getBulkProfilesWithPIDs($this->getPIDs($limit), $fields, $visibility);
2001 }
2002
2003 public function getProfile($pos = 0, $fields = 0x0000, $visibility = null)
2004 {
2005 $pid = $this->getPID($pos);
2006 if ($pid == null) {
2007 return null;
2008 } else {
2009 return Profile::get($pid, $fields, $visibility);
2010 }
2011 }
2012
2013 public function iterProfiles($limit = null, $fields = 0x0000, $visibility = null)
2014 {
2015 return Profile::iterOverPIDs($this->getPIDs($limit), true, $fields, $visibility);
2016 }
2017
2018 public function get($limit = null)
2019 {
2020 return $this->getUsers($limit);
2021 }
2022
2023
2024 public function getTotalCount()
2025 {
2026 return $this->getTotalUserCount();
2027 }
2028
2029 public function getTotalUserCount()
2030 {
2031 if (is_null($this->lastusercount)) {
2032 $this->requireAccounts();
2033 $this->buildQuery();
2034 return (int)XDB::fetchOneCell('SELECT COUNT(DISTINCT a.uid)
2035 ' . $this->query);
2036 } else {
2037 return $this->lastusercount;
2038 }
2039 }
2040
2041 public function getTotalProfileCount()
2042 {
2043 if (is_null($this->lastprofilecount)) {
2044 $this->requireProfiles();
2045 $this->buildQuery();
2046 return (int)XDB::fetchOneCell('SELECT COUNT(DISTINCT p.pid)
2047 ' . $this->query);
2048 } else {
2049 return $this->lastprofilecount;
2050 }
2051 }
2052
2053 public function setCondition(PlFilterCondition &$cond)
2054 {
2055 $this->root =& $cond;
2056 $this->query = null;
2057 }
2058
2059 public function addSort(PlFilterOrder &$sort)
2060 {
2061 if (count($this->sort) == 0 && $sort instanceof PlFilterGroupableOrder)
2062 {
2063 $this->grouper = $sort;
2064 }
2065 $this->sort[] = $sort;
2066 $this->orderby = null;
2067 }
2068
2069 static public function getLegacy($promo_min, $promo_max)
2070 {
2071 if ($promo_min != 0) {
2072 $min = new UFC_Promo('>=', self::GRADE_ING, intval($promo_min));
2073 } else {
2074 $min = new PFC_True();
2075 }
2076 if ($promo_max != 0) {
2077 $max = new UFC_Promo('<=', self::GRADE_ING, intval($promo_max));
2078 } else {
2079 $max = new PFC_True();
2080 }
2081 return new UserFilter(new PFC_And($min, $max));
2082 }
2083
2084 static public function sortByName()
2085 {
2086 return array(new UFO_Name(Profile::LASTNAME), new UFO_Name(Profile::FIRSTNAME));
2087 }
2088
2089 static public function sortByPromo()
2090 {
2091 return array(new UFO_Promo(), new UFO_Name(Profile::LASTNAME), new UFO_Name(Profile::FIRSTNAME));
2092 }
2093
2094 static private function getDBSuffix($string)
2095 {
2096 if (is_array($string)) {
2097 if (count($string) == 1) {
2098 return self::getDBSuffix(array_pop($string));
2099 }
2100 return md5(implode('|', $string));
2101 } else {
2102 return preg_replace('/[^a-z0-9]/i', '', $string);
2103 }
2104 }
2105
2106
2107 /** Stores a new (and unique) table alias in the &$table table
2108 * @param &$table Array in which the table alias must be stored
2109 * @param $val Value which will then be used to build the join
2110 * @return Name of the newly created alias
2111 */
2112 private $option = 0;
2113 private function register_optional(array &$table, $val)
2114 {
2115 if (is_null($val)) {
2116 $sub = $this->option++;
2117 $index = null;
2118 } else {
2119 $sub = self::getDBSuffix($val);
2120 $index = $val;
2121 }
2122 $sub = '_' . $sub;
2123 $table[$sub] = $index;
2124 return $sub;
2125 }
2126
2127 /** PROFILE VS ACCOUNT
2128 */
2129 private $with_profiles = false;
2130 private $with_accounts = false;
2131 public function requireAccounts()
2132 {
2133 $this->with_accounts = true;
2134 }
2135
2136 public function accountsRequired()
2137 {
2138 return $this->with_accounts;
2139 }
2140
2141 public function requireProfiles()
2142 {
2143 $this->with_profiles = true;
2144 }
2145
2146 public function profilesRequired()
2147 {
2148 return $this->with_profiles;
2149 }
2150
2151 protected function accountJoins()
2152 {
2153 $joins = array();
2154 if ($this->with_profiles && $this->with_accounts) {
2155 $joins['ap'] = PlSqlJoin::left('account_profiles', '$ME.uid = $UID AND FIND_IN_SET(\'owner\', ap.perms)');
2156 $joins['p'] = PlSqlJoin::left('profiles', '$PID = ap.pid');
2157 }
2158 return $joins;
2159 }
2160
2161 /** DISPLAY
2162 */
2163 const DISPLAY = 'display';
2164 private $pd = false;
2165 public function addDisplayFilter()
2166 {
2167 $this->requireProfiles();
2168 $this->pd = true;
2169 return '';
2170 }
2171
2172 protected function displayJoins()
2173 {
2174 if ($this->pd) {
2175 return array('pd' => PlSqlJoin::left('profile_display', '$ME.pid = $PID'));
2176 } else {
2177 return array();
2178 }
2179 }
2180
2181 /** LOGGER
2182 */
2183
2184 private $with_logger = false;
2185 public function addLoggerFilter()
2186 {
2187 $this->with_logger = true;
2188 $this->requireAccounts();
2189 return 'ls';
2190 }
2191 protected function loggerJoins()
2192 {
2193 $joins = array();
2194 if ($this->with_logger) {
2195 $joins['ls'] = PlSqlJoin::left('log_sessions', '$ME.uid = $UID');
2196 }
2197 return $joins;
2198 }
2199
2200 /** NAMES
2201 */
2202
2203 static public function assertName($name)
2204 {
2205 if (!DirEnum::getID(DirEnum::NAMETYPES, $name)) {
2206 Platal::page()->kill('Invalid name type: ' . $name);
2207 }
2208 }
2209
2210 private $pn = array();
2211 public function addNameFilter($type, $variant = null)
2212 {
2213 $this->requireProfiles();
2214 if (!is_null($variant)) {
2215 $ft = $type . '_' . $variant;
2216 } else {
2217 $ft = $type;
2218 }
2219 $sub = '_' . $ft;
2220 self::assertName($ft);
2221
2222 if (!is_null($variant) && $variant == 'other') {
2223 $sub .= $this->option++;
2224 }
2225 $this->pn[$sub] = DirEnum::getID(DirEnum::NAMETYPES, $ft);
2226 return $sub;
2227 }
2228
2229 protected function nameJoins()
2230 {
2231 $joins = array();
2232 foreach ($this->pn as $sub => $type) {
2233 $joins['pn' . $sub] = PlSqlJoin::left('profile_name', '$ME.pid = $PID AND $ME.typeid = {?}', $type);
2234 }
2235 return $joins;
2236 }
2237
2238 /** NAMETOKENS
2239 */
2240 private $name_tokens = array();
2241 private $nb_tokens = 0;
2242
2243 public function addNameTokensFilter($token)
2244 {
2245 $this->requireProfiles();
2246 $sub = 'sn' . (1 + $this->nb_tokens);
2247 $this->nb_tokens++;
2248 $this->name_tokens[$sub] = $token;
2249 return $sub;
2250 }
2251
2252 protected function nameTokensJoins()
2253 {
2254 /* We don't return joins, since with_sn forces the SELECT to run on search_name first */
2255 $joins = array();
2256 foreach ($this->name_tokens as $sub => $token) {
2257 $joins[$sub] = PlSqlJoin::left('search_name', '$ME.pid = $PID');
2258 }
2259 return $joins;
2260 }
2261
2262 public function getNameTokens()
2263 {
2264 return $this->name_tokens;
2265 }
2266
2267 /** NATIONALITY
2268 */
2269
2270 private $with_nat = false;
2271 public function addNationalityFilter()
2272 {
2273 $this->with_nat = true;
2274 return 'ngc';
2275 }
2276
2277 protected function nationalityJoins()
2278 {
2279 $joins = array();
2280 if ($this->with_nat) {
2281 $joins['ngc'] = PlSqlJoin::left('geoloc_countries', '$ME.iso_3166_1_a2 = p.nationality1 OR $ME.iso_3166_1_a2 = p.nationality2 OR $ME.iso_3166_1_a2 = p.nationality3');
2282 }
2283 return $joins;
2284 }
2285
2286 /** EDUCATION
2287 */
2288 const GRADE_ING = 'Ing.';
2289 const GRADE_PHD = 'PhD';
2290 const GRADE_MST = 'M%';
2291 static public function isGrade($grade)
2292 {
2293 return ($grade !== 0) && ($grade == self::GRADE_ING || $grade == self::GRADE_PHD || $grade == self::GRADE_MST);
2294 }
2295
2296 static public function assertGrade($grade)
2297 {
2298 if (!self::isGrade($grade)) {
2299 Platal::page()->killError("DiplĂ´me non valide: $grade");
2300 }
2301 }
2302
2303 static public function promoYear($grade)
2304 {
2305 // XXX: Definition of promotion for phds and masters might change in near future.
2306 return ($grade == UserFilter::GRADE_ING) ? 'entry_year' : 'grad_year';
2307 }
2308
2309 private $pepe = array();
2310 private $with_pee = false;
2311 public function addEducationFilter($x = false, $grade = null)
2312 {
2313 $this->requireProfiles();
2314 if (!$x) {
2315 $index = $this->option;
2316 $sub = $this->option++;
2317 } else {
2318 self::assertGrade($grade);
2319 $index = $grade;
2320 $sub = $grade[0];
2321 $this->with_pee = true;
2322 }
2323 $sub = '_' . $sub;
2324 $this->pepe[$index] = $sub;
2325 return $sub;
2326 }
2327
2328 protected function educationJoins()
2329 {
2330 $joins = array();
2331 if ($this->with_pee) {
2332 $joins['pee'] = PlSqlJoin::inner('profile_education_enum', 'pee.abbreviation = \'X\'');
2333 }
2334 foreach ($this->pepe as $grade => $sub) {
2335 if ($this->isGrade($grade)) {
2336 $joins['pe' . $sub] = PlSqlJoin::left('profile_education', '$ME.eduid = pee.id AND $ME.pid = $PID');
2337 $joins['pede' . $sub] = PlSqlJoin::inner('profile_education_degree_enum', '$ME.id = pe' . $sub . '.degreeid AND $ME.abbreviation LIKE {?}', $grade);
2338 } else {
2339 $joins['pe' . $sub] = PlSqlJoin::left('profile_education', '$ME.pid = $PID');
2340 $joins['pee' . $sub] = PlSqlJoin::inner('profile_education_enum', '$ME.id = pe' . $sub . '.eduid');
2341 $joins['pede' . $sub] = PlSqlJoin::inner('profile_education_degree_enum', '$ME.id = pe' . $sub . '.degreeid');
2342 }
2343 }
2344 return $joins;
2345 }
2346
2347
2348 /** GROUPS
2349 */
2350 private $gpm = array();
2351 public function addGroupFilter($group = null)
2352 {
2353 $this->requireAccounts();
2354 if (!is_null($group)) {
2355 if (is_int($group) || ctype_digit($group)) {
2356 $index = $sub = $group;
2357 } else {
2358 $index = $group;
2359 $sub = self::getDBSuffix($group);
2360 }
2361 } else {
2362 $sub = 'group_' . $this->option++;
2363 $index = null;
2364 }
2365 $sub = '_' . $sub;
2366 $this->gpm[$sub] = $index;
2367 return $sub;
2368 }
2369
2370 protected function groupJoins()
2371 {
2372 $joins = array();
2373 foreach ($this->gpm as $sub => $key) {
2374 if (is_null($key)) {
2375 $joins['gpa' . $sub] = PlSqlJoin::inner('groups');
2376 $joins['gpm' . $sub] = PlSqlJoin::left('group_members', '$ME.uid = $UID AND $ME.asso_id = gpa' . $sub . '.id');
2377 } else if (is_int($key) || ctype_digit($key)) {
2378 $joins['gpm' . $sub] = PlSqlJoin::left('group_members', '$ME.uid = $UID AND $ME.asso_id = ' . $key);
2379 } else {
2380 $joins['gpa' . $sub] = PlSqlJoin::inner('groups', '$ME.diminutif = {?}', $key);
2381 $joins['gpm' . $sub] = PlSqlJoin::left('group_members', '$ME.uid = $UID AND $ME.asso_id = gpa' . $sub . '.id');
2382 }
2383 }
2384 return $joins;
2385 }
2386
2387 /** BINETS
2388 */
2389
2390 private $with_bi = false;
2391 private $with_bd = false;
2392 public function addBinetsFilter($with_enum = false)
2393 {
2394 $this->requireProfiles();
2395 $this->with_bi = true;
2396 if ($with_enum) {
2397 $this->with_bd = true;
2398 return 'bd';
2399 } else {
2400 return 'bi';
2401 }
2402 }
2403
2404 protected function binetsJoins()
2405 {
2406 $joins = array();
2407 if ($this->with_bi) {
2408 $joins['bi'] = PlSqlJoin::left('profile_binets', '$ME.pid = $PID');
2409 }
2410 if ($this->with_bd) {
2411 $joins['bd'] = PlSqlJoin::left('profile_binet_enum', '$ME.id = bi.binet_id');
2412 }
2413 return $joins;
2414 }
2415
2416 /** EMAILS
2417 */
2418 private $e = array();
2419 public function addEmailRedirectFilter($email = null)
2420 {
2421 $this->requireAccounts();
2422 return $this->register_optional($this->e, $email);
2423 }
2424
2425 private $ve = array();
2426 public function addVirtualEmailFilter($email = null)
2427 {
2428 $this->addAliasFilter(self::ALIAS_FORLIFE);
2429 return $this->register_optional($this->ve, $email);
2430 }
2431
2432 const ALIAS_BEST = 'bestalias';
2433 const ALIAS_FORLIFE = 'forlife';
2434 private $al = array();
2435 public function addAliasFilter($alias = null)
2436 {
2437 $this->requireAccounts();
2438 return $this->register_optional($this->al, $alias);
2439 }
2440
2441 protected function emailJoins()
2442 {
2443 global $globals;
2444 $joins = array();
2445 foreach ($this->e as $sub=>$key) {
2446 if (is_null($key)) {
2447 $joins['e' . $sub] = PlSqlJoin::left('emails', '$ME.uid = $UID AND $ME.flags != \'filter\'');
2448 } else {
2449 if (!is_array($key)) {
2450 $key = array($key);
2451 }
2452 $joins['e' . $sub] = PlSqlJoin::left('emails', '$ME.uid = $UID AND $ME.flags != \'filter\'
2453 AND $ME.email IN {?}', $key);
2454 }
2455 }
2456 foreach ($this->al as $sub=>$key) {
2457 if (is_null($key)) {
2458 $joins['al' . $sub] = PlSqlJoin::left('aliases', '$ME.uid = $UID AND $ME.type IN (\'alias\', \'a_vie\')');
2459 } else if ($key == self::ALIAS_BEST) {
2460 $joins['al' . $sub] = PlSqlJoin::left('aliases', '$ME.uid = $UID AND $ME.type IN (\'alias\', \'a_vie\') AND FIND_IN_SET(\'bestalias\', $ME.flags)');
2461 } else if ($key == self::ALIAS_FORLIFE) {
2462 $joins['al' . $sub] = PlSqlJoin::left('aliases', '$ME.uid = $UID AND $ME.type = \'a_vie\'');
2463 } else {
2464 if (!is_array($key)) {
2465 $key = array($key);
2466 }
2467 $joins['al' . $sub] = PlSqlJoin::left('aliases', '$ME.uid = $UID AND $ME.type IN (\'alias\', \'a_vie\')
2468 AND $ME.alias IN {?}', $key);
2469 }
2470 }
2471 foreach ($this->ve as $sub=>$key) {
2472 if (is_null($key)) {
2473 $joins['v' . $sub] = PlSqlJoin::left('virtual', '$ME.type = \'user\'');
2474 } else {
2475 if (!is_array($key)) {
2476 $key = array($key);
2477 }
2478 $joins['v' . $sub] = PlSqlJoin::left('virtual', '$ME.type = \'user\' AND $ME.alias IN {?}', $key);
2479 }
2480 $joins['vr' . $sub] = PlSqlJoin::left('virtual_redirect',
2481 '$ME.vid = v' . $sub . '.vid
2482 AND ($ME.redirect IN (CONCAT(al_forlife.alias, \'@\', {?}),
2483 CONCAT(al_forlife.alias, \'@\', {?}),
2484 a.email))',
2485 $globals->mail->domain, $globals->mail->domain2);
2486 }
2487 return $joins;
2488 }
2489
2490
2491 /** ADDRESSES
2492 */
2493 private $with_pa = false;
2494 public function addAddressFilter()
2495 {
2496 $this->requireProfiles();
2497 $this->with_pa = true;
2498 return 'pa';
2499 }
2500
2501 private $with_pac = false;
2502 public function addAddressCountryFilter()
2503 {
2504 $this->requireProfiles();
2505 $this->addAddressFilter();
2506 $this->with_pac = true;
2507 return 'gc';
2508 }
2509
2510 private $with_pal = false;
2511 public function addAddressLocalityFilter()
2512 {
2513 $this->requireProfiles();
2514 $this->addAddressFilter();
2515 $this->with_pal = true;
2516 return 'gl';
2517 }
2518
2519 protected function addressJoins()
2520 {
2521 $joins = array();
2522 if ($this->with_pa) {
2523 $joins['pa'] = PlSqlJoin::left('profile_addresses', '$ME.pid = $PID');
2524 }
2525 if ($this->with_pac) {
2526 $joins['gc'] = PlSqlJoin::left('geoloc_countries', '$ME.iso_3166_1_a2 = pa.countryID');
2527 }
2528 if ($this->with_pal) {
2529 $joins['gl'] = PlSqlJoin::left('geoloc_localities', '$ME.id = pa.localityID');
2530 }
2531 return $joins;
2532 }
2533
2534
2535 /** CORPS
2536 */
2537
2538 private $pc = false;
2539 private $pce = array();
2540 private $pcr = false;
2541 public function addCorpsFilter($type)
2542 {
2543 $this->requireProfiles();
2544 $this->pc = true;
2545 if ($type == UFC_Corps::CURRENT) {
2546 $pce['pcec'] = 'current_corpsid';
2547 return 'pcec';
2548 } else if ($type == UFC_Corps::ORIGIN) {
2549 $pce['pceo'] = 'original_corpsid';
2550 return 'pceo';
2551 }
2552 }
2553
2554 public function addCorpsRankFilter()
2555 {
2556 $this->requireProfiles();
2557 $this->pc = true;
2558 $this->pcr = true;
2559 return 'pcr';
2560 }
2561
2562 protected function corpsJoins()
2563 {
2564 $joins = array();
2565 if ($this->pc) {
2566 $joins['pc'] = PlSqlJoin::left('profile_corps', '$ME.pid = $PID');
2567 }
2568 if ($this->pcr) {
2569 $joins['pcr'] = PlSqlJoin::left('profile_corps_rank_enum', '$ME.id = pc.rankid');
2570 }
2571 foreach($this->pce as $sub => $field) {
2572 $joins[$sub] = PlSqlJoin::left('profile_corps_enum', '$ME.id = pc.' . $field);
2573 }
2574 return $joins;
2575 }
2576
2577 /** JOBS
2578 */
2579
2580 const JOB_SECTOR = 0x0001;
2581 const JOB_SUBSECTOR = 0x0002;
2582 const JOB_SUBSUBSECTOR = 0x0004;
2583 const JOB_ALTERNATES = 0x0008;
2584 const JOB_USERDEFINED = 0x0010;
2585 const JOB_CV = 0x0020;
2586
2587 const JOB_SECTORIZATION = 0x000F;
2588 const JOB_ANY = 0x003F;
2589
2590 /** Joins :
2591 * pj => profile_job
2592 * pje => profile_job_enum
2593 * pjse => profile_job_sector_enum
2594 * pjsse => profile_job_subsector_enum
2595 * pjssse => profile_job_subsubsector_enum
2596 * pja => profile_job_alternates
2597 * pjt => profile_job_terms
2598 */
2599 private $with_pj = false;
2600 private $with_pje = false;
2601 private $with_pjse = false;
2602 private $with_pjsse = false;
2603 private $with_pjssse = false;
2604 private $with_pja = false;
2605 private $with_pjt = 0;
2606
2607 public function addJobFilter()
2608 {
2609 $this->requireProfiles();
2610 $this->with_pj = true;
2611 return 'pj';
2612 }
2613
2614 public function addJobCompanyFilter()
2615 {
2616 $this->addJobFilter();
2617 $this->with_pje = true;
2618 return 'pje';
2619 }
2620
2621 public function addJobSectorizationFilter($type)
2622 {
2623 $this->addJobFilter();
2624 if ($type == self::JOB_SECTOR) {
2625 $this->with_pjse = true;
2626 return 'pjse';
2627 } else if ($type == self::JOB_SUBSECTOR) {
2628 $this->with_pjsse = true;
2629 return 'pjsse';
2630 } else if ($type == self::JOB_SUBSUBSECTOR) {
2631 $this->with_pjssse = true;
2632 return 'pjssse';
2633 } else if ($type == self::JOB_ALTERNATES) {
2634 $this->with_pja = true;
2635 return 'pja';
2636 }
2637 }
2638
2639 /**
2640 * Adds a filter on job terms of profile.
2641 * @param $nb the number of job terms to use
2642 * @return an array of the fields to filter (one for each term).
2643 * Code using this function should used returned field as is (contains table and field name).
2644 */
2645 public function addJobTermsFilter($nb = 1)
2646 {
2647 $this->with_pjt = $nb;
2648 $jobtermstable = array();
2649 for ($i = 1; $i <= $nb; ++$i) {
2650 $jobtermstable[] = 'pjtr_'.$i.'.jtid_1';
2651 }
2652 return $jobtermstable;
2653 }
2654
2655 protected function jobJoins()
2656 {
2657 $joins = array();
2658 if ($this->with_pj) {
2659 $joins['pj'] = PlSqlJoin::left('profile_job', '$ME.pid = $PID');
2660 }
2661 if ($this->with_pje) {
2662 $joins['pje'] = PlSqlJoin::left('profile_job_enum', '$ME.id = pj.jobid');
2663 }
2664 if ($this->with_pjse) {
2665 $joins['pjse'] = PlSqlJoin::left('profile_job_sector_enum', '$ME.id = pj.sectorid');
2666 }
2667 if ($this->with_pjsse) {
2668 $joins['pjsse'] = PlSqlJoin::left('profile_job_subsector_enum', '$ME.id = pj.subsectorid');
2669 }
2670 if ($this->with_pjssse) {
2671 $joins['pjssse'] = PlSqlJoin::left('profile_job_subsubsector_enum', '$ME.id = pj.subsubsectorid');
2672 }
2673 if ($this->with_pja) {
2674 $joins['pja'] = PlSqlJoin::left('profile_job_alternates', '$ME.subsubsectorid = pj.subsubsectorid');
2675 }
2676 if ($this->with_pjt > 0) {
2677 for ($i = 1; $i <= $this->with_pjt; ++$i) {
2678 $joins['pjt_'.$i] = PlSqlJoin::left('profile_job_term', '$ME.pid = $PID');
2679 $joins['pjtr_'.$i] = PlSqlJoin::left('profile_job_term_relation', '$ME.jtid_2 = pjt_'.$i.'.jtid');
2680 }
2681 }
2682 return $joins;
2683 }
2684
2685 /** NETWORKING
2686 */
2687
2688 private $with_pnw = false;
2689 public function addNetworkingFilter()
2690 {
2691 $this->requireAccounts();
2692 $this->with_pnw = true;
2693 return 'pnw';
2694 }
2695
2696 protected function networkingJoins()
2697 {
2698 $joins = array();
2699 if ($this->with_pnw) {
2700 $joins['pnw'] = PlSqlJoin::left('profile_networking', '$ME.pid = $PID');
2701 }
2702 return $joins;
2703 }
2704
2705 /** PHONE
2706 */
2707
2708 private $with_ptel = false;
2709
2710 public function addPhoneFilter()
2711 {
2712 $this->requireAccounts();
2713 $this->with_ptel = true;
2714 return 'ptel';
2715 }
2716
2717 protected function phoneJoins()
2718 {
2719 $joins = array();
2720 if ($this->with_ptel) {
2721 $joins['ptel'] = PlSqlJoin::left('profile_phones', '$ME.pid = $PID');
2722 }
2723 return $joins;
2724 }
2725
2726 /** MEDALS
2727 */
2728
2729 private $with_pmed = false;
2730 public function addMedalFilter()
2731 {
2732 $this->requireProfiles();
2733 $this->with_pmed = true;
2734 return 'pmed';
2735 }
2736
2737 protected function medalJoins()
2738 {
2739 $joins = array();
2740 if ($this->with_pmed) {
2741 $joins['pmed'] = PlSqlJoin::left('profile_medals', '$ME.pid = $PID');
2742 }
2743 return $joins;
2744 }
2745
2746 /** MENTORING
2747 */
2748
2749 private $pms = array();
2750 private $mjtr = false;
2751 const MENTOR_EXPERTISE = 1;
2752 const MENTOR_COUNTRY = 2;
2753 const MENTOR_SECTOR = 3;
2754 const MENTOR_TERM = 4;
2755
2756 public function addMentorFilter($type)
2757 {
2758 $this->requireAccounts();
2759 switch($type) {
2760 case self::MENTOR_EXPERTISE:
2761 $this->pms['pme'] = 'profile_mentor';
2762 return 'pme';
2763 case self::MENTOR_COUNTRY:
2764 $this->pms['pmc'] = 'profile_mentor_country';
2765 return 'pmc';
2766 case self::MENTOR_SECTOR:
2767 $this->pms['pms'] = 'profile_mentor_sector';
2768 return 'pms';
2769 case self::MENTOR_TERM:
2770 $this->pms['pmt'] = 'profile_mentor_term';
2771 $this->mjtr = true;
2772 return 'mjtr';
2773 default:
2774 Platal::page()->killError("Undefined mentor filter.");
2775 }
2776 }
2777
2778 protected function mentorJoins()
2779 {
2780 $joins = array();
2781 foreach ($this->pms as $sub => $tab) {
2782 $joins[$sub] = PlSqlJoin::left($tab, '$ME.pid = $PID');
2783 }
2784 if ($this->mjtr) {
2785 $joins['mjtr'] = PlSqlJoin::left('profile_job_term_relation', '$ME.jtid_2 = pmt.jtid');
2786 }
2787 return $joins;
2788 }
2789
2790 /** CONTACTS
2791 */
2792 private $cts = array();
2793 public function addContactFilter($uid = null)
2794 {
2795 $this->requireProfiles();
2796 return $this->register_optional($this->cts, is_null($uid) ? null : 'user_' . $uid);
2797 }
2798
2799 protected function contactJoins()
2800 {
2801 $joins = array();
2802 foreach ($this->cts as $sub=>$key) {
2803 if (is_null($key)) {
2804 $joins['c' . $sub] = PlSqlJoin::left('contacts', '$ME.contact = $PID');
2805 } else {
2806 $joins['c' . $sub] = PlSqlJoin::left('contacts', '$ME.uid = {?} AND $ME.contact = $PID', substr($key, 5));
2807 }
2808 }
2809 return $joins;
2810 }
2811
2812
2813 /** CARNET
2814 */
2815 private $wn = array();
2816 public function addWatchRegistrationFilter($uid = null)
2817 {
2818 $this->requireAccounts();
2819 return $this->register_optional($this->wn, is_null($uid) ? null : 'user_' . $uid);
2820 }
2821
2822 private $wp = array();
2823 public function addWatchPromoFilter($uid = null)
2824 {
2825 $this->requireAccounts();
2826 return $this->register_optional($this->wp, is_null($uid) ? null : 'user_' . $uid);
2827 }
2828
2829 private $w = array();
2830 public function addWatchFilter($uid = null)
2831 {
2832 $this->requireAccounts();
2833 return $this->register_optional($this->w, is_null($uid) ? null : 'user_' . $uid);
2834 }
2835
2836 protected function watchJoins()
2837 {
2838 $joins = array();
2839 foreach ($this->w as $sub=>$key) {
2840 if (is_null($key)) {
2841 $joins['w' . $sub] = PlSqlJoin::left('watch');
2842 } else {
2843 $joins['w' . $sub] = PlSqlJoin::left('watch', '$ME.uid = {?}', substr($key, 5));
2844 }
2845 }
2846 foreach ($this->wn as $sub=>$key) {
2847 if (is_null($key)) {
2848 $joins['wn' . $sub] = PlSqlJoin::left('watch_nonins', '$ME.ni_id = $UID');
2849 } else {
2850 $joins['wn' . $sub] = PlSqlJoin::left('watch_nonins', '$ME.uid = {?} AND $ME.ni_id = $UID', substr($key, 5));
2851 }
2852 }
2853 foreach ($this->wn as $sub=>$key) {
2854 if (is_null($key)) {
2855 $joins['wn' . $sub] = PlSqlJoin::left('watch_nonins', '$ME.ni_id = $UID');
2856 } else {
2857 $joins['wn' . $sub] = PlSqlJoin::left('watch_nonins', '$ME.uid = {?} AND $ME.ni_id = $UID', substr($key, 5));
2858 }
2859 }
2860 foreach ($this->wp as $sub=>$key) {
2861 if (is_null($key)) {
2862 $joins['wp' . $sub] = PlSqlJoin::left('watch_promo');
2863 } else {
2864 $joins['wp' . $sub] = PlSqlJoin::left('watch_promo', '$ME.uid = {?}', substr($key, 5));
2865 }
2866 }
2867 return $joins;
2868 }
2869
2870
2871 /** PHOTOS
2872 */
2873 private $with_photo;
2874 public function addPhotoFilter()
2875 {
2876 $this->requireProfiles();
2877 $this->with_photo = true;
2878 return 'photo';
2879 }
2880
2881 protected function photoJoins()
2882 {
2883 if ($this->with_photo) {
2884 return array('photo' => PlSqlJoin::left('profile_photos', '$ME.pid = $PID'));
2885 } else {
2886 return array();
2887 }
2888 }
2889
2890
2891 /** MARKETING
2892 */
2893 private $with_rm;
2894 public function addMarketingHash()
2895 {
2896 $this->requireAccounts();
2897 $this->with_rm = true;
2898 }
2899
2900 protected function marketingJoins()
2901 {
2902 if ($this->with_rm) {
2903 return array('rm' => PlSqlJoin::left('register_marketing', '$ME.uid = $UID'));
2904 } else {
2905 return array();
2906 }
2907 }
2908 }
2909 // }}}
2910
2911 // {{{ class ProfileFilter
2912 class ProfileFilter extends UserFilter
2913 {
2914 public function get($limit = null)
2915 {
2916 return $this->getProfiles($limit);
2917 }
2918
2919 public function filter(array $profiles, $limit = null)
2920 {
2921 return $this->filterProfiles($profiles, self::defaultLimit($limit));
2922 }
2923
2924 public function getTotalCount()
2925 {
2926 return $this->getTotalProfileCount();
2927 }
2928
2929 public function getGroups()
2930 {
2931 return $this->getPIDGroups();
2932 }
2933 }
2934 // }}}
2935
2936 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
2937 ?>