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:60.0) Gecko/20100101 Firefox/60.0";
42 * Create a new Tweeper object controlling optional settings.
44 * @param bool $generate_enclosure
45 * Enables the creation of <enclosure/> elements (disabled by default).
46 * @param bool $show_usernames
47 * Enables showing the username in front of the content for multi-user
48 * sites (enabled by default). Only some stylesheets supports this
49 * functionality (twitter, instagram, pump.io).
51 public function __construct($generate_enclosure = FALSE, $show_usernames = TRUE) {
52 $this->generate_enclosure = $generate_enclosure;
53 $this->show_usernames = $show_usernames;
57 * Convert numeric Epoch to the date format expected in a RSS document.
59 public static function epochToRssDate($timestamp) {
60 if (!is_numeric($timestamp) || is_nan($timestamp)) {
64 return gmdate(DATE_RSS, $timestamp);
68 * Convert generic date string to the date format expected in a RSS document.
70 public static function strToRssDate($date) {
71 $timestamp = strtotime($date);
72 if (FALSE === $timestamp) {
76 return Tweeper::epochToRssDate($timestamp);
80 * Convert string to UpperCamelCase.
82 public static function toUpperCamelCase($str, $delim = ' ') {
83 $str_upper = ucwords($str, $delim);
84 $str_camel_case = str_replace($delim, '', $str_upper);
85 return $str_camel_case;
89 * Get the contents from a URL.
91 private static function getUrlContents($url) {
92 $ch = curl_init($url);
93 curl_setopt_array($ch, array(
94 CURLOPT_HEADER => FALSE,
95 // Follow http redirects to get the real URL.
96 CURLOPT_FOLLOWLOCATION => TRUE,
97 CURLOPT_RETURNTRANSFER => TRUE,
98 CURLOPT_SSL_VERIFYHOST => FALSE,
99 CURLOPT_SSL_VERIFYPEER => FALSE,
100 CURLOPT_HTTPHEADER => array('Accept-language: en'),
101 CURLOPT_USERAGENT => Tweeper::$userAgent,
103 $contents = curl_exec($ch);
104 if (FALSE === $contents) {
105 trigger_error(curl_error($ch));
113 * Get the headers from a URL.
115 private static function getUrlInfo($url) {
116 $ch = curl_init($url);
117 curl_setopt_array($ch, array(
118 CURLOPT_HEADER => TRUE,
119 CURLOPT_NOBODY => TRUE,
120 // Follow http redirects to get the real URL.
121 CURLOPT_FOLLOWLOCATION => TRUE,
122 CURLOPT_RETURNTRANSFER => TRUE,
123 CURLOPT_SSL_VERIFYHOST => FALSE,
124 CURLOPT_SSL_VERIFYPEER => FALSE,
125 CURLOPT_USERAGENT => Tweeper::$userAgent,
128 $ret = curl_exec($ch);
129 if (FALSE === $ret) {
130 trigger_error(curl_error($ch));
135 $url_info = curl_getinfo($ch);
136 if (FALSE === $url_info) {
137 trigger_error(curl_error($ch));
145 * Generate an RSS <enclosure/> element.
147 public static function generateEnclosure($url) {
148 $supported_content_types = array(
149 "application/octet-stream",
169 $url_info = Tweeper::getUrlInfo($url);
170 if (FALSE === $url_info) {
171 error_log("Failed to retrieve info for URL: " . $url);
175 $supported = in_array($url_info['content_type'], $supported_content_types);
177 error_log("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url']);
181 // The RSS specification says that the enclosure element URL must be http.
182 // See http://sourceforge.net/p/feedvalidator/bugs/72/
183 $http_url = preg_replace("/^https/", "http", $url_info['url']);
185 $dom = new DOMDocument();
186 $enc = $dom->createElement('enclosure');
187 $enc->setAttribute('url', $http_url);
188 $enc->setAttribute('length', $url_info['download_content_length']);
189 $enc->setAttribute('type', $url_info['content_type']);
195 * Mimic the message from libxml.c::php_libxml_ctx_error_level()
197 private static function logXmlError($error) {
200 switch ($error->level) {
201 case LIBXML_ERR_WARNING:
202 $output .= "Warning $error->code: ";
205 case LIBXML_ERR_ERROR:
206 $output .= "Error $error->code: ";
209 case LIBXML_ERR_FATAL:
210 $output .= "Fatal Error $error->code: ";
214 $output .= trim($error->message);
217 $output .= " in $error->file";
220 $output .= " in Entity,";
223 $output .= " line $error->line";
229 * Convert json to XML.
231 private static function jsonToXml($json, $root_node_name) {
232 // Apparently the ObjectNormalizer used afterwards is not able to handle
233 // the stdClass object created by json_decode() with the default setting
234 // $assoc = false; so use $assoc = true.
235 $data = json_decode($json, $assoc = TRUE);
240 $encoder = new XmlEncoder();
241 $normalizer = new ObjectNormalizer();
242 $serializer = new Serializer(array($normalizer), array($encoder));
244 $serializer_options = array(
245 'xml_encoding' => "UTF-8",
246 'xml_format_output' => TRUE,
247 'xml_root_node_name' => $root_node_name,
250 $xml_data = $serializer->serialize($data, 'xml', $serializer_options);
252 trigger_error("Cannot serialize data", E_USER_ERROR);
260 * Convert the Instagram content to XML.
262 private function getXmlInstagramCom($html) {
263 // Extract the json data from the html code.
264 $json_match_expr = '/window._sharedData = (.*);/';
265 $ret = preg_match($json_match_expr, $html, $matches);
267 trigger_error("Cannot match expression: $json_match_expr\n", E_USER_ERROR);
271 $data = json_decode($matches[1], $assoc = TRUE);
273 // The "qe" object contains elements which will result in invalid XML
274 // element names, so remove it.
277 // The "knobs" object contains elements with undefined namespaces, so
278 // remove it to silence an error message.
279 unset($data["knobs"]);
281 $json = json_encode($data);
283 return Tweeper::jsonToXml($json, 'instagram');
287 * Make the Facebook HTML processable.
289 private function preprocessHtmlFacebookCom($html) {
290 $html = str_replace('<!--', '', $html);
291 $html = str_replace('-->', '', $html);
296 * Convert the HTML retrieved from the site to XML.
298 private function htmlToXml($html, $host) {
299 $xmlDoc = new DOMDocument();
301 // Handle warnings and errors when loading invalid HTML.
302 $xml_errors_value = libxml_use_internal_errors(TRUE);
304 // If there is a host-specific method to get the XML data, use it!
305 $get_xml_host_method = 'getXml' . Tweeper::toUpperCamelCase($host, '.');
306 if (method_exists($this, $get_xml_host_method)) {
307 $xml_data = call_user_func_array(array($this, $get_xml_host_method), array($html));
308 $xmlDoc->loadXML($xml_data);
311 $xmlDoc->loadHTML($html);
314 foreach (libxml_get_errors() as $xml_error) {
315 Tweeper::logXmlError($xml_error);
317 libxml_clear_errors();
318 libxml_use_internal_errors($xml_errors_value);
324 * Load a stylesheet if the web site is supported.
326 private function loadStylesheet($host) {
327 $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
328 if (FALSE === file_exists($stylesheet)) {
329 trigger_error("Conversion to RSS not supported for $host ($stylesheet not found)", E_USER_ERROR);
333 $stylesheet_contents = Tweeper::getUrlContents($stylesheet);
334 if (FALSE === $stylesheet_contents) {
338 $xslDoc = new DOMDocument();
339 $xslDoc->loadXML($stylesheet_contents);
341 $xsltProcessor = new XSLTProcessor();
342 $xsltProcessor->registerPHPFunctions();
343 $xsltProcessor->setParameter('', 'generate-enclosure', $this->generate_enclosure);
344 $xsltProcessor->setParameter('', 'show-usernames', $this->show_usernames);
345 $xsltProcessor->importStylesheet($xslDoc);
347 return $xsltProcessor;
351 * Convert the site content to RSS.
353 public function tweep($src_url, $host=NULL, $validate_scheme=TRUE) {
354 $url = parse_url($src_url);
355 if (FALSE === $url) {
356 trigger_error("Invalid URL: $src_url", E_USER_ERROR);
360 if (TRUE === $validate_scheme) {
361 $scheme = $url["scheme"];
362 if (!in_array($scheme, array("http", "https"))) {
363 trigger_error("unsupported scheme: $scheme", E_USER_ERROR);
368 // if the host is not given derive it from the URL
369 if (NULL === $host) {
370 if (empty($url["host"])) {
371 trigger_error("Invalid host in URL: $src_url", E_USER_ERROR);
374 // Strip the leading www. to be more forgiving on input URLs.
375 $host = preg_replace('/^www\./', '', $url["host"]);
378 $xsltProcessor = $this->loadStylesheet($host);
379 if (NULL === $xsltProcessor) {
383 $html = Tweeper::getUrlContents($src_url);
384 if (FALSE === $html) {
388 $preprocess_html_host_method = 'preprocessHtml' . Tweeper::toUpperCamelCase($host, '.');
389 if (method_exists($this, $preprocess_html_host_method)) {
390 $html = call_user_func_array(array($this, $preprocess_html_host_method), array($html));
393 $xmlDoc = $this->htmlToXml($html, $host);
394 if (NULL === $xmlDoc) {
398 $output = $xsltProcessor->transformToXML($xmlDoc);
399 if (FALSE === $output) {
400 trigger_error('XSL transformation failed.', E_USER_ERROR);