DbExtra-sqlite.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. <?php
  2. /**
  3. * This file contains rarely used extended database functionality.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2011 Simple Machines
  10. * @license http://www.simplemachines.org/about/smf/license.php BSD
  11. *
  12. * @version 2.1 Alpha 1
  13. */
  14. if (!defined('SMF'))
  15. die('Hacking attempt...');
  16. /**
  17. * Add the functions implemented in this file to the $smcFunc array.
  18. */
  19. function db_extra_init()
  20. {
  21. global $smcFunc;
  22. if (!isset($smcFunc['db_backup_table']) || $smcFunc['db_backup_table'] != 'smf_db_backup_table')
  23. $smcFunc += array(
  24. 'db_backup_table' => 'smf_db_backup_table',
  25. 'db_optimize_table' => 'smf_db_optimize_table',
  26. 'db_insert_sql' => 'smf_db_insert_sql',
  27. 'db_table_sql' => 'smf_db_table_sql',
  28. 'db_list_tables' => 'smf_db_list_tables',
  29. 'db_get_backup' => 'smf_db_get_backup',
  30. 'db_get_version' => 'smf_db_get_version',
  31. );
  32. }
  33. /**
  34. * Backup $table to $backup_table.
  35. * @param string $table
  36. * @param string $backup_table
  37. * @return resource -the request handle to the table creation query
  38. */
  39. function smf_db_backup_table($table, $backup_table)
  40. {
  41. global $smcFunc, $db_prefix;
  42. $table = str_replace('{db_prefix}', $db_prefix, $table);
  43. $result = $smcFunc['db_query']('', '
  44. SELECT sql
  45. FROM sqlite_master
  46. WHERE type = {string:txttable}
  47. AND name = {string:table}',
  48. array(
  49. 'table' => $table,
  50. 'txttable' => 'table'
  51. )
  52. );
  53. list ($create) = $smcFunc['db_fetch_row']($result);
  54. $smcFunc['db_free_result']($result);
  55. $create = preg_split('/[\n\r]/', $create);
  56. $auto_inc = '';
  57. // Remove the first line and check to see if the second one contain useless info.
  58. unset($create[0]);
  59. if (trim($create[1]) == '(')
  60. unset($create[1]);
  61. if (trim($create[count($create)]) == ')')
  62. unset($create[count($create)]);
  63. foreach ($create as $k => $l)
  64. {
  65. // Get the name of the auto_increment column.
  66. if (strpos($l, 'primary') || strpos($l, 'PRIMARY'))
  67. $auto_inc = trim($l);
  68. // Skip everything but keys...
  69. if ((strpos($l, 'KEY') !== false && strpos($l, 'PRIMARY KEY') === false) || strpos($l, $table) !== false || strpos(trim($l), 'PRIMARY KEY') === 0)
  70. unset($create[$k]);
  71. }
  72. if (!empty($create))
  73. $create = '(
  74. ' . implode('
  75. ', $create) . ')';
  76. else
  77. $create = '';
  78. // Is there an extra junk at the end?
  79. if (substr($create, -2, 1) == ',')
  80. $create = substr($create, 0, -2) . ')';
  81. if (substr($create, -2) == '))')
  82. $create = substr($create, 0, -1);
  83. $smcFunc['db_query']('', '
  84. DROP TABLE {raw:backup_table}',
  85. array(
  86. 'backup_table' => $backup_table,
  87. 'db_error_skip' => true,
  88. )
  89. );
  90. $request = $smcFunc['db_quote']('
  91. CREATE TABLE {raw:backup_table} {raw:create}',
  92. array(
  93. 'backup_table' => $backup_table,
  94. 'create' => $create,
  95. ));
  96. $smcFunc['db_query']('', '
  97. CREATE TABLE {raw:backup_table} {raw:create}',
  98. array(
  99. 'backup_table' => $backup_table,
  100. 'create' => $create,
  101. ));
  102. $request = $smcFunc['db_query']('', '
  103. INSERT INTO {raw:backup_table}
  104. SELECT *
  105. FROM {raw:table}',
  106. array(
  107. 'backup_table' => $backup_table,
  108. 'table' => $table,
  109. ));
  110. return $request;
  111. }
  112. /**
  113. * This function optimizes a table.
  114. * @param string $table - the table to be optimized
  115. * @return how much it was gained
  116. */
  117. function smf_db_optimize_table($table)
  118. {
  119. global $smcFunc, $db_prefix;
  120. $table = str_replace('{db_prefix}', $db_prefix, $table);
  121. $request = $smcFunc['db_query']('', '
  122. VACUUM {raw:table}',
  123. array(
  124. 'table' => $table,
  125. )
  126. );
  127. if (!$request)
  128. return -1;
  129. $row = $smcFunc['db_fetch_assoc']($request);
  130. $smcFunc['db_free_result']($request);
  131. // The function returns nothing.
  132. return 0;
  133. }
  134. /**
  135. * This function lists all tables in the database.
  136. * The listing could be filtered according to $filter.
  137. * @param mixed $db, string holding the table name, or false, default false
  138. * @param mixed $filter, string to filter by, or false, default false
  139. * @return array, an array of table names. (strings)
  140. */
  141. function smf_db_list_tables($db = false, $filter = false)
  142. {
  143. global $smcFunc;
  144. $filter = $filter == false ? '' : ' AND name LIKE \'' . str_replace("\_", "_", $filter) . '\'';
  145. $request = $smcFunc['db_query']('', '
  146. SELECT name
  147. FROM sqlite_master
  148. WHERE type = {string:type}
  149. {raw:filter}
  150. ORDER BY name',
  151. array(
  152. 'type' => 'table',
  153. 'filter' => $filter,
  154. )
  155. );
  156. $tables = array();
  157. while ($row = $smcFunc['db_fetch_row']($request))
  158. $tables[] = $row[0];
  159. $smcFunc['db_free_result']($request);
  160. return $tables;
  161. }
  162. /**
  163. * Gets all the necessary INSERTs for the table named table_name.
  164. * It goes in 250 row segments.
  165. * @param string $tableName - the table to create the inserts for.
  166. * @return string, the query to insert the data back in, or an empty
  167. * string if the table was empty.
  168. */
  169. function smf_db_insert_sql($tableName, $new_table = false)
  170. {
  171. global $smcFunc, $db_prefix, $detected_id;
  172. static $start = 0, $num_rows, $fields, $limit, $last_id;
  173. if ($new_table)
  174. {
  175. $limit = strstr($tableName, 'log_') !== false ? 500 : 250;
  176. $start = 0;
  177. $last_id = 0;
  178. }
  179. $data = '';
  180. $tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
  181. // This will be handy...
  182. $crlf = "\r\n";
  183. // This is done this way because retrieve data only with LIMIT will become slower after each query
  184. // and for long tables (e.g. {db_prefix}messages) it could be a pain...
  185. // Instead using WHERE speeds up thing *a lot* (especially after the first 50'000 records)
  186. $result = $smcFunc['db_query']('', '
  187. SELECT *
  188. FROM ' . $tableName .
  189. (!empty($last_id) && !empty($detected_id) ? '
  190. WHERE ' . $detected_id . ' > ' . $last_id : '') . '
  191. LIMIT ' . (empty($last_id) ? $start . ', ' : '') . $limit,
  192. array(
  193. 'security_override' => true,
  194. )
  195. );
  196. // The number of rows, just for record keeping and breaking INSERTs up.
  197. $num_rows = $smcFunc['db_num_rows']($result);
  198. if ($num_rows == 0)
  199. return '';
  200. if ($new_table)
  201. {
  202. $fields = array_keys($smcFunc['db_fetch_assoc']($result));
  203. // SQLite fetches an array so we need to filter out the numberic index for the columns.
  204. foreach ($fields as $key => $name)
  205. if (is_numeric($name))
  206. unset($fields[$key]);
  207. $smcFunc['db_data_seek']($result, 0);
  208. }
  209. // Start it off with the basic INSERT INTO.
  210. $data = 'BEGIN TRANSACTION;' . $crlf;
  211. $insert_msg = $crlf . 'INSERT INTO ' . $tableName . $crlf . "\t" . '(' . implode(', ', $fields) . ')' . $crlf . 'VALUES ' . $crlf . "\t";
  212. // Loop through each row.
  213. while ($row = $smcFunc['db_fetch_assoc']($result))
  214. {
  215. // Get the fields in this row...
  216. $field_list = array();
  217. foreach ($row as $key => $item)
  218. {
  219. // Try to figure out the type of each field. (NULL, number, or 'string'.)
  220. if (!isset($item))
  221. $field_list[] = 'NULL';
  222. elseif (is_numeric($item) && (int) $item == $item)
  223. $field_list[] = $item;
  224. else
  225. $field_list[] = '\'' . $smcFunc['db_escape_string']($item) . '\'';
  226. }
  227. if (!empty($detected_id) && isset($row[$detected_id]))
  228. $last_id = $row[$detected_id];
  229. // 'Insert' the data.
  230. $data .= $insert_msg . '(' . implode(', ', $field_list) . ');' . $crlf;
  231. }
  232. $smcFunc['db_free_result']($result);
  233. $data .= $crlf;
  234. $start += $limit;
  235. return $data;
  236. }
  237. /**
  238. * Dumps the schema (CREATE) for a table.
  239. * @todo why is this needed for?
  240. * @param string $tableName - the table
  241. * @return string - the CREATE statement as string
  242. */
  243. function smf_db_table_sql($tableName)
  244. {
  245. global $smcFunc, $db_prefix, $detected_id;
  246. $tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
  247. $detected_id = '';
  248. // This will be needed...
  249. $crlf = "\r\n";
  250. // Start the create table...
  251. $schema_create = '';
  252. $index_create = '';
  253. // Let's get the create statement directly from SQLite.
  254. $result = $smcFunc['db_query']('', '
  255. SELECT sql
  256. FROM sqlite_master
  257. WHERE type = {string:type}
  258. AND name = {string:table_name}',
  259. array(
  260. 'type' => 'table',
  261. 'table_name' => $tableName,
  262. )
  263. );
  264. list ($schema_create) = $smcFunc['db_fetch_row']($result);
  265. $smcFunc['db_free_result']($result);
  266. // Now the indexes.
  267. $result = $smcFunc['db_query']('', '
  268. SELECT sql
  269. FROM sqlite_master
  270. WHERE type = {string:type}
  271. AND tbl_name = {string:table_name}',
  272. array(
  273. 'type' => 'index',
  274. 'table_name' => $tableName,
  275. )
  276. );
  277. $indexes = array();
  278. while ($row = $smcFunc['db_fetch_assoc']($result))
  279. if (trim($row['sql']) != '')
  280. $indexes[] = $row['sql'];
  281. $smcFunc['db_free_result']($result);
  282. $index_create .= implode(';' . $crlf, $indexes);
  283. $schema_create = empty($indexes) ? rtrim($schema_create) : $schema_create . ';' . $crlf . $crlf;
  284. return $schema_create . $index_create;
  285. }
  286. /**
  287. * Get the version number.
  288. * @return string - the version
  289. */
  290. function smf_db_get_version()
  291. {
  292. return sqlite_libversion();
  293. }
  294. /**
  295. * Simply return the database - and die!
  296. * Used by DumpDatabase.php.
  297. */
  298. function smf_db_get_backup()
  299. {
  300. global $db_name;
  301. $db_file = substr($db_name, -3) === '.db' ? $db_name : $db_name . '.db';
  302. // Add more info if zipped...
  303. $ext = '';
  304. if (isset($_REQUEST['compress']) && function_exists('gzencode'))
  305. $ext = '.gz';
  306. // Do the remaining headers.
  307. header('Content-Disposition: attachment; filename="' . $db_file . $ext . '"');
  308. header('Cache-Control: private');
  309. header('Connection: close');
  310. // Literally dump the contents. Try reading the file first.
  311. if (@readfile($db_file) == null)
  312. echo file_get_contents($db_file);
  313. obExit(false);
  314. }
  315. ?>