2 /***************************************************************************
3 * Copyright (C) 2003-2010 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();
36 * Represents an user of plat/al (without any further assumption), with a
37 * special focus on always-used properties (identification fields, display name,
38 * forlife/bestalias emails, ...).
39 * NOTE: each implementation of plat/al-code MUST subclass PlUser, and name it
45 * User data enumerations.
47 const GENDER_FEMALE
= true
;
48 const GENDER_MALE
= false
;
49 const FORMAT_HTML
= "html";
50 const FORMAT_TEXT
= "text";
54 * By convention, null means the information hasn't been fetched yet, and
55 * false means the information is not available.
58 // uid is internal user ID (potentially numeric), whereas hruid is a
59 // "human readable" unique ID
60 protected $uid = null
;
61 protected $hruid = null
;
63 // User main email aliases (forlife is the for-life email address, bestalias
64 // is user-chosen preferred email address).
65 protected $forlife = null
;
66 protected $bestalias = null
;
68 // Display name is user-chosen name to display (eg. in "Welcome
69 // <display name> !"), while full name is the official full name.
70 protected $display_name = null
;
71 protected $full_name = null
;
73 // Other important parameters used when sending emails.
74 protected $gender = null
; // Acceptable values are GENDER_MALE and GENDER_FEMALE
75 protected $email_format = null
; // Acceptable values are FORMAT_HTML and FORMAT_TEXT
78 protected $perms = null
;
79 protected $perm_flags = null
;
81 // Other properties are listed in this key-value hash map.
82 protected $data = array();
85 * Constructs the PlUser object from an identifier (any identifier which is
86 * understood by getLogin() implementation).
88 * @param $login An user login.
89 * @param $values List of known user properties.
91 public function __construct($login, $values = array())
93 $this->fillFromArray($values);
95 // If the user id was not part of the known values, determines it from
98 $this->uid
= $this->getLogin($login);
101 // Preloads main properties (assumes the loader will lazily get them
102 // from variables already set in the object).
103 $this->loadMainFields();
107 * Get the canonical user id for the @p login.
109 * @param $login An user login.
110 * @return The canonical user id.
111 * @throws UserNotFoundException when login is not found.
113 abstract protected function getLogin($login);
116 * Loads the main properties (hruid, forlife, bestalias, ...) from the
117 * database. Should return immediately when the properties are already
120 abstract protected function loadMainFields();
123 * Accessors to the main properties, ie. those available as top level
131 public function login()
136 public function bestEmail()
138 return $this->bestalias
;
140 public function forlifeEmail()
142 return $this->forlife
;
145 public function displayName()
147 return $this->display_name
;
149 public function fullName()
151 return $this->full_name
;
154 abstract public function password();
156 // Fallback value is GENDER_MALE.
157 public function isFemale()
159 return $this->gender
== self
::GENDER_FEMALE
;
162 // Fallback value is FORMAT_TEXT.
163 public function isEmailFormatHtml()
165 return $this->email_format
== self
::FORMAT_HTML
;
169 * Other properties are available directly through the $data array, or as
170 * standard object variables, using a getter.
172 public function data()
177 public function __get($name)
179 if (property_exists($this, $name)) {
183 if (isset($this->data
[$name])) {
184 return $this->data
[$name];
190 public function __isset($name)
192 return property_exists($this, $name) ||
isset($this->data
[$name]);
195 public function __unset($name)
197 if (property_exists($this, $name)) {
200 unset($this->data
[$name]);
205 * Fills the object properties using the @p associative array; the intended
206 * user case is to fill the object using SQL obtained arrays.
208 * @param $values Key-value array of user properties.
210 protected function fillFromArray(array $values)
212 // Merge main properties with existing ones.
213 unset($values['data']);
214 foreach ($values as $key => $value) {
215 if (property_exists($this, $key) && !isset($this->$key)) {
216 $this->$key = $value;
220 // Merge all value into the $this->data placeholder.
221 $this->data
= array_merge($this->data
, $values);
225 * Adds properties to the object; this method does not allow the caller to
226 * update core properties (id, ...).
228 * @param $values An associative array of non-core properties.
230 public function addProperties(array $values)
232 foreach ($values as $key => $value) {
233 if (!property_exists($this, $key)) {
234 $this->data
[$key] = $value;
241 * Build the permissions flags for the user.
243 abstract protected function buildPerms();
246 * Check wether the user got the given permission combination.
248 public function checkPerms($perms)
250 if (is_null($this->perm_flags
)) {
253 if (is_null($this->perm_flags
)) {
256 return $this->perm_flags
->hasFlagCombination($perms);
261 * Returns a valid User object built from the @p id and optionnal @p values,
262 * or returns false and calls the callback if the @p id is not valid.
264 public static function get($login, $callback = false
)
266 return User
::getWithValues($login, array(), $callback);
269 public static function getWithValues($login, $values, $callback = false
)
272 $callback = array('User', '_default_user_callback');
276 return new User($login, $values);
277 } catch (UserNotFoundException
$e) {
278 return call_user_func($callback, $login, $e->results
);
282 public static function getWithUID($uid, $callback = false
)
284 return User
::getWithValues(null
, array('uid' => $uid), $callback);
287 // Same as above, but using the silent callback as default.
288 public static function getSilent($login)
290 return User
::getWithValues($login, array(), array('User', '_silent_user_callback'));
293 public static function getSilentWithValues($login, $values)
295 return User
::getWithValues($login, $values, array('User', '_silent_user_callback'));
298 public static function getSilentWithUID($uid)
300 return User
::getWithValues(null
, array('uid' => $uid), array('User', '_silent_user_callback'));
304 * Retrieves User objects corresponding to the @p logins, and eventually
305 * extracts and returns the @p property. If @p strict mode is disabled, it
306 * also includes logins for which no forlife was found (but it still calls
307 * the callback for them).
308 * In all cases, email addresses which are not from the local domains are
311 * @param $logins Array of user logins.
312 * @param $property Property to retrieve from the User objects.
313 * @param $strict Should unvalidated logins be returned as-is or discarded ?
314 * @param $callback Callback to call when a login is unknown to the system.
315 * @return Array of validated user forlife emails.
317 private static function getBulkUserProperties($logins, $property, $strict, $callback)
319 if (!is_array($logins)) {
320 if (strlen(trim($logins)) == 0) {
323 $logins = split("[; ,\r\n\|]+", $logins);
328 foreach ($logins as $i => $login) {
329 $login = trim($login);
334 if (($user = User
::get($login, $callback))) {
335 $list[$i] = $user->$property();
336 } else if (!$strict ||
(User
::isForeignEmailAddress($login) && isvalid_email($login))) {
346 * Returns hruid corresponding to the @p logins. See getBulkUserProperties()
349 public static function getBulkHruid($logins, $callback = false
)
351 return self
::getBulkUserProperties($logins, 'login', true
, $callback);
355 * Returns forlife emails corresponding to the @p logins. See
356 * getBulkUserProperties() for details.
358 public static function getBulkForlifeEmails($logins, $strict = true
, $callback = false
)
360 return self
::getBulkUserProperties($logins, 'forlifeEmail', $strict, $callback);
364 * Predefined callbacks for the user lookup; they are called when a given
365 * login is found not to be associated with any valid user. Silent callback
366 * does nothing; default callback is supposed to display an error message,
367 * using the Platal::page() hook.
369 public static function _silent_user_callback($login, $results)
374 abstract public static function _default_user_callback($login, $results);
377 * Determines if the @p login is an email address, and an email address not
378 * served locally by plat/al.
380 abstract public static function isForeignEmailAddress($email);
382 private static function stripBadChars($text)
384 return str_replace(array(' ', "'"), array('-', ''),
385 strtolower(stripslashes(replace_accent(trim($text)))));
388 /** Creates a username from a first and last name
389 * @param $firstname User's firstname
390 * @param $lasttname User's lastname
391 * return STRING the corresponding username
393 public static function makeUserName($firstname, $lastname)
395 return self
::stripBadChars($firstname) . '.' . self
::stripBadChars($lastname);
399 * Creates a user forlive identifier from:
400 * @param $firstname User's firstname
401 * @param $lasttname User's lastname
402 * @param $category User's promotion or type of account
404 public static function makeHrid($firstname, $lastname, $category)
406 $cat = self
::stripBadChars($category);
408 Platal
::page()->kill("$category is not a suitable category.");
411 return self
::makeUserName($firstname, $lastname) . '.' . $cat;
414 /** Reformats the firstname so that all letters are in lower case,
415 * except the first letter of each part of the name.
417 public static function fixFirstnameCase($firstname)
419 $firstname = strtolower($firstname);
420 $pieces = explode('-', $firstname);
422 foreach ($pieces as $piece) {
423 $subpieces = explode("'", $piece);
426 foreach ($subpieces as $subpiece) {
427 $usubpieces[] = ucwords($subpiece);
429 $upieces[] = implode("'", $usubpieces);
431 return implode('-', $upieces);
435 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: