Project

General

Profile

Bug #12203 » dedupe-blogmeta.php

Boone Gorges, 2019-12-10 10:54 AM

 
1
<?php
2

    
3
global $wpdb, $bp;
4

    
5
$blog_ids = $wpdb->get_col( "SELECT DISTINCT blog_id FROM {$bp->blogs->table_name_blogmeta}" );
6

    
7
$has_dupes = [];
8
foreach ( $blog_ids as $blog_id ) {
9
	$blog_metas = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$bp->blogs->table_name_blogmeta} WHERE blog_id = %d", $blog_id ) );
10

    
11
	$blog_meta_ids = [];
12
	foreach ( $blog_metas as $blog_meta ) {
13
		$key   = $blog_meta->meta_key;
14
		$value = $blog_meta->meta_value;
15
		if ( ! isset( $blog_meta_ids[ $key ][ $value ] ) ) {
16
			$blog_meta_ids[ $key ][ $value ] = 0;
17
		}
18

    
19
		$blog_meta_ids[ $key ][ $value ]++;
20
	}
21

    
22
	foreach ( $blog_meta_ids as $the_key => $values ) {
23
		foreach ( $values as $value => $count ) {
24
			if ( $count > 1 ) {
25
				$has_dupes[ $blog_id ][] = $the_key;
26
				break;
27
			}
28
		}
29
	}
30
}
31

    
32
foreach ( $has_dupes as $blog_id => $dupe_keys ) {
33
	foreach ( $dupe_keys as $dupe_key ) {
34
		$dupe_ids = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM {$bp->blogs->table_name_blogmeta} WHERE blog_id = %d and meta_key = %s LIMIT 1, 1000", $blog_id, $dupe_key ) );
35

    
36
		$dupe_ids_sql = implode( ',', array_map( 'intval', $dupe_ids ) );
37

    
38
		$wpdb->query( "DELETE FROM {$bp->blogs->table_name_blogmeta} WHERE id in ({$dupe_ids_sql})" );
39
	}
40
}
    (1-1/1)