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