Merge remote branch 'origin/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, 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 firstName()
273 {
274 if (!$this->hasProfile()) {
275 return $this->displayName();
276 }
277 return $this->profile()->firstName();
278 }
279
280 public function lastName()
281 {
282 if (!$this->hasProfile()) {
283 return '';
284 }
285 return $this->profile()->lastName();
286 }
287
288 public function displayName()
289 {
290 if (!$this->hasProfile()) {
291 return $this->display_name;
292 }
293 return $this->profile()->yourself;
294 }
295
296 public function fullName($with_promo = false)
297 {
298 if (!$this->hasProfile()) {
299 return $this->full_name;
300 }
301 return $this->profile()->fullName($with_promo);
302 }
303
304 public function directoryName()
305 {
306 if (!$this->hasProfile()) {
307 return $this->directory_name;
308 }
309 return $this->profile()->directory_name;
310 }
311
312 /** Return the main profile attached with this account if any.
313 */
314 public function profile($forceFetch = false)
315 {
316 if (!$this->_profile_fetched || $forceFetch) {
317 $this->_profile_fetched = true;
318 $this->_profile = Profile::get($this);
319 }
320 return $this->_profile;
321 }
322
323 /** Return true if the user has an associated profile.
324 */
325 public function hasProfile()
326 {
327 return !is_null($this->profile());
328 }
329
330 /** Check if the user can edit to given profile.
331 */
332 public function canEdit(Profile $profile)
333 {
334 if ($this->checkPerms(User::PERM_EDIT_DIRECTORY)) {
335 return true;
336 }
337 return XDB::fetchOneCell('SELECT pid
338 FROM account_profiles
339 WHERE uid = {?} AND pid = {?}',
340 $this->id(), $profile->id());
341 }
342
343 /** Get the email alias of the user.
344 */
345 public function emailAlias()
346 {
347 global $globals;
348 $data = $this->emailAliases($globals->mail->alias_dom);
349 if (count($data) > 0) {
350 return array_pop($data);
351 }
352 return null;
353 }
354
355 /** Get all the aliases the user belongs to.
356 */
357 public function emailAliases($domain = null, $type = 'user', $sub_state = false)
358 {
359 $join = XDB::format('(vr.redirect = {?} OR vr.redirect = {?}) ',
360 $this->forlifeEmail(), $this->m4xForlifeEmail());
361 $where = '';
362 if (!is_null($domain)) {
363 $where = XDB::format('WHERE v.alias LIKE CONCAT("%@", {?})', $domain);
364 }
365 if (!is_null($type)) {
366 if (empty($where)) {
367 $where = XDB::format('WHERE v.type = {?}', $type);
368 } else {
369 $where .= XDB::format(' AND v.type = {?}', $type);
370 }
371 }
372 if ($sub_state) {
373 return XDB::fetchAllAssoc('alias', 'SELECT v.alias, vr.redirect IS NOT NULL AS sub
374 FROM virtual AS v
375 LEFT JOIN virtual_redirect AS vr ON (v.vid = vr.vid AND ' . $join . ')
376 ' . $where);
377 } else {
378 return XDB::fetchColumn('SELECT v.alias
379 FROM virtual AS v
380 INNER JOIN virtual_redirect AS vr ON (v.vid = vr.vid AND ' . $join . ')
381 ' . $where);
382 }
383 }
384
385 /** Get the alternative forlife email
386 * TODO: remove this uber-ugly hack. The issue is that you need to remove
387 * all @m4x.org addresses in virtual_redirect first.
388 * XXX: This is juste to make code more readable, to be remove as soon as possible
389 */
390 public function m4xForlifeEmail()
391 {
392 global $globals;
393 trigger_error('USING M4X FORLIFE', E_USER_NOTICE);
394 return $this->login() . '@' . $globals->mail->domain2;
395 }
396
397
398 /** Get marketing informations
399 */
400 private function fetchMarketingData()
401 {
402 if (isset($this->pending_registration_date)) {
403 return;
404 }
405 $infos = XDB::fetchOneAssoc('SELECT rp.date AS pending_registration_date, rp.email AS pending_registration_email,
406 rm.last AS last_marketing_date, rm.email AS last_marketing_email
407 FROM accounts AS a
408 LEFT JOIN register_pending AS rp ON (rp.uid = a.uid)
409 LEFT JOIN register_marketing AS rm ON (rm.uid = a.uid AND rm.last != \'0000-00-00\')
410 WHERE a.uid = {?}
411 ORDER BY rm.last DESC', $this->id());
412 if (is_null($infos)) {
413 $infos = array(
414 'pending_registration_date' => null,
415 'pending_registration_email' => null,
416 'last_marketing_date' => null,
417 'last_marketing_email' => null
418 );
419 }
420 $this->fillFromArray($infos);
421 }
422
423 public function pendingRegistrationDate()
424 {
425 $this->fetchMarketingData();
426 return $this->pending_registration_date;
427 }
428
429 public function pendingRegistrationEmail()
430 {
431 $this->fetchMarketingData();
432 return $this->pending_registration_email;
433 }
434
435 public function lastMarketingDate()
436 {
437 $this->fetchMarketingData();
438 return $this->last_marketing_date;
439 }
440
441 public function lastMarketingEmail()
442 {
443 $this->fetchMarketingData();
444 return $this->last_marketing_email;
445 }
446
447 public function lastKnownEmail()
448 {
449 $this->fetchMarketingData();
450 if ($this->pending_registration_email > $this->last_marketing_date) {
451 return $this->pending_registration_email;
452 }
453 return $this->last_marketing_email;
454 }
455
456
457 /** Format of the emails sent by the site
458 */
459 public function setEmailFormat($format)
460 {
461 Platal::assert($format == self::FORMAT_HTML || $format == self::FORMAT_TEXT,
462 "Invalid email format \"$format\"");
463 XDB::execute("UPDATE accounts
464 SET email_format = {?}
465 WHERE uid = {?}",
466 $format, $this->uid);
467 $this->email_format = $format;
468 }
469
470 /** Get watch informations
471 */
472 private function fetchWatchData()
473 {
474 if (isset($this->watch_actions)) {
475 return;
476 }
477 $watch = XDB::fetchOneAssoc('SELECT flags AS watch_flags, actions AS watch_actions,
478 UNIX_TIMESTAMP(last) AS watch_last
479 FROM watch
480 WHERE uid = {?}', $this->id());
481 $watch['watch_flags'] = new PlFlagSet($watch['watch_flags']);
482 $watch['watch_actions'] = new PlFlagSet($watch['watch_actions']);
483 $watch['watch_promos'] = XDB::fetchColumn('SELECT promo
484 FROM watch_promo
485 WHERE uid = {?}', $this->id());
486 $watch['watch_users'] = XDB::fetchColumn('SELECT ni_id
487 FROM watch_nonins
488 WHERE uid = {?}', $this->id());
489 $this->fillFromArray($watch);
490 }
491
492 public function watchType($type)
493 {
494 $this->fetchWatchData();
495 return $this->watch_actions->hasFlag($type);
496 }
497
498 public function watchContacts()
499 {
500 $this->fetchWatchData();
501 return $this->watch_flags->hasFlag('contacts');
502 }
503
504 public function watchEmail()
505 {
506 $this->fetchWatchData();
507 return $this->watch_flags->hasFlag('mail');
508 }
509
510 public function watchPromos()
511 {
512 $this->fetchWatchData();
513 return $this->watch_promos;
514 }
515
516 public function watchUsers()
517 {
518 $this->fetchWatchData();
519 return $this->watch_users;
520 }
521
522 public function watchLast()
523 {
524 $this->fetchWatchData();
525 return $this->watch_last;
526 }
527
528 public function invalidWatchCache()
529 {
530 unset($this->watch_actions);
531 unset($this->watch_users);
532 unset($this->watch_last);
533 unset($this->watch_promos);
534 }
535
536
537 // Contacts
538 private $contacts = null;
539 private function fetchContacts()
540 {
541 if (is_null($this->contacts)) {
542 $this->contacts = XDB::fetchAllAssoc('contact', 'SELECT *
543 FROM contacts
544 WHERE uid = {?}',
545 $this->id());
546 }
547 }
548
549 public function iterContacts()
550 {
551 $this->fetchContacts();
552 return Profile::iterOverPIDs(array_keys($this->contacts));
553 }
554
555 public function getContacts()
556 {
557 $this->fetchContacts();
558 return Profile::getBulkProfilesWithPIDs(array_keys($this->contacts));
559 }
560
561 public function isContact(Profile &$profile)
562 {
563 $this->fetchContacts();
564 return isset($this->contacts[$profile->id()]);
565 }
566
567 public function isWatchedUser(Profile &$profile)
568 {
569 return in_array($profile->id(), $this->watchUsers());
570 }
571
572 // Groupes X
573 private $groups = null;
574 public function groups()
575 {
576 if (is_null($this->groups)) {
577 $this->groups = XDB::fetchAllAssoc('asso_id', 'SELECT asso_id, perms, comm
578 FROM group_members
579 WHERE uid = {?}',
580 $this->id());
581 }
582 return $this->groups;
583 }
584
585 public function groupNames($institutions = false)
586 {
587 if ($institutions) {
588 $where = ' AND (g.cat = \'GroupesX\' OR g.cat = \'Institutions\')';
589 } else {
590 $where = '';
591 }
592 return XDB::fetchAllAssoc('SELECT g.diminutif, g.nom, g.site
593 FROM group_members AS gm
594 LEFT JOIN groups AS g ON (g.id = gm.asso_id)
595 WHERE gm.uid = {?}' . $where,
596 $this->id());
597 }
598
599 /**
600 * Clears a user.
601 * *always deletes in: account_lost_passwords, register_marketing,
602 * register_pending, register_subs, watch_nonins, watch, watch_promo
603 * *always keeps in: account_types, accounts, aliases, axletter_ins, carvas,
604 * group_members, homonyms, newsletter_ins, register_mstats,
605 * *deletes if $clearAll: account_auth_openid, announce_read, contacts,
606 * email_options, email_send_save, emails, forum_innd, forum_profiles,
607 * forum_subs, gapps_accounts, gapps_nicknames, group_announces_read,
608 * group_member_sub_requests, reminder, requests, requests_hidden,
609 * virtual, virtual_redirect, ML
610 * *modifies if $clearAll: accounts
611 *
612 * Use cases:
613 * *$clearAll == false: when a user dies, her family still needs to keep in
614 * touch with the community.
615 * *$clearAll == true: in every other case we want the account to be fully
616 * deleted so that it can not be used anymore.
617 */
618 public function clear($clearAll = true)
619 {
620 $tables = array('account_lost_passwords', 'register_marketing',
621 'register_pending', 'register_subs', 'watch_nonins',
622 'watch', 'watch_promo');
623
624 foreach ($tables as $t) {
625 XDB::execute('DELETE FROM ' . $t . '
626 WHERE uid = {?}',
627 $this->id());
628 }
629
630 if ($clearAll) {
631 global $globals;
632
633 $groupIds = XDB::iterator('SELECT asso_id
634 FROM group_members
635 WHERE uid = {?}',
636 $this->id());
637 while ($groupId = $groupIds->next()) {
638 $group = Group::get($groupId);
639 if (!empty($group) && $group->notif_unsub) {
640 $mailer = new PlMailer('xnetgrp/unsubscription-notif.mail.tpl');
641 $admins = $group->iterAdmins();
642 while ($admin = $admins->next()) {
643 $mailer->addTo($admin);
644 }
645 $mailer->assign('group', $group->shortname);
646 $mailer->assign('user', $this);
647 $mailer->assign('selfdone', false);
648 $mailer->send();
649 }
650 }
651
652 $tables = array('account_auth_openid', 'announce_read', 'contacts',
653 'email_options', 'email_send_save', 'emails',
654 'forum_innd', 'forum_profiles', 'forum_subs',
655 'group_announces_read', 'group_members',
656 'group_member_sub_requests', 'reminder', 'requests',
657 'requests_hidden');
658 foreach ($tables as $t) {
659 XDB::execute('DELETE FROM ' . $t . '
660 WHERE uid = {?}',
661 $this->id());
662 }
663
664 foreach (array('gapps_accounts', 'gapps_nicknames') as $t) {
665 XDB::execute('DELETE FROM ' . $t . '
666 WHERE l_userid = {?}',
667 $this->id());
668 }
669
670 XDB::execute("UPDATE accounts
671 SET registration_date = 0, state = 'pending', password = NULL,
672 weak_password = NULL, token = NULL, is_admin = 0
673 WHERE uid = {?}",
674 $this->id());
675
676 XDB::execute('DELETE v.*
677 FROM virtual AS v
678 INNER JOIN virtual_redirect AS r ON (v.vid = r.vid)
679 WHERE redirect = {?} OR redirect = {?}',
680 $this->forlifeEmail(), $this->m4xForlifeEmail());
681 XDB::execute('DELETE FROM virtual_redirect
682 WHERE redirect = {?} OR redirect = {?}',
683 $this->forlifeEmail(), $this->m4xForlifeEmail());
684
685 if ($globals->mailstorage->googleapps_domain) {
686 require_once 'googleapps.inc.php';
687
688 if (GoogleAppsAccount::account_status($this->id())) {
689 $account = new GoogleAppsAccount($this);
690 $account->suspend();
691 }
692 }
693 }
694
695 $mmlist = new MMList($this);
696 $mmlist->kill($this->hruid, $clearAll);
697 }
698
699 // Merge all infos in other user and then clean this one
700 public function mergeIn(User &$newuser) {
701 if ($this->profile()) {
702 // Don't disable user with profile in this way.
703 global $globals;
704 Platal::page()->trigError('Impossible de fusionner les comptes ' . $this->hruid . ' et ' . $newuser->hruid .
705 '. Contacte support@' . $globals->mail->domain . '.');
706 return false;
707 }
708
709 if ($this->forlifeEmail()) {
710 // If the new user is not registered and does not have already an email address,
711 // we need to give him the old user's email address if he has any.
712 if (!$newuser->perms) {
713 XDB::execute('UPDATE accounts
714 SET email = {?}
715 WHERE uid = {?} AND email IS NULL',
716 $this->forlifeEmail(), $newuser->id());
717 }
718 $newemail = XDB::fetchOneCell('SELECT email
719 FROM accounts
720 WHERE uid = {?}',
721 $newuser->id());
722
723 // Change email used in aliases and mailing lists.
724 if ($this->forlifeEmail() != $newemail) {
725 // virtual_redirect (email aliases)
726 XDB::execute('DELETE v1
727 FROM virtual_redirect AS v1, virtual_redirect AS v2
728 WHERE v1.vid = v2.vid AND v1.redirect = {?} AND v2.redirect = {?}',
729 $this->forlifeEmail(), $newemail);
730 XDB::execute('UPDATE virtual_redirect
731 SET redirect = {?}
732 WHERE redirect = {?}',
733 $newemail, $this->forlifeEmail());
734
735 // group mailing lists
736 $group_domains = XDB::fetchColumn('SELECT g.mail_domain
737 FROM groups AS g
738 INNER JOIN group_members AS gm ON(g.id = gm.asso_id)
739 WHERE g.mail_domain != \'\' AND gm.uid = {?}',
740 $this->id());
741 foreach ($group_domains as $mail_domain) {
742 $mmlist = new MMList($this, $mail_domain);
743 $mmlist->replace_email_in_all($this->forlifeEmail(), $newemail);
744 }
745 // main domain lists
746 $mmlist = new MMList($this);
747 $mmlist->replace_email_in_all($this->forlifeEmail(), $newemail);
748 }
749 }
750
751 // Updates user in following tables.
752 foreach (array('group_announces', 'payment_transactions', 'log_sessions', 'group_events') as $table) {
753 XDB::execute('UPDATE ' . $table . '
754 SET uid = {?}
755 WHERE uid = {?}',
756 $newuser->id(), $this->id());
757 }
758
759 // Merges user in following tables, ie updates when possible, then deletes remaining occurences of the old user.
760 foreach (array('group_announces_read', 'group_event_participants', 'group_member_sub_requests', 'group_members') as $table) {
761 XDB::execute('UPDATE IGNORE ' . $table . '
762 SET uid = {?}
763 WHERE uid = {?}',
764 $newuser->id(), $this->id());
765 XDB::execute('DELETE FROM ' . $table . '
766 WHERE uid = {?}',
767 $this->id());
768 }
769
770 // Eventually updates last session id and deletes old user's accounts entry.
771 $lastSession = XDB::fetchOneCell('SELECT id
772 FROM log_sessions
773 WHERE uid = {?}
774 ORDER BY start DESC
775 LIMIT 1',
776 $newuser->id());
777 XDB::execute('UPDATE log_last_sessions
778 SET id = {?}
779 WHERE uid = {?}',
780 $newuser->id());
781 XDB::execute('DELETE FROM accounts
782 WHERE uid = {?}',
783 $this->id());
784
785 return true;
786 }
787
788 // Return permission flags for a given permission level.
789 public static function makePerms($perms, $is_admin)
790 {
791 $flags = new PlFlagSet($perms);
792 $flags->addFlag(PERMS_USER);
793 if ($is_admin) {
794 $flags->addFlag(PERMS_ADMIN);
795 }
796
797 // Access to private directory implies access to 'less'-private version.
798 if ($flags->hasFlag('directory_private')) {
799 $flags->addFlag('directory_ax');
800 }
801 return $flags;
802 }
803
804 // Implementation of the default user callback.
805 public static function _default_user_callback($login, $results)
806 {
807 $result_count = count($results);
808 if ($result_count == 0 || !S::admin()) {
809 Platal::page()->trigError("Il n'y a pas d'utilisateur avec l'identifiant : $login");
810 } else {
811 Platal::page()->trigError("Il y a $result_count utilisateurs avec cet identifiant : " . join(', ', $results));
812 }
813 }
814
815 // Implementation of the static email locality checker.
816 public static function isForeignEmailAddress($email)
817 {
818 global $globals;
819 if (strpos($email, '@') === false) {
820 return false;
821 }
822
823 list($user, $dom) = explode('@', $email);
824 return $dom != $globals->mail->domain &&
825 $dom != $globals->mail->domain2 &&
826 $dom != $globals->mail->alias_dom &&
827 $dom != $globals->mail->alias_dom2;
828 }
829
830 public static function isVirtualEmailAddress($email)
831 {
832 global $globals;
833 if (strpos($email, '@') === false) {
834 return false;
835 }
836
837 list($user, $dom) = explode('@', $email);
838 return $dom == $globals->mail->alias_dom
839 || $dom == $globals->mail->alias_dom2;
840 }
841
842 /* Tries to find pending accounts with an hruid close to $login. */
843 public static function getPendingAccounts($login, $iterator = false)
844 {
845 global $globals;
846
847 if (strpos($login, '@') === false) {
848 return null;
849 }
850
851 list($login, $domain) = explode('@', $login);
852
853 if ($domain && $domain != $globals->mail->domain && $domain != $globals->mail->domain2) {
854 return null;
855 }
856
857 $sql = "SELECT uid, full_name
858 FROM accounts
859 WHERE state = 'pending' AND REPLACE(hruid, '-', '') LIKE
860 CONCAT('%', REPLACE(REPLACE(REPLACE({?}, ' ', ''), '-', ''), '\'', ''), '%')
861 ORDER BY full_name";
862 if ($iterator) {
863 return XDB::iterator($sql, $login);
864 } else {
865 $res = XDB::query($sql, $login);
866 return $res->fetchAllAssoc();
867 }
868 }
869
870
871 public static function iterOverUIDs($uids, $respect_order = true)
872 {
873 return new UserIterator(self::loadMainFieldsFromUIDs($uids, $respect_order));
874 }
875
876 /** Fetch a set of users from a list of UIDs
877 * @param $data The list of uids to fetch, or an array of arrays
878 * @param $orig If $data is an array of arrays, the subfield where uids are stored
879 * @param $dest If $data is an array of arrays, the subfield to fill with Users
880 * @param $fetchProfile Whether to fetch Profiles as well
881 * @return either an array of $uid => User, or $data with $data[$i][$dest] = User
882 */
883 public static function getBulkUsersWithUIDs(array $data, $orig = null, $dest = null, $fetchProfile = true)
884 {
885 // Fetch the list of uids
886 if (is_null($orig)) {
887 $uids = $data;
888 } else {
889 if (is_null($dest)) {
890 $dest = $orig;
891 }
892 $uids = array();
893 foreach ($data as $key=>$entry) {
894 if (isset($entry[$orig])) {
895 $uids[] = $entry[$orig];
896 }
897 }
898 }
899
900 // Fetch users
901 if (count($uids) == 0) {
902 return $data;
903 }
904 $users = self::iterOverUIDs($uids, true);
905
906 $table = array();
907 if ($fetchProfile) {
908 $profiles = Profile::iterOverUIDS($uids, true);
909 if ($profiles != null) {
910 $profile = $profiles->next();
911 } else {
912 $profile = null;
913 }
914 }
915
916 /** We iterate through the users, moving in
917 * profiles when they match the user ID :
918 * there can be users without a profile, but not
919 * the other way around.
920 */
921 while (($user = $users->next())) {
922 if ($fetchProfile) {
923 if ($profile != null && $profile->owner_id == $user->id()) {
924 $user->_profile = $profile;
925 $profile = $profiles->next();
926 }
927 $user->_profile_fetched = true;
928 }
929 $table[$user->id()] = $user;
930 }
931
932 // Build the result with respect to input order.
933 if (is_null($orig)) {
934 return $table;
935 } else {
936 foreach ($data as $key=>$entry) {
937 if (isset($entry[$orig])) {
938 $entry[$dest] = $table[$entry[$orig]];
939 $data[$key] = $entry;
940 }
941 }
942 return $data;
943 }
944 }
945
946 public static function getBulkUsersFromDB($fetchProfile = true)
947 {
948 $args = func_get_args();
949 $uids = call_user_func_array(array('XDB', 'fetchColumn'), $args);
950 return self::getBulkUsersWithUIDs($uids, null, null, $fetchProfile);
951 }
952 }
953
954 /** Iterator over a set of Users
955 * @param an XDB::Iterator obtained from a User::loadMainFieldsFromUIDs
956 */
957 class UserIterator implements PlIterator
958 {
959 private $dbiter;
960
961 public function __construct($dbiter)
962 {
963 $this->dbiter = $dbiter;
964 }
965
966 public function next()
967 {
968 $data = $this->dbiter->next();
969 if ($data == null) {
970 return null;
971 } else {
972 return User::getSilentWithValues(null, $data);
973 }
974 }
975
976 public function total()
977 {
978 return $this->dbiter->total();
979 }
980
981 public function first()
982 {
983 return $this->dbiter->first();
984 }
985
986 public function last()
987 {
988 return $this->dbiter->last();
989 }
990 }
991
992 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
993 ?>