[ Index ] |
|
Code source de Drupal 5.3 |
1 <?php 2 // $Id: database.mysql.inc,v 1.66.2.1 2007/01/22 02:20:50 unconed Exp $ 3 4 /** 5 * @file 6 * Database interface code for MySQL database servers. 7 */ 8 9 /** 10 * @ingroup database 11 * @{ 12 */ 13 14 15 /** 16 * Report database status. 17 */ 18 function db_status_report($phase) { 19 $t = get_t(); 20 21 $version = db_version(); 22 23 $form['mysql'] = array( 24 'title' => $t('MySQL database'), 25 'value' => ($phase == 'runtime') ? l($version, 'admin/logs/status/sql') : $version, 26 ); 27 28 if (version_compare($version, DRUPAL_MINIMUM_MYSQL) < 0) { 29 $form['mysql']['severity'] = REQUIREMENT_ERROR; 30 $form['mysql']['description'] = $t('Your MySQL Server is too old. Drupal requires at least MySQL %version.', array('%version' => DRUPAL_MINIMUM_MYSQL)); 31 } 32 33 return $form; 34 } 35 36 /** 37 * Returns the version of the database server currently in use. 38 * 39 * @return Database server version 40 */ 41 function db_version() { 42 list($version) = explode('-', mysql_get_server_info()); 43 return $version; 44 } 45 46 /** 47 * Initialize a database connection. 48 * 49 * Note that you can change the mysql_connect() call to mysql_pconnect() if you 50 * want to use persistent connections. This is not recommended on shared hosts, 51 * and might require additional database/webserver tuning. It can increase 52 * performance, however, when the overhead to connect to your database is high 53 * (e.g. your database and web server live on different machines). 54 */ 55 function db_connect($url) { 56 $url = parse_url($url); 57 58 // Check if MySQL support is present in PHP 59 if (!function_exists('mysql_connect')) { 60 // Redirect to installer if using default DB credentials 61 if ($url['user'] == 'username' && $url['pass'] == 'password') { 62 include_once 'includes/install.inc'; 63 install_goto('install.php'); 64 } 65 drupal_maintenance_theme(); 66 drupal_set_title('PHP MySQL support not enabled'); 67 print theme('maintenance_page', '<p>We were unable to use the MySQL database because the MySQL extension for PHP is not installed. Check your <code>PHP.ini</code> to see how you can enable it.</p> 68 <p>For more help, see the <a href="http://drupal.org/node/258">Installation and upgrading handbook</a>. If you are unsure what these terms mean you should probably contact your hosting provider.</p>'); 69 exit; 70 } 71 72 // Decode url-encoded information in the db connection string 73 $url['user'] = urldecode($url['user']); 74 // Test if database url has a password. 75 if(isset($url['pass'])) { 76 $url['pass'] = urldecode($url['pass']); 77 } 78 else { 79 $url['pass'] = ''; 80 } 81 $url['host'] = urldecode($url['host']); 82 $url['path'] = urldecode($url['path']); 83 84 // Allow for non-standard MySQL port. 85 if (isset($url['port'])) { 86 $url['host'] = $url['host'] .':'. $url['port']; 87 } 88 89 // - TRUE makes mysql_connect() always open a new link, even if 90 // mysql_connect() was called before with the same parameters. 91 // This is important if you are using two databases on the same 92 // server. 93 // - 2 means CLIENT_FOUND_ROWS: return the number of found 94 // (matched) rows, not the number of affected rows. 95 $connection = @mysql_connect($url['host'], $url['user'], $url['pass'], TRUE, 2); 96 if (!$connection) { 97 // Redirect to installer if using default DB credentials 98 if ($url['user'] == 'username' && $url['pass'] == 'password') { 99 include_once 'includes/install.inc'; 100 install_goto('install.php'); 101 } 102 103 // Show error screen otherwise 104 drupal_maintenance_theme(); 105 drupal_set_header('HTTP/1.1 503 Service Unavailable'); 106 drupal_set_title('Unable to connect to database server'); 107 print theme('maintenance_page', '<p>If you still have to install Drupal, proceed to the <a href="'. base_path() .'install.php">installation page</a>.</p> 108 <p>If you have already finished installed Drupal, this either means that the username and password information in your <code>settings.php</code> file is incorrect or that we can\'t connect to the MySQL database server. This could mean your hosting provider\'s database server is down.</p> 109 <p>The MySQL error was: '. theme('placeholder', mysql_error()) .'.</p> 110 <p>Currently, the username is '. theme('placeholder', $url['user']) .' and the database server is '. theme('placeholder', $url['host']) .'.</p> 111 <ul> 112 <li>Are you sure you have the correct username and password?</li> 113 <li>Are you sure that you have typed the correct hostname?</li> 114 <li>Are you sure that the database server is running?</li> 115 </ul> 116 <p>For more help, see the <a href="http://drupal.org/node/258">Installation and upgrading handbook</a>. If you are unsure what these terms mean you should probably contact your hosting provider.</p>'); 117 exit; 118 } 119 120 if (!mysql_select_db(substr($url['path'], 1))) { 121 drupal_maintenance_theme(); 122 drupal_set_title('Unable to select database'); 123 print theme('maintenance_page', '<p>We were able to connect to the MySQL database server (which means your username and password are okay) but not able to select the database.</p> 124 <p>The MySQL error was: '. theme('placeholder', mysql_error($connection)) .'.</p> 125 <p>Currently, the database is '. theme('placeholder', substr($url['path'], 1)) .'. The username is '. theme('placeholder', $url['user']) .' and the database server is '. theme('placeholder', $url['host']) .'.</p> 126 <ul> 127 <li>Are you sure you have the correct database name?</li> 128 <li>Are you sure the database exists?</li> 129 <li>Are you sure the username has permission to access the database?</li> 130 </ul> 131 <p>For more help, see the <a href="http://drupal.org/node/258">Installation and upgrading handbook</a>. If you are unsure what these terms mean you should probably contact your hosting provider.</p>'); 132 exit; 133 } 134 135 /* On MySQL 4.1 and later, force UTF-8 */ 136 if (version_compare(mysql_get_server_info(), '4.1.0', '>=')) { 137 mysql_query('SET NAMES "utf8"', $connection); 138 } 139 return $connection; 140 } 141 142 /** 143 * Helper function for db_query(). 144 */ 145 function _db_query($query, $debug = 0) { 146 global $active_db, $queries; 147 148 if (variable_get('dev_query', 0)) { 149 list($usec, $sec) = explode(' ', microtime()); 150 $timer = (float)$usec + (float)$sec; 151 } 152 153 $result = mysql_query($query, $active_db); 154 155 if (variable_get('dev_query', 0)) { 156 $bt = debug_backtrace(); 157 $query = $bt[2]['function'] . "\n" . $query; 158 list($usec, $sec) = explode(' ', microtime()); 159 $stop = (float)$usec + (float)$sec; 160 $diff = $stop - $timer; 161 $queries[] = array($query, $diff); 162 } 163 164 if ($debug) { 165 print '<p>query: '. $query .'<br />error:'. mysql_error($active_db) .'</p>'; 166 } 167 168 if (!mysql_errno($active_db)) { 169 return $result; 170 } 171 else { 172 trigger_error(check_plain(mysql_error($active_db) ."\nquery: ". $query), E_USER_WARNING); 173 return FALSE; 174 } 175 } 176 177 /** 178 * Fetch one result row from the previous query as an object. 179 * 180 * @param $result 181 * A database query result resource, as returned from db_query(). 182 * @return 183 * An object representing the next row of the result. The attributes of this 184 * object are the table fields selected by the query. 185 */ 186 function db_fetch_object($result) { 187 if ($result) { 188 return mysql_fetch_object($result); 189 } 190 } 191 192 /** 193 * Fetch one result row from the previous query as an array. 194 * 195 * @param $result 196 * A database query result resource, as returned from db_query(). 197 * @return 198 * An associative array representing the next row of the result. The keys of 199 * this object are the names of the table fields selected by the query, and 200 * the values are the field values for this result row. 201 */ 202 function db_fetch_array($result) { 203 if ($result) { 204 return mysql_fetch_array($result, MYSQL_ASSOC); 205 } 206 } 207 208 /** 209 * Determine how many result rows were found by the preceding query. 210 * 211 * @param $result 212 * A database query result resource, as returned from db_query(). 213 * @return 214 * The number of result rows. 215 */ 216 function db_num_rows($result) { 217 if ($result) { 218 return mysql_num_rows($result); 219 } 220 } 221 222 /** 223 * Return an individual result field from the previous query. 224 * 225 * Only use this function if exactly one field is being selected; otherwise, 226 * use db_fetch_object() or db_fetch_array(). 227 * 228 * @param $result 229 * A database query result resource, as returned from db_query(). 230 * @param $row 231 * The index of the row whose result is needed. 232 * @return 233 * The resulting field or FALSE. 234 */ 235 function db_result($result, $row = 0) { 236 if ($result && mysql_num_rows($result) > $row) { 237 return mysql_result($result, $row); 238 } 239 return FALSE; 240 } 241 242 /** 243 * Determine whether the previous query caused an error. 244 */ 245 function db_error() { 246 global $active_db; 247 return mysql_errno($active_db); 248 } 249 250 /** 251 * Return a new unique ID in the given sequence. 252 * 253 * For compatibility reasons, Drupal does not use auto-numbered fields in its 254 * database tables. Instead, this function is used to return a new unique ID 255 * of the type requested. If necessary, a new sequence with the given name 256 * will be created. 257 * 258 * Note that the table name should be in curly brackets to preserve compatibility 259 * with table prefixes. For example, db_next_id('{node}_nid'); 260 */ 261 function db_next_id($name) { 262 $name = db_prefix_tables($name); 263 db_query('LOCK TABLES {sequences} WRITE'); 264 $id = db_result(db_query("SELECT id FROM {sequences} WHERE name = '%s'", $name)) + 1; 265 db_query("REPLACE INTO {sequences} VALUES ('%s', %d)", $name, $id); 266 db_query('UNLOCK TABLES'); 267 268 return $id; 269 } 270 271 /** 272 * Determine the number of rows changed by the preceding query. 273 */ 274 function db_affected_rows() { 275 global $active_db; 276 return mysql_affected_rows($active_db); 277 } 278 279 /** 280 * Runs a limited-range query in the active database. 281 * 282 * Use this as a substitute for db_query() when a subset of the query is to be 283 * returned. 284 * User-supplied arguments to the query should be passed in as separate parameters 285 * so that they can be properly escaped to avoid SQL injection attacks. 286 * 287 * @param $query 288 * A string containing an SQL query. 289 * @param ... 290 * A variable number of arguments which are substituted into the query 291 * using printf() syntax. The query arguments can be enclosed in one 292 * array instead. 293 * Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose 294 * in '') and %%. 295 * 296 * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, 297 * and TRUE values to decimal 1. 298 * 299 * @param $from 300 * The first result row to return. 301 * @param $count 302 * The maximum number of result rows to return. 303 * @return 304 * A database query result resource, or FALSE if the query was not executed 305 * correctly. 306 */ 307 function db_query_range($query) { 308 $args = func_get_args(); 309 $count = array_pop($args); 310 $from = array_pop($args); 311 array_shift($args); 312 313 $query = db_prefix_tables($query); 314 if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax 315 $args = $args[0]; 316 } 317 _db_query_callback($args, TRUE); 318 $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query); 319 $query .= ' LIMIT '. (int)$from .', '. (int)$count; 320 return _db_query($query); 321 } 322 323 /** 324 * Runs a SELECT query and stores its results in a temporary table. 325 * 326 * Use this as a substitute for db_query() when the results need to stored 327 * in a temporary table. Temporary tables exist for the duration of the page 328 * request. 329 * User-supplied arguments to the query should be passed in as separate parameters 330 * so that they can be properly escaped to avoid SQL injection attacks. 331 * 332 * Note that if you need to know how many results were returned, you should do 333 * a SELECT COUNT(*) on the temporary table afterwards. db_num_rows() and 334 * db_affected_rows() do not give consistent result across different database 335 * types in this case. 336 * 337 * @param $query 338 * A string containing a normal SELECT SQL query. 339 * @param ... 340 * A variable number of arguments which are substituted into the query 341 * using printf() syntax. The query arguments can be enclosed in one 342 * array instead. 343 * Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose 344 * in '') and %%. 345 * 346 * NOTE: using this syntax will cast NULL and FALSE values to decimal 0, 347 * and TRUE values to decimal 1. 348 * 349 * @param $table 350 * The name of the temporary table to select into. This name will not be 351 * prefixed as there is no risk of collision. 352 * @return 353 * A database query result resource, or FALSE if the query was not executed 354 * correctly. 355 */ 356 function db_query_temporary($query) { 357 $args = func_get_args(); 358 $tablename = array_pop($args); 359 array_shift($args); 360 361 $query = preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE '. $tablename .' SELECT', db_prefix_tables($query)); 362 if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax 363 $args = $args[0]; 364 } 365 _db_query_callback($args, TRUE); 366 $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query); 367 return _db_query($query); 368 } 369 370 /** 371 * Returns a properly formatted Binary Large OBject value. 372 * 373 * @param $data 374 * Data to encode. 375 * @return 376 * Encoded data. 377 */ 378 function db_encode_blob($data) { 379 global $active_db; 380 return "'" . mysql_real_escape_string($data, $active_db) . "'"; 381 } 382 383 /** 384 * Returns text from a Binary Large Object value. 385 * 386 * @param $data 387 * Data to decode. 388 * @return 389 * Decoded data. 390 */ 391 function db_decode_blob($data) { 392 return $data; 393 } 394 395 /** 396 * Prepare user input for use in a database query, preventing SQL injection attacks. 397 */ 398 function db_escape_string($text) { 399 global $active_db; 400 return mysql_real_escape_string($text, $active_db); 401 } 402 403 /** 404 * Lock a table. 405 */ 406 function db_lock_table($table) { 407 db_query('LOCK TABLES {'. db_escape_table($table) .'} WRITE'); 408 } 409 410 /** 411 * Unlock all locked tables. 412 */ 413 function db_unlock_tables() { 414 db_query('UNLOCK TABLES'); 415 } 416 417 /** 418 * Check if a table exists. 419 */ 420 function db_table_exists($table) { 421 return db_num_rows(db_query("SHOW TABLES LIKE '{" . db_escape_table($table) . "}'")); 422 } 423 424 /** 425 * Wraps the given table.field entry with a DISTINCT(). The wrapper is added to 426 * the SELECT list entry of the given query and the resulting query is returned. 427 * This function only applies the wrapper if a DISTINCT doesn't already exist in 428 * the query. 429 * 430 * @param $table Table containing the field to set as DISTINCT 431 * @param $field Field to set as DISTINCT 432 * @param $query Query to apply the wrapper to 433 * @return SQL query with the DISTINCT wrapper surrounding the given table.field. 434 */ 435 function db_distinct_field($table, $field, $query) { 436 $field_to_select = 'DISTINCT('. $table .'.'. $field .')'; 437 // (?<!text) is a negative look-behind (no need to rewrite queries that already use DISTINCT). 438 return preg_replace('/(SELECT.*)(?:'. $table .'\.|\s)(?<!DISTINCT\()(?<!DISTINCT\('. $table .'\.)'. $field .'(.*FROM )/AUsi', '\1 '. $field_to_select .'\2', $query); 439 } 440 441 /** 442 * @} End of "ingroup database". 443 */ 444 445
titre
Description
Corps
titre
Description
Corps
titre
Description
Corps
titre
Corps
Généré le : Fri Nov 30 16:20:15 2007 | par Balluche grâce à PHPXref 0.7 |
![]() |