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 a.uid
70 WHERE a.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 a.uid
81 WHERE a.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
) {
90 $login = $login . '@' . $globals->mail
->domain
;
93 // Checks if $login is a valid alias on the main domains.
94 list($mbox, $fqdn) = explode('@', $login);
95 if ($fqdn == $globals->mail
->domain ||
$fqdn == $globals->mail
->domain2
) {
96 $res = XDB
::query('SELECT a.uid
98 INNER JOIN aliases AS al ON (al.uid = a.uid AND al.type IN (\'alias\', \'a_vie\'))
99 WHERE al.alias = {?}', $mbox);
100 if ($res->numRows()) {
101 return $res->fetchOneCell();
104 if (preg_match('/^(.*)\.([0-9]{4})$/u', $mbox, $matches)) {
105 $res = XDB
::query('SELECT a.uid
107 INNER JOIN aliases AS al ON (al.uid = a.uid AND al.type IN (\'alias\', \'a_vie\'))
108 INNER JOIN account_profiles AS ap ON (a.uid = ap.uid AND FIND_IN_SET(\'owner\', ap.perms))
109 INNER JOIN profiles AS p ON (p.pid = ap.pid)
110 INNER JOIN profile_education AS pe ON (p.pid = pe.pid AND FIND_IN_SET(\'primary\', pe.flags))
111 WHERE p.hrpid = {?} OR ((pe.entry_year <= {?} AND pe.grad_year >= {?}) AND al.alias = {?})
113 $matches[0], $matches[2], $matches[2], $matches[1]);
114 if ($res->numRows() == 1) {
115 return $res->fetchOneCell();
119 throw new UserNotFoundException();
122 // Looks for $login as an email alias from the dedicated alias domain.
123 if ($fqdn == $globals->mail
->alias_dom ||
$fqdn == $globals->mail
->alias_dom2
) {
124 $res = XDB
::query("SELECT redirect
125 FROM virtual_redirect
126 INNER JOIN virtual USING(vid)
127 WHERE alias = {?}", $mbox . '@' . $globals->mail
->alias_dom
);
128 if ($redir = $res->fetchOneCell()) {
129 // We now have a valid alias, which has to be translated to an hruid.
130 list($alias, $alias_fqdn) = explode('@', $redir);
131 $res = XDB
::query("SELECT a.uid
133 LEFT JOIN aliases AS al ON (al.uid = a.uid AND al.type IN ('alias', 'a_vie'))
134 WHERE al.alias = {?}", $alias);
135 if ($res->numRows()) {
136 return $res->fetchOneCell();
140 throw new UserNotFoundException();
143 // Looks for an account with the given email.
144 $res = XDB
::query('SELECT a.uid
146 WHERE a.email = {?}', $login);
147 if ($res->numRows() == 1) {
148 return $res->fetchOneCell();
151 // Otherwise, we do suppose $login is an email redirection.
152 $res = XDB
::query("SELECT a.uid
154 LEFT JOIN emails AS e ON (e.uid = a.uid)
155 WHERE e.email = {?}", $login);
156 if ($res->numRows() == 1) {
157 return $res->fetchOneCell();
160 throw new UserNotFoundException($res->fetchColumn(1));
163 protected static function loadMainFieldsFromUIDs(array $uids, $respect_order = true
)
166 return PlIteratorUtils
::emptyIterator();
172 if ($globals->asso('id')) {
173 $joins .= XDB
::format("LEFT JOIN group_members AS gpm ON (gpm.uid = a.uid AND gpm.asso_id = {?})\n", $globals->asso('id'));
174 $fields[] = 'gpm.perms AS group_perms';
175 $fields[] = 'gpm.comm AS group_comm';
176 $fields[] = 'gpm.position AS group_position';
178 if (count($fields) > 0) {
179 $fields = ', ' . implode(', ', $fields);
184 if ($respect_order) {
185 $order = 'ORDER BY ' . XDB
::formatCustomOrder('a.uid', $uids);
190 $uids = array_map(array('XDB', 'escape'), $uids);
192 return XDB
::iterator('SELECT a.uid, a.hruid, a.registration_date, ah.alias AS homonym,
193 IF (af.alias IS NULL, NULL, CONCAT(af.alias, \'@' . $globals->mail
->domain
. '\')) AS forlife,
194 IF (af.alias IS NULL, NULL, CONCAT(af.alias, \'@' . $globals->mail
->domain2
. '\')) AS forlife_alternate,
195 IF (ab.alias IS NULL, NULL, CONCAT(ab.alias, \'@' . $globals->mail
->domain
. '\')) AS bestalias,
196 IF (ab.alias IS NULL, NULL, CONCAT(ab.alias, \'@' . $globals->mail
->domain2
. '\')) AS bestalias_alternate,
197 a.email, a.full_name, a.directory_name, a.display_name, a.sex = \'female\' AS gender,
198 IF(a.state = \'active\', CONCAT(at.perms, \',\', IF(a.user_perms IS NULL, \'\', a.user_perms)), \'\') AS perms,
199 a.user_perms, a.email_format, a.is_admin, a.state, a.type, at.description AS type_description, a.skin,
200 FIND_IN_SET(\'watch\', a.flags) AS watch, a.comment,
201 a.weak_password IS NOT NULL AS weak_access, g.g_account_name IS NOT NULL AS googleapps,
202 a.token IS NOT NULL AS token_access, a.token, a.last_version,
203 (e.email IS NULL AND NOT FIND_IN_SET(\'googleapps\', eo.storage)) AND a.state != \'pending\' AS lost,
204 UNIX_TIMESTAMP(s.start) AS lastlogin, s.host, UNIX_TIMESTAMP(fp.last_seen) AS banana_last
207 INNER JOIN account_types AS at ON (at.type = a.type)
208 LEFT JOIN aliases AS af ON (af.uid = a.uid AND af.type = \'a_vie\')
209 LEFT JOIN aliases AS ab ON (ab.uid = a.uid AND FIND_IN_SET(\'bestalias\', ab.flags))
210 LEFT JOIN aliases AS ah ON (ah.uid = a.uid AND ah.type = \'homonyme\')
211 LEFT JOIN emails AS e ON (e.uid = a.uid AND e.flags = \'active\')
212 LEFT JOIN email_options AS eo ON (eo.uid = a.uid)
213 LEFT JOIN gapps_accounts AS g ON (a.uid = g.l_userid AND g.g_status = \'active\')
214 LEFT JOIN log_last_sessions AS ls ON (ls.uid = a.uid)
215 LEFT JOIN log_sessions AS s ON (s.id = ls.id)
216 LEFT JOIN forum_profiles AS fp ON (fp.uid = a.uid)
218 WHERE a.uid IN (' . implode(', ', $uids) . ')
223 // Implementation of the data loader.
224 protected function loadMainFields()
226 if ($this->hruid
!== null
&& $this->forlife
!== null
227 && $this->bestalias
!== null
&& $this->display_name
!== null
228 && $this->full_name
!== null
&& $this->perms
!== null
229 && $this->gender
!== null
&& $this->email_format
!== null
) {
232 $this->fillFromArray(self
::loadMainFieldsFromUIDs(array($this->uid
))->next());
235 // Specialization of the buildPerms method
236 // This function build 'generic' permissions for the user. It does not take
237 // into account page specific permissions (e.g X.net group permissions)
238 protected function buildPerms()
240 if (!is_null($this->perm_flags
)) {
243 if ($this->perms
=== null
) {
244 $this->loadMainFields();
246 $this->perm_flags
= self
::makePerms($this->perms
, $this->is_admin
);
249 public function setPerms($perms)
251 $this->perms
= $perms;
252 $this->perm_flags
= null
;
255 // We do not want to store the password in the object.
256 // So, fetch it 'on demand'
257 public function password()
259 return XDB
::fetchOneCell('SELECT a.password
261 WHERE a.uid = {?}', $this->id());
264 public function isActive()
266 return $this->state
== 'active';
269 /** Overload PlUser::promo(): there no promo defined for a user in the current
270 * schema. The promo is a field from the profile.
272 public function promo()
274 if (!$this->hasProfile()) {
277 return $this->profile()->promo();
280 public function category()
282 $promo = $this->promo();
283 if (!empty($promo)) {
286 return $this->type_description
;
290 public function firstName()
292 if (!$this->hasProfile()) {
293 return $this->displayName();
295 return $this->profile()->firstName();
298 public function lastName()
300 if (!$this->hasProfile()) {
303 return $this->profile()->lastName();
306 public function displayName()
308 if (!$this->hasProfile()) {
309 return $this->display_name
;
311 return $this->profile()->yourself
;
314 public function fullName($with_promo = false
)
316 if (!$this->hasProfile()) {
317 return $this->full_name
;
319 return $this->profile()->fullName($with_promo);
322 public function directoryName()
324 if (!$this->hasProfile()) {
325 return $this->directory_name
;
327 return $this->profile()->directory_name
;
330 /** Return the main profile attached with this account if any.
332 public function profile($forceFetch = false
, $fields = 0x0000, $visibility = null
)
334 if (!$this->_profile_fetched ||
$forceFetch) {
335 $this->_profile_fetched
= true
;
336 $this->_profile
= Profile
::get($this, $fields, $visibility);
338 return $this->_profile
;
341 /** Return true if the user has an associated profile.
343 public function hasProfile()
345 return !is_null($this->profile());
348 /** Return true if given a reference to the profile of this user.
350 public function isMyProfile($other)
354 } else if ($other instanceof Profile
) {
355 $profile = $this->profile();
356 return $profile && $profile->id() == $other->id();
361 /** Check if the user can edit to given profile.
363 public function canEdit(Profile
$profile)
365 if ($this->checkPerms(User
::PERM_EDIT_DIRECTORY
)) {
368 return XDB
::fetchOneCell('SELECT pid
369 FROM account_profiles
370 WHERE uid = {?} AND pid = {?}',
371 $this->id(), $profile->id());
374 /** Get the email alias of the user.
376 public function emailAlias()
379 $data = $this->emailAliases($globals->mail
->alias_dom
);
380 if (count($data) > 0) {
381 return array_pop($data);
386 /** Get all the aliases the user belongs to.
388 public function emailAliases($domain = null
, $type = 'user', $sub_state = false
)
390 $join = XDB
::format('(vr.redirect = {?} OR vr.redirect = {?}) ',
391 $this->forlifeEmail(), $this->m4xForlifeEmail());
393 if (!is_null($domain)) {
394 $where = XDB
::format('WHERE v.alias LIKE CONCAT("%@", {?})', $domain);
396 if (!is_null($type)) {
398 $where = XDB
::format('WHERE v.type = {?}', $type);
400 $where .= XDB
::format(' AND v.type = {?}', $type);
404 return XDB
::fetchAllAssoc('alias', 'SELECT v.alias, vr.redirect IS NOT NULL AS sub
406 LEFT JOIN virtual_redirect AS vr ON (v.vid = vr.vid AND ' . $join . ')
409 return XDB
::fetchColumn('SELECT v.alias
411 INNER JOIN virtual_redirect AS vr ON (v.vid = vr.vid AND ' . $join . ')
416 /** Get the alternative forlife email
417 * TODO: remove this uber-ugly hack. The issue is that you need to remove
418 * all @m4x.org addresses in virtual_redirect first.
419 * XXX: This is juste to make code more readable, to be remove as soon as possible
421 public function m4xForlifeEmail()
424 trigger_error('USING M4X FORLIFE', E_USER_NOTICE
);
425 return $this->login() . '@' . $globals->mail
->domain2
;
429 /** Get marketing informations
431 private function fetchMarketingData()
433 if (isset($this->pending_registration_date
)) {
436 $infos = XDB
::fetchOneAssoc('SELECT rp.date AS pending_registration_date, rp.email AS pending_registration_email,
437 rm.last AS last_marketing_date, rm.email AS last_marketing_email
439 LEFT JOIN register_pending AS rp ON (rp.uid = a.uid)
440 LEFT JOIN register_marketing AS rm ON (rm.uid = a.uid AND rm.last != \'0000-00-00\')
442 ORDER BY rm.last DESC', $this->id());
443 if (is_null($infos)) {
445 'pending_registration_date' => null
,
446 'pending_registration_email' => null
,
447 'last_marketing_date' => null
,
448 'last_marketing_email' => null
451 $this->fillFromArray($infos);
454 public function pendingRegistrationDate()
456 $this->fetchMarketingData();
457 return $this->pending_registration_date
;
460 public function pendingRegistrationEmail()
462 $this->fetchMarketingData();
463 return $this->pending_registration_email
;
466 public function lastMarketingDate()
468 $this->fetchMarketingData();
469 return $this->last_marketing_date
;
472 public function lastMarketingEmail()
474 $this->fetchMarketingData();
475 return $this->last_marketing_email
;
478 public function lastKnownEmail()
480 $this->fetchMarketingData();
481 if ($this->pending_registration_email
> $this->last_marketing_date
) {
482 return $this->pending_registration_email
;
484 return $this->last_marketing_email
;
488 /** Format of the emails sent by the site
490 public function setEmailFormat($format)
492 Platal
::assert($format == self
::FORMAT_HTML ||
$format == self
::FORMAT_TEXT
,
493 "Invalid email format \"$format\"");
494 XDB
::execute("UPDATE accounts
495 SET email_format = {?}
497 $format, $this->uid
);
498 $this->email_format
= $format;
501 /** Get watch informations
503 private function fetchWatchData()
505 if (isset($this->watch_actions
)) {
508 $watch = XDB
::fetchOneAssoc('SELECT flags AS watch_flags, actions AS watch_actions,
509 UNIX_TIMESTAMP(last) AS watch_last
511 WHERE uid = {?}', $this->id());
512 $watch['watch_flags'] = new PlFlagSet($watch['watch_flags']);
513 $watch['watch_actions'] = new PlFlagSet($watch['watch_actions']);
514 $watch['watch_promos'] = XDB
::fetchColumn('SELECT promo
516 WHERE uid = {?}', $this->id());
517 $watch['watch_users'] = XDB
::fetchColumn('SELECT ni_id
519 WHERE uid = {?}', $this->id());
520 $this->fillFromArray($watch);
523 public function watchType($type)
525 $this->fetchWatchData();
526 return $this->watch_actions
->hasFlag($type);
529 public function watchContacts()
531 $this->fetchWatchData();
532 return $this->watch_flags
->hasFlag('contacts');
535 public function watchEmail()
537 $this->fetchWatchData();
538 return $this->watch_flags
->hasFlag('mail');
541 public function watchPromos()
543 $this->fetchWatchData();
544 return $this->watch_promos
;
547 public function watchUsers()
549 $this->fetchWatchData();
550 return $this->watch_users
;
553 public function watchLast()
555 $this->fetchWatchData();
556 return $this->watch_last
;
559 public function invalidWatchCache()
561 unset($this->watch_actions
);
562 unset($this->watch_users
);
563 unset($this->watch_last
);
564 unset($this->watch_promos
);
569 private $contacts = null
;
570 private function fetchContacts()
572 if (is_null($this->contacts
)) {
573 $this->contacts
= XDB
::fetchAllAssoc('contact', 'SELECT *
580 public function iterContacts()
582 $this->fetchContacts();
583 return Profile
::iterOverPIDs(array_keys($this->contacts
));
586 public function getContacts()
588 $this->fetchContacts();
589 return Profile
::getBulkProfilesWithPIDs(array_keys($this->contacts
));
592 public function isContact(Profile
&$profile)
594 $this->fetchContacts();
595 return isset($this->contacts
[$profile->id()]);
598 public function isWatchedUser(Profile
&$profile)
600 return in_array($profile->id(), $this->watchUsers());
604 private $groups = null
;
605 public function groups($institutions = false
, $onlyPublic = false
)
607 if (is_null($this->groups
)) {
608 $this->groups
= XDB
::fetchAllAssoc('asso_id', 'SELECT gm.asso_id, gm.perms, gm.comm,
609 g.diminutif, g.nom, g.site, g.cat,
611 FROM group_members AS gm
612 INNER JOIN groups AS g ON (g.id = gm.asso_id)
616 if (!$institutions && !$onlyPublic) {
617 return $this->groups
;
620 foreach ($this->groups
as $id=>$data) {
622 if ($data['cat'] != Group
::CAT_GROUPESX
&& $data['cat'] != Group
::CAT_INSTITUTIONS
) {
627 if ($data['pub'] != 'public') {
631 $result[$id] = $data;
637 public function groupCount()
639 return XDB
::fetchOneCell('SELECT COUNT(DISTINCT(asso_id))
645 public function inGroup($asso_id)
647 $res = XDB
::fetchOneCell('SELECT COUNT(*)
649 WHERE uid = {?} AND asso_id = {?}',
650 $this->id(), $asso_id);
656 * *always deletes in: account_lost_passwords, register_marketing,
657 * register_pending, register_subs, watch_nonins, watch, watch_promo
658 * *always keeps in: account_types, accounts, aliases, axletter_ins, carvas,
659 * group_members, homonyms, newsletter_ins, register_mstats,
660 * *deletes if $clearAll: account_auth_openid, announce_read, contacts,
661 * email_options, email_send_save, emails, forum_innd, forum_profiles,
662 * forum_subs, gapps_accounts, gapps_nicknames, group_announces_read,
663 * group_member_sub_requests, reminder, requests, requests_hidden,
664 * virtual, virtual_redirect, ML
665 * *modifies if $clearAll: accounts
668 * *$clearAll == false: when a user dies, her family still needs to keep in
669 * touch with the community.
670 * *$clearAll == true: in every other case we want the account to be fully
671 * deleted so that it can not be used anymore.
673 public function clear($clearAll = true
)
675 $tables = array('account_lost_passwords', 'register_marketing',
676 'register_pending', 'register_subs', 'watch_nonins',
677 'watch', 'watch_promo');
679 foreach ($tables as $t) {
680 XDB
::execute('DELETE FROM ' . $t . '
688 $groupIds = XDB
::iterator('SELECT asso_id
692 while ($groupId = $groupIds->next()) {
693 $group = Group
::get($groupId);
694 if (!empty($group) && $group->notif_unsub
) {
695 $mailer = new PlMailer('xnetgrp/unsubscription-notif.mail.tpl');
696 $admins = $group->iterAdmins();
697 while ($admin = $admins->next()) {
698 $mailer->addTo($admin);
700 $mailer->assign('group', $group->shortname
);
701 $mailer->assign('user', $this);
702 $mailer->assign('selfdone', false
);
707 $tables = array('account_auth_openid', 'announce_read', 'contacts',
708 'email_options', 'email_send_save', 'emails',
709 'forum_innd', 'forum_profiles', 'forum_subs',
710 'group_announces_read', 'group_members',
711 'group_member_sub_requests', 'reminder', 'requests',
712 'requests_hidden', 'aliases');
713 foreach ($tables as $t) {
714 XDB
::execute('DELETE FROM ' . $t . '
719 foreach (array('gapps_accounts', 'gapps_nicknames') as $t) {
720 XDB
::execute('DELETE FROM ' . $t . '
721 WHERE l_userid = {?}',
725 XDB
::execute("UPDATE accounts
726 SET registration_date = 0, state = 'pending', password = NULL,
727 weak_password = NULL, token = NULL, is_admin = 0
731 XDB
::execute('DELETE v.*
733 INNER JOIN virtual_redirect AS r ON (v.vid = r.vid)
734 WHERE redirect = {?} OR redirect = {?}',
735 $this->forlifeEmail(), $this->m4xForlifeEmail());
736 XDB
::execute('DELETE FROM virtual_redirect
737 WHERE redirect = {?} OR redirect = {?}',
738 $this->forlifeEmail(), $this->m4xForlifeEmail());
740 if ($globals->mailstorage
->googleapps_domain
) {
741 require_once 'googleapps.inc.php';
743 if (GoogleAppsAccount
::account_status($this->id())) {
744 $account = new GoogleAppsAccount($this);
750 $mmlist = new MMList(S
::user());
751 $mmlist->kill($this->hruid
, $clearAll);
754 // Merge all infos in other user and then clean this one
755 public function mergeIn(User
&$newuser) {
756 if ($this->profile()) {
757 // Don't disable user with profile in this way.
759 Platal
::page()->trigError('Impossible de fusionner les comptes ' . $this->hruid
. ' et ' . $newuser->hruid
.
760 '. Contacte support@' . $globals->mail
->domain
. '.');
764 if ($this->forlifeEmail()) {
765 // If the new user is not registered and does not have already an email address,
766 // we need to give him the old user's email address if he has any.
767 if (!$newuser->perms
) {
768 XDB
::execute('UPDATE accounts
770 WHERE uid = {?} AND email IS NULL',
771 $this->forlifeEmail(), $newuser->id());
773 $newemail = XDB
::fetchOneCell('SELECT email
778 // Change email used in aliases and mailing lists.
779 if ($this->forlifeEmail() != $newemail) {
780 // virtual_redirect (email aliases)
781 XDB
::execute('DELETE v1
782 FROM virtual_redirect AS v1, virtual_redirect AS v2
783 WHERE v1.vid = v2.vid AND v1.redirect = {?} AND v2.redirect = {?}',
784 $this->forlifeEmail(), $newemail);
785 XDB
::execute('UPDATE virtual_redirect
787 WHERE redirect = {?}',
788 $newemail, $this->forlifeEmail());
790 // group mailing lists
791 $group_domains = XDB
::fetchColumn('SELECT g.mail_domain
793 INNER JOIN group_members AS gm ON(g.id = gm.asso_id)
794 WHERE g.mail_domain != \'\' AND gm.uid = {?}',
796 foreach ($group_domains as $mail_domain) {
797 $mmlist = new MMList($this, $mail_domain);
798 $mmlist->replace_email_in_all($this->forlifeEmail(), $newemail);
801 $mmlist = new MMList($this);
802 $mmlist->replace_email_in_all($this->forlifeEmail(), $newemail);
806 // Updates user in following tables.
807 foreach (array('group_announces', 'payment_transactions', 'log_sessions', 'group_events') as $table) {
808 XDB
::execute('UPDATE ' . $table . '
811 $newuser->id(), $this->id());
814 // Merges user in following tables, ie updates when possible, then deletes remaining occurences of the old user.
815 foreach (array('group_announces_read', 'group_event_participants', 'group_member_sub_requests', 'group_members') as $table) {
816 XDB
::execute('UPDATE IGNORE ' . $table . '
819 $newuser->id(), $this->id());
820 XDB
::execute('DELETE FROM ' . $table . '
825 // Eventually updates last session id and deletes old user's accounts entry.
826 $lastSession = XDB
::fetchOneCell('SELECT id
832 XDB
::execute('UPDATE log_last_sessions
835 $lastSession, $newuser->id());
836 XDB
::execute('DELETE FROM accounts
843 // Return permission flags for a given permission level.
844 public static function makePerms($perms, $is_admin)
846 $flags = new PlFlagSet($perms);
847 $flags->addFlag(PERMS_USER
);
849 $flags->addFlag(PERMS_ADMIN
);
852 // Access to private directory implies access to 'less'-private version.
853 if ($flags->hasFlag('directory_private')) {
854 $flags->addFlag('directory_ax');
859 // Implementation of the default user callback.
860 public static function _default_user_callback($login, $results)
862 $result_count = count($results);
863 if ($result_count == 0 ||
!S
::admin()) {
864 Platal
::page()->trigError("Il n'y a pas d'utilisateur avec l'identifiant : $login");
866 Platal
::page()->trigError("Il y a $result_count utilisateurs avec cet identifiant : " . join(', ', $results));
870 // Implementation of the static email locality checker.
871 public static function isForeignEmailAddress($email)
874 if (strpos($email, '@') === false
) {
878 list($user, $dom) = explode('@', $email);
879 return $dom != $globals->mail
->domain
&&
880 $dom != $globals->mail
->domain2
&&
881 $dom != $globals->mail
->alias_dom
&&
882 $dom != $globals->mail
->alias_dom2
;
885 public static function isVirtualEmailAddress($email)
888 if (strpos($email, '@') === false
) {
892 list($user, $dom) = explode('@', $email);
893 return $dom == $globals->mail
->alias_dom
894 ||
$dom == $globals->mail
->alias_dom2
;
897 /* Tries to find pending accounts with an hruid close to $login. */
898 public static function getPendingAccounts($login, $iterator = false
)
902 if (strpos($login, '@') === false
) {
906 list($login, $domain) = explode('@', $login);
908 if ($domain && $domain != $globals->mail
->domain
&& $domain != $globals->mail
->domain2
) {
912 $sql = "SELECT uid, full_name
914 WHERE state = 'pending' AND REPLACE(hruid, '-', '') LIKE
915 CONCAT('%', REPLACE(REPLACE(REPLACE({?}, ' ', ''), '-', ''), '\'', ''), '%')
918 return XDB
::iterator($sql, $login);
920 $res = XDB
::query($sql, $login);
921 return $res->fetchAllAssoc();
926 public static function iterOverUIDs($uids, $respect_order = true
)
928 return new UserIterator(self
::loadMainFieldsFromUIDs($uids, $respect_order));
931 /** Fetch a set of users from a list of UIDs
932 * @param $data The list of uids to fetch, or an array of arrays
933 * @param $orig If $data is an array of arrays, the subfield where uids are stored
934 * @param $dest If $data is an array of arrays, the subfield to fill with Users
935 * @param $fetchProfile Whether to fetch Profiles as well
936 * @return either an array of $uid => User, or $data with $data[$i][$dest] = User
938 public static function getBulkUsersWithUIDs(array $data, $orig = null
, $dest = null
, $fetchProfile = true
)
940 // Fetch the list of uids
941 if (is_null($orig)) {
944 if (is_null($dest)) {
948 foreach ($data as $key=>$entry) {
949 if (isset($entry[$orig])) {
950 $uids[] = $entry[$orig];
956 if (count($uids) == 0) {
959 $users = self
::iterOverUIDs($uids, true
);
963 $profiles = Profile
::iterOverUIDS($uids, true
);
964 if ($profiles != null
) {
965 $profile = $profiles->next();
971 /** We iterate through the users, moving in
972 * profiles when they match the user ID :
973 * there can be users without a profile, but not
974 * the other way around.
976 while (($user = $users->next())) {
978 if ($profile != null
&& $profile->owner_id
== $user->id()) {
979 $user->_profile
= $profile;
980 $profile = $profiles->next();
982 $user->_profile_fetched
= true
;
984 $table[$user->id()] = $user;
987 // Build the result with respect to input order.
988 if (is_null($orig)) {
991 foreach ($data as $key=>$entry) {
992 if (isset($entry[$orig])) {
993 $entry[$dest] = $table[$entry[$orig]];
994 $data[$key] = $entry;
1001 public static function getBulkUsersFromDB($fetchProfile = true
)
1003 $args = func_get_args();
1004 $uids = call_user_func_array(array('XDB', 'fetchColumn'), $args);
1005 return self
::getBulkUsersWithUIDs($uids, null
, null
, $fetchProfile);
1009 /** Iterator over a set of Users
1010 * @param an XDB::Iterator obtained from a User::loadMainFieldsFromUIDs
1012 class UserIterator
implements PlIterator
1016 public function __construct($dbiter)
1018 $this->dbiter
= $dbiter;
1021 public function next()
1023 $data = $this->dbiter
->next();
1024 if ($data == null
) {
1027 return User
::getSilentWithValues(null
, $data);
1031 public function total()
1033 return $this->dbiter
->total();
1036 public function first()
1038 return $this->dbiter
->first();
1041 public function last()
1043 return $this->dbiter
->last();
1047 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: