[pagename][#filterNS][#!filterNS]...}} * * Original authors: * Mark C. Prins * Michael Klier * https://www.dokuwiki.org/plugin:backlinks * * Section-aware modifications: * Wizardry and Steamworks * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) */ class syntax_plugin_backlinkswas extends SyntaxPlugin { public function getType(): string { return 'substition'; } public function getPType(): string { return 'block'; } public function getSort(): int { return 304; } public function connectTo($mode): void { $this->Lexer->addSpecialPattern('\{\{backlinkswas>.+?\}\}', $mode, 'plugin_backlinkswas'); } public function handle($match, $state, $pos, Handler $handler): array { // strip {{backlinkswas> from start and }} from end (15 chars) $match = substr($match, 15, -2); $includeNS = []; $excludeNS = []; if (str_contains($match, "#")) { $filters = explode('#', substr(strstr($match, "#"), 1)); $match = strstr($match, "#", true); foreach ($filters as $filter) { if ($filter === '') { continue; } if (str_starts_with($filter, '!')) { $excludeNS[] = substr($filter, 1); } else { $includeNS[] = $filter; } } } return ([$match, $includeNS, $excludeNS]); } public function render($format, Doku_Renderer $renderer, $data): bool { global $lang; global $INFO; global $ID; $id = $ID; // If it's a sidebar, get the original id. if ($INFO != null) { $id = $INFO['id']; } $match = $data[0]; $match = ($match == '.') ? $id : $match; if (str_contains($match, ".:")) { $resolver = new PageResolver($id); $match = $resolver->resolveId($match); } if ($format != 'xhtml') { return false; } $renderer->info['cache'] = false; // 1. Candidate pages from the index. $candidates = (new MetadataSearch())->backlinks($match); if ($candidates === []) { // Fall back to a wiki:-prefixed form in case the target was // indexed under a URL-style /wiki/... prefix. $alt = 'wiki:' . ltrim(str_replace('/', ':', $match), ':'); if ($alt !== $match) { $candidates = (new MetadataSearch())->backlinks($alt); } } $includeNS = $data[1]; $excludeNS = $data[2]; // 2. Namespace include filter. if ($candidates !== [] && $includeNS !== []) { $candidates = array_filter( $candidates, static function ($ns) use ($includeNS) { foreach ($includeNS as $filterNS) { if (stripos($ns, (string) $filterNS) === 0) { return true; } } return false; } ); } // 3. Namespace exclude filter. if ($candidates !== [] && $excludeNS !== []) { $candidates = array_filter( $candidates, static function ($ns) use ($excludeNS) { foreach ($excludeNS as $filterNS) { if (stripos($ns, (string) $filterNS) === 0) { return false; } } return true; } ); } // 4. Resolve each candidate into (page, fragment) pairs. $backlinks = []; foreach ($candidates as $candidate) { if (auth_quickaclcheck($candidate) < AUTH_READ) { continue; } $fragments = $this->findLinkLocations($candidate, $match, $id); foreach ($fragments as $fragment) { $key = $candidate . '#' . $fragment; $backlinks[$key] = [$candidate, $fragment]; } } $backlinks = array_values($backlinks); $renderer->doc .= '
' . "\n"; if ($backlinks !== []) { $renderer->doc .= '
    '; foreach ($backlinks as [$page, $fragment]) { $name = p_get_metadata($page, 'title'); if (empty($name)) { $name = $page; } $label = $name; if ($fragment !== '') { $sectionTitle = $this->getSectionTitle($page, $fragment); if ($sectionTitle !== '') { $label .= ' ยป ' . $sectionTitle; } } $targetId = ':' . $page; if ($fragment !== '') { $targetId .= '#' . $fragment; } $renderer->doc .= '
  • '; $renderer->doc .= html_wikilink($targetId, $label); $renderer->doc .= '
  • ' . "\n"; } $renderer->doc .= '
' . "\n"; } else { $renderer->doc .= "Plugin Backlinks: " . $lang['nothingfound'] . "" . "\n"; } $renderer->doc .= '
' . "\n"; return true; } /** * Find every location in $sourcePageId where a link to $targetPageId occurs. * * @return string[] List of fragments (may contain '' for top-of-page). */ protected function findLinkLocations(string $sourcePageId, string $targetPageId, string $contextId): array { $file = wikiFN($sourcePageId); $exists = file_exists($file); if (!$exists) { return []; } $source = io_readFile($file, false); if ($source === '') { return []; } // Resolve the target the same way DokuWiki would, so relative links match. $resolver = new PageResolver($sourcePageId); $resolvedTarget = $resolver->resolveId($targetPageId); $fragments = []; // DokuWiki link syntax: [[target]] or [[target|label]] or [[target#frag|label]] $pattern = '/\[\[([^\]\|]+)(?:\|[^\]]*)?\]\]/u'; $count = preg_match_all($pattern, $source, $matches, PREG_OFFSET_CAPTURE); if (!$count) { return []; } $headings = $this->findHeadings($source); foreach ($matches[1] as [$rawTarget, $offset]) { $rawTargetOrig = $rawTarget; $rawTarget = trim($rawTarget); $explicitFragment = ''; if (str_contains($rawTarget, '#')) { [$rawTarget, $explicitFragment] = explode('#', $rawTarget, 2); $explicitFragment = trim($explicitFragment); } if ($rawTarget === '' || str_contains($rawTarget, '://') || str_contains($rawTarget, '>')) { continue; } $resolved = $resolver->resolveId($rawTarget); $resolvedClean = cleanID($resolved); $targetClean = cleanID($resolvedTarget); if ($resolvedClean !== $targetClean) { continue; } if ($explicitFragment !== '') { $fragments[] = cleanID($explicitFragment); continue; } $section = $this->headingBeforeOffset($headings, $offset); $fragments[] = $section; } $result = array_values(array_unique($fragments)); return $result; } /** * Extract headings from raw wiki source. * * @return array */ protected function findHeadings(string $source): array { $headings = []; $lines = explode("\n", $source); $offset = 0; foreach ($lines as $line) { if (preg_match('/^(\s*)(={2,6})([^=].*?)\2\s*$/', $line, $m)) { $level = strlen($m[2]); $title = trim($m[3]); $id = $this->sectionId($title); if ($id !== '') { $headings[] = [ 'offset' => $offset, 'id' => $id, 'title' => $title, 'level' => $level, ]; } } $offset += strlen($line) + 1; } return $headings; } /** * Mirror DokuWiki's section-ID generation. */ protected function sectionId(string $title): string { $id = str_replace(' ', '_', strtolower($title)); $id = preg_replace('/[^a-z0-9_\-\.]/u', '', $id); return $id; } /** * Find the ID of the nearest heading at or before $offset. * Returns '' if the link is above the first heading. */ protected function headingBeforeOffset(array $headings, int $offset): string { $current = ''; foreach ($headings as $h) { if ($h['offset'] > $offset) { break; } $current = $h['id']; } return $current; } /** * Look up the human-readable heading title for a fragment on a page. */ protected function getSectionTitle(string $pageId, string $fragment): string { $file = wikiFN($pageId); if (!file_exists($file)) { return ''; } $source = io_readFile($file, false); if ($source === '') { return ''; } foreach ($this->findHeadings($source) as $h) { if ($h['id'] === $fragment) { return $h['title']; } } return ''; } }