mansj / enable-media-replace

***DEVELOPMENT DISCONTINUED*** Enable Media Replace, a WordPress plugin to make it possible to replace uploaded media files in a simple way.
GNU General Public License v2.0
28 stars 27 forks source link

Incorrect use of GUIDs during search and replacement #21

Open DaveMatl opened 7 years ago

DaveMatl commented 7 years ago

Thanks for the must-use plugin. I've had an instance where the post content wasn't updated for a specific post that contained a link to the old media file that was replaced. Looking at the code, I believe it's due to the search criteria $current_guid. Because the GUID represents the URL at a point in time, it's not always the current URL. Further, the current URL could be a relative URL, which would be missed.

It would seem the proper solution would be to look for either full URL matches to the old media file's current URL, AND relative URLs to the old media's URL. The GUID attribute should not be used.

See https://codex.wordpress.org/Changing_The_Site_URL#Important_GUID_Note for more information.

                // Search-and-replace filename in post database
                $sql = $wpdb->prepare(
                        "SELECT ID, post_content FROM $table_name WHERE post_content LIKE %s;",
                        '%' . $current_guid . '%'
                );

                $rs = $wpdb->get_results($sql, ARRAY_A);

                foreach($rs AS $rows) {

                        // replace old guid with new guid
                        $post_content = $rows["post_content"];
                        $post_content = addslashes(str_replace($current_guid, $new_guid, $post_content));

                        $sql = $wpdb->prepare(
                                "UPDATE $table_name SET post_content = '$post_content' WHERE ID = %d;",
                                $rows["ID"]
                        );

                        $wpdb->query($sql);
                }