c533bd13925fe5c930d8928b1d4d8989530291ae
2 /***************************************************************************
3 * Copyright (C) 2003-2009 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
22 class User
extends PlUser
24 private $_profile_fetched = false
;
25 private $_profile = null
;
27 // Implementation of the login to uid method.
28 protected function getLogin($login)
33 throw new UserNotFoundException();
36 if ($login instanceof User
) {
40 if ($login instanceof Profile
) {
41 $this->_profile
= $login;
42 $this->_profile_fetched
= true
;
43 $res = XDB
::query('SELECT ap.uid
44 FROM account_profiles AS ap
45 WHERE ap.pid = {?} AND FIND_IN_SET(\'owner\', perms)',
47 if ($res->numRows()) {
48 return $res->fetchOneCell();
50 throw new UserNotFoundException();
53 // If $data is an integer, fetches directly the result.
54 if (is_numeric($login)) {
55 $res = XDB
::query('SELECT a.uid
57 WHERE a.uid = {?}', $login);
58 if ($res->numRows()) {
59 return $res->fetchOneCell();
62 throw new UserNotFoundException();
65 // Checks whether $login is a valid hruid or not.
66 $res = XDB
::query('SELECT a.uid
68 WHERE a.hruid = {?}', $login);
69 if ($res->numRows()) {
70 return $res->fetchOneCell();
73 // From now, $login can only by an email alias, or an email redirection.
74 // If it doesn't look like a valid address, appends the plat/al's main domain.
75 $login = trim(strtolower($login));
76 if (strstr($login, '@') === false
) {
77 $login = $login . '@' . $globals->mail
->domain
;
80 // Checks if $login is a valid alias on the main domains.
81 list($mbox, $fqdn) = explode('@', $login);
82 if ($fqdn == $globals->mail
->domain ||
$fqdn == $globals->mail
->domain2
) {
83 $res = XDB
::query('SELECT a.uid
85 INNER JOIN aliases AS al ON (al.id = a.uid AND al.type IN (\'alias\', \'a_vie\'))
86 WHERE al.alias = {?}', $mbox);
87 if ($res->numRows()) {
88 return $res->fetchOneCell();
91 /** TODO: implements this by inspecting the profile.
92 if (preg_match('/^(.*)\.([0-9]{4})$/u', $mbox, $matches)) {
93 $res = XDB::query('SELECT a.uid
95 INNER JOIN aliases AS al ON (al.id = a.uid AND al.type IN ('alias', 'a_vie'))
96 WHERE al.alias = {?} AND a.promo = {?}', $matches[1], $matches[2]);
97 if ($res->numRows() == 1) {
98 return $res->fetchOneCell();
102 throw new UserNotFoundException();
105 // Looks for $login as an email alias from the dedicated alias domain.
106 if ($fqdn == $globals->mail
->alias_dom ||
$fqdn == $globals->mail
->alias_dom2
) {
107 $res = XDB
::query("SELECT redirect
108 FROM virtual_redirect
109 INNER JOIN virtual USING(vid)
110 WHERE alias = {?}", $mbox . '@' . $globals->mail
->alias_dom
);
111 if ($redir = $res->fetchOneCell()) {
112 // We now have a valid alias, which has to be translated to an hruid.
113 list($alias, $alias_fqdn) = explode('@', $redir);
114 $res = XDB
::query("SELECT a.uid
116 LEFT JOIN aliases AS al ON (al.id = a.uid AND al.type IN ('alias', 'a_vie'))
117 WHERE al.alias = {?}", $alias);
118 if ($res->numRows()) {
119 return $res->fetchOneCell();
123 throw new UserNotFoundException();
126 // Looks for an account with the given email.
127 $res = XDB
::query('SELECT a.uid
129 WHERE a.email = {?}', $login);
130 if ($res->numRows() == 1) {
131 return $res->fetchOneCell();
134 // Otherwise, we do suppose $login is an email redirection.
135 $res = XDB
::query("SELECT a.uid
137 LEFT JOIN emails AS e ON (e.uid = a.uid)
138 WHERE e.email = {?}", $login);
139 if ($res->numRows() == 1) {
140 return $res->fetchOneCell();
143 throw new UserNotFoundException($res->fetchColumn(1));
146 protected static function loadMainFieldsFromUIDs(array $uids)
151 if ($globals->asso('id')) {
152 $joins .= XDB
::format("LEFT JOIN groupex.membres AS gpm ON (gpm.uid = a.uid AND gpm.asso_id = {?})\n", $globals->asso('id'));
153 $fields[] = 'gpm.perms AS group_perms';
154 $fields[] = 'gpm.comm AS group_comm';
156 if (count($fields) > 0) {
157 $fields = ', ' . implode(', ', $fields);
161 $uids = array_map(array('XDB', 'escape'), $uids);
162 return XDB
::iterator('SELECT a.uid, a.hruid, a.registration_date,
163 CONCAT(af.alias, \'@' . $globals->mail
->domain
. '\') AS forlife,
164 CONCAT(ab.alias, \'@' . $globals->mail
->domain
. '\') AS bestalias,
165 a.full_name, a.display_name, a.sex = \'female\' AS gender,
166 IF(a.state = \'active\', at.perms, \'\') AS perms,
167 a.email_format, a.is_admin, a.state, a.type, a.skin,
168 FIND_IN_SET(\'watch\', a.flags) AS watch, a.comment,
169 a.weak_password IS NOT NULL AS weak_access,
170 a.token IS NOT NULL AS token_access,
171 (e.email IS NULL AND NOT FIND_IN_SET(\'googleapps\', eo.storage)) AND a.state != \'pending\' AS lost
174 INNER JOIN account_types AS at ON (at.type = a.type)
175 LEFT JOIN aliases AS af ON (af.id = a.uid AND af.type = \'a_vie\')
176 LEFT JOIN aliases AS ab ON (ab.id = a.uid AND FIND_IN_SET(\'bestalias\', ab.flags))
177 LEFT JOIN emails AS e ON (e.uid = a.uid AND e.flags = \'active\')
178 LEFT JOIN email_options AS eo ON (eo.uid = a.uid)
180 WHERE a.uid IN (' . implode(', ', $uids) . ')
184 // Implementation of the data loader.
185 protected function loadMainFields()
187 if ($this->hruid
!== null
&& $this->forlife
!== null
188 && $this->bestalias
!== null
&& $this->display_name
!== null
189 && $this->full_name
!== null
&& $this->perms
!== null
190 && $this->gender
!== null
&& $this->email_format
!== null
) {
193 $this->fillFromArray(self
::loadMainFieldsFromUIDs(array($this->user_id
))->next());
196 // Specialization of the fillFromArray method, to implement hacks to enable
197 // lazy loading of user's main properties from the session.
198 // TODO(vzanotti): remove the conversion hacks once the old codebase will
199 // stop being used actively.
200 protected function fillFromArray(array $values)
202 // It might happen that the 'user_id' field is called uid in some places
203 // (eg. in sessions), so we hard link uid to user_id to prevent useless
205 if (!isset($values['user_id']) && isset($values['uid'])) {
206 $values['user_id'] = $values['uid'];
209 // Also, if display_name and full_name are not known, but the user's
210 // surname and last name are, we can construct the former two.
211 if (isset($values['prenom']) && isset($values['nom'])) {
212 if (!isset($values['display_name'])) {
213 $values['display_name'] = ($values['prenom'] ?
$values['prenom'] : $values['nom']);
215 if (!isset($values['full_name'])) {
216 $values['full_name'] = $values['prenom'] . ' ' . $values['nom'];
220 // We also need to convert the gender (usually named "femme"), and the
221 // email format parameter (valued "texte" instead of "text").
222 if (isset($values['femme'])) {
223 $values['gender'] = (bool
) $values['femme'];
225 if (isset($values['mail_fmt'])) {
226 $values['email_format'] = $values['mail_fmt'];
229 parent
::fillFromArray($values);
232 // Specialization of the buildPerms method
233 // This function build 'generic' permissions for the user. It does not take
234 // into account page specific permissions (e.g X.net group permissions)
235 protected function buildPerms()
237 if (!is_null($this->perm_flags
)) {
240 if ($this->perms
=== null
) {
241 $this->loadMainFields();
243 $this->perm_flags
= self
::makePerms($this->perms
, $this->is_admin
);
246 // We do not want to store the password in the object.
247 // So, fetch it 'on demand'
248 public function password()
250 return XDB
::fetchOneCell('SELECT a.password
252 WHERE a.uid = {?}', $this->id());
255 /** Overload PlUser::promo(): there no promo defined for a user in the current
256 * schema. The promo is a field from the profile.
258 public function promo()
260 if (!$this->hasProfile()) {
263 return $this->profile()->promo();
266 public function firstName()
268 if (!$this->hasProfile()) {
269 return $this->displayName();
271 return $this->profile()->firstName();
274 public function lastName()
276 if (!$this->hasProfile()) {
279 return $this->profile()->lastName();
282 /** Return the main profile attached with this account if any.
284 public function profile()
286 if (!$this->_profile_fetched
) {
287 $this->_profile_fetched
= true
;
288 $this->_profile
= Profile
::get($this);
290 return $this->_profile
;
293 /** Return true if the user has an associated profile.
295 public function hasProfile()
297 return !is_null($this->profile());
300 /** Check if the user can edit to given profile.
302 public function canEdit(Profile
$profile)
304 // XXX: Check permissions (e.g. secretary permission)
305 // and flags from the profile
306 return XDB
::fetchOneCell('SELECT pid
307 FROM account_profiles
308 WHERE uid = {?} AND pid = {?}',
309 $this->id(), $profile->id());
312 /** Get the email alias of the user.
314 public function emailAlias()
317 $data = $this->emailAliases($globals->mail
->alias_dom
);
318 if (count($data) > 0) {
319 return array_pop($data);
324 /** Get all the aliases the user belongs to.
326 public function emailAliases($domain = null
, $type = 'user', $sub_state = false
)
328 $join = XDB
::format('(vr.redirect = {?} OR vr.redirect = {?}) ',
329 $this->forlifeEmail(), $this->m4xForlifeEmail());
331 if (!is_null($domain)) {
332 $where = XDB
::format('WHERE v.alias LIKE CONCAT("%@", {?})', $domain);
334 if (!is_null($type)) {
336 $where = XDB
::format('WHERE v.type = {?}', $type);
338 $where .= XDB
::format(' AND v.type = {?}', $type);
342 return XDB
::fetchAllAssoc('alias', 'SELECT v.alias, vr.redirect IS NOT NULL AS sub
344 LEFT JOIN virtual_redirect AS vr ON (v.vid = vr.vid AND ' . $join . ')
347 return XDB
::fetchColumn('SELECT v.alias
349 INNER JOIN virtual_redirect AS vr ON (v.vid = vr.vid AND ' . $join . ')
354 /** Get the alternative forlife email
355 * TODO: remove this uber-ugly hack. The issue is that you need to remove
356 * all @m4x.org addresses in virtual_redirect first.
357 * XXX: This is juste to make code more readable, to be remove as soon as possible
359 public function m4xForlifeEmail()
362 trigger_error('USING M4X FORLIFE', E_USER_NOTICE
);
363 return $this->login() . '@' . $globals->mail
->domain2
;
367 /** Get marketing informations
369 private function fetchMarketingData()
371 if (isset($this->last_known_email
)) {
374 $infos = XDB
::fetchOneAssoc('SELECT IF (MAX(m.last) > p.relance, MAX(m.last), p.relance) AS last_relance,
375 p.email AS last_known_email
376 FROM register_pending AS p
377 LEFT JOIN register_marketing AS m ON (p.uid = m.uid)
379 GROUP BY p.uid', $this->id());
381 $infos = array('last_relance' => null
, 'last_known_email' => null
);
383 $this->fillFromArray($infos);
386 public function lastMarketingRelance()
388 $this->fetchMarketingData();
389 return $this->last_relance
;
392 public function lastKnownEmail()
394 $this->fetchMarketingData();
395 return $this->last_known_email
;
399 /** Get watch informations
401 private function fetchWatchData()
403 if (isset($this->watch_actions
)) {
406 $watch = XDB
::fetchOneAssoc('SELECT flags AS watch_flags, actions AS watch_actions,
407 UNIX_TIMESTAMP(last) AS watch_last
409 WHERE uid = {?}', $this->id());
410 $watch['watch_flags'] = new PlFlagSet($watch['watch_flags']);
411 $watch['watch_actions'] = new PlFlagSet($watch['watch_actions']);
412 $watch['watch_promos'] = XDB
::fetchColumn('SELECT promo
414 WHERE uid = {?}', $this->id());
415 $watch['watch_users'] = XDB
::fetchColumn('SELECT ni_id
417 WHERE uid = {?}', $this->id());
418 $this->fillFromArray($watch);
421 public function watch($type)
423 $this->fetchWatchData();
424 return $this->watch_actions
->hasFlag($type);
427 public function watchContacts()
429 $this->fetchWatchData();
430 return $this->watch_flags
->hasFlag('contacts');
433 public function watchEmail()
435 $this->fetchWatchData();
436 return $this->watch_flags
->hasFlag('mail');
439 public function watchPromos()
441 $this->fetchWatchData();
442 return $this->watch_promos
;
445 public function watchUsers()
447 $this->fetchWatchData();
448 return $this->watch_users
;
451 public function watchLast()
453 $this->fetchWatchData();
454 return $this->watch_last
;
459 private $contacts = null
;
460 public function isContact(PlUser
&$user)
462 if (is_null($this->contacts
)) {
463 $this->contacts
= XDB
::fetchAllAssoc('contact', 'SELECT *
468 return isset($this->contacts
[$user->id()]);
471 // Return permission flags for a given permission level.
472 public static function makePerms($perms, $is_admin)
474 $flags = new PlFlagSet($perms);
475 $flags->addFlag(PERMS_USER
);
477 $flags->addFlag(PERMS_ADMIN
);
482 // Implementation of the default user callback.
483 public static function _default_user_callback($login, $results)
485 $result_count = count($results);
486 if ($result_count == 0 ||
!S
::has_perms()) {
487 Platal
::page()->trigError("Il n'y a pas d'utilisateur avec l'identifiant : $login");
489 Platal
::page()->trigError("Il y a $result_count utilisateurs avec cet identifiant : " . join(', ', $results));
493 // Implementation of the static email locality checker.
494 public static function isForeignEmailAddress($email)
497 if (strpos($email, '@') === false
) {
501 list($user, $dom) = explode('@', $email);
502 return $dom != $globals->mail
->domain
&&
503 $dom != $globals->mail
->domain2
&&
504 $dom != $globals->mail
->alias_dom
&&
505 $dom != $globals->mail
->alias_dom2
;
508 public static function isVirtualEmailAddress($email)
511 if (strpos($email, '@') === false
) {
515 list($user, $dom) = explode('@', $email);
516 return $dom == $globals->mail
->alias_dom
517 ||
$dom == $globals->mail
->alias_dom2
;
520 // Fetch a set of users from a list of UIDs
521 public static function getBulkUsersWithUIDs(array $data, $orig = null
, $dest = null
, $fetchProfile = true
)
523 // Fetch the list of uids
524 if (is_null($orig)) {
527 if (is_null($dest)) {
531 foreach ($data as $key=>$entry) {
532 if (isset($entry[$orig])) {
533 $uids[] = $entry[$orig];
539 if (count($uids) == 0) {
542 $fields = self
::loadMainFieldsFromUIDs($uids);
545 $profiles = Profile
::getBulkProfilesWithUIDS($uids);
547 while (($list = $fields->next())) {
549 $user = User
::getSilentWithValues(null
, $list);
551 if (isset($profiles[$uid])) {
552 $user->_profile
= $profiles[$uid];
554 $user->_profile_fetched
= true
;
556 $table[$list['uid']] = $user;
559 // Build the result with respect to input order.
560 if (is_null($orig)) {
562 foreach ($uids as $key=>$uid) {
563 $users[$key] = $table[$uid];
567 foreach ($data as $key=>$entry) {
568 if (isset($entry[$orig])) {
569 $entry[$dest] = $table[$entry[$orig]];
570 $data[$key] = $entry;
577 public static function getBulkUsersFromDB($fetchProfile = true
)
579 $args = func_get_args();
580 $uids = call_user_func_array(array('XDB', 'fetchColumn'), $args);
581 return self
::getBulkUsersWithUIDs($uids, null
, null
, $fetchProfile);
585 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: