| 1 |
<?php |
| 2 |
if (!defined('ABSPATH')) exit; |
| 3 |
|
| 4 |
function user_notes_run_migration_if_needed() { |
| 5 |
if (get_option('user_notes_db_version') === user_notes_version()) return; |
| 6 |
|
| 7 |
global $wpdb; |
| 8 |
|
| 9 |
// Pick lowest-ID admin/super-admin as author for migrated notes. |
| 10 |
$author_id = user_notes_pick_migration_author(); |
| 11 |
$now = current_time('mysql'); |
| 12 |
|
| 13 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-time activation migration across all users. |
| 14 |
$rows = $wpdb->get_results($wpdb->prepare( |
| 15 |
"SELECT user_id, meta_value FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value <> ''", |
| 16 |
'user-notes-note' |
| 17 |
)); |
| 18 |
|
| 19 |
if ($rows) { |
| 20 |
foreach ($rows as $row) { |
| 21 |
$body = user_notes_html_to_plaintext($row->meta_value); |
| 22 |
if ($body === '') continue; |
| 23 |
User_Notes_Repo::insert((int) $row->user_id, (int) $author_id, $body, 0, $now); |
| 24 |
// Keep original HTML in a backup meta so nothing is lost. |
| 25 |
update_user_meta((int) $row->user_id, '_user-notes-note-legacy-v1', $row->meta_value); |
| 26 |
delete_user_meta((int) $row->user_id, 'user-notes-note'); |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
update_option('user_notes_db_version', user_notes_version()); |
| 31 |
} |
| 32 |
|
| 33 |
function user_notes_html_to_plaintext($html) { |
| 34 |
$s = (string) $html; |
| 35 |
// Turn block/line-break tags into newlines before stripping. |
| 36 |
$s = preg_replace('#<br\s*/?>#i', "\n", $s); |
| 37 |
$s = preg_replace('#</(p|div|li|h[1-6]|tr|blockquote)>#i', "\n\n", $s); |
| 38 |
$s = wp_strip_all_tags($s); |
| 39 |
$s = html_entity_decode($s, ENT_QUOTES | ENT_HTML5, get_bloginfo('charset')); |
| 40 |
// Collapse 3+ newlines to 2, trim lines and whole string. |
| 41 |
$s = preg_replace("/\n{3,}/", "\n\n", $s); |
| 42 |
$s = preg_replace("/[ \t]+\n/", "\n", $s); |
| 43 |
return trim($s); |
| 44 |
} |
| 45 |
|
| 46 |
function user_notes_pick_migration_author() { |
| 47 |
global $wpdb; |
| 48 |
|
| 49 |
// Super admins first (multisite). |
| 50 |
if (is_multisite()) { |
| 51 |
$supers = get_super_admins(); |
| 52 |
if (!empty($supers)) { |
| 53 |
$ids = array(); |
| 54 |
foreach ($supers as $login) { |
| 55 |
$u = get_user_by('login', $login); |
| 56 |
if ($u) $ids[] = (int) $u->ID; |
| 57 |
} |
| 58 |
if ($ids) return min($ids); |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
$admins = get_users(array( |
| 63 |
'role' => 'administrator', |
| 64 |
'fields' => 'ID', |
| 65 |
'orderby' => 'ID', |
| 66 |
'order' => 'ASC', |
| 67 |
'number' => 1, |
| 68 |
)); |
| 69 |
if (!empty($admins)) return (int) $admins[0]; |
| 70 |
|
| 71 |
return 0; |
| 72 |
} |
| 73 |
|