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