DbExtra-sqlite3.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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 2013 Simple Machines and individual contributors
  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('No direct access...');
  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. *
  138. * @param mixed $db string holding the table name, or false, default false
  139. * @param mixed $filter string to filter by, or false, default false
  140. * @return array an array of table names. (strings)
  141. */
  142. function smf_db_list_tables($db = false, $filter = false)
  143. {
  144. global $smcFunc;
  145. $filter = $filter == false ? '' : ' AND name LIKE \'' . str_replace("\_", "_", $filter) . '\'';
  146. $request = $smcFunc['db_query']('', '
  147. SELECT name
  148. FROM sqlite_master
  149. WHERE type = {string:type}
  150. {raw:filter}
  151. ORDER BY name',
  152. array(
  153. 'type' => 'table',
  154. 'filter' => $filter,
  155. )
  156. );
  157. $tables = array();
  158. while ($row = $smcFunc['db_fetch_row']($request))
  159. $tables[] = $row[0];
  160. $smcFunc['db_free_result']($request);
  161. return $tables;
  162. }
  163. /**
  164. * Gets all the necessary INSERTs for the table named table_name.
  165. * It goes in 250 row segments.
  166. *
  167. * @param string $tableName - the table to create the inserts for.
  168. * @param bool new_table
  169. * @return string the query to insert the data back in, or an empty string if the table was empty.
  170. */
  171. function smf_db_insert_sql($tableName, $new_table = false)
  172. {
  173. global $smcFunc, $db_prefix;
  174. static $start = 0, $num_rows, $fields, $limit;
  175. if ($new_table)
  176. {
  177. $limit = strstr($tableName, 'log_') !== false ? 500 : 250;
  178. $start = 0;
  179. }
  180. $data = '';
  181. $tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
  182. // This will be handy...
  183. $crlf = "\r\n";
  184. $result = $smcFunc['db_query']('', '
  185. SELECT *
  186. FROM ' . $tableName . '
  187. LIMIT ' . $start . ', ' . $limit,
  188. array(
  189. 'security_override' => true,
  190. )
  191. );
  192. // The number of rows, just for record keeping and breaking INSERTs up.
  193. $num_rows = $smcFunc['db_num_rows']($result);
  194. if ($num_rows == 0)
  195. return '';
  196. if ($new_table)
  197. {
  198. $fields = array_keys($smcFunc['db_fetch_assoc']($result));
  199. // SQLite fetches an array so we need to filter out the numberic index for the columns.
  200. foreach ($fields as $key => $name)
  201. if (is_numeric($name))
  202. unset($fields[$key]);
  203. $smcFunc['db_data_seek']($result, 0);
  204. }
  205. // Start it off with the basic INSERT INTO.
  206. $data = 'BEGIN TRANSACTION;' . $crlf;
  207. $insert_msg = $crlf . 'INSERT INTO ' . $tableName . $crlf . "\t" . '(' . implode(', ', $fields) . ')' . $crlf . 'VALUES ' . $crlf . "\t";
  208. // Loop through each row.
  209. while ($row = $smcFunc['db_fetch_assoc']($result))
  210. {
  211. // Get the fields in this row...
  212. $field_list = array();
  213. foreach ($row as $key => $item)
  214. {
  215. // Try to figure out the type of each field. (NULL, number, or 'string'.)
  216. if (!isset($item))
  217. $field_list[] = 'NULL';
  218. elseif (is_numeric($item) && (int) $item == $item)
  219. $field_list[] = $item;
  220. else
  221. $field_list[] = '\'' . $smcFunc['db_escape_string']($item) . '\'';
  222. }
  223. // 'Insert' the data.
  224. $data .= $insert_msg . '(' . implode(', ', $field_list) . ');' . $crlf;
  225. }
  226. $smcFunc['db_free_result']($result);
  227. $data .= $crlf;
  228. $start += $limit;
  229. return $data;
  230. }
  231. /**
  232. * Dumps the schema (CREATE) for a table.
  233. * @todo why is this needed for?
  234. * @param string $tableName - the table
  235. * @return string - the CREATE statement as string
  236. */
  237. function smf_db_table_sql($tableName)
  238. {
  239. global $smcFunc, $db_prefix;
  240. $tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
  241. // This will be needed...
  242. $crlf = "\r\n";
  243. // Start the create table...
  244. $schema_create = '';
  245. $index_create = '';
  246. // Let's get the create statement directly from SQLite.
  247. $result = $smcFunc['db_query']('', '
  248. SELECT sql
  249. FROM sqlite_master
  250. WHERE type = {string:type}
  251. AND name = {string:table_name}',
  252. array(
  253. 'type' => 'table',
  254. 'table_name' => $tableName,
  255. )
  256. );
  257. list ($schema_create) = $smcFunc['db_fetch_row']($result);
  258. $smcFunc['db_free_result']($result);
  259. // Now the indexes.
  260. $result = $smcFunc['db_query']('', '
  261. SELECT sql
  262. FROM sqlite_master
  263. WHERE type = {string:type}
  264. AND tbl_name = {string:table_name}',
  265. array(
  266. 'type' => 'index',
  267. 'table_name' => $tableName,
  268. )
  269. );
  270. $indexes = array();
  271. while ($row = $smcFunc['db_fetch_assoc']($result))
  272. if (trim($row['sql']) != '')
  273. $indexes[] = $row['sql'];
  274. $smcFunc['db_free_result']($result);
  275. $index_create .= implode(';' . $crlf, $indexes);
  276. $schema_create = empty($indexes) ? rtrim($schema_create) : $schema_create . ';' . $crlf . $crlf;
  277. return $schema_create . $index_create;
  278. }
  279. /**
  280. * Get the version number.
  281. * @return string - the version
  282. */
  283. function smf_db_get_version()
  284. {
  285. $version = SQLite3::version();
  286. return $version['versionString'];
  287. }
  288. /**
  289. * Simply return the database - and die!
  290. * Used by DumpDatabase.php.
  291. */
  292. function smf_db_get_backup()
  293. {
  294. global $db_name;
  295. $db_file = substr($db_name, -3) === '.db' ? $db_name : $db_name . '.db';
  296. // Add more info if zipped...
  297. $ext = '';
  298. if (isset($_REQUEST['compress']) && function_exists('gzencode'))
  299. $ext = '.gz';
  300. // Do the remaining headers.
  301. header('Content-Disposition: attachment; filename="' . $db_file . $ext . '"');
  302. header('Cache-Control: private');
  303. header('Connection: close');
  304. // Literally dump the contents. Try reading the file first.
  305. if (@readfile($db_file) == null)
  306. echo file_get_contents($db_file);
  307. obExit(false);
  308. }
  309. ?>