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