Enables watch of groups (Closes #808).
[platal.git] / classes / user.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
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
22 class User extends PlUser
23 {
24 const PERM_API_USER_READONLY = 'api_user_readonly';
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';
29 const PERM_GROUPS = 'groups';
30 const PERM_LISTS = 'lists';
31 const PERM_MAIL = 'mail';
32 const PERM_PAYMENT = 'payment';
33
34 public static $sub_mail_domains = array(
35 'x' => '',
36 'master' => 'master.',
37 'phd' => 'doc.',
38 'all' => 'alumni.'
39 );
40
41 private $_profile_fetched = false;
42 private $_profile = null;
43
44 // Additional fields (non core)
45 protected $promo = null;
46
47 // Implementation of the login to uid method.
48 protected function getLogin($login)
49 {
50 global $globals;
51
52 if (!$login) {
53 throw new UserNotFoundException();
54 }
55
56 if ($login instanceof User) {
57 return $login->id();
58 }
59
60 if ($login instanceof Profile) {
61 $this->_profile = $login;
62 $this->_profile_fetched = true;
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
73 // If $data is an integer, fetches directly the result.
74 if (is_numeric($login)) {
75 $res = XDB::query('SELECT uid
76 FROM accounts
77 WHERE uid = {?}', $login);
78 if ($res->numRows()) {
79 return $res->fetchOneCell();
80 }
81
82 throw new UserNotFoundException();
83 }
84
85 // Checks whether $login is a valid hruid or not.
86 $res = XDB::query('SELECT uid
87 FROM accounts
88 WHERE hruid = {?}', $login);
89 if ($res->numRows()) {
90 return $res->fetchOneCell();
91 }
92
93 // From now, $login can only by an email alias, or an email redirection.
94 $login = trim(strtolower($login));
95 if (strstr($login, '@') === false) {
96 $res = XDB::fetchOneCell('SELECT uid
97 FROM email_source_account
98 WHERE email = {?}',
99 $login);
100 } else {
101 list($email, $domain) = explode('@', $login);
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);
108 }
109
110 if ($res) {
111 return $res;
112 }
113
114 // Looks for an account with the given email.
115 $res = XDB::query('SELECT uid
116 FROM accounts
117 WHERE email = {?}', $login);
118 if ($res->numRows() == 1) {
119 return $res->fetchOneCell();
120 }
121
122 // Otherwise, we do suppose $login is an email redirection.
123 $res = XDB::query('SELECT uid
124 FROM email_redirect_account
125 WHERE redirect = {?}', $login);
126 if ($res->numRows() == 1) {
127 return $res->fetchOneCell();
128 }
129
130 throw new UserNotFoundException($res->fetchColumn(1));
131 }
132
133 protected static function loadMainFieldsFromUIDs(array $uids, $respect_order = true)
134 {
135 if (empty($uids)) {
136 return PlIteratorUtils::emptyIterator();
137 }
138
139 global $globals;
140 $joins = '';
141 $fields = array();
142 if ($globals->asso('id')) {
143 $joins .= XDB::format("LEFT JOIN group_members AS gpm ON (gpm.uid = a.uid AND gpm.asso_id = {?})\n", $globals->asso('id'));
144 $fields[] = 'gpm.perms AS group_perms';
145 $fields[] = 'gpm.comm AS group_comm';
146 $fields[] = 'gpm.position AS group_position';
147 }
148 if (count($fields) > 0) {
149 $fields = ', ' . implode(', ', $fields);
150 } else {
151 $fields = '';
152 }
153
154 if ($respect_order) {
155 $order = 'ORDER BY ' . XDB::formatCustomOrder('a.uid', $uids);
156 } else {
157 $order = '';
158 }
159
160 $uids = array_map(array('XDB', 'escape'), $uids);
161
162 return XDB::iterator('SELECT a.uid, a.hruid, a.registration_date, h.uid IS NOT NULL AS homonym, a.firstname, a.lastname,
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,
166 (er.redirect IS NULL AND a.state = \'active\' AND FIND_IN_SET(\'mail\', at.perms)) AS lost,
167 a.email, a.full_name, a.directory_name, a.display_name, a.sex = \'female\' AS gender,
168 IF(a.state = \'active\', CONCAT(at.perms, \',\', IF(a.user_perms IS NULL, \'\', a.user_perms)), \'\') AS perms,
169 a.user_perms, a.email_format, a.is_admin, a.state, a.type, at.description AS type_description, a.skin,
170 FIND_IN_SET(\'watch\', a.flags) AS watch, a.comment,
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,
173 UNIX_TIMESTAMP(s.start) AS lastlogin, s.host, UNIX_TIMESTAMP(fp.last_seen) AS banana_last
174 ' . $fields . '
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)
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.%\')
181 LEFT JOIN email_source_account AS eb ON (eb.uid = a.uid AND FIND_IN_SET(\'bestalias\',eb.flags))
182 LEFT JOIN email_virtual_domains AS mb ON (a.best_domain = mb.id)
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)
190 ' . $joins . '
191 WHERE a.uid IN (' . implode(', ', $uids) . ')
192 GROUP BY a.uid
193 ' . $order, $globals->mail->domain2, $globals->mail->domain2);
194 }
195
196 // Implementation of the data loader.
197 protected function loadMainFields()
198 {
199 if ($this->hruid !== null && $this->forlife !== null
200 && $this->bestalias !== null && $this->display_name !== null
201 && $this->full_name !== null && $this->perms !== null
202 && $this->gender !== null && $this->email_format !== null) {
203 return;
204 }
205 $this->fillFromArray(self::loadMainFieldsFromUIDs(array($this->uid))->next());
206 }
207
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 }
219 $this->perm_flags = self::makePerms($this->perms, $this->is_admin);
220 }
221
222 public function setPerms($perms)
223 {
224 $this->perms = $perms;
225 $this->perm_flags = null;
226 }
227
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 {
239 $level = Visibility::VIEW_NONE;
240 if ($this->is_admin) {
241 $level = Visibility::VIEW_ADMIN;
242 } elseif ($this->checkPerms('directory_private')) {
243 $level = Visibility::VIEW_PRIVATE;
244 } elseif ($this->checkPerms('directory_ax')) {
245 $level = Visibility::VIEW_AX;
246 } else {
247 $level = Visibility::VIEW_PUBLIC;
248 }
249 return Visibility::get($level);
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
257 * - If someone has 'directory_edit' (which is actually directory_ax_edit): AX level
258 * - Otherwise, nothing.
259 */
260 public function editVisibility()
261 {
262 $level = Visibility::VIEW_NONE;
263 if ($this->is_admin) {
264 $level = Visibility::VIEW_ADMIN;
265 } elseif ($this->checkPerms('directory_edit')) {
266 $level = Visibility::VIEW_AX;
267 }
268 return Visibility::get($level);
269 }
270
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
280 public function isActive()
281 {
282 return $this->state == 'active';
283 }
284
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
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
306 public function firstName()
307 {
308 if (!$this->hasProfile()) {
309 return $this->displayName();
310 }
311 return $this->profile()->firstName();
312 }
313
314 public function lastName()
315 {
316 if (!$this->hasProfile()) {
317 return '';
318 }
319 return $this->profile()->lastName();
320 }
321
322 public function displayName()
323 {
324 if (!$this->hasProfile()) {
325 return $this->display_name;
326 }
327 return $this->profile()->yourself;
328 }
329
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
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
346 public function directoryName()
347 {
348 if (!$this->hasProfile()) {
349 return $this->directory_name;
350 }
351 return $this->profile()->directory_name;
352 }
353
354 static public function compareDirectoryName($a, $b)
355 {
356 return strcasecmp(replace_accent($a->directoryName()), replace_accent($b->directoryName()));
357 }
358
359 /** Return the main profile attached with this account if any.
360 */
361 public function profile($forceFetch = false, $fields = 0x0000, $visibility = null)
362 {
363 if (!$this->_profile_fetched || $forceFetch) {
364 $this->_profile_fetched = true;
365 $this->_profile = Profile::get($this, $fields, $visibility);
366 } else if ($this->_profile !== null && !$this->_profile->visibility->equals($visibility)) {
367 return Profile::get($this, $fields, $visibility);
368 }
369 return $this->_profile;
370 }
371
372 /** Return true if the user has an associated profile.
373 */
374 public function hasProfile()
375 {
376 return !is_null($this->profile());
377 }
378
379 /** Return true if given a reference to the profile of this user.
380 */
381 public function isMyProfile($other)
382 {
383 if (!$other) {
384 return false;
385 } else if ($other instanceof Profile) {
386 $profile = $this->profile();
387 return $profile && $profile->id() == $other->id();
388 }
389 return false;
390 }
391
392 /** Check if the user can edit to given profile.
393 */
394 public function canEdit(Profile $profile)
395 {
396 if ($this->checkPerms(User::PERM_EDIT_DIRECTORY)) {
397 return true;
398 }
399 return XDB::fetchOneCell('SELECT pid
400 FROM account_profiles
401 WHERE uid = {?} AND pid = {?}',
402 $this->id(), $profile->id());
403 }
404
405 /** Determines main email domain for this user.
406 */
407 public function mainEmailDomain()
408 {
409 if (array_key_exists($this->type, self::$sub_mail_domains)) {
410 return self::$sub_mail_domains[$this->type] . Platal::globals()->mail->domain;
411 }
412 }
413
414 /** Determines alternate email domain for this user.
415 */
416 public function alternateEmailDomain()
417 {
418 if (array_key_exists($this->type, self::$sub_mail_domains)) {
419 return self::$sub_mail_domains[$this->type] . Platal::globals()->mail->domain2;
420 }
421 }
422
423 public function forlifeEmailAlternate()
424 {
425 if (!empty($this->forlife_alternate)) {
426 return $this->forlife_alternate;
427 }
428 return $this->email;
429 }
430
431 /** Fetch existing auxiliary alias.
432 */
433 public function emailAlias()
434 {
435 $aliases = $this->emailAliases();
436 if (count($aliases)) {
437 return $aliases[0];
438 }
439 return null;
440 }
441
442 /** Fetch existing auxiliary aliases.
443 */
444 public function emailAliases()
445 {
446 return XDB::fetchColumn('SELECT CONCAT(s.email, \'@\', d.name)
447 FROM email_source_account AS s
448 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
449 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
450 WHERE s.uid = {?} AND s.type = \'alias_aux\'
451 ORDER BY d.name',
452 $this->id());
453 }
454
455 /** Get all group aliases the user belongs to.
456 */
457 public function emailGroupAliases($domain = null)
458 {
459 if (is_null($domain)) {
460 return XDB::fetchColumn('SELECT CONCAT(v.email, \'@\', dv.name) AS alias
461 FROM email_virtual AS v
462 INNER JOIN email_virtual_domains AS dv ON (v.domain = dv.id)
463 INNER JOIN email_source_account AS s ON (s.uid = {?})
464 INNER JOIN email_virtual_domains AS ms ON (s.domain = ms.id)
465 INNER JOIN email_virtual_domains AS ds ON (ds.aliasing = ms.id)
466 WHERE v.redirect = CONCAT(s.email, \'@\', ds.name) AND v.type = \'alias\'',
467 $this->id());
468 } else {
469 return XDB::fetchAllAssoc('alias',
470 'SELECT CONCAT(v.email, \'@\', dv.name) AS alias, MAX(v.redirect = CONCAT(s.email, \'@\', ds.name)) AS sub
471 FROM email_virtual AS v
472 INNER JOIN email_virtual_domains AS dv ON (v.domain = dv.id AND dv.name = {?})
473 INNER JOIN email_source_account AS s ON (s.uid = {?})
474 INNER JOIN email_virtual_domains AS ms ON (s.domain = ms.id)
475 INNER JOIN email_virtual_domains AS ds ON (ds.aliasing = ms.id)
476 WHERE v.type = \'alias\'
477 GROUP BY v.email
478 ORDER BY v.email',
479 $domain, $this->id());
480 }
481 }
482
483 /** Get marketing informations
484 */
485 private function fetchMarketingData()
486 {
487 if (isset($this->pending_registration_date)) {
488 return;
489 }
490 $infos = XDB::fetchOneAssoc('SELECT rp.date AS pending_registration_date, rp.email AS pending_registration_email,
491 rm.last AS last_marketing_date, rm.email AS last_marketing_email
492 FROM accounts AS a
493 LEFT JOIN register_pending AS rp ON (rp.uid = a.uid)
494 LEFT JOIN register_marketing AS rm ON (rm.uid = a.uid AND rm.last != \'0000-00-00\')
495 WHERE a.uid = {?}
496 ORDER BY rm.last DESC', $this->id());
497 if (is_null($infos)) {
498 $infos = array(
499 'pending_registration_date' => null,
500 'pending_registration_email' => null,
501 'last_marketing_date' => null,
502 'last_marketing_email' => null
503 );
504 }
505 $this->fillFromArray($infos);
506 }
507
508 public function pendingRegistrationDate()
509 {
510 $this->fetchMarketingData();
511 return $this->pending_registration_date;
512 }
513
514 public function pendingRegistrationEmail()
515 {
516 $this->fetchMarketingData();
517 return $this->pending_registration_email;
518 }
519
520 public function lastMarketingDate()
521 {
522 $this->fetchMarketingData();
523 return $this->last_marketing_date;
524 }
525
526 public function lastMarketingEmail()
527 {
528 $this->fetchMarketingData();
529 return $this->last_marketing_email;
530 }
531
532 public function lastKnownEmail()
533 {
534 $this->fetchMarketingData();
535 if ($this->pending_registration_email > $this->last_marketing_date) {
536 return $this->pending_registration_email;
537 }
538 return $this->last_marketing_email;
539 }
540
541
542 /** Format of the emails sent by the site
543 */
544 public function setEmailFormat($format)
545 {
546 Platal::assert($format == self::FORMAT_HTML || $format == self::FORMAT_TEXT,
547 "Invalid email format \"$format\"");
548 XDB::execute("UPDATE accounts
549 SET email_format = {?}
550 WHERE uid = {?}",
551 $format, $this->uid);
552 $this->email_format = $format;
553 }
554
555 /** Get watch informations
556 */
557 private function fetchWatchData()
558 {
559 if (isset($this->watch_actions)) {
560 return;
561 }
562 $watch = XDB::fetchOneAssoc('SELECT flags AS watch_flags, actions AS watch_actions,
563 UNIX_TIMESTAMP(last) AS watch_last
564 FROM watch
565 WHERE uid = {?}', $this->id());
566 $watch['watch_flags'] = new PlFlagSet($watch['watch_flags']);
567 $watch['watch_actions'] = new PlFlagSet($watch['watch_actions']);
568 $watch['watch_promos'] = XDB::fetchColumn('SELECT promo
569 FROM watch_promo
570 WHERE uid = {?}', $this->id());
571 $watch['watch_groups'] = XDB::fetchColumn("SELECT w.groupid
572 FROM watch_group AS w
573 INNER JOIN groups AS g ON (w.groupid = g.id AND NOT FIND_IN_SET('private', pub))
574 WHERE w.uid = {?}", $this->id());
575 $watch['watch_users'] = XDB::fetchColumn('SELECT ni_id
576 FROM watch_nonins
577 WHERE uid = {?}', $this->id());
578 $this->fillFromArray($watch);
579 }
580
581 public function watchType($type)
582 {
583 $this->fetchWatchData();
584 return $this->watch_actions->hasFlag($type);
585 }
586
587 public function watchContacts()
588 {
589 $this->fetchWatchData();
590 return $this->watch_flags->hasFlag('contacts');
591 }
592
593 public function watchEmail()
594 {
595 $this->fetchWatchData();
596 return $this->watch_flags->hasFlag('mail');
597 }
598
599 public function watchPromos()
600 {
601 $this->fetchWatchData();
602 return $this->watch_promos;
603 }
604
605 public function watchGroups()
606 {
607 $this->fetchWatchData();
608 return $this->watch_groups;
609 }
610
611 public function watchUsers()
612 {
613 $this->fetchWatchData();
614 return $this->watch_users;
615 }
616
617 public function watchLast()
618 {
619 $this->fetchWatchData();
620 return $this->watch_last;
621 }
622
623 public function invalidWatchCache()
624 {
625 unset($this->watch_actions);
626 unset($this->watch_users);
627 unset($this->watch_last);
628 unset($this->watch_promos);
629 unset($this->watch_groups);
630 }
631
632
633 // Contacts
634 private $contacts = null;
635 private function fetchContacts()
636 {
637 if (is_null($this->contacts)) {
638 $this->contacts = XDB::fetchAllAssoc('contact', 'SELECT *
639 FROM contacts
640 WHERE uid = {?}',
641 $this->id());
642 }
643 }
644
645 public function iterContacts()
646 {
647 $this->fetchContacts();
648 return Profile::iterOverPIDs(array_keys($this->contacts));
649 }
650
651 public function getContacts()
652 {
653 $this->fetchContacts();
654 return Profile::getBulkProfilesWithPIDs(array_keys($this->contacts));
655 }
656
657 public function isContact(Profile $profile)
658 {
659 $this->fetchContacts();
660 return isset($this->contacts[$profile->id()]);
661 }
662
663 public function isWatchedUser(Profile $profile)
664 {
665 return in_array($profile->id(), $this->watchUsers());
666 }
667
668 // Groupes X
669 private $groups = null;
670 public function groups($institutions = false, $onlyPublic = false)
671 {
672 if (is_null($this->groups)) {
673 $this->groups = XDB::fetchAllAssoc('asso_id', 'SELECT gm.asso_id, gm.perms, gm.comm,
674 g.diminutif, g.nom, g.site, g.cat,
675 g.pub
676 FROM group_members AS gm
677 INNER JOIN groups AS g ON (g.id = gm.asso_id)
678 WHERE uid = {?}',
679 $this->id());
680 }
681 if (!$institutions && !$onlyPublic) {
682 return $this->groups;
683 } else {
684 $result = array();
685 foreach ($this->groups as $id=>$data) {
686 if ($institutions) {
687 if ($data['cat'] != Group::CAT_GROUPESX && $data['cat'] != Group::CAT_INSTITUTIONS) {
688 continue;
689 }
690 }
691 if ($onlyPublic) {
692 if ($data['pub'] != 'public') {
693 continue;
694 }
695 }
696 $result[$id] = $data;
697 }
698 return $result;
699 }
700 }
701
702 public function groupCount()
703 {
704 return XDB::fetchOneCell('SELECT COUNT(DISTINCT(asso_id))
705 FROM group_members
706 WHERE uid = {?}',
707 $this->id());
708 }
709
710 public function inGroup($asso_id)
711 {
712 $res = XDB::fetchOneCell('SELECT COUNT(*)
713 FROM group_members
714 WHERE uid = {?} AND asso_id = {?}',
715 $this->id(), $asso_id);
716 return ($res > 0);
717 }
718
719 /**
720 * Clears a user.
721 * *always deletes in: account_lost_passwords, register_marketing,
722 * register_pending, register_subs, watch_nonins, watch, watch_promo, watch_group,
723 * *always keeps in: account_types, accounts, email_virtual, carvas,
724 * group_members, homonyms_list, newsletter_ins, register_mstats, email_source_account
725 * *deletes if $clearAll: account_auth_openid, announce_read, contacts,
726 * email_redirect_account, email_redirect_account, email_send_save, forum_innd, forum_profiles,
727 * forum_subs, gapps_accounts, gapps_nicknames, group_announces_read,
728 * group_member_sub_requests, reminder, requests, requests_hidden,
729 * email_virtual, ML
730 * *modifies if $clearAll: accounts
731 *
732 * Use cases:
733 * *$clearAll == false: when a user dies, her family still needs to keep in
734 * touch with the community.
735 * *$clearAll == true: in every other case we want the account to be fully
736 * deleted so that it can not be used anymore.
737 */
738 public function clear($clearAll = true)
739 {
740 $tables = array('account_lost_passwords', 'register_marketing',
741 'register_pending', 'register_subs', 'watch_nonins',
742 'watch', 'watch_promo', 'watch_group');
743
744 foreach ($tables as $t) {
745 XDB::execute('DELETE FROM ' . $t . '
746 WHERE uid = {?}',
747 $this->id());
748 }
749
750 if ($clearAll) {
751 global $globals;
752
753 $groupIds = XDB::iterator('SELECT asso_id
754 FROM group_members
755 WHERE uid = {?}',
756 $this->id());
757 while ($groupId = $groupIds->next()) {
758 $group = Group::get($groupId);
759 if (!empty($group) && $group->notif_unsub) {
760 $mailer = new PlMailer('xnetgrp/unsubscription-notif.mail.tpl');
761 $admins = $group->iterAdmins();
762 while ($admin = $admins->next()) {
763 $mailer->addTo($admin);
764 }
765 $mailer->assign('group', $group->shortname);
766 $mailer->assign('user', $this);
767 $mailer->assign('selfdone', false);
768 $mailer->send();
769 }
770 }
771
772 $tables = array('account_auth_openid', 'announce_read', 'contacts',
773 'email_send_save',
774 'forum_innd', 'forum_profiles', 'forum_subs',
775 'group_announces_read', 'group_members',
776 'group_member_sub_requests', 'reminder', 'requests',
777 'requests_hidden');
778 foreach ($tables as $t) {
779 XDB::execute('DELETE FROM ' . $t . '
780 WHERE uid = {?}',
781 $this->id());
782 }
783 XDB::execute('DELETE FROM email_redirect_account
784 WHERE uid = {?} AND type != \'homonym\'',
785 $this->id());
786 XDB::execute('DELETE FROM email_virtual
787 WHERE redirect = {?}',
788 $this->forlifeEmail());
789
790 foreach (array('gapps_accounts', 'gapps_nicknames') as $t) {
791 XDB::execute('DELETE FROM ' . $t . '
792 WHERE l_userid = {?}',
793 $this->id());
794 }
795
796 XDB::execute("UPDATE accounts
797 SET registration_date = 0, state = 'pending', password = NULL,
798 weak_password = NULL, token = NULL, is_admin = 0
799 WHERE uid = {?}",
800 $this->id());
801
802 if ($globals->mailstorage->googleapps_domain) {
803 require_once 'googleapps.inc.php';
804
805 if (GoogleAppsAccount::account_status($this->id())) {
806 $account = new GoogleAppsAccount($this);
807 $account->suspend();
808 }
809 }
810 }
811
812 $mmlist = new MMList(S::user());
813 $mmlist->kill($this->hruid, $clearAll);
814 }
815
816 // Merge all infos in other user and then clean this one
817 public function mergeIn(User $newuser) {
818 if ($this->profile()) {
819 // Don't disable user with profile in this way.
820 global $globals;
821 Platal::page()->trigError('Impossible de fusionner les comptes ' . $this->hruid . ' et ' . $newuser->hruid .
822 '. Contacte support@' . $globals->mail->domain . '.');
823 return false;
824 }
825
826 if ($this->forlifeEmail()) {
827 // If the new user is not registered and does not have already an email address,
828 // we need to give him the old user's email address if he has any.
829 if (!$newuser->perms) {
830 XDB::execute('UPDATE accounts
831 SET email = {?}
832 WHERE uid = {?} AND email IS NULL',
833 $this->forlifeEmail(), $newuser->id());
834
835 // Reftech new user so its forlifeEmail will be correct.
836 $newuser = self::getSilentWithUID($newuser->id());
837 }
838
839 // Change email used in mailing lists.
840 if ($this->forlifeEmail() != $newuser->forlifeEmail()) {
841 // The super user is the user who has the right to do the modification.
842 $super_user = S::user();
843 // group mailing lists
844 $group_domains = XDB::fetchColumn('SELECT g.mail_domain
845 FROM groups AS g
846 INNER JOIN group_members AS gm ON(g.id = gm.asso_id)
847 WHERE g.mail_domain != \'\' AND gm.uid = {?}',
848 $this->id());
849 foreach ($group_domains as $mail_domain) {
850 $mmlist = new MMList($super_user, $mail_domain);
851 $mmlist->replace_email_in_all($this->forlifeEmail(), $newuser->forlifeEmail());
852 }
853 // main domain lists
854 $mmlist = new MMList($super_user);
855 $mmlist->replace_email_in_all($this->forlifeEmail(), $newuser->forlifeEmail());
856 }
857 }
858
859 // Updates user in following tables.
860 foreach (array('group_announces', 'payment_transactions', 'log_sessions', 'group_events') as $table) {
861 XDB::execute('UPDATE ' . $table . '
862 SET uid = {?}
863 WHERE uid = {?}',
864 $newuser->id(), $this->id());
865 }
866
867 // Merges user in following tables, ie updates when possible, then deletes remaining occurences of the old user.
868 foreach (array('group_announces_read', 'group_event_participants', 'group_member_sub_requests', 'group_members', 'email_redirect_account') as $table) {
869 XDB::execute('UPDATE IGNORE ' . $table . '
870 SET uid = {?}
871 WHERE uid = {?}',
872 $newuser->id(), $this->id());
873 XDB::execute('DELETE FROM ' . $table . '
874 WHERE uid = {?}',
875 $this->id());
876 }
877
878 // Eventually updates last session id and deletes old user's accounts entry.
879 $lastSession = XDB::fetchOneCell('SELECT id
880 FROM log_sessions
881 WHERE uid = {?}
882 ORDER BY start DESC
883 LIMIT 1',
884 $newuser->id());
885 XDB::execute('UPDATE log_last_sessions
886 SET id = {?}
887 WHERE uid = {?}',
888 $lastSession, $newuser->id());
889 XDB::execute('DELETE FROM accounts
890 WHERE uid = {?}',
891 $this->id());
892
893 return true;
894 }
895
896 // Return permission flags for a given permission level.
897 public static function makePerms($perms, $is_admin)
898 {
899 $flags = new PlFlagSet($perms);
900 if ($is_admin) {
901 $flags->addFlag(PERMS_ADMIN);
902 }
903
904 // Access to private directory implies access to 'less'-private version.
905 if ($flags->hasFlag('directory_private')) {
906 $flags->addFlag('directory_ax');
907 }
908 return $flags;
909 }
910
911 // Implementation of the default user callback.
912 public static function _default_user_callback($login, $results)
913 {
914 $result_count = count($results);
915 if ($result_count == 0 || !S::admin()) {
916 Platal::page()->trigError("Il n'y a pas d'utilisateur avec l'identifiant : $login");
917 } else {
918 Platal::page()->trigError("Il y a $result_count utilisateurs avec cet identifiant : " . join(', ', $results));
919 }
920 }
921
922 public static function makeHomonymHrmid($alias)
923 {
924 return 'h.' . $alias . '.' . Platal::globals()->mail->domain;
925 }
926
927 public static function isMainMailDomain($domain)
928 {
929 global $globals;
930
931 $is_main_domain = false;
932 foreach (self::$sub_mail_domains as $sub_domain) {
933 $is_main_domain = $is_main_domain || $domain == ($sub_domain . $globals->mail->domain) || $domain == ($sub_domain . $globals->mail->domain2);
934 }
935 return $is_main_domain;
936 }
937
938 public static function isAliasMailDomain($domain)
939 {
940 global $globals;
941
942 return $domain == $globals->mail->alias_dom || $domain == $globals->mail->alias_dom2;
943 }
944
945 // Implementation of the static email locality checker.
946 public static function isForeignEmailAddress($email)
947 {
948 if (strpos($email, '@') === false) {
949 return false;
950 }
951
952 list(, $domain) = explode('@', $email);
953 return !(self::isMainMailDomain($domain) || self::isAliasMailDomain($domain));
954 }
955
956 /* Tries to find pending accounts with an hruid close to $login. */
957 public static function getPendingAccounts($login, $iterator = false)
958 {
959 if (strpos($login, '@') === false) {
960 return null;
961 }
962
963 list($login, $domain) = explode('@', $login);
964
965 if ($domain && !self::isMainMailDomain($domain)) {
966 return null;
967 }
968
969 $sql = "SELECT uid, full_name
970 FROM accounts
971 WHERE state = 'pending' AND REPLACE(hruid, '-', '') LIKE
972 CONCAT('%', REPLACE(REPLACE(REPLACE({?}, ' ', ''), '-', ''), '\'', ''), '%')
973 ORDER BY full_name";
974 if ($iterator) {
975 return XDB::iterator($sql, $login);
976 } else {
977 $res = XDB::query($sql, $login);
978 return $res->fetchAllAssoc();
979 }
980 }
981
982
983 public static function iterOverUIDs($uids, $respect_order = true)
984 {
985 return new UserIterator(self::loadMainFieldsFromUIDs($uids, $respect_order));
986 }
987
988 /** Fetch a set of users from a list of UIDs
989 * @param $data The list of uids to fetch, or an array of arrays
990 * @param $orig If $data is an array of arrays, the subfield where uids are stored
991 * @param $dest If $data is an array of arrays, the subfield to fill with Users
992 * @param $fetchProfile Whether to fetch Profiles as well
993 * @return either an array of $uid => User, or $data with $data[$i][$dest] = User
994 */
995 public static function getBulkUsersWithUIDs(array $data, $orig = null, $dest = null, $fetchProfile = true)
996 {
997 // Fetch the list of uids
998 if (is_null($orig)) {
999 $uids = $data;
1000 } else {
1001 if (is_null($dest)) {
1002 $dest = $orig;
1003 }
1004 $uids = array();
1005 foreach ($data as $key=>$entry) {
1006 if (isset($entry[$orig])) {
1007 $uids[] = $entry[$orig];
1008 }
1009 }
1010 }
1011
1012 // Fetch users
1013 if (count($uids) == 0) {
1014 return $data;
1015 }
1016 $users = self::iterOverUIDs($uids, true);
1017
1018 $table = array();
1019 if ($fetchProfile) {
1020 $profiles = Profile::iterOverUIDS($uids, true);
1021 if ($profiles != null) {
1022 $profile = $profiles->next();
1023 } else {
1024 $profile = null;
1025 }
1026 }
1027
1028 /** We iterate through the users, moving in
1029 * profiles when they match the user ID :
1030 * there can be users without a profile, but not
1031 * the other way around.
1032 */
1033 while (($user = $users->next())) {
1034 if ($fetchProfile) {
1035 if ($profile != null && $profile->owner_id == $user->id()) {
1036 $user->_profile = $profile;
1037 $profile = $profiles->next();
1038 }
1039 $user->_profile_fetched = true;
1040 }
1041 $table[$user->id()] = $user;
1042 }
1043
1044 // Build the result with respect to input order.
1045 if (is_null($orig)) {
1046 return $table;
1047 } else {
1048 foreach ($data as $key=>$entry) {
1049 if (isset($entry[$orig])) {
1050 $entry[$dest] = $table[$entry[$orig]];
1051 $data[$key] = $entry;
1052 }
1053 }
1054 return $data;
1055 }
1056 }
1057
1058 public static function getBulkUsersFromDB($fetchProfile = true)
1059 {
1060 $args = func_get_args();
1061 $uids = call_user_func_array(array('XDB', 'fetchColumn'), $args);
1062 return self::getBulkUsersWithUIDs($uids, null, null, $fetchProfile);
1063 }
1064 }
1065
1066 /** Iterator over a set of Users
1067 * @param an XDB::Iterator obtained from a User::loadMainFieldsFromUIDs
1068 */
1069 class UserIterator implements PlIterator
1070 {
1071 private $dbiter;
1072
1073 public function __construct($dbiter)
1074 {
1075 $this->dbiter = $dbiter;
1076 }
1077
1078 public function next()
1079 {
1080 $data = $this->dbiter->next();
1081 if ($data == null) {
1082 return null;
1083 } else {
1084 return User::getSilentWithValues(null, $data);
1085 }
1086 }
1087
1088 public function total()
1089 {
1090 return $this->dbiter->total();
1091 }
1092
1093 public function first()
1094 {
1095 return $this->dbiter->first();
1096 }
1097
1098 public function last()
1099 {
1100 return $this->dbiter->last();
1101 }
1102 }
1103
1104 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1105 ?>