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