PageRenderTime 68ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-admin/includes/upgrade.php

https://github.com/Mercedes/ratonesytortillas
PHP | 1278 lines | 924 code | 219 blank | 135 comment | 225 complexity | 159f2d43a795a73e15d969ce0ae944c9 MD5 | raw file
  1. <?php
  2. if ( file_exists(ABSPATH . 'wp-content/install.php') )
  3. require (ABSPATH . 'wp-content/install.php');
  4. require_once(ABSPATH . 'wp-admin/includes/admin.php');
  5. require_once(ABSPATH . 'wp-admin/includes/schema.php');
  6. if ( !function_exists('wp_install') ) :
  7. function wp_install($blog_title, $user_name, $user_email, $public, $deprecated='') {
  8. global $wp_rewrite;
  9. wp_check_mysql_version();
  10. wp_cache_flush();
  11. make_db_current_silent();
  12. populate_options();
  13. populate_roles();
  14. update_option('blogname', $blog_title);
  15. update_option('admin_email', $user_email);
  16. update_option('blog_public', $public);
  17. $schema = ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) ? 'https://' : 'http://';
  18. if ( defined('WP_SITEURL') && '' != WP_SITEURL )
  19. $guessurl = WP_SITEURL;
  20. else
  21. $guessurl = preg_replace('|/wp-admin/.*|i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
  22. update_option('siteurl', $guessurl);
  23. // If not a public blog, don't ping.
  24. if ( ! $public )
  25. update_option('default_pingback_flag', 0);
  26. // Create default user. If the user already exists, the user tables are
  27. // being shared among blogs. Just set the role in that case.
  28. $user_id = username_exists($user_name);
  29. if ( !$user_id ) {
  30. $random_password = wp_generate_password();
  31. $user_id = wp_create_user($user_name, $random_password, $user_email);
  32. } else {
  33. $random_password = __('User already exists. Password inherited.');
  34. }
  35. $user = new WP_User($user_id);
  36. $user->set_role('administrator');
  37. wp_install_defaults($user_id);
  38. $wp_rewrite->flush_rules();
  39. wp_new_blog_notification($blog_title, $guessurl, $user_id, $random_password);
  40. wp_cache_flush();
  41. return array('url' => $guessurl, 'user_id' => $user_id, 'password' => $random_password);
  42. }
  43. endif;
  44. if ( !function_exists('wp_install_defaults') ) :
  45. function wp_install_defaults($user_id) {
  46. global $wpdb;
  47. // Default category
  48. $cat_name = $wpdb->escape(__('Uncategorized'));
  49. $cat_slug = sanitize_title(__('Uncategorized'));
  50. $wpdb->query("INSERT INTO $wpdb->terms (name, slug, term_group) VALUES ('$cat_name', '$cat_slug', '0')");
  51. $wpdb->query("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ('1', 'category', '', '0', '1')");
  52. // Default link category
  53. $cat_name = $wpdb->escape(__('Blogroll'));
  54. $cat_slug = sanitize_title(__('Blogroll'));
  55. $wpdb->query("INSERT INTO $wpdb->terms (name, slug, term_group) VALUES ('$cat_name', '$cat_slug', '0')");
  56. $wpdb->query("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ('2', 'link_category', '', '0', '7')");
  57. // Now drop in some default links
  58. $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_category, link_rss, link_notes) VALUES ('http://codex.wordpress.org/', 'Documentation', 0, '', '');");
  59. $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (1, 2)" );
  60. $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_category, link_rss, link_notes) VALUES ('http://wordpress.org/development/', 'Development Blog', 0, 'http://wordpress.org/development/feed/', '');");
  61. $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (2, 2)" );
  62. $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_category, link_rss, link_notes) VALUES ('http://wordpress.org/extend/ideas/', 'Suggest Ideas', 0, '', '');");
  63. $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (3, 2)" );
  64. $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_category, link_rss, link_notes) VALUES ('http://wordpress.org/support/', 'Support Forum', 0, '', '');");
  65. $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (4, 2)" );
  66. $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_category, link_rss, link_notes) VALUES ('http://wordpress.org/extend/plugins/', 'Plugins', 0, '', '');");
  67. $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (5, 2)" );
  68. $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_category, link_rss, link_notes) VALUES ('http://wordpress.org/extend/themes/', 'Themes', 0, '', '');");
  69. $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (6, 2)" );
  70. $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_category, link_rss, link_notes) VALUES ('http://planet.wordpress.org/', 'WordPress Planet', 0, '', '');");
  71. $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (7, 2)" );
  72. // First post
  73. $now = date('Y-m-d H:i:s');
  74. $now_gmt = gmdate('Y-m-d H:i:s');
  75. $first_post_guid = get_option('home') . '/?p=1';
  76. $wpdb->query("INSERT INTO $wpdb->posts (post_author, post_date, post_date_gmt, post_content, post_excerpt, post_title, post_category, post_name, post_modified, post_modified_gmt, guid, comment_count, to_ping, pinged, post_content_filtered) VALUES ($user_id, '$now', '$now_gmt', '".$wpdb->escape(__('Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!'))."', '', '".$wpdb->escape(__('Hello world!'))."', '0', '".$wpdb->escape(__('hello-world'))."', '$now', '$now_gmt', '$first_post_guid', '1', '', '', '')");
  77. $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (1, 1)" );
  78. // Default comment
  79. $wpdb->query("INSERT INTO $wpdb->comments (comment_post_ID, comment_author, comment_author_email, comment_author_url, comment_date, comment_date_gmt, comment_content) VALUES ('1', '".$wpdb->escape(__('Mr WordPress'))."', '', 'http://wordpress.org/', '$now', '$now_gmt', '".$wpdb->escape(__('Hi, this is a comment.<br />To delete a comment, just log in and view the post&#039;s comments. There you will have the option to edit or delete them.'))."')");
  80. // First Page
  81. $first_post_guid = get_option('home') . '/?page_id=2';
  82. $wpdb->query("INSERT INTO $wpdb->posts (post_author, post_date, post_date_gmt, post_content, post_excerpt, post_title, post_category, post_name, post_modified, post_modified_gmt, guid, post_status, post_type, to_ping, pinged, post_content_filtered) VALUES ($user_id, '$now', '$now_gmt', '".$wpdb->escape(__('This is an example of a WordPress page, you could edit this to put information about yourself or your site so readers know where you are coming from. You can create as many pages like this one or sub-pages as you like and manage all of your content inside of WordPress.'))."', '', '".$wpdb->escape(__('About'))."', '0', '".$wpdb->escape(__('about'))."', '$now', '$now_gmt','$first_post_guid', 'publish', 'page', '', '', '')");
  83. }
  84. endif;
  85. if ( !function_exists('wp_new_blog_notification') ) :
  86. function wp_new_blog_notification($blog_title, $blog_url, $user_id, $password) {
  87. $user = new WP_User($user_id);
  88. $email = $user->user_email;
  89. $name = $user->user_login;
  90. $message_headers = 'From: "' . $blog_title . '" <wordpress@' . $_SERVER['SERVER_NAME'] . '>';
  91. $message = sprintf(__("Your new WordPress blog has been successfully set up at:
  92. %1\$s
  93. You can log in to the administrator account with the following information:
  94. Username: %2\$s
  95. Password: %3\$s
  96. We hope you enjoy your new blog. Thanks!
  97. --The WordPress Team
  98. http://wordpress.org/
  99. "), $blog_url, $name, $password);
  100. @wp_mail($email, __('New WordPress Blog'), $message, $message_headers);
  101. }
  102. endif;
  103. if ( !function_exists('wp_upgrade') ) :
  104. function wp_upgrade() {
  105. global $wp_current_db_version, $wp_db_version;
  106. $wp_current_db_version = __get_option('db_version');
  107. // We are up-to-date. Nothing to do.
  108. if ( $wp_db_version == $wp_current_db_version )
  109. return;
  110. wp_check_mysql_version();
  111. wp_cache_flush();
  112. make_db_current_silent();
  113. upgrade_all();
  114. wp_cache_flush();
  115. }
  116. endif;
  117. // Functions to be called in install and upgrade scripts
  118. function upgrade_all() {
  119. global $wp_current_db_version, $wp_db_version, $wp_rewrite;
  120. $wp_current_db_version = __get_option('db_version');
  121. // We are up-to-date. Nothing to do.
  122. if ( $wp_db_version == $wp_current_db_version )
  123. return;
  124. // If the version is not set in the DB, try to guess the version.
  125. if ( empty($wp_current_db_version) ) {
  126. $wp_current_db_version = 0;
  127. // If the template option exists, we have 1.5.
  128. $template = __get_option('template');
  129. if ( !empty($template) )
  130. $wp_current_db_version = 2541;
  131. }
  132. if ( $wp_current_db_version < 6039 )
  133. upgrade_230_options_table();
  134. populate_options();
  135. if ( $wp_current_db_version < 2541 ) {
  136. upgrade_100();
  137. upgrade_101();
  138. upgrade_110();
  139. upgrade_130();
  140. }
  141. if ( $wp_current_db_version < 3308 )
  142. upgrade_160();
  143. if ( $wp_current_db_version < 4772 )
  144. upgrade_210();
  145. if ( $wp_current_db_version < 4351 )
  146. upgrade_old_slugs();
  147. if ( $wp_current_db_version < 5539 )
  148. upgrade_230();
  149. if ( $wp_current_db_version < 6124 )
  150. upgrade_230_old_tables();
  151. if ( $wp_current_db_version < 7499 )
  152. upgrade_250();
  153. maybe_disable_automattic_widgets();
  154. $wp_rewrite->flush_rules();
  155. update_option('db_version', $wp_db_version);
  156. }
  157. function upgrade_100() {
  158. global $wpdb;
  159. // Get the title and ID of every post, post_name to check if it already has a value
  160. $posts = $wpdb->get_results("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''");
  161. if ($posts) {
  162. foreach($posts as $post) {
  163. if ('' == $post->post_name) {
  164. $newtitle = sanitize_title($post->post_title);
  165. $wpdb->query("UPDATE $wpdb->posts SET post_name = '$newtitle' WHERE ID = '$post->ID'");
  166. }
  167. }
  168. }
  169. $categories = $wpdb->get_results("SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories");
  170. foreach ($categories as $category) {
  171. if ('' == $category->category_nicename) {
  172. $newtitle = sanitize_title($category->cat_name);
  173. $wpdb->query("UPDATE $wpdb->categories SET category_nicename = '$newtitle' WHERE cat_ID = '$category->cat_ID'");
  174. }
  175. }
  176. $wpdb->query("UPDATE $wpdb->options SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
  177. WHERE option_name LIKE 'links_rating_image%'
  178. AND option_value LIKE 'wp-links/links-images/%'");
  179. $done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat");
  180. if ($done_ids) :
  181. foreach ($done_ids as $done_id) :
  182. $done_posts[] = $done_id->post_id;
  183. endforeach;
  184. $catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')';
  185. else:
  186. $catwhere = '';
  187. endif;
  188. $allposts = $wpdb->get_results("SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere");
  189. if ($allposts) :
  190. foreach ($allposts as $post) {
  191. // Check to see if it's already been imported
  192. $cat = $wpdb->get_row("SELECT * FROM $wpdb->post2cat WHERE post_id = $post->ID AND category_id = $post->post_category");
  193. if (!$cat && 0 != $post->post_category) { // If there's no result
  194. $wpdb->query("
  195. INSERT INTO $wpdb->post2cat
  196. (post_id, category_id)
  197. VALUES
  198. ('$post->ID', '$post->post_category')
  199. ");
  200. }
  201. }
  202. endif;
  203. }
  204. function upgrade_101() {
  205. global $wpdb;
  206. // Clean up indices, add a few
  207. add_clean_index($wpdb->posts, 'post_name');
  208. add_clean_index($wpdb->posts, 'post_status');
  209. add_clean_index($wpdb->categories, 'category_nicename');
  210. add_clean_index($wpdb->comments, 'comment_approved');
  211. add_clean_index($wpdb->comments, 'comment_post_ID');
  212. add_clean_index($wpdb->links , 'link_category');
  213. add_clean_index($wpdb->links , 'link_visible');
  214. }
  215. function upgrade_110() {
  216. global $wpdb;
  217. // Set user_nicename.
  218. $users = $wpdb->get_results("SELECT ID, user_nickname, user_nicename FROM $wpdb->users");
  219. foreach ($users as $user) {
  220. if ('' == $user->user_nicename) {
  221. $newname = sanitize_title($user->user_nickname);
  222. $wpdb->query("UPDATE $wpdb->users SET user_nicename = '$newname' WHERE ID = '$user->ID'");
  223. }
  224. }
  225. $users = $wpdb->get_results("SELECT ID, user_pass from $wpdb->users");
  226. foreach ($users as $row) {
  227. if (!preg_match('/^[A-Fa-f0-9]{32}$/', $row->user_pass)) {
  228. $wpdb->query('UPDATE '.$wpdb->users.' SET user_pass = MD5(\''.$row->user_pass.'\') WHERE ID = \''.$row->ID.'\'');
  229. }
  230. }
  231. // Get the GMT offset, we'll use that later on
  232. $all_options = get_alloptions_110();
  233. $time_difference = $all_options->time_difference;
  234. $server_time = time()+date('Z');
  235. $weblogger_time = $server_time + $time_difference*3600;
  236. $gmt_time = time();
  237. $diff_gmt_server = ($gmt_time - $server_time) / 3600;
  238. $diff_weblogger_server = ($weblogger_time - $server_time) / 3600;
  239. $diff_gmt_weblogger = $diff_gmt_server - $diff_weblogger_server;
  240. $gmt_offset = -$diff_gmt_weblogger;
  241. // Add a gmt_offset option, with value $gmt_offset
  242. add_option('gmt_offset', $gmt_offset);
  243. // Check if we already set the GMT fields (if we did, then
  244. // MAX(post_date_gmt) can't be '0000-00-00 00:00:00'
  245. // <michel_v> I just slapped myself silly for not thinking about it earlier
  246. $got_gmt_fields = ($wpdb->get_var("SELECT MAX(post_date_gmt) FROM $wpdb->posts") == '0000-00-00 00:00:00') ? false : true;
  247. if (!$got_gmt_fields) {
  248. // Add or substract time to all dates, to get GMT dates
  249. $add_hours = intval($diff_gmt_weblogger);
  250. $add_minutes = intval(60 * ($diff_gmt_weblogger - $add_hours));
  251. $wpdb->query("UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
  252. $wpdb->query("UPDATE $wpdb->posts SET post_modified = post_date");
  253. $wpdb->query("UPDATE $wpdb->posts SET post_modified_gmt = DATE_ADD(post_modified, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE) WHERE post_modified != '0000-00-00 00:00:00'");
  254. $wpdb->query("UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
  255. $wpdb->query("UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
  256. }
  257. }
  258. function upgrade_130() {
  259. global $wpdb;
  260. // Remove extraneous backslashes.
  261. $posts = $wpdb->get_results("SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts");
  262. if ($posts) {
  263. foreach($posts as $post) {
  264. $post_content = addslashes(deslash($post->post_content));
  265. $post_title = addslashes(deslash($post->post_title));
  266. $post_excerpt = addslashes(deslash($post->post_excerpt));
  267. if ( empty($post->guid) )
  268. $guid = get_permalink($post->ID);
  269. else
  270. $guid = $post->guid;
  271. $wpdb->query("UPDATE $wpdb->posts SET post_title = '$post_title', post_content = '$post_content', post_excerpt = '$post_excerpt', guid = '$guid' WHERE ID = '$post->ID'");
  272. }
  273. }
  274. // Remove extraneous backslashes.
  275. $comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments");
  276. if ($comments) {
  277. foreach($comments as $comment) {
  278. $comment_content = addslashes(deslash($comment->comment_content));
  279. $comment_author = addslashes(deslash($comment->comment_author));
  280. $wpdb->query("UPDATE $wpdb->comments SET comment_content = '$comment_content', comment_author = '$comment_author' WHERE comment_ID = '$comment->comment_ID'");
  281. }
  282. }
  283. // Remove extraneous backslashes.
  284. $links = $wpdb->get_results("SELECT link_id, link_name, link_description FROM $wpdb->links");
  285. if ($links) {
  286. foreach($links as $link) {
  287. $link_name = addslashes(deslash($link->link_name));
  288. $link_description = addslashes(deslash($link->link_description));
  289. $wpdb->query("UPDATE $wpdb->links SET link_name = '$link_name', link_description = '$link_description' WHERE link_id = '$link->link_id'");
  290. }
  291. }
  292. // The "paged" option for what_to_show is no more.
  293. if ($wpdb->get_var("SELECT option_value FROM $wpdb->options WHERE option_name = 'what_to_show'") == 'paged') {
  294. $wpdb->query("UPDATE $wpdb->options SET option_value = 'posts' WHERE option_name = 'what_to_show'");
  295. }
  296. $active_plugins = __get_option('active_plugins');
  297. // If plugins are not stored in an array, they're stored in the old
  298. // newline separated format. Convert to new format.
  299. if ( !is_array( $active_plugins ) ) {
  300. $active_plugins = explode("\n", trim($active_plugins));
  301. update_option('active_plugins', $active_plugins);
  302. }
  303. // Obsolete tables
  304. $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optionvalues');
  305. $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiontypes');
  306. $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroups');
  307. $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroup_options');
  308. // Update comments table to use comment_type
  309. $wpdb->query("UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '<trackback />', '') WHERE comment_content LIKE '<trackback />%'");
  310. $wpdb->query("UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '<pingback />', '') WHERE comment_content LIKE '<pingback />%'");
  311. // Some versions have multiple duplicate option_name rows with the same values
  312. $options = $wpdb->get_results("SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name");
  313. foreach ( $options as $option ) {
  314. if ( 1 != $option->dupes ) { // Could this be done in the query?
  315. $limit = $option->dupes - 1;
  316. $dupe_ids = $wpdb->get_col("SELECT option_id FROM $wpdb->options WHERE option_name = '$option->option_name' LIMIT $limit");
  317. $dupe_ids = join($dupe_ids, ',');
  318. $wpdb->query("DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)");
  319. }
  320. }
  321. make_site_theme();
  322. }
  323. function upgrade_160() {
  324. global $wpdb, $wp_current_db_version;
  325. populate_roles_160();
  326. $users = $wpdb->get_results("SELECT * FROM $wpdb->users");
  327. foreach ( $users as $user ) :
  328. if ( !empty( $user->user_firstname ) )
  329. update_usermeta( $user->ID, 'first_name', $wpdb->escape($user->user_firstname) );
  330. if ( !empty( $user->user_lastname ) )
  331. update_usermeta( $user->ID, 'last_name', $wpdb->escape($user->user_lastname) );
  332. if ( !empty( $user->user_nickname ) )
  333. update_usermeta( $user->ID, 'nickname', $wpdb->escape($user->user_nickname) );
  334. if ( !empty( $user->user_level ) )
  335. update_usermeta( $user->ID, $wpdb->prefix . 'user_level', $user->user_level );
  336. if ( !empty( $user->user_icq ) )
  337. update_usermeta( $user->ID, 'icq', $wpdb->escape($user->user_icq) );
  338. if ( !empty( $user->user_aim ) )
  339. update_usermeta( $user->ID, 'aim', $wpdb->escape($user->user_aim) );
  340. if ( !empty( $user->user_msn ) )
  341. update_usermeta( $user->ID, 'msn', $wpdb->escape($user->user_msn) );
  342. if ( !empty( $user->user_yim ) )
  343. update_usermeta( $user->ID, 'yim', $wpdb->escape($user->user_icq) );
  344. if ( !empty( $user->user_description ) )
  345. update_usermeta( $user->ID, 'description', $wpdb->escape($user->user_description) );
  346. if ( isset( $user->user_idmode ) ):
  347. $idmode = $user->user_idmode;
  348. if ($idmode == 'nickname') $id = $user->user_nickname;
  349. if ($idmode == 'login') $id = $user->user_login;
  350. if ($idmode == 'firstname') $id = $user->user_firstname;
  351. if ($idmode == 'lastname') $id = $user->user_lastname;
  352. if ($idmode == 'namefl') $id = $user->user_firstname.' '.$user->user_lastname;
  353. if ($idmode == 'namelf') $id = $user->user_lastname.' '.$user->user_firstname;
  354. if (!$idmode) $id = $user->user_nickname;
  355. $id = $wpdb->escape( $id );
  356. $wpdb->query("UPDATE $wpdb->users SET display_name = '$id' WHERE ID = '$user->ID'");
  357. endif;
  358. // FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set.
  359. $caps = get_usermeta( $user->ID, $wpdb->prefix . 'capabilities');
  360. if ( empty($caps) || defined('RESET_CAPS') ) {
  361. $level = get_usermeta($user->ID, $wpdb->prefix . 'user_level');
  362. $role = translate_level_to_role($level);
  363. update_usermeta( $user->ID, $wpdb->prefix . 'capabilities', array($role => true) );
  364. }
  365. endforeach;
  366. $old_user_fields = array( 'user_firstname', 'user_lastname', 'user_icq', 'user_aim', 'user_msn', 'user_yim', 'user_idmode', 'user_ip', 'user_domain', 'user_browser', 'user_description', 'user_nickname', 'user_level' );
  367. $wpdb->hide_errors();
  368. foreach ( $old_user_fields as $old )
  369. $wpdb->query("ALTER TABLE $wpdb->users DROP $old");
  370. $wpdb->show_errors();
  371. // populate comment_count field of posts table
  372. $comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
  373. if( is_array( $comments ) ) {
  374. foreach ($comments as $comment) {
  375. $wpdb->query( "UPDATE $wpdb->posts SET comment_count = $comment->c WHERE ID = '$comment->comment_post_ID'" );
  376. }
  377. }
  378. // Some alpha versions used a post status of object instead of attachment and put
  379. // the mime type in post_type instead of post_mime_type.
  380. if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
  381. $objects = $wpdb->get_results("SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'");
  382. foreach ($objects as $object) {
  383. $wpdb->query("UPDATE $wpdb->posts SET post_status = 'attachment',
  384. post_mime_type = '$object->post_type',
  385. post_type = ''
  386. WHERE ID = $object->ID");
  387. $meta = get_post_meta($object->ID, 'imagedata', true);
  388. if ( ! empty($meta['file']) )
  389. update_attached_file( $object->ID, $meta['file'] );
  390. }
  391. }
  392. }
  393. function upgrade_210() {
  394. global $wpdb, $wp_current_db_version;
  395. if ( $wp_current_db_version < 3506 ) {
  396. // Update status and type.
  397. $posts = $wpdb->get_results("SELECT ID, post_status FROM $wpdb->posts");
  398. if ( ! empty($posts) ) foreach ($posts as $post) {
  399. $status = $post->post_status;
  400. $type = 'post';
  401. if ( 'static' == $status ) {
  402. $status = 'publish';
  403. $type = 'page';
  404. } else if ( 'attachment' == $status ) {
  405. $status = 'inherit';
  406. $type = 'attachment';
  407. }
  408. $wpdb->query("UPDATE $wpdb->posts SET post_status = '$status', post_type = '$type' WHERE ID = '$post->ID'");
  409. }
  410. }
  411. if ( $wp_current_db_version < 3845 ) {
  412. populate_roles_210();
  413. }
  414. if ( $wp_current_db_version < 3531 ) {
  415. // Give future posts a post_status of future.
  416. $now = gmdate('Y-m-d H:i:59');
  417. $wpdb->query ("UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'");
  418. $posts = $wpdb->get_results("SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'");
  419. if ( !empty($posts) )
  420. foreach ( $posts as $post )
  421. wp_schedule_single_event(mysql2date('U', $post->post_date), 'publish_future_post', array($post->ID));
  422. }
  423. }
  424. function upgrade_230() {
  425. global $wp_current_db_version, $wpdb;
  426. if ( $wp_current_db_version < 5200 ) {
  427. populate_roles_230();
  428. }
  429. // Convert categories to terms.
  430. $tt_ids = array();
  431. $have_tags = false;
  432. $categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_ID");
  433. foreach ($categories as $category) {
  434. $term_id = (int) $category->cat_ID;
  435. $name = $wpdb->escape($category->cat_name);
  436. $description = $wpdb->escape($category->category_description);
  437. $slug = $wpdb->escape($category->category_nicename);
  438. $parent = $wpdb->escape($category->category_parent);
  439. $term_group = 0;
  440. // Associate terms with the same slug in a term group and make slugs unique.
  441. if ( $exists = $wpdb->get_results("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = '$slug'") ) {
  442. $term_group = $exists[0]->term_group;
  443. $id = $exists[0]->term_id;
  444. $num = 2;
  445. do {
  446. $alt_slug = $slug . "-$num";
  447. $num++;
  448. $slug_check = $wpdb->get_var("SELECT slug FROM $wpdb->terms WHERE slug = '$alt_slug'");
  449. } while ( $slug_check );
  450. $slug = $alt_slug;
  451. if ( empty( $term_group ) ) {
  452. $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group") + 1;
  453. $wpdb->query("UPDATE $wpdb->terms SET term_group = '$term_group' WHERE term_id = '$id'");
  454. }
  455. }
  456. $wpdb->query("INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES ('$term_id', '$name', '$slug', '$term_group')");
  457. $count = 0;
  458. if ( !empty($category->category_count) ) {
  459. $count = (int) $category->category_count;
  460. $taxonomy = 'category';
  461. $wpdb->query("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ('$term_id', '$taxonomy', '$description', '$parent', '$count')");
  462. $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
  463. }
  464. if ( !empty($category->link_count) ) {
  465. $count = (int) $category->link_count;
  466. $taxonomy = 'link_category';
  467. $wpdb->query("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ('$term_id', '$taxonomy', '$description', '$parent', '$count')");
  468. $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
  469. }
  470. if ( !empty($category->tag_count) ) {
  471. $have_tags = true;
  472. $count = (int) $category->tag_count;
  473. $taxonomy = 'post_tag';
  474. $wpdb->query("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ('$term_id', '$taxonomy', '$description', '$parent', '$count')");
  475. $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
  476. }
  477. if ( empty($count) ) {
  478. $count = 0;
  479. $taxonomy = 'category';
  480. $wpdb->query("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ('$term_id', '$taxonomy', '$description', '$parent', '$count')");
  481. $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
  482. }
  483. }
  484. $select = 'post_id, category_id';
  485. if ( $have_tags )
  486. $select .= ', rel_type';
  487. $posts = $wpdb->get_results("SELECT $select FROM $wpdb->post2cat GROUP BY post_id, category_id");
  488. foreach ( $posts as $post ) {
  489. $post_id = (int) $post->post_id;
  490. $term_id = (int) $post->category_id;
  491. $taxonomy = 'category';
  492. if ( !empty($post->rel_type) && 'tag' == $post->rel_type)
  493. $taxonomy = 'tag';
  494. $tt_id = $tt_ids[$term_id][$taxonomy];
  495. if ( empty($tt_id) )
  496. continue;
  497. $wpdb->query("INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id) VALUES ('$post_id', '$tt_id')");
  498. }
  499. // < 3570 we used linkcategories. >= 3570 we used categories and link2cat.
  500. if ( $wp_current_db_version < 3570 ) {
  501. // Create link_category terms for link categories. Create a map of link cat IDs
  502. // to link_category terms.
  503. $link_cat_id_map = array();
  504. $default_link_cat = 0;
  505. $tt_ids = array();
  506. $link_cats = $wpdb->get_results("SELECT cat_id, cat_name FROM " . $wpdb->prefix . 'linkcategories');
  507. foreach ( $link_cats as $category) {
  508. $cat_id = (int) $category->cat_id;
  509. $term_id = 0;
  510. $name = $wpdb->escape($category->cat_name);
  511. $slug = sanitize_title($name);
  512. $term_group = 0;
  513. // Associate terms with the same slug in a term group and make slugs unique.
  514. if ( $exists = $wpdb->get_results("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = '$slug'") ) {
  515. $term_group = $exists[0]->term_group;
  516. $term_id = $exists[0]->term_id;
  517. }
  518. if ( empty($term_id) ) {
  519. $wpdb->query("INSERT INTO $wpdb->terms (name, slug, term_group) VALUES ('$name', '$slug', '$term_group')");
  520. $term_id = (int) $wpdb->insert_id;
  521. }
  522. $link_cat_id_map[$cat_id] = $term_id;
  523. $default_link_cat = $term_id;
  524. $wpdb->query("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ('$term_id', 'link_category', '', '0', '0')");
  525. $tt_ids[$term_id] = (int) $wpdb->insert_id;
  526. }
  527. // Associate links to cats.
  528. $links = $wpdb->get_results("SELECT link_id, link_category FROM $wpdb->links");
  529. if ( !empty($links) ) foreach ( $links as $link ) {
  530. if ( 0 == $link->link_category )
  531. continue;
  532. if ( ! isset($link_cat_id_map[$link->link_category]) )
  533. continue;
  534. $term_id = $link_cat_id_map[$link->link_category];
  535. $tt_id = $tt_ids[$term_id];
  536. if ( empty($tt_id) )
  537. continue;
  538. $wpdb->query("INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id) VALUES ('$link->link_id', '$tt_id')");
  539. }
  540. // Set default to the last category we grabbed during the upgrade loop.
  541. update_option('default_link_category', $default_link_cat);
  542. } else {
  543. $links = $wpdb->get_results("SELECT link_id, category_id FROM $wpdb->link2cat GROUP BY link_id, category_id");
  544. foreach ( $links as $link ) {
  545. $link_id = (int) $link->link_id;
  546. $term_id = (int) $link->category_id;
  547. $taxonomy = 'link_category';
  548. $tt_id = $tt_ids[$term_id][$taxonomy];
  549. if ( empty($tt_id) )
  550. continue;
  551. $wpdb->query("INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id) VALUES ('$link_id', '$tt_id')");
  552. }
  553. }
  554. if ( $wp_current_db_version < 4772 ) {
  555. // Obsolete linkcategories table
  556. $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'linkcategories');
  557. }
  558. // Recalculate all counts
  559. $terms = $wpdb->get_results("SELECT term_taxonomy_id, taxonomy FROM $wpdb->term_taxonomy");
  560. foreach ( (array) $terms as $term ) {
  561. if ( ('post_tag' == $term->taxonomy) || ('category' == $term->taxonomy) )
  562. $count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type = 'post' AND term_taxonomy_id = '$term->term_taxonomy_id'");
  563. else
  564. $count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = '$term->term_taxonomy_id'");
  565. $wpdb->query("UPDATE $wpdb->term_taxonomy SET count = '$count' WHERE term_taxonomy_id = '$term->term_taxonomy_id'");
  566. }
  567. }
  568. function upgrade_230_options_table() {
  569. global $wpdb;
  570. $old_options_fields = array( 'option_can_override', 'option_type', 'option_width', 'option_height', 'option_description', 'option_admin_level' );
  571. $wpdb->hide_errors();
  572. foreach ( $old_options_fields as $old )
  573. $wpdb->query("ALTER TABLE $wpdb->options DROP $old");
  574. $wpdb->show_errors();
  575. }
  576. function upgrade_230_old_tables() {
  577. global $wpdb;
  578. $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'categories');
  579. $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'link2cat');
  580. $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'post2cat');
  581. }
  582. function upgrade_old_slugs() {
  583. // upgrade people who were using the Redirect Old Slugs plugin
  584. global $wpdb;
  585. $wpdb->query("UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'");
  586. }
  587. function upgrade_250() {
  588. global $wp_current_db_version;
  589. if ( $wp_current_db_version < 6689 ) {
  590. populate_roles_250();
  591. }
  592. }
  593. // The functions we use to actually do stuff
  594. // General
  595. function maybe_create_table($table_name, $create_ddl) {
  596. global $wpdb;
  597. foreach ($wpdb->get_col("SHOW TABLES",0) as $table ) {
  598. if ($table == $table_name) {
  599. return true;
  600. }
  601. }
  602. //didn't find it try to create it.
  603. $q = $wpdb->query($create_ddl);
  604. // we cannot directly tell that whether this succeeded!
  605. foreach ($wpdb->get_col("SHOW TABLES",0) as $table ) {
  606. if ($table == $table_name) {
  607. return true;
  608. }
  609. }
  610. return false;
  611. }
  612. function drop_index($table, $index) {
  613. global $wpdb;
  614. $wpdb->hide_errors();
  615. $wpdb->query("ALTER TABLE `$table` DROP INDEX `$index`");
  616. // Now we need to take out all the extra ones we may have created
  617. for ($i = 0; $i < 25; $i++) {
  618. $wpdb->query("ALTER TABLE `$table` DROP INDEX `{$index}_$i`");
  619. }
  620. $wpdb->show_errors();
  621. return true;
  622. }
  623. function add_clean_index($table, $index) {
  624. global $wpdb;
  625. drop_index($table, $index);
  626. $wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )");
  627. return true;
  628. }
  629. /**
  630. ** maybe_add_column()
  631. ** Add column to db table if it doesn't exist.
  632. ** Returns: true if already exists or on successful completion
  633. ** false on error
  634. */
  635. function maybe_add_column($table_name, $column_name, $create_ddl) {
  636. global $wpdb, $debug;
  637. foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
  638. if ($debug) echo("checking $column == $column_name<br />");
  639. if ($column == $column_name) {
  640. return true;
  641. }
  642. }
  643. //didn't find it try to create it.
  644. $q = $wpdb->query($create_ddl);
  645. // we cannot directly tell that whether this succeeded!
  646. foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
  647. if ($column == $column_name) {
  648. return true;
  649. }
  650. }
  651. return false;
  652. }
  653. // get_alloptions as it was for 1.2.
  654. function get_alloptions_110() {
  655. global $wpdb;
  656. if ($options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options")) {
  657. foreach ($options as $option) {
  658. // "When trying to design a foolproof system,
  659. // never underestimate the ingenuity of the fools :)" -- Dougal
  660. if ('siteurl' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
  661. if ('home' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
  662. if ('category_base' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
  663. $all_options->{$option->option_name} = stripslashes($option->option_value);
  664. }
  665. }
  666. return $all_options;
  667. }
  668. // Version of get_option that is private to install/upgrade.
  669. function __get_option($setting) {
  670. global $wpdb;
  671. if ( $setting == 'home' && defined( 'WP_HOME' ) ) {
  672. return preg_replace( '|/+$|', '', constant( 'WP_HOME' ) );
  673. }
  674. if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) ) {
  675. return preg_replace( '|/+$|', '', constant( 'WP_SITEURL' ) );
  676. }
  677. $option = $wpdb->get_var("SELECT option_value FROM $wpdb->options WHERE option_name = '$setting'");
  678. if ( 'home' == $setting && '' == $option )
  679. return __get_option('siteurl');
  680. if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting )
  681. $option = preg_replace('|/+$|', '', $option);
  682. @ $kellogs = unserialize($option);
  683. if ($kellogs !== FALSE)
  684. return $kellogs;
  685. else
  686. return $option;
  687. }
  688. function deslash($content) {
  689. // Note: \\\ inside a regex denotes a single backslash.
  690. // Replace one or more backslashes followed by a single quote with
  691. // a single quote.
  692. $content = preg_replace("/\\\+'/", "'", $content);
  693. // Replace one or more backslashes followed by a double quote with
  694. // a double quote.
  695. $content = preg_replace('/\\\+"/', '"', $content);
  696. // Replace one or more backslashes with one backslash.
  697. $content = preg_replace("/\\\+/", "\\", $content);
  698. return $content;
  699. }
  700. function dbDelta($queries, $execute = true) {
  701. global $wpdb;
  702. // Seperate individual queries into an array
  703. if( !is_array($queries) ) {
  704. $queries = explode( ';', $queries );
  705. if('' == $queries[count($queries) - 1]) array_pop($queries);
  706. }
  707. $cqueries = array(); // Creation Queries
  708. $iqueries = array(); // Insertion Queries
  709. $for_update = array();
  710. // Create a tablename index for an array ($cqueries) of queries
  711. foreach($queries as $qry) {
  712. if(preg_match("|CREATE TABLE ([^ ]*)|", $qry, $matches)) {
  713. $cqueries[strtolower($matches[1])] = $qry;
  714. $for_update[$matches[1]] = 'Created table '.$matches[1];
  715. }
  716. else if(preg_match("|CREATE DATABASE ([^ ]*)|", $qry, $matches)) {
  717. array_unshift($cqueries, $qry);
  718. }
  719. else if(preg_match("|INSERT INTO ([^ ]*)|", $qry, $matches)) {
  720. $iqueries[] = $qry;
  721. }
  722. else if(preg_match("|UPDATE ([^ ]*)|", $qry, $matches)) {
  723. $iqueries[] = $qry;
  724. }
  725. else {
  726. // Unrecognized query type
  727. }
  728. }
  729. // Check to see which tables and fields exist
  730. if($tables = $wpdb->get_col('SHOW TABLES;')) {
  731. // For every table in the database
  732. foreach($tables as $table) {
  733. // If a table query exists for the database table...
  734. if( array_key_exists(strtolower($table), $cqueries) ) {
  735. // Clear the field and index arrays
  736. unset($cfields);
  737. unset($indices);
  738. // Get all of the field names in the query from between the parens
  739. preg_match("|\((.*)\)|ms", $cqueries[strtolower($table)], $match2);
  740. $qryline = trim($match2[1]);
  741. // Separate field lines into an array
  742. $flds = explode("\n", $qryline);
  743. //echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."</pre><hr/>";
  744. // For every field line specified in the query
  745. foreach($flds as $fld) {
  746. // Extract the field name
  747. preg_match("|^([^ ]*)|", trim($fld), $fvals);
  748. $fieldname = $fvals[1];
  749. // Verify the found field name
  750. $validfield = true;
  751. switch(strtolower($fieldname))
  752. {
  753. case '':
  754. case 'primary':
  755. case 'index':
  756. case 'fulltext':
  757. case 'unique':
  758. case 'key':
  759. $validfield = false;
  760. $indices[] = trim(trim($fld), ", \n");
  761. break;
  762. }
  763. $fld = trim($fld);
  764. // If it's a valid field, add it to the field array
  765. if($validfield) {
  766. $cfields[strtolower($fieldname)] = trim($fld, ", \n");
  767. }
  768. }
  769. // Fetch the table column structure from the database
  770. $tablefields = $wpdb->get_results("DESCRIBE {$table};");
  771. // For every field in the table
  772. foreach($tablefields as $tablefield) {
  773. // If the table field exists in the field array...
  774. if(array_key_exists(strtolower($tablefield->Field), $cfields)) {
  775. // Get the field type from the query
  776. preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches);
  777. $fieldtype = $matches[1];
  778. // Is actual field type different from the field type in query?
  779. if($tablefield->Type != $fieldtype) {
  780. // Add a query to change the column type
  781. $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)];
  782. $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
  783. }
  784. // Get the default value from the array
  785. //echo "{$cfields[strtolower($tablefield->Field)]}<br>";
  786. if(preg_match("| DEFAULT '(.*)'|i", $cfields[strtolower($tablefield->Field)], $matches)) {
  787. $default_value = $matches[1];
  788. if($tablefield->Default != $default_value)
  789. {
  790. // Add a query to change the column's default value
  791. $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'";
  792. $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
  793. }
  794. }
  795. // Remove the field from the array (so it's not added)
  796. unset($cfields[strtolower($tablefield->Field)]);
  797. }
  798. else {
  799. // This field exists in the table, but not in the creation queries?
  800. }
  801. }
  802. // For every remaining field specified for the table
  803. foreach($cfields as $fieldname => $fielddef) {
  804. // Push a query line into $cqueries that adds the field to that table
  805. $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
  806. $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
  807. }
  808. // Index stuff goes here
  809. // Fetch the table index structure from the database
  810. $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
  811. if($tableindices) {
  812. // Clear the index array
  813. unset($index_ary);
  814. // For every index in the table
  815. foreach($tableindices as $tableindex) {
  816. // Add the index to the index data array
  817. $keyname = $tableindex->Key_name;
  818. $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
  819. $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
  820. }
  821. // For each actual index in the index array
  822. foreach($index_ary as $index_name => $index_data) {
  823. // Build a create string to compare to the query
  824. $index_string = '';
  825. if($index_name == 'PRIMARY') {
  826. $index_string .= 'PRIMARY ';
  827. }
  828. else if($index_data['unique']) {
  829. $index_string .= 'UNIQUE ';
  830. }
  831. $index_string .= 'KEY ';
  832. if($index_name != 'PRIMARY') {
  833. $index_string .= $index_name;
  834. }
  835. $index_columns = '';
  836. // For each column in the index
  837. foreach($index_data['columns'] as $column_data) {
  838. if($index_columns != '') $index_columns .= ',';
  839. // Add the field to the column list string
  840. $index_columns .= $column_data['fieldname'];
  841. if($column_data['subpart'] != '') {
  842. $index_columns .= '('.$column_data['subpart'].')';
  843. }
  844. }
  845. // Add the column list to the index create string
  846. $index_string .= ' ('.$index_columns.')';
  847. if(!(($aindex = array_search($index_string, $indices)) === false)) {
  848. unset($indices[$aindex]);
  849. //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br />Found index:".$index_string."</pre>\n";
  850. }
  851. //else echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br /><b>Did not find index:</b>".$index_string."<br />".print_r($indices, true)."</pre>\n";
  852. }
  853. }
  854. // For every remaining index specified for the table
  855. foreach ( (array) $indices as $index ) {
  856. // Push a query line into $cqueries that adds the index to that table
  857. $cqueries[] = "ALTER TABLE {$table} ADD $index";
  858. $for_update[$table.'.'.$fieldname] = 'Added index '.$table.' '.$index;
  859. }
  860. // Remove the original table creation query from processing
  861. unset($cqueries[strtolower($table)]);
  862. unset($for_update[strtolower($table)]);
  863. } else {
  864. // This table exists in the database, but not in the creation queries?
  865. }
  866. }
  867. }
  868. $allqueries = array_merge($cqueries, $iqueries);
  869. if($execute) {
  870. foreach($allqueries as $query) {
  871. //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($query, true)."</pre>\n";
  872. $wpdb->query($query);
  873. }
  874. }
  875. return $for_update;
  876. }
  877. function make_db_current() {
  878. global $wp_queries;
  879. $alterations = dbDelta($wp_queries);
  880. echo "<ol>\n";
  881. foreach($alterations as $alteration) echo "<li>$alteration</li>\n";
  882. echo "</ol>\n";
  883. }
  884. function make_db_current_silent() {
  885. global $wp_queries;
  886. $alterations = dbDelta($wp_queries);
  887. }
  888. function make_site_theme_from_oldschool($theme_name, $template) {
  889. $home_path = get_home_path();
  890. $site_dir = ABSPATH . "wp-content/themes/$template";
  891. if (! file_exists("$home_path/index.php"))
  892. return false;
  893. // Copy files from the old locations to the site theme.
  894. // TODO: This does not copy arbitarary include dependencies. Only the
  895. // standard WP files are copied.
  896. $files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php');
  897. foreach ($files as $oldfile => $newfile) {
  898. if ($oldfile == 'index.php')
  899. $oldpath = $home_path;
  900. else
  901. $oldpath = ABSPATH;
  902. if ($oldfile == 'index.php') { // Check to make sure it's not a new index
  903. $index = implode('', file("$oldpath/$oldfile"));
  904. if (strpos($index, 'WP_USE_THEMES') !== false) {
  905. if (! @copy(ABSPATH . 'wp-content/themes/default/index.php', "$site_dir/$newfile"))
  906. return false;
  907. continue; // Don't copy anything
  908. }
  909. }
  910. if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile"))
  911. return false;
  912. chmod("$site_dir/$newfile", 0777);
  913. // Update the blog header include in each file.
  914. $lines = explode("\n", implode('', file("$site_dir/$newfile")));
  915. if ($lines) {
  916. $f = fopen("$site_dir/$newfile", 'w');
  917. foreach ($lines as $line) {
  918. if (preg_match('/require.*wp-blog-header/', $line))
  919. $line = '//' . $line;
  920. // Update stylesheet references.
  921. $line = str_replace("<?php echo __get_option('siteurl'); ?>/wp-layout.css", "<?php bloginfo('stylesheet_url'); ?>", $line);
  922. // Update comments template inclusion.
  923. $line = str_replace("<?php include(ABSPATH . 'wp-comments.php'); ?>", "<?php comments_template(); ?>", $line);
  924. fwrite($f, "{$line}\n");
  925. }
  926. fclose($f);
  927. }
  928. }
  929. // Add a theme header.
  930. $header = "/*\nTheme Name: $theme_name\nTheme URI: " . __get_option('siteurl') . "\nDescription: A theme automatically created by the upgrade.\nVersion: 1.0\nAuthor: Moi\n*/\n";
  931. $stylelines = file_get_contents("$site_dir/style.css");
  932. if ($stylelines) {
  933. $f = fopen("$site_dir/style.css", 'w');
  934. fwrite($f, $header);
  935. fwrite($f, $stylelines);
  936. fclose($f);
  937. }
  938. return true;
  939. }
  940. function make_site_theme_from_default($theme_name, $template) {
  941. $site_dir = ABSPATH . "wp-content/themes/$template";
  942. $default_dir = ABSPATH . 'wp-content/themes/default';
  943. // Copy files from the default theme to the site theme.
  944. //$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css');
  945. $theme_dir = @ opendir("$default_dir");
  946. if ($theme_dir) {
  947. while(($theme_file = readdir( $theme_dir )) !== false) {
  948. if (is_dir("$default_dir/$theme_file"))
  949. continue;
  950. if (! @copy("$default_dir/$theme_file", "$site_dir/$theme_file"))
  951. return;
  952. chmod("$site_dir/$theme_file", 0777);
  953. }
  954. }
  955. @closedir($theme_dir);
  956. // Rewrite the theme header.
  957. $stylelines = explode("\n", implode('', file("$site_dir/style.css")));
  958. if ($stylelines) {
  959. $f = fopen("$site_dir/style.css", 'w');
  960. foreach ($stylelines as $line) {
  961. if (strpos($line, 'Theme Name:') !== false) $line = 'Theme Name: ' . $theme_name;
  962. elseif (strpos($line, 'Theme URI:') !== false) $line = 'Theme URI: ' . __get_option('url');
  963. elseif (strpos($line, 'Description:') !== false) $line = 'Description: Your theme.';
  964. elseif (strpos($line, 'Version:') !== false) $line = 'Version: 1';
  965. elseif (strpos($line, 'Author:') !== false) $line = 'Author: You';
  966. fwrite($f, $line . "\n");
  967. }
  968. fclose($f);
  969. }
  970. // Copy the images.
  971. umask(0);
  972. if (! mkdir("$site_dir/images", 0777)) {
  973. return false;
  974. }
  975. $images_dir = @ opendir("$default_dir/images");
  976. if ($images_dir) {
  977. while(($image = readdir($images_dir)) !== false) {
  978. if (is_dir("$default_dir/images/$image"))
  979. continue;
  980. if (! @copy("$default_dir/images/$image", "$site_dir/images/$image"))
  981. return;
  982. chmod("$site_dir/images/$image", 0777);
  983. }
  984. }
  985. @closedir($images_dir);
  986. }
  987. // Create a site theme from the default theme.
  988. function make_site_theme() {
  989. // Name the theme after the blog.
  990. $theme_name = __get_option('blogname');
  991. $template = sanitize_title($theme_name);
  992. $site_dir = ABSPATH . "wp-content/themes/$template";
  993. // If the theme already exists, nothing to do.
  994. if ( is_dir($site_dir)) {
  995. return false;
  996. }
  997. // We must be able to write to the themes dir.
  998. if (! is_writable(ABSPATH . "wp-content/themes")) {
  999. return false;
  1000. }
  1001. umask(0);
  1002. if (! mkdir($site_dir, 0777)) {
  1003. return false;
  1004. }
  1005. if (file_exists(ABSPATH . 'wp-layout.css')) {
  1006. if (! make_site_theme_from_oldschool($theme_name, $template)) {
  1007. // TODO: rm -rf the site theme directory.
  1008. return false;
  1009. }
  1010. } else {
  1011. if (! make_site_theme_from_default($theme_name, $template))
  1012. // TODO: rm -rf the site theme directory.
  1013. return false;
  1014. }
  1015. // Make the new site theme active.
  1016. $current_template = __get_option('template');
  1017. if ($current_template == 'default') {
  1018. update_option('template', $template);
  1019. update_option('stylesheet', $template);
  1020. }
  1021. return $template;
  1022. }
  1023. function translate_level_to_role($level) {
  1024. switch ($level) {
  1025. case 10:
  1026. case 9:
  1027. case 8:
  1028. return 'administrator';
  1029. case 7:
  1030. case 6:
  1031. case 5:
  1032. return 'editor';
  1033. case 4:
  1034. case 3:
  1035. case 2:
  1036. return 'author';
  1037. case 1:
  1038. return 'contributor';
  1039. case 0:
  1040. return 'subscriber';
  1041. }
  1042. }
  1043. function wp_check_mysql_version() {
  1044. global $wpdb;
  1045. $result = $wpdb->check_database_version();
  1046. if ( is_wp_error( $result ) )
  1047. die( $result->get_error_message() );
  1048. }
  1049. function maybe_disable_automattic_widgets() {
  1050. $plugins = __get_option( 'active_plugins' );
  1051. foreach ( (array) $plugins as $plugin ) {
  1052. if ( basename( $plugin ) == 'widgets.php' ) {
  1053. array_splice( $plugins, array_search( $plugin, $plugins ), 1 );
  1054. update_option( 'active_plugins', $plugins );
  1055. break;
  1056. }
  1057. }
  1058. }
  1059. ?>