Make WordPress Core

source: trunk/wp-admin/upgrade-functions.php @ 1601

Last change on this file since 1601 was 1601, checked in by saxmatt, 21 years ago

Install and upgrade refactoring complete.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 18.5 KB
Line 
1<?php
2require_once('./upgrade-schema.php');
3// Functions to be called in install and upgrade scripts
4function upgrade_all() {
5        populate_options();
6        upgrade_100();
7        upgrade_101();
8        upgrade_110();
9        upgrade_130();
10}
11
12function upgrade_100() {
13        global $wpdb;
14
15        // Get the title and ID of every post, post_name to check if it already has a value
16        $posts = $wpdb->get_results("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''");
17        if ($posts) {
18                foreach($posts as $post) {
19                        if ('' == $post->post_name) { 
20                                $newtitle = sanitize_title($post->post_title);
21                                $wpdb->query("UPDATE $wpdb->posts SET post_name = '$newtitle' WHERE ID = '$post->ID'");
22                        }
23                }
24        }
25       
26        $categories = $wpdb->get_results("SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories");
27        foreach ($categories as $category) {
28                if ('' == $category->category_nicename) { 
29                        $newtitle = sanitize_title($category->cat_name);
30                        $wpdb->query("UPDATE $wpdb->categories SET category_nicename = '$newtitle' WHERE cat_ID = '$category->cat_ID'");
31                }
32        }
33
34
35        $wpdb->query("UPDATE $wpdb->options SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
36                                                      WHERE option_name LIKE 'links_rating_image%'
37                                                      AND option_value LIKE 'wp-links/links-images/%'");
38
39        $done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat");
40        if ($done_ids) :
41                foreach ($done_ids as $done_id) :
42                        $done_posts[] = $done_id->post_id;
43                endforeach;
44                $catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')';
45        else:
46                $catwhere = '';
47        endif;
48       
49        $allposts = $wpdb->get_results("SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere");
50        if ($allposts) :
51                foreach ($allposts as $post) {
52                        // Check to see if it's already been imported
53                        $cat = $wpdb->get_row("SELECT * FROM $wpdb->post2cat WHERE post_id = $post->ID AND category_id = $post->post_category");
54                        if (!$cat && 0 != $post->post_category) { // If there's no result
55                                $wpdb->query("
56                                        INSERT INTO $wpdb->post2cat
57                                        (post_id, category_id)
58                                        VALUES
59                                        ('$post->ID', '$post->post_category')
60                                        ");
61                        }
62                }
63        endif;
64}
65
66function upgrade_101() {
67        global $wpdb;
68
69        // Clean up indices, add a few
70        add_clean_index($wpdb->posts, 'post_name');
71        add_clean_index($wpdb->posts, 'post_status');
72        add_clean_index($wpdb->categories, 'category_nicename');
73        add_clean_index($wpdb->comments, 'comment_approved');
74        add_clean_index($wpdb->comments, 'comment_post_ID');
75        add_clean_index($wpdb->links , 'link_category');
76        add_clean_index($wpdb->links , 'link_visible');
77}
78
79
80function upgrade_110() {
81  global $wpdb;
82       
83    // Set user_nicename.
84        $users = $wpdb->get_results("SELECT ID, user_nickname, user_nicename FROM $wpdb->users");
85        foreach ($users as $user) {
86                if ('' == $user->user_nicename) { 
87                        $newname = sanitize_title($user->user_nickname);
88                        $wpdb->query("UPDATE $wpdb->users SET user_nicename = '$newname' WHERE ID = '$user->ID'");
89                }
90        }
91
92        // Convert passwords to MD5 and update table appropiately
93        $user_table = $wpdb->get_row("DESCRIBE $wpdb->users user_pass");
94        if ($user_table->Type != 'varchar(32)') {
95                $wpdb->query("ALTER TABLE $wpdb->users MODIFY user_pass varchar(64) not null");
96        }
97       
98        $query = 'SELECT ID, user_pass from '.$wpdb->users;
99        foreach ($wpdb->get_results($query) as $row) {
100                if (!preg_match('/^[A-Fa-f0-9]{32}$/', $row->user_pass)) {
101                           $wpdb->query('UPDATE '.$wpdb->users.' SET user_pass = MD5(\''.$row->user_pass.'\') WHERE ID = \''.$row->ID.'\'');
102                }
103        }
104
105
106        // Get the GMT offset, we'll use that later on
107        $all_options = get_alloptions_110();
108
109        $time_difference = $all_options->time_difference;
110
111        $server_time = time()+date('Z');
112        $weblogger_time = $server_time + $time_difference*3600;
113        $gmt_time = time();
114
115        $diff_gmt_server = ($gmt_time - $server_time) / 3600;
116        $diff_weblogger_server = ($weblogger_time - $server_time) / 3600;
117        $diff_gmt_weblogger = $diff_gmt_server - $diff_weblogger_server;
118        $gmt_offset = -$diff_gmt_weblogger;
119
120        // Add a gmt_offset option, with value $gmt_offset
121        add_option('gmt_offset', $gmt_offset);
122
123        // Check if we already set the GMT fields (if we did, then
124        // MAX(post_date_gmt) can't be '0000-00-00 00:00:00'
125        // <michel_v> I just slapped myself silly for not thinking about it earlier
126        $got_gmt_fields = ($wpdb->get_var("SELECT MAX(post_date_gmt) FROM $wpdb->posts") == '0000-00-00 00:00:00') ? false : true;
127
128        if (!$got_gmt_fields) {
129
130                // Add or substract time to all dates, to get GMT dates
131                $add_hours = intval($diff_gmt_weblogger);
132                $add_minutes = intval(60 * ($diff_gmt_weblogger - $add_hours));
133                $wpdb->query("UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
134                $wpdb->query("UPDATE $wpdb->posts SET post_modified = post_date");
135                $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'");
136                $wpdb->query("UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
137                $wpdb->query("UPDATE $wpdb->users SET dateYMDhour = DATE_ADD(dateYMDhour, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
138        }
139
140        // First we need to enlarge option_value so it can hold larger values:
141        $wpdb->query("ALTER TABLE `$wpdb->options` CHANGE `option_value` `option_value` TEXT NOT NULL");
142
143        $wpdb->query("ALTER TABLE `$wpdb->comments` CHANGE `comment_author_url` `comment_author_url` VARCHAR( 200 ) NOT NULL");
144}
145
146function upgrade_130() {
147    global $wpdb, $table_prefix;
148
149    // Remove extraneous backslashes.
150        $posts = $wpdb->get_results("SELECT ID, post_title, post_content, post_excerpt FROM $wpdb->posts");
151        if ($posts) {
152                foreach($posts as $post) {
153            $post_content = addslashes(deslash($post->post_content));
154            $post_title = addslashes(deslash($post->post_title));
155            $post_excerpt = addslashes(deslash($post->post_excerpt));
156            $wpdb->query("UPDATE $wpdb->posts SET post_title = '$post_title', post_content = '$post_content', post_excerpt = '$post_excerpt' WHERE ID = '$post->ID'");
157                }
158        }
159
160    // Remove extraneous backslashes.
161        $comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments");
162        if ($comments) {
163                foreach($comments as $comment) {
164            $comment_content = addslashes(deslash($comment->comment_content));
165            $comment_author = addslashes(deslash($comment->comment_author));
166            $wpdb->query("UPDATE $wpdb->comments SET comment_content = '$comment_content', comment_author = '$comment_author' WHERE comment_ID = '$comment->comment_ID'");
167                }
168        }
169
170    // Remove extraneous backslashes.
171        $links = $wpdb->get_results("SELECT link_id, link_name, link_description FROM $wpdb->links");
172        if ($links) {
173                foreach($links as $link) {
174            $link_name = addslashes(deslash($link->link_name));
175            $link_description = addslashes(deslash($link->link_description));
176            $wpdb->query("UPDATE $wpdb->links SET link_name = '$link_name', link_description = '$link_description' WHERE link_id = '$link->link_id'");
177                }
178        }
179
180    // The "paged" option for what_to_show is no more.
181    if ($wpdb->get_var("SELECT option_value FROM $wpdb->options WHERE option_name = 'what_to_show'") == 'paged') {
182        $wpdb->query("UPDATE $wpdb->options SET option_value = 'posts' WHERE option_name = 'what_to_show'");
183    }
184
185        if ( !is_array( get_settings('active_plugins') ) ) {
186                $plugins = explode("\n", trim(get_settings('active_plugins')) );
187                update_option('active_plugins', $plugins);
188        }
189
190        // Obsolete tables
191        $wpdb->query('DROP TABLE IF EXISTS ' . $table_prefix . 'optionvalues');
192        $wpdb->query('DROP TABLE IF EXISTS ' . $table_prefix . 'optiontypes');
193        $wpdb->query('DROP TABLE IF EXISTS ' . $table_prefix . 'optiongroups');
194        $wpdb->query('DROP TABLE IF EXISTS ' . $table_prefix . 'optiongroup_options');
195}
196
197// The functions we use to actually do stuff
198
199// General
200function maybe_create_table($table_name, $create_ddl) {
201    global $wpdb;
202    foreach ($wpdb->get_col("SHOW TABLES",0) as $table ) {
203        if ($table == $table_name) {
204            return true;
205        }
206    }
207    //didn't find it try to create it.
208    $q = $wpdb->query($create_ddl);
209    // we cannot directly tell that whether this succeeded!
210    foreach ($wpdb->get_col("SHOW TABLES",0) as $table ) {
211        if ($table == $table_name) {
212            return true;
213        }
214    }
215    return false;
216}
217
218function drop_index($table, $index) {
219        global $wpdb;
220        $wpdb->hide_errors();
221        $wpdb->query("ALTER TABLE `$table` DROP INDEX `$index`");
222        // Now we need to take out all the extra ones we may have created
223        for ($i = 0; $i < 25; $i++) {
224                $wpdb->query("ALTER TABLE `$table` DROP INDEX `{$index}_$i`");
225        }
226        $wpdb->show_errors();
227        return true;
228}
229
230function add_clean_index($table, $index) {
231        global $wpdb;
232        drop_index($table, $index);
233        $wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )");
234        return true;
235}
236
237/**
238 ** maybe_add_column()
239 ** Add column to db table if it doesn't exist.
240 ** Returns:  true if already exists or on successful completion
241 **           false on error
242 */
243function maybe_add_column($table_name, $column_name, $create_ddl) {
244    global $wpdb, $debug;
245    foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
246        if ($debug) echo("checking $column == $column_name<br />");
247        if ($column == $column_name) {
248            return true;
249        }
250    }
251    //didn't find it try to create it.
252    $q = $wpdb->query($create_ddl);
253    // we cannot directly tell that whether this succeeded!
254    foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
255        if ($column == $column_name) {
256            return true;
257        }
258    }
259    return false;
260}
261
262
263// get_alloptions as it was for 1.2.
264function get_alloptions_110() {
265        global $wpdb;
266        if ($options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options")) {
267                foreach ($options as $option) {
268                        // "When trying to design a foolproof system,
269                        //  never underestimate the ingenuity of the fools :)" -- Dougal
270                        if ('siteurl' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
271                        if ('home' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
272                        if ('category_base' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
273                        $all_options->{$option->option_name} = stripslashes($option->option_value);
274                }
275        }
276        return $all_options;
277}
278
279function deslash($content) {
280    // Note: \\\ inside a regex denotes a single backslash.
281
282    // Replace one or more backslashes followed by a single quote with
283    // a single quote.
284    $content = preg_replace("/\\\+'/", "'", $content);
285
286    // Replace one or more backslashes followed by a double quote with
287    // a double quote.
288    $content = preg_replace('/\\\+"/', '"', $content);
289
290    // Replace one or more backslashes with one backslash.
291    $content = preg_replace("/\\\+/", "\\", $content);
292
293    return $content;
294}
295
296function dbDelta($queries, $execute = true) {
297        global $wpdb;
298       
299        // Seperate individual queries into an array
300        if( !is_array($queries) ) {
301                $queries = explode( ';', $queries );
302                if('' == $queries[count($queries) - 1]) array_pop($queries);
303        }
304       
305        $cqueries = array(); // Creation Queries
306        $iqueries = array(); // Insertion Queries
307        $for_update = array();
308       
309        // Create a tablename index for an array ($cqueries) of queries
310        foreach($queries as $qry) {
311                if(preg_match("|CREATE TABLE ([^ ]*)|", $qry, $matches)) {
312                        $cqueries[strtolower($matches[1])] = $qry;
313                        $for_update[$matches[1]] = 'Created table '.$matches[1];
314                }
315                else if(preg_match("|CREATE DATABASE ([^ ]*)|", $qry, $matches)) {
316                        array_unshift($cqueries, $qry);
317                }
318                else if(preg_match("|INSERT INTO ([^ ]*)|", $qry, $matches)) {
319                        $iqueries[] = $qry;
320                }
321                else if(preg_match("|UPDATE ([^ ]*)|", $qry, $matches)) {
322                        $iqueries[] = $qry;
323                }
324                else {
325                        // Unrecognized query type
326                }
327        }       
328
329        // Check to see which tables and fields exist
330        if($tables = $wpdb->get_col('SHOW TABLES;')) {
331                // For every table in the database
332                foreach($tables as $table) {
333                        // If a table query exists for the database table...
334                        if( array_key_exists(strtolower($table), $cqueries) ) {
335                                // Clear the field and index arrays
336                                unset($cfields);
337                                unset($indices);
338                                // Get all of the field names in the query from between the parens
339                                preg_match("|\((.*)\)|ms", $cqueries[strtolower($table)], $match2);
340                                $qryline = trim($match2[1]);
341
342                                // Separate field lines into an array
343                                $flds = explode("\n", $qryline);
344
345                                //echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."</pre><hr/>";
346                               
347                                // For every field line specified in the query
348                                foreach($flds as $fld) {
349                                        // Extract the field name
350                                        preg_match("|^([^ ]*)|", trim($fld), $fvals);
351                                        $fieldname = $fvals[1];
352                                       
353                                        // Verify the found field name
354                                        $validfield = true;
355                                        switch(strtolower($fieldname))
356                                        {
357                                        case '':
358                                        case 'primary':
359                                        case 'index':
360                                        case 'fulltext':
361                                        case 'unique':
362                                        case 'key':
363                                                $validfield = false;
364                                                $indices[] = trim(trim($fld), ", \n");
365                                                break;
366                                        }
367                                        $fld = trim($fld);
368                                       
369                                        // If it's a valid field, add it to the field array
370                                        if($validfield) {
371                                                $cfields[strtolower($fieldname)] = trim($fld, ", \n");
372                                        }
373                                }
374                               
375                                // Fetch the table column structure from the database
376                                $tablefields = $wpdb->get_results("DESCRIBE {$table};");
377                                                               
378                                // For every field in the table
379                                foreach($tablefields as $tablefield) {                         
380                                        // If the table field exists in the field array...
381                                        if(array_key_exists(strtolower($tablefield->Field), $cfields)) {
382                                                // Get the field type from the query
383                                                preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches);
384                                                $fieldtype = $matches[1];
385
386                                                // Is actual field type different from the field type in query?
387                                                if($tablefield->Type != $fieldtype) {
388                                                        // Add a query to change the column type
389                                                        $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)];
390                                                        $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
391                                                }
392                                               
393                                                // Get the default value from the array
394                                                        //echo "{$cfields[strtolower($tablefield->Field)]}<br>";
395                                                if(preg_match("| DEFAULT '(.*)'|i", $cfields[strtolower($tablefield->Field)], $matches)) {
396                                                        $default_value = $matches[1];
397                                                        if($tablefield->Default != $default_value)
398                                                        {
399                                                                // Add a query to change the column's default value
400                                                                $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'";
401                                                                $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
402                                                        }
403                                                }
404
405                                                // Remove the field from the array (so it's not added)
406                                                unset($cfields[strtolower($tablefield->Field)]);
407                                        }
408                                        else {
409                                                // This field exists in the table, but not in the creation queries?
410                                        }
411                                }
412
413                                // For every remaining field specified for the table
414                                foreach($cfields as $fieldname => $fielddef) {
415                                        // Push a query line into $cqueries that adds the field to that table
416                                        $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
417                                        $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
418                                }
419                               
420                                // Index stuff goes here
421                                // Fetch the table index structure from the database
422                                $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
423                               
424                                if($tableindices) {
425                                        // Clear the index array
426                                        unset($index_ary);
427
428                                        // For every index in the table
429                                        foreach($tableindices as $tableindex) {
430                                                // Add the index to the index data array
431                                                $keyname = $tableindex->Key_name;
432                                                $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
433                                                $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
434                                        }
435
436                                        // For each actual index in the index array
437                                        foreach($index_ary as $index_name => $index_data) {
438                                                // Build a create string to compare to the query
439                                                $index_string = '';
440                                                if($index_name == 'PRIMARY') {
441                                                        $index_string .= 'PRIMARY ';
442                                                }
443                                                else if($index_data['unique']) {
444                                                        $index_string .= 'UNIQUE ';
445                                                }
446                                                $index_string .= 'KEY ';
447                                                if($index_name != 'PRIMARY') {
448                                                        $index_string .= $index_name;
449                                                }
450                                                $index_columns = '';
451                                                // For each column in the index
452                                                foreach($index_data['columns'] as $column_data) {                                       
453                                                        if($index_columns != '') $index_columns .= ',';
454                                                        // Add the field to the column list string
455                                                        $index_columns .= $column_data['fieldname'];
456                                                        if($column_data['subpart'] != '') {
457                                                                $index_columns .= '('.$column_data['subpart'].')';
458                                                        }
459                                                }
460                                                // Add the column list to the index create string
461                                                $index_string .= ' ('.$index_columns.')';
462
463                                                if(!(($aindex = array_search($index_string, $indices)) === false)) {
464                                                        unset($indices[$aindex]);
465                                                        //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br/>Found index:".$index_string."</pre>\n";
466                                                }
467                                                //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";
468                                        }
469                                }
470
471                                // For every remaining index specified for the table
472                                foreach($indices as $index) {
473                                        // Push a query line into $cqueries that adds the index to that table
474                                        $cqueries[] = "ALTER TABLE {$table} ADD $index";
475                                        $for_update[$table.'.'.$fieldname] = 'Added index '.$table.' '.$index;
476                                }
477
478                                // Remove the original table creation query from processing
479                                unset($cqueries[strtolower($table)]);
480                                unset($for_update[strtolower($table)]);
481                        } else {
482                                // This table exists in the database, but not in the creation queries?
483                        }
484                }
485        }
486
487        $allqueries = array_merge($cqueries, $iqueries);
488        if($execute) {
489                foreach($allqueries as $query) {
490                        //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($query, true)."</pre>\n";
491                        $wpdb->query($query);
492                }
493        }
494
495        return $for_update;
496}
497
498function make_db_current() {
499        global $wp_queries;
500
501        $alterations = dbDelta($wp_queries);
502        echo "<ol>\n";
503        foreach($alterations as $alteration) echo "<li>$alteration</li>\n";
504        echo "</ol>\n";
505}
506
507function make_db_current_silent() {
508        global $wp_queries;
509
510        $alterations = dbDelta($wp_queries);
511}
512
513?>
Note: See TracBrowser for help on using the repository browser.