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