Continued:
[core.git] / framework / main / classes / user / class_BaseUser.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\User;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseFrontend;
8 use Org\Mxchange\CoreFramework\Database\Updateable;
9 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
10 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
11 use Org\Mxchange\CoreFramework\Request\Requestable;
12 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
13 use Org\Mxchange\CoreFramework\Traits\Result\Search\SearchableResultTrait;
14
15 /**
16  * A general user class
17  *
18  * @author              Roland Haeder <webmaster@shipsimu.org>
19  * @version             0.0.0
20  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
21  * @license             GNU GPL 3.0 or any newer version
22  * @link                http://www.shipsimu.org
23  *
24  * This program is free software: you can redistribute it and/or modify
25  * it under the terms of the GNU General Public License as published by
26  * the Free Software Foundation, either version 3 of the License, or
27  * (at your option) any later version.
28  *
29  * This program is distributed in the hope that it will be useful,
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
32  * GNU General Public License for more details.
33  *
34  * You should have received a copy of the GNU General Public License
35  * along with this program. If not, see <http://www.gnu.org/licenses/>.
36  */
37 abstract class BaseUser extends BaseFrameworkSystem implements Updateable {
38         // Load traits
39         use SearchableResultTrait;
40
41         // Exception constances
42         const EXCEPTION_USERNAME_NOT_FOUND   = 0x150;
43         const EXCEPTION_USER_EMAIL_NOT_FOUND = 0x151;
44         const EXCEPTION_USER_PASS_MISMATCH   = 0x152;
45         const EXCEPTION_USER_IS_GUEST        = 0x153;
46
47         /**
48          * Username of current user
49          */
50         private $userName = '';
51
52         /**
53          * User id of current user
54          */
55         private $userId = 0;
56
57         /**
58          * Email of current user
59          */
60         private $email = '';
61
62         /**
63          * Protected constructor
64          *
65          * @param       $className      Name of the class
66          * @return      void
67          */
68         protected function __construct (string $className) {
69                 // Call parent constructor
70                 parent::__construct($className);
71         }
72
73         /**
74          * Setter for username
75          *
76          * @param       $userName       The username to set
77          * @return      void
78          */
79         public final function setUserName (string $userName) {
80                 $this->userName = $userName;
81         }
82
83         /**
84          * Getter for username
85          *
86          * @return      $userName       The username to get
87          */
88         public final function getUserName () {
89                 return $this->userName;
90         }
91
92         /**
93          * Setter for user id
94          *
95          * @param       $userId         The user id to set
96          * @return      void
97          * @todo        Find a way of casting here. "(int)" might destroy the user id > 32766
98          */
99         public final function setUserId (int $userId) {
100                 $this->userId = $userId;
101         }
102
103         /**
104          * Getter for user id
105          *
106          * @return      $userId The user id to get
107          */
108         public final function getUserId () {
109                 return $this->userId;
110         }
111
112         /**
113          * Setter for email
114          *
115          * @param       $email  The email to set
116          * @return      void
117          */
118         protected final function setEmail (string $email) {
119                 $this->email = $email;
120         }
121
122         /**
123          * Getter for email
124          *
125          * @return      $email  The email to get
126          */
127         public final function getEmail () {
128                 return $this->email;
129         }
130
131         /**
132          * Determines whether the username exists or not
133          *
134          * @return      $exists         Whether the username exists
135          */
136         public function ifUsernameExists () {
137                 // By default the username does not exist
138                 $exists = false;
139
140                 // Is a previous result there?
141                 if (!$this->getResultInstance() instanceof SearchableResult) {
142                         // Get a UserDatabaseFrontend instance
143                         $frontendInstance = ObjectFactory::createObjectByConfiguredName('user_db_frontend_class');
144
145                         // Create a search criteria
146                         $criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
147
148                         // Add the username as a criteria and set limit to one entry
149                         $criteriaInstance->addCriteria(UserDatabaseFrontend::DB_COLUMN_USERNAME, $this->getUserName());
150                         $criteriaInstance->setLimit(1);
151
152                         // Get a search result
153                         $resultInstance = $frontendInstance->doSelectByCriteria($criteriaInstance);
154
155                         // Set the index "solver"
156                         $resultInstance->solveResultIndex(UserDatabaseFrontend::DB_COLUMN_USERID, $frontendInstance, array($this, 'setUserId'));
157
158                         // And finally set it
159                         $this->setResultInstance($resultInstance);
160                 }
161
162                 // Rewind it
163                 $this->getResultInstance()->rewind();
164
165                 // Search for it
166                 if ($this->getResultInstance()->valid()) {
167                         // Entry found
168                         $exists = true;
169                 }
170
171                 // Return the status
172                 return $exists;
173         }
174
175         /**
176          * Determines whether the email exists or not
177          *
178          * @return      $exists         Whether the email exists
179          */
180         public function ifEmailAddressExists () {
181                 // By default the email does not exist
182                 $exists = false;
183
184                 // Is a previous result there?
185                 if (!$this->getResultInstance() instanceof SearchableResult) {
186                         // Get a UserDatabaseFrontend instance
187                         $frontendInstance = ObjectFactory::createObjectByConfiguredName('user_db_frontend_class');
188
189                         // Create a search criteria
190                         $criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
191
192                         // Add the username as a criteria and set limit to one entry
193                         $criteriaInstance->addCriteria(UserDatabaseFrontend::DB_COLUMN_EMAIL, $this->getEmail());
194                         $criteriaInstance->setLimit(1);
195
196                         // Get a search result
197                         $resultInstance = $frontendInstance->doSelectByCriteria($criteriaInstance);
198
199                         // Set the index "solver"
200                         $resultInstance->solveResultIndex(UserDatabaseFrontend::DB_COLUMN_USERID, $frontendInstance, array($this, 'setUserId'));
201
202                         // And finally set it
203                         $this->setResultInstance($resultInstance);
204                 }
205
206                 // Rewind it
207                 $this->getResultInstance()->rewind();
208
209                 // Search for it
210                 if ($this->getResultInstance()->valid()) {
211                         // Entry found
212                         $exists = true;
213
214                         // Is the username set?
215                         if ($this->getUserName() == '') {
216                                 // Get current entry
217                                 $currEntry = $this->getResultInstance()->current();
218
219                                 // Set the username
220                                 $this->setUserName($currEntry['username']);
221                         }
222                 }
223
224                 // Return the status
225                 return $exists;
226         }
227
228         /**
229          * Checks if supplied password hash in request matches with the stored in
230          * database.
231          *
232          * @param       $requestInstance        A Requestable class instance
233          * @return      $matches                        Whether the supplied password hash matches
234          */
235         public function ifPasswordHashMatches (Requestable $requestInstance) {
236                 // By default nothing matches... ;)
237                 $matches = false;
238
239                 // Is a previous result there?
240                 if ((!$this->getResultInstance() instanceof SearchableResult) || ($this->getResultInstance()->count() == 0)) {
241                         // Get a UserDatabaseFrontend instance
242                         $frontendInstance = ObjectFactory::createObjectByConfiguredName('user_db_frontend_class');
243
244                         // Create a search criteria
245                         $criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
246
247                         // Add the username as a criteria and set limit to one entry
248                         $criteriaInstance->addCriteria(UserDatabaseFrontend::DB_COLUMN_USERNAME, $this->getUserName());
249                         $criteriaInstance->setLimit(1);
250
251                         // Get a search result
252                         $resultInstance = $frontendInstance->doSelectByCriteria($criteriaInstance);
253
254                         // Set the index "solver"
255                         $resultInstance->solveResultIndex(UserDatabaseFrontend::DB_COLUMN_USERID, $frontendInstance, array($this, 'setUserId'));
256
257                         // And finally set it
258                         $this->setResultInstance($resultInstance);
259                 }
260
261                 // Rewind it and advance to first entry
262                 $this->getResultInstance()->rewind();
263
264                 // This call set the result instance to a clean state
265                 $this->getResultInstance()->next();
266
267                 // Search for it
268                 if ($this->getResultInstance()->find('pass_hash')) {
269                         // So does the hashes match?
270                         //* DEBUG: */ echo $requestInstance->getRequestElement('pass_hash') . '<br />' . $this->getResultInstance()->getFoundValue() . '<br />';
271                         $matches = ($requestInstance->getRequestElement('pass_hash') === $this->getResultInstance()->getFoundValue());
272                 }
273
274                 // Return the status
275                 return $matches;
276         }
277
278         /**
279          * "Getter" for user's password hash
280          *
281          * @return      $passHash       User's password hash from database result
282          */
283         public final function getPasswordHash () {
284                 // Default is missing password hash
285                 $passHash = NULL;
286
287                 // Get a database entry
288                 $entry = $this->getDatabaseEntry();
289
290                 // Is the password hash there?
291                 if (isset($entry['pass_hash'])) {
292                         // Get it
293                         $passHash = $entry['pass_hash'];
294                 }
295
296                 // And return the hash
297                 return $passHash;
298         }
299
300         /**
301          * Getter for primary key value
302          *
303          * @return      $primaryValue   Value of the primary key based on database type
304          */
305         public final function getPrimaryKey () {
306                 // Get a user database frontend
307                 $frontendInstance = ObjectFactory::createObjectByConfiguredName('user_db_frontend_class');
308
309                 // Get the primary key back from the frontend
310                 $primaryKey = $frontendInstance->generatePrimaryKey();
311
312                 // Get that field
313                 $primaryValue = $this->getField($primaryKey);
314
315                 // Return the value
316                 return $primaryValue;
317         }
318
319         /**
320          * Updates a given field with new value
321          *
322          * @param       $fieldName              Field to update
323          * @param       $fieldValue             New value to store
324          * @return      void
325          * @todo        Try to make this method more generic so we can move it in BaseFrameworkSystem
326          */
327         public function updateDatabaseField (string $fieldName, $fieldValue) {
328                 // Get a critieria instance
329                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
330
331                 // Add search criteria
332                 $searchInstance->addCriteria(UserDatabaseFrontend::DB_COLUMN_USERNAME, $this->getUserName());
333                 $searchInstance->setLimit(1);
334
335                 // Now get another criteria
336                 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
337
338                 // Add criteria entry which we shall update
339                 $updateInstance->addCriteria($fieldName, $fieldValue);
340
341                 // Add the search criteria for searching for the right entry
342                 $updateInstance->setSearchInstance($searchInstance);
343
344                 // Set frontend class name
345                 $updateInstance->setFrontendConfigEntry('user_db_frontend_class');
346
347                 // Remember the update in database result
348                 $this->getResultInstance()->add2UpdateQueue($updateInstance);
349         }
350
351         /**
352          * Checks whether the user status is 'confirmed'
353          *
354          * @return      $isConfirmed    Whether the user status is 'confirmed'
355          */
356         public function isConfirmed () {
357                 // Determine it
358                 $isConfirmed = ($this->getField(UserDatabaseFrontend::DB_COLUMN_USER_STATUS) == FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('user_status_confirmed'));
359
360                 // Return it
361                 return $isConfirmed;
362         }
363
364         /**
365          * Checks whether the user status is 'guest'
366          *
367          * @return      $isGuest        Whether the user status is 'guest'
368          */
369         public function isGuest () {
370                 // Determine it
371                 $isGuest = ($this->getField(UserDatabaseFrontend::DB_COLUMN_USER_STATUS) == FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('user_status_guest'));
372
373                 // Return it
374                 return $isGuest;
375         }
376
377 }