library = new skyinpo_Keyword_Library(); $this->linker = new skyinpo_Content_Linker(); } public static function instance() { if (!self::$instance) { self::$instance = new self(); } return self::$instance; } public function library() { return $this->library; } public static function init() { $manager = self::instance(); add_action('admin_init', array($manager, 'maybe_install')); add_action('admin_menu', array($manager, 'menu')); add_action('admin_enqueue_scripts', array($manager, 'assets')); add_action('wp_ajax_skyinpo_library', array($manager, 'ajax')); add_filter('wp_insert_post_data', array($manager, 'auto_link'), 20, 4); add_action('save_post', array($manager, 'saved'), 30, 3); add_action('before_delete_post', array($manager, 'deleted')); add_action('skyinpo_library_reindex', array($manager, 'background_index')); } public function maybe_install() { if (!$this->library->ready() && (current_user_can('manage_options') || current_user_can('edit_others_posts') || current_user_can('edit_others_pages'))) { skyinpo_Keyword_Library::install(); } $this->library->recover_applied(); } public function menu() { add_management_page(__('Post Linker', '7sky-internal-post-linker'), __('Post Linker', '7sky-internal-post-linker'), skyinpo_Keyword_Library::CAPABILITY, 'skyinpo-post-linker', array($this, 'page')); } public function assets($hook) { if ('tools_page_skyinpo-post-linker' !== $hook) { return; } wp_enqueue_script('skyinpo-library-admin', SKYINPO_PLUGIN_URL . 'assets/js/library-admin.js', array(), SKYINPO_VERSION, true); wp_localize_script('skyinpo-library-admin', 'skyinpo_Library', array('ajaxUrl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('skyinpo_library'))); wp_enqueue_style('skyinpo-library-admin', SKYINPO_PLUGIN_URL . 'assets/css/library-admin.css', array(), SKYINPO_VERSION); } public function page() { if (!current_user_can(skyinpo_Keyword_Library::CAPABILITY)) { return; } ?>

Automatic rules link one eligible occurrence when you save content. Existing links and self-links are skipped. Pending and paused rules never run automatically.

Keyword library

KeywordDestinationLinked contentStatusBehaviorSourceActions
skip_auto || !$this->library->ready() || (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)) { return $data; } $id = absint($postarr['ID'] ?? 0); $type = get_post_type_object($data['post_type'] ?? ''); if (!$type || !$type->public || !$type->show_ui || 'attachment' === $type->name || !in_array($data['post_status'] ?? '', array('publish', 'private', 'draft', 'pending', 'future'), true)) { return $data; } if ($id ? (!current_user_can('edit_post', $id) || wp_is_post_revision($id) || wp_is_post_autosave($id)) : !current_user_can($type->cap->create_posts ?? $type->cap->edit_posts)) { return $data; } $content = wp_unslash($data['post_content']); $plan = $this->linker->plan($content, $this->library->rules(), $id, true); if ($plan['content'] !== $content) { $data['post_content'] = wp_slash($plan['content']); } return $data; } public function saved($id, $post, $update) { if (!wp_is_post_revision($id) && !wp_is_post_autosave($id)) { $this->library->approve_saved_links($id); $this->library->index_post($id); } } public function deleted($id) { global $wpdb; if ($this->library->ready()) { $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}skyinpo_keyword_links WHERE source_post_id = %d OR target_post_id = %d", $id, $id)); } } /** Stable keyset pagination; drafts and private sources remain permission checked by callers. */ private function batch($cursor, $max = PHP_INT_MAX) { global $wpdb; $types = get_post_types(array('public' => true, 'show_ui' => true), 'names'); unset($types['attachment']); if (!$types) { return array(); } $placeholders = implode(',', array_fill(0, count($types), '%s')); $args = array_merge(array($cursor, $max), array_values($types)); return $wpdb->get_col($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID > %d AND ID <= %d AND post_type IN ($placeholders) AND post_status IN ('publish','private','draft','pending','future') ORDER BY ID ASC LIMIT 20", $args)); } public function background_index($cursor = 0) { if (!$this->library->ready()) { return; } $ids = $this->batch($cursor); foreach ($ids as $id) { $this->library->index_post((int) $id); } if (count($ids) === 20) { $next = (int) end($ids); if (!wp_next_scheduled('skyinpo_library_reindex', array($next))) { wp_schedule_single_event(time() + 5, 'skyinpo_library_reindex', array($next)); } } elseif (!wp_next_scheduled('skyinpo_library_reindex', array(0))) { update_option('skyinpo_library_index_status', sprintf(__('Usage counts updated: %s UTC', '7sky-internal-post-linker'), current_time('mysql', true)), false); } } public function ajax() { check_ajax_referer('skyinpo_library', 'nonce'); if (!current_user_can(skyinpo_Keyword_Library::CAPABILITY)) { wp_send_json_error(array('message' => __('You cannot manage the keyword library.', '7sky-internal-post-linker')), 403); } if (!$this->library->ready()) { wp_send_json_error(array('message' => __('The keyword library is not ready. Reload the admin page.', '7sky-internal-post-linker')), 503); } $input = wp_unslash($_POST); $op = sanitize_key($input['op'] ?? 'list'); if ('applied' === $op) { $source = absint($input['post_id'] ?? 0); if ($source && !current_user_can('edit_post', $source)) { wp_send_json_error(array('message' => __('You cannot edit this source article.', '7sky-internal-post-linker')), 403); } $items = isset($input['items']) && is_string($input['items']) ? json_decode($input['items'], true) : null; if (!is_array($items) || count($items) > 100) { wp_send_json_error(array('message' => __('Invalid applied keyword list.', '7sky-internal-post-linker')), 400); } $saved = 0; $errors = array(); foreach ($items as $item) { $keyword = is_array($item) && isset($item['keyword']) && is_scalar($item['keyword']) ? sanitize_text_field((string) $item['keyword']) : ''; $target = is_array($item) && isset($item['target_post_id']) && is_scalar($item['target_post_id']) ? absint($item['target_post_id']) : 0; $result = $this->library->remember_applied($keyword, $target); if (is_wp_error($result)) { $errors[] = array('keyword' => $keyword, 'target_post_id' => $target, 'message' => $result->get_error_message()); } else { $saved++; } } if ($source) { $this->library->index_post($source); } wp_send_json_success(array('saved' => $saved, 'errors' => $errors)); } if ('save' === $op || 'remember' === $op) { if ('remember' === $op) { $input['remember'] = true; $input['status'] = 'active'; $input['mode'] = 'suggest'; unset($input['id']); } $result = $this->library->save($input); if (is_wp_error($result)) { wp_send_json_error(array('message' => $result->get_error_message()), 400); } wp_send_json_success(array('id' => $result)); } if ('delete' === $op) { wp_send_json_success(array('deleted' => $this->library->delete(absint($input['id'] ?? 0)))); } if ('usage' === $op) { wp_send_json_success($this->library->usage(absint($input['id'] ?? 0), absint($input['page'] ?? 1))); } if ('targets' === $op) { $search = new skyinpo_Content_Search(); $items = $search->get_search_results(sanitize_text_field($input['term'] ?? ''), 0); $items = array_values(array_filter($items, function ($item) { return $this->library->available($item['id']) && current_user_can('read_post', $item['id']); })); wp_send_json_success($items); } if ('list' === $op) { wp_send_json_success($this->list_rules($input)); } if ('job_start' === $op) { $result = $this->start_job(sanitize_key($input['kind'] ?? 'preview')); if (is_wp_error($result)) { wp_send_json_error(array('message' => $result->get_error_message()), 400); } wp_send_json_success($result); } if ('job_view' === $op) { $token = sanitize_text_field($input['token'] ?? ''); $job = get_transient($this->job_key($token)); if (!$job) { wp_send_json_error(array('message' => __('This preview expired. Create a new preview.', '7sky-internal-post-linker')), 409); } wp_send_json_success($this->job_result($job, $token, max(1, absint($input['page'] ?? 1)))); } if ('job_step' === $op || 'job_apply' === $op) { $result = $this->step_job(sanitize_text_field($input['token'] ?? ''), 'job_apply' === $op); if (is_wp_error($result)) { wp_send_json_error(array('message' => $result->get_error_message()), 409); } wp_send_json_success($result); } wp_send_json_error(array('message' => __('Unknown library action.', '7sky-internal-post-linker')), 400); } private function list_rules($input) { $term = sanitize_text_field($input['term'] ?? ''); $status = sanitize_key($input['status'] ?? ''); $rows = array_values(array_filter($this->library->rules(), function ($rule) use ($term, $status) { return (!$status || $rule['status'] === $status) && (!$term || false !== stripos($rule['keyword'], $term) || false !== stripos(get_the_title($rule['target_post_id']), $term)); })); usort($rows, function ($a, $b) { return strcmp($a['keyword'], $b['keyword']); }); $total = count($rows); $page = max(1, absint($input['page'] ?? 1)); $rows = array_slice($rows, ($page - 1) * 20, 20); foreach ($rows as &$row) { $row['targetTitle'] = current_user_can('read_post', $row['target_post_id']) ? get_the_title($row['target_post_id']) : ''; $row['targetTitle'] = $row['targetTitle'] ?: __('Unavailable destination', '7sky-internal-post-linker'); $row['targetUrl'] = $this->library->available($row['target_post_id']) ? get_permalink($row['target_post_id']) : ''; $row['available'] = $this->library->available($row['target_post_id']); $usage = $this->library->usage($row['id']); unset($usage['items']); $row['usage'] = $usage; } unset($row); return array('items' => $rows, 'total' => $total, 'page' => $page, 'indexStatus' => get_option('skyinpo_library_index_status', __('Rebuild usage counts to index existing content.', '7sky-internal-post-linker'))); } private function job_key($token) { return 'skyinpo_job_' . get_current_user_id() . '_' . hash('sha256', $token); } private function start_job($kind) { global $wpdb; if (!in_array($kind, array('preview', 'index'), true)) { return new WP_Error('skyinpo_kind', __('Invalid operation.', '7sky-internal-post-linker')); } $token = wp_generate_uuid4(); $job = array('kind' => $kind, 'cursor' => 0, 'max' => (int) $wpdb->get_var("SELECT MAX(ID) FROM {$wpdb->posts}"), 'fingerprint' => $this->library->fingerprint(), 'items' => array(), 'processed' => 0, 'applied' => 0, 'skipped' => 0, 'ready' => false, 'done' => false); set_transient($this->job_key($token), $job, HOUR_IN_SECONDS); return array('token' => $token, 'kind' => $kind, 'processed' => 0, 'ready' => false, 'done' => false, 'items' => array()); } public function step_job($token, $apply = false) { $key = $this->job_key($token); $job = get_transient($key); if (!$job) { return new WP_Error('skyinpo_job', __('This preview expired. Create a new preview.', '7sky-internal-post-linker')); } // Prevent two browser tabs/retries from processing the same job concurrently. $lock = $key . '_lock'; if (!add_option($lock, time(), '', false)) { if ((int) get_option($lock) < time() - 120) { delete_option($lock); } return new WP_Error('skyinpo_busy', __('This operation is already running. Try again shortly.', '7sky-internal-post-linker')); } try { $job = get_transient($key); if (!$job) { return new WP_Error('skyinpo_job', __('This preview expired. Create a new preview.', '7sky-internal-post-linker')); } if ('index' !== $job['kind'] && $job['fingerprint'] !== $this->library->fingerprint()) { return new WP_Error('skyinpo_changed', __('Keyword rules or destinations changed. Create a new preview.', '7sky-internal-post-linker')); } if ($apply && 'preview' === $job['kind'] && $job['ready']) { $job['kind'] = 'apply'; $job['cursor'] = 0; $job['done'] = false; } if ((!$job['done'] && !$job['ready']) || ('apply' === $job['kind'] && !$job['done'])) { if ('apply' === $job['kind']) { $items = array_slice($job['items'], $job['cursor'], 10); foreach ($items as $item) { $post = get_post($item['id']); if (!$post || !current_user_can('edit_post', $item['id']) || !in_array($post->post_status, array('publish', 'private', 'draft', 'pending', 'future'), true) || hash('sha256', $post->post_content) !== $item['hash']) { $job['skipped']++; continue; } $plan = $this->linker->plan($post->post_content, $this->library->rules(), $post->ID); $this->skip_auto = true; try { $saved = wp_update_post(wp_slash(array('ID' => $post->ID, 'post_content' => $plan['content'])), true); } finally { $this->skip_auto = false; } if (is_wp_error($saved)) { $job['skipped']++; } else { $job['applied']++; } } $job['cursor'] += count($items); $job['done'] = $job['cursor'] >= count($job['items']); } else { $ids = $this->batch($job['cursor'], $job['max']); foreach ($ids as $id) { $job['cursor'] = (int) $id; $job['processed']++; if ('index' === $job['kind']) { $this->library->index_post((int) $id); continue; } if (!current_user_can('edit_post', $id)) { continue; } $post = get_post($id); $plan = $this->linker->plan($post->post_content, $this->library->rules(), $post->ID); if ($plan['links']) { $job['items'][] = array('id' => (int) $id, 'title' => get_the_title($post), 'url' => get_edit_post_link($id, 'raw'), 'type' => $post->post_type, 'status' => $post->post_status, 'hash' => hash('sha256', $post->post_content), 'links' => $plan['links']); } } if (count($ids) < 20) { if ('preview' === $job['kind']) { $job['ready'] = true; } else { $job['done'] = true; update_option('skyinpo_library_index_status', sprintf(__('Usage counts updated: %s UTC', '7sky-internal-post-linker'), current_time('mysql', true)), false); } } } } set_transient($key, $job, HOUR_IN_SECONDS); return $this->job_result($job, $token); } finally { delete_option($lock); } } private function job_result($job, $token, $page = 1) { $result = $job; unset($result['fingerprint']); $result['totalChanges'] = count($job['items']); $result['previewPages'] = max(1, (int) ceil(count($job['items']) / 50)); $page = min($page, $result['previewPages']); $result['previewPage'] = $page; $result['items'] = array_slice($job['items'], ($page - 1) * 50, 50); $result['items'] = array_values(array_filter($result['items'], function ($item) { return current_user_can('edit_post', $item['id']); })); foreach ($result['items'] as &$item) { unset($item['hash']); } unset($item); $result['token'] = $token; return $result; } }