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