Switch last uses of VCard to Profile system
[platal.git] / classes / user.php
CommitLineData
9f8ebb9f
VZ
1<?php
2/***************************************************************************
9f5bd98e 3 * Copyright (C) 2003-2010 Polytechnique.org *
9f8ebb9f
VZ
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
2d96cf7b 22class User extends PlUser
9f8ebb9f 23{
3e53a496
FB
24 private $_profile_fetched = false;
25 private $_profile = null;
26
956608bc
RB
27 // Additional fields (non core)
28 protected $promo = null;
29
70232020 30 // Implementation of the login to uid method.
b1719b13
VZ
31 protected function getLogin($login)
32 {
33 global $globals;
34
f6c58d14
VZ
35 if (!$login) {
36 throw new UserNotFoundException();
37 }
38
455ea0c9
FB
39 if ($login instanceof User) {
40 $machin->id();
41 }
42
e7b93962 43 if ($login instanceof Profile) {
3e53a496
FB
44 $this->_profile = $login;
45 $this->_profile_fetched = true;
e7b93962
FB
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
b1719b13
VZ
56 // If $data is an integer, fetches directly the result.
57 if (is_numeric($login)) {
e7b93962
FB
58 $res = XDB::query('SELECT a.uid
59 FROM accounts AS a
60 WHERE a.uid = {?}', $login);
b1719b13 61 if ($res->numRows()) {
70232020 62 return $res->fetchOneCell();
b1719b13
VZ
63 }
64
65 throw new UserNotFoundException();
66 }
67
68 // Checks whether $login is a valid hruid or not.
e7b93962
FB
69 $res = XDB::query('SELECT a.uid
70 FROM accounts AS a
71 WHERE a.hruid = {?}', $login);
b1719b13 72 if ($res->numRows()) {
70232020 73 return $res->fetchOneCell();
b1719b13
VZ
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) {
e7b93962
FB
86 $res = XDB::query('SELECT a.uid
87 FROM accounts AS a
88 INNER JOIN aliases AS al ON (al.id = a.uid AND al.type IN (\'alias\', \'a_vie\'))
89 WHERE al.alias = {?}', $mbox);
b1719b13 90 if ($res->numRows()) {
70232020 91 return $res->fetchOneCell();
b1719b13
VZ
92 }
93
e7b93962 94 /** TODO: implements this by inspecting the profile.
b1719b13 95 if (preg_match('/^(.*)\.([0-9]{4})$/u', $mbox, $matches)) {
e7b93962
FB
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]);
b1719b13 100 if ($res->numRows() == 1) {
70232020 101 return $res->fetchOneCell();
b1719b13 102 }
e7b93962 103 }*/
b1719b13
VZ
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);
e7b93962
FB
117 $res = XDB::query("SELECT a.uid
118 FROM accounts AS a
119 LEFT JOIN aliases AS al ON (al.id = a.uid AND al.type IN ('alias', 'a_vie'))
120 WHERE al.alias = {?}", $alias);
b1719b13 121 if ($res->numRows()) {
70232020 122 return $res->fetchOneCell();
b1719b13
VZ
123 }
124 }
125
126 throw new UserNotFoundException();
127 }
128
cb8a8977
FB
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
b1719b13 137 // Otherwise, we do suppose $login is an email redirection.
e7b93962
FB
138 $res = XDB::query("SELECT a.uid
139 FROM accounts AS a
140 LEFT JOIN emails AS e ON (e.uid = a.uid)
b1719b13
VZ
141 WHERE e.email = {?}", $login);
142 if ($res->numRows() == 1) {
70232020 143 return $res->fetchOneCell();
b1719b13
VZ
144 }
145
146 throw new UserNotFoundException($res->fetchColumn(1));
147 }
148
d865c296 149 protected static function loadMainFieldsFromUIDs(array $uids)
832e6fcb 150 {
45dcd6dd 151 global $globals;
832e6fcb 152 $joins = '';
45dcd6dd 153 $fields = array();
45dcd6dd 154 if ($globals->asso('id')) {
eb41eda9 155 $joins .= XDB::format("LEFT JOIN group_members AS gpm ON (gpm.uid = a.uid AND gpm.asso_id = {?})\n", $globals->asso('id'));
45dcd6dd 156 $fields[] = 'gpm.perms AS group_perms';
a6761ca9 157 $fields[] = 'gpm.comm AS group_comm';
45dcd6dd
FB
158 }
159 if (count($fields) > 0) {
160 $fields = ', ' . implode(', ', $fields);
a3118782
FB
161 } else {
162 $fields = '';
45dcd6dd
FB
163 }
164 $uids = array_map(array('XDB', 'escape'), $uids);
832e6fcb
FB
165 return XDB::iterator('SELECT a.uid, a.hruid, a.registration_date,
166 CONCAT(af.alias, \'@' . $globals->mail->domain . '\') AS forlife,
c82aa04c 167 CONCAT(af.alias, \'@' . $globals->mail->domain2 . '\') AS forlife_alternate,
832e6fcb 168 CONCAT(ab.alias, \'@' . $globals->mail->domain . '\') AS bestalias,
c82aa04c 169 CONCAT(ab.alias, \'@' . $globals->mail->domain2 . '\') AS bestalias_alternate,
832e6fcb
FB
170 a.full_name, a.display_name, a.sex = \'female\' AS gender,
171 IF(a.state = \'active\', at.perms, \'\') AS perms,
172 a.email_format, a.is_admin, a.state, a.type, a.skin,
173 FIND_IN_SET(\'watch\', a.flags) AS watch, a.comment,
174 a.weak_password IS NOT NULL AS weak_access,
2c411733
FB
175 a.token IS NOT NULL AS token_access,
176 (e.email IS NULL AND NOT FIND_IN_SET(\'googleapps\', eo.storage)) AND a.state != \'pending\' AS lost
177 ' . $fields . '
832e6fcb
FB
178 FROM accounts AS a
179 INNER JOIN account_types AS at ON (at.type = a.type)
180 LEFT JOIN aliases AS af ON (af.id = a.uid AND af.type = \'a_vie\')
181 LEFT JOIN aliases AS ab ON (ab.id = a.uid AND FIND_IN_SET(\'bestalias\', ab.flags))
2c411733
FB
182 LEFT JOIN emails AS e ON (e.uid = a.uid AND e.flags = \'active\')
183 LEFT JOIN email_options AS eo ON (eo.uid = a.uid)
d865c296 184 ' . $joins . '
832e6fcb 185 WHERE a.uid IN (' . implode(', ', $uids) . ')
d865c296 186 GROUP BY a.uid');
832e6fcb
FB
187 }
188
70232020
VZ
189 // Implementation of the data loader.
190 protected function loadMainFields()
191 {
c4012d9b
VZ
192 if ($this->hruid !== null && $this->forlife !== null
193 && $this->bestalias !== null && $this->display_name !== null
8f2104cb 194 && $this->full_name !== null && $this->perms !== null
c4012d9b 195 && $this->gender !== null && $this->email_format !== null) {
70232020
VZ
196 return;
197 }
832e6fcb 198 $this->fillFromArray(self::loadMainFieldsFromUIDs(array($this->user_id))->next());
70232020
VZ
199 }
200
201 // Specialization of the fillFromArray method, to implement hacks to enable
202 // lazy loading of user's main properties from the session.
c4012d9b
VZ
203 // TODO(vzanotti): remove the conversion hacks once the old codebase will
204 // stop being used actively.
70232020
VZ
205 protected function fillFromArray(array $values)
206 {
207 // It might happen that the 'user_id' field is called uid in some places
208 // (eg. in sessions), so we hard link uid to user_id to prevent useless
209 // SQL requests.
210 if (!isset($values['user_id']) && isset($values['uid'])) {
211 $values['user_id'] = $values['uid'];
212 }
213
214 // Also, if display_name and full_name are not known, but the user's
215 // surname and last name are, we can construct the former two.
216 if (isset($values['prenom']) && isset($values['nom'])) {
217 if (!isset($values['display_name'])) {
218 $values['display_name'] = ($values['prenom'] ? $values['prenom'] : $values['nom']);
219 }
220 if (!isset($values['full_name'])) {
221 $values['full_name'] = $values['prenom'] . ' ' . $values['nom'];
222 }
223 }
224
c4012d9b
VZ
225 // We also need to convert the gender (usually named "femme"), and the
226 // email format parameter (valued "texte" instead of "text").
227 if (isset($values['femme'])) {
228 $values['gender'] = (bool) $values['femme'];
229 }
230 if (isset($values['mail_fmt'])) {
231 $values['email_format'] = $values['mail_fmt'];
232 }
c4012d9b 233
70232020
VZ
234 parent::fillFromArray($values);
235 }
236
50d5ec0b
FB
237 // Specialization of the buildPerms method
238 // This function build 'generic' permissions for the user. It does not take
239 // into account page specific permissions (e.g X.net group permissions)
240 protected function buildPerms()
241 {
242 if (!is_null($this->perm_flags)) {
243 return;
244 }
245 if ($this->perms === null) {
246 $this->loadMainFields();
247 }
365ba8c3 248 $this->perm_flags = self::makePerms($this->perms, $this->is_admin);
50d5ec0b
FB
249 }
250
7f1ff426
FB
251 // We do not want to store the password in the object.
252 // So, fetch it 'on demand'
253 public function password()
254 {
255 return XDB::fetchOneCell('SELECT a.password
256 FROM accounts AS a
257 WHERE a.uid = {?}', $this->id());
258 }
259
8f2104cb
FB
260 /** Overload PlUser::promo(): there no promo defined for a user in the current
261 * schema. The promo is a field from the profile.
262 */
263 public function promo()
264 {
265 if (!$this->hasProfile()) {
266 return '';
267 }
268 return $this->profile()->promo();
269 }
270
a6761ca9
FB
271 public function firstName()
272 {
273 if (!$this->hasProfile()) {
274 return $this->displayName();
275 }
276 return $this->profile()->firstName();
277 }
278
279 public function lastName()
280 {
281 if (!$this->hasProfile()) {
282 return '';
283 }
284 return $this->profile()->lastName();
285 }
286
e7b93962
FB
287 /** Return the main profile attached with this account if any.
288 */
289 public function profile()
290 {
3e53a496
FB
291 if (!$this->_profile_fetched) {
292 $this->_profile_fetched = true;
293 $this->_profile = Profile::get($this);
294 }
295 return $this->_profile;
296 }
297
298 /** Return true if the user has an associated profile.
299 */
300 public function hasProfile()
301 {
302 return !is_null($this->profile());
303 }
304
3af21f99
FB
305 /** Check if the user can edit to given profile.
306 */
307 public function canEdit(Profile $profile)
308 {
309 // XXX: Check permissions (e.g. secretary permission)
310 // and flags from the profile
311 return XDB::fetchOneCell('SELECT pid
312 FROM account_profiles
313 WHERE uid = {?} AND pid = {?}',
314 $this->id(), $profile->id());
315 }
316
3e53a496
FB
317 /** Get the email alias of the user.
318 */
319 public function emailAlias()
320 {
321 global $globals;
8f2104cb
FB
322 $data = $this->emailAliases($globals->mail->alias_dom);
323 if (count($data) > 0) {
324 return array_pop($data);
325 }
326 return null;
327 }
328
329 /** Get all the aliases the user belongs to.
330 */
a6761ca9 331 public function emailAliases($domain = null, $type = 'user', $sub_state = false)
8f2104cb 332 {
a6761ca9
FB
333 $join = XDB::format('(vr.redirect = {?} OR vr.redirect = {?}) ',
334 $this->forlifeEmail(), $this->m4xForlifeEmail());
8f2104cb
FB
335 $where = '';
336 if (!is_null($domain)) {
a6761ca9
FB
337 $where = XDB::format('WHERE v.alias LIKE CONCAT("%@", {?})', $domain);
338 }
339 if (!is_null($type)) {
340 if (empty($where)) {
341 $where = XDB::format('WHERE v.type = {?}', $type);
342 } else {
343 $where .= XDB::format(' AND v.type = {?}', $type);
344 }
345 }
346 if ($sub_state) {
347 return XDB::fetchAllAssoc('alias', 'SELECT v.alias, vr.redirect IS NOT NULL AS sub
348 FROM virtual AS v
349 LEFT JOIN virtual_redirect AS vr ON (v.vid = vr.vid AND ' . $join . ')
350 ' . $where);
351 } else {
352 return XDB::fetchColumn('SELECT v.alias
353 FROM virtual AS v
354 INNER JOIN virtual_redirect AS vr ON (v.vid = vr.vid AND ' . $join . ')
355 ' . $where);
8f2104cb 356 }
3e53a496
FB
357 }
358
359 /** Get the alternative forlife email
360 * TODO: remove this uber-ugly hack. The issue is that you need to remove
361 * all @m4x.org addresses in virtual_redirect first.
362 * XXX: This is juste to make code more readable, to be remove as soon as possible
363 */
364 public function m4xForlifeEmail()
365 {
366 global $globals;
367 trigger_error('USING M4X FORLIFE', E_USER_NOTICE);
368 return $this->login() . '@' . $globals->mail->domain2;
e7b93962
FB
369 }
370
38c6fe96
FB
371
372 /** Get marketing informations
373 */
374 private function fetchMarketingData()
375 {
376 if (isset($this->last_known_email)) {
377 return;
378 }
379 $infos = XDB::fetchOneAssoc('SELECT IF (MAX(m.last) > p.relance, MAX(m.last), p.relance) AS last_relance,
380 p.email AS last_known_email
381 FROM register_pending AS p
382 LEFT JOIN register_marketing AS m ON (p.uid = m.uid)
383 WHERE p.uid = {?}
384 GROUP BY p.uid', $this->id());
385 if (!$infos) {
386 $infos = array('last_relance' => null, 'last_known_email' => null);
387 }
388 $this->fillFromArray($infos);
389 }
390
391 public function lastMarketingRelance()
392 {
393 $this->fetchMarketingData();
394 return $this->last_relance;
395 }
396
397 public function lastKnownEmail()
398 {
399 $this->fetchMarketingData();
400 return $this->last_known_email;
401 }
402
009b8ab7
FB
403
404 /** Get watch informations
405 */
406 private function fetchWatchData()
407 {
408 if (isset($this->watch_actions)) {
409 return;
410 }
411 $watch = XDB::fetchOneAssoc('SELECT flags AS watch_flags, actions AS watch_actions,
412 UNIX_TIMESTAMP(last) AS watch_last
413 FROM watch
414 WHERE uid = {?}', $this->id());
415 $watch['watch_flags'] = new PlFlagSet($watch['watch_flags']);
416 $watch['watch_actions'] = new PlFlagSet($watch['watch_actions']);
417 $watch['watch_promos'] = XDB::fetchColumn('SELECT promo
418 FROM watch_promo
419 WHERE uid = {?}', $this->id());
420 $watch['watch_users'] = XDB::fetchColumn('SELECT ni_id
421 FROM watch_nonins
422 WHERE uid = {?}', $this->id());
423 $this->fillFromArray($watch);
424 }
425
426 public function watch($type)
427 {
428 $this->fetchWatchData();
429 return $this->watch_actions->hasFlag($type);
430 }
431
432 public function watchContacts()
433 {
434 $this->fetchWatchData();
435 return $this->watch_flags->hasFlag('contacts');
436 }
437
438 public function watchEmail()
439 {
440 $this->fetchWatchData();
441 return $this->watch_flags->hasFlag('mail');
442 }
443
444 public function watchPromos()
445 {
446 $this->fetchWatchData();
447 return $this->watch_promos;
448 }
449
450 public function watchUsers()
451 {
452 $this->fetchWatchData();
453 return $this->watch_users;
454 }
455
456 public function watchLast()
457 {
458 $this->fetchWatchData();
459 return $this->watch_last;
460 }
461
c350577b
FB
462
463 // Contacts
464 private $contacts = null;
465 public function isContact(PlUser &$user)
466 {
76cbe885 467 if (is_null($this->contacts)) {
c350577b
FB
468 $this->contacts = XDB::fetchAllAssoc('contact', 'SELECT *
469 FROM contacts
470 WHERE uid = {?}',
471 $this->id());
472 }
473 return isset($this->contacts[$user->id()]);
474 }
475
f5ef8b57
RB
476 // Groupes X
477 private $groups = null;
478 public function groups()
479 {
480 if (is_null($this->groups)) {
481 $this->groups = XDB::fetchAllAssoc('asso_id', 'SELECT asso_id, perms, comm
185d4ea1 482 FROM group_members
f5ef8b57
RB
483 WHERE uid = {?}',
484 $this->id());
485 }
486 return $this->groups;
487 }
488
50d5ec0b 489 // Return permission flags for a given permission level.
365ba8c3 490 public static function makePerms($perms, $is_admin)
50d5ec0b 491 {
365ba8c3 492 $flags = new PlFlagSet($perms);
50d5ec0b 493 $flags->addFlag(PERMS_USER);
365ba8c3 494 if ($is_admin) {
50d5ec0b
FB
495 $flags->addFlag(PERMS_ADMIN);
496 }
497 return $flags;
498 }
499
b1719b13
VZ
500 // Implementation of the default user callback.
501 public static function _default_user_callback($login, $results)
502 {
b1719b13 503 $result_count = count($results);
dd70cd28 504 if ($result_count == 0 || !S::admin()) {
70232020 505 Platal::page()->trigError("Il n'y a pas d'utilisateur avec l'identifiant : $login");
b1719b13 506 } else {
70232020 507 Platal::page()->trigError("Il y a $result_count utilisateurs avec cet identifiant : " . join(', ', $results));
b1719b13
VZ
508 }
509 }
70232020
VZ
510
511 // Implementation of the static email locality checker.
512 public static function isForeignEmailAddress($email)
513 {
514 global $globals;
515 if (strpos($email, '@') === false) {
516 return false;
517 }
518
519 list($user, $dom) = explode('@', $email);
520 return $dom != $globals->mail->domain &&
521 $dom != $globals->mail->domain2 &&
522 $dom != $globals->mail->alias_dom &&
523 $dom != $globals->mail->alias_dom2;
524 }
832e6fcb 525
aa21c568
FB
526 public static function isVirtualEmailAddress($email)
527 {
528 global $globals;
529 if (strpos($email, '@') === false) {
530 return false;
531 }
532
533 list($user, $dom) = explode('@', $email);
534 return $dom == $globals->mail->alias_dom
535 || $dom == $globals->mail->alias_dom2;
536 }
537
832e6fcb 538 // Fetch a set of users from a list of UIDs
b774ddab 539 public static function getBulkUsersWithUIDs(array $data, $orig = null, $dest = null, $fetchProfile = true)
832e6fcb 540 {
07eb5b0e
FB
541 // Fetch the list of uids
542 if (is_null($orig)) {
543 $uids = $data;
544 } else {
545 if (is_null($dest)) {
546 $dest = $orig;
547 }
548 $uids = array();
549 foreach ($data as $key=>$entry) {
550 if (isset($entry[$orig])) {
551 $uids[] = $entry[$orig];
552 }
553 }
554 }
555
556 // Fetch users
38c6fe96 557 if (count($uids) == 0) {
07eb5b0e 558 return $data;
38c6fe96 559 }
d865c296
FB
560 $fields = self::loadMainFieldsFromUIDs($uids);
561 $table = array();
b774ddab
FB
562 if ($fetchProfile) {
563 $profiles = Profile::getBulkProfilesWithUIDS($uids);
564 }
832e6fcb 565 while (($list = $fields->next())) {
b774ddab
FB
566 $uid = $list['uid'];
567 $user = User::getSilentWithValues(null, $list);
568 if ($fetchProfile) {
569 if (isset($profiles[$uid])) {
570 $user->_profile = $profiles[$uid];
571 }
572 $user->_profile_fetched = true;
573 }
574 $table[$list['uid']] = $user;
d865c296 575 }
07eb5b0e
FB
576
577 // Build the result with respect to input order.
578 if (is_null($orig)) {
579 $users = array();
580 foreach ($uids as $key=>$uid) {
581 $users[$key] = $table[$uid];
582 }
583 return $users;
584 } else {
585 foreach ($data as $key=>$entry) {
586 if (isset($entry[$orig])) {
587 $entry[$dest] = $table[$entry[$orig]];
588 $data[$key] = $entry;
589 }
590 }
591 return $data;
832e6fcb 592 }
07eb5b0e
FB
593 }
594
b774ddab 595 public static function getBulkUsersFromDB($fetchProfile = true)
07eb5b0e
FB
596 {
597 $args = func_get_args();
598 $uids = call_user_func_array(array('XDB', 'fetchColumn'), $args);
b774ddab 599 return self::getBulkUsersWithUIDs($uids, null, null, $fetchProfile);
832e6fcb 600 }
9f8ebb9f
VZ
601}
602
603// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
604?>