Retrieves forlifeEmailAlternate from core.
[platal.git] / classes / user.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
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. *
10 * *
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. *
15 * *
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 *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 class User extends PlUser
23 {
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';
33
34 public static $sub_mail_domains = array(
35 'x' => '',
36 'master' => 'master.',
37 'phd' => 'doc.',
38 'all' => 'alumni.'
39 );
40
41 private $_profile_fetched = false;
42 private $_profile = null;
43
44 // Additional fields (non core)
45 protected $promo = null;
46
47 // Implementation of the login to uid method.
48 protected function getLogin($login)
49 {
50 global $globals;
51
52 if (!$login) {
53 throw new UserNotFoundException();
54 }
55
56 if ($login instanceof User) {
57 return $login->id();
58 }
59
60 if ($login instanceof Profile) {
61 $this->_profile = $login;
62 $this->_profile_fetched = true;
63 $res = XDB::query('SELECT ap.uid
64 FROM account_profiles AS ap
65 WHERE ap.pid = {?} AND FIND_IN_SET(\'owner\', perms)',
66 $login->id());
67 if ($res->numRows()) {
68 return $res->fetchOneCell();
69 }
70 throw new UserNotFoundException();
71 }
72
73 // If $data is an integer, fetches directly the result.
74 if (is_numeric($login)) {
75 $res = XDB::query('SELECT uid
76 FROM accounts
77 WHERE uid = {?}', $login);
78 if ($res->numRows()) {
79 return $res->fetchOneCell();
80 }
81
82 throw new UserNotFoundException();
83 }
84
85 // Checks whether $login is a valid hruid or not.
86 $res = XDB::query('SELECT uid
87 FROM accounts
88 WHERE hruid = {?}', $login);
89 if ($res->numRows()) {
90 return $res->fetchOneCell();
91 }
92
93 // From now, $login can only by an email alias, or an email redirection.
94 // If it doesn't look like a valid address, appends the plat/al's main domain.
95 $login = trim(strtolower($login));
96 if (strstr($login, '@') === false) {
97 $email = $login;
98 $domain = $this->mainEmailDomain();
99 } else {
100 list($email, $domain) = explode('@', $login);
101 }
102
103 // Checks if $login is a valid alias on any domain.
104 $res = XDB::fetchOneCell('SELECT s.uid
105 FROM email_source_account AS s
106 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
107 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
108 WHERE s.email = {?} AND d.name = {?}',
109 $email, $domain);
110 if ($res) {
111 return $res;
112 }
113
114 // Looks for an account with the given email.
115 $res = XDB::query('SELECT uid
116 FROM accounts
117 WHERE email = {?}', $login);
118 if ($res->numRows() == 1) {
119 return $res->fetchOneCell();
120 }
121
122 // Otherwise, we do suppose $login is an email redirection.
123 $res = XDB::query('SELECT uid
124 FROM email_redirect_account
125 WHERE redirect = {?}', $login);
126 if ($res->numRows() == 1) {
127 return $res->fetchOneCell();
128 }
129
130 throw new UserNotFoundException($res->fetchColumn(1));
131 }
132
133 protected static function loadMainFieldsFromUIDs(array $uids, $respect_order = true)
134 {
135 if (empty($uids)) {
136 return PlIteratorUtils::emptyIterator();
137 }
138
139 global $globals;
140 $joins = '';
141 $fields = array();
142 if ($globals->asso('id')) {
143 $joins .= XDB::format("LEFT JOIN group_members AS gpm ON (gpm.uid = a.uid AND gpm.asso_id = {?})\n", $globals->asso('id'));
144 $fields[] = 'gpm.perms AS group_perms';
145 $fields[] = 'gpm.comm AS group_comm';
146 $fields[] = 'gpm.position AS group_position';
147 }
148 if (count($fields) > 0) {
149 $fields = ', ' . implode(', ', $fields);
150 } else {
151 $fields = '';
152 }
153
154 if ($respect_order) {
155 $order = 'ORDER BY ' . XDB::formatCustomOrder('a.uid', $uids);
156 } else {
157 $order = '';
158 }
159
160 $uids = array_map(array('XDB', 'escape'), $uids);
161
162 return XDB::iterator('SELECT a.uid, a.hruid, a.registration_date, h.uid IS NOT NULL AS homonym,
163 IF(ef.email IS NULL, NULL, CONCAT(ef.email, \'@\', mf.name)) AS forlife,
164 IF(ef.email IS NULL, NULL, CONCAT(ef.email, \'@\', df.name)) AS forlife_alternate,
165 IF(eb.email IS NULL, NULL, CONCAT(eb.email, \'@\', mb.name)) AS bestalias,
166 (er.redirect IS NULL AND a.state = \'active\') AS lost,
167 a.email, a.full_name, a.directory_name, a.display_name, a.sex = \'female\' AS gender,
168 IF(a.state = \'active\', CONCAT(at.perms, \',\', IF(a.user_perms IS NULL, \'\', a.user_perms)), \'\') AS perms,
169 a.user_perms, a.email_format, a.is_admin, a.state, a.type, at.description AS type_description, a.skin,
170 FIND_IN_SET(\'watch\', a.flags) AS watch, a.comment,
171 a.weak_password IS NOT NULL AS weak_access, g.g_account_name IS NOT NULL AS googleapps,
172 a.token IS NOT NULL AS token_access, a.token, a.last_version,
173 UNIX_TIMESTAMP(s.start) AS lastlogin, s.host, UNIX_TIMESTAMP(fp.last_seen) AS banana_last
174 ' . $fields . '
175 FROM accounts AS a
176 INNER JOIN account_types AS at ON (at.type = a.type)
177 LEFT JOIN email_source_account AS ef ON (ef.uid = a.uid AND ef.type = \'forlife\')
178 LEFT JOIN email_virtual_domains AS mf ON (ef.domain = mf.id)
179 LEFT JOIN email_virtual_domains AS df ON (df.aliasing = mf.id AND
180 df.name LIKE CONCAT(\'%\', {?}) AND df.name NOT LIKE \'alumni.%\')
181 LEFT JOIN email_source_account AS eb ON (eb.uid = a.uid AND eb.flags = \'bestalias\')
182 LEFT JOIN email_virtual_domains AS mb ON (a.best_domain = mb.id)
183 LEFT JOIN email_redirect_account AS er ON (er.uid = a.uid AND er.flags = \'active\' AND er.broken_level < 3
184 AND er.type != \'imap\' AND er.type != \'homonym\')
185 LEFT JOIN homonyms_list AS h ON (h.uid = a.uid)
186 LEFT JOIN gapps_accounts AS g ON (a.uid = g.l_userid AND g.g_status = \'active\')
187 LEFT JOIN log_last_sessions AS ls ON (ls.uid = a.uid)
188 LEFT JOIN log_sessions AS s ON (s.id = ls.id)
189 LEFT JOIN forum_profiles AS fp ON (fp.uid = a.uid)
190 ' . $joins . '
191 WHERE a.uid IN (' . implode(', ', $uids) . ')
192 GROUP BY a.uid
193 ' . $order, $globals->mail->domain2, $globals->mail->domain2);
194 }
195
196 // Implementation of the data loader.
197 protected function loadMainFields()
198 {
199 if ($this->hruid !== null && $this->forlife !== null
200 && $this->bestalias !== null && $this->display_name !== null
201 && $this->full_name !== null && $this->perms !== null
202 && $this->gender !== null && $this->email_format !== null) {
203 return;
204 }
205 $this->fillFromArray(self::loadMainFieldsFromUIDs(array($this->uid))->next());
206 }
207
208 // Specialization of the buildPerms method
209 // This function build 'generic' permissions for the user. It does not take
210 // into account page specific permissions (e.g X.net group permissions)
211 protected function buildPerms()
212 {
213 if (!is_null($this->perm_flags)) {
214 return;
215 }
216 if ($this->perms === null) {
217 $this->loadMainFields();
218 }
219 $this->perm_flags = self::makePerms($this->perms, $this->is_admin);
220 }
221
222 public function setPerms($perms)
223 {
224 $this->perms = $perms;
225 $this->perm_flags = null;
226 }
227
228 // We do not want to store the password in the object.
229 // So, fetch it 'on demand'
230 public function password()
231 {
232 return XDB::fetchOneCell('SELECT a.password
233 FROM accounts AS a
234 WHERE a.uid = {?}', $this->id());
235 }
236
237 public function isActive()
238 {
239 return $this->state == 'active';
240 }
241
242 /** Overload PlUser::promo(): there no promo defined for a user in the current
243 * schema. The promo is a field from the profile.
244 */
245 public function promo()
246 {
247 if (!$this->hasProfile()) {
248 return '';
249 }
250 return $this->profile()->promo();
251 }
252
253 public function category()
254 {
255 $promo = $this->promo();
256 if (!empty($promo)) {
257 return $promo;
258 } else {
259 return $this->type_description;
260 }
261 }
262
263 public function firstName()
264 {
265 if (!$this->hasProfile()) {
266 return $this->displayName();
267 }
268 return $this->profile()->firstName();
269 }
270
271 public function lastName()
272 {
273 if (!$this->hasProfile()) {
274 return '';
275 }
276 return $this->profile()->lastName();
277 }
278
279 public function displayName()
280 {
281 if (!$this->hasProfile()) {
282 return $this->display_name;
283 }
284 return $this->profile()->yourself;
285 }
286
287 public function fullName($with_promo = false)
288 {
289 if (!$this->hasProfile()) {
290 return $this->full_name;
291 }
292 return $this->profile()->fullName($with_promo);
293 }
294
295 public function directoryName()
296 {
297 if (!$this->hasProfile()) {
298 return $this->directory_name;
299 }
300 return $this->profile()->directory_name;
301 }
302
303 /** Return the main profile attached with this account if any.
304 */
305 public function profile($forceFetch = false, $fields = 0x0000, $visibility = null)
306 {
307 if (!$this->_profile_fetched || $forceFetch) {
308 $this->_profile_fetched = true;
309 $this->_profile = Profile::get($this, $fields, $visibility);
310 }
311 return $this->_profile;
312 }
313
314 /** Return true if the user has an associated profile.
315 */
316 public function hasProfile()
317 {
318 return !is_null($this->profile());
319 }
320
321 /** Return true if given a reference to the profile of this user.
322 */
323 public function isMyProfile($other)
324 {
325 if (!$other) {
326 return false;
327 } else if ($other instanceof Profile) {
328 $profile = $this->profile();
329 return $profile && $profile->id() == $other->id();
330 }
331 return false;
332 }
333
334 /** Check if the user can edit to given profile.
335 */
336 public function canEdit(Profile $profile)
337 {
338 if ($this->checkPerms(User::PERM_EDIT_DIRECTORY)) {
339 return true;
340 }
341 return XDB::fetchOneCell('SELECT pid
342 FROM account_profiles
343 WHERE uid = {?} AND pid = {?}',
344 $this->id(), $profile->id());
345 }
346
347 /** Determines main email domain for this user.
348 */
349 public function mainEmailDomain()
350 {
351 if (array_key_exists($this->type, self::$sub_mail_domains)) {
352 return self::$sub_mail_domains[$this->type] . Platal::globals()->mail->domain;
353 }
354 }
355
356 /** Determines alternate email domain for this user.
357 */
358 public function alternateEmailDomain()
359 {
360 if (array_key_exists($this->type, self::$sub_mail_domains)) {
361 return self::$sub_mail_domains[$this->type] . Platal::globals()->mail->domain2;
362 }
363 }
364
365 public function forlifeEmailAlternate()
366 {
367 if (!empty($this->forlife_alternate)) {
368 return $this->forlife_alternate;
369 }
370 return $this->email;
371 }
372
373 /** Fetch existing auxiliary alias.
374 */
375 public function emailAlias()
376 {
377 $aliases = $this->emailAliases();
378 if (count($aliases)) {
379 return $aliases[0];
380 }
381 return null;
382 }
383
384 /** Fetch existing auxiliary aliases.
385 */
386 public function emailAliases()
387 {
388 return XDB::fetchColumn('SELECT CONCAT(s.email, \'@\', d.name)
389 FROM email_source_account AS s
390 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
391 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
392 WHERE s.uid = {?} AND s.type = \'alias_aux\'
393 ORDER BY d.name',
394 $this->id());
395 }
396
397 /** Get all group aliases the user belongs to.
398 */
399 public function emailGroupAliases($domain = null)
400 {
401 if (is_null($domain)) {
402 return XDB::fetchColumn('SELECT CONCAT(v.email, \'@\', dv.name) AS alias
403 FROM email_virtual AS v
404 INNER JOIN email_virtual_domains AS dv ON (v.domain = dv.id)
405 INNER JOIN email_source_account AS s ON (s.uid = {?})
406 INNER JOIN email_virtual_domains AS ms ON (s.domain = ms.id)
407 INNER JOIN email_virtual_domains AS ds ON (ds.aliasing = ms.id)
408 WHERE v.redirect = CONCAT(s.email, \'@\', ds.name) AND v.type = \'alias\'',
409 $this->id());
410 } else {
411 return XDB::fetchAllAssoc('alias',
412 'SELECT CONCAT(v.email, \'@\', dv.name) AS alias, MAX(v.redirect = CONCAT(s.email, \'@\', ds.name)) AS sub
413 FROM email_virtual AS v
414 INNER JOIN email_virtual_domains AS dv ON (v.domain = dv.id AND dv.name = {?})
415 INNER JOIN email_source_account AS s ON (s.uid = {?})
416 INNER JOIN email_virtual_domains AS ms ON (s.domain = ms.id)
417 INNER JOIN email_virtual_domains AS ds ON (ds.aliasing = ms.id)
418 WHERE v.type = \'alias\'
419 GROUP BY v.email
420 ORDER BY v.email',
421 $domain, $this->id());
422 }
423 }
424
425 /** Get marketing informations
426 */
427 private function fetchMarketingData()
428 {
429 if (isset($this->pending_registration_date)) {
430 return;
431 }
432 $infos = XDB::fetchOneAssoc('SELECT rp.date AS pending_registration_date, rp.email AS pending_registration_email,
433 rm.last AS last_marketing_date, rm.email AS last_marketing_email
434 FROM accounts AS a
435 LEFT JOIN register_pending AS rp ON (rp.uid = a.uid)
436 LEFT JOIN register_marketing AS rm ON (rm.uid = a.uid AND rm.last != \'0000-00-00\')
437 WHERE a.uid = {?}
438 ORDER BY rm.last DESC', $this->id());
439 if (is_null($infos)) {
440 $infos = array(
441 'pending_registration_date' => null,
442 'pending_registration_email' => null,
443 'last_marketing_date' => null,
444 'last_marketing_email' => null
445 );
446 }
447 $this->fillFromArray($infos);
448 }
449
450 public function pendingRegistrationDate()
451 {
452 $this->fetchMarketingData();
453 return $this->pending_registration_date;
454 }
455
456 public function pendingRegistrationEmail()
457 {
458 $this->fetchMarketingData();
459 return $this->pending_registration_email;
460 }
461
462 public function lastMarketingDate()
463 {
464 $this->fetchMarketingData();
465 return $this->last_marketing_date;
466 }
467
468 public function lastMarketingEmail()
469 {
470 $this->fetchMarketingData();
471 return $this->last_marketing_email;
472 }
473
474 public function lastKnownEmail()
475 {
476 $this->fetchMarketingData();
477 if ($this->pending_registration_email > $this->last_marketing_date) {
478 return $this->pending_registration_email;
479 }
480 return $this->last_marketing_email;
481 }
482
483
484 /** Format of the emails sent by the site
485 */
486 public function setEmailFormat($format)
487 {
488 Platal::assert($format == self::FORMAT_HTML || $format == self::FORMAT_TEXT,
489 "Invalid email format \"$format\"");
490 XDB::execute("UPDATE accounts
491 SET email_format = {?}
492 WHERE uid = {?}",
493 $format, $this->uid);
494 $this->email_format = $format;
495 }
496
497 /** Get watch informations
498 */
499 private function fetchWatchData()
500 {
501 if (isset($this->watch_actions)) {
502 return;
503 }
504 $watch = XDB::fetchOneAssoc('SELECT flags AS watch_flags, actions AS watch_actions,
505 UNIX_TIMESTAMP(last) AS watch_last
506 FROM watch
507 WHERE uid = {?}', $this->id());
508 $watch['watch_flags'] = new PlFlagSet($watch['watch_flags']);
509 $watch['watch_actions'] = new PlFlagSet($watch['watch_actions']);
510 $watch['watch_promos'] = XDB::fetchColumn('SELECT promo
511 FROM watch_promo
512 WHERE uid = {?}', $this->id());
513 $watch['watch_users'] = XDB::fetchColumn('SELECT ni_id
514 FROM watch_nonins
515 WHERE uid = {?}', $this->id());
516 $this->fillFromArray($watch);
517 }
518
519 public function watchType($type)
520 {
521 $this->fetchWatchData();
522 return $this->watch_actions->hasFlag($type);
523 }
524
525 public function watchContacts()
526 {
527 $this->fetchWatchData();
528 return $this->watch_flags->hasFlag('contacts');
529 }
530
531 public function watchEmail()
532 {
533 $this->fetchWatchData();
534 return $this->watch_flags->hasFlag('mail');
535 }
536
537 public function watchPromos()
538 {
539 $this->fetchWatchData();
540 return $this->watch_promos;
541 }
542
543 public function watchUsers()
544 {
545 $this->fetchWatchData();
546 return $this->watch_users;
547 }
548
549 public function watchLast()
550 {
551 $this->fetchWatchData();
552 return $this->watch_last;
553 }
554
555 public function invalidWatchCache()
556 {
557 unset($this->watch_actions);
558 unset($this->watch_users);
559 unset($this->watch_last);
560 unset($this->watch_promos);
561 }
562
563
564 // Contacts
565 private $contacts = null;
566 private function fetchContacts()
567 {
568 if (is_null($this->contacts)) {
569 $this->contacts = XDB::fetchAllAssoc('contact', 'SELECT *
570 FROM contacts
571 WHERE uid = {?}',
572 $this->id());
573 }
574 }
575
576 public function iterContacts()
577 {
578 $this->fetchContacts();
579 return Profile::iterOverPIDs(array_keys($this->contacts));
580 }
581
582 public function getContacts()
583 {
584 $this->fetchContacts();
585 return Profile::getBulkProfilesWithPIDs(array_keys($this->contacts));
586 }
587
588 public function isContact(Profile $profile)
589 {
590 $this->fetchContacts();
591 return isset($this->contacts[$profile->id()]);
592 }
593
594 public function isWatchedUser(Profile $profile)
595 {
596 return in_array($profile->id(), $this->watchUsers());
597 }
598
599 // Groupes X
600 private $groups = null;
601 public function groups($institutions = false, $onlyPublic = false)
602 {
603 if (is_null($this->groups)) {
604 $this->groups = XDB::fetchAllAssoc('asso_id', 'SELECT gm.asso_id, gm.perms, gm.comm,
605 g.diminutif, g.nom, g.site, g.cat,
606 g.pub
607 FROM group_members AS gm
608 INNER JOIN groups AS g ON (g.id = gm.asso_id)
609 WHERE uid = {?}',
610 $this->id());
611 }
612 if (!$institutions && !$onlyPublic) {
613 return $this->groups;
614 } else {
615 $result = array();
616 foreach ($this->groups as $id=>$data) {
617 if ($institutions) {
618 if ($data['cat'] != Group::CAT_GROUPESX && $data['cat'] != Group::CAT_INSTITUTIONS) {
619 continue;
620 }
621 }
622 if ($onlyPublic) {
623 if ($data['pub'] != 'public') {
624 continue;
625 }
626 }
627 $result[$id] = $data;
628 }
629 return $result;
630 }
631 }
632
633 /**
634 * Clears a user.
635 * *always deletes in: account_lost_passwords, register_marketing,
636 * register_pending, register_subs, watch_nonins, watch, watch_promo
637 * *always keeps in: account_types, accounts, email_virtual, carvas,
638 * group_members, homonyms_list, newsletter_ins, register_mstats, email_source_account
639 * *deletes if $clearAll: account_auth_openid, announce_read, contacts,
640 * email_redirect_account, email_redirect_account, email_send_save, forum_innd, forum_profiles,
641 * forum_subs, gapps_accounts, gapps_nicknames, group_announces_read,
642 * group_member_sub_requests, reminder, requests, requests_hidden,
643 * email_virtual, ML
644 * *modifies if $clearAll: accounts
645 *
646 * Use cases:
647 * *$clearAll == false: when a user dies, her family still needs to keep in
648 * touch with the community.
649 * *$clearAll == true: in every other case we want the account to be fully
650 * deleted so that it can not be used anymore.
651 */
652 public function clear($clearAll = true)
653 {
654 $tables = array('account_lost_passwords', 'register_marketing',
655 'register_pending', 'register_subs', 'watch_nonins',
656 'watch', 'watch_promo');
657
658 foreach ($tables as $t) {
659 XDB::execute('DELETE FROM ' . $t . '
660 WHERE uid = {?}',
661 $this->id());
662 }
663
664 if ($clearAll) {
665 global $globals;
666
667 $groupIds = XDB::iterator('SELECT asso_id
668 FROM group_members
669 WHERE uid = {?}',
670 $this->id());
671 while ($groupId = $groupIds->next()) {
672 $group = Group::get($groupId);
673 if (!empty($group) && $group->notif_unsub) {
674 $mailer = new PlMailer('xnetgrp/unsubscription-notif.mail.tpl');
675 $admins = $group->iterAdmins();
676 while ($admin = $admins->next()) {
677 $mailer->addTo($admin);
678 }
679 $mailer->assign('group', $group->shortname);
680 $mailer->assign('user', $this);
681 $mailer->assign('selfdone', false);
682 $mailer->send();
683 }
684 }
685
686 $tables = array('account_auth_openid', 'announce_read', 'contacts',
687 'email_send_save', 'email_virtual',
688 'forum_innd', 'forum_profiles', 'forum_subs',
689 'group_announces_read', 'group_members',
690 'group_member_sub_requests', 'reminder', 'requests',
691 'requests_hidden');
692 foreach ($tables as $t) {
693 XDB::execute('DELETE FROM ' . $t . '
694 WHERE uid = {?}',
695 $this->id());
696 }
697 XDB::execute('DELETE FROM email_redirect_account
698 WHERE uid = {?} AND type != \'homonym\'',
699 $this->id());
700
701 foreach (array('gapps_accounts', 'gapps_nicknames') as $t) {
702 XDB::execute('DELETE FROM ' . $t . '
703 WHERE l_userid = {?}',
704 $this->id());
705 }
706
707 XDB::execute("UPDATE accounts
708 SET registration_date = 0, state = 'pending', password = NULL,
709 weak_password = NULL, token = NULL, is_admin = 0
710 WHERE uid = {?}",
711 $this->id());
712
713 if ($globals->mailstorage->googleapps_domain) {
714 require_once 'googleapps.inc.php';
715
716 if (GoogleAppsAccount::account_status($this->id())) {
717 $account = new GoogleAppsAccount($this);
718 $account->suspend();
719 }
720 }
721 }
722
723 $mmlist = new MMList(S::user());
724 $mmlist->kill($this->hruid, $clearAll);
725 }
726
727 // Merge all infos in other user and then clean this one
728 public function mergeIn(User $newuser) {
729 if ($this->profile()) {
730 // Don't disable user with profile in this way.
731 global $globals;
732 Platal::page()->trigError('Impossible de fusionner les comptes ' . $this->hruid . ' et ' . $newuser->hruid .
733 '. Contacte support@' . $globals->mail->domain . '.');
734 return false;
735 }
736
737 if ($this->forlifeEmail()) {
738 // If the new user is not registered and does not have already an email address,
739 // we need to give him the old user's email address if he has any.
740 if (!$newuser->perms) {
741 XDB::execute('UPDATE accounts
742 SET email = {?}
743 WHERE uid = {?} AND email IS NULL',
744 $this->forlifeEmail(), $newuser->id());
745
746 // Reftech new user so its forlifeEmail will be correct.
747 $newuser = getSilentWithUID($newuser->id());
748 }
749
750 // Change email used in mailing lists.
751 if ($this->forlifeEmail() != $newuser->forlifeEmail()) {
752 // group mailing lists
753 $group_domains = XDB::fetchColumn('SELECT g.mail_domain
754 FROM groups AS g
755 INNER JOIN group_members AS gm ON(g.id = gm.asso_id)
756 WHERE g.mail_domain != \'\' AND gm.uid = {?}',
757 $this->id());
758 foreach ($group_domains as $mail_domain) {
759 $mmlist = new MMList($this, $mail_domain);
760 $mmlist->replace_email_in_all($this->forlifeEmail(), $newuser->forlifeEmail());
761 }
762 // main domain lists
763 $mmlist = new MMList($this);
764 $mmlist->replace_email_in_all($this->forlifeEmail(), $newuser->forlifeEmail());
765 }
766 }
767
768 // Updates user in following tables.
769 foreach (array('group_announces', 'payment_transactions', 'log_sessions', 'group_events') as $table) {
770 XDB::execute('UPDATE ' . $table . '
771 SET uid = {?}
772 WHERE uid = {?}',
773 $newuser->id(), $this->id());
774 }
775
776 // Merges user in following tables, ie updates when possible, then deletes remaining occurences of the old user.
777 foreach (array('group_announces_read', 'group_event_participants', 'group_member_sub_requests', 'group_members', 'email_redirect_account') as $table) {
778 XDB::execute('UPDATE IGNORE ' . $table . '
779 SET uid = {?}
780 WHERE uid = {?}',
781 $newuser->id(), $this->id());
782 XDB::execute('DELETE FROM ' . $table . '
783 WHERE uid = {?}',
784 $this->id());
785 }
786
787 // Eventually updates last session id and deletes old user's accounts entry.
788 $lastSession = XDB::fetchOneCell('SELECT id
789 FROM log_sessions
790 WHERE uid = {?}
791 ORDER BY start DESC
792 LIMIT 1',
793 $newuser->id());
794 XDB::execute('UPDATE log_last_sessions
795 SET id = {?}
796 WHERE uid = {?}',
797 $lastSession, $newuser->id());
798 XDB::execute('DELETE FROM accounts
799 WHERE uid = {?}',
800 $this->id());
801
802 return true;
803 }
804
805 // Return permission flags for a given permission level.
806 public static function makePerms($perms, $is_admin)
807 {
808 $flags = new PlFlagSet($perms);
809 $flags->addFlag(PERMS_USER);
810 if ($is_admin) {
811 $flags->addFlag(PERMS_ADMIN);
812 }
813
814 // Access to private directory implies access to 'less'-private version.
815 if ($flags->hasFlag('directory_private')) {
816 $flags->addFlag('directory_ax');
817 }
818 return $flags;
819 }
820
821 // Implementation of the default user callback.
822 public static function _default_user_callback($login, $results)
823 {
824 $result_count = count($results);
825 if ($result_count == 0 || !S::admin()) {
826 Platal::page()->trigError("Il n'y a pas d'utilisateur avec l'identifiant : $login");
827 } else {
828 Platal::page()->trigError("Il y a $result_count utilisateurs avec cet identifiant : " . join(', ', $results));
829 }
830 }
831
832 public static function makeHomonymHrmid($alias)
833 {
834 return 'h.' . $alias . '.' . Platal::globals()->mail->domain;
835 }
836
837 public static function isMainMailDomain($domain)
838 {
839 global $globals;
840
841 $is_main_domain = false;
842 foreach (self::$sub_mail_domains as $sub_domain) {
843 $is_main_domain = $is_main_domain || $domain == ($sub_domain . $globals->mail->domain) && $domain == ($sub_domain . $globals->mail->domain2);
844 }
845 return $is_main_domain;
846 }
847
848 public static function isAliasMailDomain($domain)
849 {
850 global $globals;
851
852 return $domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2;
853 }
854
855 // Implementation of the static email locality checker.
856 public static function isForeignEmailAddress($email)
857 {
858 if (strpos($email, '@') === false) {
859 return false;
860 }
861
862 list(, $domain) = explode('@', $email);
863 return !(self::isMainMailDomain($domain) || self::isAliasMailDomain($domain));
864 }
865
866 /* Tries to find pending accounts with an hruid close to $login. */
867 public static function getPendingAccounts($login, $iterator = false)
868 {
869 if (strpos($login, '@') === false) {
870 return null;
871 }
872
873 list($login, $domain) = explode('@', $login);
874
875 if ($domain && !self::isMainMailDomain($domain)) {
876 return null;
877 }
878
879 $sql = "SELECT uid, full_name
880 FROM accounts
881 WHERE state = 'pending' AND REPLACE(hruid, '-', '') LIKE
882 CONCAT('%', REPLACE(REPLACE(REPLACE({?}, ' ', ''), '-', ''), '\'', ''), '%')
883 ORDER BY full_name";
884 if ($iterator) {
885 return XDB::iterator($sql, $login);
886 } else {
887 $res = XDB::query($sql, $login);
888 return $res->fetchAllAssoc();
889 }
890 }
891
892
893 public static function iterOverUIDs($uids, $respect_order = true)
894 {
895 return new UserIterator(self::loadMainFieldsFromUIDs($uids, $respect_order));
896 }
897
898 /** Fetch a set of users from a list of UIDs
899 * @param $data The list of uids to fetch, or an array of arrays
900 * @param $orig If $data is an array of arrays, the subfield where uids are stored
901 * @param $dest If $data is an array of arrays, the subfield to fill with Users
902 * @param $fetchProfile Whether to fetch Profiles as well
903 * @return either an array of $uid => User, or $data with $data[$i][$dest] = User
904 */
905 public static function getBulkUsersWithUIDs(array $data, $orig = null, $dest = null, $fetchProfile = true)
906 {
907 // Fetch the list of uids
908 if (is_null($orig)) {
909 $uids = $data;
910 } else {
911 if (is_null($dest)) {
912 $dest = $orig;
913 }
914 $uids = array();
915 foreach ($data as $key=>$entry) {
916 if (isset($entry[$orig])) {
917 $uids[] = $entry[$orig];
918 }
919 }
920 }
921
922 // Fetch users
923 if (count($uids) == 0) {
924 return $data;
925 }
926 $users = self::iterOverUIDs($uids, true);
927
928 $table = array();
929 if ($fetchProfile) {
930 $profiles = Profile::iterOverUIDS($uids, true);
931 if ($profiles != null) {
932 $profile = $profiles->next();
933 } else {
934 $profile = null;
935 }
936 }
937
938 /** We iterate through the users, moving in
939 * profiles when they match the user ID :
940 * there can be users without a profile, but not
941 * the other way around.
942 */
943 while (($user = $users->next())) {
944 if ($fetchProfile) {
945 if ($profile != null && $profile->owner_id == $user->id()) {
946 $user->_profile = $profile;
947 $profile = $profiles->next();
948 }
949 $user->_profile_fetched = true;
950 }
951 $table[$user->id()] = $user;
952 }
953
954 // Build the result with respect to input order.
955 if (is_null($orig)) {
956 return $table;
957 } else {
958 foreach ($data as $key=>$entry) {
959 if (isset($entry[$orig])) {
960 $entry[$dest] = $table[$entry[$orig]];
961 $data[$key] = $entry;
962 }
963 }
964 return $data;
965 }
966 }
967
968 public static function getBulkUsersFromDB($fetchProfile = true)
969 {
970 $args = func_get_args();
971 $uids = call_user_func_array(array('XDB', 'fetchColumn'), $args);
972 return self::getBulkUsersWithUIDs($uids, null, null, $fetchProfile);
973 }
974 }
975
976 /** Iterator over a set of Users
977 * @param an XDB::Iterator obtained from a User::loadMainFieldsFromUIDs
978 */
979 class UserIterator implements PlIterator
980 {
981 private $dbiter;
982
983 public function __construct($dbiter)
984 {
985 $this->dbiter = $dbiter;
986 }
987
988 public function next()
989 {
990 $data = $this->dbiter->next();
991 if ($data == null) {
992 return null;
993 } else {
994 return User::getSilentWithValues(null, $data);
995 }
996 }
997
998 public function total()
999 {
1000 return $this->dbiter->total();
1001 }
1002
1003 public function first()
1004 {
1005 return $this->dbiter->first();
1006 }
1007
1008 public function last()
1009 {
1010 return $this->dbiter->last();
1011 }
1012 }
1013
1014 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1015 ?>