7  * Tweeper - a Twitter to RSS web scraper.
 
   9  * Copyright (C) 2013-2018  Antonio Ospite <ao2@ao2.it>
 
  11  * This program is free software: you can redistribute it and/or modify
 
  12  * it under the terms of the GNU General Public License as published by
 
  13  * the Free Software Foundation, either version 3 of the License, or
 
  14  * (at your option) any later version.
 
  16  * This program is distributed in the hope that it will be useful,
 
  17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  19  * GNU General Public License for more details.
 
  21  * You should have received a copy of the GNU General Public License
 
  22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
  28 use Symfony\Component\Serializer\Serializer;
 
  29 use Symfony\Component\Serializer\Encoder\XmlEncoder;
 
  30 use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
 
  32 date_default_timezone_set('UTC');
 
  35  * Scrape supported websites and perform conversion to RSS.
 
  39   private static $userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0";
 
  40   private static $maxConnectionTimeout = 5;
 
  41   private static $maxConnectionRetries = 5;
 
  44    * Create a new Tweeper object controlling optional settings.
 
  46    * @param bool $generate_enclosure
 
  47    *   Enables the creation of <enclosure/> elements (disabled by default).
 
  48    * @param bool $show_usernames
 
  49    *   Enables showing the username in front of the content for multi-user
 
  50    *   sites (enabled by default). Only some stylesheets supports this
 
  51    *   functionality (twitter, instagram, pump.io).
 
  52    * @param bool $show_multimedia
 
  53    *   Enables showing multimedia content (images, videos) directly in the
 
  54    *   item description (enabled by default). Only some stylesheets supports
 
  55    *   this functionality (twitter, instagram, dilbert).
 
  57   public function __construct($generate_enclosure = FALSE, $show_usernames = TRUE, $show_multimedia = TRUE) {
 
  58     $this->generate_enclosure = $generate_enclosure;
 
  59     $this->show_usernames = $show_usernames;
 
  60     $this->show_multimedia = $show_multimedia;
 
  64    * Convert numeric Epoch to the date format expected in a RSS document.
 
  66   public static function epochToRssDate($timestamp) {
 
  67     if (!is_numeric($timestamp) || is_nan($timestamp)) {
 
  71     return gmdate(DATE_RSS, $timestamp);
 
  75    * Convert generic date string to the date format expected in a RSS document.
 
  77   public static function strToRssDate($date) {
 
  78     $timestamp = strtotime($date);
 
  79     if (FALSE === $timestamp) {
 
  83     return Tweeper::epochToRssDate($timestamp);
 
  87    * Convert string to UpperCamelCase.
 
  89   public static function toUpperCamelCase($str, $delim = ' ') {
 
  90     $str_upper = ucwords($str, $delim);
 
  91     $str_camel_case = str_replace($delim, '', $str_upper);
 
  92     return $str_camel_case;
 
  96    * Perform a cURL session multiple times when it fails with a timeout.
 
  99    *   a cURL session handle.
 
 101   private static function curlExec($ch) {
 
 105       $ret = curl_exec($ch);
 
 106       if (FALSE === $ret) {
 
 107         trigger_error(curl_error($ch), E_USER_WARNING);
 
 109     } while (curl_errno($ch) == CURLE_OPERATION_TIMEDOUT && ++$attempt < Tweeper::$maxConnectionRetries);
 
 115    * Get the contents from a URL.
 
 117   private static function getUrlContents($url) {
 
 118     $ch = curl_init($url);
 
 119     curl_setopt_array($ch, array(
 
 120       CURLOPT_HEADER => FALSE,
 
 121       CURLOPT_CONNECTTIMEOUT => Tweeper::$maxConnectionTimeout,
 
 122       // Follow http redirects to get the real URL.
 
 123       CURLOPT_FOLLOWLOCATION => TRUE,
 
 124       CURLOPT_COOKIEFILE => "",
 
 125       CURLOPT_RETURNTRANSFER => TRUE,
 
 126       CURLOPT_SSL_VERIFYHOST => FALSE,
 
 127       CURLOPT_SSL_VERIFYPEER => FALSE,
 
 128       CURLOPT_HTTPHEADER => array('Accept-language: en'),
 
 129       CURLOPT_USERAGENT => Tweeper::$userAgent,
 
 131     $contents = Tweeper::curlExec($ch);
 
 138    * Get the headers from a URL.
 
 140   private static function getUrlInfo($url) {
 
 141     $ch = curl_init($url);
 
 142     curl_setopt_array($ch, array(
 
 143       CURLOPT_HEADER => TRUE,
 
 144       CURLOPT_NOBODY => TRUE,
 
 145       CURLOPT_CONNECTTIMEOUT => Tweeper::$maxConnectionTimeout,
 
 146       // Follow http redirects to get the real URL.
 
 147       CURLOPT_FOLLOWLOCATION => TRUE,
 
 148       CURLOPT_RETURNTRANSFER => TRUE,
 
 149       CURLOPT_SSL_VERIFYHOST => FALSE,
 
 150       CURLOPT_SSL_VERIFYPEER => FALSE,
 
 151       CURLOPT_USERAGENT => Tweeper::$userAgent,
 
 154     $ret = Tweeper::curlExec($ch);
 
 155     if (FALSE === $ret) {
 
 160     $url_info = curl_getinfo($ch);
 
 161     if (FALSE === $url_info) {
 
 162       trigger_error(curl_error($ch), E_USER_WARNING);
 
 170    * Generate an RSS <enclosure/> element.
 
 172   public static function generateEnclosure($url) {
 
 173     $supported_content_types = array(
 
 174       "application/octet-stream",
 
 194     $url_info = Tweeper::getUrlInfo($url);
 
 195     if (FALSE === $url_info) {
 
 196       trigger_error("Failed to retrieve info for URL: " . $url, E_USER_WARNING);
 
 200     $supported = in_array($url_info['content_type'], $supported_content_types);
 
 202       trigger_error("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url'], E_USER_WARNING);
 
 206     // The RSS specification says that the enclosure element URL must be http.
 
 207     // See http://sourceforge.net/p/feedvalidator/bugs/72/
 
 208     $http_url = preg_replace("/^https/", "http", $url_info['url']);
 
 210     // When the server does not provide a Content-Length header,
 
 211     // curl_getinfo() would return a negative value for
 
 212     // "download_content_length", however RSS recommends to use 0 when the
 
 213     // enclosure's size cannot be determined.
 
 214     // See: https://www.feedvalidator.org/docs/error/UseZeroForUnknown.html
 
 215     $length = max($url_info['download_content_length'], 0);
 
 217     $dom = new DOMDocument();
 
 218     $enc = $dom->createElement('enclosure');
 
 219     $enc->setAttribute('url', $http_url);
 
 220     $enc->setAttribute('length', $length);
 
 221     $enc->setAttribute('type', $url_info['content_type']);
 
 227    * Mimic the message from libxml.c::php_libxml_ctx_error_level()
 
 229   private static function logXmlError($error) {
 
 232     switch ($error->level) {
 
 233       case LIBXML_ERR_WARNING:
 
 234         $output .= "Warning $error->code: ";
 
 237       case LIBXML_ERR_ERROR:
 
 238         $output .= "Error $error->code: ";
 
 241       case LIBXML_ERR_FATAL:
 
 242         $output .= "Fatal Error $error->code: ";
 
 246     $output .= trim($error->message);
 
 249       $output .= " in $error->file";
 
 252       $output .= " in Entity,";
 
 255     $output .= " line $error->line";
 
 257     trigger_error($output, E_USER_WARNING);
 
 261    * Convert json to XML.
 
 263   private static function jsonToXml($json, $root_node_name) {
 
 264     // Apparently the ObjectNormalizer used afterwards is not able to handle
 
 265     // the stdClass object created by json_decode() with the default setting
 
 266     // $assoc = false; so use $assoc = true.
 
 267     $data = json_decode($json, $assoc = TRUE);
 
 272     $encoder = new XmlEncoder();
 
 273     $normalizer = new ObjectNormalizer();
 
 274     $serializer = new Serializer(array($normalizer), array($encoder));
 
 276     $serializer_options = array(
 
 277       'xml_encoding' => "UTF-8",
 
 278       'xml_format_output' => TRUE,
 
 279       'xml_root_node_name' => $root_node_name,
 
 282     $xml_data = $serializer->serialize($data, 'xml', $serializer_options);
 
 284       trigger_error("Cannot serialize data", E_USER_WARNING);
 
 292    * Convert the Instagram content to XML.
 
 294   private function getXmlInstagramCom($html) {
 
 295     // Extract the json data from the html code.
 
 296     $json_match_expr = '/window._sharedData = (.*);/';
 
 297     $ret = preg_match($json_match_expr, $html, $matches);
 
 299       trigger_error("Cannot match expression: $json_match_expr\n", E_USER_WARNING);
 
 303     $data = json_decode($matches[1], $assoc = TRUE);
 
 305     // The "qe" object contains elements which will result in invalid XML
 
 306     // element names, so remove it.
 
 309     // The "knobs" object contains elements with undefined namespaces, so
 
 310     // remove it to silence an error message.
 
 311     unset($data["knobs"]);
 
 313     $json = json_encode($data);
 
 315     return Tweeper::jsonToXml($json, 'instagram');
 
 319    * Make the Facebook HTML processable.
 
 321   private function preprocessHtmlFacebookCom($html) {
 
 322     $html = str_replace('<!--', '', $html);
 
 323     $html = str_replace('-->', '', $html);
 
 328    * Convert the HTML retrieved from the site to XML.
 
 330   private function htmlToXml($html, $host) {
 
 331     $xmlDoc = new DOMDocument();
 
 333     // Handle warnings and errors when loading invalid HTML.
 
 334     $xml_errors_value = libxml_use_internal_errors(TRUE);
 
 336     // If there is a host-specific method to get the XML data, use it!
 
 337     $get_xml_host_method = 'getXml' . Tweeper::toUpperCamelCase($host, '.');
 
 338     if (method_exists($this, $get_xml_host_method)) {
 
 339       $xml_data = call_user_func_array(array($this, $get_xml_host_method), array($html));
 
 340       $xmlDoc->loadXML($xml_data);
 
 343       $xmlDoc->loadHTML($html);
 
 346     foreach (libxml_get_errors() as $xml_error) {
 
 347       Tweeper::logXmlError($xml_error);
 
 349     libxml_clear_errors();
 
 350     libxml_use_internal_errors($xml_errors_value);
 
 356    * Load a stylesheet if the web site is supported.
 
 358   private function loadStylesheet($host) {
 
 359     $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
 
 360     if (FALSE === file_exists($stylesheet)) {
 
 361       trigger_error("Conversion to RSS not supported for $host ($stylesheet not found)", E_USER_WARNING);
 
 365     $stylesheet_contents = Tweeper::getUrlContents($stylesheet);
 
 366     if (FALSE === $stylesheet_contents) {
 
 367       trigger_error("Cannot open $stylesheet", E_USER_WARNING);
 
 371     $xslDoc = new DOMDocument();
 
 372     $xslDoc->loadXML($stylesheet_contents);
 
 374     $xsltProcessor = new XSLTProcessor();
 
 375     $xsltProcessor->registerPHPFunctions();
 
 376     $xsltProcessor->setParameter('', 'generate-enclosure', $this->generate_enclosure);
 
 377     $xsltProcessor->setParameter('', 'show-usernames', $this->show_usernames);
 
 378     $xsltProcessor->setParameter('', 'show-multimedia', $this->show_multimedia);
 
 379     $xsltProcessor->importStylesheet($xslDoc);
 
 381     return $xsltProcessor;
 
 385    * Convert the site content to RSS.
 
 387   public function tweep($src_url, $host = NULL, $validate_scheme = TRUE) {
 
 388     $url = parse_url($src_url);
 
 389     if (FALSE === $url) {
 
 390       trigger_error("Invalid URL: $src_url", E_USER_WARNING);
 
 394     if (TRUE === $validate_scheme) {
 
 395       $scheme = $url["scheme"];
 
 396       if (!in_array($scheme, array("http", "https"))) {
 
 397         trigger_error("unsupported scheme: $scheme", E_USER_WARNING);
 
 402     // If the host is not given derive it from the URL.
 
 403     if (NULL === $host) {
 
 404       if (empty($url["host"])) {
 
 405         trigger_error("Invalid host in URL: $src_url", E_USER_WARNING);
 
 408       // Strip the leading www. to be more forgiving on input URLs.
 
 409       $host = preg_replace('/^www\./', '', $url["host"]);
 
 412     $xsltProcessor = $this->loadStylesheet($host);
 
 413     if (NULL === $xsltProcessor) {
 
 417     $html = Tweeper::getUrlContents($src_url);
 
 418     if (FALSE === $html) {
 
 419       trigger_error("Failed to retrieve $src_url", E_USER_WARNING);
 
 423     $preprocess_html_host_method = 'preprocessHtml' . Tweeper::toUpperCamelCase($host, '.');
 
 424     if (method_exists($this, $preprocess_html_host_method)) {
 
 425       $html = call_user_func_array(array($this, $preprocess_html_host_method), array($html));
 
 428     $xmlDoc = $this->htmlToXml($html, $host);
 
 429     if (NULL === $xmlDoc) {
 
 433     $output = $xsltProcessor->transformToXML($xmlDoc);
 
 434     if (FALSE === $output) {
 
 435       trigger_error('XSL transformation failed.', E_USER_WARNING);