diff options
Diffstat (limited to 'engine/lib/database.php')
| -rw-r--r-- | engine/lib/database.php | 686 |
1 files changed, 398 insertions, 288 deletions
diff --git a/engine/lib/database.php b/engine/lib/database.php index 58685bb82..a7949788d 100644 --- a/engine/lib/database.php +++ b/engine/lib/database.php @@ -1,35 +1,94 @@ <?php /** - * Elgg database - * Contains database connection and transfer functionality + * Elgg database procedural code. * - * @package Elgg - * @subpackage Core - - * @author Curverider Ltd + * Includes functions for establishing and retrieving a database link, + * reading data, writing data, upgrading DB schemas, and sanitizing input. + * + * @package Elgg.Core + * @subpackage Database + */ - * @link http://elgg.org/ +/** + * Query cache for all queries. + * + * Each query and its results are stored in this cache as: + * <code> + * $DB_QUERY_CACHE[query hash] => array(result1, result2, ... resultN) + * </code> + * @see elgg_query_runner() for details on the hash. + * + * @warning Elgg used to set this as an empty array to turn off the cache + * + * @global ElggLRUCache|null $DB_QUERY_CACHE + * @access private */ +global $DB_QUERY_CACHE; +$DB_QUERY_CACHE = null; -$DB_QUERY_CACHE = array(); +/** + * Queries to be executed upon shutdown. + * + * These queries are saved to an array and executed using + * a function registered by register_shutdown_function(). + * + * Queries are saved as an array in the format: + * <code> + * $DB_DELAYED_QUERIES[] = array( + * 'q' => str $query, + * 'l' => resource $dblink, + * 'h' => str $handler // a callback function + * ); + * </code> + * + * @global array $DB_DELAYED_QUERIES + * @access private + */ +global $DB_DELAYED_QUERIES; $DB_DELAYED_QUERIES = array(); /** + * Database connection resources. + * + * Each database link created with establish_db_link($name) is stored in + * $dblink as $dblink[$name] => resource. Use get_db_link($name) to retrieve it. + * + * @global resource[] $dblink + * @access private + */ +global $dblink; +$dblink = array(); + +/** + * Database call count + * + * Each call to the database increments this counter. + * + * @global integer $dbcalls + * @access private + */ +global $dbcalls; +$dbcalls = 0; + +/** + * Establish a connection to the database servser + * * Connect to the database server and use the Elgg database for a particular database link * - * @param string $dblinkname Default "readwrite"; you can change this to set up additional global database links, eg "read" and "write" + * @param string $dblinkname The type of database connection. Used to identify the + * resource. eg "read", "write", or "readwrite". + * + * @return void + * @throws DatabaseException + * @access private */ function establish_db_link($dblinkname = "readwrite") { // Get configuration, and globalise database link - global $CONFIG, $dblink, $DB_QUERY_CACHE, $dbcalls; - - if (!isset($dblink)) { - $dblink = array(); - } + global $CONFIG, $dblink, $DB_QUERY_CACHE; if ($dblinkname != "readwrite" && isset($CONFIG->db[$dblinkname])) { if (is_array($CONFIG->db[$dblinkname])) { - $index = rand(0,sizeof($CONFIG->db[$dblinkname])); + $index = rand(0, sizeof($CONFIG->db[$dblinkname])); $dbhost = $CONFIG->db[$dblinkname][$index]->dbhost; $dbuser = $CONFIG->db[$dblinkname][$index]->dbuser; $dbpass = $CONFIG->db[$dblinkname][$index]->dbpass; @@ -48,13 +107,14 @@ function establish_db_link($dblinkname = "readwrite") { } // Connect to database - if (!$dblink[$dblinkname] = mysql_connect($CONFIG->dbhost, $CONFIG->dbuser, $CONFIG->dbpass, true)) { - $msg = sprintf(elgg_echo('DatabaseException:WrongCredentials'), - $CONFIG->dbuser, $CONFIG->dbhost, "****"); + if (!$dblink[$dblinkname] = mysql_connect($dbhost, $dbuser, $dbpass, true)) { + $msg = elgg_echo('DatabaseException:WrongCredentials', + array($dbuser, $dbhost, "****")); throw new DatabaseException($msg); } - if (!mysql_select_db($CONFIG->dbname, $dblink[$dblinkname])) { - $msg = sprintf(elgg_echo('DatabaseException:NoConnect'), $CONFIG->dbname); + + if (!mysql_select_db($dbname, $dblink[$dblinkname])) { + $msg = elgg_echo('DatabaseException:NoConnect', array($dbname)); throw new DatabaseException($msg); } @@ -68,21 +128,22 @@ function establish_db_link($dblinkname = "readwrite") { // Set up cache if global not initialized and query cache not turned off if ((!$DB_QUERY_CACHE) && (!$db_cache_off)) { - $DB_QUERY_CACHE = new ElggStaticVariableCache('db_query_cache'); //array(); - //$DB_QUERY_CACHE = select_default_memcache('db_query_cache'); //array(); + // @todo if we keep this cache in 1.9, expose the size as a config parameter + $DB_QUERY_CACHE = new ElggLRUCache(200); } } /** - * Establish all database connections + * Establish database connections * * If the configuration has been set up for multiple read/write databases, set those - * links up separately; otherwise just create the one database link + * links up separately; otherwise just create the one database link. * + * @return void + * @access private */ function setup_db_connections() { - // Get configuration and globalise database link - global $CONFIG, $dblink; + global $CONFIG; if (!empty($CONFIG->db->split)) { establish_db_link('read'); @@ -93,7 +154,10 @@ function setup_db_connections() { } /** - * Shutdown hook to display profiling information about db (debug mode) + * Display profiling information about db at NOTICE debug level upon shutdown. + * + * @return void + * @access private */ function db_profiling_shutdown_hook() { global $dbcalls; @@ -103,44 +167,47 @@ function db_profiling_shutdown_hook() { } /** - * Execute any delayed queries. + * Execute any delayed queries upon shutdown. + * + * @return void + * @access private */ function db_delayedexecution_shutdown_hook() { - global $DB_DELAYED_QUERIES, $CONFIG; + global $DB_DELAYED_QUERIES; foreach ($DB_DELAYED_QUERIES as $query_details) { - // use one of our db functions so it is included in profiling. - $result = execute_query($query_details['q'], $query_details['l']); - try { + $link = $query_details['l']; + + if ($link == 'read' || $link == 'write') { + $link = get_db_link($link); + } elseif (!is_resource($link)) { + elgg_log("Link for delayed query not valid resource or db_link type. Query: {$query_details['q']}", 'WARNING'); + } + + $result = execute_query($query_details['q'], $link); + if ((isset($query_details['h'])) && (is_callable($query_details['h']))) { $query_details['h']($result); } - } catch (Exception $e) { // Suppress all errors since these can't be delt with here + } catch (Exception $e) { + // Suppress all errors since these can't be dealt with here elgg_log($e, 'WARNING'); } } } /** - * Alias to setup_db_connections, for use in the event handler + * Returns (if required, also creates) a database link resource. * - * @param string $event The event type - * @param string $object_type The object type - * @param mixed $object Used for nothing in this context - */ -function init_db($event, $object_type, $object = null) { - register_shutdown_function('db_delayedexecution_shutdown_hook'); - register_shutdown_function('db_profiling_shutdown_hook'); - // [Marcus Povey 20090213: Db connection moved to first db connection attempt] - return true; -} - -/** - * Gets the appropriate db link for the operation mode requested + * Database link resources are stored in the {@link $dblink} global. These + * resources are created by {@link setup_db_connections()}, which is called if + * no links exist. * - * @param string $dblinktype The type of link we want - "read", "write" or "readwrite" (the default) - * @return object Database link + * @param string $dblinktype The type of link we want: "read", "write" or "readwrite". + * + * @return resource Database link + * @access private */ function get_db_link($dblinktype) { global $dblink; @@ -149,40 +216,59 @@ function get_db_link($dblinktype) { return $dblink[$dblinktype]; } else if (isset($dblink['readwrite'])) { return $dblink['readwrite']; - } - else { + } else { setup_db_connections(); return get_db_link($dblinktype); } } /** - * Explain a given query, useful for debug. + * Execute an EXPLAIN for $query. + * + * @param string $query The query to explain + * @param mixed $link The database link resource to user. + * + * @return mixed An object of the query's result, or FALSE + * @access private */ function explain_query($query, $link) { if ($result = execute_query("explain " . $query, $link)) { return mysql_fetch_object($result); } - return false; + return FALSE; } /** * Execute a query. * - * @param string $query The query - * @param link $dblink the DB link - * @return Returns a the result of mysql_query + * $query is executed via {@link mysql_query()}. If there is an SQL error, + * a {@link DatabaseException} is thrown. + * + * @internal + * {@link $dbcalls} is incremented and the query is saved into the {@link $DB_QUERY_CACHE}. + * + * @param string $query The query + * @param resource $dblink The DB link + * + * @return resource result of mysql_query() + * @throws DatabaseException + * @access private */ function execute_query($query, $dblink) { - global $CONFIG, $dbcalls, $DB_QUERY_CACHE; + global $dbcalls; + + if ($query == NULL) { + throw new DatabaseException(elgg_echo('DatabaseException:InvalidQuery')); + } + + if (!is_resource($dblink)) { + throw new DatabaseException(elgg_echo('DatabaseException:InvalidDBLink')); + } $dbcalls++; $result = mysql_query($query, $dblink); - if ($DB_QUERY_CACHE) { - $DB_QUERY_CACHE[$query] = -1; // Set initial cache to -1 - } if (mysql_errno($dblink)) { throw new DatabaseException(mysql_error($dblink) . "\n\n QUERY: " . $query); @@ -192,14 +278,17 @@ function execute_query($query, $dblink) { } /** - * Queue a query for execution after all output has been sent to the user. + * Queue a query for execution upon shutdown. * * You can specify a handler function if you care about the result. This function will accept - * the raw result from mysql_query(); + * the raw result from {@link mysql_query()}. + * + * @param string $query The query to execute + * @param resource|string $dblink The database link to use or the link type (read | write) + * @param string $handler A callback function to pass the results array to * - * @param string $query The query to execute - * @param resource $dblink The database link to use - * @param string $handler The handler + * @return true + * @access private */ function execute_delayed_query($query, $dblink, $handler = "") { global $DB_DELAYED_QUERIES; @@ -208,6 +297,10 @@ function execute_delayed_query($query, $dblink, $handler = "") { $DB_DELAYED_QUERIES = array(); } + if (!is_resource($dblink) && $dblink != 'read' && $dblink != 'write') { + return false; + } + // Construct delayed query $delayed_query = array(); $delayed_query['q'] = $query; @@ -216,212 +309,243 @@ function execute_delayed_query($query, $dblink, $handler = "") { $DB_DELAYED_QUERIES[] = $delayed_query; - return true; + return TRUE; } /** * Write wrapper for execute_delayed_query() * - * @param string $query The query to execute + * @param string $query The query to execute * @param string $handler The handler if you care about the result. + * + * @return true + * @uses execute_delayed_query() + * @uses get_db_link() + * @access private */ function execute_delayed_write_query($query, $handler = "") { - return execute_delayed_query($query, get_db_link('write'), $handler); + return execute_delayed_query($query, 'write', $handler); } /** * Read wrapper for execute_delayed_query() * - * @param string $query The query to execute + * @param string $query The query to execute * @param string $handler The handler if you care about the result. + * + * @return true + * @uses execute_delayed_query() + * @uses get_db_link() + * @access private */ function execute_delayed_read_query($query, $handler = "") { - return execute_delayed_query($query, get_db_link('read'), $handler); + return execute_delayed_query($query, 'read', $handler); } /** - * Use this function to get data from the database - * @param mixed $query The query being passed. - * @param string $call Optionally, the name of a function to call back to on each row (which takes $row as a single parameter) - * @return array An array of database result objects + * Retrieve rows from the database. + * + * Queries are executed with {@link execute_query()} and results + * are retrieved with {@link mysql_fetch_object()}. If a callback + * function $callback is defined, each row will be passed as the single + * argument to $callback. If no callback function is defined, the + * entire result set is returned as an array. + * + * @param mixed $query The query being passed. + * @param string $callback Optionally, the name of a function to call back to on each row + * + * @return array An array of database result objects or callback function results. If the query + * returned nothing, an empty array. + * @access private */ function get_data($query, $callback = "") { - global $CONFIG, $DB_QUERY_CACHE; + return elgg_query_runner($query, $callback, false); +} - // Is cached? - if ($DB_QUERY_CACHE) { - $cached_query = $DB_QUERY_CACHE[$query]; - } +/** + * Retrieve a single row from the database. + * + * Similar to {@link get_data()} but returns only the first row + * matched. If a callback function $callback is specified, the row will be passed + * as the only argument to $callback. + * + * @param mixed $query The query to execute. + * @param string $callback A callback function + * + * @return mixed A single database result object or the result of the callback function. + * @access private + */ +function get_data_row($query, $callback = "") { + return elgg_query_runner($query, $callback, true); +} + +/** + * Handles returning data from a query, running it through a callback function, + * and caching the results. This is for R queries (from CRUD). + * + * @access private + * + * @param string $query The query to execute + * @param string $callback An optional callback function to run on each row + * @param bool $single Return only a single result? + * + * @return array An array of database result objects or callback function results. If the query + * returned nothing, an empty array. + * @since 1.8.0 + * @access private + */ +function elgg_query_runner($query, $callback = null, $single = false) { + global $DB_QUERY_CACHE; - if ((isset($cached_query)) && ($cached_query)) { - elgg_log("$query results returned from cache"); + // Since we want to cache results of running the callback, we need to + // need to namespace the query with the callback and single result request. + // https://github.com/elgg/elgg/issues/4049 + $hash = (string)$callback . (int)$single . $query; - if ($cached_query === -1) { - // Last time this query returned nothing, so return an empty array - return array(); + // Is cached? + if ($DB_QUERY_CACHE) { + if (isset($DB_QUERY_CACHE[$hash])) { + elgg_log("DB query $query results returned from cache (hash: $hash)", 'NOTICE'); + return $DB_QUERY_CACHE[$hash]; } - - return $cached_query; } $dblink = get_db_link('read'); - $resultarray = array(); + $return = array(); if ($result = execute_query("$query", $dblink)) { + + // test for callback once instead of on each iteration. + // @todo check profiling to see if this needs to be broken out into + // explicit cases instead of checking in the iteration. + $is_callable = is_callable($callback); while ($row = mysql_fetch_object($result)) { - if (!empty($callback) && is_callable($callback)) { + if ($is_callable) { $row = $callback($row); } - if ($row) { - $resultarray[] = $row; + + if ($single) { + $return = $row; + break; + } else { + $return[] = $row; } } } - if (empty($resultarray)) { - elgg_log("DB query \"$query\" returned no results."); - return false; + if (empty($return)) { + elgg_log("DB query $query returned no results.", 'NOTICE'); } // Cache result if ($DB_QUERY_CACHE) { - $DB_QUERY_CACHE[$query] = $resultarray; - elgg_log("$query results cached"); - } - - return $resultarray; -} - -/** - * Use this function to get a single data row from the database - * @param mixed $query The query to run. - * @return object A single database result object - */ - -function get_data_row($query, $callback = "") { - global $CONFIG, $DB_QUERY_CACHE; - - // Is cached - if ($DB_QUERY_CACHE) { - $cached_query = $DB_QUERY_CACHE[$query]; - } - - if ((isset($cached_query)) && ($cached_query)) { - elgg_log("$query results returned from cache"); - - if ($cached_query === -1) { - // Last time this query returned nothing, so return false - //@todo fix me this should return array(). - return false; - } - - return $cached_query; - } - - $dblink = get_db_link('read'); - - if ($result = execute_query("$query", $dblink)) { - $row = mysql_fetch_object($result); - - // Cache result (even if query returned no data) - if ($DB_QUERY_CACHE) { - $DB_QUERY_CACHE[$query] = $row; - elgg_log("$query results cached"); - } - - if (!empty($callback) && is_callable($callback)) { - $row = $callback($row); - } - - if ($row) { - return $row; - } + $DB_QUERY_CACHE[$hash] = $return; + elgg_log("DB query $query results cached (hash: $hash)", 'NOTICE'); } - elgg_log("$query returned no results."); - return FALSE; + return $return; } /** - * Use this function to insert database data; returns id or false + * Insert a row into the database. + * + * @note Altering the DB invalidates all queries in {@link $DB_QUERY_CACHE}. + * + * @param mixed $query The query to execute. * - * @param mixed $query The query to run. - * @return int $id the database id of the inserted row. + * @return int|false The database id of the inserted row if a AUTO_INCREMENT field is + * defined, 0 if not, and false on failure. + * @access private */ function insert_data($query) { - global $CONFIG, $DB_QUERY_CACHE; + elgg_log("DB query $query", 'NOTICE'); + $dblink = get_db_link('write'); - // Invalidate query cache - if ($DB_QUERY_CACHE) { - $DB_QUERY_CACHE->clear(); - } - - elgg_log("Query cache invalidated"); + _elgg_invalidate_query_cache(); if (execute_query("$query", $dblink)) { return mysql_insert_id($dblink); } - return false; + return FALSE; } /** - * Update database data + * Update the database. + * + * @note Altering the DB invalidates all queries in {@link $DB_QUERY_CACHE}. + * + * @param string $query The query to run. * - * @param mixed $query The query to run. - * @return Bool on success + * @return bool + * @access private */ function update_data($query) { - global $CONFIG, $DB_QUERY_CACHE; + + elgg_log("DB query $query", 'NOTICE'); $dblink = get_db_link('write'); - // Invalidate query cache - if ($DB_QUERY_CACHE) { - $DB_QUERY_CACHE->clear(); - elgg_log("Query cache invalidated"); - } + _elgg_invalidate_query_cache(); if (execute_query("$query", $dblink)) { - // @todo why is this comment out? - //return mysql_affected_rows(); - return true; + return TRUE; } - return false; + return FALSE; } /** - * Use this function to delete data + * Remove data from the database. * - * @param mixed $query The SQL query to run - * @return int|false Either the number of affected rows, or false on failure + * @note Altering the DB invalidates all queries in {@link $DB_QUERY_CACHE}. + * + * @param string $query The SQL query to run + * + * @return int|false The number of affected rows or false on failure + * @access private */ function delete_data($query) { - global $CONFIG, $DB_QUERY_CACHE; + + elgg_log("DB query $query", 'NOTICE'); $dblink = get_db_link('write'); - // Invalidate query cache - if ($DB_QUERY_CACHE) { - $DB_QUERY_CACHE->clear(); - elgg_log("Query cache invalidated"); - } + _elgg_invalidate_query_cache(); if (execute_query("$query", $dblink)) { return mysql_affected_rows($dblink); } - return false; + return FALSE; } +/** + * Invalidate the query cache + * + * @access private + */ +function _elgg_invalidate_query_cache() { + global $DB_QUERY_CACHE; + if ($DB_QUERY_CACHE instanceof ElggLRUCache) { + $DB_QUERY_CACHE->clear(); + elgg_log("Query cache invalidated", 'NOTICE'); + } elseif ($DB_QUERY_CACHE) { + // In case someone sets the cache to an array and primes it with data + $DB_QUERY_CACHE = array(); + elgg_log("Query cache invalidated", 'NOTICE'); + } +} /** - * Get the tables currently installed in the Elgg database + * Return tables matching the database prefix {@link $CONFIG->dbprefix}% in the currently + * selected database. * - * @return array List of tables + * @return array|false List of tables or false on failure + * @static array $tables Tables found matching the database prefix + * @access private */ function get_db_tables() { global $CONFIG; @@ -435,29 +559,36 @@ function get_db_tables() { $result = get_data("show tables like '" . $CONFIG->dbprefix . "%'"); } catch (DatabaseException $d) { // Likely we can't handle an exception here, so just return false. - return false; + return FALSE; } $tables = array(); if (is_array($result) && !empty($result)) { - foreach($result as $row) { + foreach ($result as $row) { $row = (array) $row; - if (is_array($row) && !empty($row)) - foreach($row as $element) { + if (is_array($row) && !empty($row)) { + foreach ($row as $element) { $tables[] = $element; } + } } } else { - return false; + return FALSE; } return $tables; } /** - * Run an optimize query on a mysql tables. Useful for executing after major data changes. + * Optimise a table. + * + * Executes an OPTIMIZE TABLE query on $table. Useful after large DB changes. * + * @param string $table The name of the table to optimise + * + * @return bool + * @access private */ function optimize_table($table) { $table = sanitise_string($table); @@ -467,18 +598,35 @@ function optimize_table($table) { /** * Get the last database error for a particular database link * - * @param database link $dblink + * @param resource $dblink The DB link + * * @return string Database error message + * @access private */ function get_db_error($dblink) { return mysql_error($dblink); } /** - * Runs a full database script from disk + * Runs a full database script from disk. + * + * The file specified should be a standard SQL file as created by + * mysqldump or similar. Statements must be terminated with ; + * and a newline character (\n or \r\n) with only one statement per line. + * + * The special string 'prefix_' is replaced with the database prefix + * as defined in {@link $CONFIG->dbprefix}. + * + * @warning Errors do not halt execution of the script. If a line + * generates an error, the error message is saved and the + * next line is executed. After the file is run, any errors + * are displayed as a {@link DatabaseException} * - * @uses $CONFIG * @param string $scriptlocation The full path to the script + * + * @return void + * @throws DatabaseException + * @access private */ function run_sql_script($scriptlocation) { if ($script = file_get_contents($scriptlocation)) { @@ -486,14 +634,18 @@ function run_sql_script($scriptlocation) { $errors = array(); + // Remove MySQL -- style comments $script = preg_replace('/\-\-.*\n/', '', $script); - $sql_statements = preg_split('/;[\n\r]+/', $script); - foreach($sql_statements as $statement) { + + // Statements must end with ; and a newline + $sql_statements = preg_split('/;[\n\r]+/', $script); + + foreach ($sql_statements as $statement) { $statement = trim($statement); - $statement = str_replace("prefix_",$CONFIG->dbprefix,$statement); + $statement = str_replace("prefix_", $CONFIG->dbprefix, $statement); if (!empty($statement)) { try { - $result = update_data($statement); + update_data($statement); } catch (DatabaseException $e) { $errors[] = $e->getMessage(); } @@ -501,99 +653,38 @@ function run_sql_script($scriptlocation) { } if (!empty($errors)) { $errortxt = ""; - foreach($errors as $error) + foreach ($errors as $error) { $errortxt .= " {$error};"; - throw new DatabaseException(elgg_echo('DatabaseException:DBSetupIssues') . $errortxt); - } - } else { - throw new DatabaseException(sprintf(elgg_echo('DatabaseException:ScriptNotFound'), $scriptlocation)); - } -} - -/** - * Upgrade the database schema in an ordered sequence. - * - * Makes use of schema upgrade files - * - * This is a about as core as it comes, so don't start running this from your plugins! - * - * @param int $version The version you are upgrading from (usually given in the Elgg version format of YYYYMMDDXX - see version.php for example) - * @param string $fromdir Optional directory to load upgrades from (default: engine/schema/upgrades/) - * @param bool $quiet If true, will suppress all error messages. Don't use this. - * @return bool - */ -function db_upgrade($version, $fromdir = "", $quiet = FALSE) { - global $CONFIG; - - // Elgg and its database must be installed to upgrade it! - if (!is_db_installed() || !is_installed()) { - return false; - } - - $version = (int) $version; - - if (!$fromdir) { - $fromdir = $CONFIG->path . 'engine/schema/upgrades/'; - } - - if ($handle = opendir($fromdir)) { - $sqlupgrades = array(); - - while ($sqlfile = readdir($handle)) { - if (!is_dir($fromdir . $sqlfile)) { - if (preg_match('/^([0-9]{10})\.(sql)$/', $sqlfile, $matches)) { - $sql_version = (int) $matches[1]; - if ($sql_version > $version) { - $sqlupgrades[] = $sqlfile; - } - } } - } - - asort($sqlupgrades); - if (sizeof($sqlupgrades) > 0) { - foreach($sqlupgrades as $sqlfile) { - - // hide all errors. - if ($quiet) { - try { - run_sql_script($fromdir . $sqlfile); - } catch (DatabaseException $e) { - error_log($e->getmessage()); - } - } else { - run_sql_script($fromdir . $sqlfile); - } - } + $msg = elgg_echo('DatabaseException:DBSetupIssues') . $errortxt; + throw new DatabaseException($msg); } + } else { + $msg = elgg_echo('DatabaseException:ScriptNotFound', array($scriptlocation)); + throw new DatabaseException($msg); } - - return TRUE; } /** - * This function, called by validate_platform(), will check whether the installed version of - * MySQL meets the minimum required. + * Format a query string for logging * - * TODO: If multiple dbs are supported check which db is supported and use the appropriate code to validate - * the appropriate version. - * - * @return bool + * @param string $query Query string + * @return string + * @access private */ -function db_check_version() { - $version = mysql_get_server_info(); - $points = explode('.', $version); - - if ($points[0] < 5) { - return false; - } - - return true; +function elgg_format_query($query) { + // remove newlines and extra spaces so logs are easier to read + return preg_replace('/\s\s+/', ' ', $query); } /** * Sanitise a string for database use, but with the option of escaping extra characters. + * + * @param string $string The string to sanitise + * @param string $extra_escapeable Extra characters to escape with '\\' + * + * @return string The escaped string */ function sanitise_string_special($string, $extra_escapeable = '') { $string = sanitise_string($string); @@ -606,9 +697,10 @@ function sanitise_string_special($string, $extra_escapeable = '') { } /** - * Sanitise a string for database use + * Sanitise a string for database use. * * @param string $string The string to sanitise + * * @return string Sanitised string */ function sanitise_string($string) { @@ -621,34 +713,52 @@ function sanitise_string($string) { * Wrapper function for alternate English spelling * * @param string $string The string to sanitise + * * @return string Sanitised string - * @uses sanitise_string */ function sanitize_string($string) { return sanitise_string($string); } /** - * Sanitises an integer for database use + * Sanitises an integer for database use. * - * @param int $int - * @return int Sanitised integer + * @param int $int Value to be sanitized + * @param bool $signed Whether negative values should be allowed (true) + * @return int */ -function sanitise_int($int) { +function sanitise_int($int, $signed = true) { + $int = (int) $int; + + if ($signed === false) { + if ($int < 0) { + $int = 0; + } + } + return (int) $int; } /** - * Wrapper function for alternate English spelling + * Sanitizes an integer for database use. + * Wrapper function for alternate English spelling (@see sanitise_int) * - * @param int $int - * @return int Sanitised integer - * @uses sanitise_string + * @param int $int Value to be sanitized + * @param bool $signed Whether negative values should be allowed (true) + * @return int */ -function sanitize_int($int) { - return (int) $int; +function sanitize_int($int, $signed = true) { + return sanitise_int($int, $signed); } -// Stuff for initialisation +/** + * Registers shutdown functions for database profiling and delayed queries. + * + * @access private + */ +function init_db() { + register_shutdown_function('db_delayedexecution_shutdown_hook'); + register_shutdown_function('db_profiling_shutdown_hook'); +} -register_elgg_event_handler('boot','system','init_db',0);
\ No newline at end of file +elgg_register_event_handler('init', 'system', 'init_db'); |
