Add interface PlIteraface and the corresponding abstract class
[platal.git] / classes / pluser.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 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 /**
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).
25 */
26 class UserNotFoundException extends Exception
27 {
28 public function __construct($results = array())
29 {
30 $this->results = $results;
31 parent::__construct();
32 }
33 }
34
35 interface PlUserInterface
36 {
37 public static function _default_user_callback($login, $results);
38
39 /**
40 * Determines if the @p login is an email address, and an email address not
41 * served locally by plat/al.
42 */
43 public static function isForeignEmailAddress($email);
44 }
45
46 /**
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
51 * 'User'.
52 */
53 abstract class PlUser implements PlUserInterface
54 {
55 /**
56 * User data enumerations.
57 */
58 const GENDER_FEMALE = true;
59 const GENDER_MALE = false;
60 const FORMAT_HTML = "html";
61 const FORMAT_TEXT = "text";
62
63 /**
64 * User data storage.
65 * By convention, null means the information hasn't been fetched yet, and
66 * false means the information is not available.
67 */
68
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;
73
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
76 // for the user).
77 protected $forlife = null;
78 protected $bestalias = null;
79 protected $email = null;
80
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
86 // Other important parameters used when sending emails.
87 protected $gender = null; // Acceptable values are GENDER_MALE and GENDER_FEMALE
88 protected $email_format = null; // Acceptable values are FORMAT_HTML and FORMAT_TEXT
89
90 // Permissions
91 protected $perms = null;
92 protected $perm_flags = null;
93
94 // Other properties are listed in this key-value hash map.
95 protected $data = array();
96
97 /**
98 * Constructs the PlUser object from an identifier (any identifier which is
99 * understood by getLogin() implementation).
100 *
101 * @param $login An user login.
102 * @param $values List of known user properties.
103 */
104 public function __construct($login, $values = array())
105 {
106 $this->fillFromArray($values);
107
108 // If the user id was not part of the known values, determines it from
109 // the login.
110 if (!$this->uid) {
111 $this->uid = $this->getLogin($login);
112 }
113
114 // Preloads main properties (assumes the loader will lazily get them
115 // from variables already set in the object).
116 $this->loadMainFields();
117 }
118
119 /**
120 * Get the canonical user id for the @p login.
121 *
122 * @param $login An user login.
123 * @return The canonical user id.
124 * @throws UserNotFoundException when login is not found.
125 */
126 abstract protected function getLogin($login);
127
128 /**
129 * Loads the main properties (hruid, forlife, bestalias, ...) from the
130 * database. Should return immediately when the properties are already
131 * available.
132 */
133 abstract protected function loadMainFields();
134
135 /**
136 * Accessors to the main properties, ie. those available as top level
137 * object variables.
138 */
139 public function id()
140 {
141 return $this->uid;
142 }
143
144 public function login()
145 {
146 return $this->hruid;
147 }
148
149 public function bestEmail()
150 {
151 if (!empty($this->bestalias)) {
152 return $this->bestalias;
153 }
154 return $this->email;
155 }
156 public function forlifeEmail()
157 {
158 if (!empty($this->forlife)) {
159 return $this->forlife;
160 }
161 return $this->email;
162 }
163
164 public function displayName()
165 {
166 return $this->display_name;
167 }
168 public function fullName()
169 {
170 return $this->full_name;
171 }
172
173 abstract public function password();
174
175 // Fallback value is GENDER_MALE.
176 public function isFemale()
177 {
178 return $this->gender == self::GENDER_FEMALE;
179 }
180
181 // Fallback value is FORMAT_TEXT.
182 public function isEmailFormatHtml()
183 {
184 return $this->email_format == self::FORMAT_HTML;
185 }
186
187 /**
188 * Other properties are available directly through the $data array, or as
189 * standard object variables, using a getter.
190 */
191 public function data()
192 {
193 return $this->data;
194 }
195
196 public function __get($name)
197 {
198 if (property_exists($this, $name)) {
199 return $this->$name;
200 }
201
202 if (isset($this->data[$name])) {
203 return $this->data[$name];
204 }
205
206 return null;
207 }
208
209 public function __isset($name)
210 {
211 return property_exists($this, $name) || isset($this->data[$name]);
212 }
213
214 public function __unset($name)
215 {
216 if (property_exists($this, $name)) {
217 $this->$name = null;
218 } else {
219 unset($this->data[$name]);
220 }
221 }
222
223 /**
224 * Fills the object properties using the @p associative array; the intended
225 * user case is to fill the object using SQL obtained arrays.
226 *
227 * @param $values Key-value array of user properties.
228 */
229 protected function fillFromArray(array $values)
230 {
231 // Merge main properties with existing ones.
232 unset($values['data']);
233 foreach ($values as $key => $value) {
234 if (property_exists($this, $key) && !isset($this->$key)) {
235 $this->$key = $value;
236 }
237 }
238
239 // Merge all value into the $this->data placeholder.
240 $this->data = array_merge($this->data, $values);
241 }
242
243 /**
244 * Adds properties to the object; this method does not allow the caller to
245 * update core properties (id, ...).
246 *
247 * @param $values An associative array of non-core properties.
248 */
249 public function addProperties(array $values)
250 {
251 foreach ($values as $key => $value) {
252 if (!property_exists($this, $key)) {
253 $this->data[$key] = $value;
254 }
255 }
256 }
257
258
259 /**
260 * Build the permissions flags for the user.
261 */
262 abstract protected function buildPerms();
263
264 /**
265 * Check wether the user got the given permission combination.
266 */
267 public function checkPerms($perms)
268 {
269 if (is_null($this->perm_flags)) {
270 $this->buildPerms();
271 }
272 if (is_null($this->perm_flags)) {
273 return false;
274 }
275 return $this->perm_flags->hasFlagCombination($perms);
276 }
277
278
279 /**
280 * Returns a valid User object built from the @p id and optionnal @p values,
281 * or returns false and calls the callback if the @p id is not valid.
282 */
283 public static function get($login, $callback = false)
284 {
285 return User::getWithValues($login, array(), $callback);
286 }
287
288 public static function getWithValues($login, $values, $callback = false)
289 {
290 if (!$callback) {
291 $callback = array('User', '_default_user_callback');
292 }
293
294 try {
295 return new User($login, $values);
296 } catch (UserNotFoundException $e) {
297 return call_user_func($callback, $login, $e->results);
298 }
299 }
300
301 public static function getWithUID($uid, $callback = false)
302 {
303 return User::getWithValues(null, array('uid' => $uid), $callback);
304 }
305
306 // Same as above, but using the silent callback as default.
307 public static function getSilent($login)
308 {
309 return User::getWithValues($login, array(), array('User', '_silent_user_callback'));
310 }
311
312 public static function getSilentWithValues($login, $values)
313 {
314 return User::getWithValues($login, $values, array('User', '_silent_user_callback'));
315 }
316
317 public static function getSilentWithUID($uid)
318 {
319 return User::getWithValues(null, array('uid' => $uid), array('User', '_silent_user_callback'));
320 }
321
322 /**
323 * Retrieves User objects corresponding to the @p logins, and eventually
324 * extracts and returns the @p property. If @p strict mode is disabled, it
325 * also includes logins for which no forlife was found (but it still calls
326 * the callback for them).
327 * In all cases, email addresses which are not from the local domains are
328 * kept.
329 *
330 * @param $logins Array of user logins.
331 * @param $property Property to retrieve from the User objects.
332 * @param $strict Should unvalidated logins be returned as-is or discarded ?
333 * @param $callback Callback to call when a login is unknown to the system.
334 * @return Array of validated user forlife emails.
335 */
336 private static function getBulkUserProperties($logins, $property, $strict, $callback)
337 {
338 if (!is_array($logins)) {
339 if (strlen(trim($logins)) == 0) {
340 return null;
341 }
342 $logins = preg_split("/[; ,\r\n\|]+/", $logins);
343 }
344
345 if ($logins) {
346 $list = array();
347 foreach ($logins as $i => $login) {
348 $login = trim($login);
349 if (empty($login)) {
350 continue;
351 }
352
353 if (($user = User::get($login, $callback))) {
354 $list[$i] = $user->$property();
355 } else if (!$strict || (User::isForeignEmailAddress($login) && isvalid_email($login))) {
356 $list[$i] = $login;
357 }
358 }
359 return $list;
360 }
361 return null;
362 }
363
364 /**
365 * Returns hruid corresponding to the @p logins. See getBulkUserProperties()
366 * for details.
367 */
368 public static function getBulkHruid($logins, $callback = false)
369 {
370 return self::getBulkUserProperties($logins, 'login', true, $callback);
371 }
372
373 /**
374 * Returns forlife emails corresponding to the @p logins. See
375 * getBulkUserProperties() for details.
376 */
377 public static function getBulkForlifeEmails($logins, $strict = true, $callback = false)
378 {
379 return self::getBulkUserProperties($logins, 'forlifeEmail', $strict, $callback);
380 }
381
382 /**
383 * Predefined callbacks for the user lookup; they are called when a given
384 * login is found not to be associated with any valid user. Silent callback
385 * does nothing; default callback is supposed to display an error message,
386 * using the Platal::page() hook.
387 */
388 public static function _silent_user_callback($login, $results)
389 {
390 return;
391 }
392
393 private static function stripBadChars($text)
394 {
395 return str_replace(array(' ', "'"), array('-', ''),
396 strtolower(stripslashes(replace_accent(trim($text)))));
397 }
398
399 /** Creates a username from a first and last name
400 * @param $firstname User's firstname
401 * @param $lasttname User's lastname
402 * return STRING the corresponding username
403 */
404 public static function makeUserName($firstname, $lastname)
405 {
406 return self::stripBadChars($firstname) . '.' . self::stripBadChars($lastname);
407 }
408
409 /**
410 * Creates a user forlive identifier from:
411 * @param $firstname User's firstname
412 * @param $lasttname User's lastname
413 * @param $category User's promotion or type of account
414 */
415 public static function makeHrid($firstname, $lastname, $category)
416 {
417 $cat = self::stripBadChars($category);
418 if (!cat) {
419 Platal::page()->kill("$category is not a suitable category.");
420 }
421
422 return self::makeUserName($firstname, $lastname) . '.' . $cat;
423 }
424
425 /** Reformats the firstname so that all letters are in lower case,
426 * except the first letter of each part of the name.
427 */
428 public static function fixFirstnameCase($firstname)
429 {
430 $firstname = strtolower($firstname);
431 $pieces = explode('-', $firstname);
432
433 foreach ($pieces as $piece) {
434 $subpieces = explode("'", $piece);
435 $usubpieces = '';
436
437 foreach ($subpieces as $subpiece) {
438 $usubpieces[] = ucwords($subpiece);
439 }
440 $upieces[] = implode("'", $usubpieces);
441 }
442 return implode('-', $upieces);
443 }
444 }
445
446 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
447 ?>