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 // {{{ abstract class UserFilterCondition
28 /** This class 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 abstract class UserFilterCondition
implements PlFilterCondition
39 public function export()
41 throw new Exception("This class is not exportable");
46 // {{{ class UFC_HasProfile
47 /** Filters users who have a profile
49 class UFC_HasProfile
extends UserFilterCondition
51 public function buildCondition(PlFilter
$uf)
53 $uf->requireProfiles();
54 return '$PID IS NOT NULL';
59 // {{{ class UFC_AccountType
60 /** Filters users who have one of the given account types
62 class UFC_AccountType
extends UserFilterCondition
66 public function __construct()
68 $this->types
= pl_flatten(func_get_args());
71 public function buildCondition(PlFilter
$uf)
73 $uf->requireAccounts();
74 return XDB
::format('a.type IN {?}', $this->types
);
79 // {{{ class UFC_AccountPerm
80 /** Filters users who have one of the given permissions
82 class UFC_AccountPerm
extends UserFilterCondition
86 public function __construct()
88 $this->perms
= pl_flatten(func_get_args());
91 public function buildCondition(PlFilter
$uf)
95 foreach ($this->perms
as $perm) {
96 $conds[] = XDB
::format('FIND_IN_SET({?}, IF(a.user_perms IS NULL, at.perms,
97 CONCAT(at.perms, \',\', a.user_perms)))',
101 return self
::COND_TRUE
;
103 return implode(' OR ', $conds);
109 // {{{ class UFC_Hruid
110 /** Filters users based on their hruid
111 * @param $val Either an hruid, or a list of those
113 class UFC_Hruid
extends UserFilterCondition
117 public function __construct()
119 $this->hruids
= pl_flatten(func_get_args());
122 public function buildCondition(PlFilter
$uf)
124 $uf->requireAccounts();
125 return XDB
::format('a.hruid IN {?}', $this->hruids
);
130 // {{{ class UFC_Hrpid
131 /** Filters users based on the hrpid of their profiles
132 * @param $val Either an hrpid, or a list of those
134 class UFC_Hrpid
extends UserFilterCondition
138 public function __construct()
140 $this->hrpids
= pl_flatten(func_get_args());
143 public function buildCondition(PlFilter
$uf)
145 $uf->requireProfiles();
146 return XDB
::format('p.hrpid IN {?}', $this->hrpids
);
152 /** Filters users based on one of their last IPs
153 * @param $ip IP from which connection are checked
155 class UFC_Ip
extends UserFilterCondition
159 public function __construct($ip)
164 public function buildCondition(PlFilter
$uf)
166 $sub = $uf->addLoggerFilter();
167 $ip = ip_to_uint($this->ip
);
168 return XDB
::format($sub . '.ip = {?} OR ' . $sub . '.forward_ip = {?}', $ip, $ip);
173 // {{{ class UFC_Comment
174 class UFC_Comment
extends UserFilterCondition
178 public function __construct($text)
183 public function buildCondition(PlFilter
$uf)
185 $uf->requireProfiles();
186 return $uf->getVisibilityCondition('p.freetext_pub') . ' AND p.freetext ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->text
);
191 // {{{ class UFC_Promo
192 /** Filters users based on promotion
193 * @param $comparison Comparison operator (>, =, ...)
194 * @param $grade Formation on which to restrict, UserFilter::DISPLAY for "any formation"
195 * @param $promo Promotion on which the filter is based
197 class UFC_Promo
extends UserFilterCondition
204 public function __construct($comparison, $grade, $promo)
206 $this->grade
= $grade;
207 $this->comparison
= $comparison;
208 $this->promo
= $promo;
209 if ($this->grade
!= UserFilter
::DISPLAY
) {
210 UserFilter
::assertGrade($this->grade
);
212 if ($this->grade
== UserFilter
::DISPLAY
&& $this->comparison
!= '=') {
213 // XXX: we might try to guess the grade from the first char of the promo and forbid only '<= 2004', but allow '<= X2004'
214 Platal
::page()->killError("Il n'est pas possible d'appliquer la comparaison '" . $this->comparison
. "' aux promotions sans spécifier de formation (X/M/D)");
218 public function buildCondition(PlFilter
$uf)
220 if ($this->grade
== UserFilter
::DISPLAY
) {
221 $sub = $uf->addDisplayFilter();
222 return XDB
::format('pd' . $sub . '.promo ' . $this->comparison
. ' {?}', $this->promo
);
224 $sub = $uf->addEducationFilter(true
, $this->grade
);
225 $field = 'pe' . $sub . '.' . UserFilter
::promoYear($this->grade
);
226 return $field . ' IS NOT NULL AND ' . $field . ' ' . $this->comparison
. ' ' . XDB
::format('{?}', $this->promo
);
232 // {{{ class UFC_SchoolId
233 /** Filters users based on their shoold identifier
234 * @param type Parameter type (Xorg, AX, School)
235 * @param value School id value
237 class UFC_SchoolId
extends UserFilterCondition
241 const School
= 'school';
246 static public function assertType($type)
248 if ($type != self
::AX
&& $type != self
::Xorg
&& $type != self
::School
) {
249 Platal
::page()->killError("Type de matricule invalide: $type");
253 public function __construct($type, $id)
257 self
::assertType($type);
260 public function buildCondition(PlFilter
$uf)
262 $uf->requireProfiles();
265 if ($type == self
::School
) {
267 $id = Profile
::getXorgId($id);
269 return XDB
::format('p.' . $type . '_id = {?}', $id);
274 // {{{ class UFC_EducationSchool
275 /** Filters users by formation
276 * @param $val The formation to search (either ID or array of IDs)
278 class UFC_EducationSchool
extends UserFilterCondition
282 public function __construct()
284 $this->val
= pl_flatten(func_get_args());
287 public function buildCondition(PlFilter
$uf)
289 $sub = $uf->addEducationFilter();
290 return XDB
::format('pe' . $sub . '.eduid IN {?}', $this->val
);
295 // {{{ class UFC_EducationDegree
296 class UFC_EducationDegree
extends UserFilterCondition
300 public function __construct()
302 $this->diploma
= pl_flatten(func_get_args());
305 public function buildCondition(PlFilter
$uf)
307 $sub = $uf->addEducationFilter();
308 return XDB
::format('pe' . $sub . '.degreeid IN {?}', $this->diploma
);
313 // {{{ class UFC_EducationField
314 class UFC_EducationField
extends UserFilterCondition
318 public function __construct()
320 $this->val
= pl_flatten(func_get_args());
323 public function buildCondition(PlFilter
$uf)
325 $sub = $uf->addEducationFilter();
326 return XDB
::format('pe' . $sub . '.fieldid IN {?}', $this->val
);
331 // {{{ class UFC_Name
332 /** Filters users based on name
333 * @param $type Type of name field on which filtering is done (firstname, lastname...)
334 * @param $text Text on which to filter
335 * @param $mode Flag indicating search type (prefix, suffix, with particule...)
337 class UFC_Name
extends UserFilterCondition
339 const EXACT
= XDB
::WILDCARD_EXACT
; // 0x000
340 const PREFIX
= XDB
::WILDCARD_PREFIX
; // 0x001
341 const SUFFIX
= XDB
::WILDCARD_SUFFIX
; // 0x002
342 const CONTAINS
= XDB
::WILDCARD_CONTAINS
; // 0x003
343 const PARTICLE
= 0x004;
344 const VARIANTS
= 0x008;
350 public function __construct($type, $text, $mode)
357 private function buildNameQuery($type, $variant, $where, UserFilter
$uf)
359 $sub = $uf->addNameFilter($type, $variant);
360 return str_replace('$ME', 'pn' . $sub, $where);
363 public function buildCondition(PlFilter
$uf)
366 if (($this->mode
& self
::PARTICLE
) == self
::PARTICLE
) {
367 $left = 'CONCAT($ME.particle, \' \', $ME.name)';
369 $right = XDB
::formatWildcards($this->mode
& self
::CONTAINS
, $this->text
);
371 $cond = $left . $right;
372 $conds = array($this->buildNameQuery($this->type
, null
, $cond, $uf));
373 if (($this->mode
& self
::VARIANTS
) != 0 && isset(Profile
::$name_variants[$this->type
])) {
374 foreach (Profile
::$name_variants[$this->type
] as $var) {
375 $conds[] = $this->buildNameQuery($this->type
, $var, $cond, $uf);
378 return implode(' OR ', $conds);
383 // {{{ class UFC_NameTokens
384 /** Selects users based on tokens in their name (for quicksearch)
385 * @param $tokens An array of tokens to search
386 * @param $flags Flags the tokens must have (e.g 'public' for public search)
387 * @param $soundex (bool) Whether those tokens are fulltext or soundex
389 class UFC_NameTokens
extends UserFilterCondition
392 const FLAG_PUBLIC
= 'public';
399 public function __construct($tokens, $flags = array(), $soundex = false
, $exact = false
)
401 if (is_array($tokens)) {
402 $this->tokens
= $tokens;
404 $this->tokens
= array($tokens);
406 if (is_array($flags)) {
407 $this->flags
= $flags;
409 $this->flags
= array($flags);
411 $this->soundex
= $soundex;
412 $this->exact
= $exact;
415 public function buildCondition(PlFilter
$uf)
418 foreach ($this->tokens
as $i => $token) {
419 $sub = $uf->addNameTokensFilter($token);
420 if ($this->soundex
) {
421 $c = XDB
::format($sub . '.soundex = {?}', soundex_fr($token));
422 } else if ($this->exact
) {
423 $c = XDB
::format($sub . '.token = {?}', $token);
425 $c = $sub . '.token ' . XDB
::formatWildcards(XDB
::WILDCARD_PREFIX
, $token);
427 if ($this->flags
!= null
) {
428 $c .= XDB
::format(' AND ' . $sub . '.flags IN {?}', $this->flags
);
433 return implode(' AND ', $conds);
438 // {{{ class UFC_Nationality
439 class UFC_Nationality
extends UserFilterCondition
443 public function __construct()
445 $this->val
= pl_flatten(func_get_args());
448 public function buildCondition(PlFilter
$uf)
450 $uf->requireProfiles();
451 $nat = XDB
::formatArray($this->val
);
453 'p.nationality1 IN ' . $nat,
454 'p.nationality2 IN ' . $nat,
455 'p.nationality3 IN ' . $nat,
457 return implode(' OR ', $conds);
462 // {{{ class UFC_Dead
463 /** Filters users based on death date
464 * @param $comparison Comparison operator
465 * @param $date Date to which death date should be compared (DateTime object, string or timestamp)
467 class UFC_Dead
extends UserFilterCondition
472 public function __construct($comparison = null
, $date = null
)
474 $this->comparison
= $comparison;
475 $this->date
= make_datetime($date);
478 public function buildCondition(PlFilter
$uf)
480 $uf->requireProfiles();
481 $str = 'p.deathdate IS NOT NULL';
482 if (!is_null($this->comparison
)) {
483 $str .= ' AND p.deathdate ' . $this->comparison
. ' ' . XDB
::format('{?}', $this->date
->format('Y-m-d'));
490 // {{{ class UFC_Registered
491 /** Filters users based on registration state
492 * @param $active Whether we want to use only "active" users (i.e with a valid redirection)
493 * @param $comparison Comparison operator
494 * @param $date Date to which users registration date should be compared
496 class UFC_Registered
extends UserFilterCondition
502 public function __construct($active = false
, $comparison = null
, $date = null
)
504 $this->active
= $active;
505 $this->comparison
= $comparison;
506 $this->date
= make_datetime($date);
509 public function buildCondition(PlFilter
$uf)
511 $uf->requireAccounts();
513 $date = '$UID IS NOT NULL AND a.state = \'active\'';
515 $date = '$UID IS NOT NULL AND a.state != \'pending\'';
517 if (!is_null($this->comparison
)) {
518 $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'));
525 // {{{ class UFC_ProfileUpdated
526 /** Filters users based on profile update date
527 * @param $comparison Comparison operator
528 * @param $date Date to which profile update date must be compared
530 class UFC_ProfileUpdated
extends UserFilterCondition
535 public function __construct($comparison = null
, $date = null
)
537 $this->comparison
= $comparison;
541 public function buildCondition(PlFilter
$uf)
543 $uf->requireProfiles();
544 return 'p.last_change ' . $this->comparison
. XDB
::format(' {?}', date('Y-m-d H:i:s', $this->date
));
549 // {{{ class UFC_Birthday
550 /** Filters users based on next birthday date
551 * @param $comparison Comparison operator
552 * @param $date Date to which users next birthday date should be compared
554 class UFC_Birthday
extends UserFilterCondition
559 public function __construct($comparison = null
, $date = null
)
561 $this->comparison
= $comparison;
565 public function buildCondition(PlFilter
$uf)
567 $uf->requireProfiles();
568 return 'p.next_birthday ' . $this->comparison
. XDB
::format(' {?}', date('Y-m-d', $this->date
));
574 /** Filters users based on sex
575 * @parm $sex One of User::GENDER_MALE or User::GENDER_FEMALE, for selecting users
577 class UFC_Sex
extends UserFilterCondition
580 public function __construct($sex)
585 public function buildCondition(PlFilter
$uf)
587 if ($this->sex
!= User
::GENDER_MALE
&& $this->sex
!= User
::GENDER_FEMALE
) {
588 return self
::COND_FALSE
;
590 $uf->requireProfiles();
591 return XDB
::format('p.sex = {?}', $this->sex
== User
::GENDER_FEMALE ?
'female' : 'male');
597 // {{{ class UFC_Group
598 /** Filters users based on group membership
599 * @param $group Group whose members we are selecting
600 * @param $anim Whether to restrict selection to animators of that group
602 class UFC_Group
extends UserFilterCondition
606 public function __construct($group, $anim = false
)
608 $this->group
= $group;
612 public function buildCondition(PlFilter
$uf)
614 // Groups have AX visibility.
615 if ($uf->getVisibilityLevel() == ProfileVisibility
::VIS_PUBLIC
) {
616 return self
::COND_TRUE
;
618 $sub = $uf->addGroupFilter($this->group
);
619 $where = 'gpm' . $sub . '.perms IS NOT NULL';
621 $where .= ' AND gpm' . $sub . '.perms = \'admin\'';
628 // {{{ class UFC_Binet
629 /** Selects users based on their belonging to a given (list of) binet
630 * @param $binet either a binet_id or an array of binet_ids
632 class UFC_Binet
extends UserFilterCondition
636 public function __construct()
638 $this->val
= pl_flatten(func_get_args());
641 public function buildCondition(PlFilter
$uf)
643 // Binets are private.
644 if ($uf->getVisibilityLevel() != ProfileVisibility
::VIS_PRIVATE
) {
645 return self
::CONF_TRUE
;
647 $sub = $uf->addBinetsFilter();
648 return XDB
::format($sub . '.binet_id IN {?}', $this->val
);
653 // {{{ class UFC_Section
654 /** Selects users based on section
655 * @param $section ID of the section
657 class UFC_Section
extends UserFilterCondition
661 public function __construct()
663 $this->section
= pl_flatten(func_get_args());
666 public function buildCondition(PlFilter
$uf)
668 // Sections are private.
669 if ($uf->getVisibilityLevel() != ProfileVisibility
::VIS_PRIVATE
) {
670 return self
::CONF_TRUE
;
672 $uf->requireProfiles();
673 return XDB
::format('p.section IN {?}', $this->section
);
678 // {{{ class UFC_Email
679 /** Filters users based on an email or a list of emails
680 * @param $emails List of emails whose owner must be selected
682 class UFC_Email
extends UserFilterCondition
685 public function __construct()
687 $this->emails
= pl_flatten(func_get_args());
690 public function buildCondition(PlFilter
$uf)
697 if (count($this->emails
) == 0) {
698 return PlFilterCondition
::COND_TRUE
;
701 foreach ($this->emails
as $entry) {
702 if (User
::isForeignEmailAddress($entry)) {
704 } else if (User
::isVirtualEmailAddress($entry)) {
707 @list
($user, $domain) = explode('@', $entry);
712 if (count($foreign) > 0) {
713 $sub = $uf->addEmailRedirectFilter($foreign);
714 $cond[] = XDB
::format('e' . $sub . '.email IS NOT NULL OR a.email IN {?}', $foreign);
716 if (count($virtual) > 0) {
717 $sub = $uf->addVirtualEmailFilter($virtual);
718 $cond[] = 'vr' . $sub . '.redirect IS NOT NULL';
720 if (count($aliases) > 0) {
721 $sub = $uf->addAliasFilter($aliases);
722 $cond[] = 'al' . $sub . '.alias IS NOT NULL';
724 return '(' . implode(') OR (', $cond) . ')';
729 // {{{ class UFC_Address
730 abstract class UFC_Address
extends UserFilterCondition
732 /** Valid address type ('hq' is reserved for company addresses)
738 /** Text for these types
740 protected static $typetexts = array(
741 self
::TYPE_HOME
=> 'home',
742 self
::TYPE_PRO
=> 'pro',
747 /** Flags for addresses
749 const FLAG_CURRENT
= 0x0001;
750 const FLAG_TEMP
= 0x0002;
751 const FLAG_SECOND
= 0x0004;
752 const FLAG_MAIL
= 0x0008;
753 const FLAG_CEDEX
= 0x0010;
755 // Binary OR of those flags
756 const FLAG_ANY
= 0x001F;
758 /** Text of these flags
760 protected static $flagtexts = array(
761 self
::FLAG_CURRENT
=> 'current',
762 self
::FLAG_TEMP
=> 'temporary',
763 self
::FLAG_SECOND
=> 'secondary',
764 self
::FLAG_MAIL
=> 'mail',
765 self
::FLAG_CEDEX
=> 'cedex',
770 public function __construct($type = null
, $flags = null
)
773 $this->flags
= $flags;
776 protected function initConds($sub, $vis_cond)
778 $conds = array($vis_cond);
781 foreach (self
::$typetexts as $flag => $type) {
782 if ($flag & $this->type
) {
787 $conds[] = XDB
::format($sub . '.type IN {?}', $types);
790 if ($this->flags
!= self
::FLAG_ANY
) {
791 foreach(self
::$flagtexts as $flag => $text) {
792 if ($flag & $this->flags
) {
793 $conds[] = 'FIND_IN_SET(' . XDB
::format('{?}', $text) . ', ' . $sub . '.flags)';
803 // {{{ class UFC_AddressText
804 /** Select users based on their address, using full text search
805 * @param $text Text for filter in fulltext search
806 * @param $textSearchMode Mode for search (one of XDB::WILDCARD_*)
807 * @param $type Filter on address type
808 * @param $flags Filter on address flags
809 * @param $country Filter on address country
810 * @param $locality Filter on address locality
812 class UFC_AddressText
extends UFC_Address
816 private $textSearchMode;
818 public function __construct($text = null
, $textSearchMode = XDB
::WILDCARD_CONTAINS
,
819 $type = null
, $flags = self
::FLAG_ANY
, $country = null
, $locality = null
)
821 parent
::__construct($type, $flags);
823 $this->textSearchMode
= $textSearchMode;
824 $this->country
= $country;
825 $this->locality
= $locality;
828 private function mkMatch($txt)
830 return XDB
::formatWildcards($this->textSearchMode
, $txt);
833 public function buildCondition(PlFilter
$uf)
835 $sub = $uf->addAddressFilter();
836 $conds = $this->initConds($sub, $uf->getVisibilityCondition($sub . '.pub'));
837 if ($this->text
!= null
) {
838 $conds[] = $sub . '.text' . $this->mkMatch($this->text
);
841 if ($this->country
!= null
) {
842 $subc = $uf->addAddressCountryFilter();
844 $subconds[] = $subc . '.country' . $this->mkMatch($this->country
);
845 $subconds[] = $subc . '.countryFR' . $this->mkMatch($this->country
);
846 $conds[] = implode(' OR ', $subconds);
849 if ($this->locality
!= null
) {
850 $subl = $uf->addAddressLocalityFilter();
851 $conds[] = $subl . '.name' . $this->mkMatch($this->locality
);
854 return implode(' AND ', $conds);
859 // {{{ class UFC_AddressField
860 /** Filters users based on their address,
861 * @param $val Either a code for one of the fields, or an array of such codes
862 * @param $fieldtype The type of field to look for
863 * @param $type Filter on address type
864 * @param $flags Filter on address flags
866 class UFC_AddressField
extends UFC_Address
868 const FIELD_COUNTRY
= 1;
869 const FIELD_ADMAREA
= 2;
870 const FIELD_SUBADMAREA
= 3;
871 const FIELD_LOCALITY
= 4;
872 const FIELD_ZIPCODE
= 5;
874 /** Data of the filter
879 public function __construct($val, $fieldtype, $type = null
, $flags = self
::FLAG_ANY
)
881 parent
::__construct($type, $flags);
883 if (!is_array($val)) {
887 $this->fieldtype
= $fieldtype;
890 public function buildCondition(PlFilter
$uf)
892 $sub = $uf->addAddressFilter();
893 $conds = $this->initConds($sub, $uf->getVisibilityCondition($sub . '.pub'));
895 switch ($this->fieldtype
) {
896 case self
::FIELD_COUNTRY
:
897 $field = 'countryId';
899 case self
::FIELD_ADMAREA
:
900 $field = 'administrativeAreaId';
902 case self
::FIELD_SUBADMAREA
:
903 $field = 'subAdministrativeAreaId';
905 case self
::FIELD_LOCALITY
:
906 $field = 'localityId';
908 case self
::FIELD_ZIPCODE
:
909 $field = 'postalCode';
912 Platal
::page()->killError('Invalid address field type: ' . $this->fieldtype
);
914 $conds[] = XDB
::format($sub . '.' . $field . ' IN {?}', $this->val
);
916 return implode(' AND ', $conds);
921 // {{{ class UFC_Corps
922 /** Filters users based on the corps they belong to
923 * @param $corps Corps we are looking for (abbreviation)
924 * @param $type Whether we search for original or current corps
926 class UFC_Corps
extends UserFilterCondition
934 public function __construct($corps, $type = self
::CURRENT
)
936 $this->corps
= $corps;
940 public function buildCondition(PlFilter
$uf)
942 /** Tables shortcuts:
943 * pc for profile_corps,
944 * pceo for profile_corps_enum - orginal
945 * pcec for profile_corps_enum - current
947 $sub = $uf->addCorpsFilter($this->type
);
948 $cond = $sub . '.abbreviation = ' . $corps;
949 $cond .= ' AND ' . $uf->getVisibilityCondition($sub . '.corps_pub');
955 // {{{ class UFC_Corps_Rank
956 /** Filters users based on their rank in the corps
957 * @param $rank Rank we are looking for (abbreviation)
959 class UFC_Corps_Rank
extends UserFilterCondition
962 public function __construct($rank)
967 public function buildCondition(PlFilter
$uf)
969 /** Tables shortcuts:
970 * pc for profile_corps
971 * pcr for profile_corps_rank
973 $sub = $uf->addCorpsRankFilter();
974 $cond = $sub . '.abbreviation = ' . $rank;
975 // XXX(x2006barrois): find a way to get rid of that hardcoded
976 // reference to 'pc'.
977 $cond .= ' AND ' . $uf->getVisibilityCondition('pc.corps_pub');
983 // {{{ class UFC_Job_Company
984 /** Filters users based on the company they belong to
985 * @param $type The field being searched (self::JOBID, self::JOBNAME or self::JOBACRONYM)
986 * @param $value The searched value
988 class UFC_Job_Company
extends UserFilterCondition
991 const JOBNAME
= 'name';
992 const JOBACRONYM
= 'acronym';
997 public function __construct($type, $value)
999 $this->assertType($type);
1000 $this->type
= $type;
1001 $this->value
= $value;
1004 private function assertType($type)
1006 if ($type != self
::JOBID
&& $type != self
::JOBNAME
&& $type != self
::JOBACRONYM
) {
1007 Platal
::page()->killError("Type de recherche non valide.");
1011 public function buildCondition(PlFilter
$uf)
1013 $sub = $uf->addJobCompanyFilter();
1014 $cond = $sub . '.' . $this->type
. XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->value
);
1015 $jsub = $uf->addJobFilter();
1016 $cond .= ' AND ' . $uf->getVisibilityCondition($jsub . '.pub');
1022 // {{{ class UFC_Job_Terms
1023 /** Filters users based on the job terms they assigned to one of their
1025 * @param $val The ID of the job term, or an array of such IDs
1027 class UFC_Job_Terms
extends UserFilterCondition
1031 public function __construct($val)
1033 if (!is_array($val)) {
1039 public function buildCondition(PlFilter
$uf)
1041 $sub = $uf->addJobTermsFilter(count($this->val
));
1042 $conditions = array();
1043 foreach ($this->val
as $i => $jtid) {
1044 $conditions[] = $sub[$i] . '.jtid_1 = ' . XDB
::escape($jtid);
1046 $jsub = $uf->addJobFilter();
1047 $conditions[] = $uf->getVisibilityCondition($jsub . '.pub');
1048 return implode(' AND ', $conditions);
1053 // {{{ class UFC_Job_Description
1054 /** Filters users based on their job description
1055 * @param $description The text being searched for
1056 * @param $fields The fields to search for (CV, user-defined)
1058 class UFC_Job_Description
extends UserFilterCondition
1061 private $description;
1064 public function __construct($description, $fields)
1066 $this->fields
= $fields;
1067 $this->description
= $description;
1070 public function buildCondition(PlFilter
$uf)
1074 $jsub = $uf->addJobFilter();
1075 // CV is private => if only CV requested, and not private,
1076 // don't do anything. Otherwise restrict to standard job visibility.
1077 if ($this->fields
== UserFilter
::JOB_CV
) {
1078 if ($uf->getVisibilityLevel() != ProfileVisibility
::VIS_PRIVATE
) {
1079 return self
::CONF_TRUE
;
1082 $conds[] = $uf->getVisibilityCondition($jsub . '.pub');
1085 if ($this->fields
& UserFilter
::JOB_USERDEFINED
) {
1086 $conds[] = $jsub . '.description ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->description
);
1088 if ($this->fields
& UserFilter
::JOB_CV
&& $uf->getVisibilityLevel() == ProfileVisibility
::VIS_PRIVATE
) {
1089 $uf->requireProfiles();
1090 $conds[] = 'p.cv ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->description
);
1092 return implode(' OR ', $conds);
1097 // {{{ class UFC_Networking
1098 /** Filters users based on network identity (IRC, ...)
1099 * @param $type Type of network (-1 for any)
1100 * @param $value Value to search
1102 class UFC_Networking
extends UserFilterCondition
1107 public function __construct($type, $value)
1109 $this->type
= $type;
1110 $this->value
= $value;
1113 public function buildCondition(PlFilter
$uf)
1115 $sub = $uf->addNetworkingFilter();
1117 $conds[] = $uf->getVisibilityCondition($sub . '.pub');
1118 $conds[] = $sub . '.address ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->value
);
1119 if ($this->type
!= -1) {
1120 $conds[] = $sub . '.nwid = ' . XDB
::format('{?}', $this->type
);
1122 return implode(' AND ', $conds);
1127 // {{{ class UFC_Phone
1128 /** Filters users based on their phone number
1129 * @param $num_type Type of number (pro/user/home)
1130 * @param $phone_type Type of phone (fixed/mobile/fax)
1131 * @param $number Phone number
1133 class UFC_Phone
extends UserFilterCondition
1135 const NUM_PRO
= 'pro';
1136 const NUM_USER
= 'user';
1137 const NUM_HOME
= 'address';
1138 const NUM_ANY
= 'any';
1140 const PHONE_FIXED
= 'fixed';
1141 const PHONE_MOBILE
= 'mobile';
1142 const PHONE_FAX
= 'fax';
1143 const PHONE_ANY
= 'any';
1146 private $phone_type;
1149 public function __construct($number, $num_type = self
::NUM_ANY
, $phone_type = self
::PHONE_ANY
)
1151 $phone = new Phone(array('display' => $number));
1153 $this->number
= $phone->search();
1154 $this->num_type
= $num_type;
1155 $this->phone_type
= $phone_type;
1158 public function buildCondition(PlFilter
$uf)
1160 $sub = $uf->addPhoneFilter();
1163 $conds[] = $uf->getVisibilityCondition($sub . '.pub');
1165 $conds[] = $sub . '.search_tel = ' . XDB
::format('{?}', $this->number
);
1166 if ($this->num_type
!= self
::NUM_ANY
) {
1167 $conds[] = $sub . '.link_type = ' . XDB
::format('{?}', $this->num_type
);
1169 if ($this->phone_type
!= self
::PHONE_ANY
) {
1170 $conds[] = $sub . '.tel_type = ' . XDB
::format('{?}', $this->phone_type
);
1172 return implode(' AND ', $conds);
1177 // {{{ class UFC_Medal
1178 /** Filters users based on their medals
1179 * @param $medal ID of the medal
1180 * @param $grade Grade of the medal (null for 'any')
1182 class UFC_Medal
extends UserFilterCondition
1187 public function __construct($medal, $grade = null
)
1189 $this->medal
= $medal;
1190 $this->grade
= $grade;
1193 public function buildCondition(PlFilter
$uf)
1197 // This will require profiles => table 'p' will be available.
1198 $sub = $uf->addMedalFilter();
1200 $conds[] = $uf->getVisibilityCondition('p.medals_pub');
1202 $conds[] = $sub . '.mid = ' . XDB
::format('{?}', $this->medal
);
1203 if ($this->grade
!= null
) {
1204 $conds[] = $sub . '.gid = ' . XDB
::format('{?}', $this->grade
);
1206 return implode(' AND ', $conds);
1211 // {{{ class UFC_Photo
1212 /** Filters profiles with photo
1214 class UFC_Photo
extends UserFilterCondition
1216 public function buildCondition(PlFilter
$uf)
1218 $sub = $uf->addPhotoFilter();
1219 return $sub . '.attach IS NOT NULL AND ' . $uf->getVisibilityCondition($sub . '.pub');
1224 // {{{ class UFC_Mentor
1225 class UFC_Mentor
extends UserFilterCondition
1227 public function buildCondition(PlFilter
$uf)
1229 $sub = $uf->addMentorFilter(UserFilter
::MENTOR
);
1230 return $sub . '.expertise IS NOT NULL';
1236 // {{{ class UFC_Mentor_Expertise
1237 /** Filters users by mentoring expertise
1238 * @param $expertise Domain of expertise
1240 class UFC_Mentor_Expertise
extends UserFilterCondition
1244 public function __construct($expertise)
1246 $this->expertise
= $expertise;
1249 public function buildCondition(PlFilter
$uf)
1251 $sub = $uf->addMentorFilter(UserFilter
::MENTOR_EXPERTISE
);
1252 return $sub . '.expertise ' . XDB
::formatWildcards(XDB
::WILDCARD_CONTAINS
, $this->expertise
);
1257 // {{{ class UFC_Mentor_Country
1258 /** Filters users by mentoring country
1259 * @param $country Two-letters code of country being searched
1261 class UFC_Mentor_Country
extends UserFilterCondition
1265 public function __construct()
1267 $this->country
= pl_flatten(func_get_args());
1270 public function buildCondition(PlFilter
$uf)
1272 $sub = $uf->addMentorFilter(UserFilter
::MENTOR_COUNTRY
);
1273 return $sub . '.country IN ' . XDB
::format('{?}', $this->country
);
1278 // {{{ class UFC_Mentor_Terms
1279 /** Filters users based on the job terms they used in mentoring.
1280 * @param $val The ID of the job term, or an array of such IDs
1282 class UFC_Mentor_Terms
extends UserFilterCondition
1286 public function __construct($val)
1291 public function buildCondition(PlFilter
$uf)
1293 $sub = $uf->addMentorFilter(UserFilter
::MENTOR_TERM
);
1294 return $sub . '.jtid_1 = ' . XDB
::escape($this->val
);
1299 // {{{ class UFC_UserRelated
1300 /** Filters users based on a relation toward a user
1301 * @param $user User to which searched users are related
1303 abstract class UFC_UserRelated
extends UserFilterCondition
1306 public function __construct(PlUser
&$user)
1308 $this->user
=& $user;
1313 // {{{ class UFC_Contact
1314 /** Filters users who belong to selected user's contacts
1316 class UFC_Contact
extends UFC_UserRelated
1318 public function buildCondition(PlFilter
$uf)
1320 $sub = $uf->addContactFilter($this->user
->id());
1321 return 'c' . $sub . '.contact IS NOT NULL';
1326 // {{{ class UFC_WatchRegistration
1327 /** Filters users being watched by selected user
1329 class UFC_WatchRegistration
extends UFC_UserRelated
1331 public function buildCondition(PlFilter
$uf)
1333 if (!$this->user
->watchType('registration')) {
1334 return PlFilterCondition
::COND_FALSE
;
1336 $uids = $this->user
->watchUsers();
1337 if (count($uids) == 0) {
1338 return PlFilterCondition
::COND_FALSE
;
1340 return XDB
::format('$UID IN {?}', $uids);
1346 // {{{ class UFC_WatchPromo
1347 /** Filters users belonging to a promo watched by selected user
1348 * @param $user Selected user (the one watching promo)
1349 * @param $grade Formation the user is watching
1351 class UFC_WatchPromo
extends UFC_UserRelated
1354 public function __construct(PlUser
&$user, $grade = UserFilter
::GRADE_ING
)
1356 parent
::__construct($user);
1357 $this->grade
= $grade;
1360 public function buildCondition(PlFilter
$uf)
1362 $promos = $this->user
->watchPromos();
1363 if (count($promos) == 0) {
1364 return PlFilterCondition
::COND_FALSE
;
1366 $sube = $uf->addEducationFilter(true
, $this->grade
);
1367 $field = 'pe' . $sube . '.' . UserFilter
::promoYear($this->grade
);
1368 return XDB
::format($field . ' IN {?}', $promos);
1374 // {{{ class UFC_WatchContact
1375 /** Filters users watched by selected user
1377 class UFC_WatchContact
extends UFC_Contact
1379 public function buildCondition(PlFilter
$uf)
1381 if (!$this->user
->watchContacts()) {
1382 return PlFilterCondition
::COND_FALSE
;
1384 return parent
::buildCondition($uf);
1389 // {{{ class UFC_MarketingHash
1390 /** Filters users using the hash generated
1391 * to send marketing emails to him.
1393 class UFC_MarketingHash
extends UserFilterCondition
1397 public function __construct($hash)
1399 $this->hash
= $hash;
1402 public function buildCondition(PlFilter
$uf)
1404 $table = $uf->addMarketingHash();
1405 return XDB
::format('rm.hash = {?}', $this->hash
);
1414 // {{{ class UFO_Promo
1415 /** Orders users by promotion
1416 * @param $grade Formation whose promotion users should be sorted by (restricts results to users of that formation)
1417 * @param $desc Whether sort is descending
1419 class UFO_Promo
extends PlFilterGroupableOrder
1423 public function __construct($grade = null
, $desc = false
)
1425 parent
::__construct($desc);
1426 $this->grade
= $grade;
1429 protected function getSortTokens(PlFilter
$uf)
1431 if (UserFilter
::isGrade($this->grade
)) {
1432 $sub = $uf->addEducationFilter($this->grade
);
1433 return 'pe' . $sub . '.' . UserFilter
::promoYear($this->grade
);
1435 $sub = $uf->addDisplayFilter();
1436 return 'pd' . $sub . '.promo';
1442 // {{{ class UFO_Name
1443 /** Sorts users by name
1444 * @param $type Type of name on which to sort (firstname...)
1445 * @param $variant Variant of that name to use (marital, ordinary...)
1446 * @param $particle Set to true if particles should be included in the sorting order
1447 * @param $desc If sort order should be descending
1449 class UFO_Name
extends PlFilterOrder
1455 public function __construct($type, $variant = null
, $particle = false
, $desc = false
)
1457 parent
::__construct($desc);
1458 $this->type
= $type;
1459 $this->variant
= $variant;
1460 $this->particle
= $particle;
1463 protected function getSortTokens(PlFilter
$uf)
1465 if (Profile
::isDisplayName($this->type
)) {
1466 $sub = $uf->addDisplayFilter();
1467 $token = 'pd' . $sub . '.' . $this->type
;
1468 if ($uf->accountsRequired()) {
1469 $account_token = Profile
::getAccountEquivalentName($this->type
);
1470 return 'IFNULL(' . $token . ', a.' . $account_token . ')';
1475 $sub = $uf->addNameFilter($this->type
, $this->variant
);
1476 if ($this->particle
) {
1477 return 'CONCAT(pn' . $sub . '.particle, \' \', pn' . $sub . '.name)';
1479 return 'pn' . $sub . '.name';
1486 // {{{ class UFO_Score
1487 class UFO_Score
extends PlFilterOrder
1489 protected function getSortTokens(PlFilter
$uf)
1491 $toks = $uf->getNameTokens();
1494 // If there weren't any sort tokens, we shouldn't sort by score, sort by NULL instead
1495 if (count($toks) == 0) {
1499 foreach ($toks as $sub => $token) {
1500 $scores[] = XDB
::format('SUM(' . $sub . '.score + IF (' . $sub . '.token = {?}, 5, 0) )', $token);
1502 return implode(' + ', $scores);
1507 // {{{ class UFO_Registration
1508 /** Sorts users based on registration date
1510 class UFO_Registration
extends PlFilterOrder
1512 protected function getSortTokens(PlFilter
$uf)
1514 $uf->requireAccounts();
1515 return 'a.registration_date';
1520 // {{{ class UFO_Birthday
1521 /** Sorts users based on next birthday date
1523 class UFO_Birthday
extends PlFilterOrder
1525 protected function getSortTokens(PlFilter
$uf)
1527 $uf->requireProfiles();
1528 return 'p.next_birthday';
1533 // {{{ class UFO_ProfileUpdate
1534 /** Sorts users based on last profile update
1536 class UFO_ProfileUpdate
extends PlFilterOrder
1538 protected function getSortTokens(PlFilter
$uf)
1540 $uf->requireProfiles();
1541 return 'p.last_change';
1546 // {{{ class UFO_Death
1547 /** Sorts users based on death date
1549 class UFO_Death
extends PlFilterOrder
1551 protected function getSortTokens(PlFilter
$uf)
1553 $uf->requireProfiles();
1554 return 'p.deathdate';
1559 // {{{ class UFO_Uid
1560 /** Sorts users based on their uid
1562 class UFO_Uid
extends PlFilterOrder
1564 protected function getSortTokens(PlFilter
$uf)
1566 $uf->requireAccounts();
1572 // {{{ class UFO_Hruid
1573 /** Sorts users based on their hruid
1575 class UFO_Hruid
extends PlFilterOrder
1577 protected function getSortTokens(PlFilter
$uf)
1579 $uf->requireAccounts();
1585 // {{{ class UFO_Pid
1586 /** Sorts users based on their pid
1588 class UFO_Pid
extends PlFilterOrder
1590 protected function getSortTokens(PlFilter
$uf)
1592 $uf->requireProfiles();
1598 // {{{ class UFO_Hrpid
1599 /** Sorts users based on their hrpid
1601 class UFO_Hrpid
extends PlFilterOrder
1603 protected function getSortTokens(PlFilter
$uf)
1605 $uf->requireProfiles();
1612 /***********************************
1613 *********************************
1615 *********************************
1616 ***********************************/
1618 // {{{ class UserFilter
1619 /** This class provides a convenient and centralized way of filtering users.
1622 * $uf = new UserFilter(new UFC_Blah($x, $y), new UFO_Coin($z, $t));
1624 * Resulting UserFilter can be used to:
1625 * - get a list of User objects matching the filter
1626 * - get a list of UIDs matching the filter
1627 * - get the number of users matching the filter
1628 * - check whether a given User matches the filter
1629 * - filter a list of User objects depending on whether they match the filter
1631 * Usage for UFC and UFO objects:
1632 * A UserFilter will call all private functions named XXXJoins.
1633 * These functions must return an array containing the list of join
1634 * required by the various UFC and UFO associated to the UserFilter.
1635 * Entries in those returned array are of the following form:
1636 * 'join_tablealias' => array('join_type', 'joined_table', 'join_criter')
1637 * which will be translated into :
1638 * join_type JOIN joined_table AS join_tablealias ON (join_criter)
1639 * in the final query.
1641 * In the join_criter text, $ME is replaced with 'join_tablealias', $PID with
1642 * profile.pid, and $UID with accounts.uid.
1644 * For each kind of "JOIN" needed, a function named addXXXFilter() should be defined;
1645 * its parameter will be used to set various private vars of the UserFilter describing
1646 * the required joins ; such a function shall return the "join_tablealias" to use
1647 * when referring to the joined table.
1649 * For example, if data from profile_job must be available to filter results,
1650 * the UFC object will call $uf-addJobFilter(), which will set the 'with_pj' var and
1651 * return 'pj', the short name to use when referring to profile_job; when building
1652 * the query, calling the jobJoins function will return an array containing a single
1654 * 'pj' => array('left', 'profile_job', '$ME.pid = $UID');
1656 * The 'register_optional' function can be used to generate unique table aliases when
1657 * the same table has to be joined several times with different aliases.
1659 class UserFilter
extends PlFilter
1661 protected $joinMethods = array();
1663 protected $joinMetas = array(
1669 private $sort = array();
1670 private $grouper = null
;
1671 private $query = null
;
1672 private $orderby = null
;
1674 // Store the current 'search' visibility.
1675 private $profile_visibility = null
;
1677 private $lastusercount = null
;
1678 private $lastprofilecount = null
;
1680 public function __construct($cond = null
, $sort = null
)
1682 if (empty($this->joinMethods
)) {
1683 $class = new ReflectionClass('UserFilter');
1684 foreach ($class->getMethods() as $method) {
1685 $name = $method->getName();
1686 if (substr($name, -5) == 'Joins' && $name != 'buildJoins') {
1687 $this->joinMethods
[] = $name;
1691 if (!is_null($cond)) {
1692 if ($cond instanceof PlFilterCondition
) {
1693 $this->setCondition($cond);
1696 if (!is_null($sort)) {
1697 if ($sort instanceof PlFilterOrder
) {
1698 $this->addSort($sort);
1699 } else if (is_array($sort)) {
1700 foreach ($sort as $s) {
1706 // This will set the visibility to the default correct level.
1707 $this->profile_visibility
= new ProfileVisibility();
1710 public function getVisibilityLevels()
1712 return $this->profile_visibility
->levels();
1715 public function getVisibilityLevel()
1717 return $this->profile_visibility
->level();
1720 public function restrictVisibilityTo($level)
1722 $this->profile_visibility
->setLevel($level);
1725 public function getVisibilityCondition($field)
1727 return $field . ' IN ' . XDB
::formatArray($this->getVisibilityLevels());
1730 private function buildQuery()
1732 // The root condition is built first because some orders need info
1733 // available only once all UFC have set their conditions (UFO_Score)
1734 if (is_null($this->query
)) {
1735 $where = $this->root
->buildCondition($this);
1736 $where = str_replace(array_keys($this->joinMetas
),
1740 if (is_null($this->orderby
)) {
1742 foreach ($this->sort
as $sort) {
1743 $orders = array_merge($orders, $sort->buildSort($this));
1745 if (count($orders) == 0) {
1746 $this->orderby
= '';
1748 $this->orderby
= 'ORDER BY ' . implode(', ', $orders);
1750 $this->orderby
= str_replace(array_keys($this->joinMetas
),
1754 if (is_null($this->query
)) {
1755 if ($this->with_accounts
) {
1756 $from = 'accounts AS a';
1758 $this->requireProfiles();
1759 $from = 'profiles AS p';
1761 $joins = $this->buildJoins();
1762 $this->query
= 'FROM ' . $from . '
1764 WHERE (' . $where . ')';
1768 public function hasGroups()
1770 return $this->grouper
!= null
;
1773 public function getGroups()
1775 return $this->getUIDGroups();
1778 public function getUIDGroups()
1780 $this->requireAccounts();
1781 $this->buildQuery();
1782 $token = $this->grouper
->getGroupToken($this);
1784 $groups = XDB
::rawFetchAllRow('SELECT ' . $token . ', COUNT(a.uid)
1785 ' . $this->query
. '
1786 GROUP BY ' . $token,
1791 public function getPIDGroups()
1793 $this->requireProfiles();
1794 $this->buildQuery();
1795 $token = $this->grouper
->getGroupToken($this);
1797 $groups = XDB
::rawFetchAllRow('SELECT ' . $token . ', COUNT(p.pid)
1798 ' . $this->query
. '
1799 GROUP BY ' . $token,
1804 private function getUIDList($uids = null
, PlLimit
&$limit)
1806 $this->requireAccounts();
1807 $this->buildQuery();
1808 $lim = $limit->getSql();
1810 if (!empty($uids)) {
1811 $cond = XDB
::format(' AND a.uid IN {?}', $uids);
1813 $fetched = XDB
::rawFetchColumn('SELECT SQL_CALC_FOUND_ROWS a.uid
1814 ' . $this->query
. $cond . '
1816 ' . $this->orderby
. '
1818 $this->lastusercount
= (int)XDB
::fetchOneCell('SELECT FOUND_ROWS()');
1822 private function getPIDList($pids = null
, PlLimit
&$limit)
1824 $this->requireProfiles();
1825 $this->buildQuery();
1826 $lim = $limit->getSql();
1828 if (!is_null($pids)) {
1829 $cond = XDB
::format(' AND p.pid IN {?}', $pids);
1831 $fetched = XDB
::rawFetchColumn('SELECT SQL_CALC_FOUND_ROWS p.pid
1832 ' . $this->query
. $cond . '
1834 ' . $this->orderby
. '
1836 $this->lastprofilecount
= (int)XDB
::fetchOneCell('SELECT FOUND_ROWS()');
1840 private static function defaultLimit($limit) {
1841 if ($limit == null
) {
1842 return new PlLimit();
1848 /** Check that the user match the given rule.
1850 public function checkUser(PlUser
&$user)
1852 $this->requireAccounts();
1853 $this->buildQuery();
1854 $count = (int)XDB
::rawFetchOneCell('SELECT COUNT(*)
1856 . XDB
::format(' AND a.uid = {?}', $user->id()));
1860 /** Check that the profile match the given rule.
1862 public function checkProfile(Profile
&$profile)
1864 $this->requireProfiles();
1865 $this->buildQuery();
1866 $count = (int)XDB
::rawFetchOneCell('SELECT COUNT(*)
1868 . XDB
::format(' AND p.pid = {?}', $profile->id()));
1872 /** Default filter is on users
1874 public function filter(array $users, $limit = null
)
1876 return $this->filterUsers($users, self
::defaultLimit($limit));
1879 /** Filter a list of users to extract the users matching the rule.
1881 public function filterUsers(array $users, $limit = null
)
1883 $limit = self
::defaultLimit($limit);
1884 $this->requireAccounts();
1885 $this->buildQuery();
1888 foreach ($users as $user) {
1889 if ($user instanceof PlUser
) {
1895 $table[$uid] = $user;
1897 $fetched = $this->getUIDList($uids, $limit);
1899 foreach ($fetched as $uid) {
1900 $output[] = $table[$uid];
1905 /** Filter a list of profiles to extract the users matching the rule.
1907 public function filterProfiles(array $profiles, $limit = null
)
1909 $limit = self
::defaultLimit($limit);
1910 $this->requireProfiles();
1911 $this->buildQuery();
1914 foreach ($profiles as $profile) {
1915 if ($profile instanceof Profile
) {
1916 $pid = $profile->id();
1921 $table[$pid] = $profile;
1923 $fetched = $this->getPIDList($pids, $limit);
1925 foreach ($fetched as $pid) {
1926 $output[] = $table[$pid];
1931 public function getUIDs($limit = null
)
1933 $limit = self
::defaultLimit($limit);
1934 return $this->getUIDList(null
, $limit);
1937 public function getUID($pos = 0)
1939 $uids =$this->getUIDList(null
, new PlLimit(1, $pos));
1940 if (count($uids) == 0) {
1947 public function getPIDs($limit = null
)
1949 $limit = self
::defaultLimit($limit);
1950 return $this->getPIDList(null
, $limit);
1953 public function getPID($pos = 0)
1955 $pids =$this->getPIDList(null
, new PlLimit(1, $pos));
1956 if (count($pids) == 0) {
1963 public function getUsers($limit = null
)
1965 return User
::getBulkUsersWithUIDs($this->getUIDs($limit));
1968 public function getUser($pos = 0)
1970 $uid = $this->getUID($pos);
1974 return User
::getWithUID($uid);
1978 public function iterUsers($limit = null
)
1980 return User
::iterOverUIDs($this->getUIDs($limit));
1983 public function getProfiles($limit = null
, $fields = 0x0000, $visibility = null
)
1985 return Profile
::getBulkProfilesWithPIDs($this->getPIDs($limit), $fields, $visibility);
1988 public function getProfile($pos = 0, $fields = 0x0000, $visibility = null
)
1990 $pid = $this->getPID($pos);
1994 return Profile
::get($pid, $fields, $visibility);
1998 public function iterProfiles($limit = null
, $fields = 0x0000, $visibility = null
)
2000 return Profile
::iterOverPIDs($this->getPIDs($limit), true
, $fields, $visibility);
2003 public function get($limit = null
)
2005 return $this->getUsers($limit);
2009 public function getTotalCount()
2011 return $this->getTotalUserCount();
2014 public function getTotalUserCount()
2016 if (is_null($this->lastusercount
)) {
2017 $this->requireAccounts();
2018 $this->buildQuery();
2019 return (int)XDB
::rawFetchOneCell('SELECT COUNT(DISTINCT a.uid)
2022 return $this->lastusercount
;
2026 public function getTotalProfileCount()
2028 if (is_null($this->lastprofilecount
)) {
2029 $this->requireProfiles();
2030 $this->buildQuery();
2031 return (int)XDB
::rawFetchOneCell('SELECT COUNT(DISTINCT p.pid)
2034 return $this->lastprofilecount
;
2038 public function setCondition(PlFilterCondition
$cond)
2040 $this->root
=& $cond;
2041 $this->query
= null
;
2044 public function addSort(PlFilterOrder
$sort)
2046 if (count($this->sort
) == 0 && $sort instanceof PlFilterGroupableOrder
)
2048 $this->grouper
= $sort;
2050 $this->sort
[] = $sort;
2051 $this->orderby
= null
;
2054 public function export()
2056 $export = array('condition' => $this->root
->export());
2057 if (!empty($this->sort
)) {
2058 $export['sort'] = array();
2059 foreach ($this->sort
as $sort) {
2060 $export['sort'][] = $sort->export();
2066 static public function getLegacy($promo_min, $promo_max)
2068 if ($promo_min != 0) {
2069 $min = new UFC_Promo('>=', self
::GRADE_ING
, intval($promo_min));
2071 $min = new PFC_True();
2073 if ($promo_max != 0) {
2074 $max = new UFC_Promo('<=', self
::GRADE_ING
, intval($promo_max));
2076 $max = new PFC_True();
2078 return new UserFilter(new PFC_And($min, $max));
2081 static public function sortByName()
2083 return array(new UFO_Name(Profile
::LASTNAME
), new UFO_Name(Profile
::FIRSTNAME
));
2086 static public function sortByPromo()
2088 return array(new UFO_Promo(), new UFO_Name(Profile
::LASTNAME
), new UFO_Name(Profile
::FIRSTNAME
));
2091 static private function getDBSuffix($string)
2093 if (is_array($string)) {
2094 if (count($string) == 1) {
2095 return self
::getDBSuffix(array_pop($string));
2097 return md5(implode('|', $string));
2099 return preg_replace('/[^a-z0-9]/i', '', $string);
2104 /** Stores a new (and unique) table alias in the &$table table
2105 * @param &$table Array in which the table alias must be stored
2106 * @param $val Value which will then be used to build the join
2107 * @return Name of the newly created alias
2109 private $option = 0;
2110 private function register_optional(array &$table, $val)
2112 if (is_null($val)) {
2113 $sub = $this->option++
;
2116 $sub = self
::getDBSuffix($val);
2120 $table[$sub] = $index;
2124 /** PROFILE VS ACCOUNT
2126 private $with_profiles = false
;
2127 private $with_accounts = false
;
2128 public function requireAccounts()
2130 $this->with_accounts
= true
;
2133 public function accountsRequired()
2135 return $this->with_accounts
;
2138 public function requireProfiles()
2140 $this->with_profiles
= true
;
2143 public function profilesRequired()
2145 return $this->with_profiles
;
2148 protected function accountJoins()
2151 if ($this->with_profiles
&& $this->with_accounts
) {
2152 $joins['ap'] = PlSqlJoin
::left('account_profiles', '$ME.uid = $UID AND FIND_IN_SET(\'owner\', ap.perms)');
2153 $joins['p'] = PlSqlJoin
::left('profiles', '$PID = ap.pid');
2160 private $at = false
;
2161 public function requirePerms()
2163 $this->requireAccounts();
2168 protected function permJoins()
2171 return array('at' => PlSqlJoin
::left('account_types', '$ME.type = a.type'));
2179 const DISPLAY
= 'display';
2180 private $pd = false
;
2181 public function addDisplayFilter()
2183 $this->requireProfiles();
2188 protected function displayJoins()
2191 return array('pd' => PlSqlJoin
::left('profile_display', '$ME.pid = $PID'));
2200 private $with_logger = false
;
2201 public function addLoggerFilter()
2203 $this->with_logger
= true
;
2204 $this->requireAccounts();
2207 protected function loggerJoins()
2210 if ($this->with_logger
) {
2211 $joins['ls'] = PlSqlJoin
::left('log_sessions', '$ME.uid = $UID');
2219 static public function assertName($name)
2221 if (!DirEnum
::getID(DirEnum
::NAMETYPES
, $name)) {
2222 Platal
::page()->kill('Invalid name type: ' . $name);
2226 private $pn = array();
2227 public function addNameFilter($type, $variant = null
)
2229 $this->requireProfiles();
2230 if (!is_null($variant)) {
2231 $ft = $type . '_' . $variant;
2236 self
::assertName($ft);
2238 if (!is_null($variant) && $variant == 'other') {
2239 $sub .= $this->option++
;
2241 $this->pn
[$sub] = DirEnum
::getID(DirEnum
::NAMETYPES
, $ft);
2245 protected function nameJoins()
2248 foreach ($this->pn
as $sub => $type) {
2249 $joins['pn' . $sub] = PlSqlJoin
::left('profile_name', '$ME.pid = $PID AND $ME.typeid = {?}', $type);
2256 private $name_tokens = array();
2257 private $nb_tokens = 0;
2259 public function addNameTokensFilter($token)
2261 $this->requireProfiles();
2262 $sub = 'sn' . (1 +
$this->nb_tokens
);
2264 $this->name_tokens
[$sub] = $token;
2268 protected function nameTokensJoins()
2270 /* We don't return joins, since with_sn forces the SELECT to run on search_name first */
2272 foreach ($this->name_tokens
as $sub => $token) {
2273 $joins[$sub] = PlSqlJoin
::left('search_name', '$ME.pid = $PID');
2278 public function getNameTokens()
2280 return $this->name_tokens
;
2286 private $with_nat = false
;
2287 public function addNationalityFilter()
2289 $this->with_nat
= true
;
2293 protected function nationalityJoins()
2296 if ($this->with_nat
) {
2297 $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');
2304 const GRADE_ING
= 'Ing.';
2305 const GRADE_PHD
= 'PhD';
2306 const GRADE_MST
= 'M%';
2307 static public function isGrade($grade)
2309 return ($grade !== 0) && ($grade == self
::GRADE_ING ||
$grade == self
::GRADE_PHD ||
$grade == self
::GRADE_MST
);
2312 static public function assertGrade($grade)
2314 if (!self
::isGrade($grade)) {
2315 Platal
::page()->killError("DiplĂ´me non valide: $grade");
2319 static public function promoYear($grade)
2321 // XXX: Definition of promotion for phds and masters might change in near future.
2322 return ($grade == UserFilter
::GRADE_ING
) ?
'entry_year' : 'grad_year';
2325 private $pepe = array();
2326 private $with_pee = false
;
2327 public function addEducationFilter($x = false
, $grade = null
)
2329 $this->requireProfiles();
2331 $index = $this->option
;
2332 $sub = $this->option++
;
2334 self
::assertGrade($grade);
2337 $this->with_pee
= true
;
2340 $this->pepe
[$index] = $sub;
2344 protected function educationJoins()
2347 if ($this->with_pee
) {
2348 $joins['pee'] = PlSqlJoin
::inner('profile_education_enum', 'pee.abbreviation = \'X\'');
2350 foreach ($this->pepe
as $grade => $sub) {
2351 if ($this->isGrade($grade)) {
2352 $joins['pe' . $sub] = PlSqlJoin
::left('profile_education', '$ME.eduid = pee.id AND $ME.pid = $PID');
2353 $joins['pede' . $sub] = PlSqlJoin
::inner('profile_education_degree_enum', '$ME.id = pe' . $sub . '.degreeid AND $ME.abbreviation LIKE {?}', $grade);
2355 $joins['pe' . $sub] = PlSqlJoin
::left('profile_education', '$ME.pid = $PID');
2356 $joins['pee' . $sub] = PlSqlJoin
::inner('profile_education_enum', '$ME.id = pe' . $sub . '.eduid');
2357 $joins['pede' . $sub] = PlSqlJoin
::inner('profile_education_degree_enum', '$ME.id = pe' . $sub . '.degreeid');
2366 private $gpm = array();
2367 public function addGroupFilter($group = null
)
2369 $this->requireAccounts();
2370 if (!is_null($group)) {
2371 if (is_int($group) ||
ctype_digit($group)) {
2372 $index = $sub = $group;
2375 $sub = self
::getDBSuffix($group);
2378 $sub = 'group_' . $this->option++
;
2382 $this->gpm
[$sub] = $index;
2386 protected function groupJoins()
2389 foreach ($this->gpm
as $sub => $key) {
2390 if (is_null($key)) {
2391 $joins['gpa' . $sub] = PlSqlJoin
::inner('groups');
2392 $joins['gpm' . $sub] = PlSqlJoin
::left('group_members', '$ME.uid = $UID AND $ME.asso_id = gpa' . $sub . '.id');
2393 } else if (is_int($key) ||
ctype_digit($key)) {
2394 $joins['gpm' . $sub] = PlSqlJoin
::left('group_members', '$ME.uid = $UID AND $ME.asso_id = ' . $key);
2396 $joins['gpa' . $sub] = PlSqlJoin
::inner('groups', '$ME.diminutif = {?}', $key);
2397 $joins['gpm' . $sub] = PlSqlJoin
::left('group_members', '$ME.uid = $UID AND $ME.asso_id = gpa' . $sub . '.id');
2406 private $with_bi = false
;
2407 private $with_bd = false
;
2408 public function addBinetsFilter($with_enum = false
)
2410 $this->requireProfiles();
2411 $this->with_bi
= true
;
2413 $this->with_bd
= true
;
2420 protected function binetsJoins()
2423 if ($this->with_bi
) {
2424 $joins['bi'] = PlSqlJoin
::left('profile_binets', '$ME.pid = $PID');
2426 if ($this->with_bd
) {
2427 $joins['bd'] = PlSqlJoin
::left('profile_binet_enum', '$ME.id = bi.binet_id');
2434 private $e = array();
2435 public function addEmailRedirectFilter($email = null
)
2437 $this->requireAccounts();
2438 return $this->register_optional($this->e
, $email);
2441 private $ve = array();
2442 public function addVirtualEmailFilter($email = null
)
2444 $this->addAliasFilter(self
::ALIAS_FORLIFE
);
2445 return $this->register_optional($this->ve
, $email);
2448 const ALIAS_BEST
= 'bestalias';
2449 const ALIAS_FORLIFE
= 'forlife';
2450 private $al = array();
2451 public function addAliasFilter($alias = null
)
2453 $this->requireAccounts();
2454 return $this->register_optional($this->al
, $alias);
2457 protected function emailJoins()
2461 foreach ($this->e
as $sub=>$key) {
2462 if (is_null($key)) {
2463 $joins['e' . $sub] = PlSqlJoin
::left('emails', '$ME.uid = $UID AND $ME.flags != \'filter\'');
2465 if (!is_array($key)) {
2468 $joins['e' . $sub] = PlSqlJoin
::left('emails', '$ME.uid = $UID AND $ME.flags != \'filter\'
2469 AND $ME.email IN {?}', $key);
2472 foreach ($this->al
as $sub=>$key) {
2473 if (is_null($key)) {
2474 $joins['al' . $sub] = PlSqlJoin
::left('aliases', '$ME.uid = $UID AND $ME.type IN (\'alias\', \'a_vie\')');
2475 } else if ($key == self
::ALIAS_BEST
) {
2476 $joins['al' . $sub] = PlSqlJoin
::left('aliases', '$ME.uid = $UID AND $ME.type IN (\'alias\', \'a_vie\') AND FIND_IN_SET(\'bestalias\', $ME.flags)');
2477 } else if ($key == self
::ALIAS_FORLIFE
) {
2478 $joins['al' . $sub] = PlSqlJoin
::left('aliases', '$ME.uid = $UID AND $ME.type = \'a_vie\'');
2480 if (!is_array($key)) {
2483 $joins['al' . $sub] = PlSqlJoin
::left('aliases', '$ME.uid = $UID AND $ME.type IN (\'alias\', \'a_vie\')
2484 AND $ME.alias IN {?}', $key);
2487 foreach ($this->ve
as $sub=>$key) {
2488 if (is_null($key)) {
2489 $joins['v' . $sub] = PlSqlJoin
::left('virtual', '$ME.type = \'user\'');
2491 if (!is_array($key)) {
2494 $joins['v' . $sub] = PlSqlJoin
::left('virtual', '$ME.type = \'user\' AND $ME.alias IN {?}', $key);
2496 $joins['vr' . $sub] = PlSqlJoin
::left('virtual_redirect',
2497 '$ME.vid = v' . $sub . '.vid
2498 AND ($ME.redirect IN (CONCAT(al_forlife.alias, \'@\', {?}),
2499 CONCAT(al_forlife.alias, \'@\', {?}),
2501 $globals->mail
->domain
, $globals->mail
->domain2
);
2509 private $with_pa = false
;
2510 public function addAddressFilter()
2512 $this->requireProfiles();
2513 $this->with_pa
= true
;
2517 private $with_pac = false
;
2518 public function addAddressCountryFilter()
2520 $this->requireProfiles();
2521 $this->addAddressFilter();
2522 $this->with_pac
= true
;
2526 private $with_pal = false
;
2527 public function addAddressLocalityFilter()
2529 $this->requireProfiles();
2530 $this->addAddressFilter();
2531 $this->with_pal
= true
;
2535 protected function addressJoins()
2538 if ($this->with_pa
) {
2539 $joins['pa'] = PlSqlJoin
::left('profile_addresses', '$ME.pid = $PID');
2541 if ($this->with_pac
) {
2542 $joins['gc'] = PlSqlJoin
::left('geoloc_countries', '$ME.iso_3166_1_a2 = pa.countryID');
2544 if ($this->with_pal
) {
2545 $joins['gl'] = PlSqlJoin
::left('geoloc_localities', '$ME.id = pa.localityID');
2554 private $pc = false
;
2555 private $pce = array();
2556 private $pcr = false
;
2557 public function addCorpsFilter($type)
2559 $this->requireProfiles();
2561 if ($type == UFC_Corps
::CURRENT
) {
2562 $pce['pcec'] = 'current_corpsid';
2564 } else if ($type == UFC_Corps
::ORIGIN
) {
2565 $pce['pceo'] = 'original_corpsid';
2570 public function addCorpsRankFilter()
2572 $this->requireProfiles();
2578 protected function corpsJoins()
2582 $joins['pc'] = PlSqlJoin
::left('profile_corps', '$ME.pid = $PID');
2585 $joins['pcr'] = PlSqlJoin
::left('profile_corps_rank_enum', '$ME.id = pc.rankid');
2587 foreach($this->pce
as $sub => $field) {
2588 $joins[$sub] = PlSqlJoin
::left('profile_corps_enum', '$ME.id = pc.' . $field);
2596 const JOB_USERDEFINED
= 0x0001;
2597 const JOB_CV
= 0x0002;
2598 const JOB_ANY
= 0x0003;
2602 * pje => profile_job_enum
2603 * pjt => profile_job_terms
2605 private $with_pj = false
;
2606 private $with_pje = false
;
2607 private $with_pjt = 0;
2609 public function addJobFilter()
2611 $this->requireProfiles();
2612 $this->with_pj
= true
;
2616 public function addJobCompanyFilter()
2618 $this->addJobFilter();
2619 $this->with_pje
= true
;
2624 * Adds a filter on job terms of profile.
2625 * @param $nb the number of job terms to use
2626 * @return an array of the fields to filter (one for each term).
2628 public function addJobTermsFilter($nb = 1)
2630 $this->with_pjt
= $nb;
2631 $jobtermstable = array();
2632 for ($i = 1; $i <= $nb; ++
$i) {
2633 $jobtermstable[] = 'pjtr_'.$i;
2635 return $jobtermstable;
2638 protected function jobJoins()
2641 if ($this->with_pj
) {
2642 $joins['pj'] = PlSqlJoin
::left('profile_job', '$ME.pid = $PID');
2644 if ($this->with_pje
) {
2645 $joins['pje'] = PlSqlJoin
::left('profile_job_enum', '$ME.id = pj.jobid');
2647 if ($this->with_pjt
> 0) {
2648 for ($i = 1; $i <= $this->with_pjt
; ++
$i) {
2649 $joins['pjt_'.$i] = PlSqlJoin
::left('profile_job_term', '$ME.pid = $PID');
2650 $joins['pjtr_'.$i] = PlSqlJoin
::left('profile_job_term_relation', '$ME.jtid_2 = pjt_'.$i.'.jtid');
2659 private $with_pnw = false
;
2660 public function addNetworkingFilter()
2662 $this->requireAccounts();
2663 $this->with_pnw
= true
;
2667 protected function networkingJoins()
2670 if ($this->with_pnw
) {
2671 $joins['pnw'] = PlSqlJoin
::left('profile_networking', '$ME.pid = $PID');
2679 private $with_ptel = false
;
2681 public function addPhoneFilter()
2683 $this->requireAccounts();
2684 $this->with_ptel
= true
;
2688 protected function phoneJoins()
2691 if ($this->with_ptel
) {
2692 $joins['ptel'] = PlSqlJoin
::left('profile_phones', '$ME.pid = $PID');
2700 private $with_pmed = false
;
2701 public function addMedalFilter()
2703 $this->requireProfiles();
2704 $this->with_pmed
= true
;
2708 protected function medalJoins()
2711 if ($this->with_pmed
) {
2712 $joins['pmed'] = PlSqlJoin
::left('profile_medals', '$ME.pid = $PID');
2720 private $pms = array();
2721 private $mjtr = false
;
2723 const MENTOR_EXPERTISE
= 2;
2724 const MENTOR_COUNTRY
= 3;
2725 const MENTOR_TERM
= 4;
2727 public function addMentorFilter($type)
2729 $this->requireAccounts();
2732 $this->pms
['pm'] = 'profile_mentor';
2734 case self
::MENTOR_EXPERTISE
:
2735 $this->pms
['pme'] = 'profile_mentor';
2737 case self
::MENTOR_COUNTRY
:
2738 $this->pms
['pmc'] = 'profile_mentor_country';
2740 case self
::MENTOR_TERM
:
2741 $this->pms
['pmt'] = 'profile_mentor_term';
2745 Platal
::page()->killError("Undefined mentor filter.");
2749 protected function mentorJoins()
2752 foreach ($this->pms
as $sub => $tab) {
2753 $joins[$sub] = PlSqlJoin
::left($tab, '$ME.pid = $PID');
2756 $joins['mjtr'] = PlSqlJoin
::left('profile_job_term_relation', '$ME.jtid_2 = pmt.jtid');
2763 private $cts = array();
2764 public function addContactFilter($uid = null
)
2766 $this->requireProfiles();
2767 return $this->register_optional($this->cts
, is_null($uid) ? null
: 'user_' . $uid);
2770 protected function contactJoins()
2773 foreach ($this->cts
as $sub=>$key) {
2774 if (is_null($key)) {
2775 $joins['c' . $sub] = PlSqlJoin
::left('contacts', '$ME.contact = $PID');
2777 $joins['c' . $sub] = PlSqlJoin
::left('contacts', '$ME.uid = {?} AND $ME.contact = $PID', substr($key, 5));
2786 private $wn = array();
2787 public function addWatchRegistrationFilter($uid = null
)
2789 $this->requireAccounts();
2790 return $this->register_optional($this->wn
, is_null($uid) ? null
: 'user_' . $uid);
2793 private $wp = array();
2794 public function addWatchPromoFilter($uid = null
)
2796 $this->requireAccounts();
2797 return $this->register_optional($this->wp
, is_null($uid) ? null
: 'user_' . $uid);
2800 private $w = array();
2801 public function addWatchFilter($uid = null
)
2803 $this->requireAccounts();
2804 return $this->register_optional($this->w
, is_null($uid) ? null
: 'user_' . $uid);
2807 protected function watchJoins()
2810 foreach ($this->w
as $sub=>$key) {
2811 if (is_null($key)) {
2812 $joins['w' . $sub] = PlSqlJoin
::left('watch');
2814 $joins['w' . $sub] = PlSqlJoin
::left('watch', '$ME.uid = {?}', substr($key, 5));
2817 foreach ($this->wn
as $sub=>$key) {
2818 if (is_null($key)) {
2819 $joins['wn' . $sub] = PlSqlJoin
::left('watch_nonins', '$ME.ni_id = $UID');
2821 $joins['wn' . $sub] = PlSqlJoin
::left('watch_nonins', '$ME.uid = {?} AND $ME.ni_id = $UID', substr($key, 5));
2824 foreach ($this->wn
as $sub=>$key) {
2825 if (is_null($key)) {
2826 $joins['wn' . $sub] = PlSqlJoin
::left('watch_nonins', '$ME.ni_id = $UID');
2828 $joins['wn' . $sub] = PlSqlJoin
::left('watch_nonins', '$ME.uid = {?} AND $ME.ni_id = $UID', substr($key, 5));
2831 foreach ($this->wp
as $sub=>$key) {
2832 if (is_null($key)) {
2833 $joins['wp' . $sub] = PlSqlJoin
::left('watch_promo');
2835 $joins['wp' . $sub] = PlSqlJoin
::left('watch_promo', '$ME.uid = {?}', substr($key, 5));
2844 private $with_photo;
2845 public function addPhotoFilter()
2847 $this->requireProfiles();
2848 $this->with_photo
= true
;
2852 protected function photoJoins()
2854 if ($this->with_photo
) {
2855 return array('photo' => PlSqlJoin
::left('profile_photos', '$ME.pid = $PID'));
2865 public function addMarketingHash()
2867 $this->requireAccounts();
2868 $this->with_rm
= true
;
2871 protected function marketingJoins()
2873 if ($this->with_rm
) {
2874 return array('rm' => PlSqlJoin
::left('register_marketing', '$ME.uid = $UID'));
2882 // {{{ class ProfileFilter
2883 class ProfileFilter
extends UserFilter
2885 public function get($limit = null
)
2887 return $this->getProfiles($limit);
2890 public function filter(array $profiles, $limit = null
)
2892 return $this->filterProfiles($profiles, self
::defaultLimit($limit));
2895 public function getTotalCount()
2897 return $this->getTotalProfileCount();
2900 public function getGroups()
2902 return $this->getPIDGroups();
2907 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: