Subversion Repositories php_users

Rev

Rev 10 | Rev 17 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
4 rodolico 1
<?php
2
 
3
/*
7 rodolico 4
   Copyright (c) 2021, Daily Data, Inc. Redistribution and use in 
5
   source and binary forms, with or without modification, are permitted
6
   provided that the following conditions are met:
7
 
8
   * Redistributions of source code must retain the above copyright 
9
     notice, this list of conditions and the following disclaimer.
10
   * Redistributions in binary form must reproduce the above copyright 
11
     notice, this list of conditions and the following disclaimer in the 
12
     documentation and/or other materials provided with the distribution.
13
 
14
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
15
   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
16
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
17
   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
18
   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19
   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
20
   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21
   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22
   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24
   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25
 
26
*/
27
 
28
/*
29
 * UsersDataSourceMySQLi.class.php
30
 * 
31
 * Authors: R. W. Rodolico
32
 * 
4 rodolico 33
 */
34
 
7 rodolico 35
/**
36
 * usersDataSource class
37
 * 
38
 * usersDataSource provides the data access capabilities for the Users
39
 * class.
40
 * 
41
 * To build a data access class for Users, the following 5 methods must
42
 * exist.
43
 * getPassword(username)
44
 * getRecord(username)
45
 * getAllUsers()
46
 * getARecord
47
 * update
48
 * 
49
 * Additionally, where appropriate, the following function is useful
50
 * buildTable()
51
 * 
52
 * This particular instance provides an interface to MySQL using
53
 * the mysqli libraries.
54
 * 
55
 * Create an instance of this, then pass the variable to several Users
56
 * calls.
57
 * 
58
 * @author R. W. Rodolico <rodo@unixservertech.com>
59
 * 
60
 * @version 0.9.0 (beta)
61
 * @copyright 2021 Daily Data, Inc.
62
 * 
63
 */
64
 
4 rodolico 65
class usersDataSource {
66
 
7 rodolico 67
   /**
16 rodolico 68
    * @var string[] $configuration Contains the configuration for the class
7 rodolico 69
    * 
70
    * May be modified by the calling program. Must be replicated in userDataSource class
71
    */
16 rodolico 72
   protected $configuration = array(
4 rodolico 73
      'tables' => array(
74
         'users'  => array(
75
            'table'     => '_users',   // table name for user records
76
            'id'        => '_user_id', // ID column name
77
            'display'   => array(      // fields which are displayed to select
78
               'login'
79
               ),
80
            'password'  => array(      // These fields are stored encrypted
81
               'pass'
82
               ),
83
            'fields' => array(
84
               'login'  => array(
85
                     'dbColumn'  =>  'login',       // login name column name
86
                     'type'      => 'varchar',
87
                     'size'      => 64,
10 rodolico 88
                     'required'  => true
4 rodolico 89
                     ),
90
               'pass'   => array( 
91
                     'dbColumn'  => 'password',    // password column name
92
                     'type'   => 'varchar',
93
                     'size'      => 128,
10 rodolico 94
                     'required'  => true
4 rodolico 95
                     ),
96
               'admin'  => array(
97
                     'dbColumn'  => 'isAdmin',
98
                     'type'      => 'boolean',
99
                     'required'  => true,
100
                     'default'   => '0'
101
                     ),
102
               'enabled'   => array(
103
                     'dbColumn'  => 'enabled',
104
                     'type'      => 'boolean',
105
                     'required'  => true,
106
                     'default'   => '1'
107
                     )
108
               )
109
            )
110
         )
111
      );
7 rodolico 112
      /** @var mysqli $dbConnection Holds the mysqli database connection */
16 rodolico 113
      protected $dbConnection = false;
4 rodolico 114
 
7 rodolico 115
      /**
116
       * constructor for an instance of the class
117
       * 
118
       * If $dbConnection is not null, will be used for database access
119
       * If $dbLoginInfo is not null, will override $dbConnection, make
120
       * a new connection and use that.
121
       * 
16 rodolico 122
       * If $dbDef is set, will be merged with $configuration
7 rodolico 123
       * 
124
       * @param mysqli $dbConnection Existing mysqli database connection
16 rodolico 125
       * @param string[] $dbDef Array to be merged with $configuration
7 rodolico 126
       * @param string[] $dbLoginInfo Array containing username, hostname, etc.. to make mysqli connection_aborted
127
       * 
128
       * @return null
129
       * 
130
       */
4 rodolico 131
      public function __construct( $dbConnection = null, $dbDef = array(), $dbLoginInfo = array() ) {
132
         $this->dbConnection = $dbConnection;
133
         if ( $dbDef ) {
16 rodolico 134
            $this->configuration = array_merge_recursive( $this->configuration, $dbDef );
4 rodolico 135
         }
136
         if ( $dbLoginInfo ) {
137
            $this->setDBConnection( $dbLoginInfo );
138
         }
139
      }
140
 
7 rodolico 141
      /**
142
       * Make string safe for MySQL
143
       * 
144
       * If the string is completely numeric, returns it, otherwise 
145
       * puts single quotes around it
146
       * 
147
       * @param string $string The string to be fixed
148
       * @return string A copy of the string, ready for SQL
149
       */
16 rodolico 150
      protected function escapeString ( $string ) {
4 rodolico 151
         $string = $this->dbConnection->real_escape_string( $string );
152
         if ( ! is_numeric( $string ) )
153
            $string = "'$string'";
154
         return $string;
155
      }
156
 
157
      /**
7 rodolico 158
       * Create a query to retrieve info from database
4 rodolico 159
       * 
160
       * Builds a query to retrieve records from the database. With all
161
       * parameters set to null, will retrieve all columns and records
162
       * Setting $field and $toFind create a where clause, and setting
163
       * $fieldList as a has (ie, 'fieldname' => 1) will limit the 
164
       * fields returned
165
       * 
16 rodolico 166
       * @param string $field A valid field definition from $configuration
4 rodolico 167
       * @param string $toFind The string to find, ie where $field = $username
168
       * @param string[] $fieldList a hash where the keys make a list of columns to return. If empty, returns all columns
169
       * 
170
       * @return string A cleaned and formatted SQL Query
171
       * 
172
      */
16 rodolico 173
      protected function buildQuery( $whereFields, $fieldList = null ) {
4 rodolico 174
         // always get the ID field
16 rodolico 175
         $fields = array( $this->configuration['tables']['users']['id'] . ' id');
4 rodolico 176
         // Get the rest of the available fields
16 rodolico 177
         foreach ( $this->configuration['tables']['users']['fields'] as $key => $value ) {
4 rodolico 178
            // do not use this one if $fieldList doesn't have it
179
            if ( ! isset( $fieldList ) || isset( $fieldList[$key] ) )
180
               $fields[] = $value['dbColumn'] . ' ' . $key;
181
         }
182
         // Change it into something SQL can handle
183
         $query = implode( ',', $fields );
184
         // now, build the rest of the query
16 rodolico 185
         $query = "select $query from " . $this->configuration['tables']['users']['table'];
4 rodolico 186
         if ( isset( $whereFields ) ) {
187
            $temp = array();
188
            foreach ( $whereFields as $key => $value ) {
189
               $temp[] = ( 
190
                  $key == 'id' ? 
16 rodolico 191
                  $this->configuration['tables']['users']['id'] : 
192
                  $this->configuration['tables']['users']['fields'][$key]['dbColumn']
4 rodolico 193
                  ) . '= ' . $this->escapeString( $value );
194
            }
195
            $query .= ' where ' . implode( ' and ', $temp );
196
         }
197
         //print "<p>$query</p>";
198
         return $query;
199
      }
200
 
201
      /**
202
       * Get a record from the database
203
       * 
204
       * Gets a single record from the database which matches $field containing
205
       * $username. If more than one record is returned, will return the first
206
       * one
207
       * 
208
       * @param string[] $whereFields column=>value pairs for where clause
209
       * @param string[] $fieldList a list of columns to return. If empty, returns all columns
210
       * 
7 rodolico 211
       * @return string[] a hash containing fieldname=>value pairs from fetch_assoc
4 rodolico 212
       * 
213
      */
214
      public function getARecord( $whereFields, $fieldList = null ) {
215
         // run the query, placing value in $result
216
         mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
16 rodolico 217
         $result = $this->doSQL( $this->buildQuery( $whereFields, $fieldList ) );
4 rodolico 218
         if ( $result ) { // got one, so return it
219
            return $result->fetch_assoc();
220
         }
221
         // WTFO? nothing, so return empty array
222
         return array();
223
      }
224
 
7 rodolico 225
      /**
226
       * Retrieves the password field from table
227
       * 
228
       * Note that the password is stored as a hash in the table
229
       * 
230
       * @param string $username username used to find record
231
       * @return string[] an array of values key/value pairs
232
       */
4 rodolico 233
      public function getPassword( $username ) {
234
         return $this->getARecord( array('login' => $username,'enabled' => 1), array('pass' => 1 ) );
235
      }
236
 
7 rodolico 237
      /**
238
       * Gets the entire record for a user
239
       * 
240
       * NOTE: this does not actually get all columns. getARecord only gets
16 rodolico 241
       * the columns defined in $configuration
7 rodolico 242
       * 
243
       * @param string $username the value of the login field to find
244
       * 
245
       * @return string[] fieldname=>value array of found record
246
       */
4 rodolico 247
      public function getRecord ( $username ) {
248
         return $this->getARecord( array( 'login' => $username ) );
249
      }
250
 
7 rodolico 251
      /**
252
       * Make the database connection
253
       * 
254
       * @param string[] $parameters Parameters for makeing the connection
255
       * @return mysqli|false
256
       */
16 rodolico 257
      protected function setDBConnection ( $parameters ) {
4 rodolico 258
         if ( !isset($parameters['username'], $parameters['password'],$parameters['database']  )) {
259
            return false;
260
         }
261
         if ( !isset( $parameters['host'] ) ) {
262
            $parameters['host'] = 'localhost';
263
         }
264
         mysqli_report( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
265
         $this->dbConnection = new mysqli( $parameters['host'], $parameters['username'], $parameters['password'],$parameters['database'] );
266
      }
267
 
268
      /**
16 rodolico 269
       * Convenience function to create the tables defined in $configuration
4 rodolico 270
       * 
16 rodolico 271
       * Using $configuration, build the table (replacing the current one)
4 rodolico 272
       * then add $username with $password, setting as admin
273
       * 
274
      */
16 rodolico 275
      public function buildTable( ) {
4 rodolico 276
         if ( $this->dbConnection ) {
16 rodolico 277
            foreach ( $this->configuration['tables'] as $table => $tableRecord ) {
278
               //print "<pre>Building " . $table . "\n</pre>";
279
               $fields = array( $tableRecord['id'] . ' int unsigned not null auto_increment' );
280
               foreach ( $tableRecord['fields'] as $key => $record ) {
281
                  //print "<pre>\tColumn " . $key . ' using ' . print_r( $record, true)  . "\n</pre>";
282
                  $fieldDef = $record['dbColumn'];
283
                  $fieldDef .= ' ' . $record['type'];
284
                  if ( isset( $record['size'] ) ) {
285
                     $fieldDef .= '(' . $record['size'] . ')';
286
                  }
287
                  if ( isset( $record['required'] ) ) {
288
                     $fieldDef .= $record['required'] ? ' not null ' : '';
289
                  }
290
                  if ( isset( $record['default'] ) ) {
291
                     $fieldDef .= sprintf( " default '%s'", $record['default'] );
292
                  }
293
                  if ( isset( $record['comment'] ) ) {
294
                     $fieldDef .= "comment '" . $record['comment'] . "'";
295
                  }
296
                  $fields[] = $fieldDef;
4 rodolico 297
               }
16 rodolico 298
               $fields[] = 'primary key (' . $tableRecord['id'] . ')';
299
               $query = implode( ',', $fields );
300
               $query = 'create or replace table ' . $tableRecord['table'] .
301
                     "($query)";
302
               //print '<pre>' . $query . "\n</pre>";
303
               $this->doSQL( $query );
4 rodolico 304
            }
16 rodolico 305
         } // foreach table
306
      } // buildTable
307
 
308
      /**
309
       * Convenience function to initialize tables to values
310
       * 
311
       * @param string[] $initValues Array of tablenames, column names and values
312
       * 
313
      */
314
      public function initTables ( $initValues ) {
315
         foreach ( $initValues as $table => $fieldDef ) {
316
            $columns = array();
317
            $values = array();
318
            foreach ( $fieldDef as $columnName => $columnValue ) {
319
               $columns[] = $this->tableColumnName( $table, $columnName );
320
               $values[] = $this->escapeString( $columnValue );
321
            }
322
            $query = sprintf( "insert into %s (%s) values (%s)", 
323
                  $this->configuration['tables'][$table]['table'],
324
                  implode( ",", $columns ), 
325
                  implode( ',', $values ) 
326
                  );
327
            //print '<pre>' . $query . "\n</pre>";
328
            $this->doSQL( $query );
4 rodolico 329
         }
16 rodolico 330
      }
4 rodolico 331
 
16 rodolico 332
      protected function tableColumnName ( $table, $field ) {
333
         return $this->configuration['tables'][$table]['fields'][$field]['dbColumn'];
334
      }
335
 
4 rodolico 336
      /**
337
       * Tests that the database connection works and the table is built
7 rodolico 338
       *
339
       * @return boolean True if table exists (does not verify columns)
4 rodolico 340
       */
341
      public function test() {
16 rodolico 342
         $result = $this->doSQL( sprintf( "show tables like '%s'", $this->configuration['tables']['users']['table'] ) );
4 rodolico 343
         return $result !== false && $result->num_rows;
344
      } // test
345
 
7 rodolico 346
      /**
347
       * updates row in database with $newData
348
       * 
349
       * @param string[] $newData fieldname/value pairs to be updated in table
350
       * 
351
       * @return mysqli_result|bool The mysqli result from a query
352
       */
4 rodolico 353
      public function update ( $newData ) {
354
         $query = '';
355
         foreach ( $newData as $key => $value ) {
356
            $newData[$key] = $this->escapeString( $value );
357
         }
358
         if ( $newData ) { // make sure they sent us something
359
            if ( $newData['id'] > 0 ) { // we are doing an update
360
               $fields = array();
16 rodolico 361
               foreach ( $this->configuration['tables']['users']['fields'] as $key => $record ) {
4 rodolico 362
                  if ( isset( $newData[$key] ) ) {
363
                     $fields[] = $record['dbColumn'] . " = $newData[$key]";
364
                  } // if
365
               }
16 rodolico 366
               $query = 'update ' . $this->configuration['tables']['users']['table'] . ' set ' .
4 rodolico 367
                  implode( ',', $fields ) .
16 rodolico 368
                  ' where ' . $this->configuration['tables']['users']['id'] . ' = ' . 
4 rodolico 369
                  $this->dbConnection->real_escape_string( $newData['id'] );
370
            } else { // we are doing an insert
371
               $columns = array();
372
               $values = array();
16 rodolico 373
               foreach ( $this->configuration['tables']['users']['fields'] as $key => $record ) {
4 rodolico 374
                  if ( isset( $newData[$key] ) ) {
375
                     $columns[] = $record['dbColumn'];
376
                     $values[] = $newData[$key];
377
                  } // if
378
               }
16 rodolico 379
               $query = 'insert into ' . $this->configuration['tables']['users']['table'] . 
4 rodolico 380
                  '(' . implode( ',', $columns ) . ') values (' .
381
                  implode( ',', $values ) . ')';
382
            }
383
            //print "<p>$query</p>";
16 rodolico 384
            return $this->doSQL( $query );
4 rodolico 385
         }
386
      } // update
387
 
7 rodolico 388
      /**
389
       * retrieves all users from the database
390
       * 
391
       * Retrieves all data for all users from table
392
       * 
393
       * @return string[] array of array of rows/columns
394
       */
4 rodolico 395
      public function getAllUsers() {
396
         $query = $this->buildQuery( null, null, array('login' => 1) );
397
         //print "<p>$query</p>\n";
398
         mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
16 rodolico 399
         $result = $this->doSQL( $query );
4 rodolico 400
         if ( $result ) {
401
            return $result->fetch_all(MYSQLI_ASSOC);
402
         }
403
         return array();
404
      }
16 rodolico 405
 
406
      /**
407
       * Executes an SQL statement, returning the result
408
       * 
409
       * This simply runs mysqli::query, and returns the value of that
410
       * 
411
       * Created for testing and debugging, if the second parameter is 
412
       * true, will NOT execute the query, but will instead display the 
413
       * query passed.
414
       * 
415
       * @parameter string $query SQL Query to execute
416
       * @parameter boolean $testing If set to true, displays query instead of executing it
417
       * 
418
       * @returns mysqli_result
419
       */
420
      protected function doSQL( $query, $testing = false ) {
421
         if ( $testing ) {
422
            print "<pre>$query</pre>"; return;
423
         } else {
424
            mysqli_report( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
425
            $result = $this->dbConnection->query( $query );
426
            return $result;
427
         }
428
      }
429
 
430
      /**
431
       * Gets a single field from a table
432
       * 
433
       * Builds a query similar to
434
       * select $returnColumn from $tableName where $fieldName = $value
435
       * executes it, and returns the first column of the first
436
       * row returned, or null if it does not exist.
437
       * 
438
       * @parameter string $tableName Name of database table
439
       * @parameter string $returnColumn Column to return
440
       * @parameter string $fieldName Name of column to search for value
441
       * @parameter string $value The value to match
442
       * 
443
       * @returns string $returnColumn of first row, or null if none
444
       */
445
      protected function getAField( $tableName, $returnColumn, $fieldName, $value ) {
446
         $value = $this->escapeString( $value );
447
         $result = $this->doSQL( "select $returnColumn from $tableName where $fieldName = $value" );
448
         $field = $result->fetch_array(MYSQLI_NUM);
449
         return $field ? $field[0] : null;
450
      }
4 rodolico 451
 
452
}
453
 
454
?>