Subversion Repositories php_users

Rev

Rev 21 | Rev 42 | 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
 * getAllUsers()
45
 * getARecord
46
 * update
47
 * 
48
 * Additionally, where appropriate, the following function is useful
49
 * buildTable()
50
 * 
51
 * This particular instance provides an interface to MySQL using
52
 * the mysqli libraries.
53
 * 
54
 * Create an instance of this, then pass the variable to several Users
55
 * calls.
56
 * 
57
 * @author R. W. Rodolico <rodo@unixservertech.com>
58
 * 
59
 * @version 0.9.0 (beta)
60
 * @copyright 2021 Daily Data, Inc.
61
 * 
62
 */
21 rodolico 63
require_once( 'UsersDataSource.class.php' );
7 rodolico 64
 
21 rodolico 65
class usersDataSourceMySQLi extends usersDataSource {
4 rodolico 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,
21 rodolico 88
                     'required'  => true,
89
                     'unique'    => true
4 rodolico 90
                     ),
91
               'pass'   => array( 
92
                     'dbColumn'  => 'password',    // password column name
93
                     'type'   => 'varchar',
94
                     'size'      => 128,
10 rodolico 95
                     'required'  => true
4 rodolico 96
                     ),
97
               'admin'  => array(
98
                     'dbColumn'  => 'isAdmin',
99
                     'type'      => 'boolean',
100
                     'required'  => true,
101
                     'default'   => '0'
102
                     ),
103
               'enabled'   => array(
104
                     'dbColumn'  => 'enabled',
105
                     'type'      => 'boolean',
106
                     'required'  => true,
107
                     'default'   => '1'
108
                     )
109
               )
110
            )
111
         )
112
      );
7 rodolico 113
      /** @var mysqli $dbConnection Holds the mysqli database connection */
16 rodolico 114
      protected $dbConnection = false;
4 rodolico 115
 
7 rodolico 116
      /**
117
       * constructor for an instance of the class
118
       * 
119
       * If $dbConnection is not null, will be used for database access
120
       * If $dbLoginInfo is not null, will override $dbConnection, make
121
       * a new connection and use that.
122
       * 
16 rodolico 123
       * If $dbDef is set, will be merged with $configuration
7 rodolico 124
       * 
21 rodolico 125
       * @param mysqli $dbConnection Existing mysqli database connection or array with login information
16 rodolico 126
       * @param string[] $dbDef Array to be merged with $configuration
7 rodolico 127
       * 
128
       * @return null
129
       * 
130
       */
21 rodolico 131
      public function __construct( $connection, $customFields = array() ) {
132
         parent::__construct( $customFields );
133
         if ( is_array( $connection ) ) { // they sent us some login values
134
            $this->setDBConnection( $connection );
32 rodolico 135
         } elseif ( $connection instanceof mysqli ) { // mysqli, or some extension
21 rodolico 136
            $this->dbConnection = $connection;
137
         } else {
138
            throw new Exception( 'Can not open database using; must give open mysqli class or array of login information' );
4 rodolico 139
         }
140
      }
141
 
7 rodolico 142
      /**
143
       * Make string safe for MySQL
144
       * 
145
       * If the string is completely numeric, returns it, otherwise 
146
       * puts single quotes around it
147
       * 
148
       * @param string $string The string to be fixed
149
       * @return string A copy of the string, ready for SQL
150
       */
16 rodolico 151
      protected function escapeString ( $string ) {
17 rodolico 152
         if ( ! is_numeric( $string ) ) {
153
            $string = $this->dbConnection->real_escape_string( $string );
4 rodolico 154
            $string = "'$string'";
17 rodolico 155
         }
4 rodolico 156
         return $string;
157
      }
158
 
159
      /**
7 rodolico 160
       * Create a query to retrieve info from database
4 rodolico 161
       * 
162
       * Builds a query to retrieve records from the database. With all
163
       * parameters set to null, will retrieve all columns and records
164
       * Setting $field and $toFind create a where clause, and setting
165
       * $fieldList as a has (ie, 'fieldname' => 1) will limit the 
166
       * fields returned
167
       * 
16 rodolico 168
       * @param string $field A valid field definition from $configuration
4 rodolico 169
       * @param string $toFind The string to find, ie where $field = $username
170
       * @param string[] $fieldList a hash where the keys make a list of columns to return. If empty, returns all columns
171
       * 
172
       * @return string A cleaned and formatted SQL Query
173
       * 
174
      */
16 rodolico 175
      protected function buildQuery( $whereFields, $fieldList = null ) {
4 rodolico 176
         // always get the ID field
16 rodolico 177
         $fields = array( $this->configuration['tables']['users']['id'] . ' id');
4 rodolico 178
         // Get the rest of the available fields
16 rodolico 179
         foreach ( $this->configuration['tables']['users']['fields'] as $key => $value ) {
4 rodolico 180
            // do not use this one if $fieldList doesn't have it
181
            if ( ! isset( $fieldList ) || isset( $fieldList[$key] ) )
182
               $fields[] = $value['dbColumn'] . ' ' . $key;
183
         }
184
         // Change it into something SQL can handle
185
         $query = implode( ',', $fields );
186
         // now, build the rest of the query
16 rodolico 187
         $query = "select $query from " . $this->configuration['tables']['users']['table'];
4 rodolico 188
         if ( isset( $whereFields ) ) {
189
            $temp = array();
190
            foreach ( $whereFields as $key => $value ) {
191
               $temp[] = ( 
192
                  $key == 'id' ? 
16 rodolico 193
                  $this->configuration['tables']['users']['id'] : 
194
                  $this->configuration['tables']['users']['fields'][$key]['dbColumn']
4 rodolico 195
                  ) . '= ' . $this->escapeString( $value );
196
            }
197
            $query .= ' where ' . implode( ' and ', $temp );
198
         }
199
         return $query;
200
      }
201
 
202
      /**
203
       * Get a record from the database
204
       * 
205
       * Gets a single record from the database which matches $field containing
206
       * $username. If more than one record is returned, will return the first
207
       * one
208
       * 
209
       * @param string[] $whereFields column=>value pairs for where clause
210
       * @param string[] $fieldList a list of columns to return. If empty, returns all columns
211
       * 
7 rodolico 212
       * @return string[] a hash containing fieldname=>value pairs from fetch_assoc
4 rodolico 213
       * 
214
      */
215
      public function getARecord( $whereFields, $fieldList = null ) {
216
         // run the query, placing value in $result
217
         mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
16 rodolico 218
         $result = $this->doSQL( $this->buildQuery( $whereFields, $fieldList ) );
4 rodolico 219
         if ( $result ) { // got one, so return it
220
            return $result->fetch_assoc();
221
         }
222
         // WTFO? nothing, so return empty array
223
         return array();
224
      }
225
 
7 rodolico 226
      /**
227
       * Retrieves the password field from table
228
       * 
229
       * Note that the password is stored as a hash in the table
230
       * 
231
       * @param string $username username used to find record
232
       * @return string[] an array of values key/value pairs
233
       */
4 rodolico 234
      public function getPassword( $username ) {
235
         return $this->getARecord( array('login' => $username,'enabled' => 1), array('pass' => 1 ) );
236
      }
237
 
7 rodolico 238
      /**
21 rodolico 239
       * retrieves the userID from the table
240
       * 
241
       * @param string $username
242
       * @return integer user id
243
       */
244
      public function getUserID( $username ) {
245
         $record = $this->getARecord( array( 'login' => $username ), array('id' => 1 ) );
246
         return $record['id'];
247
      }
248
 
249
      /**
7 rodolico 250
       * Make the database connection
251
       * 
252
       * @param string[] $parameters Parameters for makeing the connection
253
       * @return mysqli|false
254
       */
16 rodolico 255
      protected function setDBConnection ( $parameters ) {
4 rodolico 256
         if ( !isset($parameters['username'], $parameters['password'],$parameters['database']  )) {
257
            return false;
258
         }
259
         if ( !isset( $parameters['host'] ) ) {
260
            $parameters['host'] = 'localhost';
261
         }
262
         mysqli_report( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
263
         $this->dbConnection = new mysqli( $parameters['host'], $parameters['username'], $parameters['password'],$parameters['database'] );
264
      }
265
 
266
      /**
16 rodolico 267
       * Convenience function to create the tables defined in $configuration
4 rodolico 268
       * 
16 rodolico 269
       * Using $configuration, build the table (replacing the current one)
4 rodolico 270
       * then add $username with $password, setting as admin
271
       * 
272
      */
16 rodolico 273
      public function buildTable( ) {
4 rodolico 274
         if ( $this->dbConnection ) {
16 rodolico 275
            foreach ( $this->configuration['tables'] as $table => $tableRecord ) {
276
               $fields = array( $tableRecord['id'] . ' int unsigned not null auto_increment' );
277
               foreach ( $tableRecord['fields'] as $key => $record ) {
278
                  $fieldDef = $record['dbColumn'];
279
                  $fieldDef .= ' ' . $record['type'];
280
                  if ( isset( $record['size'] ) ) {
281
                     $fieldDef .= '(' . $record['size'] . ')';
282
                  }
21 rodolico 283
                  if ( isset( $record['unique'] ) ) {
284
                     $fieldDef .= ' unique ';
285
                  }
16 rodolico 286
                  if ( isset( $record['required'] ) ) {
287
                     $fieldDef .= $record['required'] ? ' not null ' : '';
288
                  }
289
                  if ( isset( $record['default'] ) ) {
290
                     $fieldDef .= sprintf( " default '%s'", $record['default'] );
291
                  }
292
                  if ( isset( $record['comment'] ) ) {
293
                     $fieldDef .= "comment '" . $record['comment'] . "'";
294
                  }
295
                  $fields[] = $fieldDef;
4 rodolico 296
               }
16 rodolico 297
               $fields[] = 'primary key (' . $tableRecord['id'] . ')';
298
               $query = implode( ',', $fields );
299
               $query = 'create or replace table ' . $tableRecord['table'] .
300
                     "($query)";
301
               $this->doSQL( $query );
4 rodolico 302
            }
16 rodolico 303
         } // foreach table
304
      } // buildTable
305
 
306
      /**
307
       * Convenience function to initialize tables to values
308
       * 
309
       * @param string[] $initValues Array of tablenames, column names and values
310
       * 
311
      */
312
      public function initTables ( $initValues ) {
313
         foreach ( $initValues as $table => $fieldDef ) {
314
            $columns = array();
315
            $values = array();
316
            foreach ( $fieldDef as $columnName => $columnValue ) {
317
               $columns[] = $this->tableColumnName( $table, $columnName );
318
               $values[] = $this->escapeString( $columnValue );
319
            }
320
            $query = sprintf( "insert into %s (%s) values (%s)", 
321
                  $this->configuration['tables'][$table]['table'],
322
                  implode( ",", $columns ), 
323
                  implode( ',', $values ) 
324
                  );
325
            $this->doSQL( $query );
4 rodolico 326
         }
16 rodolico 327
      }
4 rodolico 328
 
21 rodolico 329
      /**
330
       * Gets the actual database column name from the configuration file
331
       * 
332
       * Since we use a lot of indirection, this is a handy function which
333
       * allows us to replace something like
334
       * $this->configuration['tables']['users']['fields']['name']['dbColumn']
335
       * with
336
       * $this->tableColumnName( 'users', 'name' )
337
       * 
338
       * If called with only one parameter (the table), will return the
339
       * actual database table name
340
       * 
341
       * @param string $table Name of Table
342
       * @param string $field Name of field in $table
343
       * @param boolean $fullTableColumn If set to true, will return table.column format
344
       * 
345
       * @return string The actual name of the dbColumn in the table
346
       */
347
      protected function tableColumnName ( $table, $field = '', $fullTableColumn = false ) {
348
         if ( ! $field ) { // just return the table name
349
            $return = $this->configuration['tables'][$table]['table'];
350
         } elseif ( $field == 'id' ) { // looking for the index
351
            $return = $this->configuration['tables'][$table]['id'];
352
         } else { // return the column name
353
            $return = $this->configuration['tables'][$table]['fields'][$field]['dbColumn'];
354
         }
355
         if ( $fullTableColumn && $field ) {
356
            $return = $this->configuration['tables'][$table]['table'] . '.' . $return;
357
         }
358
         return $return;
16 rodolico 359
      }
360
 
4 rodolico 361
      /**
362
       * Tests that the database connection works and the table is built
7 rodolico 363
       *
364
       * @return boolean True if table exists (does not verify columns)
4 rodolico 365
       */
366
      public function test() {
21 rodolico 367
         $query = sprintf( "show tables like '%s'", $this->tableColumnName ( 'users' ) );
368
         $result = $this->doSQL( $query );
4 rodolico 369
         return $result !== false && $result->num_rows;
370
      } // test
371
 
7 rodolico 372
      /**
373
       * updates row in database with $newData
374
       * 
375
       * @param string[] $newData fieldname/value pairs to be updated in table
376
       * 
377
       * @return mysqli_result|bool The mysqli result from a query
378
       */
4 rodolico 379
      public function update ( $newData ) {
380
         $query = '';
381
         foreach ( $newData as $key => $value ) {
382
            $newData[$key] = $this->escapeString( $value );
383
         }
384
         if ( $newData ) { // make sure they sent us something
385
            if ( $newData['id'] > 0 ) { // we are doing an update
386
               $fields = array();
16 rodolico 387
               foreach ( $this->configuration['tables']['users']['fields'] as $key => $record ) {
4 rodolico 388
                  if ( isset( $newData[$key] ) ) {
389
                     $fields[] = $record['dbColumn'] . " = $newData[$key]";
390
                  } // if
391
               }
21 rodolico 392
               $query = 'update ' . $this->tableColumnName ( 'users' ) . ' set ' .
4 rodolico 393
                  implode( ',', $fields ) .
21 rodolico 394
                  ' where ' . $this->tableColumnName ( 'users', 'id' ) . ' = ' . 
17 rodolico 395
                  $this->escapeString( $newData['id'] );
4 rodolico 396
            } else { // we are doing an insert
397
               $columns = array();
398
               $values = array();
16 rodolico 399
               foreach ( $this->configuration['tables']['users']['fields'] as $key => $record ) {
4 rodolico 400
                  if ( isset( $newData[$key] ) ) {
401
                     $columns[] = $record['dbColumn'];
402
                     $values[] = $newData[$key];
403
                  } // if
404
               }
21 rodolico 405
               $query = 'insert into ' . $this->tableColumnName ( 'users' ) . 
4 rodolico 406
                  '(' . implode( ',', $columns ) . ') values (' .
407
                  implode( ',', $values ) . ')';
408
            }
21 rodolico 409
            return $this->doSQL( $query );
4 rodolico 410
         }
411
      } // update
412
 
7 rodolico 413
      /**
414
       * retrieves all users from the database
415
       * 
416
       * Retrieves all data for all users from table
417
       * 
418
       * @return string[] array of array of rows/columns
419
       */
4 rodolico 420
      public function getAllUsers() {
421
         $query = $this->buildQuery( null, null, array('login' => 1) );
422
         //print "<p>$query</p>\n";
423
         mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
16 rodolico 424
         $result = $this->doSQL( $query );
4 rodolico 425
         if ( $result ) {
426
            return $result->fetch_all(MYSQLI_ASSOC);
427
         }
428
         return array();
429
      }
16 rodolico 430
 
431
      /**
432
       * Executes an SQL statement, returning the result
433
       * 
434
       * This simply runs mysqli::query, and returns the value of that
435
       * 
436
       * Created for testing and debugging, if the second parameter is 
437
       * true, will NOT execute the query, but will instead display the 
438
       * query passed.
439
       * 
440
       * @parameter string $query SQL Query to execute
18 rodolico 441
       * @parameter string $comment if not empty, writes comment and query to a file
16 rodolico 442
       * 
443
       * @returns mysqli_result
444
       */
18 rodolico 445
      protected function doSQL( $query, $comment = '' ) {
446
         if ( $comment ) {
447
            $handle = fopen( '/tmp/log.sql', 'a' );
448
            fwrite( $handle, "$comment\n$query\n" );
449
            fclose( $handle );
450
         }
17 rodolico 451
         mysqli_report( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
452
         $result = $this->dbConnection->query( $query );
453
         return $result;
16 rodolico 454
      }
455
 
456
      /**
457
       * Gets a single field from a table
458
       * 
459
       * Builds a query similar to
460
       * select $returnColumn from $tableName where $fieldName = $value
461
       * executes it, and returns the first column of the first
462
       * row returned, or null if it does not exist.
463
       * 
464
       * @parameter string $tableName Name of database table
465
       * @parameter string $returnColumn Column to return
466
       * @parameter string $fieldName Name of column to search for value
467
       * @parameter string $value The value to match
468
       * 
469
       * @returns string $returnColumn of first row, or null if none
470
       */
471
      protected function getAField( $tableName, $returnColumn, $fieldName, $value ) {
472
         $value = $this->escapeString( $value );
473
         $result = $this->doSQL( "select $returnColumn from $tableName where $fieldName = $value" );
474
         $field = $result->fetch_array(MYSQLI_NUM);
475
         return $field ? $field[0] : null;
476
      }
4 rodolico 477
 
478
}
479
 
480
?>