49b285fa7c779b43d71268faae44a93cc2978a40
[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   = 0x060;
42         const EXCEPTION_USER_EMAIL_NOT_FOUND = 0x061;
43         const EXCEPTION_USER_PASS_MISMATCH   = 0x062;
44
45         /**
46          * Protected constructor
47          *
48          * @return      void
49          */
50         protected function __construct ($class = "") {
51                 // Is the class name empty? Then this is not a specialized user class
52                 if (empty($class)) $class = __CLASS__;
53
54                 // Call parent constructor
55                 parent::__construct($class);
56
57                 // Set part description
58                 $this->setObjectDescription("Generic user class");
59
60                 // Create unique ID number
61                 $this->generateUniqueId();
62
63                 // Clean up a little
64                 $this->removeNumberFormaters();
65                 $this->removeSystemArray();
66         }
67
68         /**
69          * Creates an instance of this user class by a provided username. This
70          * factory method will check if the username is already taken and if not
71          * so it will throw an exception.
72          *
73          * @param       $userName               Username we need a class instance for
74          * @return      $userInstance   An instance of this user class
75          * @throws      UsernameMissingException        If the username does not exist
76          */
77         public final static function createUserByUsername ($userName) {
78                 // Get a new instance
79                 $userInstance = new User();
80
81                 // Set the username
82                 $userInstance->setUserName($userName);
83
84                 // Check if the username exists
85                 if (!$userInstance->ifUsernameExists()) {
86                         // Throw an exception here
87                         throw new UsernameMissingException(array($userInstance, $userName), self::EXCEPTION_USERNAME_NOT_FOUND);
88                 }
89
90                 // Return the instance
91                 return $userInstance;
92         }
93
94         /**
95          * Creates an instance of this user class by a provided email address. This
96          * factory method will not check if the email address is there.
97          *
98          * @param       $email                  Email address of the user
99          * @return      $userInstance   An instance of this user class
100          */
101         public final static function createUserByEmail ($email) {
102                 // Get a new instance
103                 $userInstance = new User();
104
105                 // Set the username
106                 $userInstance->setEmail($email);
107
108                 // Return the instance
109                 return $userInstance;
110         }
111
112         /**
113          * "Getter" for databse entry
114          *
115          * @return      $entry  An array with database entries
116          * @throws      NullPointerException    If the database result is not found
117          * @throws      InvalidDatabaseResultException  If the database result is invalid
118          */
119         private function getDatabaseEntry () {
120                 // Is there an instance?
121                 if (is_null($this->resultInstance)) {
122                         // Throw new exception
123                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
124                 } // END - if
125
126                 // Rewind it
127                 $this->resultInstance->rewind();
128
129                 // Do we have an entry?
130                 if (!$this->resultInstance->valid()) {
131                         throw new InvalidDatabaseResultException(array($this, $this->resultInstance), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
132                 } // END - if
133
134                 // Get next entry
135                 $this->resultInstance->next();
136
137                 // Fetch it
138                 $entry = $this->resultInstance->current();
139
140                 // And return it
141                 return $entry;
142         }
143
144         /**
145          * Setter for username
146          *
147          * @param       $userName       The username to set
148          * @return      void
149          */
150         public final function setUserName ($userName) {
151                 $this->userName = $userName;
152         }
153
154         /**
155          * Setter for email
156          *
157          * @param       $email  The email to set
158          * @return      void
159          */
160         protected final function setEmail ($email) {
161                 $this->email = $email;
162         }
163
164         /**
165          * Getter for username
166          *
167          * @return      $userName       The username to get
168          */
169         public final function getUsername () {
170                 return $this->userName;
171         }
172
173         /**
174          * Getter for email
175          *
176          * @return      $email  The email to get
177          */
178         public final function getEmail () {
179                 return $this->email;
180         }
181
182         /**
183          * Determines wether the username exists or not
184          *
185          * @return      $exists         Wether the username exists
186          */
187         public function ifUsernameExists () {
188                 // By default the username does not exist
189                 $exists = false;
190
191                 // Is a previous result there?
192                 if (is_null($this->resultInstance)) {
193                         // Get a UserDatabaseWrapper instance
194                         $wrapperInstance = ObjectFactory::createObjectByConfiguredName('user_db_wrapper_class');
195
196                         // Create a search criteria
197                         $criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
198
199                         // Add the username as a criteria and set limit to one entry
200                         $criteriaInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUsername());
201                         $criteriaInstance->setLimit(1);
202
203                         // Get a search result
204                         $this->resultInstance = $wrapperInstance->doSelectByCriteria($criteriaInstance);
205                 } else {
206                         // Rewind it
207                         $this->resultInstance->rewind();
208                 }
209
210                 // Search for it
211                 if ($this->resultInstance->next()) {
212                         // Entry found
213                         $exists = true;
214                 } // END - if
215
216                 // Return the status
217                 return $exists;
218         }
219
220         /**
221          * Determines wether the email exists or not
222          *
223          * @return      $exists         Wether the email exists
224          */
225         public function ifEmailAddressExists () {
226                 // By default the email does not exist
227                 $exists = false;
228
229                 // Is a previous result there?
230                 if (is_null($this->resultInstance)) {
231                         // Get a UserDatabaseWrapper instance
232                         $wrapperInstance = ObjectFactory::createObjectByConfiguredName('user_db_wrapper_class');
233
234                         // Create a search criteria
235                         $criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
236
237                         // Add the username as a criteria and set limit to one entry
238                         $criteriaInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_EMAIL, $this->getEmail());
239                         $criteriaInstance->setLimit(1);
240
241                         // Get a search resultInstance
242                         $this->resultInstance = $wrapperInstance->doSelectByCriteria($criteriaInstance);
243                 } else {
244                         // Rewind it
245                         $this->resultInstance->rewind();
246                 }
247
248                 // Search for it
249                 if ($this->resultInstance->next()) {
250                         // Entry found
251                         $exists = true;
252                 } // END - if
253
254                 // Return the status
255                 return $exists;
256         }
257
258         /**
259          * Checks if the supplied password hash in request matches with the stored
260          * in database.
261          *
262          * @param       $requestInstance        A requestable class instance
263          * @return      $matches                        Wether the supplied password hash matches
264          */
265         public function ifPasswordHashMatches (Requestable $requestInstance) {
266                 // By default nothing matches... ;)
267                 $matches = false;
268
269                 // Get a UserDatabaseWrapper instance
270                 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('user_db_wrapper_class');
271
272                 // Create a search criteria
273                 $criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
274
275                 // Add the username as a criteria and set limit to one entry
276                 $criteriaInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
277                 $criteriaInstance->setLimit(1);
278
279                 // Get a search resultInstance
280                 $this->resultInstance = $wrapperInstance->doSelectByCriteria($criteriaInstance);
281
282                 // Search for it
283                 if ($this->resultInstance->next()) {
284                         // Get the current entry (can only be one!)
285                         $entry = $this->resultInstance->current();
286
287                         // So does the hashes match?
288                         //* DEBUG: */ echo $requestInstance->getRequestElement('pass_hash')."/".$entry['pass_hash'];
289                         $matches = ($requestInstance->getRequestElement('pass_hash') === $entry['pass_hash']);
290                 } // END - if
291
292                 // Return the status
293                 return $matches;
294         }
295
296         /**
297          * Adds data for later complete update
298          *
299          * @param       $column         Column we want to update
300          * @param       $value          New value to store in database
301          * @return      void
302          */
303         public function addUpdateData ($column, $value) {
304                 $this->partialStub("Column={$column}, value={$value}");
305         }
306
307         /**
308          * "Getter" for user's password hash
309          *
310          * @return      $passHash       User's password hash from database result
311          */
312         public function getPasswordHash () {
313                 // Default is missing password hash
314                 $passHash = null;
315
316                 // Get a database entry
317                 $entry = $this->getDatabaseEntry();
318
319                 // Is the password hash there?
320                 if (isset($entry['pass_hash'])) {
321                         // Get it
322                         $passHash = $entry['pass_hash'];
323                 }
324
325                 // And return the hash
326                 return $passHash;
327         }
328
329         /**
330          * Updates the last activity timestamp and last performed action in the
331          * database result. You should call flushUpdates() to flush these updates
332          * to the database layer.
333          *
334          * @param       $requestInstance        A requestable class instance
335          * @return      void
336          */
337         public function updateLastActivity (Requestable $requestInstance) {
338                 // Set last action
339                 $lastAction = $requestInstance->getRequestElement('action');
340
341                 // If there is no action use the default on
342                 if (is_null($lastAction)) {
343                         $lastAction = $this->getConfigInstance()->readConfig('login_default_action');
344                 } // END - if
345
346                 // Get a critieria instance
347                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
348
349                 // Add search criteria
350                 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
351                 $searchInstance->setLimit(1);
352
353                 // Now get another criteria
354                 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
355
356                 // And add our both entries
357                 $updateInstance->addCriteria('last_activity', date("Y-m-d H:i:s", time()));
358                 $updateInstance->addCriteria('last_action', $lastAction);
359
360                 // Add the search criteria for searching for the right entry
361                 $updateInstance->setSearchInstance($searchInstance);
362
363                 // Remember the update in database result
364                 $this->resultInstance->add2UpdateQueue($updateInstance);
365         }
366
367         /**
368          * Flushs all updated entries to the database layer
369          *
370          * @return      void
371          */
372         public function flushUpdates () {
373                 // Get a database wrapper
374                 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('user_db_wrapper_class');
375
376                 // Do we have data to update?
377                 if ($this->resultInstance->ifDataNeedsFlush()) {
378                         // Yes, then send the whole result to the database layer
379                         $wrapperInstance->doUpdateByResult($this->resultInstance);
380                 } // END - if
381         }
382 }
383
384 // [EOF]
385 ?>