2 /***************************************************************************
3 * Copyright (C) 2003-2011 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 ***************************************************************************/
22 class User
extends PlUser
24 const PERM_API_USER_READONLY
= 'api_user_readonly';
25 const PERM_DIRECTORY_AX
= 'directory_ax';
26 const PERM_DIRECTORY_PRIVATE
= 'directory_private';
27 const PERM_EDIT_DIRECTORY
= 'edit_directory';
28 const PERM_FORUMS
= 'forums';
29 const PERM_GROUPS
= 'groups';
30 const PERM_LISTS
= 'lists';
31 const PERM_MAIL
= 'mail';
32 const PERM_PAYMENT
= 'payment';
34 private $_profile_fetched = false
;
35 private $_profile = null
;
37 // Additional fields (non core)
38 protected $promo = null
;
40 // Implementation of the login to uid method.
41 protected function getLogin($login)
46 throw new UserNotFoundException();
49 if ($login instanceof User
) {
53 if ($login instanceof Profile
) {
54 $this->_profile
= $login;
55 $this->_profile_fetched
= true
;
56 $res = XDB
::query('SELECT ap.uid
57 FROM account_profiles AS ap
58 WHERE ap.pid = {?} AND FIND_IN_SET(\'owner\', perms)',
60 if ($res->numRows()) {
61 return $res->fetchOneCell();
63 throw new UserNotFoundException();
66 // If $data is an integer, fetches directly the result.
67 if (is_numeric($login)) {
68 $res = XDB
::query('SELECT uid
70 WHERE uid = {?}', $login);
71 if ($res->numRows()) {
72 return $res->fetchOneCell();
75 throw new UserNotFoundException();
78 // Checks whether $login is a valid hruid or not.
79 $res = XDB
::query('SELECT uid
81 WHERE hruid = {?}', $login);
82 if ($res->numRows()) {
83 return $res->fetchOneCell();
86 // From now, $login can only by an email alias, or an email redirection.
87 // If it doesn't look like a valid address, appends the plat/al's main domain.
88 $login = trim(strtolower($login));
89 if (strstr($login, '@') === false
) {
91 $domain = $globals->mail
->domain
;
93 list($email, $domain) = explode('@', $login);
96 // Checks if $login is a valid alias on any domain.
97 $res = XDB
::fetchOneCell('SELECT s.uid
98 FROM email_source_account AS s
99 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
100 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
101 WHERE s.email = {?} AND d.name = {?}',
107 // Looks for an account with the given email.
108 $res = XDB
::query('SELECT uid
110 WHERE email = {?}', $login);
111 if ($res->numRows() == 1) {
112 return $res->fetchOneCell();
115 // Otherwise, we do suppose $login is an email redirection.
116 $res = XDB
::query('SELECT uid
117 FROM email_redirect_account
118 WHERE redirect = {?}', $login);
119 if ($res->numRows() == 1) {
120 return $res->fetchOneCell();
123 throw new UserNotFoundException($res->fetchColumn(1));
126 protected static function loadMainFieldsFromUIDs(array $uids, $respect_order = true
)
129 return PlIteratorUtils
::emptyIterator();
135 if ($globals->asso('id')) {
136 $joins .= XDB
::format("LEFT JOIN group_members AS gpm ON (gpm.uid = a.uid AND gpm.asso_id = {?})\n", $globals->asso('id'));
137 $fields[] = 'gpm.perms AS group_perms';
138 $fields[] = 'gpm.comm AS group_comm';
139 $fields[] = 'gpm.position AS group_position';
141 if (count($fields) > 0) {
142 $fields = ', ' . implode(', ', $fields);
147 if ($respect_order) {
148 $order = 'ORDER BY ' . XDB
::formatCustomOrder('a.uid', $uids);
153 $uids = array_map(array('XDB', 'escape'), $uids);
155 return XDB
::iterator('SELECT a.uid, a.hruid, a.registration_date, h.uid IS NOT NULL AS homonym,
156 IF(ef.email IS NULL, NULL, CONCAT(ef.email, \'@\', MAX(df.name))) AS forlife,
157 IF(ef.email IS NULL, NULL, CONCAT(ef.email, \'@\', MIN(df.name))) AS forlife_alternate,
158 IF(eb.email IS NULL, NULL, CONCAT(eb.email, \'@\', MAX(db.name))) AS bestalias,
159 IF(eb.email IS NULL, NULL, CONCAT(eb.email, \'@\', MIN(db.name))) AS bestalias_alternate,
160 (er.redirect IS NULL AND a.state = \'active\') AS lost,
161 a.email, a.full_name, a.directory_name, a.display_name, a.sex = \'female\' AS gender,
162 IF(a.state = \'active\', CONCAT(at.perms, \',\', IF(a.user_perms IS NULL, \'\', a.user_perms)), \'\') AS perms,
163 a.user_perms, a.email_format, a.is_admin, a.state, a.type, at.description AS type_description, a.skin,
164 FIND_IN_SET(\'watch\', a.flags) AS watch, a.comment,
165 a.weak_password IS NOT NULL AS weak_access, g.g_account_name IS NOT NULL AS googleapps,
166 a.token IS NOT NULL AS token_access, a.token, a.last_version,
167 UNIX_TIMESTAMP(s.start) AS lastlogin, s.host, UNIX_TIMESTAMP(fp.last_seen) AS banana_last
170 INNER JOIN account_types AS at ON (at.type = a.type)
171 LEFT JOIN email_source_account AS ef ON (ef.uid = a.uid AND ef.type = \'forlife\')
172 LEFT JOIN email_virtual_domains AS mf ON (ef.domain = mf.id)
173 LEFT JOIN email_virtual_domains AS df ON (df.aliasing = mf.id)
174 LEFT JOIN email_source_account AS eb ON (eb.uid = a.uid AND eb.flags = \'bestalias\')
175 LEFT JOIN email_virtual_domains AS mb ON (eb.domain = mb.id)
176 LEFT JOIN email_virtual_domains AS db ON (db.aliasing = mb.id)
177 LEFT JOIN email_redirect_account AS er ON (er.uid = a.uid AND er.flags = \'active\' AND er.broken_level < 3
178 AND er.type != \'imap\' AND er.type != \'homonym\')
179 LEFT JOIN homonyms_list AS h ON (h.uid = a.uid)
180 LEFT JOIN gapps_accounts AS g ON (a.uid = g.l_userid AND g.g_status = \'active\')
181 LEFT JOIN log_last_sessions AS ls ON (ls.uid = a.uid)
182 LEFT JOIN log_sessions AS s ON (s.id = ls.id)
183 LEFT JOIN forum_profiles AS fp ON (fp.uid = a.uid)
185 WHERE a.uid IN (' . implode(', ', $uids) . ')
190 // Implementation of the data loader.
191 protected function loadMainFields()
193 if ($this->hruid
!== null
&& $this->forlife
!== null
194 && $this->bestalias
!== null
&& $this->display_name
!== null
195 && $this->full_name
!== null
&& $this->perms
!== null
196 && $this->gender
!== null
&& $this->email_format
!== null
) {
199 $this->fillFromArray(self
::loadMainFieldsFromUIDs(array($this->uid
))->next());
202 // Specialization of the buildPerms method
203 // This function build 'generic' permissions for the user. It does not take
204 // into account page specific permissions (e.g X.net group permissions)
205 protected function buildPerms()
207 if (!is_null($this->perm_flags
)) {
210 if ($this->perms
=== null
) {
211 $this->loadMainFields();
213 $this->perm_flags
= self
::makePerms($this->perms
, $this->is_admin
);
216 public function setPerms($perms)
218 $this->perms
= $perms;
219 $this->perm_flags
= null
;
222 // We do not want to store the password in the object.
223 // So, fetch it 'on demand'
224 public function password()
226 return XDB
::fetchOneCell('SELECT a.password
228 WHERE a.uid = {?}', $this->id());
231 public function isActive()
233 return $this->state
== 'active';
236 /** Overload PlUser::promo(): there no promo defined for a user in the current
237 * schema. The promo is a field from the profile.
239 public function promo()
241 if (!$this->hasProfile()) {
244 return $this->profile()->promo();
247 public function category()
249 $promo = $this->promo();
250 if (!empty($promo)) {
253 return $this->type_description
;
257 public function firstName()
259 if (!$this->hasProfile()) {
260 return $this->displayName();
262 return $this->profile()->firstName();
265 public function lastName()
267 if (!$this->hasProfile()) {
270 return $this->profile()->lastName();
273 public function displayName()
275 if (!$this->hasProfile()) {
276 return $this->display_name
;
278 return $this->profile()->yourself
;
281 public function fullName($with_promo = false
)
283 if (!$this->hasProfile()) {
284 return $this->full_name
;
286 return $this->profile()->fullName($with_promo);
289 public function directoryName()
291 if (!$this->hasProfile()) {
292 return $this->directory_name
;
294 return $this->profile()->directory_name
;
297 /** Return the main profile attached with this account if any.
299 public function profile($forceFetch = false
, $fields = 0x0000, $visibility = null
)
301 if (!$this->_profile_fetched ||
$forceFetch) {
302 $this->_profile_fetched
= true
;
303 $this->_profile
= Profile
::get($this, $fields, $visibility);
305 return $this->_profile
;
308 /** Return true if the user has an associated profile.
310 public function hasProfile()
312 return !is_null($this->profile());
315 /** Return true if given a reference to the profile of this user.
317 public function isMyProfile($other)
321 } else if ($other instanceof Profile
) {
322 $profile = $this->profile();
323 return $profile && $profile->id() == $other->id();
328 /** Check if the user can edit to given profile.
330 public function canEdit(Profile
$profile)
332 if ($this->checkPerms(User
::PERM_EDIT_DIRECTORY
)) {
335 return XDB
::fetchOneCell('SELECT pid
336 FROM account_profiles
337 WHERE uid = {?} AND pid = {?}',
338 $this->id(), $profile->id());
341 /** Fetch existing @alias_dom alias.
343 public function emailAlias()
345 $aliases = $this->emailAliases();
346 if (count($aliases)) {
352 /** Fetch existing @alias_dom aliases.
354 public function emailAliases()
356 return XDB
::fetchColumn('SELECT CONCAT(s.email, \'@\', d.name)
357 FROM email_source_account AS s
358 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
359 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
360 WHERE s.uid = {?} AND m.name = {?}
362 $this->id(), Platal
::globals()->mail
->alias_dom
);
365 /** Get all group aliases the user belongs to.
367 public function emailGroupAliases($domain = null
)
369 if (is_null($domain)) {
370 return XDB
::fetchColumn('SELECT CONCAT(v.email, \'@\', dv.name) AS alias
371 FROM email_virtual AS v
372 INNER JOIN email_virtual_domains AS dv ON (v.domain = dv.id)
373 INNER JOIN email_source_account AS s ON (s.uid = {?})
374 INNER JOIN email_virtual_domains AS ms ON (s.domain = ms.id)
375 INNER JOIN email_virtual_domains AS ds ON (ds.aliasing = ms.id)
376 WHERE v.redirect = CONCAT(s.email, \'@\', ds.name) AND v.type = \'alias\'',
379 return XDB
::fetchAllAssoc('alias',
380 'SELECT CONCAT(v.email, \'@\', dv.name) AS alias, MAX(v.redirect = CONCAT(s.email, \'@\', ds.name)) AS sub
381 FROM email_virtual AS v
382 INNER JOIN email_virtual_domains AS dv ON (v.domain = dv.id AND dv.name = {?})
383 INNER JOIN email_source_account AS s ON (s.uid = {?})
384 INNER JOIN email_virtual_domains AS ms ON (s.domain = ms.id)
385 INNER JOIN email_virtual_domains AS ds ON (ds.aliasing = ms.id)
386 WHERE v.type = \'alias\'
389 $domain, $this->id());
393 /** Get marketing informations
395 private function fetchMarketingData()
397 if (isset($this->pending_registration_date
)) {
400 $infos = XDB
::fetchOneAssoc('SELECT rp.date AS pending_registration_date, rp.email AS pending_registration_email,
401 rm.last AS last_marketing_date, rm.email AS last_marketing_email
403 LEFT JOIN register_pending AS rp ON (rp.uid = a.uid)
404 LEFT JOIN register_marketing AS rm ON (rm.uid = a.uid AND rm.last != \'0000-00-00\')
406 ORDER BY rm.last DESC', $this->id());
407 if (is_null($infos)) {
409 'pending_registration_date' => null
,
410 'pending_registration_email' => null
,
411 'last_marketing_date' => null
,
412 'last_marketing_email' => null
415 $this->fillFromArray($infos);
418 public function pendingRegistrationDate()
420 $this->fetchMarketingData();
421 return $this->pending_registration_date
;
424 public function pendingRegistrationEmail()
426 $this->fetchMarketingData();
427 return $this->pending_registration_email
;
430 public function lastMarketingDate()
432 $this->fetchMarketingData();
433 return $this->last_marketing_date
;
436 public function lastMarketingEmail()
438 $this->fetchMarketingData();
439 return $this->last_marketing_email
;
442 public function lastKnownEmail()
444 $this->fetchMarketingData();
445 if ($this->pending_registration_email
> $this->last_marketing_date
) {
446 return $this->pending_registration_email
;
448 return $this->last_marketing_email
;
452 /** Format of the emails sent by the site
454 public function setEmailFormat($format)
456 Platal
::assert($format == self
::FORMAT_HTML ||
$format == self
::FORMAT_TEXT
,
457 "Invalid email format \"$format\"");
458 XDB
::execute("UPDATE accounts
459 SET email_format = {?}
461 $format, $this->uid
);
462 $this->email_format
= $format;
465 /** Get watch informations
467 private function fetchWatchData()
469 if (isset($this->watch_actions
)) {
472 $watch = XDB
::fetchOneAssoc('SELECT flags AS watch_flags, actions AS watch_actions,
473 UNIX_TIMESTAMP(last) AS watch_last
475 WHERE uid = {?}', $this->id());
476 $watch['watch_flags'] = new PlFlagSet($watch['watch_flags']);
477 $watch['watch_actions'] = new PlFlagSet($watch['watch_actions']);
478 $watch['watch_promos'] = XDB
::fetchColumn('SELECT promo
480 WHERE uid = {?}', $this->id());
481 $watch['watch_users'] = XDB
::fetchColumn('SELECT ni_id
483 WHERE uid = {?}', $this->id());
484 $this->fillFromArray($watch);
487 public function watchType($type)
489 $this->fetchWatchData();
490 return $this->watch_actions
->hasFlag($type);
493 public function watchContacts()
495 $this->fetchWatchData();
496 return $this->watch_flags
->hasFlag('contacts');
499 public function watchEmail()
501 $this->fetchWatchData();
502 return $this->watch_flags
->hasFlag('mail');
505 public function watchPromos()
507 $this->fetchWatchData();
508 return $this->watch_promos
;
511 public function watchUsers()
513 $this->fetchWatchData();
514 return $this->watch_users
;
517 public function watchLast()
519 $this->fetchWatchData();
520 return $this->watch_last
;
523 public function invalidWatchCache()
525 unset($this->watch_actions
);
526 unset($this->watch_users
);
527 unset($this->watch_last
);
528 unset($this->watch_promos
);
533 private $contacts = null
;
534 private function fetchContacts()
536 if (is_null($this->contacts
)) {
537 $this->contacts
= XDB
::fetchAllAssoc('contact', 'SELECT *
544 public function iterContacts()
546 $this->fetchContacts();
547 return Profile
::iterOverPIDs(array_keys($this->contacts
));
550 public function getContacts()
552 $this->fetchContacts();
553 return Profile
::getBulkProfilesWithPIDs(array_keys($this->contacts
));
556 public function isContact(Profile
$profile)
558 $this->fetchContacts();
559 return isset($this->contacts
[$profile->id()]);
562 public function isWatchedUser(Profile
$profile)
564 return in_array($profile->id(), $this->watchUsers());
568 private $groups = null
;
569 public function groups($institutions = false
, $onlyPublic = false
)
571 if (is_null($this->groups
)) {
572 $this->groups
= XDB
::fetchAllAssoc('asso_id', 'SELECT gm.asso_id, gm.perms, gm.comm,
573 g.diminutif, g.nom, g.site, g.cat,
575 FROM group_members AS gm
576 INNER JOIN groups AS g ON (g.id = gm.asso_id)
580 if (!$institutions && !$onlyPublic) {
581 return $this->groups
;
584 foreach ($this->groups
as $id=>$data) {
586 if ($data['cat'] != Group
::CAT_GROUPESX
&& $data['cat'] != Group
::CAT_INSTITUTIONS
) {
591 if ($data['pub'] != 'public') {
595 $result[$id] = $data;
603 * *always deletes in: account_lost_passwords, register_marketing,
604 * register_pending, register_subs, watch_nonins, watch, watch_promo
605 * *always keeps in: account_types, accounts, email_virtual, carvas,
606 * group_members, homonyms_list, newsletter_ins, register_mstats, email_source_account
607 * *deletes if $clearAll: account_auth_openid, announce_read, contacts,
608 * email_redirect_account, email_redirect_account, email_send_save, forum_innd, forum_profiles,
609 * forum_subs, gapps_accounts, gapps_nicknames, group_announces_read,
610 * group_member_sub_requests, reminder, requests, requests_hidden,
612 * *modifies if $clearAll: accounts
615 * *$clearAll == false: when a user dies, her family still needs to keep in
616 * touch with the community.
617 * *$clearAll == true: in every other case we want the account to be fully
618 * deleted so that it can not be used anymore.
620 public function clear($clearAll = true
)
622 $tables = array('account_lost_passwords', 'register_marketing',
623 'register_pending', 'register_subs', 'watch_nonins',
624 'watch', 'watch_promo');
626 foreach ($tables as $t) {
627 XDB
::execute('DELETE FROM ' . $t . '
635 $groupIds = XDB
::iterator('SELECT asso_id
639 while ($groupId = $groupIds->next()) {
640 $group = Group
::get($groupId);
641 if (!empty($group) && $group->notif_unsub
) {
642 $mailer = new PlMailer('xnetgrp/unsubscription-notif.mail.tpl');
643 $admins = $group->iterAdmins();
644 while ($admin = $admins->next()) {
645 $mailer->addTo($admin);
647 $mailer->assign('group', $group->shortname
);
648 $mailer->assign('user', $this);
649 $mailer->assign('selfdone', false
);
654 $tables = array('account_auth_openid', 'announce_read', 'contacts',
655 'email_send_save', 'email_virtual',
656 'forum_innd', 'forum_profiles', 'forum_subs',
657 'group_announces_read', 'group_members',
658 'group_member_sub_requests', 'reminder', 'requests',
660 foreach ($tables as $t) {
661 XDB
::execute('DELETE FROM ' . $t . '
665 XDB
::execute('DELETE FROM email_redirect_account
666 WHERE uid = {?} AND type != \'homonym\'',
669 foreach (array('gapps_accounts', 'gapps_nicknames') as $t) {
670 XDB
::execute('DELETE FROM ' . $t . '
671 WHERE l_userid = {?}',
675 XDB
::execute("UPDATE accounts
676 SET registration_date = 0, state = 'pending', password = NULL,
677 weak_password = NULL, token = NULL, is_admin = 0
681 if ($globals->mailstorage
->googleapps_domain
) {
682 require_once 'googleapps.inc.php';
684 if (GoogleAppsAccount
::account_status($this->id())) {
685 $account = new GoogleAppsAccount($this);
691 $mmlist = new MMList(S
::user());
692 $mmlist->kill($this->hruid
, $clearAll);
695 // Merge all infos in other user and then clean this one
696 public function mergeIn(User
$newuser) {
697 if ($this->profile()) {
698 // Don't disable user with profile in this way.
700 Platal
::page()->trigError('Impossible de fusionner les comptes ' . $this->hruid
. ' et ' . $newuser->hruid
.
701 '. Contacte support@' . $globals->mail
->domain
. '.');
705 if ($this->forlifeEmail()) {
706 // If the new user is not registered and does not have already an email address,
707 // we need to give him the old user's email address if he has any.
708 if (!$newuser->perms
) {
709 XDB
::execute('UPDATE accounts
711 WHERE uid = {?} AND email IS NULL',
712 $this->forlifeEmail(), $newuser->id());
714 // Reftech new user so its forlifeEmail will be correct.
715 $newuser = getSilentWithUID($newuser->id());
718 // Change email used in mailing lists.
719 if ($this->forlifeEmail() != $newuser->forlifeEmail()) {
720 // group mailing lists
721 $group_domains = XDB
::fetchColumn('SELECT g.mail_domain
723 INNER JOIN group_members AS gm ON(g.id = gm.asso_id)
724 WHERE g.mail_domain != \'\' AND gm.uid = {?}',
726 foreach ($group_domains as $mail_domain) {
727 $mmlist = new MMList($this, $mail_domain);
728 $mmlist->replace_email_in_all($this->forlifeEmail(), $newuser->forlifeEmail());
731 $mmlist = new MMList($this);
732 $mmlist->replace_email_in_all($this->forlifeEmail(), $newuser->forlifeEmail());
736 // Updates user in following tables.
737 foreach (array('group_announces', 'payment_transactions', 'log_sessions', 'group_events') as $table) {
738 XDB
::execute('UPDATE ' . $table . '
741 $newuser->id(), $this->id());
744 // Merges user in following tables, ie updates when possible, then deletes remaining occurences of the old user.
745 foreach (array('group_announces_read', 'group_event_participants', 'group_member_sub_requests', 'group_members', 'email_redirect_account') as $table) {
746 XDB
::execute('UPDATE IGNORE ' . $table . '
749 $newuser->id(), $this->id());
750 XDB
::execute('DELETE FROM ' . $table . '
755 // Eventually updates last session id and deletes old user's accounts entry.
756 $lastSession = XDB
::fetchOneCell('SELECT id
762 XDB
::execute('UPDATE log_last_sessions
765 $lastSession, $newuser->id());
766 XDB
::execute('DELETE FROM accounts
773 // Return permission flags for a given permission level.
774 public static function makePerms($perms, $is_admin)
776 $flags = new PlFlagSet($perms);
777 $flags->addFlag(PERMS_USER
);
779 $flags->addFlag(PERMS_ADMIN
);
782 // Access to private directory implies access to 'less'-private version.
783 if ($flags->hasFlag('directory_private')) {
784 $flags->addFlag('directory_ax');
789 // Implementation of the default user callback.
790 public static function _default_user_callback($login, $results)
792 $result_count = count($results);
793 if ($result_count == 0 ||
!S
::admin()) {
794 Platal
::page()->trigError("Il n'y a pas d'utilisateur avec l'identifiant : $login");
796 Platal
::page()->trigError("Il y a $result_count utilisateurs avec cet identifiant : " . join(', ', $results));
800 // Implementation of the static email locality checker.
801 public static function isForeignEmailAddress($email)
804 if (strpos($email, '@') === false
) {
808 list($user, $dom) = explode('@', $email);
809 return $dom != $globals->mail
->domain
&&
810 $dom != $globals->mail
->domain2
&&
811 $dom != $globals->mail
->alias_dom
&&
812 $dom != $globals->mail
->alias_dom2
;
815 public static function isVirtualEmailAddress($email)
818 if (strpos($email, '@') === false
) {
822 list($user, $dom) = explode('@', $email);
823 return $dom == $globals->mail
->alias_dom
824 ||
$dom == $globals->mail
->alias_dom2
;
827 /* Tries to find pending accounts with an hruid close to $login. */
828 public static function getPendingAccounts($login, $iterator = false
)
832 if (strpos($login, '@') === false
) {
836 list($login, $domain) = explode('@', $login);
838 if ($domain && $domain != $globals->mail
->domain
&& $domain != $globals->mail
->domain2
) {
842 $sql = "SELECT uid, full_name
844 WHERE state = 'pending' AND REPLACE(hruid, '-', '') LIKE
845 CONCAT('%', REPLACE(REPLACE(REPLACE({?}, ' ', ''), '-', ''), '\'', ''), '%')
848 return XDB
::iterator($sql, $login);
850 $res = XDB
::query($sql, $login);
851 return $res->fetchAllAssoc();
856 public static function iterOverUIDs($uids, $respect_order = true
)
858 return new UserIterator(self
::loadMainFieldsFromUIDs($uids, $respect_order));
861 /** Fetch a set of users from a list of UIDs
862 * @param $data The list of uids to fetch, or an array of arrays
863 * @param $orig If $data is an array of arrays, the subfield where uids are stored
864 * @param $dest If $data is an array of arrays, the subfield to fill with Users
865 * @param $fetchProfile Whether to fetch Profiles as well
866 * @return either an array of $uid => User, or $data with $data[$i][$dest] = User
868 public static function getBulkUsersWithUIDs(array $data, $orig = null
, $dest = null
, $fetchProfile = true
)
870 // Fetch the list of uids
871 if (is_null($orig)) {
874 if (is_null($dest)) {
878 foreach ($data as $key=>$entry) {
879 if (isset($entry[$orig])) {
880 $uids[] = $entry[$orig];
886 if (count($uids) == 0) {
889 $users = self
::iterOverUIDs($uids, true
);
893 $profiles = Profile
::iterOverUIDS($uids, true
);
894 if ($profiles != null
) {
895 $profile = $profiles->next();
901 /** We iterate through the users, moving in
902 * profiles when they match the user ID :
903 * there can be users without a profile, but not
904 * the other way around.
906 while (($user = $users->next())) {
908 if ($profile != null
&& $profile->owner_id
== $user->id()) {
909 $user->_profile
= $profile;
910 $profile = $profiles->next();
912 $user->_profile_fetched
= true
;
914 $table[$user->id()] = $user;
917 // Build the result with respect to input order.
918 if (is_null($orig)) {
921 foreach ($data as $key=>$entry) {
922 if (isset($entry[$orig])) {
923 $entry[$dest] = $table[$entry[$orig]];
924 $data[$key] = $entry;
931 public static function getBulkUsersFromDB($fetchProfile = true
)
933 $args = func_get_args();
934 $uids = call_user_func_array(array('XDB', 'fetchColumn'), $args);
935 return self
::getBulkUsersWithUIDs($uids, null
, null
, $fetchProfile);
939 /** Iterator over a set of Users
940 * @param an XDB::Iterator obtained from a User::loadMainFieldsFromUIDs
942 class UserIterator
implements PlIterator
946 public function __construct($dbiter)
948 $this->dbiter
= $dbiter;
951 public function next()
953 $data = $this->dbiter
->next();
957 return User
::getSilentWithValues(null
, $data);
961 public function total()
963 return $this->dbiter
->total();
966 public function first()
968 return $this->dbiter
->first();
971 public function last()
973 return $this->dbiter
->last();
977 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: