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