|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * @package koko-analytics |
| 5 | + * @license GPL-3.0+ |
| 6 | + * @author Danny van Kooten |
| 7 | + */ |
| 8 | + |
| 9 | +namespace KokoAnalytics\Import; |
| 10 | + |
| 11 | +use DateTimeImmutable; |
| 12 | +use DateTimeZone; |
| 13 | +use Exception; |
| 14 | +use KokoAnalytics\Normalizers\Path; |
| 15 | +use KokoAnalytics\Normalizers\Referrer; |
| 16 | + |
| 17 | +class SlimStat_Importer extends Importer |
| 18 | +{ |
| 19 | + private const CHUNK_SIZE = 30; |
| 20 | + |
| 21 | + protected function get_admin_url(): string |
| 22 | + { |
| 23 | + return admin_url('options-general.php?page=koko-analytics-settings&tab=slimstat_importer'); |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * @return array{start: string, end: string}|null |
| 28 | + */ |
| 29 | + public function get_available_date_range(): ?array |
| 30 | + { |
| 31 | + /** @var \wpdb $wpdb */ |
| 32 | + global $wpdb; |
| 33 | + |
| 34 | + $tables = $this->get_source_tables(); |
| 35 | + if (count($tables) === 0) { |
| 36 | + return null; |
| 37 | + } |
| 38 | + |
| 39 | + $source = $this->build_source_query($tables); |
| 40 | + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared |
| 41 | + $range = $wpdb->get_row("SELECT MIN(dt) AS start, MAX(dt) AS end FROM ({$source}) slimstat_stats"); |
| 42 | + if (!$range || !$range->start || !$range->end) { |
| 43 | + return null; |
| 44 | + } |
| 45 | + |
| 46 | + return [ |
| 47 | + 'start' => gmdate('Y-m-d', (int) $range->start), |
| 48 | + 'end' => gmdate('Y-m-d', (int) $range->end), |
| 49 | + ]; |
| 50 | + } |
| 51 | + |
| 52 | + public function start_import(): void |
| 53 | + { |
| 54 | + if (!current_user_can('manage_koko_analytics') || !check_admin_referer('koko_analytics_start_slimstat_import')) { |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + if (count($this->get_source_tables()) === 0) { |
| 59 | + $this->redirect_with_error($this->get_admin_url(), __('Could not find the SlimStat Analytics database table.', 'koko-analytics')); |
| 60 | + exit; |
| 61 | + } |
| 62 | + |
| 63 | + $date_start = trim(wp_unslash($_POST['date-start'] ?? '')); |
| 64 | + $date_end = trim(wp_unslash($_POST['date-end'] ?? '')); |
| 65 | + if ($date_start === '' || $date_end === '') { |
| 66 | + $this->redirect_with_error($this->get_admin_url(), __('A required field was missing', 'koko-analytics')); |
| 67 | + exit; |
| 68 | + } |
| 69 | + |
| 70 | + try { |
| 71 | + $date_start = new DateTimeImmutable($date_start, wp_timezone()); |
| 72 | + $date_end = new DateTimeImmutable($date_end, wp_timezone()); |
| 73 | + if ($date_end < $date_start) { |
| 74 | + throw new Exception('End date must be after start date'); |
| 75 | + } |
| 76 | + } catch (Exception $e) { |
| 77 | + $this->redirect_with_error($this->get_admin_url(), __('Invalid date fields', 'koko-analytics')); |
| 78 | + exit; |
| 79 | + } |
| 80 | + |
| 81 | + $this->redirect($this->get_admin_url(), [ |
| 82 | + 'koko_analytics_action' => 'slimstat_import_chunk', |
| 83 | + 'date-start' => $date_start->format('Y-m-d'), |
| 84 | + 'date-end' => $date_end->format('Y-m-d'), |
| 85 | + '_wpnonce' => wp_create_nonce('koko_analytics_slimstat_import_chunk'), |
| 86 | + ]); |
| 87 | + } |
| 88 | + |
| 89 | + public function import_chunk(): void |
| 90 | + { |
| 91 | + if (!current_user_can('manage_koko_analytics')) { |
| 92 | + return; |
| 93 | + } |
| 94 | + |
| 95 | + check_admin_referer('koko_analytics_slimstat_import_chunk'); |
| 96 | + |
| 97 | + try { |
| 98 | + $date_start_value = trim(wp_unslash($_GET['date-start'] ?? '')); |
| 99 | + $date_end_value = trim(wp_unslash($_GET['date-end'] ?? '')); |
| 100 | + if ($date_start_value === '' || $date_end_value === '') { |
| 101 | + throw new Exception('Missing date fields'); |
| 102 | + } |
| 103 | + |
| 104 | + $date_start = new DateTimeImmutable($date_start_value, wp_timezone()); |
| 105 | + $date_end = new DateTimeImmutable($date_end_value, wp_timezone()); |
| 106 | + if ($date_end < $date_start) { |
| 107 | + throw new Exception('End date must be after start date'); |
| 108 | + } |
| 109 | + |
| 110 | + $chunk_end = $date_start->modify('+' . (self::CHUNK_SIZE - 1) . ' days'); |
| 111 | + if ($chunk_end > $date_end) { |
| 112 | + $chunk_end = $date_end; |
| 113 | + } |
| 114 | + |
| 115 | + $this->perform_chunk_import($date_start, $chunk_end); |
| 116 | + } catch (Exception $e) { |
| 117 | + $this->redirect_with_error($this->get_admin_url(), $e->getMessage()); |
| 118 | + exit; |
| 119 | + } |
| 120 | + |
| 121 | + $next_date_start = $chunk_end->modify('+1 day'); |
| 122 | + if ($next_date_start > $date_end) { |
| 123 | + $this->redirect($this->get_admin_url(), ['success' => 1]); |
| 124 | + exit; |
| 125 | + } |
| 126 | + |
| 127 | + $url = add_query_arg([ |
| 128 | + 'koko_analytics_action' => 'slimstat_import_chunk', |
| 129 | + 'date-start' => $next_date_start->format('Y-m-d'), |
| 130 | + 'date-end' => $date_end->format('Y-m-d'), |
| 131 | + '_wpnonce' => wp_create_nonce('koko_analytics_slimstat_import_chunk'), |
| 132 | + ]); |
| 133 | + |
| 134 | + $days_left = $next_date_start->diff($date_end)->days + 1; |
| 135 | + $chunks_left = (int) ceil($days_left / self::CHUNK_SIZE); |
| 136 | + ?> |
| 137 | + <style> |
| 138 | + body { |
| 139 | + background: #f0f0f1; |
| 140 | + color: #3c434a; |
| 141 | + font-family: sans-serif; |
| 142 | + font-size: 16px; |
| 143 | + line-height: 1.5; |
| 144 | + padding: 32px; |
| 145 | + } |
| 146 | + </style> |
| 147 | + <meta http-equiv="refresh" content="1; url=<?php echo esc_attr($url); ?>"> |
| 148 | + <h1><?php esc_html_e('Liberating your data... Please wait.', 'koko-analytics'); ?></h1> |
| 149 | + <p> |
| 150 | + <?php |
| 151 | + echo wp_kses(sprintf( |
| 152 | + /* translators: 1: import start date, 2: import end date. */ |
| 153 | + __('Imported stats between %1$s and %2$s.', 'koko-analytics'), |
| 154 | + '<strong>' . esc_html($date_start->format('Y-m-d')) . '</strong>', |
| 155 | + '<strong>' . esc_html($chunk_end->format('Y-m-d')) . '</strong>' |
| 156 | + ), ['strong' => []]); |
| 157 | + ?> |
| 158 | + </p> |
| 159 | + <p><?php esc_html_e('Please do not close this browser tab while the importer is running.', 'koko-analytics'); ?></p> |
| 160 | + <?php /* translators: %s: estimated number of seconds remaining. */ ?> |
| 161 | + <p><?php printf(esc_html__('Estimated time left: %s seconds.', 'koko-analytics'), esc_html((string) round($chunks_left * 1.5))); ?></p> |
| 162 | + <?php |
| 163 | + exit; |
| 164 | + } |
| 165 | + |
| 166 | + public function perform_chunk_import(DateTimeImmutable $date_start, DateTimeImmutable $date_end): void |
| 167 | + { |
| 168 | + @set_time_limit(90); |
| 169 | + |
| 170 | + /** @var \wpdb $wpdb */ |
| 171 | + global $wpdb; |
| 172 | + |
| 173 | + $tables = $this->get_source_tables(); |
| 174 | + if (count($tables) === 0) { |
| 175 | + throw new Exception(esc_html__('Could not find the SlimStat Analytics database table.', 'koko-analytics')); |
| 176 | + } |
| 177 | + |
| 178 | + $source = $this->build_source_query($tables); |
| 179 | + $site_stats = []; |
| 180 | + $utc = new DateTimeZone('UTC'); |
| 181 | + $date = new DateTimeImmutable($date_start->format('Y-m-d'), $utc); |
| 182 | + $last_date = new DateTimeImmutable($date_end->format('Y-m-d'), $utc); |
| 183 | + |
| 184 | + while ($date <= $last_date) { |
| 185 | + $next_date = $date->modify('+1 day'); |
| 186 | + $range = [$date->getTimestamp(), $next_date->getTimestamp()]; |
| 187 | + $date_key = $date->format('Y-m-d'); |
| 188 | + |
| 189 | + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared |
| 190 | + $site = $wpdb->get_row($wpdb->prepare("SELECT COUNT(*) AS pageviews, COUNT(DISTINCT NULLIF(ip, '')) AS visitors FROM ({$source}) slimstat_stats WHERE dt >= %d AND dt < %d AND visit_id > 0 AND COALESCE(browser_type, 0) <> 1", $range)); |
| 191 | + $this->throw_if_database_error(); |
| 192 | + |
| 193 | + if ($site && (int) $site->pageviews > 0) { |
| 194 | + $site_stats[] = [$date_key, (int) $site->visitors, (int) $site->pageviews]; |
| 195 | + } |
| 196 | + |
| 197 | + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared |
| 198 | + $pages = $wpdb->get_results($wpdb->prepare("SELECT resource, MAX(CASE WHEN content_type IN ('post', 'page') OR LEFT(content_type, 4) = 'cpt:' THEN content_id ELSE 0 END) AS post_id, COUNT(*) AS pageviews, COUNT(DISTINCT NULLIF(ip, '')) AS visitors FROM ({$source}) slimstat_stats WHERE dt >= %d AND dt < %d AND visit_id > 0 AND COALESCE(browser_type, 0) <> 1 AND resource IS NOT NULL AND resource != '' GROUP BY resource", $range)); |
| 199 | + $this->throw_if_database_error(); |
| 200 | + |
| 201 | + $page_stats = []; |
| 202 | + foreach ($pages as $page) { |
| 203 | + $page_stats[] = [$date_key, Path::normalize($page->resource), (int) $page->post_id, (int) $page->visitors, (int) $page->pageviews]; |
| 204 | + } |
| 205 | + $this->bulk_insert_page_stats($page_stats); |
| 206 | + |
| 207 | + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared |
| 208 | + $referrers = $wpdb->get_results($wpdb->prepare("SELECT referer, COUNT(*) AS pageviews, COUNT(DISTINCT NULLIF(ip, '')) AS visitors FROM ({$source}) slimstat_stats WHERE dt >= %d AND dt < %d AND visit_id > 0 AND COALESCE(browser_type, 0) <> 1 AND referer IS NOT NULL AND referer != '' GROUP BY referer", $range)); |
| 209 | + $this->throw_if_database_error(); |
| 210 | + |
| 211 | + $referrer_stats = []; |
| 212 | + foreach ($referrers as $referrer) { |
| 213 | + $value = Referrer::normalize($referrer->referer); |
| 214 | + if ($value !== '') { |
| 215 | + $referrer_stats[] = [$date_key, $value, (int) $referrer->visitors, (int) $referrer->pageviews]; |
| 216 | + } |
| 217 | + } |
| 218 | + $this->bulk_insert_referrer_stats($referrer_stats); |
| 219 | + |
| 220 | + $date = $next_date; |
| 221 | + } |
| 222 | + |
| 223 | + $this->bulk_insert_site_stats($site_stats); |
| 224 | + } |
| 225 | + |
| 226 | + /** |
| 227 | + * @return array<string> |
| 228 | + */ |
| 229 | + private function get_source_tables(): array |
| 230 | + { |
| 231 | + /** @var \wpdb $wpdb */ |
| 232 | + global $wpdb; |
| 233 | + |
| 234 | + $tables = []; |
| 235 | + foreach (['slim_stats', 'slim_stats_archive'] as $suffix) { |
| 236 | + $table = $wpdb->prefix . $suffix; |
| 237 | + if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table))) === $table) { |
| 238 | + $tables[] = $table; |
| 239 | + } |
| 240 | + } |
| 241 | + |
| 242 | + return $tables; |
| 243 | + } |
| 244 | + |
| 245 | + /** |
| 246 | + * @param array<string> $tables |
| 247 | + */ |
| 248 | + private function build_source_query(array $tables): string |
| 249 | + { |
| 250 | + return implode(' UNION ALL ', array_map(function (string $table): string { |
| 251 | + return "SELECT dt, ip, referer, resource, visit_id, browser_type, content_type, content_id FROM {$table}"; |
| 252 | + }, $tables)); |
| 253 | + } |
| 254 | + |
| 255 | + private function throw_if_database_error(): void |
| 256 | + { |
| 257 | + /** @var \wpdb $wpdb */ |
| 258 | + global $wpdb; |
| 259 | + |
| 260 | + if ($wpdb->last_error !== '') { |
| 261 | + throw new Exception(esc_html__("A database error occurred: ", 'koko-analytics') . esc_html(" {$wpdb->last_error}")); |
| 262 | + } |
| 263 | + } |
| 264 | +} |
0 commit comments