Fix to_forlife in list.rpc.py (Closes #1454)
[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.
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
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,
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,
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.%\')
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
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 347 /** Determines main email domain for this user.
3e53a496 348 */
f036c896 349 public function mainEmailDomain()
3e53a496 350 {
f036c896
SJ
351 if (array_key_exists($this->type, self::$sub_mail_domains)) {
352 return self::$sub_mail_domains[$this->type] . Platal::globals()->mail->domain;
8f2104cb 353 }
8f2104cb
FB
354 }
355
f036c896 356 /** Determines alternate email domain for this user.
8f2104cb 357 */
f036c896
SJ
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;
a6761ca9 362 }
f036c896
SJ
363 }
364
72e12532
SJ
365 public function forlifeEmailAlternate()
366 {
367 if (!empty($this->forlife_alternate)) {
368 return $this->forlife_alternate;
8f2104cb 369 }
72e12532 370 return $this->email;
3e53a496
FB
371 }
372
08d33afc 373 /** Fetch existing auxiliary alias.
3e53a496 374 */
3e53a496 375 public function emailAlias()
3e53a496 376 {
06a548e5
SJ
377 $aliases = $this->emailAliases();
378 if (count($aliases)) {
379 return $aliases[0];
8f2104cb
FB
380 }
381 return null;
e7b93962
FB
382 }
383
08d33afc 384 /** Fetch existing auxiliary aliases.
8f2104cb 385 */
06a548e5
SJ
386 public function emailAliases()
387 {
388 return XDB::fetchColumn('SELECT CONCAT(s.email, \'@\', d.name)
389 FROM email_source_account AS s
390 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
391 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
08d33afc 392 WHERE s.uid = {?} AND s.type = \'alias_aux\'
06a548e5 393 ORDER BY d.name',
08d33afc 394 $this->id());
3e53a496
FB
395 }
396
06a548e5 397 /** Get all group aliases the user belongs to.
3e53a496 398 */
06a548e5
SJ
399 public function emailGroupAliases($domain = null)
400 {
401 if (is_null($domain)) {
402 return XDB::fetchColumn('SELECT CONCAT(v.email, \'@\', dv.name) AS alias
403 FROM email_virtual AS v
404 INNER JOIN email_virtual_domains AS dv ON (v.domain = dv.id)
405 INNER JOIN email_source_account AS s ON (s.uid = {?})
406 INNER JOIN email_virtual_domains AS ms ON (s.domain = ms.id)
407 INNER JOIN email_virtual_domains AS ds ON (ds.aliasing = ms.id)
51c2c63a 408 WHERE v.redirect = CONCAT(s.email, \'@\', ds.name) AND v.type = \'alias\'',
06a548e5
SJ
409 $this->id());
410 } else {
a94fdc4e
SJ
411 return XDB::fetchAllAssoc('alias',
412 'SELECT CONCAT(v.email, \'@\', dv.name) AS alias, MAX(v.redirect = CONCAT(s.email, \'@\', ds.name)) AS sub
06a548e5
SJ
413 FROM email_virtual AS v
414 INNER JOIN email_virtual_domains AS dv ON (v.domain = dv.id AND dv.name = {?})
415 INNER JOIN email_source_account AS s ON (s.uid = {?})
416 INNER JOIN email_virtual_domains AS ms ON (s.domain = ms.id)
417 INNER JOIN email_virtual_domains AS ds ON (ds.aliasing = ms.id)
51c2c63a 418 WHERE v.type = \'alias\'
a94fdc4e
SJ
419 GROUP BY v.email
420 ORDER BY v.email',
06a548e5
SJ
421 $domain, $this->id());
422 }
e7b93962 423 }
38c6fe96
FB
424
425 /** Get marketing informations
426 */
427 private function fetchMarketingData()
428 {
db8432d5 429 if (isset($this->pending_registration_date)) {
38c6fe96
FB
430 return;
431 }
db8432d5
SJ
432 $infos = XDB::fetchOneAssoc('SELECT rp.date AS pending_registration_date, rp.email AS pending_registration_email,
433 rm.last AS last_marketing_date, rm.email AS last_marketing_email
434 FROM accounts AS a
435 LEFT JOIN register_pending AS rp ON (rp.uid = a.uid)
436 LEFT JOIN register_marketing AS rm ON (rm.uid = a.uid AND rm.last != \'0000-00-00\')
437 WHERE a.uid = {?}
438 ORDER BY rm.last DESC', $this->id());
439 if (is_null($infos)) {
440 $infos = array(
441 'pending_registration_date' => null,
442 'pending_registration_email' => null,
443 'last_marketing_date' => null,
444 'last_marketing_email' => null
445 );
38c6fe96
FB
446 }
447 $this->fillFromArray($infos);
448 }
449
db8432d5 450 public function pendingRegistrationDate()
38c6fe96
FB
451 {
452 $this->fetchMarketingData();
db8432d5
SJ
453 return $this->pending_registration_date;
454 }
455
456 public function pendingRegistrationEmail()
457 {
458 $this->fetchMarketingData();
459 return $this->pending_registration_email;
460 }
461
462 public function lastMarketingDate()
463 {
464 $this->fetchMarketingData();
465 return $this->last_marketing_date;
466 }
467
468 public function lastMarketingEmail()
469 {
470 $this->fetchMarketingData();
471 return $this->last_marketing_email;
38c6fe96
FB
472 }
473
474 public function lastKnownEmail()
475 {
476 $this->fetchMarketingData();
db8432d5
SJ
477 if ($this->pending_registration_email > $this->last_marketing_date) {
478 return $this->pending_registration_email;
479 }
480 return $this->last_marketing_email;
38c6fe96
FB
481 }
482
009b8ab7 483
8d308ee4
FB
484 /** Format of the emails sent by the site
485 */
486 public function setEmailFormat($format)
487 {
488 Platal::assert($format == self::FORMAT_HTML || $format == self::FORMAT_TEXT,
489 "Invalid email format \"$format\"");
490 XDB::execute("UPDATE accounts
491 SET email_format = {?}
492 WHERE uid = {?}",
493 $format, $this->uid);
494 $this->email_format = $format;
495 }
496
009b8ab7
FB
497 /** Get watch informations
498 */
499 private function fetchWatchData()
500 {
501 if (isset($this->watch_actions)) {
502 return;
503 }
504 $watch = XDB::fetchOneAssoc('SELECT flags AS watch_flags, actions AS watch_actions,
505 UNIX_TIMESTAMP(last) AS watch_last
506 FROM watch
507 WHERE uid = {?}', $this->id());
508 $watch['watch_flags'] = new PlFlagSet($watch['watch_flags']);
509 $watch['watch_actions'] = new PlFlagSet($watch['watch_actions']);
510 $watch['watch_promos'] = XDB::fetchColumn('SELECT promo
511 FROM watch_promo
512 WHERE uid = {?}', $this->id());
513 $watch['watch_users'] = XDB::fetchColumn('SELECT ni_id
514 FROM watch_nonins
515 WHERE uid = {?}', $this->id());
516 $this->fillFromArray($watch);
517 }
518
a87530ea 519 public function watchType($type)
009b8ab7
FB
520 {
521 $this->fetchWatchData();
522 return $this->watch_actions->hasFlag($type);
523 }
524
525 public function watchContacts()
526 {
527 $this->fetchWatchData();
528 return $this->watch_flags->hasFlag('contacts');
529 }
530
531 public function watchEmail()
532 {
533 $this->fetchWatchData();
534 return $this->watch_flags->hasFlag('mail');
535 }
536
537 public function watchPromos()
538 {
539 $this->fetchWatchData();
540 return $this->watch_promos;
541 }
542
543 public function watchUsers()
544 {
545 $this->fetchWatchData();
546 return $this->watch_users;
547 }
548
549 public function watchLast()
550 {
551 $this->fetchWatchData();
552 return $this->watch_last;
553 }
554
069ddda8
FB
555 public function invalidWatchCache()
556 {
557 unset($this->watch_actions);
558 unset($this->watch_users);
559 unset($this->watch_last);
560 unset($this->watch_promos);
561 }
562
c350577b
FB
563
564 // Contacts
565 private $contacts = null;
48e683dd 566 private function fetchContacts()
c350577b 567 {
76cbe885 568 if (is_null($this->contacts)) {
c350577b
FB
569 $this->contacts = XDB::fetchAllAssoc('contact', 'SELECT *
570 FROM contacts
571 WHERE uid = {?}',
572 $this->id());
573 }
48e683dd
FB
574 }
575
576 public function iterContacts()
577 {
578 $this->fetchContacts();
a289e967 579 return Profile::iterOverPIDs(array_keys($this->contacts));
48e683dd
FB
580 }
581
582 public function getContacts()
583 {
584 $this->fetchContacts();
a289e967 585 return Profile::getBulkProfilesWithPIDs(array_keys($this->contacts));
48e683dd
FB
586 }
587
26ba053e 588 public function isContact(Profile $profile)
48e683dd
FB
589 {
590 $this->fetchContacts();
a289e967 591 return isset($this->contacts[$profile->id()]);
c350577b
FB
592 }
593
26ba053e 594 public function isWatchedUser(Profile $profile)
958def08
PC
595 {
596 return in_array($profile->id(), $this->watchUsers());
597 }
598
f5ef8b57
RB
599 // Groupes X
600 private $groups = null;
56cd7aee 601 public function groups($institutions = false, $onlyPublic = false)
f5ef8b57
RB
602 {
603 if (is_null($this->groups)) {
56cd7aee
FB
604 $this->groups = XDB::fetchAllAssoc('asso_id', 'SELECT gm.asso_id, gm.perms, gm.comm,
605 g.diminutif, g.nom, g.site, g.cat,
606 g.pub
607 FROM group_members AS gm
608 INNER JOIN groups AS g ON (g.id = gm.asso_id)
f5ef8b57
RB
609 WHERE uid = {?}',
610 $this->id());
611 }
56cd7aee
FB
612 if (!$institutions && !$onlyPublic) {
613 return $this->groups;
fa589f90 614 } else {
56cd7aee
FB
615 $result = array();
616 foreach ($this->groups as $id=>$data) {
617 if ($institutions) {
1d889ac4 618 if ($data['cat'] != Group::CAT_GROUPESX && $data['cat'] != Group::CAT_INSTITUTIONS) {
56cd7aee
FB
619 continue;
620 }
621 }
622 if ($onlyPublic) {
623 if ($data['pub'] != 'public') {
624 continue;
625 }
626 }
627 $result[$id] = $data;
628 }
629 return $result;
fa589f90 630 }
fa589f90
RB
631 }
632
9a7f3d8e 633 public function groupCount()
4257b11a 634 {
9a7f3d8e
SJ
635 return XDB::fetchOneCell('SELECT COUNT(DISTINCT(asso_id))
636 FROM group_members
637 WHERE uid = {?}',
638 $this->id());
4257b11a
SJ
639 }
640
7ae5c545
SJ
641 public function inGroup($asso_id)
642 {
643 $res = XDB::fetchOneCell('SELECT COUNT(*)
644 FROM group_members
645 WHERE uid = {?} AND asso_id = {?}',
646 $this->id(), $asso_id);
647 return ($res > 0);
648 }
649
6150f591
SJ
650 /**
651 * Clears a user.
652 * *always deletes in: account_lost_passwords, register_marketing,
653 * register_pending, register_subs, watch_nonins, watch, watch_promo
06a548e5
SJ
654 * *always keeps in: account_types, accounts, email_virtual, carvas,
655 * group_members, homonyms_list, newsletter_ins, register_mstats, email_source_account
6150f591 656 * *deletes if $clearAll: account_auth_openid, announce_read, contacts,
06a548e5 657 * email_redirect_account, email_redirect_account, email_send_save, forum_innd, forum_profiles,
6150f591
SJ
658 * forum_subs, gapps_accounts, gapps_nicknames, group_announces_read,
659 * group_member_sub_requests, reminder, requests, requests_hidden,
06a548e5 660 * email_virtual, ML
6150f591
SJ
661 * *modifies if $clearAll: accounts
662 *
663 * Use cases:
664 * *$clearAll == false: when a user dies, her family still needs to keep in
665 * touch with the community.
666 * *$clearAll == true: in every other case we want the account to be fully
667 * deleted so that it can not be used anymore.
668 */
669 public function clear($clearAll = true)
670 {
405d70cc
RB
671 $tables = array('account_lost_passwords', 'register_marketing',
672 'register_pending', 'register_subs', 'watch_nonins',
673 'watch', 'watch_promo');
674
675 foreach ($tables as $t) {
676 XDB::execute('DELETE FROM ' . $t . '
677 WHERE uid = {?}',
678 $this->id());
679 }
6150f591
SJ
680
681 if ($clearAll) {
c79e28fc
SJ
682 global $globals;
683
0e5b3438
SJ
684 $groupIds = XDB::iterator('SELECT asso_id
685 FROM group_members
686 WHERE uid = {?}',
687 $this->id());
688 while ($groupId = $groupIds->next()) {
689 $group = Group::get($groupId);
c79e28fc 690 if (!empty($group) && $group->notif_unsub) {
0e5b3438
SJ
691 $mailer = new PlMailer('xnetgrp/unsubscription-notif.mail.tpl');
692 $admins = $group->iterAdmins();
693 while ($admin = $admins->next()) {
694 $mailer->addTo($admin);
695 }
696 $mailer->assign('group', $group->shortname);
697 $mailer->assign('user', $this);
698 $mailer->assign('selfdone', false);
699 $mailer->send();
700 }
701 }
702
c79e28fc 703 $tables = array('account_auth_openid', 'announce_read', 'contacts',
06a548e5 704 'email_send_save', 'email_virtual',
c79e28fc
SJ
705 'forum_innd', 'forum_profiles', 'forum_subs',
706 'group_announces_read', 'group_members',
707 'group_member_sub_requests', 'reminder', 'requests',
06a548e5 708 'requests_hidden');
405d70cc
RB
709 foreach ($tables as $t) {
710 XDB::execute('DELETE FROM ' . $t . '
711 WHERE uid = {?}',
c79e28fc
SJ
712 $this->id());
713 }
06a548e5
SJ
714 XDB::execute('DELETE FROM email_redirect_account
715 WHERE uid = {?} AND type != \'homonym\'',
716 $this->id());
c79e28fc
SJ
717
718 foreach (array('gapps_accounts', 'gapps_nicknames') as $t) {
719 XDB::execute('DELETE FROM ' . $t . '
720 WHERE l_userid = {?}',
721 $this->id());
405d70cc
RB
722 }
723
6150f591
SJ
724 XDB::execute("UPDATE accounts
725 SET registration_date = 0, state = 'pending', password = NULL,
726 weak_password = NULL, token = NULL, is_admin = 0
727 WHERE uid = {?}",
728 $this->id());
729
6150f591
SJ
730 if ($globals->mailstorage->googleapps_domain) {
731 require_once 'googleapps.inc.php';
732
c79e28fc
SJ
733 if (GoogleAppsAccount::account_status($this->id())) {
734 $account = new GoogleAppsAccount($this);
6150f591
SJ
735 $account->suspend();
736 }
737 }
738 }
739
dec84555 740 $mmlist = new MMList(S::user());
a85562a0 741 $mmlist->kill($this->hruid, $clearAll);
6150f591
SJ
742 }
743
ab06182d 744 // Merge all infos in other user and then clean this one
26ba053e 745 public function mergeIn(User $newuser) {
33a4f3f9
SJ
746 if ($this->profile()) {
747 // Don't disable user with profile in this way.
748 global $globals;
749 Platal::page()->trigError('Impossible de fusionner les comptes ' . $this->hruid . ' et ' . $newuser->hruid .
750 '. Contacte support@' . $globals->mail->domain . '.');
ab06182d
PC
751 return false;
752 }
ab06182d 753
33a4f3f9
SJ
754 if ($this->forlifeEmail()) {
755 // If the new user is not registered and does not have already an email address,
756 // we need to give him the old user's email address if he has any.
757 if (!$newuser->perms) {
758 XDB::execute('UPDATE accounts
759 SET email = {?}
760 WHERE uid = {?} AND email IS NULL',
761 $this->forlifeEmail(), $newuser->id());
06a548e5
SJ
762
763 // Reftech new user so its forlifeEmail will be correct.
764 $newuser = getSilentWithUID($newuser->id());
ab06182d 765 }
33a4f3f9 766
06a548e5
SJ
767 // Change email used in mailing lists.
768 if ($this->forlifeEmail() != $newuser->forlifeEmail()) {
33a4f3f9
SJ
769 // group mailing lists
770 $group_domains = XDB::fetchColumn('SELECT g.mail_domain
771 FROM groups AS g
772 INNER JOIN group_members AS gm ON(g.id = gm.asso_id)
773 WHERE g.mail_domain != \'\' AND gm.uid = {?}',
774 $this->id());
775 foreach ($group_domains as $mail_domain) {
776 $mmlist = new MMList($this, $mail_domain);
06a548e5 777 $mmlist->replace_email_in_all($this->forlifeEmail(), $newuser->forlifeEmail());
33a4f3f9
SJ
778 }
779 // main domain lists
780 $mmlist = new MMList($this);
06a548e5 781 $mmlist->replace_email_in_all($this->forlifeEmail(), $newuser->forlifeEmail());
33a4f3f9
SJ
782 }
783 }
784
785 // Updates user in following tables.
7f376ae0 786 foreach (array('group_announces', 'payment_transactions', 'log_sessions', 'group_events') as $table) {
33a4f3f9
SJ
787 XDB::execute('UPDATE ' . $table . '
788 SET uid = {?}
789 WHERE uid = {?}',
790 $newuser->id(), $this->id());
791 }
33a4f3f9
SJ
792
793 // Merges user in following tables, ie updates when possible, then deletes remaining occurences of the old user.
06a548e5 794 foreach (array('group_announces_read', 'group_event_participants', 'group_member_sub_requests', 'group_members', 'email_redirect_account') as $table) {
33a4f3f9
SJ
795 XDB::execute('UPDATE IGNORE ' . $table . '
796 SET uid = {?}
797 WHERE uid = {?}',
798 $newuser->id(), $this->id());
799 XDB::execute('DELETE FROM ' . $table . '
800 WHERE uid = {?}',
801 $this->id());
802 }
ab06182d 803
33a4f3f9
SJ
804 // Eventually updates last session id and deletes old user's accounts entry.
805 $lastSession = XDB::fetchOneCell('SELECT id
806 FROM log_sessions
807 WHERE uid = {?}
808 ORDER BY start DESC
809 LIMIT 1',
810 $newuser->id());
811 XDB::execute('UPDATE log_last_sessions
812 SET id = {?}
813 WHERE uid = {?}',
be281b31 814 $lastSession, $newuser->id());
33a4f3f9
SJ
815 XDB::execute('DELETE FROM accounts
816 WHERE uid = {?}',
817 $this->id());
ab06182d
PC
818
819 return true;
820 }
821
50d5ec0b 822 // Return permission flags for a given permission level.
365ba8c3 823 public static function makePerms($perms, $is_admin)
50d5ec0b 824 {
365ba8c3 825 $flags = new PlFlagSet($perms);
50d5ec0b 826 $flags->addFlag(PERMS_USER);
365ba8c3 827 if ($is_admin) {
50d5ec0b
FB
828 $flags->addFlag(PERMS_ADMIN);
829 }
7fd6dbb3
FB
830
831 // Access to private directory implies access to 'less'-private version.
832 if ($flags->hasFlag('directory_private')) {
833 $flags->addFlag('directory_ax');
834 }
50d5ec0b
FB
835 return $flags;
836 }
837
b1719b13
VZ
838 // Implementation of the default user callback.
839 public static function _default_user_callback($login, $results)
840 {
b1719b13 841 $result_count = count($results);
dd70cd28 842 if ($result_count == 0 || !S::admin()) {
70232020 843 Platal::page()->trigError("Il n'y a pas d'utilisateur avec l'identifiant : $login");
b1719b13 844 } else {
70232020 845 Platal::page()->trigError("Il y a $result_count utilisateurs avec cet identifiant : " . join(', ', $results));
b1719b13
VZ
846 }
847 }
70232020 848
f88d9154
SJ
849 public static function makeHomonymHrmid($alias)
850 {
851 return 'h.' . $alias . '.' . Platal::globals()->mail->domain;
852 }
853
f036c896 854 public static function isMainMailDomain($domain)
70232020
VZ
855 {
856 global $globals;
70232020 857
f036c896
SJ
858 $is_main_domain = false;
859 foreach (self::$sub_mail_domains as $sub_domain) {
3f7c719e 860 $is_main_domain = $is_main_domain || $domain == ($sub_domain . $globals->mail->domain) && $domain == ($sub_domain . $globals->mail->domain2);
f036c896
SJ
861 }
862 return $is_main_domain;
70232020 863 }
832e6fcb 864
f036c896 865 public static function isAliasMailDomain($domain)
aa21c568
FB
866 {
867 global $globals;
f036c896
SJ
868
869 return $domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2;
870 }
871
872 // Implementation of the static email locality checker.
873 public static function isForeignEmailAddress($email)
874 {
aa21c568
FB
875 if (strpos($email, '@') === false) {
876 return false;
877 }
878
f036c896
SJ
879 list(, $domain) = explode('@', $email);
880 return !(self::isMainMailDomain($domain) || self::isAliasMailDomain($domain));
aa21c568
FB
881 }
882
61a7d279
SJ
883 /* Tries to find pending accounts with an hruid close to $login. */
884 public static function getPendingAccounts($login, $iterator = false)
885 {
61a7d279
SJ
886 if (strpos($login, '@') === false) {
887 return null;
888 }
889
890 list($login, $domain) = explode('@', $login);
891
f036c896 892 if ($domain && !self::isMainMailDomain($domain)) {
61a7d279
SJ
893 return null;
894 }
895
896 $sql = "SELECT uid, full_name
897 FROM accounts
898 WHERE state = 'pending' AND REPLACE(hruid, '-', '') LIKE
899 CONCAT('%', REPLACE(REPLACE(REPLACE({?}, ' ', ''), '-', ''), '\'', ''), '%')
900 ORDER BY full_name";
901 if ($iterator) {
902 return XDB::iterator($sql, $login);
903 } else {
904 $res = XDB::query($sql, $login);
905 return $res->fetchAllAssoc();
906 }
907 }
908
909
0d906109
RB
910 public static function iterOverUIDs($uids, $respect_order = true)
911 {
912 return new UserIterator(self::loadMainFieldsFromUIDs($uids, $respect_order));
913 }
914
915 /** Fetch a set of users from a list of UIDs
916 * @param $data The list of uids to fetch, or an array of arrays
917 * @param $orig If $data is an array of arrays, the subfield where uids are stored
918 * @param $dest If $data is an array of arrays, the subfield to fill with Users
919 * @param $fetchProfile Whether to fetch Profiles as well
920 * @return either an array of $uid => User, or $data with $data[$i][$dest] = User
921 */
b774ddab 922 public static function getBulkUsersWithUIDs(array $data, $orig = null, $dest = null, $fetchProfile = true)
832e6fcb 923 {
07eb5b0e
FB
924 // Fetch the list of uids
925 if (is_null($orig)) {
926 $uids = $data;
927 } else {
928 if (is_null($dest)) {
929 $dest = $orig;
930 }
931 $uids = array();
932 foreach ($data as $key=>$entry) {
933 if (isset($entry[$orig])) {
934 $uids[] = $entry[$orig];
935 }
936 }
937 }
938
939 // Fetch users
38c6fe96 940 if (count($uids) == 0) {
07eb5b0e 941 return $data;
38c6fe96 942 }
0d906109
RB
943 $users = self::iterOverUIDs($uids, true);
944
d865c296 945 $table = array();
b774ddab 946 if ($fetchProfile) {
0d906109 947 $profiles = Profile::iterOverUIDS($uids, true);
7a8da8e8
PC
948 if ($profiles != null) {
949 $profile = $profiles->next();
950 } else {
951 $profile = null;
952 }
b774ddab 953 }
0d906109
RB
954
955 /** We iterate through the users, moving in
956 * profiles when they match the user ID :
957 * there can be users without a profile, but not
958 * the other way around.
959 */
960 while (($user = $users->next())) {
b774ddab 961 if ($fetchProfile) {
7a8da8e8 962 if ($profile != null && $profile->owner_id == $user->id()) {
0d906109
RB
963 $user->_profile = $profile;
964 $profile = $profiles->next();
b774ddab
FB
965 }
966 $user->_profile_fetched = true;
967 }
0d906109 968 $table[$user->id()] = $user;
d865c296 969 }
07eb5b0e
FB
970
971 // Build the result with respect to input order.
972 if (is_null($orig)) {
0d906109 973 return $table;
07eb5b0e
FB
974 } else {
975 foreach ($data as $key=>$entry) {
976 if (isset($entry[$orig])) {
977 $entry[$dest] = $table[$entry[$orig]];
978 $data[$key] = $entry;
979 }
980 }
981 return $data;
832e6fcb 982 }
07eb5b0e
FB
983 }
984
b774ddab 985 public static function getBulkUsersFromDB($fetchProfile = true)
07eb5b0e
FB
986 {
987 $args = func_get_args();
988 $uids = call_user_func_array(array('XDB', 'fetchColumn'), $args);
b774ddab 989 return self::getBulkUsersWithUIDs($uids, null, null, $fetchProfile);
832e6fcb 990 }
9f8ebb9f
VZ
991}
992
0d906109
RB
993/** Iterator over a set of Users
994 * @param an XDB::Iterator obtained from a User::loadMainFieldsFromUIDs
995 */
996class UserIterator implements PlIterator
997{
998 private $dbiter;
999
1000 public function __construct($dbiter)
1001 {
1002 $this->dbiter = $dbiter;
1003 }
1004
1005 public function next()
1006 {
1007 $data = $this->dbiter->next();
1008 if ($data == null) {
1009 return null;
1010 } else {
1011 return User::getSilentWithValues(null, $data);
1012 }
1013 }
1014
1015 public function total()
1016 {
1017 return $this->dbiter->total();
1018 }
1019
1020 public function first()
1021 {
1022 return $this->dbiter->first();
1023 }
1024
1025 public function last()
1026 {
1027 return $this->dbiter->last();
1028 }
1029}
1030
9f8ebb9f
VZ
1031// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1032?>