DbExtra-sqlite.php 8.4 KB

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