<?php

/**
 * @package    Grav\Common\Page
 *
 * @copyright  Copyright (c) 2015 - 2026 Trilby Media, LLC. All rights reserved.
 * @license    MIT License; see LICENSE file for details.
 */

namespace Grav\Common\Page\Markdown;

use Grav\Common\Grav;
use Grav\Common\Media\Interfaces\ImageMediaInterface;
use Grav\Common\Media\Interfaces\MediaLinkInterface;
use Grav\Common\Media\Interfaces\MediaObjectInterface;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Page\Medium\Link;
use Grav\Common\Page\Pages;
use Grav\Common\Uri;
use Grav\Common\Page\Medium\Medium;
use Grav\Common\Utils;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use function array_key_exists;
use function count;
use function dirname;
use function in_array;
use function is_bool;
use function is_string;

/**
 * Class Excerpts
 * @package Grav\Common\Page\Markdown
 */
class Excerpts
{
    /** @var PageInterface|null */
    protected $page;
    /** @var array */
    protected $config;

    /**
     * Excerpts constructor.
     * @param PageInterface|null $page
     * @param array|null $config
     */
    public function __construct(?PageInterface $page = null, ?array $config = null)
    {
        $this->page = $page ?? Grav::instance()['page'] ?? null;

        // Add defaults to the configuration.
        if (null === $config || !isset($config['markdown'], $config['images'])) {
            $c = Grav::instance()['config'];
            $config ??= [];
            $config += [
                'markdown' => $c->get('system.pages.markdown', []),
                'images' => $c->get('system.images', [])
            ];
        }

        $this->config = $config;
    }

    /**
     * @return PageInterface|null
     */
    public function getPage(): ?PageInterface
    {
        return $this->page;
    }

    /**
     * @return array
     */
    public function getConfig(): array
    {
        return $this->config;
    }

    /**
     * @param object $markdown
     * @return void
     */
    public function fireInitializedEvent($markdown): void
    {
        $grav = Grav::instance();

        $grav->fireEvent('onMarkdownInitialized', new Event(['markdown' => $markdown, 'page' => $this->page]));
    }

    /**
     * Process a Link excerpt
     *
     * @param array $excerpt
     * @param string $type
     * @return array
     */
    public function processLinkExcerpt(array $excerpt, string $type = 'link'): array
    {
        // A data: URI carries its payload inline; decoding it would turn %23
        // into a fragment and corrupt the content, so leave it as written.
        if (static::isDataUri((string) $excerpt['element']['attributes']['href'])) {
            return $excerpt;
        }

        $grav = Grav::instance();
        $url = htmlspecialchars_decode(rawurldecode((string) $excerpt['element']['attributes']['href']));
        $url_parts = $this->parseUrl($url);

        // If there is a query, then parse it and build action calls.
        if (isset($url_parts['query'])) {
            $actions = [];
            foreach (explode('&', (string) $url_parts['query']) as $item) {
                $parts = explode('=', $item, 2);
                $actions[$parts[0]] = isset($parts[1]) ? rawurldecode($parts[1]) : true;
            }

            // Valid attributes supported.
            $valid_attributes = $grav['config']->get('system.pages.markdown.valid_link_attributes') ?? [];

            $skip = [];
            // Unless told to not process, go through actions.
            if (array_key_exists('noprocess', $actions)) {
                $skip = is_bool($actions['noprocess']) ? $actions : explode(',', (string) $actions['noprocess']);
                unset($actions['noprocess']);
            }

            // Loop through actions for the image and call them.
            foreach ($actions as $attrib => $value) {
                if (!in_array($attrib, $skip)) {
                    $key = $attrib;

                    if (in_array($attrib, $valid_attributes, true)) {
                        // support both class and classes.
                        if ($attrib === 'classes') {
                            $attrib = 'class';
                        }
                        $excerpt['element']['attributes'][$attrib] = str_replace(',', ' ', $value);
                        unset($actions[$key]);
                    }
                }
            }

            $url_parts['query'] = http_build_query($actions, '', '&', PHP_QUERY_RFC3986);
        }

        // If no query elements left, unset query.
        if (empty($url_parts['query'])) {
            unset($url_parts['query']);
        }

        // Set path to / if not set.
        if (empty($url_parts['path'])) {
            $url_parts['path'] = '';
        }

        // If scheme isn't http(s)..
        if (!empty($url_parts['scheme']) && !in_array($url_parts['scheme'], ['http', 'https'])) {
            // Handle custom streams.
            /** @var UniformResourceLocator $locator */
            $locator = $grav['locator'];
            if ($type === 'link' && $locator->isStream($url)) {
                $path = $locator->findResource($url, false) ?: $locator->findResource($url, false, true);
                $url_parts['path'] = $grav['base_url_relative'] . '/' . $path;
                unset($url_parts['stream'], $url_parts['scheme']);
            }

            $excerpt['element']['attributes']['href'] = Uri::buildUrl($url_parts);

            return $excerpt;
        }

        // Handle paths and such.
        $url_parts = Uri::convertUrl($this->page, $url_parts, $type);

        // Build the URL from the component parts and set it on the element.
        $excerpt['element']['attributes']['href'] = Uri::buildUrl($url_parts);

        return $excerpt;
    }

    /**
     * Process an image excerpt
     *
     * @param array $excerpt
     * @return array
     */
    public function processImageExcerpt(array $excerpt): array
    {
        // A pasted image arrives as a data: URI. Its base64 payload uses '+',
        // which form-style decoding turned into a space, breaking the image on
        // the frontend. It is never page media, so leave it as written.
        if (static::isDataUri((string) $excerpt['element']['attributes']['src'])) {
            return $excerpt;
        }

        // rawurldecode(), as for links: a '+' in a URL path is a literal plus
        // (e.g. "a+b.png"), not an encoded space.
        $url = htmlspecialchars_decode(rawurldecode((string) $excerpt['element']['attributes']['src']));
        $url_parts = $this->parseUrl($url);

        $media = null;
        $filename = null;

        if (!empty($url_parts['stream'])) {
            $filename = $url_parts['scheme'] . '://' . ($url_parts['path'] ?? '');

            $media = $this->page->media();
        } else {
            $grav = Grav::instance();
            /** @var Pages $pages */
            $pages = $grav['pages'];

            // File is also local if scheme is http(s) and host matches.
            $local_file = isset($url_parts['path'])
                && (empty($url_parts['scheme']) || in_array($url_parts['scheme'], ['http', 'https'], true))
                && (empty($url_parts['host']) || $url_parts['host'] === $grav['uri']->host());

            if ($local_file) {
                $filename = Utils::basename($url_parts['path']);
                $folder = dirname((string) $url_parts['path']);

                // Get the local path to page media if possible.
                if ($this->page && $folder === $this->page->url(false, false, false)) {
                    // Get the media objects for this page. media() rather than
                    // getMedia(), because media() is where `pages.media_route_urls`
                    // gives each file its route URL. getgrav/grav#4298.
                    $media = $this->page->media();
                } else {
                    // see if this is an external page to this one
                    $base_url = rtrim($grav['base_url_relative'] . $pages->base(), '/');
                    $page_route = '/' . ltrim(str_replace($base_url, '', $folder), '/');

                    $ext_page = $pages->find($page_route, true);
                    if ($ext_page) {
                        $media = $ext_page->media();
                    } else {
                        $grav->fireEvent('onMediaLocate', new Event(['route' => $page_route, 'media' => &$media]));
                    }
                }
            }
        }

        // If there is a media file that matches the path referenced..
        // A stream URI can name a file that is not media (no medium for it).
        $found = $media && $filename && isset($media[$filename]) ? $media[$filename] : null;
        if ($found) {
            // Work on a copy: the page's medium is shared by every embed of the
            // file, and actions like the querystring outlive reset().
            /** @var Medium $medium */
            $medium = $found->copy();

            // Process operations
            $medium = $this->processMediaActions($medium, $url_parts);
            $element_excerpt = $excerpt['element']['attributes'];

            $alt = $element_excerpt['alt'] ?? '';
            $title = $element_excerpt['title'] ?? '';
            $class = $element_excerpt['class'] ?? '';
            $id = $element_excerpt['id'] ?? '';

            $excerpt['element'] = $medium->parsedownElement($title, $alt, $class, $id, true);
        } else {
            // Not a current page media file, see if it needs converting to relative.
            $excerpt['element']['attributes']['src'] = Uri::buildUrl($url_parts);
        }

        return $excerpt;
    }

    /**
     * Process media actions
     *
     * @param Medium $medium
     * @param string|array $url
     * @return Medium|Link
     */
    public function processMediaActions($medium, $url)
    {
        $url_parts = is_string($url) ? $this->parseUrl($url) : $url;
        $actions = [];


        // if there is a query, then parse it and build action calls
        if (isset($url_parts['query'])) {
            foreach (explode('&', (string) $url_parts['query']) as $item) {
                $parts = explode('=', $item, 2);
                $actions[] = ['method' => $parts[0], 'params' => $parts[1] ?? null];
            }
        }

        // `system.images.defaults` is image configuration, so it must only be
        // applied to image media. Applying it to audio, video or a document
        // replaced the player or download with a linked thumbnail (`link`) and
        // pushed the HTML attributes through the medium's `__call()` URL
        // passthrough, which appended them to the querystring instead.
        // Individual defaults are also checked against the medium: an SVG or an
        // animated GIF is an image but has no decoding()/fetchpriority(), and
        // would leak those the same way. getgrav/grav#4264.
        $defaults = $this->config['images']['defaults'] ?? [];
        if (count($defaults) && $medium instanceof ImageMediaInterface) {
            // An image manipulation such as `resize` is not a real method, it is
            // dispatched by ImageMediaTrait::__call() off its own allowlist, so ask
            // for that too. Without it every processing default was silently dropped.
            // getgrav/grav#4282.
            $magic = property_exists($medium, 'magic_actions') ? (array) $medium::$magic_actions : [];

            foreach ($defaults as $method => $params) {
                if (!method_exists($medium, (string) $method) && !in_array((string) $method, $magic, true)) {
                    continue;
                }

                if (array_search($method, array_column($actions, 'method')) === false) {
                    $actions[] = [
                        'method' => $method,
                        'params' => $params,
                        'trusted' => true,
                    ];
                }
            }
        }

        // loop through actions for the image and call them
        foreach ($actions as $action) {
            $method = (string) $action['method'];
            $hasMethod = $medium instanceof Link ? $medium->hasMethod($method) : method_exists($medium, $method);
            if (empty($action['trusted']) && $hasMethod && !Medium::isAllowedAction($method)) {
                continue;
            }

            $matches = [];

            if (preg_match('/\[(.*)\]/', (string) $action['params'], $matches)) {
                $args = [explode(',', $matches[1])];
            } else {
                $args = explode(',', (string) $action['params']);
            }

            // Only media and link results replace the current medium.
            $result = $medium->{$method}(...$args);
            if ($result instanceof MediaObjectInterface || $result instanceof MediaLinkInterface) {
                $medium = $result;
            }
        }

        if (isset($url_parts['fragment'])) {
            $medium->urlHash($url_parts['fragment']);
        }

        return $medium;
    }

    /**
     * Variation of parse_url() which works also with local streams.
     *
     * @param string $url
     * @return array
     */
    protected function parseUrl(string $url)
    {
        $url_parts = Utils::multibyteParseUrl($url);

        if (isset($url_parts['scheme'])) {
            /** @var UniformResourceLocator $locator */
            $locator = Grav::instance()['locator'];
            $is_registered_stream = $locator->schemeExists($url_parts['scheme']);

            $rebuilt = $url_parts['scheme'] . ':' . ($url_parts['host'] ?? '') . ($url_parts['path'] ?? '');

            if (
                !$is_registered_stream
                && strpos($url, '://') === false
                && (
                    !preg_match('/^[a-zA-Z][a-zA-Z0-9+.-]*$/', $url_parts['scheme'])
                    || static::isLocalMediaFilename($rebuilt)
                )
            ) {
                // parse_url() misreads a relative filename that merely contains a
                // literal ':' (e.g. "2025-06-29T13:36:56.png") as a scheme:path
                // split, because unlike RFC 3986 it allows a "scheme" to start
                // with a digit. Two things mark such a "scheme" as untrusted, and
                // either is enough (getgrav/grav#3933):
                //
                //   1. It fails RFC 3986 scheme grammar - a real scheme always
                //      starts with a letter, so "2025-06-29T13" cannot be one.
                //   2. The whole reference names a file we serve as media, e.g.
                //      "note:2025.png" or "IMG:001.png". Grammar alone cannot
                //      separate those from an unknown protocol, but no real
                //      scheme carries a media extension on its path, whereas an
                //      editor pasting a colon-named attachment is routine.
                //
                // Either way the reference matches no registered stream, so it is
                // rebuilt as a plain path and resolved against the page's media.
                $url_parts['path'] = $rebuilt;
                unset($url_parts['scheme'], $url_parts['host'], $url_parts['port'], $url_parts['user'], $url_parts['pass']);
            } elseif ($is_registered_stream) {
                // Special handling for the streams.
                if (isset($url_parts['host'])) {
                    // Merge host and path into a path.
                    $url_parts['path'] = $url_parts['host'] . (isset($url_parts['path']) ? '/' . $url_parts['path'] : '');
                    unset($url_parts['host']);
                }

                $url_parts['stream'] = true;
            }
        }

        return $url_parts;
    }

    /**
     * Whether a reference is an inline data: URI.
     *
     * @param string $url
     * @return bool
     */
    protected static function isDataUri(string $url): bool
    {
        return strncasecmp(ltrim($url), 'data:', 5) === 0;
    }

    /**
     * Whether a colon-bearing reference names a file Grav serves as media.
     *
     * Used to recognise a filename such as `note:2025.png` that RFC 3986 scheme
     * grammar cannot distinguish from an unknown protocol, since both are a
     * letter-led token followed by a colon. Real schemes never carry a media
     * extension on their path, so the extension is the disambiguator.
     *
     * The protocols Grav itself treats as external are excluded outright, so a
     * `mailto:`/`tel:`/`git:` reference is never reinterpreted as a local file
     * whatever it happens to end with.
     *
     * @param string $candidate Reference rebuilt as a plain path.
     * @return bool
     */
    protected static function isLocalMediaFilename(string $candidate): bool
    {
        if (Uri::isExternal($candidate) || str_starts_with($candidate, 'data:')) {
            return false;
        }

        $extension = strtolower(Utils::pathinfo($candidate, PATHINFO_EXTENSION) ?: '');
        if ($extension === '') {
            return false;
        }

        return (bool) Grav::instance()['config']->get('media.types.' . $extension);
    }
}
