DbExtra-sqlite.php 8.6 KB

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