<?php

/*
Plugin Name: CF GUID Fix 
Plugin URI: http://crowdfavorite.com/wordpress/plugins/cf-guid-fix/ 
Description: Correct duplicate GUID values created with versions of WordPress that exhibited a <a href="http://core.trac.wordpress.org/ticket/15041">non-unique GUID bug</a>.
Version: 1.0 
Author: Crowd Favorite
Author URI: http://crowdfavorite.com
*/

function cf_guid_fix_admin_init() {
	if (isset($_GET['cf_action'])) {
		switch ($_GET['cf_action']) {
			case 'guid-fix':
				cf_guid_fix();
				wp_die('Post GUIDs should be unique now.');
			break;
		}
	}
}
add_action('admin_init', 'cf_guid_fix_admin_init');

function cf_guid_fix() {
	global $wpdb;

// add index on GUID column
	$wpdb->query("
		ALTER TABLE $wpdb->posts
		ADD INDEX (guid)
	");

// find non-unique GUID values

// NOTE: not including revisions since that's a whole other mess to 
// try to get the numbering right if we change the GUID

// this gets the GUIDs
// 		SELECT guid
// 		FROM $wpdb->posts
// 		WHERE post_type != 'revision'
// 		GROUP BY guid
// 		HAVING COUNT(guid) > 1

// WORKS - but is very slow
// 		SELECT ID
// 		FROM $wpdb->posts
// 		WHERE guid IN (
// 			SELECT guid
// 			FROM $wpdb->posts
// 			WHERE post_type != 'revision'
// 			GROUP BY guid
// 			HAVING COUNT(guid) > 1
// 		)
// 		AND post_type != 'revision'

	$non_unique_guids = $wpdb->get_col($wpdb->prepare("
		SELECT p1.ID
		FROM $wpdb->posts p1
		WHERE 1 < (
			SELECT COUNT(ID) 
			FROM $wpdb->posts p2 
			WHERE p1.post_type != 'revision'
			AND p1.guid = p2.guid
		)
		AND p1.post_type != 'revision'
	"));

// make them unique

	if (count($non_unique_guids)) {
		foreach ($non_unique_guids as $post_id) {
			$url = site_url('?p='.$post_id);
			$wpdb->query($wpdb->prepare("
				UPDATE $wpdb->posts
				SET guid = %s
				WHERE ID = %d
			", $url, $post_id));
		}
	}

// remove index from GUID column
	$wpdb->query("
		ALTER TABLE $wpdb->posts
		DROP INDEX guid
	");

}
