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