db = $db;
}
// ── 単一記事スキャン ──────────────────────────────────────────────────
public function scan_post( int $post_id ): int {
$post = get_post( $post_id );
if ( ! $post ) {
return 0;
}
$settings = ACSIL_Core::get_settings();
$post_types = $settings['post_types'];
if ( ! in_array( $post->post_type, $post_types, true ) ) {
return 0;
}
if ( in_array( $post->post_status, array( 'auto-draft', 'trash', 'inherit' ), true ) ) {
return 0;
}
$links = $this->parse_links( $post->post_content, $post_id );
$this->db->save_links( $post_id, $links );
delete_transient( 'acsil_dashboard_data' );
return count( $links );
}
// ── save_post フック ─────────────────────────────────────────────────
public function on_save_post( int $post_id, WP_Post $post ): void {
// リビジョン・自動下書きは除外
if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
return;
}
// 権限チェック
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
$settings = ACSIL_Core::get_settings();
$post_types = $settings['post_types'];
if ( ! in_array( $post->post_type, $post_types, true ) ) {
return;
}
$this->scan_post( $post_id );
}
// ── HTMLパース(DOMDocument → 正規表現フォールバック) ────────────────
public function parse_links( string $content, int $source_post_id ): array {
if ( empty( $content ) ) {
return array();
}
$home_url = trailingslashit( home_url() );
$links = array();
$seen = array();
$extracted = $this->extract_links_dom( $content );
if ( empty( $extracted ) ) {
$extracted = $this->extract_links_regex( $content );
}
foreach ( $extracted as $item ) {
$href = $item['href'];
$anchor = $item['anchor'];
// 自サイト判定
$normalized = $this->normalize_url( $href );
if ( null === $normalized ) {
continue;
}
// URL → 投稿IDに変換
$target_id = url_to_postid( $normalized );
if ( ! $target_id || $target_id === $source_post_id ) {
continue;
}
// 重複チェック(source + target + anchor の組み合わせ)
$key = $target_id . '|' . mb_substr( $anchor, 0, 191 );
if ( isset( $seen[ $key ] ) ) {
continue;
}
$seen[ $key ] = true;
$links[] = array(
'target_id' => $target_id,
'anchor' => $anchor,
'url' => $normalized,
);
}
return $links;
}
// ── DOMDocument でリンク抽出 ──────────────────────────────────────────
private function extract_links_dom( string $content ): array {
$links = array();
$dom = new DOMDocument();
libxml_use_internal_errors( true );
/*
* Gutenberg のコンテンツはブロックコメント( など)と
* 複数のルートレベル要素が混在するため、LIBXML_HTML_NOIMPLIED フラグは
* 使用しない。標準的な HTML ラッパー(html/head/body)で囲むことで
* DOMDocument が全 タグを確実に認識できるようにする。
* charset meta タグで UTF-8 を指定して文字化けを防ぐ。
*/
$dom->loadHTML(
'' . $content . ''
);
libxml_clear_errors();
$anchors = $dom->getElementsByTagName( 'a' );
foreach ( $anchors as $a ) {
$href = $a->getAttribute( 'href' );
if ( empty( $href ) ) {
continue;
}
$links[] = array(
'href' => $href,
'anchor' => trim( $a->textContent ), // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- DOMNode property.
);
}
return $links;
}
// ── 正規表現フォールバック ────────────────────────────────────────────
private function extract_links_regex( string $content ): array {
$links = array();
if ( ! preg_match_all( '/]*href=["\']([^"\']+)["\'][^>]*>(.*?)<\/a>/is', $content, $matches ) ) {
return $links;
}
foreach ( $matches[1] as $i => $href ) {
$anchor = wp_strip_all_tags( $matches[2][ $i ] );
$links[] = array(
'href' => $href,
'anchor' => trim( $anchor ),
);
}
return $links;
}
// ── URL正規化 ─────────────────────────────────────────────────────────
private function normalize_url( string $url ): ?string {
// 相対URLをフルURLに変換
if ( str_starts_with( $url, '/' ) && ! str_starts_with( $url, '//' ) ) {
$url = home_url( $url );
}
// スキームが省略された場合(//example.com/...)
if ( str_starts_with( $url, '//' ) ) {
$url = 'https:' . $url;
}
// 自サイト判定
$home_host = wp_parse_url( home_url(), PHP_URL_HOST );
$url_host = wp_parse_url( $url, PHP_URL_HOST );
if ( null === $url_host || strtolower( $url_host ) !== strtolower( $home_host ) ) {
return null;
}
// アンカー・クエリパラメータを除去
$parsed = wp_parse_url( $url );
if ( false === $parsed ) {
return null;
}
$clean = ( $parsed['scheme'] ?? 'https' ) . '://';
$clean .= $parsed['host'] ?? '';
$clean .= $parsed['path'] ?? '/';
/*
* スキームを home_url() に合わせて統一する。
* http→https の強制変換は行わない。
* 理由: url_to_postid() が内部で str_replace( home_url(), '', $url ) を
* 実行するため、スキームが home_url() と異なると ID が 0 になる。
*/
$home_scheme = wp_parse_url( home_url(), PHP_URL_SCHEME ) ?: 'https';
$clean = preg_replace( '/^https?:\/\//', $home_scheme . '://', $clean );
// www あり/なし統一は行わない(サイト設定に依存)
// トレイリングスラッシュの統一
$clean = trailingslashit( $clean );
return $clean;
}
// ── 全記事バッチスキャン ──────────────────────────────────────────────
public function get_total_scannable(): int {
$settings = ACSIL_Core::get_settings();
$post_types = $settings['post_types'];
$args = array(
'post_type' => $post_types,
'post_status' => array( 'publish', 'draft' ),
'posts_per_page' => -1,
'fields' => 'ids',
);
return count( get_posts( $args ) );
}
public function batch_scan( int $offset, int $batch_size = 50 ): array {
$settings = ACSIL_Core::get_settings();
$post_types = $settings['post_types'];
$posts = get_posts(
array(
'post_type' => $post_types,
'post_status' => array( 'publish', 'draft' ),
'posts_per_page' => $batch_size,
'offset' => $offset,
'fields' => 'ids',
'orderby' => 'ID',
'order' => 'ASC',
)
);
$scanned = 0;
foreach ( $posts as $post_id ) {
$this->scan_post( $post_id );
++$scanned;
}
// 最後のバッチ完了時にスキャン時刻を記録
if ( $scanned < $batch_size ) {
update_option( 'acsil_last_scan_time', current_time( 'mysql' ) );
update_option( 'acsil_initial_scan_needed', '' );
delete_transient( 'acsil_dashboard_data' );
}
return array(
'scanned' => $scanned,
'is_done' => $scanned < $batch_size,
);
}
// ── Ajax: バッチスキャン ──────────────────────────────────────────────
public function ajax_scan_batch(): void {
check_ajax_referer( 'acsil_scan_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( array( 'message' => __( 'Sorry, you are not allowed to access this page.', 'acs-internal-links' ) ) );
}
$action_type = isset( $_POST['scan_action'] ) ? sanitize_text_field( wp_unslash( $_POST['scan_action'] ) ) : 'batch';
// 総件数の取得
if ( 'get_total' === $action_type ) {
wp_send_json_success( array( 'total' => $this->get_total_scannable() ) );
}
// バッチ処理
$offset = isset( $_POST['offset'] ) ? absint( $_POST['offset'] ) : 0;
$batch_size = isset( $_POST['batch_size'] ) ? absint( $_POST['batch_size'] ) : 50;
$batch_size = min( $batch_size, 100 ); // 上限100
$result = $this->batch_scan( $offset, $batch_size );
wp_send_json_success( $result );
}
}