Change comletter from and replyto and add Return-Path header
[platal.git] / classes / user.php
CommitLineData
9f8ebb9f
VZ
1<?php
2/***************************************************************************
c441aabe 3 * Copyright (C) 2003-2014 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.
bfc34dc5 86 $res = XDB::query('SELECT uid
06a548e5 87 FROM accounts
c846452b
RB
88 WHERE hruid = {?}', $login);
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.
b1719b13
VZ
94 $login = trim(strtolower($login));
95 if (strstr($login, '@') === false) {
ac57076f
SJ
96 $res = XDB::fetchOneCell('SELECT uid
97 FROM email_source_account
98 WHERE email = {?}',
99 $login);
06a548e5
SJ
100 } else {
101 list($email, $domain) = explode('@', $login);
ac57076f
SJ
102 $res = XDB::fetchOneCell('SELECT s.uid
103 FROM email_source_account AS s
104 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
105 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
106 WHERE s.email = {?} AND d.name = {?}',
107 $email, $domain);
b1719b13
VZ
108 }
109
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
b7753795 162 return XDB::iterator('SELECT a.uid, a.hruid, a.registration_date, h.uid IS NOT NULL AS homonym, a.firstname, a.lastname,
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,
dac6e2c6 166 (er.redirect IS NULL AND a.state = \'active\' AND FIND_IN_SET(\'mail\', at.perms)) 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,
1b78b883 173 s.start AS lastlogin, s.host, 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.%\')
f67c8d9a 181 LEFT JOIN email_source_account AS eb ON (eb.uid = a.uid AND FIND_IN_SET(\'bestalias\',eb.flags))
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
38a86f60
RB
228 /** Retrieve the 'general' read visibility.
229 * This is the maximum level of fields that may be viewed by the current user on other profiles.
230 *
231 * Rules are:
232 * - Everyone can view 'public'
233 * - directory_ax gives access to 'AX' level
234 * - directory_private gives access to 'private' level
235 * - admin gives access to 'hidden' level
236 */
237 public function readVisibility()
238 {
22771578 239 $level = Visibility::VIEW_NONE;
38a86f60 240 if ($this->is_admin) {
22771578 241 $level = Visibility::VIEW_ADMIN;
38a86f60 242 } elseif ($this->checkPerms('directory_private')) {
22771578 243 $level = Visibility::VIEW_PRIVATE;
38a86f60 244 } elseif ($this->checkPerms('directory_ax')) {
22771578 245 $level = Visibility::VIEW_AX;
38a86f60 246 } else {
22771578 247 $level = Visibility::VIEW_PUBLIC;
38a86f60 248 }
22771578 249 return Visibility::get($level);
38a86f60
RB
250 }
251
252 /** Retrieve the 'general' edit visibility.
253 * This is the maximum level of fields that may be edited by the current user on other profiles.
254 *
255 * Rules are:
256 * - Only admins can edit the 'hidden' fields
22771578 257 * - If someone has 'directory_edit' (which is actually directory_ax_edit): AX level
38a86f60
RB
258 * - Otherwise, nothing.
259 */
260 public function editVisibility()
261 {
22771578 262 $level = Visibility::VIEW_NONE;
38a86f60 263 if ($this->is_admin) {
22771578 264 $level = Visibility::VIEW_ADMIN;
38a86f60 265 } elseif ($this->checkPerms('directory_edit')) {
22771578 266 $level = Visibility::VIEW_AX;
38a86f60 267 }
22771578 268 return Visibility::get($level);
38a86f60
RB
269 }
270
7f1ff426
FB
271 // We do not want to store the password in the object.
272 // So, fetch it 'on demand'
273 public function password()
274 {
275 return XDB::fetchOneCell('SELECT a.password
276 FROM accounts AS a
277 WHERE a.uid = {?}', $this->id());
278 }
279
280806d9
SJ
280 public function isActive()
281 {
282 return $this->state == 'active';
283 }
284
8f2104cb
FB
285 /** Overload PlUser::promo(): there no promo defined for a user in the current
286 * schema. The promo is a field from the profile.
287 */
288 public function promo()
289 {
290 if (!$this->hasProfile()) {
291 return '';
292 }
293 return $this->profile()->promo();
294 }
295
f60c3d1f
FB
296 public function category()
297 {
298 $promo = $this->promo();
299 if (!empty($promo)) {
300 return $promo;
301 } else {
302 return $this->type_description;
303 }
304 }
305
a6761ca9
FB
306 public function firstName()
307 {
308 if (!$this->hasProfile()) {
94b6106c 309 return $this->firstname;
a6761ca9
FB
310 }
311 return $this->profile()->firstName();
312 }
313
314 public function lastName()
315 {
316 if (!$this->hasProfile()) {
94b6106c 317 return $this->lastname;
a6761ca9
FB
318 }
319 return $this->profile()->lastName();
320 }
321
2ab3486b
SJ
322 public function displayName()
323 {
324 if (!$this->hasProfile()) {
325 return $this->display_name;
326 }
327 return $this->profile()->yourself;
328 }
329
09e54905
SJ
330 public function fullName($with_promo = false)
331 {
332 if (!$this->hasProfile()) {
333 return $this->full_name;
334 }
335 return $this->profile()->fullName($with_promo);
336 }
337
fc1227ef
SJ
338 public function shortName($with_promo = false)
339 {
340 if (!$this->hasProfile()) {
341 return $this->full_name;
342 }
343 return $this->profile()->shortName($with_promo);
344 }
345
09e54905
SJ
346 public function directoryName()
347 {
348 if (!$this->hasProfile()) {
d081acb2 349 return $this->directory_name;
09e54905
SJ
350 }
351 return $this->profile()->directory_name;
352 }
353
52366335
SJ
354 static public function compareDirectoryName($a, $b)
355 {
356 return strcasecmp(replace_accent($a->directoryName()), replace_accent($b->directoryName()));
357 }
358
e7b93962
FB
359 /** Return the main profile attached with this account if any.
360 */
4ac2e2ba 361 public function profile($forceFetch = false, $fields = 0x0000, $visibility = null)
e7b93962 362 {
4e698dc9 363 if (!$this->_profile_fetched || $forceFetch) {
3e53a496 364 $this->_profile_fetched = true;
4ac2e2ba 365 $this->_profile = Profile::get($this, $fields, $visibility);
6178c3f3 366 } else if ($this->_profile !== null && $visibility !== null && !$this->_profile->visibility->equals($visibility)) {
22771578 367 return Profile::get($this, $fields, $visibility);
3e53a496
FB
368 }
369 return $this->_profile;
370 }
371
83040cf5
RB
372 public function setPrefetchedProfile(Profile $profile)
373 {
374 $this->_profile_fetched = true;
375 $this->_profile = $profile;
376 }
377
3e53a496
FB
378 /** Return true if the user has an associated profile.
379 */
380 public function hasProfile()
381 {
382 return !is_null($this->profile());
383 }
384
fceed6ea
FB
385 /** Return true if given a reference to the profile of this user.
386 */
387 public function isMyProfile($other)
388 {
389 if (!$other) {
390 return false;
391 } else if ($other instanceof Profile) {
392 $profile = $this->profile();
393 return $profile && $profile->id() == $other->id();
394 }
395 return false;
396 }
397
3af21f99
FB
398 /** Check if the user can edit to given profile.
399 */
400 public function canEdit(Profile $profile)
401 {
a81ee987
FB
402 if ($this->checkPerms(User::PERM_EDIT_DIRECTORY)) {
403 return true;
404 }
3af21f99
FB
405 return XDB::fetchOneCell('SELECT pid
406 FROM account_profiles
407 WHERE uid = {?} AND pid = {?}',
408 $this->id(), $profile->id());
409 }
410
f036c896 411 /** Determines main email domain for this user.
3e53a496 412 */
f036c896 413 public function mainEmailDomain()
3e53a496 414 {
f036c896
SJ
415 if (array_key_exists($this->type, self::$sub_mail_domains)) {
416 return self::$sub_mail_domains[$this->type] . Platal::globals()->mail->domain;
8f2104cb 417 }
8f2104cb
FB
418 }
419
f036c896 420 /** Determines alternate email domain for this user.
8f2104cb 421 */
f036c896
SJ
422 public function alternateEmailDomain()
423 {
424 if (array_key_exists($this->type, self::$sub_mail_domains)) {
425 return self::$sub_mail_domains[$this->type] . Platal::globals()->mail->domain2;
a6761ca9 426 }
f036c896
SJ
427 }
428
72e12532
SJ
429 public function forlifeEmailAlternate()
430 {
431 if (!empty($this->forlife_alternate)) {
432 return $this->forlife_alternate;
8f2104cb 433 }
72e12532 434 return $this->email;
3e53a496
FB
435 }
436
08d33afc 437 /** Fetch existing auxiliary alias.
3e53a496 438 */
3e53a496 439 public function emailAlias()
3e53a496 440 {
06a548e5
SJ
441 $aliases = $this->emailAliases();
442 if (count($aliases)) {
443 return $aliases[0];
8f2104cb
FB
444 }
445 return null;
e7b93962
FB
446 }
447
08d33afc 448 /** Fetch existing auxiliary aliases.
8f2104cb 449 */
06a548e5
SJ
450 public function emailAliases()
451 {
452 return XDB::fetchColumn('SELECT CONCAT(s.email, \'@\', d.name)
453 FROM email_source_account AS s
454 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
455 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
08d33afc 456 WHERE s.uid = {?} AND s.type = \'alias_aux\'
06a548e5 457 ORDER BY d.name',
08d33afc 458 $this->id());
3e53a496
FB
459 }
460
06a548e5 461 /** Get all group aliases the user belongs to.
3e53a496 462 */
06a548e5
SJ
463 public function emailGroupAliases($domain = null)
464 {
465 if (is_null($domain)) {
466 return XDB::fetchColumn('SELECT CONCAT(v.email, \'@\', dv.name) AS alias
467 FROM email_virtual AS v
468 INNER JOIN email_virtual_domains AS dv ON (v.domain = dv.id)
469 INNER JOIN email_source_account AS s ON (s.uid = {?})
470 INNER JOIN email_virtual_domains AS ms ON (s.domain = ms.id)
471 INNER JOIN email_virtual_domains AS ds ON (ds.aliasing = ms.id)
51c2c63a 472 WHERE v.redirect = CONCAT(s.email, \'@\', ds.name) AND v.type = \'alias\'',
06a548e5
SJ
473 $this->id());
474 } else {
a94fdc4e
SJ
475 return XDB::fetchAllAssoc('alias',
476 'SELECT CONCAT(v.email, \'@\', dv.name) AS alias, MAX(v.redirect = CONCAT(s.email, \'@\', ds.name)) AS sub
06a548e5
SJ
477 FROM email_virtual AS v
478 INNER JOIN email_virtual_domains AS dv ON (v.domain = dv.id AND dv.name = {?})
479 INNER JOIN email_source_account AS s ON (s.uid = {?})
480 INNER JOIN email_virtual_domains AS ms ON (s.domain = ms.id)
481 INNER JOIN email_virtual_domains AS ds ON (ds.aliasing = ms.id)
51c2c63a 482 WHERE v.type = \'alias\'
a94fdc4e
SJ
483 GROUP BY v.email
484 ORDER BY v.email',
06a548e5
SJ
485 $domain, $this->id());
486 }
e7b93962 487 }
38c6fe96
FB
488
489 /** Get marketing informations
490 */
491 private function fetchMarketingData()
492 {
db8432d5 493 if (isset($this->pending_registration_date)) {
38c6fe96
FB
494 return;
495 }
db8432d5
SJ
496 $infos = XDB::fetchOneAssoc('SELECT rp.date AS pending_registration_date, rp.email AS pending_registration_email,
497 rm.last AS last_marketing_date, rm.email AS last_marketing_email
498 FROM accounts AS a
499 LEFT JOIN register_pending AS rp ON (rp.uid = a.uid)
500 LEFT JOIN register_marketing AS rm ON (rm.uid = a.uid AND rm.last != \'0000-00-00\')
501 WHERE a.uid = {?}
502 ORDER BY rm.last DESC', $this->id());
503 if (is_null($infos)) {
504 $infos = array(
505 'pending_registration_date' => null,
506 'pending_registration_email' => null,
507 'last_marketing_date' => null,
508 'last_marketing_email' => null
509 );
38c6fe96
FB
510 }
511 $this->fillFromArray($infos);
512 }
513
db8432d5 514 public function pendingRegistrationDate()
38c6fe96
FB
515 {
516 $this->fetchMarketingData();
db8432d5
SJ
517 return $this->pending_registration_date;
518 }
519
520 public function pendingRegistrationEmail()
521 {
522 $this->fetchMarketingData();
523 return $this->pending_registration_email;
524 }
525
526 public function lastMarketingDate()
527 {
528 $this->fetchMarketingData();
529 return $this->last_marketing_date;
530 }
531
532 public function lastMarketingEmail()
533 {
534 $this->fetchMarketingData();
535 return $this->last_marketing_email;
38c6fe96
FB
536 }
537
538 public function lastKnownEmail()
539 {
540 $this->fetchMarketingData();
db8432d5
SJ
541 if ($this->pending_registration_email > $this->last_marketing_date) {
542 return $this->pending_registration_email;
543 }
544 return $this->last_marketing_email;
38c6fe96
FB
545 }
546
009b8ab7 547
8d308ee4
FB
548 /** Format of the emails sent by the site
549 */
550 public function setEmailFormat($format)
551 {
552 Platal::assert($format == self::FORMAT_HTML || $format == self::FORMAT_TEXT,
553 "Invalid email format \"$format\"");
554 XDB::execute("UPDATE accounts
555 SET email_format = {?}
556 WHERE uid = {?}",
557 $format, $this->uid);
558 $this->email_format = $format;
559 }
560
009b8ab7
FB
561 /** Get watch informations
562 */
563 private function fetchWatchData()
564 {
565 if (isset($this->watch_actions)) {
566 return;
567 }
568 $watch = XDB::fetchOneAssoc('SELECT flags AS watch_flags, actions AS watch_actions,
569 UNIX_TIMESTAMP(last) AS watch_last
570 FROM watch
571 WHERE uid = {?}', $this->id());
572 $watch['watch_flags'] = new PlFlagSet($watch['watch_flags']);
573 $watch['watch_actions'] = new PlFlagSet($watch['watch_actions']);
574 $watch['watch_promos'] = XDB::fetchColumn('SELECT promo
575 FROM watch_promo
576 WHERE uid = {?}', $this->id());
fe286e5f
SJ
577 $watch['watch_groups'] = XDB::fetchColumn("SELECT w.groupid
578 FROM watch_group AS w
579 INNER JOIN groups AS g ON (w.groupid = g.id AND NOT FIND_IN_SET('private', pub))
580 WHERE w.uid = {?}", $this->id());
009b8ab7
FB
581 $watch['watch_users'] = XDB::fetchColumn('SELECT ni_id
582 FROM watch_nonins
583 WHERE uid = {?}', $this->id());
584 $this->fillFromArray($watch);
585 }
586
a87530ea 587 public function watchType($type)
009b8ab7
FB
588 {
589 $this->fetchWatchData();
590 return $this->watch_actions->hasFlag($type);
591 }
592
593 public function watchContacts()
594 {
595 $this->fetchWatchData();
596 return $this->watch_flags->hasFlag('contacts');
597 }
598
599 public function watchEmail()
600 {
601 $this->fetchWatchData();
602 return $this->watch_flags->hasFlag('mail');
603 }
604
605 public function watchPromos()
606 {
607 $this->fetchWatchData();
608 return $this->watch_promos;
609 }
610
fe286e5f
SJ
611 public function watchGroups()
612 {
613 $this->fetchWatchData();
614 return $this->watch_groups;
615 }
616
009b8ab7
FB
617 public function watchUsers()
618 {
619 $this->fetchWatchData();
620 return $this->watch_users;
621 }
622
623 public function watchLast()
624 {
625 $this->fetchWatchData();
626 return $this->watch_last;
627 }
628
069ddda8
FB
629 public function invalidWatchCache()
630 {
631 unset($this->watch_actions);
632 unset($this->watch_users);
633 unset($this->watch_last);
634 unset($this->watch_promos);
fe286e5f 635 unset($this->watch_groups);
069ddda8
FB
636 }
637
c350577b
FB
638
639 // Contacts
640 private $contacts = null;
48e683dd 641 private function fetchContacts()
c350577b 642 {
76cbe885 643 if (is_null($this->contacts)) {
c350577b
FB
644 $this->contacts = XDB::fetchAllAssoc('contact', 'SELECT *
645 FROM contacts
646 WHERE uid = {?}',
647 $this->id());
648 }
48e683dd
FB
649 }
650
651 public function iterContacts()
652 {
653 $this->fetchContacts();
a289e967 654 return Profile::iterOverPIDs(array_keys($this->contacts));
48e683dd
FB
655 }
656
657 public function getContacts()
658 {
659 $this->fetchContacts();
a289e967 660 return Profile::getBulkProfilesWithPIDs(array_keys($this->contacts));
48e683dd
FB
661 }
662
26ba053e 663 public function isContact(Profile $profile)
48e683dd
FB
664 {
665 $this->fetchContacts();
a289e967 666 return isset($this->contacts[$profile->id()]);
c350577b
FB
667 }
668
26ba053e 669 public function isWatchedUser(Profile $profile)
958def08
PC
670 {
671 return in_array($profile->id(), $this->watchUsers());
672 }
673
f5ef8b57
RB
674 // Groupes X
675 private $groups = null;
56cd7aee 676 public function groups($institutions = false, $onlyPublic = false)
f5ef8b57
RB
677 {
678 if (is_null($this->groups)) {
56cd7aee
FB
679 $this->groups = XDB::fetchAllAssoc('asso_id', 'SELECT gm.asso_id, gm.perms, gm.comm,
680 g.diminutif, g.nom, g.site, g.cat,
681 g.pub
682 FROM group_members AS gm
683 INNER JOIN groups AS g ON (g.id = gm.asso_id)
f5ef8b57
RB
684 WHERE uid = {?}',
685 $this->id());
686 }
56cd7aee
FB
687 if (!$institutions && !$onlyPublic) {
688 return $this->groups;
fa589f90 689 } else {
56cd7aee
FB
690 $result = array();
691 foreach ($this->groups as $id=>$data) {
692 if ($institutions) {
1d889ac4 693 if ($data['cat'] != Group::CAT_GROUPESX && $data['cat'] != Group::CAT_INSTITUTIONS) {
56cd7aee
FB
694 continue;
695 }
696 }
697 if ($onlyPublic) {
698 if ($data['pub'] != 'public') {
699 continue;
700 }
701 }
702 $result[$id] = $data;
703 }
704 return $result;
fa589f90 705 }
fa589f90
RB
706 }
707
9a7f3d8e 708 public function groupCount()
4257b11a 709 {
9a7f3d8e
SJ
710 return XDB::fetchOneCell('SELECT COUNT(DISTINCT(asso_id))
711 FROM group_members
712 WHERE uid = {?}',
713 $this->id());
4257b11a
SJ
714 }
715
7ae5c545
SJ
716 public function inGroup($asso_id)
717 {
718 $res = XDB::fetchOneCell('SELECT COUNT(*)
719 FROM group_members
720 WHERE uid = {?} AND asso_id = {?}',
721 $this->id(), $asso_id);
722 return ($res > 0);
723 }
724
6150f591
SJ
725 /**
726 * Clears a user.
727 * *always deletes in: account_lost_passwords, register_marketing,
fe286e5f 728 * register_pending, register_subs, watch_nonins, watch, watch_promo, watch_group,
06a548e5
SJ
729 * *always keeps in: account_types, accounts, email_virtual, carvas,
730 * group_members, homonyms_list, newsletter_ins, register_mstats, email_source_account
6150f591 731 * *deletes if $clearAll: account_auth_openid, announce_read, contacts,
06a548e5 732 * email_redirect_account, email_redirect_account, email_send_save, forum_innd, forum_profiles,
6150f591
SJ
733 * forum_subs, gapps_accounts, gapps_nicknames, group_announces_read,
734 * group_member_sub_requests, reminder, requests, requests_hidden,
06a548e5 735 * email_virtual, ML
6150f591
SJ
736 * *modifies if $clearAll: accounts
737 *
738 * Use cases:
739 * *$clearAll == false: when a user dies, her family still needs to keep in
740 * touch with the community.
741 * *$clearAll == true: in every other case we want the account to be fully
742 * deleted so that it can not be used anymore.
743 */
744 public function clear($clearAll = true)
745 {
405d70cc
RB
746 $tables = array('account_lost_passwords', 'register_marketing',
747 'register_pending', 'register_subs', 'watch_nonins',
fe286e5f 748 'watch', 'watch_promo', 'watch_group');
405d70cc
RB
749
750 foreach ($tables as $t) {
751 XDB::execute('DELETE FROM ' . $t . '
752 WHERE uid = {?}',
753 $this->id());
754 }
6150f591
SJ
755
756 if ($clearAll) {
c79e28fc
SJ
757 global $globals;
758
0e5b3438
SJ
759 $groupIds = XDB::iterator('SELECT asso_id
760 FROM group_members
761 WHERE uid = {?}',
762 $this->id());
763 while ($groupId = $groupIds->next()) {
764 $group = Group::get($groupId);
c79e28fc 765 if (!empty($group) && $group->notif_unsub) {
0e5b3438
SJ
766 $mailer = new PlMailer('xnetgrp/unsubscription-notif.mail.tpl');
767 $admins = $group->iterAdmins();
768 while ($admin = $admins->next()) {
769 $mailer->addTo($admin);
770 }
771 $mailer->assign('group', $group->shortname);
772 $mailer->assign('user', $this);
773 $mailer->assign('selfdone', false);
774 $mailer->send();
775 }
776 }
777
c79e28fc 778 $tables = array('account_auth_openid', 'announce_read', 'contacts',
13b45814 779 'email_send_save',
c79e28fc
SJ
780 'forum_innd', 'forum_profiles', 'forum_subs',
781 'group_announces_read', 'group_members',
782 'group_member_sub_requests', 'reminder', 'requests',
06a548e5 783 'requests_hidden');
405d70cc
RB
784 foreach ($tables as $t) {
785 XDB::execute('DELETE FROM ' . $t . '
786 WHERE uid = {?}',
c79e28fc
SJ
787 $this->id());
788 }
06a548e5
SJ
789 XDB::execute('DELETE FROM email_redirect_account
790 WHERE uid = {?} AND type != \'homonym\'',
791 $this->id());
13b45814
SJ
792 XDB::execute('DELETE FROM email_virtual
793 WHERE redirect = {?}',
794 $this->forlifeEmail());
c79e28fc
SJ
795
796 foreach (array('gapps_accounts', 'gapps_nicknames') as $t) {
797 XDB::execute('DELETE FROM ' . $t . '
798 WHERE l_userid = {?}',
799 $this->id());
405d70cc
RB
800 }
801
6150f591
SJ
802 XDB::execute("UPDATE accounts
803 SET registration_date = 0, state = 'pending', password = NULL,
804 weak_password = NULL, token = NULL, is_admin = 0
805 WHERE uid = {?}",
806 $this->id());
807
6150f591
SJ
808 if ($globals->mailstorage->googleapps_domain) {
809 require_once 'googleapps.inc.php';
810
c79e28fc
SJ
811 if (GoogleAppsAccount::account_status($this->id())) {
812 $account = new GoogleAppsAccount($this);
6150f591
SJ
813 $account->suspend();
814 }
815 }
816 }
817
dec84555 818 $mmlist = new MMList(S::user());
a85562a0 819 $mmlist->kill($this->hruid, $clearAll);
6150f591
SJ
820 }
821
ab06182d 822 // Merge all infos in other user and then clean this one
26ba053e 823 public function mergeIn(User $newuser) {
33a4f3f9
SJ
824 if ($this->profile()) {
825 // Don't disable user with profile in this way.
826 global $globals;
827 Platal::page()->trigError('Impossible de fusionner les comptes ' . $this->hruid . ' et ' . $newuser->hruid .
828 '. Contacte support@' . $globals->mail->domain . '.');
ab06182d
PC
829 return false;
830 }
ab06182d 831
33a4f3f9
SJ
832 if ($this->forlifeEmail()) {
833 // If the new user is not registered and does not have already an email address,
834 // we need to give him the old user's email address if he has any.
835 if (!$newuser->perms) {
836 XDB::execute('UPDATE accounts
837 SET email = {?}
838 WHERE uid = {?} AND email IS NULL',
839 $this->forlifeEmail(), $newuser->id());
06a548e5
SJ
840
841 // Reftech new user so its forlifeEmail will be correct.
cb8b7945 842 $newuser = self::getSilentWithUID($newuser->id());
ab06182d 843 }
33a4f3f9 844
06a548e5
SJ
845 // Change email used in mailing lists.
846 if ($this->forlifeEmail() != $newuser->forlifeEmail()) {
f7d43ed5
SJ
847 // The super user is the user who has the right to do the modification.
848 $super_user = S::user();
33a4f3f9
SJ
849 // group mailing lists
850 $group_domains = XDB::fetchColumn('SELECT g.mail_domain
851 FROM groups AS g
852 INNER JOIN group_members AS gm ON(g.id = gm.asso_id)
853 WHERE g.mail_domain != \'\' AND gm.uid = {?}',
854 $this->id());
855 foreach ($group_domains as $mail_domain) {
f7d43ed5 856 $mmlist = new MMList($super_user, $mail_domain);
06a548e5 857 $mmlist->replace_email_in_all($this->forlifeEmail(), $newuser->forlifeEmail());
33a4f3f9
SJ
858 }
859 // main domain lists
f7d43ed5 860 $mmlist = new MMList($super_user);
06a548e5 861 $mmlist->replace_email_in_all($this->forlifeEmail(), $newuser->forlifeEmail());
33a4f3f9
SJ
862 }
863 }
864
865 // Updates user in following tables.
7f376ae0 866 foreach (array('group_announces', 'payment_transactions', 'log_sessions', 'group_events') as $table) {
33a4f3f9
SJ
867 XDB::execute('UPDATE ' . $table . '
868 SET uid = {?}
869 WHERE uid = {?}',
870 $newuser->id(), $this->id());
871 }
33a4f3f9
SJ
872
873 // Merges user in following tables, ie updates when possible, then deletes remaining occurences of the old user.
06a548e5 874 foreach (array('group_announces_read', 'group_event_participants', 'group_member_sub_requests', 'group_members', 'email_redirect_account') as $table) {
33a4f3f9
SJ
875 XDB::execute('UPDATE IGNORE ' . $table . '
876 SET uid = {?}
877 WHERE uid = {?}',
878 $newuser->id(), $this->id());
879 XDB::execute('DELETE FROM ' . $table . '
880 WHERE uid = {?}',
881 $this->id());
882 }
ab06182d 883
33a4f3f9
SJ
884 // Eventually updates last session id and deletes old user's accounts entry.
885 $lastSession = XDB::fetchOneCell('SELECT id
886 FROM log_sessions
887 WHERE uid = {?}
888 ORDER BY start DESC
889 LIMIT 1',
890 $newuser->id());
891 XDB::execute('UPDATE log_last_sessions
892 SET id = {?}
893 WHERE uid = {?}',
be281b31 894 $lastSession, $newuser->id());
33a4f3f9
SJ
895 XDB::execute('DELETE FROM accounts
896 WHERE uid = {?}',
897 $this->id());
ab06182d
PC
898
899 return true;
900 }
901
50d5ec0b 902 // Return permission flags for a given permission level.
365ba8c3 903 public static function makePerms($perms, $is_admin)
50d5ec0b 904 {
365ba8c3 905 $flags = new PlFlagSet($perms);
365ba8c3 906 if ($is_admin) {
50d5ec0b
FB
907 $flags->addFlag(PERMS_ADMIN);
908 }
7fd6dbb3
FB
909
910 // Access to private directory implies access to 'less'-private version.
911 if ($flags->hasFlag('directory_private')) {
912 $flags->addFlag('directory_ax');
913 }
50d5ec0b
FB
914 return $flags;
915 }
916
b1719b13
VZ
917 // Implementation of the default user callback.
918 public static function _default_user_callback($login, $results)
919 {
b1719b13 920 $result_count = count($results);
dd70cd28 921 if ($result_count == 0 || !S::admin()) {
70232020 922 Platal::page()->trigError("Il n'y a pas d'utilisateur avec l'identifiant : $login");
b1719b13 923 } else {
70232020 924 Platal::page()->trigError("Il y a $result_count utilisateurs avec cet identifiant : " . join(', ', $results));
b1719b13
VZ
925 }
926 }
70232020 927
f88d9154
SJ
928 public static function makeHomonymHrmid($alias)
929 {
930 return 'h.' . $alias . '.' . Platal::globals()->mail->domain;
931 }
932
f036c896 933 public static function isMainMailDomain($domain)
70232020
VZ
934 {
935 global $globals;
70232020 936
f036c896
SJ
937 $is_main_domain = false;
938 foreach (self::$sub_mail_domains as $sub_domain) {
ca2f19b8 939 $is_main_domain = $is_main_domain || $domain == ($sub_domain . $globals->mail->domain) || $domain == ($sub_domain . $globals->mail->domain2);
f036c896
SJ
940 }
941 return $is_main_domain;
70232020 942 }
832e6fcb 943
f036c896 944 public static function isAliasMailDomain($domain)
aa21c568
FB
945 {
946 global $globals;
f036c896
SJ
947
948 return $domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2;
949 }
950
951 // Implementation of the static email locality checker.
952 public static function isForeignEmailAddress($email)
953 {
aa21c568
FB
954 if (strpos($email, '@') === false) {
955 return false;
956 }
957
f036c896
SJ
958 list(, $domain) = explode('@', $email);
959 return !(self::isMainMailDomain($domain) || self::isAliasMailDomain($domain));
aa21c568
FB
960 }
961
61a7d279
SJ
962 /* Tries to find pending accounts with an hruid close to $login. */
963 public static function getPendingAccounts($login, $iterator = false)
964 {
61a7d279
SJ
965 if (strpos($login, '@') === false) {
966 return null;
967 }
968
969 list($login, $domain) = explode('@', $login);
970
f036c896 971 if ($domain && !self::isMainMailDomain($domain)) {
61a7d279
SJ
972 return null;
973 }
974
975 $sql = "SELECT uid, full_name
976 FROM accounts
977 WHERE state = 'pending' AND REPLACE(hruid, '-', '') LIKE
978 CONCAT('%', REPLACE(REPLACE(REPLACE({?}, ' ', ''), '-', ''), '\'', ''), '%')
979 ORDER BY full_name";
980 if ($iterator) {
981 return XDB::iterator($sql, $login);
982 } else {
983 $res = XDB::query($sql, $login);
984 return $res->fetchAllAssoc();
985 }
986 }
987
988
0d906109
RB
989 public static function iterOverUIDs($uids, $respect_order = true)
990 {
991 return new UserIterator(self::loadMainFieldsFromUIDs($uids, $respect_order));
992 }
993
994 /** Fetch a set of users from a list of UIDs
995 * @param $data The list of uids to fetch, or an array of arrays
996 * @param $orig If $data is an array of arrays, the subfield where uids are stored
997 * @param $dest If $data is an array of arrays, the subfield to fill with Users
998 * @param $fetchProfile Whether to fetch Profiles as well
999 * @return either an array of $uid => User, or $data with $data[$i][$dest] = User
1000 */
b774ddab 1001 public static function getBulkUsersWithUIDs(array $data, $orig = null, $dest = null, $fetchProfile = true)
832e6fcb 1002 {
07eb5b0e
FB
1003 // Fetch the list of uids
1004 if (is_null($orig)) {
1005 $uids = $data;
1006 } else {
1007 if (is_null($dest)) {
1008 $dest = $orig;
1009 }
1010 $uids = array();
1011 foreach ($data as $key=>$entry) {
1012 if (isset($entry[$orig])) {
1013 $uids[] = $entry[$orig];
1014 }
1015 }
1016 }
1017
1018 // Fetch users
38c6fe96 1019 if (count($uids) == 0) {
07eb5b0e 1020 return $data;
38c6fe96 1021 }
0d906109
RB
1022 $users = self::iterOverUIDs($uids, true);
1023
d865c296 1024 $table = array();
b774ddab 1025 if ($fetchProfile) {
0d906109 1026 $profiles = Profile::iterOverUIDS($uids, true);
7a8da8e8
PC
1027 if ($profiles != null) {
1028 $profile = $profiles->next();
1029 } else {
1030 $profile = null;
1031 }
b774ddab 1032 }
0d906109
RB
1033
1034 /** We iterate through the users, moving in
1035 * profiles when they match the user ID :
1036 * there can be users without a profile, but not
1037 * the other way around.
1038 */
1039 while (($user = $users->next())) {
b774ddab 1040 if ($fetchProfile) {
7a8da8e8 1041 if ($profile != null && $profile->owner_id == $user->id()) {
0d906109
RB
1042 $user->_profile = $profile;
1043 $profile = $profiles->next();
b774ddab
FB
1044 }
1045 $user->_profile_fetched = true;
1046 }
0d906109 1047 $table[$user->id()] = $user;
d865c296 1048 }
07eb5b0e
FB
1049
1050 // Build the result with respect to input order.
1051 if (is_null($orig)) {
0d906109 1052 return $table;
07eb5b0e
FB
1053 } else {
1054 foreach ($data as $key=>$entry) {
1055 if (isset($entry[$orig])) {
1056 $entry[$dest] = $table[$entry[$orig]];
1057 $data[$key] = $entry;
1058 }
1059 }
1060 return $data;
832e6fcb 1061 }
07eb5b0e
FB
1062 }
1063
b774ddab 1064 public static function getBulkUsersFromDB($fetchProfile = true)
07eb5b0e
FB
1065 {
1066 $args = func_get_args();
1067 $uids = call_user_func_array(array('XDB', 'fetchColumn'), $args);
b774ddab 1068 return self::getBulkUsersWithUIDs($uids, null, null, $fetchProfile);
832e6fcb 1069 }
9f8ebb9f
VZ
1070}
1071
0d906109
RB
1072/** Iterator over a set of Users
1073 * @param an XDB::Iterator obtained from a User::loadMainFieldsFromUIDs
1074 */
1075class UserIterator implements PlIterator
1076{
1077 private $dbiter;
1078
1079 public function __construct($dbiter)
1080 {
1081 $this->dbiter = $dbiter;
1082 }
1083
1084 public function next()
1085 {
1086 $data = $this->dbiter->next();
1087 if ($data == null) {
1088 return null;
1089 } else {
1090 return User::getSilentWithValues(null, $data);
1091 }
1092 }
1093
1094 public function total()
1095 {
1096 return $this->dbiter->total();
1097 }
1098
1099 public function first()
1100 {
1101 return $this->dbiter->first();
1102 }
1103
1104 public function last()
1105 {
1106 return $this->dbiter->last();
1107 }
1108}
1109
448c8cdc 1110// vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8:
9f8ebb9f 1111?>