2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
23 * PlUserNotFound is raised when a user id cannot be linked to a real user.
24 * The @p results give the list hruids (useful when several users are found).
26 class UserNotFoundException
extends Exception
28 public function __construct($results = array())
30 $this->results
= $results;
31 parent
::__construct();
35 interface PlUserInterface
37 public static function _default_user_callback($login, $results);
40 * Determines if the @p login is an email address, and an email address not
41 * served locally by plat/al.
43 public static function isForeignEmailAddress($email);
47 * Represents an user of plat/al (without any further assumption), with a
48 * special focus on always-used properties (identification fields, display name,
49 * forlife/bestalias emails, ...).
50 * NOTE: each implementation of plat/al-code MUST subclass PlUser, and name it
53 abstract class PlUser
implements PlUserInterface
56 * User data enumerations.
58 const GENDER_FEMALE
= true
;
59 const GENDER_MALE
= false
;
60 const FORMAT_HTML
= "html";
61 const FORMAT_TEXT
= "text";
65 * By convention, null means the information hasn't been fetched yet, and
66 * false means the information is not available.
69 // uid is internal user ID (potentially numeric), whereas hruid is a
70 // "human readable" unique ID
71 protected $uid = null
;
72 protected $hruid = null
;
74 // User main email aliases (forlife is the for-life email address, bestalias
75 // is user-chosen preferred email address, email might be any email available
77 protected $forlife = null
;
78 protected $bestalias = null
;
79 protected $email = null
;
81 // Display name is user-chosen name to display (eg. in "Welcome
82 // <display name> !"), while full name is the official full name.
83 protected $display_name = null
;
84 protected $full_name = null
;
85 protected $sort_name = null
;
87 // Other important parameters used when sending emails.
88 protected $gender = null
; // Acceptable values are GENDER_MALE and GENDER_FEMALE
89 protected $email_format = null
; // Acceptable values are FORMAT_HTML and FORMAT_TEXT
92 protected $perms = null
;
93 protected $perm_flags = null
;
95 // Other properties are listed in this key-value hash map.
96 protected $data = array();
99 * Constructs the PlUser object from an identifier (any identifier which is
100 * understood by getLogin() implementation).
102 * @param $login An user login.
103 * @param $values List of known user properties.
105 public function __construct($login, $values = array())
107 $this->fillFromArray($values);
109 // If the user id was not part of the known values, determines it from
112 $this->uid
= $this->getLogin($login);
115 // Preloads main properties (assumes the loader will lazily get them
116 // from variables already set in the object).
117 $this->loadMainFields();
121 * Get the canonical user id for the @p login.
123 * @param $login An user login.
124 * @return The canonical user id.
125 * @throws UserNotFoundException when login is not found.
127 abstract protected function getLogin($login);
130 * Loads the main properties (hruid, forlife, bestalias, ...) from the
131 * database. Should return immediately when the properties are already
134 abstract protected function loadMainFields();
137 * Accessors to the main properties, ie. those available as top level
145 public function login()
150 public function isMe($other)
154 } else if ($other instanceof PlUser
) {
155 return $other->id() == $this->id();
161 public function bestEmail()
163 if (!empty($this->bestalias
)) {
164 return $this->bestalias
;
168 public function forlifeEmail()
170 if (!empty($this->forlife
)) {
171 return $this->forlife
;
176 public function displayName()
178 return $this->display_name
;
180 public function fullName()
182 return $this->full_name
;
185 abstract public function password();
187 // Fallback value is GENDER_MALE.
188 public function isFemale()
190 return $this->gender
== self
::GENDER_FEMALE
;
193 // Fallback value is FORMAT_TEXT.
194 public function isEmailFormatHtml()
196 return $this->email_format
== self
::FORMAT_HTML
;
200 * Other properties are available directly through the $data array, or as
201 * standard object variables, using a getter.
203 public function data()
208 public function __get($name)
210 if (property_exists($this, $name)) {
214 if (isset($this->data
[$name])) {
215 return $this->data
[$name];
221 public function __isset($name)
223 return property_exists($this, $name) ||
isset($this->data
[$name]);
226 public function __unset($name)
228 if (property_exists($this, $name)) {
231 unset($this->data
[$name]);
236 * Fills the object properties using the @p associative array; the intended
237 * user case is to fill the object using SQL obtained arrays.
239 * @param $values Key-value array of user properties.
241 protected function fillFromArray(array $values)
243 // Merge main properties with existing ones.
244 unset($values['data']);
245 foreach ($values as $key => $value) {
246 if (property_exists($this, $key) && !isset($this->$key)) {
247 $this->$key = $value;
251 // Merge all value into the $this->data placeholder.
252 $this->data
= array_merge($this->data
, $values);
256 * Adds properties to the object; this method does not allow the caller to
257 * update core properties (id, ...).
259 * @param $values An associative array of non-core properties.
261 public function addProperties(array $values)
263 foreach ($values as $key => $value) {
264 if (!property_exists($this, $key)) {
265 $this->data
[$key] = $value;
272 * Build the permissions flags for the user.
274 abstract protected function buildPerms();
277 * Check wether the user got the given permission combination.
279 public function checkPerms($perms)
281 if (is_null($this->perm_flags
)) {
284 if (is_null($this->perm_flags
)) {
287 return $this->perm_flags
->hasFlagCombination($perms);
292 * Returns a valid User object built from the @p id and optionnal @p values,
293 * or returns false and calls the callback if the @p id is not valid.
295 public static function get($login, $callback = false
)
297 return User
::getWithValues($login, array(), $callback);
300 public static function getWithValues($login, $values, $callback = false
)
303 $callback = array('User', '_default_user_callback');
307 return new User($login, $values);
308 } catch (UserNotFoundException
$e) {
309 return call_user_func($callback, $login, $e->results
);
313 public static function getWithUID($uid, $callback = false
)
315 return User
::getWithValues(null
, array('uid' => $uid), $callback);
318 // Same as above, but using the silent callback as default.
319 public static function getSilent($login)
321 return User
::getWithValues($login, array(), array('User', '_silent_user_callback'));
324 public static function getSilentWithValues($login, $values)
326 return User
::getWithValues($login, $values, array('User', '_silent_user_callback'));
329 public static function getSilentWithUID($uid)
331 return User
::getWithValues(null
, array('uid' => $uid), array('User', '_silent_user_callback'));
335 * Retrieves User objects corresponding to the @p logins, and eventually
336 * extracts and returns the @p property. If @p strict mode is disabled, it
337 * also includes logins for which no forlife was found (but it still calls
338 * the callback for them).
339 * In all cases, email addresses which are not from the local domains are
342 * @param $logins Array of user logins.
343 * @param $property Property to retrieve from the User objects.
344 * @param $strict Should unvalidated logins be returned as-is or discarded ?
345 * @param $callback Callback to call when a login is unknown to the system.
346 * @return Array of validated user forlife emails.
348 private static function getBulkUserProperties($logins, $property, $strict, $callback)
350 if (!is_array($logins)) {
351 if (strlen(trim($logins)) == 0) {
354 $logins = preg_split("/[; ,\r\n\|]+/", $logins);
359 foreach ($logins as $i => $login) {
360 $login = trim($login);
365 if (($user = User
::get($login, $callback))) {
366 $list[$i] = $user->$property();
367 } else if (!$strict ||
(User
::isForeignEmailAddress($login) && isvalid_email($login))) {
371 return array_unique($list);
377 * Returns hruid corresponding to the @p logins. See getBulkUserProperties()
380 public static function getBulkHruid($logins, $callback = false
)
382 return self
::getBulkUserProperties($logins, 'login', true
, $callback);
386 * Returns forlife emails corresponding to the @p logins. See
387 * getBulkUserProperties() for details.
389 public static function getBulkForlifeEmails($logins, $strict = true
, $callback = false
)
391 return self
::getBulkUserProperties($logins, 'forlifeEmail', $strict, $callback);
395 * Predefined callbacks for the user lookup; they are called when a given
396 * login is found not to be associated with any valid user. Silent callback
397 * does nothing; default callback is supposed to display an error message,
398 * using the Platal::page() hook.
400 public static function _silent_user_callback($login, $results)
405 private static function stripBadChars($text)
407 return str_replace(array(' ', "'", '+'), array('-', '', '_'),
408 strtolower(stripslashes(replace_accent(trim($text)))));
411 /** Creates a username from a first and last name
412 * @param $firstname User's firstname
413 * @param $lasttname User's lastname
414 * return STRING the corresponding username
416 public static function makeUserName($firstname, $lastname)
418 return self
::stripBadChars($firstname) . '.' . self
::stripBadChars($lastname);
422 * Creates a user forlive identifier from:
423 * @param $firstname User's firstname
424 * @param $lasttname User's lastname
425 * @param $category User's promotion or type of account
427 public static function makeHrid($firstname, $lastname, $category)
429 $cat = self
::stripBadChars($category);
431 Platal
::page()->kill("$category is not a suitable category.");
434 return self
::makeUserName($firstname, $lastname) . '.' . $cat;
437 /** Reformats the firstname so that all letters are in lower case,
438 * except the first letter of each part of the name.
440 public static function fixFirstnameCase($firstname)
442 $firstname = strtolower($firstname);
443 $pieces = explode('-', $firstname);
445 foreach ($pieces as $piece) {
446 $subpieces = explode("'", $piece);
449 foreach ($subpieces as $subpiece) {
450 $usubpieces[] = ucwords($subpiece);
452 $upieces[] = implode("'", $usubpieces);
454 return implode('-', $upieces);
458 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8: