|null */ public static function state(): ?array { $state = get_option( self::STATE_OPTION ); return is_array( $state ) ? $state : null; } /** * アップロードを受け付けて取り込みを開始する(admin_postハンドラ)。 */ public static function handle_upload(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Insufficient permissions.', 'ailys-lens' ) ); } check_admin_referer( 'ailens_import_upload' ); $file = $_FILES['ailens_log'] ?? null; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- 直後に個別検証。 if ( ! is_array( $file ) || ! isset( $file['error'] ) ) { self::redirect( 'error', __( 'No file was uploaded.', 'ailys-lens' ) ); } if ( UPLOAD_ERR_OK !== (int) $file['error'] ) { self::redirect( 'error', self::upload_error_message( (int) $file['error'] ) ); } if ( ! is_uploaded_file( $file['tmp_name'] ) ) { self::redirect( 'error', __( 'Invalid upload.', 'ailys-lens' ) ); } if ( null !== self::state() ) { self::redirect( 'error', __( 'An import is already in progress. Continue or cancel it first.', 'ailys-lens' ) ); } $dir = self::working_dir(); if ( null === $dir ) { self::redirect( 'error', __( 'Could not create the working directory.', 'ailys-lens' ) ); } // 推測困難な64文字ランダム名+非実行拡張子(ファイル冒頭の設計方針参照)。 $dest = $dir . '/import-' . bin2hex( random_bytes( 32 ) ) . '.log'; $stored = self::store_as_plain_text( (string) $file['tmp_name'], $dest ); if ( null !== $stored ) { self::redirect( 'error', $stored ); } update_option( self::STATE_OPTION, array( 'file' => $dest, 'orig_name' => sanitize_file_name( (string) ( $file['name'] ?? 'access.log' ) ), 'offset' => 0, 'total_bytes' => (int) filesize( $dest ), 'lines' => 0, 'imported' => 0, 'skipped' => 0, 'min_date' => null, 'started_at' => time(), ), false ); // 最初のバッチをその場で処理する。 self::handle_process_internal(); } /** * 「続行」ボタン(admin_postハンドラ)。 */ public static function handle_process(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Insufficient permissions.', 'ailys-lens' ) ); } check_admin_referer( 'ailens_import_process' ); self::handle_process_internal(); } /** * 「中止」ボタン(admin_postハンドラ)。 */ public static function handle_cancel(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Insufficient permissions.', 'ailys-lens' ) ); } check_admin_referer( 'ailens_import_cancel' ); $state = self::state(); if ( null !== $state && is_string( $state['file'] ?? null ) && file_exists( $state['file'] ) ) { wp_delete_file( $state['file'] ); } delete_option( self::STATE_OPTION ); self::redirect( 'notice', __( 'Import cancelled.', 'ailys-lens' ) ); } /** * 1バッチ処理して結果に応じてリダイレクトする。 */ private static function handle_process_internal(): void { $state = self::state(); if ( null === $state ) { self::redirect( 'error', __( 'No import in progress.', 'ailys-lens' ) ); } try { $state = self::process_batch( $state ); } catch ( \Throwable $e ) { self::redirect( 'error', __( 'Import failed: ', 'ailys-lens' ) . $e->getMessage() ); } if ( ! empty( $state['done'] ) ) { /* translators: 1: inserted rows, 2: skipped (duplicate/invalid) count. */ self::redirect( 'notice', sprintf( __( 'Import finished: %1$s hits imported, %2$s lines skipped (non-AI, invalid, or duplicate).', 'ailys-lens' ), number_format_i18n( (int) $state['imported'] ), number_format_i18n( (int) $state['skipped'] ) ) ); } self::redirect( 'notice', '' ); // 進捗はstateから設定画面が描画する。 } /** * 1バッチ(最大BATCH_LINES行/BATCH_SECS秒)を処理し、更新後のstateを返す。 * * 設定画面以外(WP-CLI・テスト)からも呼べるようにpublic。 * * @param array $state 現在の状態。 * @return array 更新後の状態(done=trueで完了)。 * @throws \RuntimeException 作業ファイルの欠損・オープン失敗時。 */ public static function process_batch( array $state ): array { require_once AILENS_PLUGIN_DIR . 'includes/class-ailens-wpdb-storage.php'; $path = (string) $state['file']; if ( ! is_readable( $path ) ) { delete_option( self::STATE_OPTION ); throw new \RuntimeException( 'import file is missing' ); } $repository = DefinitionRepository::fromFile( AILENS_PLUGIN_DIR . 'vendor-core/data/crawlers.json' ); $detector = new Detector( $repository ); $parser = new CombinedLogParser(); $storage = new Ailens_Wpdb_Storage(); $secret = (string) get_option( 'ailens_master_secret', '' ); $hasher = '' !== $secret ? new IpHasher( $secret ) : null; $tz = wp_timezone(); // IPレンジ照合(同梱スナップショット)。リアルタイム記録と同じCIDR照合を // インポート行にも適用する(過去分の穴埋めというインポートの趣旨上、検証も // 同等であるべき)。照合はローカル完結で外部通信なし。rDNSは適用しない // (過去ログのIPへの後追いrDNSは外部通信であり、意味も薄いため)。 // 生IPはメモリ内の照合にのみ使用し、保存されない(リアルタイム記録と同じ扱い)。 try { $ranges = \AilysLens\Core\IpRangeRepository::fromFile( AILENS_PLUGIN_DIR . 'vendor-core/data/crawler-ip-ranges.json' ); } catch ( \Throwable $e ) { $ranges = null; } $range_verifier = new \AilysLens\Core\Verification\IpRangeVerifier(); $handle = fopen( $path, 'r' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- ストリーミング必須のため直接fopen。 if ( false === $handle ) { throw new \RuntimeException( 'could not open import file' ); } fseek( $handle, (int) $state['offset'] ); $deadline = microtime( true ) + self::BATCH_SECS; $lines = 0; $batch = array(); while ( $lines < self::BATCH_LINES && microtime( true ) < $deadline ) { $line = fgets( $handle ); if ( false === $line ) { $state['done'] = true; break; } ++$lines; $parsed = $parser->parseLine( $line ); if ( null === $parsed ) { ++$state['skipped']; continue; } $result = $detector->detectUserAgent( $parsed->userAgent ); if ( null === $result ) { ++$state['skipped']; continue; } // タイムゾーン変換: ログのオフセット付き時刻→サイトTZ(リアルタイム記録と同一基準)。 $hit_at = $parsed->time->setTimezone( $tz ); // ip_hash はTZ変換後の日付で計算(日付境界で別ハッシュになる事故を防ぐ)。 $ip_hash = ( null !== $hasher && '' !== $parsed->ip ) ? $hasher->hash( $parsed->ip, $hit_at ) : null; // リアルタイム記録と同一の正規化: クエリ文字列除去+2048文字上限。 $url_path = explode( '?', $parsed->path, 2 )[0]; $url_path = mb_substr( '' !== $url_path ? $url_path : '/', 0, 2048 ); // CIDR照合(レンジ収載ベンダーのみ昇格可。それ以外は verified=false のまま)。 $verified = false; if ( null !== $ranges && '' !== $parsed->ip && $ranges->hasRanges( $result->crawler->id ) ) { $verified = $range_verifier->matches( $parsed->ip, $ranges->rangesFor( $result->crawler->id ) ); } $batch[] = new HitRecord( $result->crawler->id, $result->crawler->category, $url_path, $hit_at, $verified, HitRecord::SOURCE_IMPORT, $ip_hash ); $date = $hit_at->format( 'Y-m-d' ); if ( null === $state['min_date'] || $date < $state['min_date'] ) { $state['min_date'] = $date; } } $state['offset'] = (int) ftell( $handle ); fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose if ( array() !== $batch ) { $inserted = $storage->importHits( $batch ); $state['imported'] += $inserted; $state['skipped'] += count( $batch ) - $inserted; // 重複排除ぶん。 } $state['lines'] += $lines; if ( ! empty( $state['done'] ) ) { wp_delete_file( $path ); delete_option( self::STATE_OPTION ); if ( null !== $state['min_date'] ) { Ailens_Cron::rebuild_summary_from( (string) $state['min_date'] ); } } else { update_option( self::STATE_OPTION, $state, false ); } return $state; } /** * アップロードファイルを平文テキストとして保存する(.gzはストリーム解凍)。 * * @param string $tmp アップロード一時ファイル。 * @param string $dest 保存先。 * @return string|null エラーメッセージ(成功時null)。 */ private static function store_as_plain_text( string $tmp, string $dest ): ?string { $head = (string) file_get_contents( $tmp, false, null, 0, 2 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- ローカル一時ファイルの先頭2バイト(gzipマジック)判定。 $gzip = "\x1f\x8b" === $head; $out = fopen( $dest, 'wb' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- ストリーミング必須。 if ( false === $out ) { return __( 'Could not store the uploaded file.', 'ailys-lens' ); } if ( $gzip ) { // .gz: ストリーム解凍(チャンク単位。全体をメモリに載せない)。 $in = gzopen( $tmp, 'rb' ); if ( false === $in ) { fclose( $out ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose wp_delete_file( $dest ); return __( 'Could not open the gzip file.', 'ailys-lens' ); } while ( ! gzeof( $in ) ) { $chunk = gzread( $in, 1024 * 512 ); if ( false === $chunk || '' === $chunk ) { break; } fwrite( $out, $chunk ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite } gzclose( $in ); } else { // 平文: gz経路とエラー処理を揃えるためストリームコピーで保存する。 $in = fopen( $tmp, 'rb' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- ストリーミング必須。 if ( false === $in ) { fclose( $out ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose wp_delete_file( $dest ); return __( 'Could not store the uploaded file.', 'ailys-lens' ); } stream_copy_to_stream( $in, $out ); fclose( $in ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose } fclose( $out ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose return null; } /** * 中断放置された作業ファイル・stateのTTLクリーンアップ(日次cronから呼ばれる)。 * * 生IPを含むファイルを無期限に残さないための防御。stateが指すファイルに加え、 * 迷子になった作業ファイル(state消失後の残骸)もmtimeで破棄する。 */ public static function cleanup_stale(): void { $state = self::state(); if ( null !== $state && isset( $state['started_at'] ) && ( time() - (int) $state['started_at'] ) > self::FILE_TTL ) { if ( is_string( $state['file'] ?? null ) && file_exists( $state['file'] ) ) { wp_delete_file( $state['file'] ); } delete_option( self::STATE_OPTION ); } $uploads = wp_upload_dir(); $dir = trailingslashit( $uploads['basedir'] ) . 'ailys-lens'; foreach ( (array) glob( $dir . '/import-*' ) as $path ) { if ( is_string( $path ) && is_file( $path ) && ( time() - (int) filemtime( $path ) ) > self::FILE_TTL ) { wp_delete_file( $path ); } } } /** * php.ini上限に応じたアップロードエラーメッセージ(制限の出どころを明示する)。 * * @param int $code UPLOAD_ERR_*。 */ public static function upload_error_message( int $code ): string { if ( UPLOAD_ERR_INI_SIZE === $code ) { /* translators: %s: upload_max_filesize value from php.ini. */ return sprintf( __( 'The file exceeds the server\'s PHP limit (php.ini upload_max_filesize = %s). Split the log or raise the limit.', 'ailys-lens' ), (string) ini_get( 'upload_max_filesize' ) ); } if ( UPLOAD_ERR_FORM_SIZE === $code || UPLOAD_ERR_PARTIAL === $code ) { /* translators: %s: post_max_size value from php.ini. */ return sprintf( __( 'The upload was cut short by a server limit (php.ini post_max_size = %s). Split the log or raise the limit.', 'ailys-lens' ), (string) ini_get( 'post_max_size' ) ); } if ( UPLOAD_ERR_NO_FILE === $code ) { return __( 'No file was uploaded.', 'ailys-lens' ); } /* translators: %d: PHP upload error code. */ return sprintf( __( 'Upload failed (PHP error code %d).', 'ailys-lens' ), $code ); } /** * 作業ディレクトリ(uploads/ailys-lens、直アクセス拒否)を用意する。 */ private static function working_dir(): ?string { $uploads = wp_upload_dir(); $dir = trailingslashit( $uploads['basedir'] ) . 'ailys-lens'; if ( ! wp_mkdir_p( $dir ) ) { return null; } // 直アクセスを遮断する.htaccess(新旧Apacheの両ディレクティブに対応)。内容が想定と異なれば書き直す。 $htaccess = "\nRequire all denied\n\n\nDeny from all\n\n"; $ht_path = $dir . '/.htaccess'; if ( ! file_exists( $ht_path ) || file_get_contents( $ht_path ) !== $htaccess ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- ローカルファイルの内容比較。 file_put_contents( $ht_path, $htaccess ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents } if ( ! file_exists( $dir . '/index.php' ) ) { file_put_contents( $dir . '/index.php', " 'ailys-lens-settings' ); if ( '' !== $message ) { set_transient( 'ailens_import_msg_' . get_current_user_id(), array( $type, $message ), MINUTE_IN_SECONDS * 5 ); } wp_safe_redirect( add_query_arg( $args, admin_url( 'admin.php' ) ) ); exit; } }