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_AccountType
56 /** Filters users who have one of the given account types
58 class UFC_AccountType
implements UserFilterCondition
62 public function __construct()
64 $this->types
= pl_flatten(func_get_args());
67 public function buildCondition(PlFilter
&$uf)
69 $uf->requireAccounts();
70 return XDB
::format('a.type IN {?}', $this->types
);
75 // {{{ class UFC_AccountPerm
76 /** Filters users who have one of the given permissions
78 class UFC_AccountPerm
implements UserFilterCondition
82 public function __construct()
84 $this->perms
= pl_flatten(func_get_args());
87 public function buildCondition(PlFilter
&$uf)
91 foreach ($this->perms
as $perm) {
92 $conds[] = XDB
::format('FIND_IN_SET({?}, IF(a.user_perms IS NULL, at.perms,
93 CONCAT(at.perms, \',\', a.user_perms)))',
97 return self
::COND_TRUE
;
99 return implode(' OR ', $conds);
105 // {{{ class UFC_Hruid
106 /** Filters users based on their hruid
107 * @param $val Either an hruid, or a list of those
109 class UFC_Hruid
implements UserFilterCondition
113 public function __construct()
115 $this->hruids
= pl_flatten(func_get_args());
118 public function buildCondition(PlFilter
&$uf)
120 $uf->requireAccounts();
121 return XDB
::format('a.hruid IN {?}', $this->hruids
);
126 // {{{ class UFC_Hrpid
127 /** Filters users based on the hrpid of their profiles
128 * @param $val Either an hrpid, or a list of those
130 class UFC_Hrpid
implements UserFilterCondition
134 public function __construct()
136 $this->hrpids
= pl_flatten(func_get_args());
139 public function buildCondition(PlFilter
&$uf)
141 $uf->requireProfiles();
142 return XDB
::format('p.hrpid IN {?}', $this->hrpids
);
148 /** Filters users based on one of their last IPs
149 * @param $ip IP from which connection are checked
151 class UFC_Ip
implements UserFilterCondition
155 public function __construct($ip)
160 public function buildCondition(PlFilter
&$uf)
162 $sub = $uf->addLoggerFilter();
163 $ip = ip_to_uint($this->ip
);
164 return XDB
::format($sub . '.ip = {?} OR ' . $sub . '.forward_ip = {?}', $ip, $ip);
169 // {{{ class UFC_Comment
170 class UFC_Comment
implements UserFilterCondition
174 public function __construct($text)
179 public function buildCondition(PlFilter
&$uf)
181 $uf->requireProfiles();
182 return $uf->getVisibilityCondition('p.freetext_pub') . ' AND p.freetext ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->text
);
187 // {{{ class UFC_Promo
188 /** Filters users based on promotion
189 * @param $comparison Comparison operator (>, =, ...)
190 * @param $grade Formation on which to restrict, UserFilter::DISPLAY for "any formation"
191 * @param $promo Promotion on which the filter is based
193 class UFC_Promo
implements UserFilterCondition
200 public function __construct($comparison, $grade, $promo)
202 $this->grade
= $grade;
203 $this->comparison
= $comparison;
204 $this->promo
= $promo;
205 if ($this->grade
!= UserFilter
::DISPLAY
) {
206 UserFilter
::assertGrade($this->grade
);
208 if ($this->grade
== UserFilter
::DISPLAY
&& $this->comparison
!= '=') {
209 // XXX: we might try to guess the grade from the first char of the promo and forbid only '<= 2004', but allow '<= X2004'
210 Platal
::page()->killError("Il n'est pas possible d'appliquer la comparaison '" . $this->comparison
. "' aux promotions sans spécifier de formation (X/M/D)");
214 public function buildCondition(PlFilter
&$uf)
216 if ($this->grade
== UserFilter
::DISPLAY
) {
217 $sub = $uf->addDisplayFilter();
218 return XDB
::format('pd' . $sub . '.promo ' . $this->comparison
. ' {?}', $this->promo
);
220 $sub = $uf->addEducationFilter(true
, $this->grade
);
221 $field = 'pe' . $sub . '.' . UserFilter
::promoYear($this->grade
);
222 return $field . ' IS NOT NULL AND ' . $field . ' ' . $this->comparison
. ' ' . XDB
::format('{?}', $this->promo
);
228 // {{{ class UFC_SchoolId
229 /** Filters users based on their shoold identifier
230 * @param type Parameter type (Xorg, AX, School)
231 * @param value School id value
233 class UFC_SchoolId
implements UserFilterCondition
237 const School
= 'school';
242 static public function assertType($type)
244 if ($type != self
::AX
&& $type != self
::Xorg
&& $type != self
::School
) {
245 Platal
::page()->killError("Type de matricule invalide: $type");
249 public function __construct($type, $id)
253 self
::assertType($type);
256 public function buildCondition(PlFilter
&$uf)
258 $uf->requireProfiles();
261 if ($type == self
::School
) {
263 $id = Profile
::getXorgId($id);
265 return XDB
::format('p.' . $type . '_id = {?}', $id);
270 // {{{ class UFC_EducationSchool
271 /** Filters users by formation
272 * @param $val The formation to search (either ID or array of IDs)
274 class UFC_EducationSchool
implements UserFilterCondition
278 public function __construct()
280 $this->val
= pl_flatten(func_get_args());
283 public function buildCondition(PlFilter
&$uf)
285 $sub = $uf->addEducationFilter();
286 return XDB
::format('pe' . $sub . '.eduid IN {?}', $this->val
);
291 // {{{ class UFC_EducationDegree
292 class UFC_EducationDegree
implements UserFilterCondition
296 public function __construct()
298 $this->diploma
= pl_flatten(func_get_args());
301 public function buildCondition(PlFilter
&$uf)
303 $sub = $uf->addEducationFilter();
304 return XDB
::format('pe' . $sub . '.degreeid IN {?}', $this->diploma
);
309 // {{{ class UFC_EducationField
310 class UFC_EducationField
implements UserFilterCondition
314 public function __construct()
316 $this->val
= pl_flatten(func_get_args());
319 public function buildCondition(PlFilter
&$uf)
321 $sub = $uf->addEducationFilter();
322 return XDB
::format('pe' . $sub . '.fieldid IN {?}', $this->val
);
327 // {{{ class UFC_Name
328 /** Filters users based on name
329 * @param $type Type of name field on which filtering is done (firstname, lastname...)
330 * @param $text Text on which to filter
331 * @param $mode Flag indicating search type (prefix, suffix, with particule...)
333 class UFC_Name
implements UserFilterCondition
335 const EXACT
= XDB
::WILDCARD_EXACT
; // 0x000
336 const PREFIX
= XDB
::WILDCARD_PREFIX
; // 0x001
337 const SUFFIX
= XDB
::WILDCARD_SUFFIX
; // 0x002
338 const CONTAINS
= XDB
::WILDCARD_CONTAINS
; // 0x003
339 const PARTICLE
= 0x004;
340 const VARIANTS
= 0x008;
346 public function __construct($type, $text, $mode)
353 private function buildNameQuery($type, $variant, $where, UserFilter
&$uf)
355 $sub = $uf->addNameFilter($type, $variant);
356 return str_replace('$ME', 'pn' . $sub, $where);
359 public function buildCondition(PlFilter
&$uf)
362 if (($this->mode
& self
::PARTICLE
) == self
::PARTICLE
) {
363 $left = 'CONCAT($ME.particle, \' \', $ME.name)';
365 $right = XDB
::formatWildcards($this->mode
& self
::CONTAINS
, $this->text
);
367 $cond = $left . $right;
368 $conds = array($this->buildNameQuery($this->type
, null
, $cond, $uf));
369 if (($this->mode
& self
::VARIANTS
) != 0 && isset(Profile
::$name_variants[$this->type
])) {
370 foreach (Profile
::$name_variants[$this->type
] as $var) {
371 $conds[] = $this->buildNameQuery($this->type
, $var, $cond, $uf);
374 return implode(' OR ', $conds);
379 // {{{ class UFC_NameTokens
380 /** Selects users based on tokens in their name (for quicksearch)
381 * @param $tokens An array of tokens to search
382 * @param $flags Flags the tokens must have (e.g 'public' for public search)
383 * @param $soundex (bool) Whether those tokens are fulltext or soundex
385 class UFC_NameTokens
implements UserFilterCondition
388 const FLAG_PUBLIC
= 'public';
395 public function __construct($tokens, $flags = array(), $soundex = false
, $exact = false
)
397 if (is_array($tokens)) {
398 $this->tokens
= $tokens;
400 $this->tokens
= array($tokens);
402 if (is_array($flags)) {
403 $this->flags
= $flags;
405 $this->flags
= array($flags);
407 $this->soundex
= $soundex;
408 $this->exact
= $exact;
411 public function buildCondition(PlFilter
&$uf)
414 foreach ($this->tokens
as $i => $token) {
415 $sub = $uf->addNameTokensFilter($token);
416 if ($this->soundex
) {
417 $c = XDB
::format($sub . '.soundex = {?}', soundex_fr($token));
418 } else if ($this->exact
) {
419 $c = XDB
::format($sub . '.token = {?}', $token);
421 $c = $sub . '.token ' . XDB
::formatWildcards(XDB
::WILDCARD_PREFIX
, $token);
423 if ($this->flags
!= null
) {
424 $c .= XDB
::format(' AND ' . $sub . '.flags IN {?}', $this->flags
);
429 return implode(' AND ', $conds);
434 // {{{ class UFC_Nationality
435 class UFC_Nationality
implements UserFilterCondition
439 public function __construct()
441 $this->val
= pl_flatten(func_get_args());
444 public function buildCondition(PlFilter
&$uf)
446 $uf->requireProfiles();
447 $nat = XDB
::formatArray($this->val
);
449 'p.nationality1 IN ' . $nat,
450 'p.nationality2 IN ' . $nat,
451 'p.nationality3 IN ' . $nat,
453 return implode(' OR ', $conds);
458 // {{{ class UFC_Dead
459 /** Filters users based on death date
460 * @param $comparison Comparison operator
461 * @param $date Date to which death date should be compared (DateTime object, string or timestamp)
463 class UFC_Dead
implements UserFilterCondition
468 public function __construct($comparison = null
, $date = null
)
470 $this->comparison
= $comparison;
471 $this->date
= make_datetime($date);
474 public function buildCondition(PlFilter
&$uf)
476 $uf->requireProfiles();
477 $str = 'p.deathdate IS NOT NULL';
478 if (!is_null($this->comparison
)) {
479 $str .= ' AND p.deathdate ' . $this->comparison
. ' ' . XDB
::format('{?}', $this->date
->format('Y-m-d'));
486 // {{{ class UFC_Registered
487 /** Filters users based on registration state
488 * @param $active Whether we want to use only "active" users (i.e with a valid redirection)
489 * @param $comparison Comparison operator
490 * @param $date Date to which users registration date should be compared
492 class UFC_Registered
implements UserFilterCondition
498 public function __construct($active = false
, $comparison = null
, $date = null
)
500 $this->active
= $active;
501 $this->comparison
= $comparison;
502 $this->date
= make_datetime($date);
505 public function buildCondition(PlFilter
&$uf)
507 $uf->requireAccounts();
509 $date = '$UID IS NOT NULL AND a.state = \'active\'';
511 $date = '$UID IS NOT NULL AND a.state != \'pending\'';
513 if (!is_null($this->comparison
)) {
514 $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'));
521 // {{{ class UFC_ProfileUpdated
522 /** Filters users based on profile update date
523 * @param $comparison Comparison operator
524 * @param $date Date to which profile update date must be compared
526 class UFC_ProfileUpdated
implements UserFilterCondition
531 public function __construct($comparison = null
, $date = null
)
533 $this->comparison
= $comparison;
537 public function buildCondition(PlFilter
&$uf)
539 $uf->requireProfiles();
540 return 'p.last_change ' . $this->comparison
. XDB
::format(' {?}', date('Y-m-d H:i:s', $this->date
));
545 // {{{ class UFC_Birthday
546 /** Filters users based on next birthday date
547 * @param $comparison Comparison operator
548 * @param $date Date to which users next birthday date should be compared
550 class UFC_Birthday
implements UserFilterCondition
555 public function __construct($comparison = null
, $date = null
)
557 $this->comparison
= $comparison;
561 public function buildCondition(PlFilter
&$uf)
563 $uf->requireProfiles();
564 return 'p.next_birthday ' . $this->comparison
. XDB
::format(' {?}', date('Y-m-d', $this->date
));
570 /** Filters users based on sex
571 * @parm $sex One of User::GENDER_MALE or User::GENDER_FEMALE, for selecting users
573 class UFC_Sex
implements UserFilterCondition
576 public function __construct($sex)
581 public function buildCondition(PlFilter
&$uf)
583 if ($this->sex
!= User
::GENDER_MALE
&& $this->sex
!= User
::GENDER_FEMALE
) {
584 return self
::COND_FALSE
;
586 $uf->requireProfiles();
587 return XDB
::format('p.sex = {?}', $this->sex
== User
::GENDER_FEMALE ?
'female' : 'male');
593 // {{{ class UFC_Group
594 /** Filters users based on group membership
595 * @param $group Group whose members we are selecting
596 * @param $anim Whether to restrict selection to animators of that group
598 class UFC_Group
implements UserFilterCondition
602 public function __construct($group, $anim = false
)
604 $this->group
= $group;
608 public function buildCondition(PlFilter
&$uf)
610 // Groups have AX visibility.
611 if ($uf->getVisibilityLevel() == ProfileVisibility
::VIS_PUBLIC
) {
612 return self
::COND_TRUE
;
614 $sub = $uf->addGroupFilter($this->group
);
615 $where = 'gpm' . $sub . '.perms IS NOT NULL';
617 $where .= ' AND gpm' . $sub . '.perms = \'admin\'';
624 // {{{ class UFC_Binet
625 /** Selects users based on their belonging to a given (list of) binet
626 * @param $binet either a binet_id or an array of binet_ids
628 class UFC_Binet
implements UserFilterCondition
632 public function __construct()
634 $this->val
= pl_flatten(func_get_args());
637 public function buildCondition(PlFilter
&$uf)
639 // Binets are private.
640 if ($uf->getVisibilityLevel() != ProfileVisibility
::VIS_PRIVATE
) {
641 return self
::CONF_TRUE
;
643 $sub = $uf->addBinetsFilter();
644 return XDB
::format($sub . '.binet_id IN {?}', $this->val
);
649 // {{{ class UFC_Section
650 /** Selects users based on section
651 * @param $section ID of the section
653 class UFC_Section
implements UserFilterCondition
657 public function __construct()
659 $this->section
= pl_flatten(func_get_args());
662 public function buildCondition(PlFilter
&$uf)
664 // Sections are private.
665 if ($uf->getVisibilityLevel() != ProfileVisibility
::VIS_PRIVATE
) {
666 return self
::CONF_TRUE
;
668 $uf->requireProfiles();
669 return XDB
::format('p.section IN {?}', $this->section
);
674 // {{{ class UFC_Email
675 /** Filters users based on an email or a list of emails
676 * @param $emails List of emails whose owner must be selected
678 class UFC_Email
implements UserFilterCondition
681 public function __construct()
683 $this->emails
= pl_flatten(func_get_args());
686 public function buildCondition(PlFilter
&$uf)
693 if (count($this->emails
) == 0) {
694 return PlFilterCondition
::COND_TRUE
;
697 foreach ($this->emails
as $entry) {
698 if (User
::isForeignEmailAddress($entry)) {
700 } else if (User
::isVirtualEmailAddress($entry)) {
703 @list
($user, $domain) = explode('@', $entry);
708 if (count($foreign) > 0) {
709 $sub = $uf->addEmailRedirectFilter($foreign);
710 $cond[] = XDB
::format('e' . $sub . '.email IS NOT NULL OR a.email IN {?}', $foreign);
712 if (count($virtual) > 0) {
713 $sub = $uf->addVirtualEmailFilter($virtual);
714 $cond[] = 'vr' . $sub . '.redirect IS NOT NULL';
716 if (count($aliases) > 0) {
717 $sub = $uf->addAliasFilter($aliases);
718 $cond[] = 'al' . $sub . '.alias IS NOT NULL';
720 return '(' . implode(') OR (', $cond) . ')';
725 // {{{ class UFC_Address
726 abstract class UFC_Address
implements UserFilterCondition
728 /** Valid address type ('hq' is reserved for company addresses)
734 /** Text for these types
736 protected static $typetexts = array(
737 self
::TYPE_HOME
=> 'home',
738 self
::TYPE_PRO
=> 'pro',
743 /** Flags for addresses
745 const FLAG_CURRENT
= 0x0001;
746 const FLAG_TEMP
= 0x0002;
747 const FLAG_SECOND
= 0x0004;
748 const FLAG_MAIL
= 0x0008;
749 const FLAG_CEDEX
= 0x0010;
751 // Binary OR of those flags
752 const FLAG_ANY
= 0x001F;
754 /** Text of these flags
756 protected static $flagtexts = array(
757 self
::FLAG_CURRENT
=> 'current',
758 self
::FLAG_TEMP
=> 'temporary',
759 self
::FLAG_SECOND
=> 'secondary',
760 self
::FLAG_MAIL
=> 'mail',
761 self
::FLAG_CEDEX
=> 'cedex',
766 public function __construct($type = null
, $flags = null
)
769 $this->flags
= $flags;
772 protected function initConds($sub, $vis_cond)
774 $conds = array($vis_cond);
777 foreach (self
::$typetexts as $flag => $type) {
778 if ($flag & $this->type
) {
783 $conds[] = XDB
::format($sub . '.type IN {?}', $types);
786 if ($this->flags
!= self
::FLAG_ANY
) {
787 foreach(self
::$flagtexts as $flag => $text) {
788 if ($flag & $this->flags
) {
789 $conds[] = 'FIND_IN_SET(' . XDB
::format('{?}', $text) . ', ' . $sub . '.flags)';
799 // {{{ class UFC_AddressText
800 /** Select users based on their address, using full text search
801 * @param $text Text for filter in fulltext search
802 * @param $textSearchMode Mode for search (one of XDB::WILDCARD_*)
803 * @param $type Filter on address type
804 * @param $flags Filter on address flags
805 * @param $country Filter on address country
806 * @param $locality Filter on address locality
808 class UFC_AddressText
extends UFC_Address
812 private $textSearchMode;
814 public function __construct($text = null
, $textSearchMode = XDB
::WILDCARD_CONTAINS
,
815 $type = null
, $flags = self
::FLAG_ANY
, $country = null
, $locality = null
)
817 parent
::__construct($type, $flags);
819 $this->textSearchMode
= $textSearchMode;
820 $this->country
= $country;
821 $this->locality
= $locality;
824 private function mkMatch($txt)
826 return XDB
::formatWildcards($this->textSearchMode
, $txt);
829 public function buildCondition(PlFilter
&$uf)
831 $sub = $uf->addAddressFilter();
832 $conds = $this->initConds($sub, $uf->getVisibilityCondition($sub . '.pub'));
833 if ($this->text
!= null
) {
834 $conds[] = $sub . '.text' . $this->mkMatch($this->text
);
837 if ($this->country
!= null
) {
838 $subc = $uf->addAddressCountryFilter();
840 $subconds[] = $subc . '.country' . $this->mkMatch($this->country
);
841 $subconds[] = $subc . '.countryFR' . $this->mkMatch($this->country
);
842 $conds[] = implode(' OR ', $subconds);
845 if ($this->locality
!= null
) {
846 $subl = $uf->addAddressLocalityFilter();
847 $conds[] = $subl . '.name' . $this->mkMatch($this->locality
);
850 return implode(' AND ', $conds);
855 // {{{ class UFC_AddressField
856 /** Filters users based on their address,
857 * @param $val Either a code for one of the fields, or an array of such codes
858 * @param $fieldtype The type of field to look for
859 * @param $type Filter on address type
860 * @param $flags Filter on address flags
862 class UFC_AddressField
extends UFC_Address
864 const FIELD_COUNTRY
= 1;
865 const FIELD_ADMAREA
= 2;
866 const FIELD_SUBADMAREA
= 3;
867 const FIELD_LOCALITY
= 4;
868 const FIELD_ZIPCODE
= 5;
870 /** Data of the filter
875 public function __construct($val, $fieldtype, $type = null
, $flags = self
::FLAG_ANY
)
877 parent
::__construct($type, $flags);
879 if (!is_array($val)) {
883 $this->fieldtype
= $fieldtype;
886 public function buildCondition(PlFilter
&$uf)
888 $sub = $uf->addAddressFilter();
889 $conds = $this->initConds($sub, $uf->getVisibilityCondition($sub . '.pub'));
891 switch ($this->fieldtype
) {
892 case self
::FIELD_COUNTRY
:
893 $field = 'countryId';
895 case self
::FIELD_ADMAREA
:
896 $field = 'administrativeAreaId';
898 case self
::FIELD_SUBADMAREA
:
899 $field = 'subAdministrativeAreaId';
901 case self
::FIELD_LOCALITY
:
902 $field = 'localityId';
904 case self
::FIELD_ZIPCODE
:
905 $field = 'postalCode';
908 Platal
::page()->killError('Invalid address field type: ' . $this->fieldtype
);
910 $conds[] = XDB
::format($sub . '.' . $field . ' IN {?}', $this->val
);
912 return implode(' AND ', $conds);
917 // {{{ class UFC_Corps
918 /** Filters users based on the corps they belong to
919 * @param $corps Corps we are looking for (abbreviation)
920 * @param $type Whether we search for original or current corps
922 class UFC_Corps
implements UserFilterCondition
930 public function __construct($corps, $type = self
::CURRENT
)
932 $this->corps
= $corps;
936 public function buildCondition(PlFilter
&$uf)
938 /** Tables shortcuts:
939 * pc for profile_corps,
940 * pceo for profile_corps_enum - orginal
941 * pcec for profile_corps_enum - current
943 $sub = $uf->addCorpsFilter($this->type
);
944 $cond = $sub . '.abbreviation = ' . $corps;
945 $cond .= ' AND ' . $uf->getVisibilityCondition($sub . '.corps_pub');
951 // {{{ class UFC_Corps_Rank
952 /** Filters users based on their rank in the corps
953 * @param $rank Rank we are looking for (abbreviation)
955 class UFC_Corps_Rank
implements UserFilterCondition
958 public function __construct($rank)
963 public function buildCondition(PlFilter
&$uf)
965 /** Tables shortcuts:
966 * pc for profile_corps
967 * pcr for profile_corps_rank
969 $sub = $uf->addCorpsRankFilter();
970 $cond = $sub . '.abbreviation = ' . $rank;
971 // XXX(x2006barrois): find a way to get rid of that hardcoded
972 // reference to 'pc'.
973 $cond .= ' AND ' . $uf->getVisibilityCondition('pc.corps_pub');
979 // {{{ class UFC_Job_Company
980 /** Filters users based on the company they belong to
981 * @param $type The field being searched (self::JOBID, self::JOBNAME or self::JOBACRONYM)
982 * @param $value The searched value
984 class UFC_Job_Company
implements UserFilterCondition
987 const JOBNAME
= 'name';
988 const JOBACRONYM
= 'acronym';
993 public function __construct($type, $value)
995 $this->assertType($type);
997 $this->value
= $value;
1000 private function assertType($type)
1002 if ($type != self
::JOBID
&& $type != self
::JOBNAME
&& $type != self
::JOBACRONYM
) {
1003 Platal
::page()->killError("Type de recherche non valide.");
1007 public function buildCondition(PlFilter
&$uf)
1009 $sub = $uf->addJobCompanyFilter();
1010 $cond = $sub . '.' . $this->type
. XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->value
);
1011 $jsub = $uf->addJobFilter();
1012 $cond .= ' AND ' . $uf->getVisibilityCondition($jsub . '.pub');
1018 // {{{ class UFC_Job_Terms
1019 /** Filters users based on the job terms they assigned to one of their
1021 * @param $val The ID of the job term, or an array of such IDs
1023 class UFC_Job_Terms
implements UserFilterCondition
1027 public function __construct($val)
1029 if (!is_array($val)) {
1035 public function buildCondition(PlFilter
&$uf)
1037 $sub = $uf->addJobTermsFilter(count($this->val
));
1038 $conditions = array();
1039 foreach ($this->val
as $i => $jtid) {
1040 $conditions[] = $sub[$i] . '.jtid_1 = ' . XDB
::escape($jtid);
1042 $jsub = $uf->addJobFilter();
1043 $conditions[] = $uf->getVisibilityCondition($jsub . '.pub');
1044 return implode(' AND ', $conditions);
1049 // {{{ class UFC_Job_Description
1050 /** Filters users based on their job description
1051 * @param $description The text being searched for
1052 * @param $fields The fields to search for (CV, user-defined)
1054 class UFC_Job_Description
implements UserFilterCondition
1057 private $description;
1060 public function __construct($description, $fields)
1062 $this->fields
= $fields;
1063 $this->description
= $description;
1066 public function buildCondition(PlFilter
&$uf)
1070 $jsub = $uf->addJobFilter();
1071 // CV is private => if only CV requested, and not private,
1072 // don't do anything. Otherwise restrict to standard job visibility.
1073 if ($this->fields
== UserFilter
::JOB_CV
) {
1074 if ($uf->getVisibilityLevel() != ProfileVisibility
::VIS_PRIVATE
) {
1075 return self
::CONF_TRUE
;
1078 $conds[] = $uf->getVisibilityCondition($jsub . '.pub');
1081 if ($this->fields
& UserFilter
::JOB_USERDEFINED
) {
1082 $conds[] = $jsub . '.description ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->description
);
1084 if ($this->fields
& UserFilter
::JOB_CV
&& $uf->getVisibilityLevel() == ProfileVisibility
::VIS_PRIVATE
) {
1085 $uf->requireProfiles();
1086 $conds[] = 'p.cv ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->description
);
1088 return implode(' OR ', $conds);
1093 // {{{ class UFC_Networking
1094 /** Filters users based on network identity (IRC, ...)
1095 * @param $type Type of network (-1 for any)
1096 * @param $value Value to search
1098 class UFC_Networking
implements UserFilterCondition
1103 public function __construct($type, $value)
1105 $this->type
= $type;
1106 $this->value
= $value;
1109 public function buildCondition(PlFilter
&$uf)
1111 $sub = $uf->addNetworkingFilter();
1113 $conds[] = $uf->getVisibilityCondition($sub . '.pub');
1114 $conds[] = $sub . '.address ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->value
);
1115 if ($this->type
!= -1) {
1116 $conds[] = $sub . '.nwid = ' . XDB
::format('{?}', $this->type
);
1118 return implode(' AND ', $conds);
1123 // {{{ class UFC_Phone
1124 /** Filters users based on their phone number
1125 * @param $num_type Type of number (pro/user/home)
1126 * @param $phone_type Type of phone (fixed/mobile/fax)
1127 * @param $number Phone number
1129 class UFC_Phone
implements UserFilterCondition
1131 const NUM_PRO
= 'pro';
1132 const NUM_USER
= 'user';
1133 const NUM_HOME
= 'address';
1134 const NUM_ANY
= 'any';
1136 const PHONE_FIXED
= 'fixed';
1137 const PHONE_MOBILE
= 'mobile';
1138 const PHONE_FAX
= 'fax';
1139 const PHONE_ANY
= 'any';
1142 private $phone_type;
1145 public function __construct($number, $num_type = self
::NUM_ANY
, $phone_type = self
::PHONE_ANY
)
1147 $phone = new Phone(array('display' => $number));
1149 $this->number
= $phone->search();
1150 $this->num_type
= $num_type;
1151 $this->phone_type
= $phone_type;
1154 public function buildCondition(PlFilter
&$uf)
1156 $sub = $uf->addPhoneFilter();
1159 $conds[] = $uf->getVisibilityCondition($sub . '.pub');
1161 $conds[] = $sub . '.search_tel = ' . XDB
::format('{?}', $this->number
);
1162 if ($this->num_type
!= self
::NUM_ANY
) {
1163 $conds[] = $sub . '.link_type = ' . XDB
::format('{?}', $this->num_type
);
1165 if ($this->phone_type
!= self
::PHONE_ANY
) {
1166 $conds[] = $sub . '.tel_type = ' . XDB
::format('{?}', $this->phone_type
);
1168 return implode(' AND ', $conds);
1173 // {{{ class UFC_Medal
1174 /** Filters users based on their medals
1175 * @param $medal ID of the medal
1176 * @param $grade Grade of the medal (null for 'any')
1178 class UFC_Medal
implements UserFilterCondition
1183 public function __construct($medal, $grade = null
)
1185 $this->medal
= $medal;
1186 $this->grade
= $grade;
1189 public function buildCondition(PlFilter
&$uf)
1193 // This will require profiles => table 'p' will be available.
1194 $sub = $uf->addMedalFilter();
1196 $conds[] = $uf->getVisibilityCondition('p.medals_pub');
1198 $conds[] = $sub . '.mid = ' . XDB
::format('{?}', $this->medal
);
1199 if ($this->grade
!= null
) {
1200 $conds[] = $sub . '.gid = ' . XDB
::format('{?}', $this->grade
);
1202 return implode(' AND ', $conds);
1207 // {{{ class UFC_Photo
1208 /** Filters profiles with photo
1210 class UFC_Photo
implements UserFilterCondition
1212 public function buildCondition(PlFilter
&$uf)
1214 $sub = $uf->addPhotoFilter();
1215 return $sub . '.attach IS NOT NULL AND ' . $uf->getVisibilityCondition($sub . '.pub');
1220 // {{{ class UFC_Mentor
1221 class UFC_Mentor
implements UserFilterCondition
1223 public function buildCondition(PlFilter
&$uf)
1225 $sub = $uf->addMentorFilter(UserFilter
::MENTOR
);
1226 return $sub . '.expertise IS NOT NULL';
1232 // {{{ class UFC_Mentor_Expertise
1233 /** Filters users by mentoring expertise
1234 * @param $expertise Domain of expertise
1236 class UFC_Mentor_Expertise
implements UserFilterCondition
1240 public function __construct($expertise)
1242 $this->expertise
= $expertise;
1245 public function buildCondition(PlFilter
&$uf)
1247 $sub = $uf->addMentorFilter(UserFilter
::MENTOR_EXPERTISE
);
1248 return $sub . '.expertise ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->expertise
);
1253 // {{{ class UFC_Mentor_Country
1254 /** Filters users by mentoring country
1255 * @param $country Two-letters code of country being searched
1257 class UFC_Mentor_Country
implements UserFilterCondition
1261 public function __construct()
1263 $this->country
= pl_flatten(func_get_args());
1266 public function buildCondition(PlFilter
&$uf)
1268 $sub = $uf->addMentorFilter(UserFilter
::MENTOR_COUNTRY
);
1269 return $sub . '.country IN ' . XDB
::format('{?}', $this->country
);
1274 // {{{ class UFC_Mentor_Terms
1275 /** Filters users based on the job terms they used in mentoring.
1276 * @param $val The ID of the job term, or an array of such IDs
1278 class UFC_Mentor_Terms
implements UserFilterCondition
1282 public function __construct($val)
1287 public function buildCondition(PlFilter
&$uf)
1289 $sub = $uf->addMentorFilter(UserFilter
::MENTOR_TERM
);
1290 return $sub . '.jtid_1 = ' . XDB
::escape($this->val
);
1295 // {{{ class UFC_UserRelated
1296 /** Filters users based on a relation toward a user
1297 * @param $user User to which searched users are related
1299 abstract class UFC_UserRelated
implements UserFilterCondition
1302 public function __construct(PlUser
&$user)
1304 $this->user
=& $user;
1309 // {{{ class UFC_Contact
1310 /** Filters users who belong to selected user's contacts
1312 class UFC_Contact
extends UFC_UserRelated
1314 public function buildCondition(PlFilter
&$uf)
1316 $sub = $uf->addContactFilter($this->user
->id());
1317 return 'c' . $sub . '.contact IS NOT NULL';
1322 // {{{ class UFC_WatchRegistration
1323 /** Filters users being watched by selected user
1325 class UFC_WatchRegistration
extends UFC_UserRelated
1327 public function buildCondition(PlFilter
&$uf)
1329 if (!$this->user
->watchType('registration')) {
1330 return PlFilterCondition
::COND_FALSE
;
1332 $uids = $this->user
->watchUsers();
1333 if (count($uids) == 0) {
1334 return PlFilterCondition
::COND_FALSE
;
1336 return XDB
::format('$UID IN {?}', $uids);
1342 // {{{ class UFC_WatchPromo
1343 /** Filters users belonging to a promo watched by selected user
1344 * @param $user Selected user (the one watching promo)
1345 * @param $grade Formation the user is watching
1347 class UFC_WatchPromo
extends UFC_UserRelated
1350 public function __construct(PlUser
&$user, $grade = UserFilter
::GRADE_ING
)
1352 parent
::__construct($user);
1353 $this->grade
= $grade;
1356 public function buildCondition(PlFilter
&$uf)
1358 $promos = $this->user
->watchPromos();
1359 if (count($promos) == 0) {
1360 return PlFilterCondition
::COND_FALSE
;
1362 $sube = $uf->addEducationFilter(true
, $this->grade
);
1363 $field = 'pe' . $sube . '.' . UserFilter
::promoYear($this->grade
);
1364 return XDB
::format($field . ' IN {?}', $promos);
1370 // {{{ class UFC_WatchContact
1371 /** Filters users watched by selected user
1373 class UFC_WatchContact
extends UFC_Contact
1375 public function buildCondition(PlFilter
&$uf)
1377 if (!$this->user
->watchContacts()) {
1378 return PlFilterCondition
::COND_FALSE
;
1380 return parent
::buildCondition($uf);
1385 // {{{ class UFC_MarketingHash
1386 /** Filters users using the hash generated
1387 * to send marketing emails to him.
1389 class UFC_MarketingHash
implements UserFilterCondition
1393 public function __construct($hash)
1395 $this->hash
= $hash;
1398 public function buildCondition(PlFilter
&$uf)
1400 $table = $uf->addMarketingHash();
1401 return XDB
::format('rm.hash = {?}', $this->hash
);
1410 // {{{ class UFO_Promo
1411 /** Orders users by promotion
1412 * @param $grade Formation whose promotion users should be sorted by (restricts results to users of that formation)
1413 * @param $desc Whether sort is descending
1415 class UFO_Promo
extends PlFilterGroupableOrder
1419 public function __construct($grade = null
, $desc = false
)
1421 parent
::__construct($desc);
1422 $this->grade
= $grade;
1425 protected function getSortTokens(PlFilter
&$uf)
1427 if (UserFilter
::isGrade($this->grade
)) {
1428 $sub = $uf->addEducationFilter($this->grade
);
1429 return 'pe' . $sub . '.' . UserFilter
::promoYear($this->grade
);
1431 $sub = $uf->addDisplayFilter();
1432 return 'pd' . $sub . '.promo';
1438 // {{{ class UFO_Name
1439 /** Sorts users by name
1440 * @param $type Type of name on which to sort (firstname...)
1441 * @param $variant Variant of that name to use (marital, ordinary...)
1442 * @param $particle Set to true if particles should be included in the sorting order
1443 * @param $desc If sort order should be descending
1445 class UFO_Name
extends PlFilterOrder
1451 public function __construct($type, $variant = null
, $particle = false
, $desc = false
)
1453 parent
::__construct($desc);
1454 $this->type
= $type;
1455 $this->variant
= $variant;
1456 $this->particle
= $particle;
1459 protected function getSortTokens(PlFilter
&$uf)
1461 if (Profile
::isDisplayName($this->type
)) {
1462 $sub = $uf->addDisplayFilter();
1463 $token = 'pd' . $sub . '.' . $this->type
;
1464 if ($uf->accountsRequired()) {
1465 $account_token = Profile
::getAccountEquivalentName($this->type
);
1466 return 'IFNULL(' . $token . ', a.' . $account_token . ')';
1471 $sub = $uf->addNameFilter($this->type
, $this->variant
);
1472 if ($this->particle
) {
1473 return 'CONCAT(pn' . $sub . '.particle, \' \', pn' . $sub . '.name)';
1475 return 'pn' . $sub . '.name';
1482 // {{{ class UFO_Score
1483 class UFO_Score
extends PlFilterOrder
1485 protected function getSortTokens(PlFilter
&$uf)
1487 $toks = $uf->getNameTokens();
1490 // If there weren't any sort tokens, we shouldn't sort by score, sort by NULL instead
1491 if (count($toks) == 0) {
1495 foreach ($toks as $sub => $token) {
1496 $scores[] = XDB
::format('SUM(' . $sub . '.score + IF (' . $sub . '.token = {?}, 5, 0) )', $token);
1498 return implode(' + ', $scores);
1503 // {{{ class UFO_Registration
1504 /** Sorts users based on registration date
1506 class UFO_Registration
extends PlFilterOrder
1508 protected function getSortTokens(PlFilter
&$uf)
1510 $uf->requireAccounts();
1511 return 'a.registration_date';
1516 // {{{ class UFO_Birthday
1517 /** Sorts users based on next birthday date
1519 class UFO_Birthday
extends PlFilterOrder
1521 protected function getSortTokens(PlFilter
&$uf)
1523 $uf->requireProfiles();
1524 return 'p.next_birthday';
1529 // {{{ class UFO_ProfileUpdate
1530 /** Sorts users based on last profile update
1532 class UFO_ProfileUpdate
extends PlFilterOrder
1534 protected function getSortTokens(PlFilter
&$uf)
1536 $uf->requireProfiles();
1537 return 'p.last_change';
1542 // {{{ class UFO_Death
1543 /** Sorts users based on death date
1545 class UFO_Death
extends PlFilterOrder
1547 protected function getSortTokens(PlFilter
&$uf)
1549 $uf->requireProfiles();
1550 return 'p.deathdate';
1555 // {{{ class UFO_Uid
1556 /** Sorts users based on their uid
1558 class UFO_Uid
extends PlFilterOrder
1560 protected function getSortTokens(PlFilter
&$uf)
1562 $uf->requireAccounts();
1568 // {{{ class UFO_Hruid
1569 /** Sorts users based on their hruid
1571 class UFO_Hruid
extends PlFilterOrder
1573 protected function getSortTokens(PlFilter
&$uf)
1575 $uf->requireAccounts();
1581 // {{{ class UFO_Pid
1582 /** Sorts users based on their pid
1584 class UFO_Pid
extends PlFilterOrder
1586 protected function getSortTokens(PlFilter
&$uf)
1588 $uf->requireProfiles();
1594 // {{{ class UFO_Hrpid
1595 /** Sorts users based on their hrpid
1597 class UFO_Hrpid
extends PlFilterOrder
1599 protected function getSortTokens(PlFilter
&$uf)
1601 $uf->requireProfiles();
1608 /***********************************
1609 *********************************
1611 *********************************
1612 ***********************************/
1614 // {{{ class UserFilter
1615 /** This class provides a convenient and centralized way of filtering users.
1618 * $uf = new UserFilter(new UFC_Blah($x, $y), new UFO_Coin($z, $t));
1620 * Resulting UserFilter can be used to:
1621 * - get a list of User objects matching the filter
1622 * - get a list of UIDs matching the filter
1623 * - get the number of users matching the filter
1624 * - check whether a given User matches the filter
1625 * - filter a list of User objects depending on whether they match the filter
1627 * Usage for UFC and UFO objects:
1628 * A UserFilter will call all private functions named XXXJoins.
1629 * These functions must return an array containing the list of join
1630 * required by the various UFC and UFO associated to the UserFilter.
1631 * Entries in those returned array are of the following form:
1632 * 'join_tablealias' => array('join_type', 'joined_table', 'join_criter')
1633 * which will be translated into :
1634 * join_type JOIN joined_table AS join_tablealias ON (join_criter)
1635 * in the final query.
1637 * In the join_criter text, $ME is replaced with 'join_tablealias', $PID with
1638 * profile.pid, and $UID with accounts.uid.
1640 * For each kind of "JOIN" needed, a function named addXXXFilter() should be defined;
1641 * its parameter will be used to set various private vars of the UserFilter describing
1642 * the required joins ; such a function shall return the "join_tablealias" to use
1643 * when referring to the joined table.
1645 * For example, if data from profile_job must be available to filter results,
1646 * the UFC object will call $uf-addJobFilter(), which will set the 'with_pj' var and
1647 * return 'pj', the short name to use when referring to profile_job; when building
1648 * the query, calling the jobJoins function will return an array containing a single
1650 * 'pj' => array('left', 'profile_job', '$ME.pid = $UID');
1652 * The 'register_optional' function can be used to generate unique table aliases when
1653 * the same table has to be joined several times with different aliases.
1655 class UserFilter
extends PlFilter
1657 protected $joinMethods = array();
1659 protected $joinMetas = array(
1665 private $sort = array();
1666 private $grouper = null
;
1667 private $query = null
;
1668 private $orderby = null
;
1670 // Store the current 'search' visibility.
1671 private $profile_visibility = null
;
1673 private $lastusercount = null
;
1674 private $lastprofilecount = null
;
1676 public function __construct($cond = null
, $sort = null
)
1678 if (empty($this->joinMethods
)) {
1679 $class = new ReflectionClass('UserFilter');
1680 foreach ($class->getMethods() as $method) {
1681 $name = $method->getName();
1682 if (substr($name, -5) == 'Joins' && $name != 'buildJoins') {
1683 $this->joinMethods
[] = $name;
1687 if (!is_null($cond)) {
1688 if ($cond instanceof PlFilterCondition
) {
1689 $this->setCondition($cond);
1692 if (!is_null($sort)) {
1693 if ($sort instanceof PlFilterOrder
) {
1694 $this->addSort($sort);
1695 } else if (is_array($sort)) {
1696 foreach ($sort as $s) {
1702 // This will set the visibility to the default correct level.
1703 $this->profile_visibility
= new ProfileVisibility();
1706 public function getVisibilityLevels()
1708 return $this->profile_visibility
->levels();
1711 public function getVisibilityLevel()
1713 return $this->profile_visibility
->level();
1716 public function restrictVisibilityTo($level)
1718 $this->profile_visibility
->setLevel($level);
1721 public function getVisibilityCondition($field)
1723 return $field . ' IN ' . XDB
::formatArray($this->getVisibilityLevels());
1726 private function buildQuery()
1728 // The root condition is built first because some orders need info
1729 // available only once all UFC have set their conditions (UFO_Score)
1730 if (is_null($this->query
)) {
1731 $where = $this->root
->buildCondition($this);
1732 $where = str_replace(array_keys($this->joinMetas
),
1736 if (is_null($this->orderby
)) {
1738 foreach ($this->sort
as $sort) {
1739 $orders = array_merge($orders, $sort->buildSort($this));
1741 if (count($orders) == 0) {
1742 $this->orderby
= '';
1744 $this->orderby
= 'ORDER BY ' . implode(', ', $orders);
1746 $this->orderby
= str_replace(array_keys($this->joinMetas
),
1750 if (is_null($this->query
)) {
1751 if ($this->with_accounts
) {
1752 $from = 'accounts AS a';
1754 $this->requireProfiles();
1755 $from = 'profiles AS p';
1757 $joins = $this->buildJoins();
1758 $this->query
= 'FROM ' . $from . '
1760 WHERE (' . $where . ')';
1764 public function hasGroups()
1766 return $this->grouper
!= null
;
1769 public function getGroups()
1771 return $this->getUIDGroups();
1774 public function getUIDGroups()
1776 $this->requireAccounts();
1777 $this->buildQuery();
1778 $token = $this->grouper
->getGroupToken($this);
1780 $groups = XDB
::rawFetchAllRow('SELECT ' . $token . ', COUNT(a.uid)
1781 ' . $this->query
. '
1782 GROUP BY ' . $token,
1787 public function getPIDGroups()
1789 $this->requireProfiles();
1790 $this->buildQuery();
1791 $token = $this->grouper
->getGroupToken($this);
1793 $groups = XDB
::rawFetchAllRow('SELECT ' . $token . ', COUNT(p.pid)
1794 ' . $this->query
. '
1795 GROUP BY ' . $token,
1800 private function getUIDList($uids = null
, PlLimit
&$limit)
1802 $this->requireAccounts();
1803 $this->buildQuery();
1804 $lim = $limit->getSql();
1806 if (!empty($uids)) {
1807 $cond = XDB
::format(' AND a.uid IN {?}', $uids);
1809 $fetched = XDB
::rawFetchColumn('SELECT SQL_CALC_FOUND_ROWS a.uid
1810 ' . $this->query
. $cond . '
1812 ' . $this->orderby
. '
1814 $this->lastusercount
= (int)XDB
::fetchOneCell('SELECT FOUND_ROWS()');
1818 private function getPIDList($pids = null
, PlLimit
&$limit)
1820 $this->requireProfiles();
1821 $this->buildQuery();
1822 $lim = $limit->getSql();
1824 if (!is_null($pids)) {
1825 $cond = XDB
::format(' AND p.pid IN {?}', $pids);
1827 $fetched = XDB
::rawFetchColumn('SELECT SQL_CALC_FOUND_ROWS p.pid
1828 ' . $this->query
. $cond . '
1830 ' . $this->orderby
. '
1832 $this->lastprofilecount
= (int)XDB
::fetchOneCell('SELECT FOUND_ROWS()');
1836 private static function defaultLimit($limit) {
1837 if ($limit == null
) {
1838 return new PlLimit();
1844 /** Check that the user match the given rule.
1846 public function checkUser(PlUser
&$user)
1848 $this->requireAccounts();
1849 $this->buildQuery();
1850 $count = (int)XDB
::rawFetchOneCell('SELECT COUNT(*)
1852 . XDB
::format(' AND a.uid = {?}', $user->id()));
1856 /** Check that the profile match the given rule.
1858 public function checkProfile(Profile
&$profile)
1860 $this->requireProfiles();
1861 $this->buildQuery();
1862 $count = (int)XDB
::rawFetchOneCell('SELECT COUNT(*)
1864 . XDB
::format(' AND p.pid = {?}', $profile->id()));
1868 /** Default filter is on users
1870 public function filter(array $users, $limit = null
)
1872 return $this->filterUsers($users, self
::defaultLimit($limit));
1875 /** Filter a list of users to extract the users matching the rule.
1877 public function filterUsers(array $users, $limit = null
)
1879 $limit = self
::defaultLimit($limit);
1880 $this->requireAccounts();
1881 $this->buildQuery();
1884 foreach ($users as $user) {
1885 if ($user instanceof PlUser
) {
1891 $table[$uid] = $user;
1893 $fetched = $this->getUIDList($uids, $limit);
1895 foreach ($fetched as $uid) {
1896 $output[] = $table[$uid];
1901 /** Filter a list of profiles to extract the users matching the rule.
1903 public function filterProfiles(array $profiles, $limit = null
)
1905 $limit = self
::defaultLimit($limit);
1906 $this->requireProfiles();
1907 $this->buildQuery();
1910 foreach ($profiles as $profile) {
1911 if ($profile instanceof Profile
) {
1912 $pid = $profile->id();
1917 $table[$pid] = $profile;
1919 $fetched = $this->getPIDList($pids, $limit);
1921 foreach ($fetched as $pid) {
1922 $output[] = $table[$pid];
1927 public function getUIDs($limit = null
)
1929 $limit = self
::defaultLimit($limit);
1930 return $this->getUIDList(null
, $limit);
1933 public function getUID($pos = 0)
1935 $uids =$this->getUIDList(null
, new PlLimit(1, $pos));
1936 if (count($uids) == 0) {
1943 public function getPIDs($limit = null
)
1945 $limit = self
::defaultLimit($limit);
1946 return $this->getPIDList(null
, $limit);
1949 public function getPID($pos = 0)
1951 $pids =$this->getPIDList(null
, new PlLimit(1, $pos));
1952 if (count($pids) == 0) {
1959 public function getUsers($limit = null
)
1961 return User
::getBulkUsersWithUIDs($this->getUIDs($limit));
1964 public function getUser($pos = 0)
1966 $uid = $this->getUID($pos);
1970 return User
::getWithUID($uid);
1974 public function iterUsers($limit = null
)
1976 return User
::iterOverUIDs($this->getUIDs($limit));
1979 public function getProfiles($limit = null
, $fields = 0x0000, $visibility = null
)
1981 return Profile
::getBulkProfilesWithPIDs($this->getPIDs($limit), $fields, $visibility);
1984 public function getProfile($pos = 0, $fields = 0x0000, $visibility = null
)
1986 $pid = $this->getPID($pos);
1990 return Profile
::get($pid, $fields, $visibility);
1994 public function iterProfiles($limit = null
, $fields = 0x0000, $visibility = null
)
1996 return Profile
::iterOverPIDs($this->getPIDs($limit), true
, $fields, $visibility);
1999 public function get($limit = null
)
2001 return $this->getUsers($limit);
2005 public function getTotalCount()
2007 return $this->getTotalUserCount();
2010 public function getTotalUserCount()
2012 if (is_null($this->lastusercount
)) {
2013 $this->requireAccounts();
2014 $this->buildQuery();
2015 return (int)XDB
::rawFetchOneCell('SELECT COUNT(DISTINCT a.uid)
2018 return $this->lastusercount
;
2022 public function getTotalProfileCount()
2024 if (is_null($this->lastprofilecount
)) {
2025 $this->requireProfiles();
2026 $this->buildQuery();
2027 return (int)XDB
::rawFetchOneCell('SELECT COUNT(DISTINCT p.pid)
2030 return $this->lastprofilecount
;
2034 public function setCondition(PlFilterCondition
&$cond)
2036 $this->root
=& $cond;
2037 $this->query
= null
;
2040 public function addSort(PlFilterOrder
&$sort)
2042 if (count($this->sort
) == 0 && $sort instanceof PlFilterGroupableOrder
)
2044 $this->grouper
= $sort;
2046 $this->sort
[] = $sort;
2047 $this->orderby
= null
;
2050 static public function getLegacy($promo_min, $promo_max)
2052 if ($promo_min != 0) {
2053 $min = new UFC_Promo('>=', self
::GRADE_ING
, intval($promo_min));
2055 $min = new PFC_True();
2057 if ($promo_max != 0) {
2058 $max = new UFC_Promo('<=', self
::GRADE_ING
, intval($promo_max));
2060 $max = new PFC_True();
2062 return new UserFilter(new PFC_And($min, $max));
2065 static public function sortByName()
2067 return array(new UFO_Name(Profile
::LASTNAME
), new UFO_Name(Profile
::FIRSTNAME
));
2070 static public function sortByPromo()
2072 return array(new UFO_Promo(), new UFO_Name(Profile
::LASTNAME
), new UFO_Name(Profile
::FIRSTNAME
));
2075 static private function getDBSuffix($string)
2077 if (is_array($string)) {
2078 if (count($string) == 1) {
2079 return self
::getDBSuffix(array_pop($string));
2081 return md5(implode('|', $string));
2083 return preg_replace('/[^a-z0-9]/i', '', $string);
2088 /** Stores a new (and unique) table alias in the &$table table
2089 * @param &$table Array in which the table alias must be stored
2090 * @param $val Value which will then be used to build the join
2091 * @return Name of the newly created alias
2093 private $option = 0;
2094 private function register_optional(array &$table, $val)
2096 if (is_null($val)) {
2097 $sub = $this->option++
;
2100 $sub = self
::getDBSuffix($val);
2104 $table[$sub] = $index;
2108 /** PROFILE VS ACCOUNT
2110 private $with_profiles = false
;
2111 private $with_accounts = false
;
2112 public function requireAccounts()
2114 $this->with_accounts
= true
;
2117 public function accountsRequired()
2119 return $this->with_accounts
;
2122 public function requireProfiles()
2124 $this->with_profiles
= true
;
2127 public function profilesRequired()
2129 return $this->with_profiles
;
2132 protected function accountJoins()
2135 if ($this->with_profiles
&& $this->with_accounts
) {
2136 $joins['ap'] = PlSqlJoin
::left('account_profiles', '$ME.uid = $UID AND FIND_IN_SET(\'owner\', ap.perms)');
2137 $joins['p'] = PlSqlJoin
::left('profiles', '$PID = ap.pid');
2144 private $at = false
;
2145 public function requirePerms()
2147 $this->requireAccounts();
2152 protected function permJoins()
2155 return array('at' => PlSqlJoin
::left('account_types', '$ME.type = a.type'));
2163 const DISPLAY
= 'display';
2164 private $pd = false
;
2165 public function addDisplayFilter()
2167 $this->requireProfiles();
2172 protected function displayJoins()
2175 return array('pd' => PlSqlJoin
::left('profile_display', '$ME.pid = $PID'));
2184 private $with_logger = false
;
2185 public function addLoggerFilter()
2187 $this->with_logger
= true
;
2188 $this->requireAccounts();
2191 protected function loggerJoins()
2194 if ($this->with_logger
) {
2195 $joins['ls'] = PlSqlJoin
::left('log_sessions', '$ME.uid = $UID');
2203 static public function assertName($name)
2205 if (!DirEnum
::getID(DirEnum
::NAMETYPES
, $name)) {
2206 Platal
::page()->kill('Invalid name type: ' . $name);
2210 private $pn = array();
2211 public function addNameFilter($type, $variant = null
)
2213 $this->requireProfiles();
2214 if (!is_null($variant)) {
2215 $ft = $type . '_' . $variant;
2220 self
::assertName($ft);
2222 if (!is_null($variant) && $variant == 'other') {
2223 $sub .= $this->option++
;
2225 $this->pn
[$sub] = DirEnum
::getID(DirEnum
::NAMETYPES
, $ft);
2229 protected function nameJoins()
2232 foreach ($this->pn
as $sub => $type) {
2233 $joins['pn' . $sub] = PlSqlJoin
::left('profile_name', '$ME.pid = $PID AND $ME.typeid = {?}', $type);
2240 private $name_tokens = array();
2241 private $nb_tokens = 0;
2243 public function addNameTokensFilter($token)
2245 $this->requireProfiles();
2246 $sub = 'sn' . (1 +
$this->nb_tokens
);
2248 $this->name_tokens
[$sub] = $token;
2252 protected function nameTokensJoins()
2254 /* We don't return joins, since with_sn forces the SELECT to run on search_name first */
2256 foreach ($this->name_tokens
as $sub => $token) {
2257 $joins[$sub] = PlSqlJoin
::left('search_name', '$ME.pid = $PID');
2262 public function getNameTokens()
2264 return $this->name_tokens
;
2270 private $with_nat = false
;
2271 public function addNationalityFilter()
2273 $this->with_nat
= true
;
2277 protected function nationalityJoins()
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');
2288 const GRADE_ING
= 'Ing.';
2289 const GRADE_PHD
= 'PhD';
2290 const GRADE_MST
= 'M%';
2291 static public function isGrade($grade)
2293 return ($grade !== 0) && ($grade == self
::GRADE_ING ||
$grade == self
::GRADE_PHD ||
$grade == self
::GRADE_MST
);
2296 static public function assertGrade($grade)
2298 if (!self
::isGrade($grade)) {
2299 Platal
::page()->killError("Diplôme non valide: $grade");
2303 static public function promoYear($grade)
2305 // XXX: Definition of promotion for phds and masters might change in near future.
2306 return ($grade == UserFilter
::GRADE_ING
) ?
'entry_year' : 'grad_year';
2309 private $pepe = array();
2310 private $with_pee = false
;
2311 public function addEducationFilter($x = false
, $grade = null
)
2313 $this->requireProfiles();
2315 $index = $this->option
;
2316 $sub = $this->option++
;
2318 self
::assertGrade($grade);
2321 $this->with_pee
= true
;
2324 $this->pepe
[$index] = $sub;
2328 protected function educationJoins()
2331 if ($this->with_pee
) {
2332 $joins['pee'] = PlSqlJoin
::inner('profile_education_enum', 'pee.abbreviation = \'X\'');
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);
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');
2350 private $gpm = array();
2351 public function addGroupFilter($group = null
)
2353 $this->requireAccounts();
2354 if (!is_null($group)) {
2355 if (is_int($group) ||
ctype_digit($group)) {
2356 $index = $sub = $group;
2359 $sub = self
::getDBSuffix($group);
2362 $sub = 'group_' . $this->option++
;
2366 $this->gpm
[$sub] = $index;
2370 protected function groupJoins()
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);
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');
2390 private $with_bi = false
;
2391 private $with_bd = false
;
2392 public function addBinetsFilter($with_enum = false
)
2394 $this->requireProfiles();
2395 $this->with_bi
= true
;
2397 $this->with_bd
= true
;
2404 protected function binetsJoins()
2407 if ($this->with_bi
) {
2408 $joins['bi'] = PlSqlJoin
::left('profile_binets', '$ME.pid = $PID');
2410 if ($this->with_bd
) {
2411 $joins['bd'] = PlSqlJoin
::left('profile_binet_enum', '$ME.id = bi.binet_id');
2418 private $e = array();
2419 public function addEmailRedirectFilter($email = null
)
2421 $this->requireAccounts();
2422 return $this->register_optional($this->e
, $email);
2425 private $ve = array();
2426 public function addVirtualEmailFilter($email = null
)
2428 $this->addAliasFilter(self
::ALIAS_FORLIFE
);
2429 return $this->register_optional($this->ve
, $email);
2432 const ALIAS_BEST
= 'bestalias';
2433 const ALIAS_FORLIFE
= 'forlife';
2434 private $al = array();
2435 public function addAliasFilter($alias = null
)
2437 $this->requireAccounts();
2438 return $this->register_optional($this->al
, $alias);
2441 protected function emailJoins()
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\'');
2449 if (!is_array($key)) {
2452 $joins['e' . $sub] = PlSqlJoin
::left('emails', '$ME.uid = $UID AND $ME.flags != \'filter\'
2453 AND $ME.email IN {?}', $key);
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\'');
2464 if (!is_array($key)) {
2467 $joins['al' . $sub] = PlSqlJoin
::left('aliases', '$ME.uid = $UID AND $ME.type IN (\'alias\', \'a_vie\')
2468 AND $ME.alias IN {?}', $key);
2471 foreach ($this->ve
as $sub=>$key) {
2472 if (is_null($key)) {
2473 $joins['v' . $sub] = PlSqlJoin
::left('virtual', '$ME.type = \'user\'');
2475 if (!is_array($key)) {
2478 $joins['v' . $sub] = PlSqlJoin
::left('virtual', '$ME.type = \'user\' AND $ME.alias IN {?}', $key);
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, \'@\', {?}),
2485 $globals->mail
->domain
, $globals->mail
->domain2
);
2493 private $with_pa = false
;
2494 public function addAddressFilter()
2496 $this->requireProfiles();
2497 $this->with_pa
= true
;
2501 private $with_pac = false
;
2502 public function addAddressCountryFilter()
2504 $this->requireProfiles();
2505 $this->addAddressFilter();
2506 $this->with_pac
= true
;
2510 private $with_pal = false
;
2511 public function addAddressLocalityFilter()
2513 $this->requireProfiles();
2514 $this->addAddressFilter();
2515 $this->with_pal
= true
;
2519 protected function addressJoins()
2522 if ($this->with_pa
) {
2523 $joins['pa'] = PlSqlJoin
::left('profile_addresses', '$ME.pid = $PID');
2525 if ($this->with_pac
) {
2526 $joins['gc'] = PlSqlJoin
::left('geoloc_countries', '$ME.iso_3166_1_a2 = pa.countryID');
2528 if ($this->with_pal
) {
2529 $joins['gl'] = PlSqlJoin
::left('geoloc_localities', '$ME.id = pa.localityID');
2538 private $pc = false
;
2539 private $pce = array();
2540 private $pcr = false
;
2541 public function addCorpsFilter($type)
2543 $this->requireProfiles();
2545 if ($type == UFC_Corps
::CURRENT
) {
2546 $pce['pcec'] = 'current_corpsid';
2548 } else if ($type == UFC_Corps
::ORIGIN
) {
2549 $pce['pceo'] = 'original_corpsid';
2554 public function addCorpsRankFilter()
2556 $this->requireProfiles();
2562 protected function corpsJoins()
2566 $joins['pc'] = PlSqlJoin
::left('profile_corps', '$ME.pid = $PID');
2569 $joins['pcr'] = PlSqlJoin
::left('profile_corps_rank_enum', '$ME.id = pc.rankid');
2571 foreach($this->pce
as $sub => $field) {
2572 $joins[$sub] = PlSqlJoin
::left('profile_corps_enum', '$ME.id = pc.' . $field);
2580 const JOB_USERDEFINED
= 0x0001;
2581 const JOB_CV
= 0x0002;
2582 const JOB_ANY
= 0x0003;
2586 * pje => profile_job_enum
2587 * pjt => profile_job_terms
2589 private $with_pj = false
;
2590 private $with_pje = false
;
2591 private $with_pjt = 0;
2593 public function addJobFilter()
2595 $this->requireProfiles();
2596 $this->with_pj
= true
;
2600 public function addJobCompanyFilter()
2602 $this->addJobFilter();
2603 $this->with_pje
= true
;
2608 * Adds a filter on job terms of profile.
2609 * @param $nb the number of job terms to use
2610 * @return an array of the fields to filter (one for each term).
2612 public function addJobTermsFilter($nb = 1)
2614 $this->with_pjt
= $nb;
2615 $jobtermstable = array();
2616 for ($i = 1; $i <= $nb; ++
$i) {
2617 $jobtermstable[] = 'pjtr_'.$i;
2619 return $jobtermstable;
2622 protected function jobJoins()
2625 if ($this->with_pj
) {
2626 $joins['pj'] = PlSqlJoin
::left('profile_job', '$ME.pid = $PID');
2628 if ($this->with_pje
) {
2629 $joins['pje'] = PlSqlJoin
::left('profile_job_enum', '$ME.id = pj.jobid');
2631 if ($this->with_pjt
> 0) {
2632 for ($i = 1; $i <= $this->with_pjt
; ++
$i) {
2633 $joins['pjt_'.$i] = PlSqlJoin
::left('profile_job_term', '$ME.pid = $PID');
2634 $joins['pjtr_'.$i] = PlSqlJoin
::left('profile_job_term_relation', '$ME.jtid_2 = pjt_'.$i.'.jtid');
2643 private $with_pnw = false
;
2644 public function addNetworkingFilter()
2646 $this->requireAccounts();
2647 $this->with_pnw
= true
;
2651 protected function networkingJoins()
2654 if ($this->with_pnw
) {
2655 $joins['pnw'] = PlSqlJoin
::left('profile_networking', '$ME.pid = $PID');
2663 private $with_ptel = false
;
2665 public function addPhoneFilter()
2667 $this->requireAccounts();
2668 $this->with_ptel
= true
;
2672 protected function phoneJoins()
2675 if ($this->with_ptel
) {
2676 $joins['ptel'] = PlSqlJoin
::left('profile_phones', '$ME.pid = $PID');
2684 private $with_pmed = false
;
2685 public function addMedalFilter()
2687 $this->requireProfiles();
2688 $this->with_pmed
= true
;
2692 protected function medalJoins()
2695 if ($this->with_pmed
) {
2696 $joins['pmed'] = PlSqlJoin
::left('profile_medals', '$ME.pid = $PID');
2704 private $pms = array();
2705 private $mjtr = false
;
2707 const MENTOR_EXPERTISE
= 2;
2708 const MENTOR_COUNTRY
= 3;
2709 const MENTOR_TERM
= 4;
2711 public function addMentorFilter($type)
2713 $this->requireAccounts();
2716 $this->pms
['pm'] = 'profile_mentor';
2718 case self
::MENTOR_EXPERTISE
:
2719 $this->pms
['pme'] = 'profile_mentor';
2721 case self
::MENTOR_COUNTRY
:
2722 $this->pms
['pmc'] = 'profile_mentor_country';
2724 case self
::MENTOR_TERM
:
2725 $this->pms
['pmt'] = 'profile_mentor_term';
2729 Platal
::page()->killError("Undefined mentor filter.");
2733 protected function mentorJoins()
2736 foreach ($this->pms
as $sub => $tab) {
2737 $joins[$sub] = PlSqlJoin
::left($tab, '$ME.pid = $PID');
2740 $joins['mjtr'] = PlSqlJoin
::left('profile_job_term_relation', '$ME.jtid_2 = pmt.jtid');
2747 private $cts = array();
2748 public function addContactFilter($uid = null
)
2750 $this->requireProfiles();
2751 return $this->register_optional($this->cts
, is_null($uid) ? null
: 'user_' . $uid);
2754 protected function contactJoins()
2757 foreach ($this->cts
as $sub=>$key) {
2758 if (is_null($key)) {
2759 $joins['c' . $sub] = PlSqlJoin
::left('contacts', '$ME.contact = $PID');
2761 $joins['c' . $sub] = PlSqlJoin
::left('contacts', '$ME.uid = {?} AND $ME.contact = $PID', substr($key, 5));
2770 private $wn = array();
2771 public function addWatchRegistrationFilter($uid = null
)
2773 $this->requireAccounts();
2774 return $this->register_optional($this->wn
, is_null($uid) ? null
: 'user_' . $uid);
2777 private $wp = array();
2778 public function addWatchPromoFilter($uid = null
)
2780 $this->requireAccounts();
2781 return $this->register_optional($this->wp
, is_null($uid) ? null
: 'user_' . $uid);
2784 private $w = array();
2785 public function addWatchFilter($uid = null
)
2787 $this->requireAccounts();
2788 return $this->register_optional($this->w
, is_null($uid) ? null
: 'user_' . $uid);
2791 protected function watchJoins()
2794 foreach ($this->w
as $sub=>$key) {
2795 if (is_null($key)) {
2796 $joins['w' . $sub] = PlSqlJoin
::left('watch');
2798 $joins['w' . $sub] = PlSqlJoin
::left('watch', '$ME.uid = {?}', substr($key, 5));
2801 foreach ($this->wn
as $sub=>$key) {
2802 if (is_null($key)) {
2803 $joins['wn' . $sub] = PlSqlJoin
::left('watch_nonins', '$ME.ni_id = $UID');
2805 $joins['wn' . $sub] = PlSqlJoin
::left('watch_nonins', '$ME.uid = {?} AND $ME.ni_id = $UID', substr($key, 5));
2808 foreach ($this->wn
as $sub=>$key) {
2809 if (is_null($key)) {
2810 $joins['wn' . $sub] = PlSqlJoin
::left('watch_nonins', '$ME.ni_id = $UID');
2812 $joins['wn' . $sub] = PlSqlJoin
::left('watch_nonins', '$ME.uid = {?} AND $ME.ni_id = $UID', substr($key, 5));
2815 foreach ($this->wp
as $sub=>$key) {
2816 if (is_null($key)) {
2817 $joins['wp' . $sub] = PlSqlJoin
::left('watch_promo');
2819 $joins['wp' . $sub] = PlSqlJoin
::left('watch_promo', '$ME.uid = {?}', substr($key, 5));
2828 private $with_photo;
2829 public function addPhotoFilter()
2831 $this->requireProfiles();
2832 $this->with_photo
= true
;
2836 protected function photoJoins()
2838 if ($this->with_photo
) {
2839 return array('photo' => PlSqlJoin
::left('profile_photos', '$ME.pid = $PID'));
2849 public function addMarketingHash()
2851 $this->requireAccounts();
2852 $this->with_rm
= true
;
2855 protected function marketingJoins()
2857 if ($this->with_rm
) {
2858 return array('rm' => PlSqlJoin
::left('register_marketing', '$ME.uid = $UID'));
2866 // {{{ class ProfileFilter
2867 class ProfileFilter
extends UserFilter
2869 public function get($limit = null
)
2871 return $this->getProfiles($limit);
2874 public function filter(array $profiles, $limit = null
)
2876 return $this->filterProfiles($profiles, self
::defaultLimit($limit));
2879 public function getTotalCount()
2881 return $this->getTotalProfileCount();
2884 public function getGroups()
2886 return $this->getPIDGroups();
2891 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: