Add interface PlIteraface and the corresponding abstract class
[platal.git] / classes / pluser.php
CommitLineData
5421ab09
VZ
1<?php
2/***************************************************************************
2ab75571 3 * Copyright (C) 2003-2010 Polytechnique.org *
5421ab09
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
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 */
26class UserNotFoundException extends Exception
27{
28 public function __construct($results = array())
29 {
30 $this->results = $results;
31 parent::__construct();
32 }
33}
34
9e394323
R
35interface 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
5421ab09
VZ
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 */
9e394323 53abstract class PlUser implements PlUserInterface
5421ab09
VZ
54{
55 /**
8829b862
VZ
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 /**
5421ab09
VZ
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 */
6c36b907 68
643ae90b 69 // uid is internal user ID (potentially numeric), whereas hruid is a
6c36b907 70 // "human readable" unique ID
643ae90b 71 protected $uid = null;
5421ab09
VZ
72 protected $hruid = null;
73
74 // User main email aliases (forlife is the for-life email address, bestalias
3f0fafbd
RB
75 // is user-chosen preferred email address, email might be any email available
76 // for the user).
5421ab09
VZ
77 protected $forlife = null;
78 protected $bestalias = null;
3f0fafbd 79 protected $email = null;
5421ab09
VZ
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;
5421ab09 85
8829b862
VZ
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
f8b161ad
FB
90 // Permissions
91 protected $perms = null;
92 protected $perm_flags = null;
93
5421ab09
VZ
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.
643ae90b
SJ
110 if (!$this->uid) {
111 $this->uid = $this->getLogin($login);
5421ab09
VZ
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 */
f8b161ad
FB
139 public function id()
140 {
643ae90b 141 return $this->uid;
f8b161ad 142 }
5421ab09 143
f8b161ad
FB
144 public function login()
145 {
146 return $this->hruid;
147 }
5421ab09 148
f8b161ad
FB
149 public function bestEmail()
150 {
f992b7a5
PC
151 if (!empty($this->bestalias)) {
152 return $this->bestalias;
153 }
154 return $this->email;
f8b161ad
FB
155 }
156 public function forlifeEmail()
157 {
f992b7a5
PC
158 if (!empty($this->forlife)) {
159 return $this->forlife;
160 }
161 return $this->email;
f8b161ad
FB
162 }
163
164 public function displayName()
165 {
166 return $this->display_name;
167 }
168 public function fullName()
169 {
170 return $this->full_name;
171 }
5421ab09 172
35fff9b0
FB
173 abstract public function password();
174
8829b862
VZ
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
5421ab09
VZ
187 /**
188 * Other properties are available directly through the $data array, or as
189 * standard object variables, using a getter.
190 */
f8b161ad
FB
191 public function data()
192 {
193 return $this->data;
194 }
5421ab09
VZ
195
196 public function __get($name)
197 {
9ddc36c1 198 if (property_exists($this, $name)) {
5421ab09
VZ
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 {
9ddc36c1 211 return property_exists($this, $name) || isset($this->data[$name]);
5421ab09
VZ
212 }
213
fd05958d
FB
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
5421ab09
VZ
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
9ddc36c1
VZ
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
5421ab09
VZ
258
259 /**
f8b161ad
FB
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 /**
5421ab09
VZ
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
933e1c23
FB
301 public static function getWithUID($uid, $callback = false)
302 {
643ae90b 303 return User::getWithValues(null, array('uid' => $uid), $callback);
933e1c23
FB
304 }
305
5421ab09
VZ
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
933e1c23
FB
317 public static function getSilentWithUID($uid)
318 {
643ae90b 319 return User::getWithValues(null, array('uid' => $uid), array('User', '_silent_user_callback'));
933e1c23
FB
320 }
321
5421ab09 322 /**
40d6b19a
VZ
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).
5421ab09
VZ
327 * In all cases, email addresses which are not from the local domains are
328 * kept.
329 *
330 * @param $logins Array of user logins.
40d6b19a 331 * @param $property Property to retrieve from the User objects.
5421ab09
VZ
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 */
40d6b19a 336 private static function getBulkUserProperties($logins, $property, $strict, $callback)
5421ab09
VZ
337 {
338 if (!is_array($logins)) {
339 if (strlen(trim($logins)) == 0) {
340 return null;
341 }
9e394323 342 $logins = preg_split("/[; ,\r\n\|]+/", $logins);
5421ab09
VZ
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))) {
40d6b19a 354 $list[$i] = $user->$property();
b9ca76f9 355 } else if (!$strict || (User::isForeignEmailAddress($login) && isvalid_email($login))) {
5421ab09
VZ
356 $list[$i] = $login;
357 }
358 }
359 return $list;
360 }
361 return null;
362 }
363
364 /**
40d6b19a
VZ
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 /**
5421ab09
VZ
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
cdf1c82b
SJ
393 private static function stripBadChars($text)
394 {
395 return str_replace(array(' ', "'"), array('-', ''),
a95dcb6e 396 strtolower(stripslashes(replace_accent(trim($text)))));
cdf1c82b
SJ
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 */
2a683f7f 404 public static function makeUserName($firstname, $lastname)
cdf1c82b
SJ
405 {
406 return self::stripBadChars($firstname) . '.' . self::stripBadChars($lastname);
407 }
408
0be5c71c
SJ
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 {
cdf1c82b
SJ
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;
0be5c71c
SJ
423 }
424
a95dcb6e
SJ
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 = '';
0be5c71c 436
a95dcb6e
SJ
437 foreach ($subpieces as $subpiece) {
438 $usubpieces[] = ucwords($subpiece);
439 }
440 $upieces[] = implode("'", $usubpieces);
441 }
442 return implode('-', $upieces);
443 }
5421ab09
VZ
444}
445
446// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
447?>