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