c533bd13925fe5c930d8928b1d4d8989530291ae
[platal.git] / classes / user.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2009 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 // Implementation of the login to uid method.
28 protected function getLogin($login)
29 {
30 global $globals;
31
32 if (!$login) {
33 throw new UserNotFoundException();
34 }
35
36 if ($login instanceof User) {
37 $machin->id();
38 }
39
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)',
46 $login->id());
47 if ($res->numRows()) {
48 return $res->fetchOneCell();
49 }
50 throw new UserNotFoundException();
51 }
52
53 // If $data is an integer, fetches directly the result.
54 if (is_numeric($login)) {
55 $res = XDB::query('SELECT a.uid
56 FROM accounts AS a
57 WHERE a.uid = {?}', $login);
58 if ($res->numRows()) {
59 return $res->fetchOneCell();
60 }
61
62 throw new UserNotFoundException();
63 }
64
65 // Checks whether $login is a valid hruid or not.
66 $res = XDB::query('SELECT a.uid
67 FROM accounts AS a
68 WHERE a.hruid = {?}', $login);
69 if ($res->numRows()) {
70 return $res->fetchOneCell();
71 }
72
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;
78 }
79
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
84 FROM accounts AS a
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();
89 }
90
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
94 FROM accounts AS a
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();
99 }
100 }*/
101
102 throw new UserNotFoundException();
103 }
104
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
115 FROM accounts AS a
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();
120 }
121 }
122
123 throw new UserNotFoundException();
124 }
125
126 // Looks for an account with the given email.
127 $res = XDB::query('SELECT a.uid
128 FROM accounts AS a
129 WHERE a.email = {?}', $login);
130 if ($res->numRows() == 1) {
131 return $res->fetchOneCell();
132 }
133
134 // Otherwise, we do suppose $login is an email redirection.
135 $res = XDB::query("SELECT a.uid
136 FROM accounts AS a
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();
141 }
142
143 throw new UserNotFoundException($res->fetchColumn(1));
144 }
145
146 protected static function loadMainFieldsFromUIDs(array $uids)
147 {
148 global $globals;
149 $joins = '';
150 $fields = array();
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';
155 }
156 if (count($fields) > 0) {
157 $fields = ', ' . implode(', ', $fields);
158 } else {
159 $fields = '';
160 }
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
172 ' . $fields . '
173 FROM accounts AS a
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)
179 ' . $joins . '
180 WHERE a.uid IN (' . implode(', ', $uids) . ')
181 GROUP BY a.uid');
182 }
183
184 // Implementation of the data loader.
185 protected function loadMainFields()
186 {
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) {
191 return;
192 }
193 $this->fillFromArray(self::loadMainFieldsFromUIDs(array($this->user_id))->next());
194 }
195
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)
201 {
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
204 // SQL requests.
205 if (!isset($values['user_id']) && isset($values['uid'])) {
206 $values['user_id'] = $values['uid'];
207 }
208
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']);
214 }
215 if (!isset($values['full_name'])) {
216 $values['full_name'] = $values['prenom'] . ' ' . $values['nom'];
217 }
218 }
219
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'];
224 }
225 if (isset($values['mail_fmt'])) {
226 $values['email_format'] = $values['mail_fmt'];
227 }
228
229 parent::fillFromArray($values);
230 }
231
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()
236 {
237 if (!is_null($this->perm_flags)) {
238 return;
239 }
240 if ($this->perms === null) {
241 $this->loadMainFields();
242 }
243 $this->perm_flags = self::makePerms($this->perms, $this->is_admin);
244 }
245
246 // We do not want to store the password in the object.
247 // So, fetch it 'on demand'
248 public function password()
249 {
250 return XDB::fetchOneCell('SELECT a.password
251 FROM accounts AS a
252 WHERE a.uid = {?}', $this->id());
253 }
254
255 /** Overload PlUser::promo(): there no promo defined for a user in the current
256 * schema. The promo is a field from the profile.
257 */
258 public function promo()
259 {
260 if (!$this->hasProfile()) {
261 return '';
262 }
263 return $this->profile()->promo();
264 }
265
266 public function firstName()
267 {
268 if (!$this->hasProfile()) {
269 return $this->displayName();
270 }
271 return $this->profile()->firstName();
272 }
273
274 public function lastName()
275 {
276 if (!$this->hasProfile()) {
277 return '';
278 }
279 return $this->profile()->lastName();
280 }
281
282 /** Return the main profile attached with this account if any.
283 */
284 public function profile()
285 {
286 if (!$this->_profile_fetched) {
287 $this->_profile_fetched = true;
288 $this->_profile = Profile::get($this);
289 }
290 return $this->_profile;
291 }
292
293 /** Return true if the user has an associated profile.
294 */
295 public function hasProfile()
296 {
297 return !is_null($this->profile());
298 }
299
300 /** Check if the user can edit to given profile.
301 */
302 public function canEdit(Profile $profile)
303 {
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());
310 }
311
312 /** Get the email alias of the user.
313 */
314 public function emailAlias()
315 {
316 global $globals;
317 $data = $this->emailAliases($globals->mail->alias_dom);
318 if (count($data) > 0) {
319 return array_pop($data);
320 }
321 return null;
322 }
323
324 /** Get all the aliases the user belongs to.
325 */
326 public function emailAliases($domain = null, $type = 'user', $sub_state = false)
327 {
328 $join = XDB::format('(vr.redirect = {?} OR vr.redirect = {?}) ',
329 $this->forlifeEmail(), $this->m4xForlifeEmail());
330 $where = '';
331 if (!is_null($domain)) {
332 $where = XDB::format('WHERE v.alias LIKE CONCAT("%@", {?})', $domain);
333 }
334 if (!is_null($type)) {
335 if (empty($where)) {
336 $where = XDB::format('WHERE v.type = {?}', $type);
337 } else {
338 $where .= XDB::format(' AND v.type = {?}', $type);
339 }
340 }
341 if ($sub_state) {
342 return XDB::fetchAllAssoc('alias', 'SELECT v.alias, vr.redirect IS NOT NULL AS sub
343 FROM virtual AS v
344 LEFT JOIN virtual_redirect AS vr ON (v.vid = vr.vid AND ' . $join . ')
345 ' . $where);
346 } else {
347 return XDB::fetchColumn('SELECT v.alias
348 FROM virtual AS v
349 INNER JOIN virtual_redirect AS vr ON (v.vid = vr.vid AND ' . $join . ')
350 ' . $where);
351 }
352 }
353
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
358 */
359 public function m4xForlifeEmail()
360 {
361 global $globals;
362 trigger_error('USING M4X FORLIFE', E_USER_NOTICE);
363 return $this->login() . '@' . $globals->mail->domain2;
364 }
365
366
367 /** Get marketing informations
368 */
369 private function fetchMarketingData()
370 {
371 if (isset($this->last_known_email)) {
372 return;
373 }
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)
378 WHERE p.uid = {?}
379 GROUP BY p.uid', $this->id());
380 if (!$infos) {
381 $infos = array('last_relance' => null, 'last_known_email' => null);
382 }
383 $this->fillFromArray($infos);
384 }
385
386 public function lastMarketingRelance()
387 {
388 $this->fetchMarketingData();
389 return $this->last_relance;
390 }
391
392 public function lastKnownEmail()
393 {
394 $this->fetchMarketingData();
395 return $this->last_known_email;
396 }
397
398
399 /** Get watch informations
400 */
401 private function fetchWatchData()
402 {
403 if (isset($this->watch_actions)) {
404 return;
405 }
406 $watch = XDB::fetchOneAssoc('SELECT flags AS watch_flags, actions AS watch_actions,
407 UNIX_TIMESTAMP(last) AS watch_last
408 FROM watch
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
413 FROM watch_promo
414 WHERE uid = {?}', $this->id());
415 $watch['watch_users'] = XDB::fetchColumn('SELECT ni_id
416 FROM watch_nonins
417 WHERE uid = {?}', $this->id());
418 $this->fillFromArray($watch);
419 }
420
421 public function watch($type)
422 {
423 $this->fetchWatchData();
424 return $this->watch_actions->hasFlag($type);
425 }
426
427 public function watchContacts()
428 {
429 $this->fetchWatchData();
430 return $this->watch_flags->hasFlag('contacts');
431 }
432
433 public function watchEmail()
434 {
435 $this->fetchWatchData();
436 return $this->watch_flags->hasFlag('mail');
437 }
438
439 public function watchPromos()
440 {
441 $this->fetchWatchData();
442 return $this->watch_promos;
443 }
444
445 public function watchUsers()
446 {
447 $this->fetchWatchData();
448 return $this->watch_users;
449 }
450
451 public function watchLast()
452 {
453 $this->fetchWatchData();
454 return $this->watch_last;
455 }
456
457
458 // Contacts
459 private $contacts = null;
460 public function isContact(PlUser &$user)
461 {
462 if (is_null($this->contacts)) {
463 $this->contacts = XDB::fetchAllAssoc('contact', 'SELECT *
464 FROM contacts
465 WHERE uid = {?}',
466 $this->id());
467 }
468 return isset($this->contacts[$user->id()]);
469 }
470
471 // Return permission flags for a given permission level.
472 public static function makePerms($perms, $is_admin)
473 {
474 $flags = new PlFlagSet($perms);
475 $flags->addFlag(PERMS_USER);
476 if ($is_admin) {
477 $flags->addFlag(PERMS_ADMIN);
478 }
479 return $flags;
480 }
481
482 // Implementation of the default user callback.
483 public static function _default_user_callback($login, $results)
484 {
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");
488 } else {
489 Platal::page()->trigError("Il y a $result_count utilisateurs avec cet identifiant : " . join(', ', $results));
490 }
491 }
492
493 // Implementation of the static email locality checker.
494 public static function isForeignEmailAddress($email)
495 {
496 global $globals;
497 if (strpos($email, '@') === false) {
498 return false;
499 }
500
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;
506 }
507
508 public static function isVirtualEmailAddress($email)
509 {
510 global $globals;
511 if (strpos($email, '@') === false) {
512 return false;
513 }
514
515 list($user, $dom) = explode('@', $email);
516 return $dom == $globals->mail->alias_dom
517 || $dom == $globals->mail->alias_dom2;
518 }
519
520 // Fetch a set of users from a list of UIDs
521 public static function getBulkUsersWithUIDs(array $data, $orig = null, $dest = null, $fetchProfile = true)
522 {
523 // Fetch the list of uids
524 if (is_null($orig)) {
525 $uids = $data;
526 } else {
527 if (is_null($dest)) {
528 $dest = $orig;
529 }
530 $uids = array();
531 foreach ($data as $key=>$entry) {
532 if (isset($entry[$orig])) {
533 $uids[] = $entry[$orig];
534 }
535 }
536 }
537
538 // Fetch users
539 if (count($uids) == 0) {
540 return $data;
541 }
542 $fields = self::loadMainFieldsFromUIDs($uids);
543 $table = array();
544 if ($fetchProfile) {
545 $profiles = Profile::getBulkProfilesWithUIDS($uids);
546 }
547 while (($list = $fields->next())) {
548 $uid = $list['uid'];
549 $user = User::getSilentWithValues(null, $list);
550 if ($fetchProfile) {
551 if (isset($profiles[$uid])) {
552 $user->_profile = $profiles[$uid];
553 }
554 $user->_profile_fetched = true;
555 }
556 $table[$list['uid']] = $user;
557 }
558
559 // Build the result with respect to input order.
560 if (is_null($orig)) {
561 $users = array();
562 foreach ($uids as $key=>$uid) {
563 $users[$key] = $table[$uid];
564 }
565 return $users;
566 } else {
567 foreach ($data as $key=>$entry) {
568 if (isset($entry[$orig])) {
569 $entry[$dest] = $table[$entry[$orig]];
570 $data[$key] = $entry;
571 }
572 }
573 return $data;
574 }
575 }
576
577 public static function getBulkUsersFromDB($fetchProfile = true)
578 {
579 $args = func_get_args();
580 $uids = call_user_func_array(array('XDB', 'fetchColumn'), $args);
581 return self::getBulkUsersWithUIDs($uids, null, null, $fetchProfile);
582 }
583 }
584
585 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
586 ?>