<?php

namespace Tweeper;

/**
 * @file
 * Tweeper - a Twitter to RSS web scraper.
 *
 * Copyright (C) 2013-2020  Antonio Ospite <ao2@ao2.it>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

use DOMDocument;
use XSLTProcessor;

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

date_default_timezone_set('UTC');

/**
 * Scrape supported websites and perform conversion to RSS.
 */
class Tweeper {

  private static $userAgent = "APIs-Google (+https://developers.google.com/webmasters/APIs-Google.html)";
  private static $maxConnectionTimeout = 5;
  private static $maxConnectionRetries = 5;

  /**
   * Create a new Tweeper object controlling optional settings.
   *
   * @param bool $generate_enclosure
   *   Enables the creation of <enclosure/> elements (disabled by default).
   * @param bool $show_usernames
   *   Enables showing the username in front of the content for multi-user
   *   sites (enabled by default). Only some stylesheets supports this
   *   functionality (twitter, instagram, pump.io).
   * @param bool $show_multimedia
   *   Enables showing multimedia content (images, videos) directly in the
   *   item description (enabled by default). Only some stylesheets supports
   *   this functionality (twitter, instagram, dilbert).
   * @param bool $verbose_output
   *   Enables showing non-fatal errors like XML parsing errors.
   */
  public function __construct($generate_enclosure = FALSE, $show_usernames = TRUE, $show_multimedia = TRUE, $verbose_output = TRUE) {
    $this->generate_enclosure = $generate_enclosure;
    $this->show_usernames = $show_usernames;
    $this->show_multimedia = $show_multimedia;
    $this->verbose_output = $verbose_output;
  }

  /**
   * Convert numeric Epoch to the date format expected in a RSS document.
   */
  public static function epochToRssDate($timestamp) {
    if (!is_numeric($timestamp) || is_nan($timestamp)) {
      $timestamp = 0;
    }

    return gmdate(DATE_RSS, $timestamp);
  }

  /**
   * Convert generic date string to the date format expected in a RSS document.
   */
  public static function strToRssDate($date) {
    $timestamp = strtotime($date);
    if (FALSE === $timestamp) {
      $timestamp = 0;
    }

    return Tweeper::epochToRssDate($timestamp);
  }

  /**
   * Convert string to UpperCamelCase.
   */
  public static function toUpperCamelCase($str, $delim = ' ') {
    $str_upper = ucwords($str, $delim);
    $str_camel_case = str_replace($delim, '', $str_upper);
    return $str_camel_case;
  }

  /**
   * Perform a cURL session multiple times when it fails with a timeout.
   *
   * @param resource $ch
   *   a cURL session handle.
   */
  private static function curlExec($ch) {
    $ret = FALSE;
    $attempt = 0;
    do {
      $ret = curl_exec($ch);
      if (FALSE === $ret) {
        trigger_error(curl_error($ch), E_USER_WARNING);
      }
    } while (curl_errno($ch) == CURLE_OPERATION_TIMEDOUT && ++$attempt < Tweeper::$maxConnectionRetries);

    $response_code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    if (FALSE === $response_code) {
      trigger_error(curl_error($ch), E_USER_WARNING);
      return FALSE;
    }

    if ($response_code >= 400) {
      trigger_error("HTTP reponse code $response_code", E_USER_WARNING);
      return FALSE;
    }

    return $ret;
  }

  /**
   * Get the contents from a URL.
   */
  private static function getUrlContents($url, $user_agent = NULL) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
      CURLOPT_HEADER => FALSE,
      CURLOPT_CONNECTTIMEOUT => Tweeper::$maxConnectionTimeout,
      // Follow http redirects to get the real URL.
      CURLOPT_FOLLOWLOCATION => TRUE,
      CURLOPT_COOKIEFILE => "",
      CURLOPT_RETURNTRANSFER => TRUE,
      CURLOPT_HTTPHEADER => ['Accept-language: en'],
      CURLOPT_USERAGENT => isset($user_agent) ? $user_agent : Tweeper::$userAgent,
    ]);
    $contents = Tweeper::curlExec($ch);
    curl_close($ch);

    return $contents;
  }

  /**
   * Get the headers from a URL.
   */
  private static function getUrlInfo($url, $user_agent = NULL) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
      CURLOPT_HEADER => TRUE,
      CURLOPT_NOBODY => TRUE,
      CURLOPT_CONNECTTIMEOUT => Tweeper::$maxConnectionTimeout,
      // Follow http redirects to get the real URL.
      CURLOPT_FOLLOWLOCATION => TRUE,
      CURLOPT_RETURNTRANSFER => TRUE,
      CURLOPT_USERAGENT => isset($user_agent) ? $user_agent : Tweeper::$userAgent,
    ]);

    $ret = Tweeper::curlExec($ch);
    if (FALSE === $ret) {
      curl_close($ch);
      return FALSE;
    }

    $url_info = curl_getinfo($ch);
    if (FALSE === $url_info) {
      trigger_error(curl_error($ch), E_USER_WARNING);
    }
    curl_close($ch);

    return $url_info;
  }

  /**
   * Generate an RSS <enclosure/> element.
   */
  public static function generateEnclosure($url) {
    $supported_content_types = [
      "application/octet-stream",
      "application/ogg",
      "application/pdf",
      "audio/aac",
      "audio/mp4",
      "audio/mpeg",
      "audio/ogg",
      "audio/vorbis",
      "audio/wav",
      "audio/webm",
      "audio/x-midi",
      "image/gif",
      "image/jpeg",
      "image/png",
      "video/avi",
      "video/mp4",
      "video/mpeg",
      "video/ogg",
    ];

    $url_info = Tweeper::getUrlInfo($url);
    if (FALSE === $url_info) {
      trigger_error("Failed to retrieve info for URL: " . $url, E_USER_WARNING);
      return '';
    }

    $supported = in_array($url_info['content_type'], $supported_content_types);
    if (!$supported) {
      trigger_error("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url'], E_USER_WARNING);
      return '';
    }

    // The RSS specification says that the enclosure element URL must be http.
    // See http://sourceforge.net/p/feedvalidator/bugs/72/
    $http_url = preg_replace("/^https/", "http", $url_info['url']);

    // When the server does not provide a Content-Length header,
    // curl_getinfo() would return a negative value for
    // "download_content_length", however RSS recommends to use 0 when the
    // enclosure's size cannot be determined.
    // See: https://www.feedvalidator.org/docs/error/UseZeroForUnknown.html
    $length = max($url_info['download_content_length'], 0);

    $dom = new DOMDocument();
    $enc = $dom->createElement('enclosure');
    $enc->setAttribute('url', $http_url);
    $enc->setAttribute('length', $length);
    $enc->setAttribute('type', $url_info['content_type']);

    return $enc;
  }

  /**
   * Mimic the message from libxml.c::php_libxml_ctx_error_level()
   */
  private static function logXmlError($error) {
    $output = "";

    switch ($error->level) {
      case LIBXML_ERR_WARNING:
        $output .= "Warning $error->code: ";
        break;

      case LIBXML_ERR_ERROR:
        $output .= "Error $error->code: ";
        break;

      case LIBXML_ERR_FATAL:
        $output .= "Fatal Error $error->code: ";
        break;
    }

    $output .= trim($error->message);

    if ($error->file) {
      $output .= " in $error->file";
    }
    else {
      $output .= " in Entity,";
    }

    $output .= " line $error->line";

    trigger_error($output, E_USER_WARNING);
  }

  /**
   * Convert json to XML.
   */
  private static function jsonToXml($json, $root_node_name) {
    // Apparently the ObjectNormalizer used afterwards is not able to handle
    // the stdClass object created by json_decode() with the default setting
    // $assoc = false; so use $assoc = true.
    $data = json_decode($json, $assoc = TRUE);
    if (!$data) {
      return NULL;
    }

    $encoder = new XmlEncoder();
    $normalizer = new ObjectNormalizer();
    $serializer = new Serializer([$normalizer], [$encoder]);

    $serializer_options = [
      'xml_encoding' => "UTF-8",
      'xml_format_output' => TRUE,
      'xml_root_node_name' => $root_node_name,
    ];

    $xml_data = $serializer->serialize($data, 'xml', $serializer_options);
    if (!$xml_data) {
      trigger_error("Cannot serialize data", E_USER_WARNING);
      return NULL;
    }

    return $xml_data;
  }

  /**
   * Convert the Instagram content to XML.
   */
  private function getXmlInstagramCom($html) {
    // Extract the json data from the html code.
    $json_match_expr = '/window._sharedData = (.*);/';
    $ret = preg_match($json_match_expr, $html, $matches);
    if ($ret !== 1) {
      trigger_error("Cannot match expression: $json_match_expr\n", E_USER_WARNING);
      return NULL;
    }

    $data = json_decode($matches[1], $assoc = TRUE);

    // The "qe" object contains elements which will result in invalid XML
    // element names, so remove it.
    unset($data["qe"]);

    // The "knobs" object contains elements with undefined namespaces, so
    // remove it to silence an error message.
    unset($data["knobs"]);

    // Stop here in case Instagram redirected to the login page, this can
    // happen when too many consecutive requests have been made from the same
    // IP.
    if (array_key_exists("LoginAndSignupPage", $data["entry_data"])) {
      trigger_error("Cannot open instagram page: redirected to Login page.\n", E_USER_WARNING);
      return NULL;
    }

    $json = json_encode($data);

    return Tweeper::jsonToXml($json, 'instagram');
  }

  /**
   * Make the Facebook HTML processable.
   */
  private function preprocessHtmlFacebookCom($html) {
    $html = str_replace('<!--', '', $html);
    $html = str_replace('-->', '', $html);
    return $html;
  }

  /**
   * Convert the HTML retrieved from the site to XML.
   */
  private function htmlToXml($html, $host) {
    $xmlDoc = new DOMDocument();

    // Handle warnings and errors when loading invalid HTML.
    $xml_errors_value = libxml_use_internal_errors(TRUE);

    // If there is a host-specific method to get the XML data, use it!
    $get_xml_host_method = 'getXml' . Tweeper::toUpperCamelCase($host, '.');
    if (method_exists($this, $get_xml_host_method)) {
      $xml_data = call_user_func_array([$this, $get_xml_host_method], [$html]);
      if (NULL === $xml_data) {
        return NULL;
      }
      $xmlDoc->loadXML($xml_data);
    }
    else {
      $xmlDoc->loadHTML($html);
    }

    if ($this->verbose_output) {
      foreach (libxml_get_errors() as $xml_error) {
        Tweeper::logXmlError($xml_error);
      }
    }
    libxml_clear_errors();
    libxml_use_internal_errors($xml_errors_value);

    return $xmlDoc;
  }

  /**
   * Load a stylesheet if the web site is supported.
   */
  private function loadStylesheet($host) {
    $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
    if (FALSE === file_exists($stylesheet)) {
      trigger_error("Conversion to RSS not supported for $host ($stylesheet not found)", E_USER_WARNING);
      return NULL;
    }

    $stylesheet_contents = file_get_contents($stylesheet);
    if (FALSE === $stylesheet_contents) {
      trigger_error("Cannot open $stylesheet", E_USER_WARNING);
      return NULL;
    }

    $xslDoc = new DOMDocument();
    $xslDoc->loadXML($stylesheet_contents);

    $xsltProcessor = new XSLTProcessor();
    $xsltProcessor->registerPHPFunctions();
    $xsltProcessor->setParameter('', 'generate-enclosure', $this->generate_enclosure);
    $xsltProcessor->setParameter('', 'show-usernames', $this->show_usernames);
    $xsltProcessor->setParameter('', 'show-multimedia', $this->show_multimedia);
    $xsltProcessor->importStylesheet($xslDoc);

    return $xsltProcessor;
  }

  /**
   * Convert the site content to RSS.
   */
  public function tweep($src_url, $host = NULL, $validate_scheme = TRUE) {
    $url = parse_url($src_url);
    if (FALSE === $url) {
      trigger_error("Invalid URL: $src_url", E_USER_WARNING);
      return NULL;
    }

    if (TRUE === $validate_scheme) {
      $scheme = $url["scheme"];
      if (!in_array($scheme, ["http", "https"])) {
        trigger_error("unsupported scheme: $scheme", E_USER_WARNING);
        return NULL;
      }
    }

    // If the host is not given derive it from the URL.
    if (NULL === $host) {
      if (empty($url["host"])) {
        trigger_error("Invalid host in URL: $src_url", E_USER_WARNING);
        return NULL;
      }
      // Strip the leading www. to be more forgiving on input URLs.
      $host = preg_replace('/^www\./', '', $url["host"]);
    }

    $xsltProcessor = $this->loadStylesheet($host);
    if (NULL === $xsltProcessor) {
      return NULL;
    }

    $html = Tweeper::getUrlContents($src_url);
    if (FALSE === $html) {
      trigger_error("Failed to retrieve $src_url", E_USER_WARNING);
      return NULL;
    }

    $preprocess_html_host_method = 'preprocessHtml' . Tweeper::toUpperCamelCase($host, '.');
    if (method_exists($this, $preprocess_html_host_method)) {
      $html = call_user_func_array([$this, $preprocess_html_host_method], [$html]);
    }

    $xmlDoc = $this->htmlToXml($html, $host);
    if (NULL === $xmlDoc) {
      return NULL;
    }

    $output = $xsltProcessor->transformToXML($xmlDoc);
    if (FALSE === $output) {
      trigger_error('XSL transformation failed.', E_USER_WARNING);
      return NULL;
    }

    return $output;
  }

}
