2
0

DbPackages-sqlite.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. <?php
  2. /**
  3. * This file contains database functionality specifically designed for packages (mods) to utilize.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2012 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 file functions to the $smcFunc array.
  18. */
  19. function db_packages_init()
  20. {
  21. global $smcFunc, $reservedTables, $db_package_log, $db_prefix;
  22. if (!isset($smcFunc['db_create_table']) || $smcFunc['db_create_table'] != 'smf_db_create_table')
  23. {
  24. $smcFunc += array(
  25. 'db_add_column' => 'smf_db_add_column',
  26. 'db_add_index' => 'smf_db_add_index',
  27. 'db_alter_table' => 'smf_db_alter_table',
  28. 'db_calculate_type' => 'smf_db_calculate_type',
  29. 'db_change_column' => 'smf_db_change_column',
  30. 'db_create_table' => 'smf_db_create_table',
  31. 'db_drop_table' => 'smf_db_drop_table',
  32. 'db_table_structure' => 'smf_db_table_structure',
  33. 'db_list_columns' => 'smf_db_list_columns',
  34. 'db_list_indexes' => 'smf_db_list_indexes',
  35. 'db_remove_column' => 'smf_db_remove_column',
  36. 'db_remove_index' => 'smf_db_remove_index',
  37. );
  38. $db_package_log = array();
  39. }
  40. // We setup an array of SMF tables we can't do auto-remove on - in case a mod writer cocks it up!
  41. $reservedTables = array('admin_info_files', 'approval_queue', 'attachments', 'ban_groups', 'ban_items',
  42. 'board_permissions', 'boards', 'calendar', 'calendar_holidays', 'categories', 'collapsed_categories',
  43. 'custom_fields', 'group_moderators', 'log_actions', 'log_activity', 'log_banned', 'log_boards',
  44. 'log_digest', 'log_errors', 'log_floodcontrol', 'log_group_requests', 'log_karma', 'log_mark_read',
  45. 'log_notify', 'log_online', 'log_packages', 'log_polls', 'log_reported', 'log_reported_comments',
  46. 'log_scheduled_tasks', 'log_search_messages', 'log_search_results', 'log_search_subjects',
  47. 'log_search_topics', 'log_topics', 'mail_queue', 'membergroups', 'members', 'message_icons',
  48. 'messages', 'moderators', 'package_servers', 'permission_profiles', 'permissions', 'personal_messages',
  49. 'pm_recipients', 'poll_choices', 'polls', 'scheduled_tasks', 'sessions', 'settings', 'smileys',
  50. 'themes', 'topics');
  51. foreach ($reservedTables as $k => $table_name)
  52. $reservedTables[$k] = strtolower($db_prefix . $table_name);
  53. // We in turn may need the extra stuff.
  54. db_extend('extra');
  55. }
  56. /**
  57. * This function can be used to create a table without worrying about schema
  58. * compatabilities across supported database systems.
  59. * - If the table exists will, by default, do nothing.
  60. * - Builds table with columns as passed to it - at least one column must be sent.
  61. * The columns array should have one sub-array for each column - these sub arrays contain:
  62. * 'name' = Column name
  63. * 'type' = Type of column - values from (smallint, mediumint, int, text, varchar, char, tinytext, mediumtext, largetext)
  64. * 'size' => Size of column (If applicable) - for example 255 for a large varchar, 10 for an int etc.
  65. * If not set SMF will pick a size.
  66. * - 'default' = Default value - do not set if no default required.
  67. * - 'null' => Can it be null (true or false) - if not set default will be false.
  68. * - 'auto' => Set to true to make it an auto incrementing column. Set to a numerical value to set from what
  69. * it should begin counting.
  70. * - Adds indexes as specified within indexes parameter. Each index should be a member of $indexes. Values are:
  71. * - 'name' => Index name (If left empty SMF will generate).
  72. * - 'type' => Type of index. Choose from 'primary', 'unique' or 'index'. If not set will default to 'index'.
  73. * - 'columns' => Array containing columns that form part of key - in the order the index is to be created.
  74. * - parameters: (None yet)
  75. * - if_exists values:
  76. * - 'ignore' will do nothing if the table exists. (And will return true)
  77. * - 'overwrite' will drop any existing table of the same name.
  78. * - 'error' will return false if the table already exists.
  79. * @param string $table_name
  80. * @param array $columns, in the format specified.
  81. * @param array $indexes, default array(), in the format specified.
  82. * @param array $parameters, default array()
  83. * @param string $if_exists, default 'ignore'
  84. * @param string $error, default 'fatal'
  85. */
  86. function smf_db_create_table($table_name, $columns, $indexes = array(), $parameters = array(), $if_exists = 'ignore', $error = 'fatal')
  87. {
  88. global $reservedTables, $smcFunc, $db_package_log, $db_prefix;
  89. // With or without the database name, the full name looks like this.
  90. $real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
  91. $full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
  92. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  93. // First - no way do we touch SMF tables.
  94. // Commented out for now. We need to alter SMF tables in order to use this in the upgrade.
  95. /*
  96. if (in_array(strtolower($table_name), $reservedTables))
  97. return false;
  98. */
  99. // Log that we'll want to remove this on uninstall.
  100. $db_package_log[] = array('remove_table', $table_name);
  101. // Does this table exist or not?
  102. $tables = $smcFunc['db_list_tables']();
  103. if (in_array($full_table_name, $tables))
  104. {
  105. // This is a sad day... drop the table? If not, return false (error) by default.
  106. if ($if_exists == 'overwrite')
  107. $smcFunc['db_drop_table']($table_name);
  108. else
  109. return $if_exists == 'ignore';
  110. }
  111. // Righty - let's do the damn thing!
  112. $table_query = 'CREATE TABLE ' . $table_name . "\n" . '(';
  113. $done_primary = false;
  114. foreach ($columns as $column)
  115. {
  116. // Auto increment is special
  117. if (!empty($column['auto']))
  118. {
  119. $table_query .= "\n" . $column['name'] . ' integer PRIMARY KEY,';
  120. $done_primary = true;
  121. continue;
  122. }
  123. elseif (isset($column['default']) && $column['default'] !== null)
  124. $default = 'default \'' . $smcFunc['db_escape_string']($column['default']) . '\'';
  125. else
  126. $default = '';
  127. // Sort out the size... and stuff...
  128. $column['size'] = isset($column['size']) && is_numeric($column['size']) ? $column['size'] : null;
  129. list ($type, $size) = $smcFunc['db_calculate_type']($column['type'], $column['size']);
  130. if ($size !== null)
  131. $type = $type . '(' . $size . ')';
  132. // Now just put it together!
  133. $table_query .= "\n\t" . $column['name'] . ' ' . $type . ' ' . (!empty($column['null']) ? '' : 'NOT NULL') . ' ' . $default . ',';
  134. }
  135. // Loop through the indexes next...
  136. $index_queries = array();
  137. foreach ($indexes as $index)
  138. {
  139. $columns = implode(',', $index['columns']);
  140. // Is it the primary?
  141. if (isset($index['type']) && $index['type'] == 'primary')
  142. {
  143. // If we've done the primary via auto_inc, don't do it again!
  144. if (!$done_primary)
  145. $table_query .= "\n\t" . 'PRIMARY KEY (' . implode(',', $index['columns']) . '),';
  146. }
  147. else
  148. {
  149. if (empty($index['name']))
  150. $index['name'] = implode('_', $index['columns']);
  151. $index_queries[] = 'CREATE ' . (isset($index['type']) && $index['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $table_name . '_' . $index['name'] . ' ON ' . $table_name . ' (' . $columns . ')';
  152. }
  153. }
  154. // No trailing commas!
  155. if (substr($table_query, -1) == ',')
  156. $table_query = substr($table_query, 0, -1);
  157. $table_query .= ')';
  158. if (empty($parameters['skip_transaction']))
  159. $smcFunc['db_transaction']('begin');
  160. // Do the table and indexes...
  161. $smcFunc['db_query']('', $table_query,
  162. array(
  163. 'security_override' => true,
  164. )
  165. );
  166. foreach ($index_queries as $query)
  167. $smcFunc['db_query']('', $query,
  168. array(
  169. 'security_override' => true,
  170. )
  171. );
  172. if (empty($parameters['skip_transaction']))
  173. $smcFunc['db_transaction']('commit');
  174. }
  175. /**
  176. * Drop a table.
  177. * @param string $table_name
  178. * @param array $parameters, default array()
  179. * @param string $error, default 'fatal'
  180. */
  181. function smf_db_drop_table($table_name, $parameters = array(), $error = 'fatal')
  182. {
  183. global $reservedTables, $smcFunc, $db_prefix;
  184. // Strip out the table name, we might not need it in some cases
  185. $real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
  186. $full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
  187. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  188. // God no - dropping one of these = bad.
  189. if (in_array(strtolower($table_name), $reservedTables))
  190. return false;
  191. // Does it exist?
  192. if (in_array($full_table_name, $smcFunc['db_list_tables']()))
  193. {
  194. $query = 'DROP TABLE ' . $table_name;
  195. $smcFunc['db_query']('', $query,
  196. array(
  197. 'security_override' => true,
  198. )
  199. );
  200. return true;
  201. }
  202. // Otherwise do 'nout.
  203. return false;
  204. }
  205. /**
  206. * This function adds a column.
  207. * @param string $table_name, the name of the table
  208. * @param array $column_info, with column information
  209. * @param array $parameters, default array()
  210. * @param string $if_exists, default 'update'
  211. * @param string $error, default 'fatal'
  212. */
  213. function smf_db_add_column($table_name, $column_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
  214. {
  215. global $smcFunc, $db_package_log, $txt, $db_prefix;
  216. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  217. // Log that we will want to uninstall this!
  218. $db_package_log[] = array('remove_column', $table_name, $column_info['name']);
  219. // Does it exist - if so don't add it again!
  220. $columns = $smcFunc['db_list_columns']($table_name, false);
  221. foreach ($columns as $column)
  222. if ($column == $column_info['name'])
  223. {
  224. // If we're going to overwrite then use change column.
  225. if ($if_exists == 'update')
  226. return $smcFunc['db_change_column']($table_name, $column_info['name'], $column_info);
  227. else
  228. return false;
  229. }
  230. // Alter the table to add the column.
  231. if ($smcFunc['db_alter_table']($table_name, array('add' => array($column_info))) === false)
  232. return false;
  233. return true;
  234. }
  235. /**
  236. * Removes a column.
  237. * We can't reliably do this on SQLite - damn!
  238. * @param string $table_name
  239. * @param string $column_name
  240. * @param array $parameters, default array()
  241. * @param string $error, default 'fatal'
  242. */
  243. function smf_db_remove_column($table_name, $column_name, $parameters = array(), $error = 'fatal')
  244. {
  245. global $smcFunc, $db_prefix;
  246. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  247. if ($smcFunc['db_alter_table']($table_name, array('remove' => array(array('name' => $column_name)))))
  248. return true;
  249. else
  250. return false;
  251. }
  252. /**
  253. * Change a column.
  254. * @param string $table_name
  255. * @param $old_column
  256. * @param $column_info
  257. * @param array $parameters, default array()
  258. * @param string $error, default 'fatal'
  259. */
  260. function smf_db_change_column($table_name, $old_column, $column_info, $parameters = array(), $error = 'fatal')
  261. {
  262. global $smcFunc, $db_prefix;
  263. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  264. if ($smcFunc['db_alter_table']($table_name, array('change' => array(array('name' => $old_column) + $column_info))))
  265. return true;
  266. else
  267. return false;
  268. }
  269. /**
  270. * Add an index.
  271. * @param string $table_name
  272. * @param array $index_info
  273. * @param array $parameters, default array()
  274. * @param string $if_exists, default 'update'
  275. * @param string $error, default 'fatal'
  276. */
  277. function smf_db_add_index($table_name, $index_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
  278. {
  279. global $smcFunc, $db_package_log, $db_prefix;
  280. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  281. // No columns = no index.
  282. if (empty($index_info['columns']))
  283. return false;
  284. $columns = implode(',', $index_info['columns']);
  285. // No name - make it up!
  286. if (empty($index_info['name']))
  287. {
  288. // No need for primary.
  289. if (isset($index_info['type']) && $index_info['type'] == 'primary')
  290. $index_info['name'] = '';
  291. else
  292. $index_info['name'] = implode('_', $index_info['columns']);
  293. }
  294. else
  295. $index_info['name'] = $index_info['name'];
  296. // Log that we are going to want to remove this!
  297. $db_package_log[] = array('remove_index', $table_name, $index_info['name']);
  298. // Let's get all our indexes.
  299. $indexes = $smcFunc['db_list_indexes']($table_name, true);
  300. // Do we already have it?
  301. foreach ($indexes as $index)
  302. {
  303. if ($index['name'] == $index_info['name'] || ($index['type'] == 'primary' && isset($index_info['type']) && $index_info['type'] == 'primary'))
  304. {
  305. // If we want to overwrite simply remove the current one then continue.
  306. if ($if_exists != 'update' || $index['type'] == 'primary')
  307. return false;
  308. else
  309. $smcFunc['db_remove_index']($table_name, $index_info['name']);
  310. }
  311. }
  312. // If we're here we know we don't have the index - so just add it.
  313. if (!empty($index_info['type']) && $index_info['type'] == 'primary')
  314. {
  315. // @todo Doesn't work with PRIMARY KEY yet.
  316. }
  317. else
  318. {
  319. $smcFunc['db_query']('', '
  320. CREATE ' . (isset($index_info['type']) && $index_info['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $index_info['name'] . ' ON ' . $table_name . ' (' . $columns . ')',
  321. array(
  322. 'security_override' => true,
  323. )
  324. );
  325. }
  326. }
  327. /**
  328. * Remove an index.
  329. * @param string $table_name
  330. * @param string $index_name
  331. * @param array$parameters, default array()
  332. * @param string $error, default 'fatal'
  333. */
  334. function smf_db_remove_index($table_name, $index_name, $parameters = array(), $error = 'fatal')
  335. {
  336. global $smcFunc, $db_prefix;
  337. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  338. // Better exist!
  339. $indexes = $smcFunc['db_list_indexes']($table_name, true);
  340. foreach ($indexes as $index)
  341. {
  342. // @todo Doesn't do primary key at the moment!
  343. if ($index['type'] != 'primary' && $index['name'] == $index_name)
  344. {
  345. // Drop the bugger...
  346. $smcFunc['db_query']('', '
  347. DROP INDEX ' . $index_name,
  348. array(
  349. 'security_override' => true,
  350. )
  351. );
  352. return true;
  353. }
  354. }
  355. // Not to be found ;(
  356. return false;
  357. }
  358. /**
  359. * Get the schema formatted name for a type.
  360. * @param string $type_name
  361. * @param $type_size
  362. * @param $reverse
  363. */
  364. function smf_db_calculate_type($type_name, $type_size = null, $reverse = false)
  365. {
  366. // Let's be sure it's lowercase MySQL likes both, others no.
  367. $type_name = strtolower($type_name);
  368. // Generic => Specific.
  369. if (!$reverse)
  370. {
  371. $types = array(
  372. 'mediumint' => 'int',
  373. 'tinyint' => 'smallint',
  374. 'mediumtext' => 'text',
  375. 'largetext' => 'text',
  376. );
  377. }
  378. else
  379. {
  380. $types = array(
  381. 'integer' => 'int',
  382. );
  383. }
  384. // Got it? Change it!
  385. if (isset($types[$type_name]))
  386. {
  387. if ($type_name == 'tinytext')
  388. $type_size = 255;
  389. $type_name = $types[$type_name];
  390. }
  391. // Numbers don't have a size.
  392. if (strpos($type_name, 'int') !== false)
  393. $type_size = null;
  394. return array($type_name, $type_size);
  395. }
  396. /**
  397. * Get table structure.
  398. * @param string $table_name
  399. * @param array $parameters, default array()
  400. */
  401. function smf_db_table_structure($table_name, $parameters = array())
  402. {
  403. global $smcFunc, $db_prefix;
  404. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  405. return array(
  406. 'name' => $table_name,
  407. 'columns' => $smcFunc['db_list_columns']($table_name, true),
  408. 'indexes' => $smcFunc['db_list_indexes']($table_name, true),
  409. );
  410. }
  411. /**
  412. * Return column information for a table.
  413. * Harder than it should be, on sqlite!
  414. * @param string $table_name
  415. * @param bool $detail
  416. * @param array $parameters, default array()
  417. * @return mixed
  418. */
  419. function smf_db_list_columns($table_name, $detail = false, $parameters = array())
  420. {
  421. global $smcFunc, $db_prefix;
  422. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  423. $result = $smcFunc['db_query']('', '
  424. PRAGMA table_info(' . $table_name . ')',
  425. array(
  426. 'security_override' => true,
  427. )
  428. );
  429. $columns = array();
  430. $primaries = array();
  431. while ($row = $smcFunc['db_fetch_assoc']($result))
  432. {
  433. if (!$detail)
  434. {
  435. $columns[] = $row['name'];
  436. }
  437. else
  438. {
  439. // Auto increment is hard to tell really... if there's only one primary it probably is.
  440. if ($row['pk'])
  441. $primaries[] = $row['name'];
  442. // Can we split out the size?
  443. if (preg_match('~(.+?)\s*\((\d+)\)~i', $row['type'], $matches))
  444. {
  445. $type = $matches[1];
  446. $size = $matches[2];
  447. }
  448. else
  449. {
  450. $type = $row['type'];
  451. $size = null;
  452. }
  453. $columns[$row['name']] = array(
  454. 'name' => $row['name'],
  455. 'null' => $row['notnull'] ? false : true,
  456. 'default' => $row['dflt_value'],
  457. 'type' => $type,
  458. 'size' => $size,
  459. 'auto' => false,
  460. );
  461. }
  462. }
  463. $smcFunc['db_free_result']($result);
  464. // Put in our guess at auto_inc.
  465. if (count($primaries) == 1)
  466. $columns[$primaries[0]]['auto'] = true;
  467. return $columns;
  468. }
  469. /**
  470. * Get index information.
  471. * @param string $table_name
  472. * @param bool $detail
  473. * @param array $parameters
  474. * @return mixed
  475. */
  476. function smf_db_list_indexes($table_name, $detail = false, $parameters = array())
  477. {
  478. global $smcFunc, $db_prefix;
  479. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  480. $result = $smcFunc['db_query']('', '
  481. PRAGMA index_list(' . $table_name . ')',
  482. array(
  483. 'security_override' => true,
  484. )
  485. );
  486. $indexes = array();
  487. while ($row = $smcFunc['db_fetch_assoc']($result))
  488. {
  489. if (!$detail)
  490. $indexes[] = $row['name'];
  491. else
  492. {
  493. $result2 = $smcFunc['db_query']('', '
  494. PRAGMA index_info(' . $row['name'] . ')',
  495. array(
  496. 'security_override' => true,
  497. )
  498. );
  499. while ($row2 = $smcFunc['db_fetch_assoc']($result2))
  500. {
  501. // What is the type?
  502. if ($row['unique'])
  503. $type = 'unique';
  504. else
  505. $type = 'index';
  506. // This is the first column we've seen?
  507. if (empty($indexes[$row['name']]))
  508. {
  509. $indexes[$row['name']] = array(
  510. 'name' => $row['name'],
  511. 'type' => $type,
  512. 'columns' => array(),
  513. );
  514. }
  515. // Add the column...
  516. $indexes[$row['name']]['columns'][] = $row2['name'];
  517. }
  518. $smcFunc['db_free_result']($result2);
  519. }
  520. }
  521. $smcFunc['db_free_result']($result);
  522. return $indexes;
  523. }
  524. /**
  525. * Alter table on SQLite.
  526. * @param string $table_name
  527. * @param array $columns
  528. */
  529. function smf_db_alter_table($table_name, $columns)
  530. {
  531. global $smcFunc, $db_prefix, $db_name, $boarddir;
  532. $db_file = substr($db_name, -3) === '.db' ? $db_name : $db_name . '.db';
  533. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  534. // Let's get the current columns for the table.
  535. $current_columns = $smcFunc['db_list_columns']($table_name, true);
  536. // Let's get a list of columns for the temp table.
  537. $temp_table_columns = array();
  538. // Let's see if we have columns to remove or columns that are being added that already exist.
  539. foreach ($current_columns as $key => $column)
  540. {
  541. $exists = false;
  542. if (isset($columns['remove']))
  543. foreach ($columns['remove'] as $drop)
  544. if ($drop['name'] == $column['name'])
  545. {
  546. $exists = true;
  547. break;
  548. }
  549. if (isset($columns['add']))
  550. foreach ($columns['add'] as $key2 => $add)
  551. if ($add['name'] == $column['name'])
  552. {
  553. unset($columns['add'][$key2]);
  554. break;
  555. }
  556. // Doesn't exist then we 'remove'.
  557. if (!$exists)
  558. $temp_table_columns[] = $column['name'];
  559. }
  560. // If they are equal then that means that the column that we are adding exists or it doesn't exist and we are not looking to change any one of them.
  561. if (count($temp_table_columns) == count($current_columns) && empty($columns['change']) && empty($columns['add']))
  562. return true;
  563. // Drop the temp table.
  564. $smcFunc['db_query']('', '
  565. DROP TABLE {raw:temp_table_name}',
  566. array(
  567. 'temp_table_name' => $table_name . '_tmp',
  568. 'db_error_skip' => true,
  569. )
  570. );
  571. // Let's make a backup of the current database.
  572. // We only want the first backup of a table modification. So if there is a backup file and older than an hour just delete and back up again
  573. $db_backup_file = $boarddir . '/Packages/backups/backup_' . $table_name . '_' . basename($db_file) . md5($table_name . $db_file);
  574. if (file_exists($db_backup_file) && time() - filemtime($db_backup_file) > 3600)
  575. {
  576. @unlink($db_backup_file);
  577. @copy($db_file, $db_backup_file);
  578. }
  579. elseif (!file_exists($db_backup_file))
  580. @copy($db_file, $db_backup_file);
  581. // If we don't have temp tables then everything crapped out. Just exit.
  582. if (empty($temp_table_columns))
  583. return false;
  584. // Start
  585. $smcFunc['db_transaction']('begin');
  586. // Let's create the temporary table.
  587. $createTempTable = $smcFunc['db_query']('', '
  588. CREATE TEMPORARY TABLE {raw:temp_table_name}
  589. (
  590. {raw:columns}
  591. );',
  592. array(
  593. 'temp_table_name' => $table_name . '_tmp',
  594. 'columns' => implode(', ', $temp_table_columns),
  595. 'db_error_skip' => true,
  596. )
  597. ) !== false;
  598. if (!$createTempTable)
  599. return false;
  600. // Insert into temp table.
  601. $smcFunc['db_query']('', '
  602. INSERT INTO {raw:temp_table_name}
  603. ({raw:columns})
  604. SELECT {raw:columns}
  605. FROM {raw:table_name}',
  606. array(
  607. 'table_name' => $table_name,
  608. 'columns' => implode(', ', $temp_table_columns),
  609. 'temp_table_name' => $table_name . '_tmp',
  610. )
  611. );
  612. // Drop the current table.
  613. $dropTable = $smcFunc['db_query']('', '
  614. DROP TABLE {raw:table_name}',
  615. array(
  616. 'table_name' => $table_name,
  617. 'db_error_skip' => true,
  618. )
  619. ) !== false;
  620. // If you can't drop the main table then there is no where to go from here. Just return.
  621. if (!$dropTable)
  622. return false;
  623. // We need to keep track of the structure for the current columns and the new columns.
  624. $new_columns = array();
  625. $column_names = array();
  626. // Let's get the ones that we already have first.
  627. foreach ($current_columns as $name => $column)
  628. {
  629. if (in_array($name, $temp_table_columns))
  630. {
  631. $new_columns[$name] = array(
  632. 'name' => $name,
  633. 'type' => $column['type'],
  634. 'size' => isset($column['size']) ? (int) $column['size'] : null,
  635. 'null' => !empty($column['null']),
  636. 'auto' => isset($column['auto']) ? $column['auto'] : false,
  637. 'default' => isset($column['default']) ? $column['default'] : '',
  638. );
  639. // Lets keep track of the name for the column.
  640. $column_names[$name] = $name;
  641. }
  642. }
  643. // Now the new.
  644. if (!empty($columns['add']))
  645. foreach ($columns['add'] as $add)
  646. {
  647. $new_columns[$add['name']] = array(
  648. 'name' => $add['name'],
  649. 'type' => $add['type'],
  650. 'size' => isset($add['size']) ? (int) $add['size'] : null,
  651. 'null' => !empty($add['null']),
  652. 'auto' => isset($add['auto']) ? $add['auto'] : false,
  653. 'default' => isset($add['default']) ? $add['default'] : '',
  654. );
  655. // Let's keep track of the name for the column.
  656. $column_names[$add['name']] = strstr('int', $add['type']) ? ' 0 AS ' . $add['name'] : ' {string:empty_string} AS ' . $add['name'];
  657. }
  658. // Now to change a column. Not drop but change it.
  659. if (isset($columns['change']))
  660. foreach ($columns['change'] as $change)
  661. if (isset($new_columns[$change['name']]))
  662. $new_columns[$change['name']] = array(
  663. 'name' => $change['name'],
  664. 'type' => $change['type'],
  665. 'size' => isset($change['size']) ? (int) $change['size'] : null,
  666. 'null' => !empty($change['null']),
  667. 'auto' => isset($change['auto']) ? $change['auto'] : false,
  668. 'default' => isset($change['default']) ? $change['default'] : '',
  669. );
  670. // Now let's create the table.
  671. $createTable = $smcFunc['db_create_table']($table_name, $new_columns, array(), array('skip_transaction' => true));
  672. // Did it create correctly?
  673. if ($createTable === false)
  674. return false;
  675. // Back to it's original table.
  676. $insertData = $smcFunc['db_query']('', '
  677. INSERT INTO {raw:table_name}
  678. ({raw:columns})
  679. SELECT ' . implode(', ', $column_names) . '
  680. FROM {raw:temp_table_name}',
  681. array(
  682. 'table_name' => $table_name,
  683. 'columns' => implode(', ', array_keys($new_columns)),
  684. 'columns_select' => implode(', ', $column_names),
  685. 'temp_table_name' => $table_name . '_tmp',
  686. 'empty_string' => '',
  687. )
  688. );
  689. // Did everything insert correctly?
  690. if (!$insertData)
  691. return false;
  692. // Drop the temp table.
  693. $smcFunc['db_query']('', '
  694. DROP TABLE {raw:temp_table_name}',
  695. array(
  696. 'temp_table_name' => $table_name . '_tmp',
  697. 'db_error_skip' => true,
  698. )
  699. );
  700. // Commit or else there is no point in doing the previous steps.
  701. $smcFunc['db_transaction']('commit');
  702. // We got here so we're good. The temp table should be deleted, if not it will be gone later on >:D.
  703. return true;
  704. }
  705. ?>