DbExtra-sqlite.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. if ($tableName != $db_prefix . 'messages' || $tableName != $db_prefix . 'topics')
  182. $detected_id = 0;
  183. // This will be handy...
  184. $crlf = "\r\n";
  185. // This is done this way because retrieve data only with LIMIT will become slower after each query
  186. // and for long tables (e.g. {db_prefix}messages) it could be a pain...
  187. // Instead using WHERE speeds up thing *a lot* (especially after the first 50'000 records)
  188. $result = $smcFunc['db_query']('', '
  189. SELECT *
  190. FROM ' . $tableName .
  191. (!empty($last_id) && !empty($detected_id) ? '
  192. WHERE ' . $detected_id . ' > ' . $last_id : '') . '
  193. LIMIT ' . (empty($last_id) ? $start . ', ' : '') . $limit,
  194. array(
  195. 'security_override' => true,
  196. )
  197. );
  198. // The number of rows, just for record keeping and breaking INSERTs up.
  199. $num_rows = $smcFunc['db_num_rows']($result);
  200. if ($num_rows == 0)
  201. return '';
  202. if ($new_table)
  203. {
  204. $fields = array_keys($smcFunc['db_fetch_assoc']($result));
  205. // SQLite fetches an array so we need to filter out the numberic index for the columns.
  206. foreach ($fields as $key => $name)
  207. if (is_numeric($name))
  208. unset($fields[$key]);
  209. $smcFunc['db_data_seek']($result, 0);
  210. }
  211. // Start it off with the basic INSERT INTO.
  212. $data = 'BEGIN TRANSACTION;' . $crlf;
  213. $insert_msg = $crlf . 'INSERT INTO ' . $tableName . $crlf . "\t" . '(' . implode(', ', $fields) . ')' . $crlf . 'VALUES ' . $crlf . "\t";
  214. // Loop through each row.
  215. while ($row = $smcFunc['db_fetch_assoc']($result))
  216. {
  217. // Get the fields in this row...
  218. $field_list = array();
  219. foreach ($row as $key => $item)
  220. {
  221. // Try to figure out the type of each field. (NULL, number, or 'string'.)
  222. if (!isset($item))
  223. $field_list[] = 'NULL';
  224. elseif (is_numeric($item) && (int) $item == $item)
  225. $field_list[] = $item;
  226. else
  227. $field_list[] = '\'' . $smcFunc['db_escape_string']($item) . '\'';
  228. }
  229. if (!empty($detected_id) && isset($row[$detected_id]))
  230. $last_id = $row[$detected_id];
  231. // 'Insert' the data.
  232. $data .= $insert_msg . '(' . implode(', ', $field_list) . ');' . $crlf;
  233. }
  234. $smcFunc['db_free_result']($result);
  235. $data .= $crlf;
  236. $start += $limit;
  237. return $data;
  238. }
  239. /**
  240. * Dumps the schema (CREATE) for a table.
  241. * @todo why is this needed for?
  242. * @param string $tableName - the table
  243. * @return string - the CREATE statement as string
  244. */
  245. function smf_db_table_sql($tableName)
  246. {
  247. global $smcFunc, $db_prefix, $detected_id;
  248. $tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
  249. $detected_id = '';
  250. // This will be needed...
  251. $crlf = "\r\n";
  252. // Start the create table...
  253. $schema_create = '';
  254. $index_create = '';
  255. // Let's get the create statement directly from SQLite.
  256. $result = $smcFunc['db_query']('', '
  257. SELECT sql
  258. FROM sqlite_master
  259. WHERE type = {string:type}
  260. AND name = {string:table_name}',
  261. array(
  262. 'type' => 'table',
  263. 'table_name' => $tableName,
  264. )
  265. );
  266. list ($schema_create) = $smcFunc['db_fetch_row']($result);
  267. $smcFunc['db_free_result']($result);
  268. // Now the indexes.
  269. $result = $smcFunc['db_query']('', '
  270. SELECT sql
  271. FROM sqlite_master
  272. WHERE type = {string:type}
  273. AND tbl_name = {string:table_name}',
  274. array(
  275. 'type' => 'index',
  276. 'table_name' => $tableName,
  277. )
  278. );
  279. $indexes = array();
  280. while ($row = $smcFunc['db_fetch_assoc']($result))
  281. if (trim($row['sql']) != '')
  282. $indexes[] = $row['sql'];
  283. $smcFunc['db_free_result']($result);
  284. $index_create .= implode(';' . $crlf, $indexes);
  285. $schema_create = empty($indexes) ? rtrim($schema_create) : $schema_create . ';' . $crlf . $crlf;
  286. return $schema_create . $index_create;
  287. }
  288. /**
  289. * Get the version number.
  290. * @return string - the version
  291. */
  292. function smf_db_get_version()
  293. {
  294. return sqlite_libversion();
  295. }
  296. /**
  297. * Simply return the database - and die!
  298. * Used by DumpDatabase.php.
  299. */
  300. function smf_db_get_backup()
  301. {
  302. global $db_name;
  303. $db_file = substr($db_name, -3) === '.db' ? $db_name : $db_name . '.db';
  304. // Add more info if zipped...
  305. $ext = '';
  306. if (isset($_REQUEST['compress']) && function_exists('gzencode'))
  307. $ext = '.gz';
  308. // Do the remaining headers.
  309. header('Content-Disposition: attachment; filename="' . $db_file . $ext . '"');
  310. header('Cache-Control: private');
  311. header('Connection: close');
  312. // Literally dump the contents. Try reading the file first.
  313. if (@readfile($db_file) == null)
  314. echo file_get_contents($db_file);
  315. obExit(false);
  316. }
  317. ?>