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