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