Subversion Repositories php_users

Rev

Rev 32 | 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'] );
42 rodolico 291
                  } elseif ( ! empty( $record['required'] ) && strtolower($record['type']) == 'date' ) {
292
                     $fieldDef .= ' default CURRENT_TIMESTAMP';
16 rodolico 293
                  }
294
                  if ( isset( $record['comment'] ) ) {
295
                     $fieldDef .= "comment '" . $record['comment'] . "'";
296
                  }
297
                  $fields[] = $fieldDef;
4 rodolico 298
               }
16 rodolico 299
               $fields[] = 'primary key (' . $tableRecord['id'] . ')';
300
               $query = implode( ',', $fields );
301
               $query = 'create or replace table ' . $tableRecord['table'] .
302
                     "($query)";
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
            $this->doSQL( $query );
4 rodolico 328
         }
16 rodolico 329
      }
4 rodolico 330
 
21 rodolico 331
      /**
332
       * Gets the actual database column name from the configuration file
333
       * 
334
       * Since we use a lot of indirection, this is a handy function which
335
       * allows us to replace something like
336
       * $this->configuration['tables']['users']['fields']['name']['dbColumn']
337
       * with
338
       * $this->tableColumnName( 'users', 'name' )
339
       * 
340
       * If called with only one parameter (the table), will return the
341
       * actual database table name
342
       * 
343
       * @param string $table Name of Table
344
       * @param string $field Name of field in $table
345
       * @param boolean $fullTableColumn If set to true, will return table.column format
346
       * 
347
       * @return string The actual name of the dbColumn in the table
348
       */
349
      protected function tableColumnName ( $table, $field = '', $fullTableColumn = false ) {
350
         if ( ! $field ) { // just return the table name
351
            $return = $this->configuration['tables'][$table]['table'];
352
         } elseif ( $field == 'id' ) { // looking for the index
353
            $return = $this->configuration['tables'][$table]['id'];
354
         } else { // return the column name
355
            $return = $this->configuration['tables'][$table]['fields'][$field]['dbColumn'];
356
         }
357
         if ( $fullTableColumn && $field ) {
358
            $return = $this->configuration['tables'][$table]['table'] . '.' . $return;
359
         }
360
         return $return;
16 rodolico 361
      }
362
 
4 rodolico 363
      /**
364
       * Tests that the database connection works and the table is built
7 rodolico 365
       *
366
       * @return boolean True if table exists (does not verify columns)
4 rodolico 367
       */
368
      public function test() {
21 rodolico 369
         $query = sprintf( "show tables like '%s'", $this->tableColumnName ( 'users' ) );
370
         $result = $this->doSQL( $query );
4 rodolico 371
         return $result !== false && $result->num_rows;
372
      } // test
373
 
7 rodolico 374
      /**
375
       * updates row in database with $newData
376
       * 
377
       * @param string[] $newData fieldname/value pairs to be updated in table
378
       * 
379
       * @return mysqli_result|bool The mysqli result from a query
380
       */
4 rodolico 381
      public function update ( $newData ) {
382
         $query = '';
383
         foreach ( $newData as $key => $value ) {
384
            $newData[$key] = $this->escapeString( $value );
385
         }
386
         if ( $newData ) { // make sure they sent us something
387
            if ( $newData['id'] > 0 ) { // we are doing an update
388
               $fields = array();
16 rodolico 389
               foreach ( $this->configuration['tables']['users']['fields'] as $key => $record ) {
4 rodolico 390
                  if ( isset( $newData[$key] ) ) {
391
                     $fields[] = $record['dbColumn'] . " = $newData[$key]";
392
                  } // if
393
               }
21 rodolico 394
               $query = 'update ' . $this->tableColumnName ( 'users' ) . ' set ' .
4 rodolico 395
                  implode( ',', $fields ) .
21 rodolico 396
                  ' where ' . $this->tableColumnName ( 'users', 'id' ) . ' = ' . 
17 rodolico 397
                  $this->escapeString( $newData['id'] );
4 rodolico 398
            } else { // we are doing an insert
399
               $columns = array();
400
               $values = array();
16 rodolico 401
               foreach ( $this->configuration['tables']['users']['fields'] as $key => $record ) {
4 rodolico 402
                  if ( isset( $newData[$key] ) ) {
403
                     $columns[] = $record['dbColumn'];
404
                     $values[] = $newData[$key];
405
                  } // if
406
               }
21 rodolico 407
               $query = 'insert into ' . $this->tableColumnName ( 'users' ) . 
4 rodolico 408
                  '(' . implode( ',', $columns ) . ') values (' .
409
                  implode( ',', $values ) . ')';
410
            }
21 rodolico 411
            return $this->doSQL( $query );
4 rodolico 412
         }
413
      } // update
414
 
7 rodolico 415
      /**
416
       * retrieves all users from the database
417
       * 
418
       * Retrieves all data for all users from table
419
       * 
420
       * @return string[] array of array of rows/columns
421
       */
4 rodolico 422
      public function getAllUsers() {
423
         $query = $this->buildQuery( null, null, array('login' => 1) );
424
         //print "<p>$query</p>\n";
425
         mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
16 rodolico 426
         $result = $this->doSQL( $query );
4 rodolico 427
         if ( $result ) {
428
            return $result->fetch_all(MYSQLI_ASSOC);
429
         }
430
         return array();
431
      }
16 rodolico 432
 
433
      /**
434
       * Executes an SQL statement, returning the result
435
       * 
436
       * This simply runs mysqli::query, and returns the value of that
437
       * 
438
       * Created for testing and debugging, if the second parameter is 
439
       * true, will NOT execute the query, but will instead display the 
440
       * query passed.
441
       * 
442
       * @parameter string $query SQL Query to execute
18 rodolico 443
       * @parameter string $comment if not empty, writes comment and query to a file
16 rodolico 444
       * 
445
       * @returns mysqli_result
446
       */
18 rodolico 447
      protected function doSQL( $query, $comment = '' ) {
448
         if ( $comment ) {
449
            $handle = fopen( '/tmp/log.sql', 'a' );
450
            fwrite( $handle, "$comment\n$query\n" );
451
            fclose( $handle );
452
         }
17 rodolico 453
         mysqli_report( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
454
         $result = $this->dbConnection->query( $query );
455
         return $result;
16 rodolico 456
      }
457
 
458
      /**
459
       * Gets a single field from a table
460
       * 
461
       * Builds a query similar to
462
       * select $returnColumn from $tableName where $fieldName = $value
463
       * executes it, and returns the first column of the first
464
       * row returned, or null if it does not exist.
465
       * 
466
       * @parameter string $tableName Name of database table
467
       * @parameter string $returnColumn Column to return
468
       * @parameter string $fieldName Name of column to search for value
469
       * @parameter string $value The value to match
470
       * 
471
       * @returns string $returnColumn of first row, or null if none
472
       */
473
      protected function getAField( $tableName, $returnColumn, $fieldName, $value ) {
474
         $value = $this->escapeString( $value );
475
         $result = $this->doSQL( "select $returnColumn from $tableName where $fieldName = $value" );
476
         $field = $result->fetch_array(MYSQLI_NUM);
477
         return $field ? $field[0] : null;
478
      }
4 rodolico 479
 
480
}
481
 
482
?>