class Database

Tuskfish database handler class, implements \PDO and exclusively uses prepared statements.

Prepared statements with bound values are used to mitigate SQL injection attacks. Table and column identifiers are also escaped. However, you should have thoroughly validated and range checked data before it reaches this class.

Traits

Validate and range check integers.
Provides methods for validating UTF-8 character encoding and string composition.

Methods

bool
isInt(int $int, int $min = null, int $max = null)

Validate integer, optionally include range check.

string
encodeEscapeUrl(string $url)

URL-encode and escape a query string for use in a URL.

bool
isAlnum(string $alnum)

Check that a string is comprised solely of alphanumeric characters.

bool
isAlnumUnderscore(string $alnumUnderscore)

Check that a string is comprised solely of alphanumeric characters and underscores.

bool
isAlpha(string $alpha)

Check that a string is comprised solely of alphabetical characters.

bool
isUtf8(string $text)

Check if the character encoding of text is UTF-8.

string
trimString(mixed $text)

Cast to string, check UTF-8 encoding and strip trailing whitespace and control characters.

__construct(Logger $logger, FileHandler $fileHandler)

Constructor.

string
addBackticks(string $identifier)

Enclose table and column identifiers in backticks to escape them.

bool
close()

Close the connection to the database.

bool
connect()

Establish a connection to the database.

string|bool
create(string $dbName)

Create an SQLite database with random prefix and creates a language constant for it.

bool
createTable(string $table, array $columns, string $primaryKey = null)

Create a table in the database.

bool
delete(string $table, int $id)

Delete single row from table based on its ID.

bool
deleteAll(string $table, Criteria $criteria)

Delete multiple rows from a table according to criteria.

string
escapeIdentifier(string $identifier)

Escape delimiters for identifiers (table and column names).

bool
executeTransaction(PDOStatement $statement)

Execute a prepared statement within a transaction.

bool
insert(string $table, array $keyValues)

Insert a single row into the database within a transaction.

int|bool
lastInsertId()

Retrieves the ID of the last row inserted into the database.

preparedStatement(string $sql)

Return a \PDO statement object.

select(string $table, Criteria $criteria = null, array $columns = null)

Prepare and execute a select query.

int|object
selectCount(string $table, Criteria $criteria = null, string $column = '')

Count the number of rows matching a set of conditions.

selectDistinct(string $table, Criteria $criteria = null, array $columns)

Select results from the database but remove duplicate rows.

bool
toggleBoolean(int $id, string $table, string $column)

Toggle the online status of a column between 0 and 1, use for columns representing booleans.

bool
updateCounter(int $id, string $table, string $column)

Increment a content object counter field by one.

bool
update(string $table, int $id, array $keyValues)

Update a single row in the database.

updateAll(string $table, array $keyValues, Criteria $criteria = null)

Update multiple rows in a table according to criteria.

int
setType(mixed $data)

Helper method to set appropriate \PDO predefined constants in bindValue() and bindParam().

validateCriteriaObject(Criteria $criteria)

Validates the properties of a Criteria object to be used in constructing a query.

array
validateColumns(array $columns)

Validate and escape column names to be used in constructing a database query.

int
validateId(int $id)

Validates and sanitises an ID to be used in constructing a database query.

array
validateKeys(array $keyValues)

Validate and escapes keys to be used in constructing a database query.

string
validateTableName(string $tableName)

Validate and escape a table name to be used in constructing a database query.

Details

in IntegerCheck at line 39
bool isInt(int $int, int $min = null, int $max = null)

Validate integer, optionally include range check.

Parameters

int $int Input to be tested.
int $min Minimum acceptable value.
int $max Maximum acceptable value.

Return Value

bool True if valid int and within optional range check, false otherwise.

in ValidateString at line 41
string encodeEscapeUrl(string $url)

URL-encode and escape a query string for use in a URL.

Trims, checks for UTF-8 compliance, rawurlencodes and then escapes with htmlspecialchars(). If you wish to use the data on a landing page you must decode it with htmlspecialchars_decode() followed by rawurldecode() in that order. But really, if you are using any characters that need to be encoded in the first place you should probably just stop.

Parameters

string $url Unescaped input URL.

Return Value

string Encoded and escaped URL.

in ValidateString at line 59
bool isAlnum(string $alnum)

Check that a string is comprised solely of alphanumeric characters.

Accented regional characters are rejected. This method is designed to be used to check database identifiers or object property names.

Parameters

string $alnum Input to be tested.

Return Value

bool True if valid alphanumerical string, false otherwise.

in ValidateString at line 77
bool isAlnumUnderscore(string $alnumUnderscore)

Check that a string is comprised solely of alphanumeric characters and underscores.

Accented regional characters are rejected. This method is designed to be used to check database identifiers or object property names.

Parameters

string $alnumUnderscore Input to be tested.

Return Value

bool True if valid alphanumerical or underscore string, false otherwise.

in ValidateString at line 95
bool isAlpha(string $alpha)

Check that a string is comprised solely of alphabetical characters.

Tolerates vanilla ASCII only. Accented regional characters are rejected. This method is designed to be used to check database identifiers or object property names.

Parameters

string $alpha Input to be tested.

Return Value

bool True if valid alphabetical string, false otherwise.

in ValidateString at line 113
bool isUtf8(string $text)

Check if the character encoding of text is UTF-8.

All strings received from external sources must be passed through this function, particularly prior to storage in the database.

Parameters

string $text Input string to check.

Return Value

bool True if string is UTF-8 encoded otherwise false.

in ValidateString at line 131
string trimString(mixed $text)

Cast to string, check UTF-8 encoding and strip trailing whitespace and control characters.

Removes trailing whitespace and control characters (ASCII <= 32 / UTF-8 points 0-32 inclusive), checks for UTF-8 character set and casts input to a string. Note that the data returned by this function still requires escaping at the point of use; it is not database or XSS safe.

As the input is cast to a string do NOT apply this function to non-string types (int, float, bool, object, resource, null, array, etc).

Parameters

mixed $text Input to be trimmed.

Return Value

string Trimmed and UTF-8 validated string.

at line 52
__construct(Logger $logger, FileHandler $fileHandler)

Constructor.

Parameters

Logger $logger An instance of the Tuskfish error logger class.
FileHandler $fileHandler An instance of the Tuskfish file handler class.

at line 74
string addBackticks(string $identifier)

Enclose table and column identifiers in backticks to escape them.

This method must only be used on TABLE and COLUMN names. Column values must be escaped through the use of bound parameters.

Parameters

string $identifier Table or column name.

Return Value

string Identifier encapsulated in backticks.

at line 84
bool close()

Close the connection to the database.

Return Value

bool True on success false on failure.

at line 98
bool connect()

Establish a connection to the database.

Connection is deliberately non-persistent (persistence can break things if scripts terminate unexpectedly).

Return Value

bool True on success, false on failure.

at line 120
string|bool create(string $dbName)

Create an SQLite database with random prefix and creates a language constant for it.

Database name must be alphanumeric and underscore characters only. The database will automatically be appended with the suffix .db

Parameters

string $dbName Database name.

Return Value

string|bool Path to database file on success, false on failure.

at line 169
bool createTable(string $table, array $columns, string $primaryKey = null)

Create a table in the database.

Table names may only be alphanumeric characters. Column names are also alphanumeric but may also contain underscores.

Parameters

string $table Table name (alphanumeric characters only).
array $columns Array of column names (keys) and types (values).
string $primaryKey Name of field to be used as primary key.

Return Value

bool True on success, false on failure.

at line 258
bool delete(string $table, int $id)

Delete single row from table based on its ID.

Parameters

string $table Name of table.
int $id ID of row to be deleted.

Return Value

bool True on success false on failure.

at line 293
bool deleteAll(string $table, Criteria $criteria)

Delete multiple rows from a table according to criteria.

For safety reasons criteria are required; the function will not unconditionally empty table. Note that SQLite does not support DELETE with INNER JOIN or table alias. Therefore, you cannot use tags as a criteria in deleteAll() (they will simply be ignored). It may be possible to get around this restriction with a loop or subquery.

Parameters

string $table Name of table.
Criteria $criteria Criteria object used to build conditional database query.

Return Value

bool True on success, false on failure.

at line 362
string escapeIdentifier(string $identifier)

Escape delimiters for identifiers (table and column names).

SQLite supports three styles of identifier delimitation:

  1. Standard SQL double quotes: "
  2. MySQL style grave accents: `
  3. MS SQL style square brackets: []

Escaping of delimiters where they are used as part of a table or column name is done by doubling them, eg ` becomes ``. In order to safely escape table and column names ALL three delimiter types must be escaped.

Tuskfish policy is that table names can only contain alphanumeric characters (and column names can only contain alphanumeric plus underscore characters) so delimiters should never get into a query as part of an identifier. But just because we are paranoid they are escaped here anyway.

Parameters

string $identifier Name of table or column.

Return Value

string Escaped table or column name.

at line 384
bool executeTransaction(PDOStatement $statement)

Execute a prepared statement within a transaction.

The $statement parameter should be a prepared statement obtained via preparedStatement($sql). Note that statement execution is within a transaction and rollback will occur if it fails. This method should be used with database write operations (INSERT, UPDATE, DELETE).

Parameters

PDOStatement $statement Prepared statement.

Return Value

bool True on success, false on failure.

at line 406
bool insert(string $table, array $keyValues)

Insert a single row into the database within a transaction.

Parameters

string $table Name of table.
array $keyValues Column names and values to be inserted.

Return Value

bool True on success, false on failure.

at line 450
int|bool lastInsertId()

Retrieves the ID of the last row inserted into the database.

Used primarily to grab the ID of newly created content objects so that their accompanying taglinks can be correctly associated to them.

Return Value

int|bool Row ID on success, false on failure.

at line 468
PDOStatement preparedStatement(string $sql)

Return a \PDO statement object.

Statement object can be used to bind values or parameters and execute queries, thereby mitigating direct SQL injection attacks.

Parameters

string $sql SQL statement.

Return Value

PDOStatement \PDOStatement object on success \PDOException object on failure.

at line 736
PDOStatement select(string $table, Criteria $criteria = null, array $columns = null)

Prepare and execute a select query.

Returns a \PDO statement object, from which results can be extracted with standard \PDO calls.

Parameters

string $table Name of table.
Criteria $criteria Query composer object used to build conditional database query.
array $columns Names of database columns to be selected.

Return Value

PDOStatement \PDOStatement object on success \PDOException on failure.

at line 832
int|object selectCount(string $table, Criteria $criteria = null, string $column = '')

Count the number of rows matching a set of conditions.

Parameters

string $table Name of table.
Criteria $criteria Query composer object used to build conditional database query.
string $column Name of column.

Return Value

int|object Row count on success, \PDOException object on failure.

at line 926
PDOStatement selectDistinct(string $table, Criteria $criteria = null, array $columns)

Select results from the database but remove duplicate rows.

Use the $columns array to specify which fields you want to filter the results by.

Parameters

string $table Name of table.
Criteria $criteria Query composer object used to build conditional database query.
array $columns Name of columns to filter results by.

Return Value

PDOStatement \PDOStatement on success, \PDOException on failure.

at line 1016
bool toggleBoolean(int $id, string $table, string $column)

Toggle the online status of a column between 0 and 1, use for columns representing booleans.

Note that the $id MUST represent a column called ID for whatever table you want to run it on.

Parameters

int $id ID of the row to update.
string $table Name of table.
string $column Name of column to update.

Return Value

bool True on success, false on failure.

at line 1054
bool updateCounter(int $id, string $table, string $column)

Increment a content object counter field by one.

Call this method when the full description of an individual content object is viewed, or when a related media file is downloaded.

Parameters

int $id ID of content object.
string $table Name of table.
string $column Name of column.

Return Value

bool True on success false on failure.

at line 1088
bool update(string $table, int $id, array $keyValues)

Update a single row in the database.

Parameters

string $table Name of table.
int $id ID of row to update.
array $keyValues Array of column names and values to update.

Return Value

bool True on success, false on failure.

at line 1140
updateAll(string $table, array $keyValues, Criteria $criteria = null)

Update multiple rows in a table according to criteria.

Note that SQLite does not support INNER JOIN or table aliases in UPDATE; therefore it is not possible to use tags as a criteria in updateAll() at present. It may be possible to get around this limitation with a subquery. But given that the use case would be unusual / marginal it is probably just easier to work around it.

Parameters

string $table Name of table.
array $keyValues Array of column names and values to update.
Criteria $criteria Query composer object used to build conditional database query.

at line 1209
int setType(mixed $data)

Helper method to set appropriate \PDO predefined constants in bindValue() and bindParam().

Do not use this method for arrays, objects or resources. Note that if you pass in an unexpected data type (ie. one that clashes with a column type definition) \PDO will throw an error.

Parameters

mixed $data Input data to be type set.

Return Value

int \PDO data type constant.

at line 1260
Criteria validateCriteriaObject(Criteria $criteria)

Validates the properties of a Criteria object to be used in constructing a query.

Parameters

Criteria $criteria Query composer object.

Return Value

Criteria Validated Criteria object.

at line 1355
array validateColumns(array $columns)

Validate and escape column names to be used in constructing a database query.

Parameters

array $columns Array of unescaped column names.

Return Value

array Array of valid, escaped column names

at line 1386
int validateId(int $id)

Validates and sanitises an ID to be used in constructing a database query.

Parameters

int $id Input ID to be tested.

Return Value

int $id Validated ID.

at line 1406
array validateKeys(array $keyValues)

Validate and escapes keys to be used in constructing a database query.

Keys may only consist of alphanumeric and underscore characters. SQLite identifier delimiters are escaped.

Parameters

array $keyValues Array of unescaped keys.

Return Value

array Array of valid and escaped keys.

at line 1437
string validateTableName(string $tableName)

Validate and escape a table name to be used in constructing a database query.

Parameters

string $tableName Table name to be checked.

Return Value

string Valid and escaped table name.