<?php

use CRM_Oembed_ExtensionUtil as E;

/**
 * The `civicrm/share?url=ABSOLUTE_URL` route defines a stub/placeholder.
 * It can be used to generate alternative oEmbed links with coerced parameters
 * (such as `maxwidth` or `maxheight`).
 */
class CRM_Oembed_Page_OembedShare extends CRM_Core_Page {

  public function run() {
    $url = CRM_Utils_Request::retrieve('url', 'String');

    $parsedUrl = \CRM_Utils_Url::parseInternalRoute($url);
    parse_str($parsedUrl['query'] ?? '', $parsedUrlQuery);

    if (!Civi::service('oembed')->isAllowedRoute($parsedUrl['path'])) {
      throw new \CRM_Core_Exception('Route does permit sharing');
    }

    // The actual <HEAD><LINK></HEAD> tags are generated by OembedDiscovery.

    CRM_Core_Region::instance('oembed-share')->add([
      'script' => sprintf("window.location.href = %s;", json_encode((string) $url)),
    ]);
    CRM_Core_Region::instance('oembed-share')->add([
      'markup' => htmlentities(ts('Redirecting...')),
    ]);

    return parent::run();
  }

}
