2 /***************************************************************************
3 * Copyright (C) 2003-2010 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
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
37 interface UserFilterCondition
extends PlFilterCondition
42 // {{{ class UFC_HasProfile
43 /** Filters users who have a profile
45 class UFC_HasProfile
implements UserFilterCondition
47 public function buildCondition(PlFilter
&$uf)
49 $uf->requireProfiles();
50 return '$PID IS NOT NULL';
55 // {{{ class UFC_Hruid
56 /** Filters users based on their hruid
57 * @param $val Either an hruid, or a list of those
59 class UFC_Hruid
implements UserFilterCondition
63 public function __construct()
65 $this->hruids
= pl_flatten(func_get_args());
68 public function buildCondition(PlFilter
&$uf)
70 $uf->requireAccounts();
71 return XDB
::format('a.hruid IN {?}', $this->hruids
);
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
80 class UFC_Hrpid
implements UserFilterCondition
84 public function __construct()
86 $this->hrpids
= pl_flatten(func_get_args());
89 public function buildCondition(PlFilter
&$uf)
91 $uf->requireProfiles();
92 return XDB
::format('p.hrpid IN {?}', $this->hrpids
);
98 /** Filters users based on one of their last IPs
99 * @param $ip IP from which connection are checked
101 class UFC_Ip
implements UserFilterCondition
105 public function __construct($ip)
110 public function buildCondition(PlFilter
&$uf)
112 $sub = $uf->addLoggerFilter();
113 $ip = ip_to_uint($this->ip
);
114 return XDB
::format($sub . '.ip = {?} OR ' . $sub . '.forward_ip = {?}', $ip, $ip);
119 // {{{ class UFC_Comment
120 class UFC_Comment
implements UserFilterCondition
124 public function __construct($text)
129 public function buildCondition(PlFilter
&$uf)
131 $uf->requireProfiles();
132 return 'p.freetext ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->text
);
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
143 class UFC_Promo
implements UserFilterCondition
150 public function __construct($comparison, $grade, $promo)
152 $this->grade
= $grade;
153 $this->comparison
= $comparison;
154 $this->promo
= $promo;
155 if ($this->grade
!= UserFilter
::DISPLAY
) {
156 UserFilter
::assertGrade($this->grade
);
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)");
164 public function buildCondition(PlFilter
&$uf)
166 if ($this->grade
== UserFilter
::DISPLAY
) {
167 $sub = $uf->addDisplayFilter();
168 return XDB
::format('pd' . $sub . '.promo ' . $this->comparison
. ' {?}', $this->promo
);
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
);
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
183 class UFC_SchoolId
implements UserFilterCondition
187 const School
= 'school';
192 static public function assertType($type)
194 if ($type != self
::AX
&& $type != self
::Xorg
&& $type != self
::School
) {
195 Platal
::page()->killError("Type de matricule invalide: $type");
199 public function __construct($type, $id)
203 self
::assertType($type);
206 public function buildCondition(PlFilter
&$uf)
208 $uf->requireProfiles();
211 if ($type == self
::School
) {
213 $id = Profile
::getXorgId($id);
215 return XDB
::format('p.' . $type . '_id = {?}', $id);
220 // {{{ class UFC_EducationSchool
221 /** Filters users by formation
222 * @param $val The formation to search (either ID or array of IDs)
224 class UFC_EducationSchool
implements UserFilterCondition
228 public function __construct()
230 $this->val
= pl_flatten(func_get_args());
233 public function buildCondition(PlFilter
&$uf)
235 $sub = $uf->addEducationFilter();
236 return XDB
::format('pe' . $sub . '.eduid IN {?}', $this->val
);
241 // {{{ class UFC_EducationDegree
242 class UFC_EducationDegree
implements UserFilterCondition
246 public function __construct()
248 $this->diploma
= pl_flatten(func_get_args());
251 public function buildCondition(PlFilter
&$uf)
253 $sub = $uf->addEducationFilter();
254 return XDB
::format('pe' . $sub . '.degreeid IN {?}', $this->diploma
);
259 // {{{ class UFC_EducationField
260 class UFC_EducationField
implements UserFilterCondition
264 public function __construct()
266 $this->val
= pl_flatten(func_get_args());
269 public function buildCondition(PlFilter
&$uf)
271 $sub = $uf->addEducationFilter();
272 return XDB
::format('pe' . $sub . '.fieldid IN {?}', $this->val
);
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...)
283 class UFC_Name
implements UserFilterCondition
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;
296 public function __construct($type, $text, $mode)
303 private function buildNameQuery($type, $variant, $where, UserFilter
&$uf)
305 $sub = $uf->addNameFilter($type, $variant);
306 return str_replace('$ME', 'pn' . $sub, $where);
309 public function buildCondition(PlFilter
&$uf)
312 if (($this->mode
& self
::PARTICLE
) == self
::PARTICLE
) {
313 $left = 'CONCAT($ME.particle, \' \', $ME.name)';
315 $right = XDB
::formatWildcards($this->mode
& self
::CONTAINS
, $this->text
);
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);
324 return implode(' OR ', $conds);
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
335 class UFC_NameTokens
implements UserFilterCondition
338 const FLAG_PUBLIC
= 'public';
345 public function __construct($tokens, $flags = array(), $soundex = false
, $exact = false
)
347 if (is_array($tokens)) {
348 $this->tokens
= $tokens;
350 $this->tokens
= array($tokens);
352 if (is_array($flags)) {
353 $this->flags
= $flags;
355 $this->flags
= array($flags);
357 $this->soundex
= $soundex;
358 $this->exact
= $exact;
361 public function buildCondition(PlFilter
&$uf)
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);
371 $c = $sub . '.token ' . XDB
::formatWildcards(XDB
::WILDCARD_PREFIX
, $token);
373 if ($this->flags
!= null
) {
374 $c .= XDB
::format(' AND ' . $sub . '.flags IN {?}', $this->flags
);
379 return implode(' AND ', $conds);
384 // {{{ class UFC_Nationality
385 class UFC_Nationality
implements UserFilterCondition
389 public function __construct()
391 $this->val
= pl_flatten(func_get_args());
394 public function buildCondition(PlFilter
&$uf)
396 $uf->requireProfiles();
397 $nat = XDB
::formatArray($this->val
);
399 'p.nationality1 IN ' . $nat,
400 'p.nationality2 IN ' . $nat,
401 'p.nationality3 IN ' . $nat,
403 return implode(' OR ', $conds);
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)
413 class UFC_Dead
implements UserFilterCondition
418 public function __construct($comparison = null
, $date = null
)
420 $this->comparison
= $comparison;
421 $this->date
= make_datetime($date);
424 public function buildCondition(PlFilter
&$uf)
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'));
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
442 class UFC_Registered
implements UserFilterCondition
448 public function __construct($active = false
, $comparison = null
, $date = null
)
450 $this->active
= $active;
451 $this->comparison
= $comparison;
452 $this->date
= make_datetime($date);
455 public function buildCondition(PlFilter
&$uf)
457 $uf->requireAccounts();
459 $date = '$UID IS NOT NULL AND a.state = \'active\'';
461 $date = '$UID IS NOT NULL AND a.state != \'pending\'';
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'));
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
476 class UFC_ProfileUpdated
implements UserFilterCondition
481 public function __construct($comparison = null
, $date = null
)
483 $this->comparison
= $comparison;
487 public function buildCondition(PlFilter
&$uf)
489 $uf->requireProfiles();
490 return 'p.last_change ' . $this->comparison
. XDB
::format(' {?}', date('Y-m-d H:i:s', $this->date
));
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
500 class UFC_Birthday
implements UserFilterCondition
505 public function __construct($comparison = null
, $date = null
)
507 $this->comparison
= $comparison;
511 public function buildCondition(PlFilter
&$uf)
513 $uf->requireProfiles();
514 return 'p.next_birthday ' . $this->comparison
. XDB
::format(' {?}', date('Y-m-d', $this->date
));
520 /** Filters users based on sex
521 * @parm $sex One of User::GENDER_MALE or User::GENDER_FEMALE, for selecting users
523 class UFC_Sex
implements UserFilterCondition
526 public function __construct($sex)
531 public function buildCondition(PlFilter
&$uf)
533 if ($this->sex
!= User
::GENDER_MALE
&& $this->sex
!= User
::GENDER_FEMALE
) {
534 return self
::COND_FALSE
;
536 $uf->requireProfiles();
537 return XDB
::format('p.sex = {?}', $this->sex
== User
::GENDER_FEMALE ?
'female' : 'male');
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
548 class UFC_Group
implements UserFilterCondition
552 public function __construct($group, $anim = false
)
554 $this->group
= $group;
558 public function buildCondition(PlFilter
&$uf)
560 $sub = $uf->addGroupFilter($this->group
);
561 $where = 'gpm' . $sub . '.perms IS NOT NULL';
563 $where .= ' AND gpm' . $sub . '.perms = \'admin\'';
570 // {{{ class UFC_Binet
571 /** Selects users based on their belonging to a given (list of) binet
572 * @param $binet either a binet_id or an array of binet_ids
574 class UFC_Binet
implements UserFilterCondition
578 public function __construct()
580 $this->val
= pl_flatten(func_get_args());
583 public function buildCondition(PlFilter
&$uf)
585 $sub = $uf->addBinetsFilter();
586 return XDB
::format($sub . '.binet_id IN {?}', $this->val
);
591 // {{{ class UFC_Section
592 /** Selects users based on section
593 * @param $section ID of the section
595 class UFC_Section
implements UserFilterCondition
599 public function __construct()
601 $this->section
= pl_flatten(func_get_args());
604 public function buildCondition(PlFilter
&$uf)
606 $uf->requireProfiles();
607 return XDB
::format('p.section IN {?}', $this->section
);
612 // {{{ class UFC_Email
613 /** Filters users based on an email or a list of emails
614 * @param $emails List of emails whose owner must be selected
616 class UFC_Email
implements UserFilterCondition
619 public function __construct()
621 $this->emails
= pl_flatten(func_get_args());
624 public function buildCondition(PlFilter
&$uf)
631 if (count($this->emails
) == 0) {
632 return PlFilterCondition
::COND_TRUE
;
635 foreach ($this->emails
as $entry) {
636 if (User
::isForeignEmailAddress($entry)) {
638 } else if (User
::isVirtualEmailAddress($entry)) {
641 @list
($user, $domain) = explode('@', $entry);
646 if (count($foreign) > 0) {
647 $sub = $uf->addEmailRedirectFilter($foreign);
648 $cond[] = XDB
::format('e' . $sub . '.email IS NOT NULL OR a.email IN {?}', $foreign);
650 if (count($virtual) > 0) {
651 $sub = $uf->addVirtualEmailFilter($virtual);
652 $cond[] = 'vr' . $sub . '.redirect IS NOT NULL';
654 if (count($aliases) > 0) {
655 $sub = $uf->addAliasFilter($aliases);
656 $cond[] = 'al' . $sub . '.alias IS NOT NULL';
658 return '(' . implode(') OR (', $cond) . ')';
663 // {{{ class UFC_Address
664 abstract class UFC_Address
implements UserFilterCondition
666 /** Valid address type ('hq' is reserved for company addresses)
672 /** Text for these types
674 protected static $typetexts = array(
675 self
::TYPE_HOME
=> 'home',
676 self
::TYPE_PRO
=> 'pro',
681 /** Flags for addresses
683 const FLAG_CURRENT
= 0x0001;
684 const FLAG_TEMP
= 0x0002;
685 const FLAG_SECOND
= 0x0004;
686 const FLAG_MAIL
= 0x0008;
687 const FLAG_CEDEX
= 0x0010;
689 // Binary OR of those flags
690 const FLAG_ANY
= 0x001F;
692 /** Text of these flags
694 protected static $flagtexts = array(
695 self
::FLAG_CURRENT
=> 'current',
696 self
::FLAG_TEMP
=> 'temporary',
697 self
::FLAG_SECOND
=> 'secondary',
698 self
::FLAG_MAIL
=> 'mail',
699 self
::FLAG_CEDEX
=> 'cedex',
704 public function __construct($type = null
, $flags = null
)
707 $this->flags
= $flags;
710 protected function initConds($sub)
714 foreach (self
::$typetexts as $flag => $type) {
715 if ($flag & $this->type
) {
720 $conds[] = XDB
::format($sub . '.type IN {?}', $types);
723 if ($this->flags
!= self
::FLAG_ANY
) {
724 foreach(self
::$flagtexts as $flag => $text) {
725 if ($flag & $this->flags
) {
726 $conds[] = 'FIND_IN_SET(' . XDB
::format('{?}', $text) . ', ' . $sub . '.flags)';
736 // {{{ class UFC_AddressText
737 /** Select users based on their address, using full text search
738 * @param $text Text for filter in fulltext search
739 * @param $textSearchMode Mode for search (one of XDB::WILDCARD_*)
740 * @param $type Filter on address type
741 * @param $flags Filter on address flags
742 * @param $country Filter on address country
743 * @param $locality Filter on address locality
745 class UFC_AddressText
extends UFC_Address
749 private $textSearchMode;
751 public function __construct($text = null
, $textSearchMode = XDB
::WILDCARD_CONTAINS
,
752 $type = null
, $flags = self
::FLAG_ANY
, $country = null
, $locality = null
)
754 parent
::__construct($type, $flags);
756 $this->textSearchMode
= $textSearchMode;
757 $this->country
= $country;
758 $this->locality
= $locality;
761 private function mkMatch($txt)
763 return XDB
::formatWildcards($this->textSearchMode
, $txt);
766 public function buildCondition(PlFilter
&$uf)
768 $sub = $uf->addAddressFilter();
769 $conds = $this->initConds($sub);
770 if ($this->text
!= null
) {
771 $conds[] = $sub . '.text' . $this->mkMatch($this->text
);
774 if ($this->country
!= null
) {
775 $subc = $uf->addAddressCountryFilter();
777 $subconds[] = $subc . '.country' . $this->mkMatch($this->country
);
778 $subconds[] = $subc . '.countryFR' . $this->mkMatch($this->country
);
779 $conds[] = implode(' OR ', $subconds);
782 if ($this->locality
!= null
) {
783 $subl = $uf->addAddressLocalityFilter();
784 $conds[] = $subl . '.name' . $this->mkMatch($this->locality
);
787 return implode(' AND ', $conds);
792 // {{{ class UFC_AddressField
793 /** Filters users based on their address,
794 * @param $val Either a code for one of the fields, or an array of such codes
795 * @param $fieldtype The type of field to look for
796 * @param $type Filter on address type
797 * @param $flags Filter on address flags
799 class UFC_AddressField
extends UFC_Address
801 const FIELD_COUNTRY
= 1;
802 const FIELD_ADMAREA
= 2;
803 const FIELD_SUBADMAREA
= 3;
804 const FIELD_LOCALITY
= 4;
805 const FIELD_ZIPCODE
= 5;
807 /** Data of the filter
812 public function __construct($val, $fieldtype, $type = null
, $flags = self
::FLAG_ANY
)
814 parent
::__construct($type, $flags);
816 if (!is_array($val)) {
820 $this->fieldtype
= $fieldtype;
823 public function buildCondition(PlFilter
&$uf)
825 $sub = $uf->addAddressFilter();
826 $conds = $this->initConds($sub);
828 switch ($this->fieldtype
) {
829 case self
::FIELD_COUNTRY
:
830 $field = 'countryId';
832 case self
::FIELD_ADMAREA
:
833 $field = 'administrativeAreaId';
835 case self
::FIELD_SUBADMAREA
:
836 $field = 'subAdministrativeAreaId';
838 case self
::FIELD_LOCALITY
:
839 $field = 'localityId';
841 case self
::FIELD_ZIPCODE
:
842 $field = 'postalCode';
845 Platal
::page()->killError('Invalid address field type: ' . $this->fieldtype
);
847 $conds[] = XDB
::format($sub . '.' . $field . ' IN {?}', $this->val
);
849 return implode(' AND ', $conds);
854 // {{{ class UFC_Corps
855 /** Filters users based on the corps they belong to
856 * @param $corps Corps we are looking for (abbreviation)
857 * @param $type Whether we search for original or current corps
859 class UFC_Corps
implements UserFilterCondition
867 public function __construct($corps, $type = self
::CURRENT
)
869 $this->corps
= $corps;
873 public function buildCondition(PlFilter
&$uf)
875 /** Tables shortcuts:
876 * pc for profile_corps,
877 * pceo for profile_corps_enum - orginal
878 * pcec for profile_corps_enum - current
880 $sub = $uf->addCorpsFilter($this->type
);
881 $cond = $sub . '.abbreviation = ' . $corps;
887 // {{{ class UFC_Corps_Rank
888 /** Filters users based on their rank in the corps
889 * @param $rank Rank we are looking for (abbreviation)
891 class UFC_Corps_Rank
implements UserFilterCondition
894 public function __construct($rank)
899 public function buildCondition(PlFilter
&$uf)
901 /** Tables shortcuts:
902 * pcr for profile_corps_rank
904 $sub = $uf->addCorpsRankFilter();
905 $cond = $sub . '.abbreviation = ' . $rank;
911 // {{{ class UFC_Job_Company
912 /** Filters users based on the company they belong to
913 * @param $type The field being searched (self::JOBID, self::JOBNAME or self::JOBACRONYM)
914 * @param $value The searched value
916 class UFC_Job_Company
implements UserFilterCondition
919 const JOBNAME
= 'name';
920 const JOBACRONYM
= 'acronym';
925 public function __construct($type, $value)
927 $this->assertType($type);
929 $this->value
= $value;
932 private function assertType($type)
934 if ($type != self
::JOBID
&& $type != self
::JOBNAME
&& $type != self
::JOBACRONYM
) {
935 Platal
::page()->killError("Type de recherche non valide.");
939 public function buildCondition(PlFilter
&$uf)
941 $sub = $uf->addJobCompanyFilter();
942 $cond = $sub . '.' . $this->type
. XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->value
);
948 // {{{ class UFC_Job_Sectorization
949 /** Filters users based on the ((sub)sub)sector they work in
950 * @param $val The ID of the sector, or an array of such IDs
951 * @param $type The kind of search (subsubsector/subsector/sector)
953 class UFC_Job_Sectorization
implements UserFilterCondition
958 public function __construct($val, $type = UserFilter
::JOB_SECTOR
)
960 self
::assertType($type);
961 if (!is_array($val)) {
968 private static function assertType($type)
970 if ($type != UserFilter
::JOB_SECTOR
&& $type != UserFilter
::JOB_SUBSECTOR
&& $type != UserFilter
::JOB_SUBSUBSECTOR
) {
971 Platal
::page()->killError("Type de secteur non valide.");
975 public function buildCondition(PlFilter
&$uf)
977 $sub = $uf->addJobSectorizationFilter($this->type
);
978 return $sub . '.id = ' . XDB
::format('{?}', $this->val
);
983 // {{{ class UFC_Job_Description
984 /** Filters users based on their job description
985 * @param $description The text being searched for
986 * @param $fields The fields to search for (user-defined, ((sub|)sub|)sector)
988 class UFC_Job_Description
implements UserFilterCondition
991 private $description;
994 public function __construct($description, $fields)
996 $this->fields
= $fields;
997 $this->description
= $description;
1000 public function buildCondition(PlFilter
&$uf)
1003 if ($this->fields
& UserFilter
::JOB_USERDEFINED
) {
1004 $sub = $uf->addJobFilter();
1005 $conds[] = $sub . '.description ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->description
);
1007 if ($this->fields
& UserFilter
::JOB_CV
) {
1008 $uf->requireProfiles();
1009 $conds[] = 'p.cv ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->description
);
1011 if ($this->fields
& UserFilter
::JOB_SECTOR
) {
1012 $sub = $uf->addJobSectorizationFilter(UserFilter
::JOB_SECTOR
);
1013 $conds[] = $sub . '.name ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->description
);
1015 if ($this->fields
& UserFilter
::JOB_SUBSECTOR
) {
1016 $sub = $uf->addJobSectorizationFilter(UserFilter
::JOB_SUBSECTOR
);
1017 $conds[] = $sub . '.name ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->description
);
1019 if ($this->fields
& UserFilter
::JOB_SUBSUBSECTOR
) {
1020 $sub = $uf->addJobSectorizationFilter(UserFilter
::JOB_SUBSUBSECTOR
);
1021 $conds[] = $sub . '.name ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->description
);
1022 $sub = $uf->addJobSectorizationFilter(UserFilter
::JOB_ALTERNATES
);
1023 $conds[] = $sub . '.name ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->description
);
1025 return implode(' OR ', $conds);
1030 // {{{ class UFC_Networking
1031 /** Filters users based on network identity (IRC, ...)
1032 * @param $type Type of network (-1 for any)
1033 * @param $value Value to search
1035 class UFC_Networking
implements UserFilterCondition
1040 public function __construct($type, $value)
1042 $this->type
= $type;
1043 $this->value
= $value;
1046 public function buildCondition(PlFilter
&$uf)
1048 $sub = $uf->addNetworkingFilter();
1050 $conds[] = $sub . '.address ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->value
);
1051 if ($this->type
!= -1) {
1052 $conds[] = $sub . '.nwid = ' . XDB
::format('{?}', $this->type
);
1054 return implode(' AND ', $conds);
1059 // {{{ class UFC_Phone
1060 /** Filters users based on their phone number
1061 * @param $num_type Type of number (pro/user/home)
1062 * @param $phone_type Type of phone (fixed/mobile/fax)
1063 * @param $number Phone number
1065 class UFC_Phone
implements UserFilterCondition
1067 const NUM_PRO
= 'pro';
1068 const NUM_USER
= 'user';
1069 const NUM_HOME
= 'address';
1070 const NUM_ANY
= 'any';
1072 const PHONE_FIXED
= 'fixed';
1073 const PHONE_MOBILE
= 'mobile';
1074 const PHONE_FAX
= 'fax';
1075 const PHONE_ANY
= 'any';
1078 private $phone_type;
1081 public function __construct($number, $num_type = self
::NUM_ANY
, $phone_type = self
::PHONE_ANY
)
1083 require_once('profil.func.inc.php');
1084 $this->number
= $number;
1085 $this->num_type
= $num_type;
1086 $this->phone_type
= format_phone_number($phone_type);
1089 public function buildCondition(PlFilter
&$uf)
1091 $sub = $uf->addPhoneFilter();
1093 $conds[] = $sub . '.search_tel = ' . XDB
::format('{?}', $this->number
);
1094 if ($this->num_type
!= self
::NUM_ANY
) {
1095 $conds[] = $sub . '.link_type = ' . XDB
::format('{?}', $this->num_type
);
1097 if ($this->phone_type
!= self
::PHONE_ANY
) {
1098 $conds[] = $sub . '.tel_type = ' . XDB
::format('{?}', $this->phone_type
);
1100 return implode(' AND ', $conds);
1105 // {{{ class UFC_Medal
1106 /** Filters users based on their medals
1107 * @param $medal ID of the medal
1108 * @param $grade Grade of the medal (null for 'any')
1110 class UFC_Medal
implements UserFilterCondition
1115 public function __construct($medal, $grade = null
)
1117 $this->medal
= $medal;
1118 $this->grade
= $grade;
1121 public function buildCondition(PlFilter
&$uf)
1124 $sub = $uf->addMedalFilter();
1125 $conds[] = $sub . '.mid = ' . XDB
::format('{?}', $this->medal
);
1126 if ($this->grade
!= null
) {
1127 $conds[] = $sub . '.gid = ' . XDB
::format('{?}', $this->grade
);
1129 return implode(' AND ', $conds);
1134 // {{{ class UFC_Photo
1135 /** Filters profiles with photo
1137 class UFC_Photo
implements UserFilterCondition
1139 public function buildCondition(PlFilter
&$uf)
1141 $uf->addPhotoFilter();
1142 return 'photo.attach IS NOT NULL';
1147 // {{{ class UFC_Mentor_Expertise
1148 /** Filters users by mentoring expertise
1149 * @param $expertise Domain of expertise
1151 class UFC_Mentor_Expertise
implements UserFilterCondition
1155 public function __construct($expertise)
1157 $this->expertise
= $expertise;
1160 public function buildCondition(PlFilter
&$uf)
1162 $sub = $uf->addMentorFilter(UserFilter
::MENTOR_EXPERTISE
);
1163 return $sub . '.expertise ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->expertise
);
1168 // {{{ class UFC_Mentor_Country
1169 /** Filters users by mentoring country
1170 * @param $country Two-letters code of country being searched
1172 class UFC_Mentor_Country
implements UserFilterCondition
1176 public function __construct()
1178 $this->country
= pl_flatten(func_get_args());
1181 public function buildCondition(PlFilter
&$uf)
1183 $sub = $uf->addMentorFilter(UserFilter
::MENTOR_COUNTRY
);
1184 return $sub . '.country IN ' . XDB
::format('{?}', $this->country
);
1189 // {{{ class UFC_Mentor_Sectorization
1190 /** Filters users based on mentoring (sub|)sector
1191 * @param $sector ID of (sub)sector
1192 * @param $type Whether we are looking for a sector or a subsector
1194 class UFC_Mentor_Sectorization
implements UserFilterCondition
1197 const SUBSECTOR
= 2;
1201 public function __construct($sector, $type = self
::SECTOR
)
1203 $this->sector
= $sector;
1204 $this->type
= $type;
1207 public function buildCondition(PlFilter
&$uf)
1209 $sub = $uf->addMentorFilter(UserFilter
::MENTOR_SECTOR
);
1210 if ($this->type
== self
::SECTOR
) {
1211 $field = 'sectorid';
1213 $field = 'subsectorid';
1215 return $sub . '.' . $field . ' = ' . XDB
::format('{?}', $this->sector
);
1220 // {{{ class UFC_UserRelated
1221 /** Filters users based on a relation toward a user
1222 * @param $user User to which searched users are related
1224 abstract class UFC_UserRelated
implements UserFilterCondition
1227 public function __construct(PlUser
&$user)
1229 $this->user
=& $user;
1234 // {{{ class UFC_Contact
1235 /** Filters users who belong to selected user's contacts
1237 class UFC_Contact
extends UFC_UserRelated
1239 public function buildCondition(PlFilter
&$uf)
1241 $sub = $uf->addContactFilter($this->user
->id());
1242 return 'c' . $sub . '.contact IS NOT NULL';
1247 // {{{ class UFC_WatchRegistration
1248 /** Filters users being watched by selected user
1250 class UFC_WatchRegistration
extends UFC_UserRelated
1252 public function buildCondition(PlFilter
&$uf)
1254 if (!$this->user
->watchType('registration')) {
1255 return PlFilterCondition
::COND_FALSE
;
1257 $uids = $this->user
->watchUsers();
1258 if (count($uids) == 0) {
1259 return PlFilterCondition
::COND_FALSE
;
1261 return XDB
::format('$UID IN {?}', $uids);
1267 // {{{ class UFC_WatchPromo
1268 /** Filters users belonging to a promo watched by selected user
1269 * @param $user Selected user (the one watching promo)
1270 * @param $grade Formation the user is watching
1272 class UFC_WatchPromo
extends UFC_UserRelated
1275 public function __construct(PlUser
&$user, $grade = UserFilter
::GRADE_ING
)
1277 parent
::__construct($user);
1278 $this->grade
= $grade;
1281 public function buildCondition(PlFilter
&$uf)
1283 $promos = $this->user
->watchPromos();
1284 if (count($promos) == 0) {
1285 return PlFilterCondition
::COND_FALSE
;
1287 $sube = $uf->addEducationFilter(true
, $this->grade
);
1288 $field = 'pe' . $sube . '.' . UserFilter
::promoYear($this->grade
);
1289 return XDB
::format($field . ' IN {?}', $promos);
1295 // {{{ class UFC_WatchContact
1296 /** Filters users watched by selected user
1298 class UFC_WatchContact
extends UFC_Contact
1300 public function buildCondition(PlFilter
&$uf)
1302 if (!$this->user
->watchContacts()) {
1303 return PlFilterCondition
::COND_FALSE
;
1305 return parent
::buildCondition($uf);
1310 // {{{ class UFC_MarketingHash
1311 /** Filters users using the hash generated
1312 * to send marketing emails to him.
1314 class UFC_MarketingHash
implements UserFilterCondition
1318 public function __construct($hash)
1320 $this->hash
= $hash;
1323 public function buildCondition(PlFilter
&$uf)
1325 $table = $uf->addMarketingHash();
1326 return XDB
::format('rm.hash = {?}', $this->hash
);
1335 // {{{ class UserFilterOrder
1336 /** Base class for ordering results of a query.
1337 * Parameters for the ordering must be given to the constructor ($desc for a
1338 * descending order).
1339 * The getSortTokens function is used to get actual ordering part of the query.
1341 abstract class UserFilterOrder
extends PlFilterOrder
1343 /** This function must return the tokens to use for ordering
1344 * @param &$uf The UserFilter whose results must be ordered
1345 * @return The name of the field to use for ordering results
1347 // abstract protected function getSortTokens(UserFilter &$uf);
1351 // {{{ class UFO_Promo
1352 /** Orders users by promotion
1353 * @param $grade Formation whose promotion users should be sorted by (restricts results to users of that formation)
1354 * @param $desc Whether sort is descending
1356 class UFO_Promo
extends UserFilterOrder
1360 public function __construct($grade = null
, $desc = false
)
1362 parent
::__construct($desc);
1363 $this->grade
= $grade;
1366 protected function getSortTokens(PlFilter
&$uf)
1368 if (UserFilter
::isGrade($this->grade
)) {
1369 $sub = $uf->addEducationFilter($this->grade
);
1370 return 'pe' . $sub . '.' . UserFilter
::promoYear($this->grade
);
1372 $sub = $uf->addDisplayFilter();
1373 return 'pd' . $sub . '.promo';
1379 // {{{ class UFO_Name
1380 /** Sorts users by name
1381 * @param $type Type of name on which to sort (firstname...)
1382 * @param $variant Variant of that name to use (marital, ordinary...)
1383 * @param $particle Set to true if particles should be included in the sorting order
1384 * @param $desc If sort order should be descending
1386 class UFO_Name
extends UserFilterOrder
1392 public function __construct($type, $variant = null
, $particle = false
, $desc = false
)
1394 parent
::__construct($desc);
1395 $this->type
= $type;
1396 $this->variant
= $variant;
1397 $this->particle
= $particle;
1400 protected function getSortTokens(PlFilter
&$uf)
1402 if (Profile
::isDisplayName($this->type
)) {
1403 $sub = $uf->addDisplayFilter();
1404 $token = 'pd' . $sub . '.' . $this->type
;
1405 if ($uf->accountsRequired()) {
1406 $account_token = Profile
::getAccountEquivalentName($this->type
);
1407 return 'IFNULL(' . $token . ', a.' . $account_token . ')';
1412 $sub = $uf->addNameFilter($this->type
, $this->variant
);
1413 if ($this->particle
) {
1414 return 'CONCAT(pn' . $sub . '.particle, \' \', pn' . $sub . '.name)';
1416 return 'pn' . $sub . '.name';
1423 // {{{ class UFO_Score
1424 class UFO_Score
extends UserFilterOrder
1426 protected function getSortTokens(PlFilter
&$uf)
1428 $toks = $uf->getNameTokens();
1431 // If there weren't any sort tokens, we shouldn't sort by score, sort by NULL instead
1432 if (count($toks) == 0) {
1436 foreach ($toks as $sub => $token) {
1437 $scores[] = XDB
::format('SUM(' . $sub . '.score + IF (' . $sub . '.token = {?}, 5, 0) )', $token);
1439 return implode(' + ', $scores);
1444 // {{{ class UFO_Registration
1445 /** Sorts users based on registration date
1447 class UFO_Registration
extends UserFilterOrder
1449 protected function getSortTokens(PlFilter
&$uf)
1451 $uf->requireAccounts();
1452 return 'a.registration_date';
1457 // {{{ class UFO_Birthday
1458 /** Sorts users based on next birthday date
1460 class UFO_Birthday
extends UserFilterOrder
1462 protected function getSortTokens(PlFilter
&$uf)
1464 $uf->requireProfiles();
1465 return 'p.next_birthday';
1470 // {{{ class UFO_ProfileUpdate
1471 /** Sorts users based on last profile update
1473 class UFO_ProfileUpdate
extends UserFilterOrder
1475 protected function getSortTokens(PlFilter
&$uf)
1477 $uf->requireProfiles();
1478 return 'p.last_change';
1483 // {{{ class UFO_Death
1484 /** Sorts users based on death date
1486 class UFO_Death
extends UserFilterOrder
1488 protected function getSortTokens(PlFilter
&$uf)
1490 $uf->requireProfiles();
1491 return 'p.deathdate';
1496 // {{{ class UFO_Uid
1497 /** Sorts users based on their uid
1499 class UFO_Uid
extends UserFilterOrder
1501 protected function getSortTokens(PlFilter
&$uf)
1503 $uf->requireAccounts();
1509 // {{{ class UFO_Hruid
1510 /** Sorts users based on their hruid
1512 class UFO_Hruid
extends UserFilterOrder
1514 protected function getSortTokens(PlFilter
&$uf)
1516 $uf->requireAccounts();
1522 // {{{ class UFO_Pid
1523 /** Sorts users based on their pid
1525 class UFO_Pid
extends UserFilterOrder
1527 protected function getSortTokens(PlFilter
&$uf)
1529 $uf->requireProfiles();
1535 // {{{ class UFO_Hrpid
1536 /** Sorts users based on their hrpid
1538 class UFO_Hrpid
extends UserFilterOrder
1540 protected function getSortTokens(PlFilter
&$uf)
1542 $uf->requireProfiles();
1549 /***********************************
1550 *********************************
1552 *********************************
1553 ***********************************/
1555 // {{{ class UserFilter
1556 /** This class provides a convenient and centralized way of filtering users.
1559 * $uf = new UserFilter(new UFC_Blah($x, $y), new UFO_Coin($z, $t));
1561 * Resulting UserFilter can be used to:
1562 * - get a list of User objects matching the filter
1563 * - get a list of UIDs matching the filter
1564 * - get the number of users matching the filter
1565 * - check whether a given User matches the filter
1566 * - filter a list of User objects depending on whether they match the filter
1568 * Usage for UFC and UFO objects:
1569 * A UserFilter will call all private functions named XXXJoins.
1570 * These functions must return an array containing the list of join
1571 * required by the various UFC and UFO associated to the UserFilter.
1572 * Entries in those returned array are of the following form:
1573 * 'join_tablealias' => array('join_type', 'joined_table', 'join_criter')
1574 * which will be translated into :
1575 * join_type JOIN joined_table AS join_tablealias ON (join_criter)
1576 * in the final query.
1578 * In the join_criter text, $ME is replaced with 'join_tablealias', $PID with
1579 * profile.pid, and $UID with accounts.uid.
1581 * For each kind of "JOIN" needed, a function named addXXXFilter() should be defined;
1582 * its parameter will be used to set various private vars of the UserFilter describing
1583 * the required joins ; such a function shall return the "join_tablealias" to use
1584 * when referring to the joined table.
1586 * For example, if data from profile_job must be available to filter results,
1587 * the UFC object will call $uf-addJobFilter(), which will set the 'with_pj' var and
1588 * return 'pj', the short name to use when referring to profile_job; when building
1589 * the query, calling the jobJoins function will return an array containing a single
1591 * 'pj' => array('left', 'profile_job', '$ME.pid = $UID');
1593 * The 'register_optional' function can be used to generate unique table aliases when
1594 * the same table has to be joined several times with different aliases.
1596 class UserFilter
extends PlFilter
1598 protected $joinMethods = array();
1600 protected $joinMetas = array(
1606 private $sort = array();
1607 private $query = null
;
1608 private $orderby = null
;
1610 private $lastusercount = null
;
1611 private $lastprofilecount = null
;
1613 public function __construct($cond = null
, $sort = null
)
1615 if (empty($this->joinMethods
)) {
1616 $class = new ReflectionClass('UserFilter');
1617 foreach ($class->getMethods() as $method) {
1618 $name = $method->getName();
1619 if (substr($name, -5) == 'Joins' && $name != 'buildJoins') {
1620 $this->joinMethods
[] = $name;
1624 if (!is_null($cond)) {
1625 if ($cond instanceof PlFilterCondition
) {
1626 $this->setCondition($cond);
1629 if (!is_null($sort)) {
1630 if ($sort instanceof UserFilterOrder
) {
1631 $this->addSort($sort);
1632 } else if (is_array($sort)) {
1633 foreach ($sort as $s) {
1640 private function buildQuery()
1642 // The root condition is built first because some orders need info
1643 // available only once all UFC have set their conditions (UFO_Score)
1644 if (is_null($this->query
)) {
1645 $where = $this->root
->buildCondition($this);
1646 $where = str_replace(array_keys($this->joinMetas
),
1650 if (is_null($this->orderby
)) {
1652 foreach ($this->sort
as $sort) {
1653 $orders = array_merge($orders, $sort->buildSort($this));
1655 if (count($orders) == 0) {
1656 $this->orderby
= '';
1658 $this->orderby
= 'ORDER BY ' . implode(', ', $orders);
1660 $this->orderby
= str_replace(array_keys($this->joinMetas
),
1664 if (is_null($this->query
)) {
1665 if ($this->with_accounts
) {
1666 $from = 'accounts AS a';
1668 $this->requireProfiles();
1669 $from = 'profiles AS p';
1671 $joins = $this->buildJoins();
1672 $this->query
= 'FROM ' . $from . '
1674 WHERE (' . $where . ')';
1678 private function getUIDList($uids = null
, PlLimit
&$limit)
1680 $this->requireAccounts();
1681 $this->buildQuery();
1682 $lim = $limit->getSql();
1684 if (!empty($uids)) {
1685 $cond = XDB
::format(' AND a.uid IN {?}', $uids);
1687 $fetched = XDB
::fetchColumn('SELECT SQL_CALC_FOUND_ROWS a.uid
1688 ' . $this->query
. $cond . '
1690 ' . $this->orderby
. '
1692 $this->lastusercount
= (int)XDB
::fetchOneCell('SELECT FOUND_ROWS()');
1696 private function getPIDList($pids = null
, PlLimit
&$limit)
1698 $this->requireProfiles();
1699 $this->buildQuery();
1700 $lim = $limit->getSql();
1702 if (!is_null($pids)) {
1703 $cond = XDB
::format(' AND p.pid IN {?}', $pids);
1705 $fetched = XDB
::fetchColumn('SELECT SQL_CALC_FOUND_ROWS p.pid
1706 ' . $this->query
. $cond . '
1708 ' . $this->orderby
. '
1710 $this->lastprofilecount
= (int)XDB
::fetchOneCell('SELECT FOUND_ROWS()');
1714 private static function defaultLimit($limit) {
1715 if ($limit == null
) {
1716 return new PlLimit();
1722 /** Check that the user match the given rule.
1724 public function checkUser(PlUser
&$user)
1726 $this->requireAccounts();
1727 $this->buildQuery();
1728 $count = (int)XDB
::fetchOneCell('SELECT COUNT(*)
1729 ' . $this->query
. XDB
::format(' AND a.uid = {?}', $user->id()));
1733 /** Check that the profile match the given rule.
1735 public function checkProfile(Profile
&$profile)
1737 $this->requireProfiles();
1738 $this->buildQuery();
1739 $count = (int)XDB
::fetchOneCell('SELECT COUNT(*)
1740 ' . $this->query
. XDB
::format(' AND p.pid = {?}', $profile->id()));
1744 /** Default filter is on users
1746 public function filter(array $users, $limit = null
)
1748 return $this->filterUsers($users, self
::defaultLimit($limit));
1751 /** Filter a list of users to extract the users matching the rule.
1753 public function filterUsers(array $users, $limit = null
)
1755 $limit = self
::defaultLimit($limit);
1756 $this->requireAccounts();
1757 $this->buildQuery();
1760 foreach ($users as $user) {
1761 if ($user instanceof PlUser
) {
1767 $table[$uid] = $user;
1769 $fetched = $this->getUIDList($uids, $limit);
1771 foreach ($fetched as $uid) {
1772 $output[] = $table[$uid];
1777 /** Filter a list of profiles to extract the users matching the rule.
1779 public function filterProfiles(array $profiles, $limit = null
)
1781 $limit = self
::defaultLimit($limit);
1782 $this->requireProfiles();
1783 $this->buildQuery();
1786 foreach ($profiles as $profile) {
1787 if ($profile instanceof Profile
) {
1788 $pid = $profile->id();
1793 $table[$pid] = $profile;
1795 $fetched = $this->getPIDList($pids, $limit);
1797 foreach ($fetched as $pid) {
1798 $output[] = $table[$pid];
1803 public function getUIDs($limit = null
)
1805 $limit = self
::defaultLimit($limit);
1806 return $this->getUIDList(null
, $limit);
1809 public function getUID($pos = 0)
1811 $uids =$this->getUIDList(null
, new PlLimit(1, $pos));
1812 if (count($uids) == 0) {
1819 public function getPIDs($limit = null
)
1821 $limit = self
::defaultLimit($limit);
1822 return $this->getPIDList(null
, $limit);
1825 public function getPID($pos = 0)
1827 $pids =$this->getPIDList(null
, new PlLimit(1, $pos));
1828 if (count($pids) == 0) {
1835 public function getUsers($limit = null
)
1837 return User
::getBulkUsersWithUIDs($this->getUIDs($limit));
1840 public function getUser($pos = 0)
1842 $uid = $this->getUID($pos);
1846 return User
::getWithUID($uid);
1850 public function iterUsers($limit = null
)
1852 return User
::iterOverUIDs($this->getUIDs($limit));
1855 public function getProfiles($limit = null
, $fields = 0x0000, $visibility = null
)
1857 return Profile
::getBulkProfilesWithPIDs($this->getPIDs($limit), $fields, $visibility);
1860 public function getProfile($pos = 0, $fields = 0x0000, $visibility = null
)
1862 $pid = $this->getPID($pos);
1866 return Profile
::get($pid, $fields, $visibility);
1870 public function iterProfiles($limit = null
, $fields = 0x0000, $visibility = null
)
1872 return Profile
::iterOverPIDs($this->getPIDs($limit), true
, $fields, $visibility);
1875 public function get($limit = null
)
1877 return $this->getUsers($limit);
1881 public function getTotalCount()
1883 return $this->getTotalUserCount();
1886 public function getTotalUserCount()
1888 if (is_null($this->lastusercount
)) {
1889 $this->requireAccounts();
1890 $this->buildQuery();
1891 return (int)XDB
::fetchOneCell('SELECT COUNT(DISTINCT a.uid)
1894 return $this->lastusercount
;
1898 public function getTotalProfileCount()
1900 if (is_null($this->lastprofilecount
)) {
1901 $this->requireProfiles();
1902 $this->buildQuery();
1903 return (int)XDB
::fetchOneCell('SELECT COUNT(DISTINCT p.pid)
1906 return $this->lastprofilecount
;
1910 public function setCondition(PlFilterCondition
&$cond)
1912 $this->root
=& $cond;
1913 $this->query
= null
;
1916 public function addSort(PlFilterOrder
&$sort)
1918 $this->sort
[] = $sort;
1919 $this->orderby
= null
;
1922 static public function getLegacy($promo_min, $promo_max)
1924 if ($promo_min != 0) {
1925 $min = new UFC_Promo('>=', self
::GRADE_ING
, intval($promo_min));
1927 $min = new PFC_True();
1929 if ($promo_max != 0) {
1930 $max = new UFC_Promo('<=', self
::GRADE_ING
, intval($promo_max));
1932 $max = new PFC_True();
1934 return new UserFilter(new PFC_And($min, $max));
1937 static public function sortByName()
1939 return array(new UFO_Name(Profile
::LASTNAME
), new UFO_Name(Profile
::FIRSTNAME
));
1942 static public function sortByPromo()
1944 return array(new UFO_Promo(), new UFO_Name(Profile
::LASTNAME
), new UFO_Name(Profile
::FIRSTNAME
));
1947 static private function getDBSuffix($string)
1949 if (is_array($string)) {
1950 if (count($string) == 1) {
1951 return self
::getDBSuffix(array_pop($string));
1953 return md5(implode('|', $string));
1955 return preg_replace('/[^a-z0-9]/i', '', $string);
1960 /** Stores a new (and unique) table alias in the &$table table
1961 * @param &$table Array in which the table alias must be stored
1962 * @param $val Value which will then be used to build the join
1963 * @return Name of the newly created alias
1965 private $option = 0;
1966 private function register_optional(array &$table, $val)
1968 if (is_null($val)) {
1969 $sub = $this->option++
;
1972 $sub = self
::getDBSuffix($val);
1976 $table[$sub] = $index;
1980 /** PROFILE VS ACCOUNT
1982 private $with_profiles = false
;
1983 private $with_accounts = false
;
1984 public function requireAccounts()
1986 $this->with_accounts
= true
;
1989 public function accountsRequired()
1991 return $this->with_accounts
;
1994 public function requireProfiles()
1996 $this->with_profiles
= true
;
1999 public function profilesRequired()
2001 return $this->with_profiles
;
2004 protected function accountJoins()
2007 if ($this->with_profiles
&& $this->with_accounts
) {
2008 $joins['ap'] = PlSqlJoin
::left('account_profiles', '$ME.uid = $UID AND FIND_IN_SET(\'owner\', ap.perms)');
2009 $joins['p'] = PlSqlJoin
::left('profiles', '$PID = ap.pid');
2016 const DISPLAY
= 'display';
2017 private $pd = false
;
2018 public function addDisplayFilter()
2020 $this->requireProfiles();
2025 protected function displayJoins()
2028 return array('pd' => PlSqlJoin
::left('profile_display', '$ME.pid = $PID'));
2037 private $with_logger = false
;
2038 public function addLoggerFilter()
2040 $this->with_logger
= true
;
2041 $this->requireAccounts();
2044 protected function loggerJoins()
2047 if ($this->with_logger
) {
2048 $joins['ls'] = PlSqlJoin
::left('log_sessions', '$ME.uid = $UID');
2056 static public function assertName($name)
2058 if (!DirEnum
::getID(DirEnum
::NAMETYPES
, $name)) {
2059 Platal
::page()->kill('Invalid name type: ' . $name);
2063 private $pn = array();
2064 public function addNameFilter($type, $variant = null
)
2066 $this->requireProfiles();
2067 if (!is_null($variant)) {
2068 $ft = $type . '_' . $variant;
2073 self
::assertName($ft);
2075 if (!is_null($variant) && $variant == 'other') {
2076 $sub .= $this->option++
;
2078 $this->pn
[$sub] = DirEnum
::getID(DirEnum
::NAMETYPES
, $ft);
2082 protected function nameJoins()
2085 foreach ($this->pn
as $sub => $type) {
2086 $joins['pn' . $sub] = PlSqlJoin
::left('profile_name', '$ME.pid = $PID AND $ME.typeid = {?}', $type);
2093 private $name_tokens = array();
2094 private $nb_tokens = 0;
2096 public function addNameTokensFilter($token)
2098 $this->requireProfiles();
2099 $sub = 'sn' . (1 +
$this->nb_tokens
);
2101 $this->name_tokens
[$sub] = $token;
2105 protected function nameTokensJoins()
2107 /* We don't return joins, since with_sn forces the SELECT to run on search_name first */
2109 foreach ($this->name_tokens
as $sub => $token) {
2110 $joins[$sub] = PlSqlJoin
::left('search_name', '$ME.pid = $PID');
2115 public function getNameTokens()
2117 return $this->name_tokens
;
2123 private $with_nat = false
;
2124 public function addNationalityFilter()
2126 $this->with_nat
= true
;
2130 protected function nationalityJoins()
2133 if ($this->with_nat
) {
2134 $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');
2141 const GRADE_ING
= 'Ing.';
2142 const GRADE_PHD
= 'PhD';
2143 const GRADE_MST
= 'M%';
2144 static public function isGrade($grade)
2146 return ($grade !== 0) && ($grade == self
::GRADE_ING ||
$grade == self
::GRADE_PHD ||
$grade == self
::GRADE_MST
);
2149 static public function assertGrade($grade)
2151 if (!self
::isGrade($grade)) {
2152 Platal
::page()->killError("DiplĂ´me non valide: $grade");
2156 static public function promoYear($grade)
2158 // XXX: Definition of promotion for phds and masters might change in near future.
2159 return ($grade == UserFilter
::GRADE_ING
) ?
'entry_year' : 'grad_year';
2162 private $pepe = array();
2163 private $with_pee = false
;
2164 public function addEducationFilter($x = false
, $grade = null
)
2166 $this->requireProfiles();
2168 $index = $this->option
;
2169 $sub = $this->option++
;
2171 self
::assertGrade($grade);
2174 $this->with_pee
= true
;
2177 $this->pepe
[$index] = $sub;
2181 protected function educationJoins()
2184 if ($this->with_pee
) {
2185 $joins['pee'] = PlSqlJoin
::inner('profile_education_enum', 'pee.abbreviation = \'X\'');
2187 foreach ($this->pepe
as $grade => $sub) {
2188 if ($this->isGrade($grade)) {
2189 $joins['pe' . $sub] = PlSqlJoin
::left('profile_education', '$ME.eduid = pee.id AND $ME.pid = $PID');
2190 $joins['pede' . $sub] = PlSqlJoin
::inner('profile_education_degree_enum', '$ME.id = pe' . $sub . '.degreeid AND $ME.abbreviation LIKE {?}', $grade);
2192 $joins['pe' . $sub] = PlSqlJoin
::left('profile_education', '$ME.pid = $PID');
2193 $joins['pee' . $sub] = PlSqlJoin
::inner('profile_education_enum', '$ME.id = pe' . $sub . '.eduid');
2194 $joins['pede' . $sub] = PlSqlJoin
::inner('profile_education_degree_enum', '$ME.id = pe' . $sub . '.degreeid');
2203 private $gpm = array();
2204 public function addGroupFilter($group = null
)
2206 $this->requireAccounts();
2207 if (!is_null($group)) {
2208 if (is_int($group) ||
ctype_digit($group)) {
2209 $index = $sub = $group;
2212 $sub = self
::getDBSuffix($group);
2215 $sub = 'group_' . $this->option++
;
2219 $this->gpm
[$sub] = $index;
2223 protected function groupJoins()
2226 foreach ($this->gpm
as $sub => $key) {
2227 if (is_null($key)) {
2228 $joins['gpa' . $sub] = PlSqlJoin
::inner('groups');
2229 $joins['gpm' . $sub] = PlSqlJoin
::left('group_members', '$ME.uid = $UID AND $ME.asso_id = gpa' . $sub . '.id');
2230 } else if (is_int($key) ||
ctype_digit($key)) {
2231 $joins['gpm' . $sub] = PlSqlJoin
::left('group_members', '$ME.uid = $UID AND $ME.asso_id = ' . $key);
2233 $joins['gpa' . $sub] = PlSqlJoin
::inner('groups', '$ME.diminutif = {?}', $key);
2234 $joins['gpm' . $sub] = PlSqlJoin
::left('group_members', '$ME.uid = $UID AND $ME.asso_id = gpa' . $sub . '.id');
2243 private $with_bi = false
;
2244 private $with_bd = false
;
2245 public function addBinetsFilter($with_enum = false
)
2247 $this->requireProfiles();
2248 $this->with_bi
= true
;
2250 $this->with_bd
= true
;
2257 protected function binetsJoins()
2260 if ($this->with_bi
) {
2261 $joins['bi'] = PlSqlJoin
::left('profile_binets', '$ME.pid = $PID');
2263 if ($this->with_bd
) {
2264 $joins['bd'] = PlSqlJoin
::left('profile_binet_enum', '$ME.id = bi.binet_id');
2271 private $e = array();
2272 public function addEmailRedirectFilter($email = null
)
2274 $this->requireAccounts();
2275 return $this->register_optional($this->e
, $email);
2278 private $ve = array();
2279 public function addVirtualEmailFilter($email = null
)
2281 $this->addAliasFilter(self
::ALIAS_FORLIFE
);
2282 return $this->register_optional($this->ve
, $email);
2285 const ALIAS_BEST
= 'bestalias';
2286 const ALIAS_FORLIFE
= 'forlife';
2287 private $al = array();
2288 public function addAliasFilter($alias = null
)
2290 $this->requireAccounts();
2291 return $this->register_optional($this->al
, $alias);
2294 protected function emailJoins()
2298 foreach ($this->e
as $sub=>$key) {
2299 if (is_null($key)) {
2300 $joins['e' . $sub] = PlSqlJoin
::left('emails', '$ME.uid = $UID AND $ME.flags != \'filter\'');
2302 if (!is_array($key)) {
2305 $joins['e' . $sub] = PlSqlJoin
::left('emails', '$ME.uid = $UID AND $ME.flags != \'filter\'
2306 AND $ME.email IN {?}', $key);
2309 foreach ($this->al
as $sub=>$key) {
2310 if (is_null($key)) {
2311 $joins['al' . $sub] = PlSqlJoin
::left('aliases', '$ME.uid = $UID AND $ME.type IN (\'alias\', \'a_vie\')');
2312 } else if ($key == self
::ALIAS_BEST
) {
2313 $joins['al' . $sub] = PlSqlJoin
::left('aliases', '$ME.uid = $UID AND $ME.type IN (\'alias\', \'a_vie\') AND FIND_IN_SET(\'bestalias\', $ME.flags)');
2314 } else if ($key == self
::ALIAS_FORLIFE
) {
2315 $joins['al' . $sub] = PlSqlJoin
::left('aliases', '$ME.uid = $UID AND $ME.type = \'a_vie\'');
2317 if (!is_array($key)) {
2320 $joins['al' . $sub] = PlSqlJoin
::left('aliases', '$ME.uid = $UID AND $ME.type IN (\'alias\', \'a_vie\')
2321 AND $ME.alias IN {?}', $key);
2324 foreach ($this->ve
as $sub=>$key) {
2325 if (is_null($key)) {
2326 $joins['v' . $sub] = PlSqlJoin
::left('virtual', '$ME.type = \'user\'');
2328 if (!is_array($key)) {
2331 $joins['v' . $sub] = PlSqlJoin
::left('virtual', '$ME.type = \'user\' AND $ME.alias IN {?}', $key);
2333 $joins['vr' . $sub] = PlSqlJoin
::left('virtual_redirect',
2334 '$ME.vid = v' . $sub . '.vid
2335 AND ($ME.redirect IN (CONCAT(al_forlife.alias, \'@\', {?}),
2336 CONCAT(al_forlife.alias, \'@\', {?}),
2338 $globals->mail
->domain
, $globals->mail
->domain2
);
2346 private $with_pa = false
;
2347 public function addAddressFilter()
2349 $this->requireProfiles();
2350 $this->with_pa
= true
;
2354 private $with_pac = false
;
2355 public function addAddressCountryFilter()
2357 $this->requireProfiles();
2358 $this->addAddressFilter();
2359 $this->with_pac
= true
;
2363 private $with_pal = false
;
2364 public function addAddressLocalityFilter()
2366 $this->requireProfiles();
2367 $this->addAddressFilter();
2368 $this->with_pal
= true
;
2372 protected function addressJoins()
2375 if ($this->with_pa
) {
2376 $joins['pa'] = PlSqlJoin
::left('profile_addresses', '$ME.pid = $PID');
2378 if ($this->with_pac
) {
2379 $joins['gc'] = PlSqlJoin
::left('geoloc_countries', '$ME.iso_3166_1_a2 = pa.countryID');
2381 if ($this->with_pal
) {
2382 $joins['gl'] = PlSqlJoin
::left('geoloc_localities', '$ME.id = pa.localityID');
2391 private $pc = false
;
2392 private $pce = array();
2393 private $pcr = false
;
2394 public function addCorpsFilter($type)
2396 $this->requireProfiles();
2398 if ($type == UFC_Corps
::CURRENT
) {
2399 $pce['pcec'] = 'current_corpsid';
2401 } else if ($type == UFC_Corps
::ORIGIN
) {
2402 $pce['pceo'] = 'original_corpsid';
2407 public function addCorpsRankFilter()
2409 $this->requireProfiles();
2415 protected function corpsJoins()
2419 $joins['pc'] = PlSqlJoin
::left('profile_corps', '$ME.pid = $PID');
2422 $joins['pcr'] = PlSqlJoin
::left('profile_corps_rank_enum', '$ME.id = pc.rankid');
2424 foreach($this->pce
as $sub => $field) {
2425 $joins[$sub] = PlSqlJoin
::left('profile_corps_enum', '$ME.id = pc.' . $field);
2433 const JOB_SECTOR
= 0x0001;
2434 const JOB_SUBSECTOR
= 0x0002;
2435 const JOB_SUBSUBSECTOR
= 0x0004;
2436 const JOB_ALTERNATES
= 0x0008;
2437 const JOB_USERDEFINED
= 0x0010;
2438 const JOB_CV
= 0x0020;
2440 const JOB_SECTORIZATION
= 0x000F;
2441 const JOB_ANY
= 0x003F;
2445 * pje => profile_job_enum
2446 * pjse => profile_job_sector_enum
2447 * pjsse => profile_job_subsector_enum
2448 * pjssse => profile_job_subsubsector_enum
2449 * pja => profile_job_alternates
2451 private $with_pj = false
;
2452 private $with_pje = false
;
2453 private $with_pjse = false
;
2454 private $with_pjsse = false
;
2455 private $with_pjssse = false
;
2456 private $with_pja = false
;
2458 public function addJobFilter()
2460 $this->requireProfiles();
2461 $this->with_pj
= true
;
2465 public function addJobCompanyFilter()
2467 $this->addJobFilter();
2468 $this->with_pje
= true
;
2472 public function addJobSectorizationFilter($type)
2474 $this->addJobFilter();
2475 if ($type == self
::JOB_SECTOR
) {
2476 $this->with_pjse
= true
;
2478 } else if ($type == self
::JOB_SUBSECTOR
) {
2479 $this->with_pjsse
= true
;
2481 } else if ($type == self
::JOB_SUBSUBSECTOR
) {
2482 $this->with_pjssse
= true
;
2484 } else if ($type == self
::JOB_ALTERNATES
) {
2485 $this->with_pja
= true
;
2490 protected function jobJoins()
2493 if ($this->with_pj
) {
2494 $joins['pj'] = PlSqlJoin
::left('profile_job', '$ME.pid = $PID');
2496 if ($this->with_pje
) {
2497 $joins['pje'] = PlSqlJoin
::left('profile_job_enum', '$ME.id = pj.jobid');
2499 if ($this->with_pjse
) {
2500 $joins['pjse'] = PlSqlJoin
::left('profile_job_sector_enum', '$ME.id = pj.sectorid');
2502 if ($this->with_pjsse
) {
2503 $joins['pjsse'] = PlSqlJoin
::left('profile_job_subsector_enum', '$ME.id = pj.subsectorid');
2505 if ($this->with_pjssse
) {
2506 $joins['pjssse'] = PlSqlJoin
::left('profile_job_subsubsector_enum', '$ME.id = pj.subsubsectorid');
2508 if ($this->with_pja
) {
2509 $joins['pja'] = PlSqlJoin
::left('profile_job_alternates', '$ME.subsubsectorid = pj.subsubsectorid');
2517 private $with_pnw = false
;
2518 public function addNetworkingFilter()
2520 $this->requireAccounts();
2521 $this->with_pnw
= true
;
2525 protected function networkingJoins()
2528 if ($this->with_pnw
) {
2529 $joins['pnw'] = PlSqlJoin
::left('profile_networking', '$ME.pid = $PID');
2537 private $with_ptel = false
;
2539 public function addPhoneFilter()
2541 $this->requireAccounts();
2542 $this->with_ptel
= true
;
2546 protected function phoneJoins()
2549 if ($this->with_ptel
) {
2550 $joins['ptel'] = PlSqlJoin
::left('profile_phones', '$ME.pid = $PID');
2558 private $with_pmed = false
;
2559 public function addMedalFilter()
2561 $this->requireProfiles();
2562 $this->with_pmed
= true
;
2566 protected function medalJoins()
2569 if ($this->with_pmed
) {
2570 $joins['pmed'] = PlSqlJoin
::left('profile_medals', '$ME.pid = $PID');
2578 private $pms = array();
2579 const MENTOR_EXPERTISE
= 1;
2580 const MENTOR_COUNTRY
= 2;
2581 const MENTOR_SECTOR
= 3;
2583 public function addMentorFilter($type)
2585 $this->requireAccounts();
2587 case self
::MENTOR_EXPERTISE
:
2588 $this->pms
['pme'] = 'profile_mentor';
2590 case self
::MENTOR_COUNTRY
:
2591 $this->pms
['pmc'] = 'profile_mentor_country';
2593 case self
::MENTOR_SECTOR
:
2594 $this->pms
['pms'] = 'profile_mentor_sector';
2597 Platal
::page()->killError("Undefined mentor filter.");
2601 protected function mentorJoins()
2604 foreach ($this->pms
as $sub => $tab) {
2605 $joins[$sub] = PlSqlJoin
::left($tab, '$ME.pid = $PID');
2612 private $cts = array();
2613 public function addContactFilter($uid = null
)
2615 $this->requireProfiles();
2616 return $this->register_optional($this->cts
, is_null($uid) ? null
: 'user_' . $uid);
2619 protected function contactJoins()
2622 foreach ($this->cts
as $sub=>$key) {
2623 if (is_null($key)) {
2624 $joins['c' . $sub] = PlSqlJoin
::left('contacts', '$ME.contact = $PID');
2626 $joins['c' . $sub] = PlSqlJoin
::left('contacts', '$ME.uid = {?} AND $ME.contact = $PID', substr($key, 5));
2635 private $wn = array();
2636 public function addWatchRegistrationFilter($uid = null
)
2638 $this->requireAccounts();
2639 return $this->register_optional($this->wn
, is_null($uid) ? null
: 'user_' . $uid);
2642 private $wp = array();
2643 public function addWatchPromoFilter($uid = null
)
2645 $this->requireAccounts();
2646 return $this->register_optional($this->wp
, is_null($uid) ? null
: 'user_' . $uid);
2649 private $w = array();
2650 public function addWatchFilter($uid = null
)
2652 $this->requireAccounts();
2653 return $this->register_optional($this->w
, is_null($uid) ? null
: 'user_' . $uid);
2656 protected function watchJoins()
2659 foreach ($this->w
as $sub=>$key) {
2660 if (is_null($key)) {
2661 $joins['w' . $sub] = PlSqlJoin
::left('watch');
2663 $joins['w' . $sub] = PlSqlJoin
::left('watch', '$ME.uid = {?}', substr($key, 5));
2666 foreach ($this->wn
as $sub=>$key) {
2667 if (is_null($key)) {
2668 $joins['wn' . $sub] = PlSqlJoin
::left('watch_nonins', '$ME.ni_id = $UID');
2670 $joins['wn' . $sub] = PlSqlJoin
::left('watch_nonins', '$ME.uid = {?} AND $ME.ni_id = $UID', substr($key, 5));
2673 foreach ($this->wn
as $sub=>$key) {
2674 if (is_null($key)) {
2675 $joins['wn' . $sub] = PlSqlJoin
::left('watch_nonins', '$ME.ni_id = $UID');
2677 $joins['wn' . $sub] = PlSqlJoin
::left('watch_nonins', '$ME.uid = {?} AND $ME.ni_id = $UID', substr($key, 5));
2680 foreach ($this->wp
as $sub=>$key) {
2681 if (is_null($key)) {
2682 $joins['wp' . $sub] = PlSqlJoin
::left('watch_promo');
2684 $joins['wp' . $sub] = PlSqlJoin
::left('watch_promo', '$ME.uid = {?}', substr($key, 5));
2693 private $with_photo;
2694 public function addPhotoFilter()
2696 $this->requireProfiles();
2697 $this->with_photo
= true
;
2700 protected function photoJoins()
2702 if ($this->with_photo
) {
2703 return array('photo' => PlSqlJoin
::left('profile_photos', '$ME.pid = $PID'));
2713 public function addMarketingHash()
2715 $this->requireAccounts();
2716 $this->with_rm
= true
;
2719 protected function marketingJoins()
2721 if ($this->with_rm
) {
2722 return array('rm' => PlSqlJoin
::left('register_marketing', '$ME.uid = $UID'));
2730 // {{{ class ProfileFilter
2731 class ProfileFilter
extends UserFilter
2733 public function get($limit = null
)
2735 return $this->getProfiles($limit);
2738 public function filter(array $profiles, $limit = null
)
2740 return $this->filterProfiles($profiles, self
::defaultLimit($limit));
2743 public function getTotalCount()
2745 return $this->getTotalProfileCount();
2750 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: