]> git.mxchange.org Git - shipsimu.git/blob - inc/classes/main/user/class_User.php
Fixes for XHTML validity
[shipsimu.git] / inc / classes / main / user / class_User.php
1 <?php
2 /**
3  * A generic class for handling users
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright(c) 2007, 2008 Roland Haeder, this is free software
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <http://www.gnu.org/licenses/>.
23  */
24 class User extends BaseFrameworkSystem implements ManageableUser, Registerable {
25         /**
26          * Instance of the database result
27          */
28         private $resultInstance = null;
29
30         /**
31          * Username of current user
32          */
33         private $userName = "";
34
35         /**
36          * Email of current user
37          */
38         private $email = "";
39
40         // Exceptions
41         const EXCEPTION_USERNAME_NOT_FOUND   = 0x600;
42         const EXCEPTION_USER_EMAIL_NOT_FOUND = 0x601;
43         const EXCEPTION_USER_PASS_MISMATCH   = 0x602;
44
45         /**
46          * Protected constructor
47          *
48          * @param       $className      Name of the class
49          * @return      void
50          */
51         protected function __construct ($className = "") {
52                 // Is the class name empty? Then this is not a specialized user class
53                 if (empty($className)) $className = __CLASS__;
54
55                 // Call parent constructor
56                 parent::__construct($className);
57
58                 // Set part description
59                 $this->setObjectDescription("Generic user class");
60
61                 // Create unique ID number
62                 $this->generateUniqueId();
63
64                 // Clean up a little
65                 $this->removeNumberFormaters();
66                 $this->removeSystemArray();
67         }
68
69         /**
70          * Creates an instance of this user class by a provided username. This
71          * factory method will check if the username is already taken and if not
72          * so it will throw an exception.
73          *
74          * @param       $userName               Username we need a class instance for
75          * @return      $userInstance   An instance of this user class
76          * @throws      UsernameMissingException        If the username does not exist
77          */
78         public final static function createUserByUsername ($userName) {
79                 // Get a new instance
80                 $userInstance = new User();
81
82                 // Set the username
83                 $userInstance->setUserName($userName);
84
85                 // Check if the username exists
86                 if (!$userInstance->ifUsernameExists()) {
87                         // Throw an exception here
88                         throw new UsernameMissingException(array($userInstance, $userName), self::EXCEPTION_USERNAME_NOT_FOUND);
89                 }
90
91                 // Return the instance
92                 return $userInstance;
93         }
94
95         /**
96          * Creates an instance of this user class by a provided email address. This
97          * factory method will not check if the email address is there.
98          *
99          * @param       $email                  Email address of the user
100          * @return      $userInstance   An instance of this user class
101          */
102         public final static function createUserByEmail ($email) {
103                 // Get a new instance
104                 $userInstance = new User();
105
106                 // Set the username
107                 $userInstance->setEmail($email);
108
109                 // Return the instance
110                 return $userInstance;
111         }
112
113         /**
114          * Creates a user by a given request instance
115          *
116          * @param       $requestInstance        An instance of a Requestable class
117          * @return      $userInstance           An instance of this user class
118          */
119         public final static function createUserByRequest (Requestable $requestInstance) {
120                 // Determine if by email or username
121                 if (!is_null($requestInstance->getRequestElement('username'))) {
122                         // Username supplied
123                         $userInstance = self::createUserByUserName($requestInstance->getRequestElement('username'));
124                 } elseif (!is_null($requestInstance->getRequestElement('email'))) {
125                         // Email supplied
126                         $userInstance = self::createUserByEmail($requestInstance->getRequestElement('email'));
127                 } else {
128                         // Unsupported mode
129                         $userInstance = new User();
130                         $userInstance->partialStub("We need to add more ways of creating user classes here.");
131                         $userInstance->debugBackTrace();
132                         exit();
133                 }
134
135                 // Return the prepared instance
136                 return $userInstance;
137         }
138
139         /**
140          * "Getter" for databse entry
141          *
142          * @return      $entry  An array with database entries
143          * @throws      NullPointerException    If the database result is not found
144          * @throws      InvalidDatabaseResultException  If the database result is invalid
145          */
146         private function getDatabaseEntry () {
147                 // Is there an instance?
148                 if (is_null($this->resultInstance)) {
149                         // Throw new exception
150                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
151                 } // END - if
152
153                 // Rewind it
154                 $this->resultInstance->rewind();
155
156                 // Do we have an entry?
157                 if (!$this->resultInstance->valid()) {
158                         throw new InvalidDatabaseResultException(array($this, $this->resultInstance), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
159                 } // END - if
160
161                 // Get next entry
162                 $this->resultInstance->next();
163
164                 // Fetch it
165                 $entry = $this->resultInstance->current();
166
167                 // And return it
168                 return $entry;
169         }
170
171         /**
172          * Setter for username
173          *
174          * @param       $userName       The username to set
175          * @return      void
176          */
177         public final function setUserName ($userName) {
178                 $this->userName = $userName;
179         }
180
181         /**
182          * Setter for email
183          *
184          * @param       $email  The email to set
185          * @return      void
186          */
187         protected final function setEmail ($email) {
188                 $this->email = $email;
189         }
190
191         /**
192          * Getter for username
193          *
194          * @return      $userName       The username to get
195          */
196         public final function getUsername () {
197                 return $this->userName;
198         }
199
200         /**
201          * Getter for email
202          *
203          * @return      $email  The email to get
204          */
205         public final function getEmail () {
206                 return $this->email;
207         }
208
209         /**
210          * Determines wether the username exists or not
211          *
212          * @return      $exists         Wether the username exists
213          */
214         public function ifUsernameExists () {
215                 // By default the username does not exist
216                 $exists = false;
217
218                 // Is a previous result there?
219                 if (is_null($this->resultInstance)) {
220                         // Get a UserDatabaseWrapper instance
221                         $wrapperInstance = ObjectFactory::createObjectByConfiguredName('user_db_wrapper_class');
222
223                         // Create a search criteria
224                         $criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
225
226                         // Add the username as a criteria and set limit to one entry
227                         $criteriaInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUsername());
228                         $criteriaInstance->setLimit(1);
229
230                         // Get a search result
231                         $this->resultInstance = $wrapperInstance->doSelectByCriteria($criteriaInstance);
232                 } else {
233                         // Rewind it
234                         $this->resultInstance->rewind();
235                 }
236
237                 // Search for it
238                 if ($this->resultInstance->next()) {
239                         // Entry found
240                         $exists = true;
241                 } // END - if
242
243                 // Return the status
244                 return $exists;
245         }
246
247         /**
248          * Determines wether the email exists or not
249          *
250          * @return      $exists         Wether the email exists
251          */
252         public function ifEmailAddressExists () {
253                 // By default the email does not exist
254                 $exists = false;
255
256                 // Is a previous result there?
257                 if (is_null($this->resultInstance)) {
258                         // Get a UserDatabaseWrapper instance
259                         $wrapperInstance = ObjectFactory::createObjectByConfiguredName('user_db_wrapper_class');
260
261                         // Create a search criteria
262                         $criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
263
264                         // Add the username as a criteria and set limit to one entry
265                         $criteriaInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_EMAIL, $this->getEmail());
266                         $criteriaInstance->setLimit(1);
267
268                         // Get a search resultInstance
269                         $this->resultInstance = $wrapperInstance->doSelectByCriteria($criteriaInstance);
270                 } else {
271                         // Rewind it
272                         $this->resultInstance->rewind();
273                 }
274
275                 // Search for it
276                 if ($this->resultInstance->next()) {
277                         // Entry found
278                         $exists = true;
279                 } // END - if
280
281                 // Return the status
282                 return $exists;
283         }
284
285         /**
286          * Checks if the supplied password hash in request matches with the stored
287          * in database.
288          *
289          * @param       $requestInstance        A requestable class instance
290          * @return      $matches                        Wether the supplied password hash matches
291          */
292         public function ifPasswordHashMatches (Requestable $requestInstance) {
293                 // By default nothing matches... ;)
294                 $matches = false;
295
296                 // Get a UserDatabaseWrapper instance
297                 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('user_db_wrapper_class');
298
299                 // Create a search criteria
300                 $criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
301
302                 // Add the username as a criteria and set limit to one entry
303                 $criteriaInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
304                 $criteriaInstance->setLimit(1);
305
306                 // Get a search resultInstance
307                 $this->resultInstance = $wrapperInstance->doSelectByCriteria($criteriaInstance);
308
309                 // Search for it
310                 if ($this->resultInstance->next()) {
311                         // Get the current entry (can only be one!)
312                         $entry = $this->resultInstance->current();
313
314                         // So does the hashes match?
315                         //* DEBUG: */ echo $requestInstance->getRequestElement('pass_hash')."/".$entry['pass_hash'];
316                         $matches = ($requestInstance->getRequestElement('pass_hash') === $entry['pass_hash']);
317                 } // END - if
318
319                 // Return the status
320                 return $matches;
321         }
322
323         /**
324          * Adds data for later complete update
325          *
326          * @param       $column         Column we want to update
327          * @param       $value          New value to store in database
328          * @return      void
329          * @todo        0% done
330          */
331         public function addUpdateData ($column, $value) {
332                 $this->partialStub("Column={$column}, value={$value}");
333         }
334
335         /**
336          * "Getter" for user's password hash
337          *
338          * @return      $passHash       User's password hash from database result
339          */
340         public function getPasswordHash () {
341                 // Default is missing password hash
342                 $passHash = null;
343
344                 // Get a database entry
345                 $entry = $this->getDatabaseEntry();
346
347                 // Is the password hash there?
348                 if (isset($entry['pass_hash'])) {
349                         // Get it
350                         $passHash = $entry['pass_hash'];
351                 }
352
353                 // And return the hash
354                 return $passHash;
355         }
356
357         /**
358          * Updates the last activity timestamp and last performed action in the
359          * database result. You should call flushUpdates() to flush these updates
360          * to the database layer.
361          *
362          * @param       $requestInstance        A requestable class instance
363          * @return      void
364          */
365         public function updateLastActivity (Requestable $requestInstance) {
366                 // Set last action
367                 $lastAction = $requestInstance->getRequestElement('action');
368
369                 // If there is no action use the default on
370                 if (is_null($lastAction)) {
371                         $lastAction = $this->getConfigInstance()->readConfig('login_default_action');
372                 } // END - if
373
374                 // Get a critieria instance
375                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
376
377                 // Add search criteria
378                 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
379                 $searchInstance->setLimit(1);
380
381                 // Now get another criteria
382                 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
383
384                 // And add our both entries
385                 $updateInstance->addCriteria('last_activity', date("Y-m-d H:i:s", time()));
386                 $updateInstance->addCriteria('last_action', $lastAction);
387
388                 // Add the search criteria for searching for the right entry
389                 $updateInstance->setSearchInstance($searchInstance);
390
391                 // Remember the update in database result
392                 $this->resultInstance->add2UpdateQueue($updateInstance);
393         }
394
395         /**
396          * Flushs all updated entries to the database layer
397          *
398          * @return      void
399          */
400         public function flushUpdates () {
401                 // Get a database wrapper
402                 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('user_db_wrapper_class');
403
404                 // Do we have data to update?
405                 if ($this->resultInstance->ifDataNeedsFlush()) {
406                         // Yes, then send the whole result to the database layer
407                         $wrapperInstance->doUpdateByResult($this->resultInstance);
408                 } // END - if
409         }
410
411         /**
412          * Getter for field name
413          *
414          * @param       $fieldName              Field name which we shall get
415          * @return      $fieldValue             Field value from the user
416          */
417         public function getField ($fieldName) {
418                 // Default field value
419                 $fieldValue = null;
420
421                 // Get current array
422                 $fieldArray = $this->resultInstance->current();
423
424                 // Does the field exist?
425                 if (isset($fieldArray[$fieldName])) {
426                         // Get it
427                         $fieldValue = $fieldArray[$fieldName];
428                 } // END - if
429
430                 // Return it
431                 return $fieldValue;
432         }
433 }
434
435 // [EOF]
436 ?>