matcher = new skyinpo_Keyword_Matcher(); } public function linked_keywords($content) { $links = array(); $content = $this->mask_shortcodes($content); $content = preg_replace('#<(script|style|textarea|code|pre)\b[^>]*>.*?#is', '', $content); preg_match_all('#]|"[^"]*"|\'[^\']*\')*)>(.*?)#is', $content, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $attributes = wp_kses_hair($match[1], wp_allowed_protocols()); if (!isset($attributes['href'])) { continue; } $text = html_entity_decode(wp_strip_all_tags($match[2]), ENT_QUOTES | ENT_HTML5, 'UTF-8'); $key = $this->matcher->normalize_phrase($text); $url = html_entity_decode($attributes['href']['value'], ENT_QUOTES | ENT_HTML5, 'UTF-8'); if ('' !== $key) { $links[] = array('keyword' => $key, 'url' => $url); } } return $links; } private function mask_shortcodes($content) { global $shortcode_tags; if (empty($shortcode_tags) || false === strpos($content, '[')) { return $content; } return preg_replace_callback('/' . get_shortcode_regex() . '/s', function ($match) { return str_repeat("\x01", strlen($match[0])); }, $content); } public function plan($content, $rules, $source_id, $automatic_only = false) { usort($rules, function ($a, $b) { return (substr_count($b['keyword'], ' ') <=> substr_count($a['keyword'], ' ')) ?: (strlen($b['keyword']) <=> strlen($a['keyword'])) ?: ((int) $a['id'] <=> (int) $b['id']); }); $existing = array(); foreach ($this->linked_keywords($content) as $link) { $existing[$link['keyword']] = true; } $changes = array(); foreach ($rules as $rule) { $key = $this->matcher->normalize_phrase($rule['keyword']); if ('active' !== $rule['status'] || ($automatic_only && 'automatic' !== $rule['mode']) || isset($existing[$key]) || (int) $rule['target_post_id'] === (int) $source_id) { continue; } $target = get_post($rule['target_post_id']); $type = $target ? get_post_type_object($target->post_type) : null; if (!$target || 'publish' !== $target->post_status || $target->post_password || !$type || !$type->public || !$type->show_ui || 'attachment' === $target->post_type) { continue; } $url = get_permalink($target); if (!$url) { continue; } $updated = $this->apply_keyword($content, $rule['keyword'], $url); if ($updated !== $content) { $content = $updated; $existing[$key] = true; $changes[] = array('keyword' => $rule['keyword'], 'target' => get_the_title($target), 'url' => $url); } } return array('content' => $content, 'links' => $changes); } /** Text runs include source byte offsets and their open inline ancestors. */ private function runs($content) { preg_match_all('/|<(?:[^"\'>]|"[^"]*"|\'[^\']*\')*>|[^<]+| '', 'parts' => array()); $stack = array(); $excluded = ''; $depth = 0; $flush = function () use (&$runs, &$run) { if ('' !== $run['text']) { $runs[] = $run; } $run = array('text' => '', 'parts' => array()); }; foreach ($matches[0] as $token) { list($raw, $offset) = $token; if (preg_match('/^<(\/?)\s*([a-z][a-z0-9]*)\b/i', $raw, $tag)) { $name = strtolower($tag[2]); $closing = '/' === $tag[1]; $void = preg_match('/^(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/', $name); if ($depth) { if ($name === $excluded) { $depth += $closing ? -1 : ($void ? 0 : 1); } continue; } $skip = preg_match('/^(a|script|style|code|pre|textarea|select|button|svg|math|iframe|noscript)$/', $name) || preg_match('/\scontenteditable\s*=\s*(?:"false"|\'false\'|false(?=[\s>]))/i', $raw); if (!$closing && $skip) { $flush(); $excluded = $name; $depth = $void ? 0 : 1; continue; } if (preg_match('/^(address|article|aside|blockquote|dd|div|dl|dt|fieldset|figcaption|figure|footer|form|h[1-6]|header|hr|li|main|nav|ol|p|section|table|tbody|td|tfoot|th|thead|tr|ul|br|img|input|wbr)$/', $name)) { $flush(); } if ($closing) { for ($i = count($stack) - 1; $i >= 0; $i--) { if ($stack[$i]['tag'] === $name) { $stack = array_slice($stack, 0, $i); break; } } } elseif (!$void) { $stack[] = array('tag' => $name, 'html' => $raw, 'offset' => $offset); } } elseif (0 === strpos($raw, ' strlen($run['text']), 'text' => $decoded, 'raw' => $raw, 'offset' => $offset, 'stack' => $stack); $run['text'] .= $decoded; } } $flush(); return $runs; } /** Translate a decoded UTF-8 byte position back through HTML entities. */ private function raw_offset($raw, $position) { preg_match_all('/&(?:#[0-9]+|#x[0-9a-f]+|[a-z][a-z0-9]+);|./isu', $raw, $pieces, PREG_OFFSET_CAPTURE); $decoded = 0; foreach ($pieces[0] as $piece) { if ($decoded >= $position) { return $piece[1]; } $decoded += strlen(html_entity_decode($piece[0], ENT_QUOTES | ENT_HTML5, 'UTF-8')); } return strlen($raw); } public function apply_keyword($content, $keyword, $url) { if ('' === trim($keyword)) { return $content; } $words = preg_split('/[\s\p{Z}]+/u', trim($keyword)); $words = array_map(function ($word) { return preg_quote($word, '/'); }, $words); $pattern = '/(?runs($this->mask_shortcodes($content)) as $run) { if (!preg_match($pattern, $run['text'], $match, PREG_OFFSET_CAPTURE)) { continue; } $start = $match[0][1]; $end = $start + strlen($match[0][0]); $first = $last = null; foreach ($run['parts'] as $part) { $limit = $part['start'] + strlen($part['text']); if ($start >= $part['start'] && $start < $limit) { $first = $part; } if ($end > $part['start'] && $end <= $limit) { $last = $part; } } if (!$first || !$last) { continue; } $from = $first['offset'] + $this->raw_offset($first['raw'], $start - $first['start']); $to = $last['offset'] + $this->raw_offset($last['raw'], $end - $last['start']); $common = 0; while (isset($first['stack'][$common], $last['stack'][$common]) && $first['stack'][$common]['offset'] === $last['stack'][$common]['offset']) { $common++; } $left = array_slice($first['stack'], $common); $right = array_slice($last['stack'], $common); $close_left = $open_left = $close_right = $open_right = ''; foreach ($left as $tag) { $open_left .= $tag['html']; $close_left = '' . $close_left; } foreach ($right as $tag) { $open_right .= $tag['html']; $close_right = '' . $close_right; } return substr($content, 0, $from) . $close_left . '' . $open_left . substr($content, $from, $to - $from) . $close_right . '' . $open_right . substr($content, $to); } return $content; } }