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