DbPackages-mysql.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2011 Simple Machines
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.0
  11. */
  12. if (!defined('SMF'))
  13. die('Hacking attempt...');
  14. /* This file contains database functionality specifically designed for packages to utilize.
  15. bool smf_db_create_table(string table_name, array columns, array indexes = array(),
  16. array parameters = array(), string if_exists = 'ignore')
  17. - Can be used to create a table without worrying about schema compatabilities.
  18. - If the table exists will, by default, do nothing.
  19. - Builds table with columns as passed to it - at least one column must be sent.
  20. The columns array should have one sub-array for each column - these sub arrays contain:
  21. + 'name' = Column name
  22. + 'type' = Type of column - values from (smallint,mediumint,int,text,varchar,char,tinytext,mediumtext,largetext)
  23. + 'size' => Size of column (If applicable) - for example 255 for a large varchar, 10 for an int etc. If not
  24. set SMF will pick a size.
  25. + 'default' = Default value - do not set if no default required.
  26. + 'null' => Can it be null (true or false) - if not set default will be false.
  27. + 'auto' => Set to true to make it an auto incrementing column. Set to a numerical value to set
  28. from what it should begin counting.
  29. - Adds indexes as specified within indexes parameter. Each index should be a member of $indexes. Values are:
  30. + 'name' => Index name (If left empty SMF will generate).
  31. + 'type' => Type of index. Choose from 'primary', 'unique' or 'index'. If not set will default to 'index'.
  32. + 'columns' => Array containing columns that form part of key - in the order the index is to be created.
  33. - parameters: (None yet)
  34. - if_exists values:
  35. + 'ignore' will do nothing if the table exists. (And will return true)
  36. + 'overwrite' will drop any existing table of the same name.
  37. + 'error' will return false if the table already exists.
  38. */
  39. // Add the file functions to the $smcFunc array.
  40. function db_packages_init()
  41. {
  42. global $smcFunc, $reservedTables, $db_package_log, $db_prefix;
  43. if (!isset($smcFunc['db_create_table']) || $smcFunc['db_create_table'] != 'smf_db_create_table')
  44. {
  45. $smcFunc += array(
  46. 'db_add_column' => 'smf_db_add_column',
  47. 'db_add_index' => 'smf_db_add_index',
  48. 'db_calculate_type' => 'smf_db_calculate_type',
  49. 'db_change_column' => 'smf_db_change_column',
  50. 'db_create_table' => 'smf_db_create_table',
  51. 'db_drop_table' => 'smf_db_drop_table',
  52. 'db_table_structure' => 'smf_db_table_structure',
  53. 'db_list_columns' => 'smf_db_list_columns',
  54. 'db_list_indexes' => 'smf_db_list_indexes',
  55. 'db_remove_column' => 'smf_db_remove_column',
  56. 'db_remove_index' => 'smf_db_remove_index',
  57. );
  58. $db_package_log = array();
  59. }
  60. // We setup an array of SMF tables we can't do auto-remove on - in case a mod writer cocks it up!
  61. $reservedTables = array('admin_info_files', 'approval_queue', 'attachments', 'ban_groups', 'ban_items',
  62. 'board_permissions', 'boards', 'calendar', 'calendar_holidays', 'categories', 'collapsed_categories',
  63. 'custom_fields', 'group_moderators', 'log_actions', 'log_activity', 'log_banned', 'log_boards',
  64. 'log_digest', 'log_errors', 'log_floodcontrol', 'log_group_requests', 'log_karma', 'log_mark_read',
  65. 'log_notify', 'log_online', 'log_packages', 'log_polls', 'log_reported', 'log_reported_comments',
  66. 'log_scheduled_tasks', 'log_search_messages', 'log_search_results', 'log_search_subjects',
  67. 'log_search_topics', 'log_topics', 'mail_queue', 'membergroups', 'members', 'message_icons',
  68. 'messages', 'moderators', 'package_servers', 'permission_profiles', 'permissions', 'personal_messages',
  69. 'pm_recipients', 'poll_choices', 'polls', 'scheduled_tasks', 'sessions', 'settings', 'smileys',
  70. 'themes', 'topics');
  71. foreach ($reservedTables as $k => $table_name)
  72. $reservedTables[$k] = strtolower($db_prefix . $table_name);
  73. // We in turn may need the extra stuff.
  74. db_extend('extra');
  75. }
  76. // Create a table.
  77. function smf_db_create_table($table_name, $columns, $indexes = array(), $parameters = array(), $if_exists = 'ignore', $error = 'fatal')
  78. {
  79. global $reservedTables, $smcFunc, $db_package_log, $db_prefix, $db_character_set;
  80. // Strip out the table name, we might not need it in some cases
  81. $real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
  82. // With or without the database name, the fullname looks like this.
  83. $full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
  84. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  85. // First - no way do we touch SMF tables.
  86. if (in_array(strtolower($table_name), $reservedTables))
  87. return false;
  88. // Log that we'll want to remove this on uninstall.
  89. $db_package_log[] = array('remove_table', $table_name);
  90. // Slightly easier on MySQL than the others...
  91. $tables = $smcFunc['db_list_tables']();
  92. if (in_array($full_table_name, $tables))
  93. {
  94. // This is a sad day... drop the table? If not, return false (error) by default.
  95. if ($if_exists == 'overwrite')
  96. $smcFunc['db_drop_table']($table_name);
  97. else
  98. return $if_exists == 'ignore';
  99. }
  100. // Righty - let's do the damn thing!
  101. $table_query = 'CREATE TABLE ' . $table_name . "\n" . '(';
  102. foreach ($columns as $column)
  103. {
  104. // Auto increment is easy here!
  105. if (!empty($column['auto']))
  106. {
  107. $default = 'auto_increment';
  108. }
  109. elseif (isset($column['default']) && $column['default'] !== null)
  110. $default = 'default \'' . $smcFunc['db_escape_string']($column['default']) . '\'';
  111. else
  112. $default = '';
  113. // Sort out the size... and stuff...
  114. $column['size'] = isset($column['size']) && is_numeric($column['size']) ? $column['size'] : null;
  115. list ($type, $size) = $smcFunc['db_calculate_type']($column['type'], $column['size']);
  116. // Allow unsigned integers (mysql only)
  117. $unsigned = in_array($type, array('int', 'tinyint', 'smallint', 'mediumint', 'bigint')) && !empty($column['unsigned']) ? 'unsigned ' : '';
  118. if ($size !== null)
  119. $type = $type . '(' . $size . ')';
  120. // Now just put it together!
  121. $table_query .= "\n\t`" .$column['name'] . '` ' . $type . ' ' . (!empty($unsigned) ? $unsigned : '') . (!empty($column['null']) ? '' : 'NOT NULL') . ' ' . $default . ',';
  122. }
  123. // Loop through the indexes next...
  124. foreach ($indexes as $index)
  125. {
  126. $columns = implode(',', $index['columns']);
  127. // Is it the primary?
  128. if (isset($index['type']) && $index['type'] == 'primary')
  129. $table_query .= "\n\t" . 'PRIMARY KEY (' . implode(',', $index['columns']) . '),';
  130. else
  131. {
  132. if (empty($index['name']))
  133. $index['name'] = implode('_', $index['columns']);
  134. $table_query .= "\n\t" . (isset($index['type']) && $index['type'] == 'unique' ? 'UNIQUE' : 'KEY') . ' ' . $index['name'] . ' (' . $columns . '),';
  135. }
  136. }
  137. // No trailing commas!
  138. if (substr($table_query, -1) == ',')
  139. $table_query = substr($table_query, 0, -1);
  140. $table_query .= ') ENGINE=MyISAM';
  141. if (!empty($db_character_set) && $db_character_set == 'utf8')
  142. $table_query .= ' DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci';
  143. // Create the table!
  144. $smcFunc['db_query']('', $table_query,
  145. array(
  146. 'security_override' => true,
  147. )
  148. );
  149. }
  150. // Drop a table.
  151. function smf_db_drop_table($table_name, $parameters = array(), $error = 'fatal')
  152. {
  153. global $reservedTables, $smcFunc, $db_prefix;
  154. // After stripping away the database name, this is what's left.
  155. $real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
  156. // Get some aliases.
  157. $full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
  158. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  159. // God no - dropping one of these = bad.
  160. if (in_array(strtolower($table_name), $reservedTables))
  161. return false;
  162. // Does it exist?
  163. if (in_array($full_table_name, $smcFunc['db_list_tables']()))
  164. {
  165. $query = 'DROP TABLE ' . $table_name;
  166. $smcFunc['db_query']('',
  167. $query,
  168. array(
  169. 'security_override' => true,
  170. )
  171. );
  172. return true;
  173. }
  174. // Otherwise do 'nout.
  175. return false;
  176. }
  177. // Add a column.
  178. function smf_db_add_column($table_name, $column_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
  179. {
  180. global $smcFunc, $db_package_log, $txt, $db_prefix;
  181. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  182. // Log that we will want to uninstall this!
  183. $db_package_log[] = array('remove_column', $table_name, $column_info['name']);
  184. // Does it exist - if so don't add it again!
  185. $columns = $smcFunc['db_list_columns']($table_name, false);
  186. foreach ($columns as $column)
  187. if ($column == $column_info['name'])
  188. {
  189. // If we're going to overwrite then use change column.
  190. if ($if_exists == 'update')
  191. return $smcFunc['db_change_column']($table_name, $column_info['name'], $column_info);
  192. else
  193. return false;
  194. }
  195. // Get the specifics...
  196. $column_info['size'] = isset($column_info['size']) && is_numeric($column_info['size']) ? $column_info['size'] : null;
  197. list ($type, $size) = $smcFunc['db_calculate_type']($column_info['type'], $column_info['size']);
  198. // Allow unsigned integers (mysql only)
  199. $unsigned = in_array($type, array('int', 'tinyint', 'smallint', 'mediumint', 'bigint')) && !empty($column_info['unsigned']) ? 'unsigned ' : '';
  200. if ($size !== null)
  201. $type = $type . '(' . $size . ')';
  202. // Now add the thing!
  203. $query = '
  204. ALTER TABLE ' . $table_name . '
  205. ADD `' . $column_info['name'] . '` ' . $type . ' ' . (!empty($unsigned) ? $unsigned : '') . (empty($column_info['null']) ? 'NOT NULL' : '') . ' ' .
  206. (!isset($column_info['default']) ? '' : 'default \'' . $smcFunc['db_escape_string']($column_info['default']) . '\'') . ' ' .
  207. (empty($column_info['auto']) ? '' : 'auto_increment primary key') . ' ';
  208. $smcFunc['db_query']('', $query,
  209. array(
  210. 'security_override' => true,
  211. )
  212. );
  213. return true;
  214. }
  215. // Remove a column.
  216. function smf_db_remove_column($table_name, $column_name, $parameters = array(), $error = 'fatal')
  217. {
  218. global $smcFunc, $db_prefix;
  219. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  220. // Does it exist?
  221. $columns = $smcFunc['db_list_columns']($table_name, true);
  222. foreach ($columns as $column)
  223. if ($column['name'] == $column_name)
  224. {
  225. $smcFunc['db_query']('', '
  226. ALTER TABLE ' . $table_name . '
  227. DROP COLUMN ' . $column_name,
  228. array(
  229. 'security_override' => true,
  230. )
  231. );
  232. return true;
  233. }
  234. // If here we didn't have to work - joy!
  235. return false;
  236. }
  237. // Change a column.
  238. function smf_db_change_column($table_name, $old_column, $column_info, $parameters = array(), $error = 'fatal')
  239. {
  240. global $smcFunc, $db_prefix;
  241. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  242. // Check it does exist!
  243. $columns = $smcFunc['db_list_columns']($table_name, true);
  244. $old_info = null;
  245. foreach ($columns as $column)
  246. if ($column['name'] == $old_column)
  247. $old_info = $column;
  248. // Nothing?
  249. if ($old_info == null)
  250. return false;
  251. // Get the right bits.
  252. if (!isset($column_info['name']))
  253. $column_info['name'] = $old_column;
  254. if (!isset($column_info['default']))
  255. $column_info['default'] = $old_info['default'];
  256. if (!isset($column_info['null']))
  257. $column_info['null'] = $old_info['null'];
  258. if (!isset($column_info['auto']))
  259. $column_info['auto'] = $old_info['auto'];
  260. if (!isset($column_info['type']))
  261. $column_info['type'] = $old_info['type'];
  262. if (!isset($column_info['size']) || !is_numeric($column_info['size']))
  263. $column_info['size'] = $old_info['size'];
  264. if (!isset($column_info['unsigned']) || !in_array($column_info['type'], array('int', 'tinyint', 'smallint', 'mediumint', 'bigint')))
  265. $column_info['unsigned'] = '';
  266. list ($type, $size) = $smcFunc['db_calculate_type']($column_info['type'], $column_info['size']);
  267. // Allow for unsigned integers (mysql only)
  268. $unsigned = in_array($type, array('int', 'tinyint', 'smallint', 'mediumint', 'bigint')) && !empty($column_info['unsigned']) ? 'unsigned ' : '';
  269. if ($size !== null)
  270. $type = $type . '(' . $size . ')';
  271. $smcFunc['db_query']('', '
  272. ALTER TABLE ' . $table_name . '
  273. CHANGE COLUMN `' . $old_column . '` `' . $column_info['name'] . '` ' . $type . ' ' . (!empty($unsigned) ? $unsigned : '') . (empty($column_info['null']) ? 'NOT NULL' : '') . ' ' .
  274. (!isset($column_info['default']) ? '' : 'default \'' . $smcFunc['db_escape_string']($column_info['default']) . '\'') . ' ' .
  275. (empty($column_info['auto']) ? '' : 'auto_increment') . ' ',
  276. array(
  277. 'security_override' => true,
  278. )
  279. );
  280. }
  281. // Add an index.
  282. function smf_db_add_index($table_name, $index_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
  283. {
  284. global $smcFunc, $db_package_log, $db_prefix;
  285. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  286. // No columns = no index.
  287. if (empty($index_info['columns']))
  288. return false;
  289. $columns = implode(',', $index_info['columns']);
  290. // No name - make it up!
  291. if (empty($index_info['name']))
  292. {
  293. // No need for primary.
  294. if (isset($index_info['type']) && $index_info['type'] == 'primary')
  295. $index_info['name'] = '';
  296. else
  297. $index_info['name'] = implode('_', $index_info['columns']);
  298. }
  299. else
  300. $index_info['name'] = $index_info['name'];
  301. // Log that we are going to want to remove this!
  302. $db_package_log[] = array('remove_index', $table_name, $index_info['name']);
  303. // Let's get all our indexes.
  304. $indexes = $smcFunc['db_list_indexes']($table_name, true);
  305. // Do we already have it?
  306. foreach ($indexes as $index)
  307. {
  308. if ($index['name'] == $index_info['name'] || ($index['type'] == 'primary' && isset($index_info['type']) && $index_info['type'] == 'primary'))
  309. {
  310. // If we want to overwrite simply remove the current one then continue.
  311. if ($if_exists != 'update' || $index['type'] == 'primary')
  312. return false;
  313. else
  314. $smcFunc['db_remove_index']($table_name, $index_info['name']);
  315. }
  316. }
  317. // If we're here we know we don't have the index - so just add it.
  318. if (!empty($index_info['type']) && $index_info['type'] == 'primary')
  319. {
  320. $smcFunc['db_query']('', '
  321. ALTER TABLE ' . $table_name . '
  322. ADD PRIMARY KEY (' . $columns . ')',
  323. array(
  324. 'security_override' => true,
  325. )
  326. );
  327. }
  328. else
  329. {
  330. $smcFunc['db_query']('', '
  331. ALTER TABLE ' . $table_name . '
  332. ADD ' . (isset($index_info['type']) && $index_info['type'] == 'unique' ? 'UNIQUE' : 'INDEX') . ' ' . $index_info['name'] . ' (' . $columns . ')',
  333. array(
  334. 'security_override' => true,
  335. )
  336. );
  337. }
  338. }
  339. // Remove an index.
  340. function smf_db_remove_index($table_name, $index_name, $parameters = array(), $error = 'fatal')
  341. {
  342. global $smcFunc, $db_prefix;
  343. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  344. // Better exist!
  345. $indexes = $smcFunc['db_list_indexes']($table_name, true);
  346. foreach ($indexes as $index)
  347. {
  348. // If the name is primary we want the primary key!
  349. if ($index['type'] == 'primary' && $index_name == 'primary')
  350. {
  351. // Dropping primary key?
  352. $smcFunc['db_query']('', '
  353. ALTER TABLE ' . $table_name . '
  354. DROP PRIMARY KEY',
  355. array(
  356. 'security_override' => true,
  357. )
  358. );
  359. return true;
  360. }
  361. if ($index['name'] == $index_name)
  362. {
  363. // Drop the bugger...
  364. $smcFunc['db_query']('', '
  365. ALTER TABLE ' . $table_name . '
  366. DROP INDEX ' . $index_name,
  367. array(
  368. 'security_override' => true,
  369. )
  370. );
  371. return true;
  372. }
  373. }
  374. // Not to be found ;(
  375. return false;
  376. }
  377. // Get the schema formatted name for a type.
  378. function smf_db_calculate_type($type_name, $type_size = null, $reverse = false)
  379. {
  380. // MySQL is actually the generic baseline.
  381. return array($type_name, $type_size);
  382. }
  383. // Get table structure.
  384. function smf_db_table_structure($table_name, $parameters = array())
  385. {
  386. global $smcFunc, $db_prefix;
  387. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  388. return array(
  389. 'name' => $table_name,
  390. 'columns' => $smcFunc['db_list_columns']($table_name, true),
  391. 'indexes' => $smcFunc['db_list_indexes']($table_name, true),
  392. );
  393. }
  394. // Return column information for a table.
  395. function smf_db_list_columns($table_name, $detail = false, $parameters = array())
  396. {
  397. global $smcFunc, $db_prefix;
  398. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  399. $result = $smcFunc['db_query']('', '
  400. SHOW FIELDS
  401. FROM {raw:table_name}',
  402. array(
  403. 'table_name' => substr($table_name, 0, 1) == '`' ? $table_name : '`' . $table_name . '`',
  404. )
  405. );
  406. $columns = array();
  407. while ($row = $smcFunc['db_fetch_assoc']($result))
  408. {
  409. if (!$detail)
  410. {
  411. $columns[] = $row['Field'];
  412. }
  413. else
  414. {
  415. // Is there an auto_increment?
  416. $auto = strpos($row['Extra'], 'auto_increment') !== false ? true : false;
  417. // Can we split out the size?
  418. if (preg_match('~(.+?)\s*\((\d+)\)(?:(?:\s*)?(unsigned))?~i', $row['Type'], $matches) === 1)
  419. {
  420. $type = $matches[1];
  421. $size = $matches[2];
  422. if (!empty($matches[3]) && $matches[3] == 'unsigned')
  423. $unsigned = true;
  424. }
  425. else
  426. {
  427. $type = $row['Type'];
  428. $size = null;
  429. }
  430. $columns[$row['Field']] = array(
  431. 'name' => $row['Field'],
  432. 'null' => $row['Null'] != 'YES' ? false : true,
  433. 'default' => isset($row['Default']) ? $row['Default'] : null,
  434. 'type' => $type,
  435. 'size' => $size,
  436. 'auto' => $auto,
  437. );
  438. if (isset($unsigned))
  439. {
  440. $columns[$row['Field']]['unsigned'] = $unsigned;
  441. unset($unsigned);
  442. }
  443. }
  444. }
  445. $smcFunc['db_free_result']($result);
  446. return $columns;
  447. }
  448. // What about some index information?
  449. function smf_db_list_indexes($table_name, $detail = false, $parameters = array())
  450. {
  451. global $smcFunc, $db_prefix;
  452. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  453. $result = $smcFunc['db_query']('', '
  454. SHOW KEYS
  455. FROM {raw:table_name}',
  456. array(
  457. 'table_name' => substr($table_name, 0, 1) == '`' ? $table_name : '`' . $table_name . '`',
  458. )
  459. );
  460. $indexes = array();
  461. while ($row = $smcFunc['db_fetch_assoc']($result))
  462. {
  463. if (!$detail)
  464. $indexes[] = $row['Key_name'];
  465. else
  466. {
  467. // What is the type?
  468. if ($row['Key_name'] == 'PRIMARY')
  469. $type = 'primary';
  470. elseif (empty($row['Non_unique']))
  471. $type = 'unique';
  472. elseif (isset($row['Index_type']) && $row['Index_type'] == 'FULLTEXT')
  473. $type = 'fulltext';
  474. else
  475. $type = 'index';
  476. // This is the first column we've seen?
  477. if (empty($indexes[$row['Key_name']]))
  478. {
  479. $indexes[$row['Key_name']] = array(
  480. 'name' => $row['Key_name'],
  481. 'type' => $type,
  482. 'columns' => array(),
  483. );
  484. }
  485. // Is it a partial index?
  486. if (!empty($row['Sub_part']))
  487. $indexes[$row['Key_name']]['columns'][] = $row['Column_name'] . '(' . $row['Sub_part'] . ')';
  488. else
  489. $indexes[$row['Key_name']]['columns'][] = $row['Column_name'];
  490. }
  491. }
  492. $smcFunc['db_free_result']($result);
  493. return $indexes;
  494. }
  495. ?>