3  * tweeper - a Twitter to RSS web scraper
 
   5  * Copyright (C) 2013-2015  Antonio Ospite <ao2@ao2.it>
 
   7  * This program is free software: you can redistribute it and/or modify
 
   8  * it under the terms of the GNU General Public License as published by
 
   9  * the Free Software Foundation, either version 3 of the License, or
 
  10  * (at your option) any later version.
 
  12  * This program is distributed in the hope that it will be useful,
 
  13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  15  * GNU General Public License for more details.
 
  17  * You should have received a copy of the GNU General Public License
 
  18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
  21 require_once 'Symfony/Component/Serializer/autoload.php';
 
  23 use Symfony\Component\Serializer\Serializer;
 
  24 use Symfony\Component\Serializer\Encoder\XmlEncoder;
 
  25 use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
 
  27 date_default_timezone_set('UTC');
 
  31   private static $USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20130405 Firefox/22.0";
 
  33   public function __construct($generate_enclosure = FALSE) {
 
  34     $this->generate_enclosure = $generate_enclosure;
 
  37   public static function epoch_to_gmdate($timestamp)
 
  39     if (!is_numeric($timestamp) || is_nan($timestamp)) {
 
  43     return gmdate('D, d M Y H:i:s', $timestamp) . ' GMT';
 
  46   public static function str_to_gmdate($date)
 
  48     $timestamp = strtotime($date);
 
  49     if (FALSE === $timestamp) {
 
  53     return Tweeper::epoch_to_gmdate($timestamp);
 
  56   private static function get_contents($url)
 
  58     $ch = curl_init($url);
 
  59     curl_setopt_array($ch, array(
 
  60       CURLOPT_HEADER => FALSE,
 
  61       CURLOPT_FOLLOWLOCATION => TRUE,  // follow http redirects to get the real URL
 
  62       CURLOPT_RETURNTRANSFER => TRUE,
 
  63       CURLOPT_SSL_VERIFYHOST => FALSE,
 
  64       CURLOPT_SSL_VERIFYPEER => FALSE,
 
  65       CURLOPT_HTTPHEADER => array('Accept-language: en'),
 
  66       CURLOPT_USERAGENT => Tweeper::$USER_AGENT,
 
  68     $contents = curl_exec($ch);
 
  74   private static function get_info($url)
 
  76     $ch = curl_init($url);
 
  77     curl_setopt_array($ch, array(
 
  78       CURLOPT_HEADER => TRUE,
 
  79       CURLOPT_NOBODY => TRUE,
 
  80       CURLOPT_FOLLOWLOCATION => TRUE,  // follow http redirects to get the real URL
 
  81       CURLOPT_RETURNTRANSFER => TRUE,
 
  82       CURLOPT_SSL_VERIFYHOST => FALSE,
 
  83       CURLOPT_SSL_VERIFYPEER => FALSE,
 
  84       CURLOPT_USERAGENT => Tweeper::$USER_AGENT,
 
  87     $url_info = curl_getinfo($ch);
 
  93   public static function generate_enclosure($url)
 
  95     $supported_content_types = array(
 
 113     // The RSS specification says that the enclosure element url must be http.
 
 114     // See http://sourceforge.net/p/feedvalidator/bugs/72/
 
 115     $http_url = preg_replace("/^https/", "http", $url);
 
 117     $url_info = Tweeper::get_info($http_url);
 
 119     $supported = in_array($url_info['content_type'], $supported_content_types);
 
 121       error_log("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url']);
 
 125     $dom = new DomDocument();
 
 126     $enc = $dom->createElement('enclosure');
 
 127     $enc->setAttribute('url', $url_info['url']);
 
 128     $enc->setAttribute('length', $url_info['download_content_length']);
 
 129     $enc->setAttribute('type', $url_info['content_type']);
 
 131     $dom->appendChild($enc);
 
 133     return $dom->saveXML($enc);
 
 136   /* Mimic the message from libxml.c::php_libxml_ctx_error_level() */
 
 137   private function log_xml_error($error) {
 
 140     switch ($error->level) {
 
 141     case LIBXML_ERR_WARNING:
 
 142       $output .= "Warning $error->code: ";
 
 144     case LIBXML_ERR_ERROR:
 
 145       $output .= "Error $error->code: ";
 
 147     case LIBXML_ERR_FATAL:
 
 148       $output .= "Fatal Error $error->code: ";
 
 152     $output .= trim($error->message);
 
 155       $output .= " in $error->file";
 
 157       $output .= " in Entity,";
 
 160     $output .=" line $error->line";
 
 165   private function load_stylesheet($host) {
 
 166     $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
 
 167     if (FALSE === file_exists($stylesheet)) {
 
 168       trigger_error("Conversion to RSS not supported for $host ($stylesheet not found)", E_USER_ERROR);
 
 172     $stylesheet_contents = $this->get_contents($stylesheet);
 
 174     $xslDoc = new DOMDocument();
 
 175     $xslDoc->loadXML($stylesheet_contents);
 
 177     $xsltProcessor = new XSLTProcessor();
 
 178     $xsltProcessor->registerPHPFunctions();
 
 179     $xsltProcessor->setParameter('', 'generateEnclosure', $this->generate_enclosure);
 
 180     $xsltProcessor->importStylesheet($xslDoc);
 
 182     return $xsltProcessor;
 
 185   private function json_to_xml($html, $json_match_expr, $rootName) {
 
 186     // pre-process, convert json to XML
 
 187     $ret = preg_match($json_match_expr, $html, $matches);
 
 189       trigger_error("Cannot match expression: $json_match_expr\n", E_USER_ERROR);
 
 193     // Apparenty the ObjectNormalizer used afterwards is not able to handle
 
 194     // the stdClass object created by json_decode() with the default setting
 
 195     // $assoc = false; so use $assoc = true 
 
 196     $data = json_decode($matches[1], $assoc = true);
 
 201     $encoder = new XmlEncoder();
 
 202     $normalizer = new ObjectNormalizer();
 
 203     $serializer = new Serializer(array($normalizer), array($encoder));
 
 205     $serializer_options = array (
 
 206       'xml_encoding' => "UTF-8",
 
 207       'xml_format_output' => TRUE,
 
 208       'xml_root_node_name' => $rootName,
 
 211     $xml_data = $serializer->serialize($data, 'xml', $serializer_options);
 
 213       trigger_error("Cannot serialize data", E_USER_ERROR);
 
 220   private function get_xml_instagram_com($html) {
 
 221     return $this->json_to_xml($html, '/window._sharedData = (.*);/', 'instagram');
 
 224   private function preprocess_html_facebook_com($html) {
 
 225     $html = str_replace('<!--', '', $html);
 
 226     $html = str_replace('-->', '', $html);
 
 230   private function html_to_xml($html, $host) {
 
 231     $xmlDoc = new DOMDocument();
 
 233     // Handle warnings and errors when loading invalid HTML.
 
 234     $xml_errors_value = libxml_use_internal_errors(true);
 
 236     // If there is a host-specific method to get the xml data, use it!
 
 237     $get_xml_host_method = 'get_xml_' . str_replace(".", "_", $host);
 
 238     if (method_exists($this, $get_xml_host_method)) {
 
 239       $xml_data = call_user_func_array(array($this, $get_xml_host_method), array($html));
 
 240       $xmlDoc->loadXML($xml_data);
 
 242       $xmlDoc->loadHTML($html);
 
 245     foreach (libxml_get_errors() as $xml_error) {
 
 246       $this->log_xml_error($xml_error);
 
 248     libxml_clear_errors();
 
 249     libxml_use_internal_errors($xml_errors_value);
 
 254   public function tweep($src_url) {
 
 255     $url = parse_url($src_url);
 
 256     if (FALSE === $url || empty($url["host"])) {
 
 257       trigger_error("Invalid url: $src_url", E_USER_ERROR);
 
 261     // Strip the leading www. to be more forgiving on input URLs
 
 262     $host = preg_replace('/^www\./', '', $url["host"]);
 
 264     $xsltProcessor = $this->load_stylesheet($host);
 
 265     if (NULL === $xsltProcessor) {
 
 269     $html = $this->get_contents($src_url);
 
 270     if (FALSE === $html) {
 
 274     $preprocess_html_host_method = 'preprocess_html_' . str_replace(".", "_", $host);
 
 275     if (method_exists($this, $preprocess_html_host_method)) {
 
 276       $html = call_user_func_array(array($this, $preprocess_html_host_method), array($html));
 
 279     $xmlDoc = $this->html_to_xml($html, $host);
 
 280     if (NULL === $xmlDoc) {
 
 284     $output = $xsltProcessor->transformToXML($xmlDoc);
 
 286     if (FALSE === $output) {
 
 287       trigger_error('XSL transformation failed.', E_USER_ERROR);
 
 296   return (php_sapi_name() === "cli");
 
 299 function usage($argv)
 
 302     $usage = "{$argv[0]} [-e|-h|--help] <src_url>\n";
 
 304     $usage = htmlentities("{$_SERVER['SCRIPT_NAME']}?src_url=<src_url>&generate_enclosure=<0|1>");
 
 307   return "usage: $usage";
 
 310 function parse_options_cli($argv, $argc)
 
 313     'generate_enclosure' => FALSE
 
 319   $cli_options = getopt("eh", array("help"));
 
 320   foreach ($cli_options as $opt => $val) {
 
 323       $options['generate_enclosure'] = TRUE;
 
 330       fwrite(STDERR, usage($argv));
 
 335   $options['src_url'] = $argv[count($cli_options) + 1];
 
 340 function parse_options_query_string()
 
 343     'generate_enclosure' => FALSE
 
 346   if (isset($_GET['src_url']))
 
 347     $options['src_url'] = $_GET['src_url'];
 
 349   if (isset($_GET['generate_enclosure']))
 
 350     $options['generate_enclosure'] = $_GET['generate_enclosure'] == 1;
 
 357   $options = parse_options_cli($argv, $argc);
 
 358   $ERROR_STREAM = fopen('php://stderr', 'w');
 
 360   $options = parse_options_query_string();
 
 361   $ERROR_STREAM = fopen('php://output', 'w');
 
 364 if (!isset($options['src_url'])) {
 
 365   fwrite($ERROR_STREAM, usage(is_cli() ? $argv : NULL));
 
 369 $tweeper = new Tweeper($options['generate_enclosure']);
 
 370 echo $tweeper->tweep($options['src_url']);