4 * Tweeper - a Twitter to RSS web scraper.
6 * Copyright (C) 2013-2015 Antonio Ospite <ao2@ao2.it>
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 require_once 'Symfony/Component/Serializer/autoload.php';
24 use Symfony\Component\Serializer\Serializer;
25 use Symfony\Component\Serializer\Encoder\XmlEncoder;
26 use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
28 date_default_timezone_set('UTC');
31 * Scrape supported websites and perform conversion to RSS.
35 private static $userAgent = "Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20130405 Firefox/22.0";
38 * Constructor sets up {@link $generate_enclosure}.
40 public function __construct($generate_enclosure = FALSE) {
41 $this->generate_enclosure = $generate_enclosure;
45 * Convert numeric Epoch to the date format expected in a RSS document.
47 public static function epochToRssDate($timestamp) {
48 if (!is_numeric($timestamp) || is_nan($timestamp)) {
52 return gmdate(DATE_RSS, $timestamp);
56 * Convert generic date string to the date format expected in a RSS document.
58 public static function strToRssDate($date) {
59 $timestamp = strtotime($date);
60 if (FALSE === $timestamp) {
64 return Tweeper::epochToRssDate($timestamp);
68 * Convert string to UpperCamelCase.
70 public static function toUpperCamelCase($str, $delim = ' ') {
71 $str_upper = ucwords($str, $delim);
72 $str_camel_case = str_replace($delim, '', $str_upper);
73 return $str_camel_case;
77 * Get the contents from a URL.
79 private static function getUrlContents($url) {
80 $ch = curl_init($url);
81 curl_setopt_array($ch, array(
82 CURLOPT_HEADER => FALSE,
83 // Follow http redirects to get the real URL.
84 CURLOPT_FOLLOWLOCATION => TRUE,
85 CURLOPT_RETURNTRANSFER => TRUE,
86 CURLOPT_SSL_VERIFYHOST => FALSE,
87 CURLOPT_SSL_VERIFYPEER => FALSE,
88 CURLOPT_HTTPHEADER => array('Accept-language: en'),
89 CURLOPT_USERAGENT => Tweeper::$userAgent,
91 $contents = curl_exec($ch);
98 * Get the headers from a URL.
100 private static function getUrlInfo($url) {
101 $ch = curl_init($url);
102 curl_setopt_array($ch, array(
103 CURLOPT_HEADER => TRUE,
104 CURLOPT_NOBODY => TRUE,
105 // Follow http redirects to get the real URL.
106 CURLOPT_FOLLOWLOCATION => TRUE,
107 CURLOPT_RETURNTRANSFER => TRUE,
108 CURLOPT_SSL_VERIFYHOST => FALSE,
109 CURLOPT_SSL_VERIFYPEER => FALSE,
110 CURLOPT_USERAGENT => Tweeper::$userAgent,
113 $url_info = curl_getinfo($ch);
120 * Generate an RSS <enclosure/> element.
122 public static function generateEnclosure($url) {
123 $supported_content_types = array(
124 "application/octet-stream",
144 $url_info = Tweeper::getUrlInfo($url);
146 $supported = in_array($url_info['content_type'], $supported_content_types);
148 error_log("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url']);
152 // The RSS specification says that the enclosure element URL must be http.
153 // See http://sourceforge.net/p/feedvalidator/bugs/72/
154 $http_url = preg_replace("/^https/", "http", $url_info['url']);
156 $dom = new DOMDocument();
157 $enc = $dom->createElement('enclosure');
158 $enc->setAttribute('url', $http_url);
159 $enc->setAttribute('length', $url_info['download_content_length']);
160 $enc->setAttribute('type', $url_info['content_type']);
166 * Mimic the message from libxml.c::php_libxml_ctx_error_level()
168 private static function logXmlError($error) {
171 switch ($error->level) {
172 case LIBXML_ERR_WARNING:
173 $output .= "Warning $error->code: ";
176 case LIBXML_ERR_ERROR:
177 $output .= "Error $error->code: ";
180 case LIBXML_ERR_FATAL:
181 $output .= "Fatal Error $error->code: ";
185 $output .= trim($error->message);
188 $output .= " in $error->file";
191 $output .= " in Entity,";
194 $output .= " line $error->line";
200 * Convert json to XML.
202 private static function jsonToXml($json, $root_node_name) {
203 // Apparently the ObjectNormalizer used afterwards is not able to handle
204 // the stdClass object created by json_decode() with the default setting
205 // $assoc = false; so use $assoc = true.
206 $data = json_decode($json, $assoc = TRUE);
211 $encoder = new XmlEncoder();
212 $normalizer = new ObjectNormalizer();
213 $serializer = new Serializer(array($normalizer), array($encoder));
215 $serializer_options = array(
216 'xml_encoding' => "UTF-8",
217 'xml_format_output' => TRUE,
218 'xml_root_node_name' => $root_node_name,
221 $xml_data = $serializer->serialize($data, 'xml', $serializer_options);
223 trigger_error("Cannot serialize data", E_USER_ERROR);
231 * Convert the Instagram content to XML.
233 private function getXmlInstagramCom($html) {
234 // Extract the json data from the html code.
235 $json_match_expr = '/window._sharedData = (.*);/';
236 $ret = preg_match($json_match_expr, $html, $matches);
238 trigger_error("Cannot match expression: $json_match_expr\n", E_USER_ERROR);
242 return Tweeper::jsonToXml($matches[1], 'instagram');
246 * Make the Facebook HTML processable.
248 private function preprocessHtmlFacebookCom($html) {
249 $html = str_replace('<!--', '', $html);
250 $html = str_replace('-->', '', $html);
255 * Convert the HTML retrieved from the site to XML.
257 private function htmlToXml($html, $host) {
258 $xmlDoc = new DOMDocument();
260 // Handle warnings and errors when loading invalid HTML.
261 $xml_errors_value = libxml_use_internal_errors(TRUE);
263 // If there is a host-specific method to get the XML data, use it!
264 $get_xml_host_method = 'getXml' . Tweeper::toUpperCamelCase($host, '.');
265 if (method_exists($this, $get_xml_host_method)) {
266 $xml_data = call_user_func_array(array($this, $get_xml_host_method), array($html));
267 $xmlDoc->loadXML($xml_data);
270 $xmlDoc->loadHTML($html);
273 foreach (libxml_get_errors() as $xml_error) {
274 Tweeper::logXmlError($xml_error);
276 libxml_clear_errors();
277 libxml_use_internal_errors($xml_errors_value);
283 * Load a stylesheet if the web site is supported.
285 private function loadStylesheet($host) {
286 $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
287 if (FALSE === file_exists($stylesheet)) {
288 trigger_error("Conversion to RSS not supported for $host ($stylesheet not found)", E_USER_ERROR);
292 $stylesheet_contents = Tweeper::getUrlContents($stylesheet);
294 $xslDoc = new DOMDocument();
295 $xslDoc->loadXML($stylesheet_contents);
297 $xsltProcessor = new XSLTProcessor();
298 $xsltProcessor->registerPHPFunctions();
299 $xsltProcessor->setParameter('', 'generate-enclosure', $this->generate_enclosure);
300 $xsltProcessor->importStylesheet($xslDoc);
302 return $xsltProcessor;
306 * Convert the site content to RSS.
308 public function tweep($src_url) {
309 $url = parse_url($src_url);
310 if (FALSE === $url || empty($url["host"])) {
311 trigger_error("Invalid URL: $src_url", E_USER_ERROR);
315 // Strip the leading www. to be more forgiving on input URLs.
316 $host = preg_replace('/^www\./', '', $url["host"]);
318 $xsltProcessor = $this->loadStylesheet($host);
319 if (NULL === $xsltProcessor) {
323 $html = Tweeper::getUrlContents($src_url);
324 if (FALSE === $html) {
328 $preprocess_html_host_method = 'preprocessHtml' . Tweeper::toUpperCamelCase($host, '.');
329 if (method_exists($this, $preprocess_html_host_method)) {
330 $html = call_user_func_array(array($this, $preprocess_html_host_method), array($html));
333 $xmlDoc = $this->htmlToXml($html, $host);
334 if (NULL === $xmlDoc) {
338 $output = $xsltProcessor->transformToXML($xmlDoc);
340 if (FALSE === $output) {
341 trigger_error('XSL transformation failed.', E_USER_ERROR);
350 * Check if the script is being run from the command line.
353 return (php_sapi_name() === "cli");
357 * Show the script usage.
359 function usage($argv) {
361 $usage = "{$argv[0]} [-e|-h|--help] <src_url>\n";
364 $usage = htmlentities("{$_SERVER['SCRIPT_NAME']}?src_url=<src_url>&generate_enclosure=<0|1>");
367 return "usage: $usage";
371 * Parse command line options.
373 function parse_options_cli($argv, $argc) {
375 'generate_enclosure' => FALSE,
382 $cli_options = getopt("eh", array("help"));
383 foreach ($cli_options as $opt => $val) {
386 $options['generate_enclosure'] = TRUE;
395 fwrite(STDERR, usage($argv));
400 $options['src_url'] = $argv[count($cli_options) + 1];
406 * Parse options passed from a query string.
408 function parse_options_query_string() {
410 'generate_enclosure' => FALSE,
413 if (isset($_GET['src_url'])) {
414 $options['src_url'] = $_GET['src_url'];
417 if (isset($_GET['generate_enclosure'])) {
418 $options['generate_enclosure'] = $_GET['generate_enclosure'] == 1;
425 $options = parse_options_cli($argv, $argc);
426 $error_stream = fopen('php://stderr', 'w');
429 $options = parse_options_query_string();
430 $error_stream = fopen('php://output', 'w');
433 if (!isset($options['src_url'])) {
434 fwrite($error_stream, usage(is_cli() ? $argv : NULL));
438 $tweeper = new Tweeper($options['generate_enclosure']);
439 echo $tweeper->tweep($options['src_url']);