common_syndication_parser.inc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. <?php
  2. /**
  3. * @file
  4. * Downloading and parsing functions for Common Syndication Parser.
  5. * Pillaged from FeedAPI common syndication parser.
  6. *
  7. * @todo Restructure. OO could work wonders here.
  8. * @todo Write unit tests.
  9. * @todo Keep in Feeds project or host on Drupal?
  10. */
  11. /**
  12. * Parse the feed into a data structure.
  13. *
  14. * @param $feed
  15. * The feed object (contains the URL or the parsed XML structure.
  16. * @return
  17. * stdClass The structured datas extracted from the feed.
  18. */
  19. function common_syndication_parser_parse($string) {
  20. @ $xml = simplexml_load_string($string, NULL, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NOCDATA);
  21. // Got a malformed XML.
  22. if ($xml === FALSE || is_null($xml)) {
  23. return FALSE;
  24. }
  25. $feed_type = _parser_common_syndication_feed_format_detect($xml);
  26. if ($feed_type == "atom1.0") {
  27. return _parser_common_syndication_atom10_parse($xml);
  28. }
  29. if ($feed_type == "RSS2.0" || $feed_type == "RSS0.91" || $feed_type == "RSS0.92") {
  30. return _parser_common_syndication_RSS20_parse($xml);
  31. }
  32. if ($feed_type == "RDF") {
  33. return _parser_common_syndication_RDF10_parse($xml);
  34. }
  35. return FALSE;
  36. }
  37. /**
  38. * Determine the feed format of a SimpleXML parsed object structure.
  39. *
  40. * @param $xml
  41. * SimpleXML-preprocessed feed.
  42. * @return
  43. * The feed format short description or FALSE if not compatible.
  44. */
  45. function _parser_common_syndication_feed_format_detect($xml) {
  46. if (!is_object($xml)) {
  47. return FALSE;
  48. }
  49. $attr = $xml->attributes();
  50. $type = strtolower($xml->getName());
  51. if (isset($xml->entry) && $type == "feed") {
  52. return "atom1.0";
  53. }
  54. if ($type == "rss" && $attr["version"] == "2.0") {
  55. return "RSS2.0";
  56. }
  57. if ($type == "rdf" && isset($xml->channel)) {
  58. return "RDF";
  59. }
  60. if ($type == "rss" && $attr["version"] == "0.91") {
  61. return "RSS0.91";
  62. }
  63. if ($type == "rss" && $attr["version"] == "0.92") {
  64. return "RSS0.92";
  65. }
  66. return FALSE;
  67. }
  68. /**
  69. * Parse atom feeds.
  70. */
  71. function _parser_common_syndication_atom10_parse($feed_XML) {
  72. $parsed_source = array();
  73. $ns = array(
  74. "georss" => "http://www.georss.org/georss",
  75. );
  76. $base = $feed_XML->xpath("@base");
  77. $base = (string) array_shift($base);
  78. if (!valid_url($base, TRUE)) {
  79. $base = FALSE;
  80. }
  81. // Detect the title
  82. $parsed_source['title'] = isset($feed_XML->title) ? _parser_common_syndication_title("{$feed_XML->title}") : "";
  83. // Detect the description
  84. $parsed_source['description'] = isset($feed_XML->subtitle) ? "{$feed_XML->subtitle}" : "";
  85. $parsed_source['link'] = _parser_common_syndication_link($feed_XML->link);
  86. if (valid_url($parsed_source['link']) && !valid_url($parsed_source['link'], TRUE) && !empty($base)) {
  87. $parsed_source['link'] = $base . $parsed_source['link'];
  88. }
  89. $parsed_source['items'] = array();
  90. foreach ($feed_XML->entry as $news) {
  91. $original_url = NULL;
  92. $guid = !empty($news->id) ? "{$news->id}" : NULL;
  93. if (valid_url($guid, TRUE)) {
  94. $original_url = $guid;
  95. }
  96. $georss = (array)$news->children($ns["georss"]);
  97. $geoname = '';
  98. if (isset($georss['featureName'])) {
  99. $geoname = "{$georss['featureName']}";
  100. }
  101. $latlon =
  102. $lat =
  103. $lon = NULL;
  104. if (isset($georss['point'])) {
  105. $latlon = explode(' ', $georss['point']);
  106. $lat = "{$latlon[0]}";
  107. $lon = "{$latlon[1]}";
  108. if (!$geoname) {
  109. $geoname = "{$lat} {$lon}";
  110. }
  111. }
  112. $additional_taxonomies = array();
  113. if (isset($news->category)) {
  114. $additional_taxonomies['ATOM Categories'] = array();
  115. $additional_taxonomies['ATOM Domains'] = array();
  116. foreach ($news->category as $category) {
  117. if (isset($category['scheme'])) {
  118. $domain = "{$category['scheme']}";
  119. if (!empty($domain)) {
  120. if (!isset($additional_taxonomies['ATOM Domains'][$domain])) {
  121. $additional_taxonomies['ATOM Domains'][$domain] = array();
  122. }
  123. $additional_taxonomies['ATOM Domains'][$domain][] = count($additional_taxonomies['ATOM Categories']) - 1;
  124. }
  125. }
  126. $additional_taxonomies['ATOM Categories'][] = "{$category['term']}";
  127. }
  128. }
  129. $title = "{$news->title}";
  130. $body = '';
  131. if (!empty($news->content)) {
  132. foreach ($news->content->children() as $child) {
  133. $body .= $child->asXML();
  134. }
  135. $body .= "{$news->content}";
  136. }
  137. elseif (!empty($news->summary)) {
  138. foreach ($news->summary->children() as $child) {
  139. $body .= $child->asXML();
  140. }
  141. $body .= "{$news->summary}";
  142. }
  143. if (!empty($news->content['src'])) {
  144. // some src elements in some valid atom feeds contained no urls at all
  145. if (valid_url("{$news->content['src']}", TRUE)) {
  146. $original_url = "{$news->content['src']}";
  147. }
  148. }
  149. $original_author = '';
  150. if (!empty($news->source->author->name)) {
  151. $original_author = "{$news->source->author->name}";
  152. }
  153. elseif (!empty($news->author->name)) {
  154. $original_author = "{$news->author->name}";
  155. }
  156. elseif (!empty($feed_XML->author->name)) {
  157. $original_author = "{$feed_XML->author->name}";
  158. }
  159. $original_url = _parser_common_syndication_link($news->link);
  160. $item = array();
  161. $item['title'] = _parser_common_syndication_title($title, $body);
  162. $item['description'] = $body;
  163. $item['author_name'] = $original_author;
  164. // Fall back to updated for timestamp if both published and issued are
  165. // empty.
  166. if (isset($news->published)) {
  167. $item['timestamp'] = _parser_common_syndication_parse_date("{$news->published}");
  168. }
  169. elseif (isset($news->issued)) {
  170. $item['timestamp'] = _parser_common_syndication_parse_date("{$news->issued}");
  171. }
  172. elseif (isset($news->updated)) {
  173. $item['timestamp'] = _parser_common_syndication_parse_date("{$news->updated}");
  174. }
  175. $item['url'] = trim($original_url);
  176. if (valid_url($item['url']) && !valid_url($item['url'], TRUE) && !empty($base)) {
  177. $item['url'] = $base . $item['url'];
  178. }
  179. // Fall back on URL if GUID is empty.
  180. if (!empty($guid)) {
  181. $item['guid'] = $guid;
  182. }
  183. else {
  184. $item['guid'] = $item['url'];
  185. }
  186. $item['geolocations'] = array();
  187. if ($lat && $lon) {
  188. $item['geolocations'] = array(
  189. array(
  190. 'name' => $geoname,
  191. 'lat' => $lat,
  192. 'lon' => $lon,
  193. ),
  194. );
  195. }
  196. $item['tags'] = isset($additional_taxonomies['ATOM Categories']) ? $additional_taxonomies['ATOM Categories'] : array();
  197. $item['domains'] = isset($additional_taxonomies['ATOM Domains']) ? $additional_taxonomies['ATOM Domains'] : array();
  198. $parsed_source['items'][] = $item;
  199. }
  200. return $parsed_source;
  201. }
  202. /**
  203. * Parse RDF Site Summary (RSS) 1.0 feeds in RDF/XML format.
  204. *
  205. * @see http://web.resource.org/rss/1.0/
  206. */
  207. function _parser_common_syndication_RDF10_parse($feed_XML) {
  208. // Declare some canonical standard prefixes for well-known namespaces:
  209. static $canonical_namespaces = array(
  210. 'rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
  211. 'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#',
  212. 'xsi' => 'http://www.w3.org/2001/XMLSchema-instance#',
  213. 'xsd' => 'http://www.w3.org/2001/XMLSchema#',
  214. 'owl' => 'http://www.w3.org/2002/07/owl#',
  215. 'dc' => 'http://purl.org/dc/elements/1.1/',
  216. 'dcterms' => 'http://purl.org/dc/terms/',
  217. 'dcmitype' => 'http://purl.org/dc/dcmitype/',
  218. 'foaf' => 'http://xmlns.com/foaf/0.1/',
  219. 'rss' => 'http://purl.org/rss/1.0/',
  220. );
  221. // Get all namespaces declared in the feed element.
  222. $namespaces = $feed_XML->getNamespaces(TRUE);
  223. // Process the <rss:channel> resource containing feed metadata:
  224. foreach ($feed_XML->children($canonical_namespaces['rss'])->channel as $rss_channel) {
  225. $parsed_source = array(
  226. 'title' => _parser_common_syndication_title((string) $rss_channel->title),
  227. 'description' => (string) $rss_channel->description,
  228. 'link' => (string) $rss_channel->link,
  229. 'items' => array(),
  230. );
  231. break;
  232. }
  233. // Process each <rss:item> resource contained in the feed:
  234. foreach ($feed_XML->children($canonical_namespaces['rss'])->item as $rss_item) {
  235. // Extract all available RDF statements from the feed item's RDF/XML
  236. // tags, allowing for both the item's attributes and child elements to
  237. // contain RDF properties:
  238. $rdf_data = array();
  239. foreach ($namespaces as $ns => $ns_uri) {
  240. // Note that we attempt to normalize the found property name
  241. // namespaces to well-known 'standard' prefixes where possible, as the
  242. // feed may in principle use any arbitrary prefixes and we should
  243. // still be able to correctly handle it.
  244. foreach ($rss_item->attributes($ns_uri) as $attr_name => $attr_value) {
  245. $ns_prefix = ($ns_prefix = array_search($ns_uri, $canonical_namespaces)) ? $ns_prefix : $ns;
  246. $rdf_data[$ns_prefix . ':' . $attr_name][] = (string) $attr_value;
  247. }
  248. foreach ($rss_item->children($ns_uri) as $rss_property) {
  249. $ns_prefix = ($ns_prefix = array_search($ns_uri, $canonical_namespaces)) ? $ns_prefix : $ns;
  250. $rdf_data[$ns_prefix . ':' . $rss_property->getName()][] = (string) $rss_property;
  251. }
  252. }
  253. // Declaratively define mappings that determine how to construct the result object.
  254. $item = _parser_common_syndication_RDF10_item($rdf_data, array(
  255. 'title' => array('rss:title', 'dc:title'),
  256. 'description' => array('rss:description', 'dc:description', 'content:encoded'),
  257. 'url' => array('rss:link', 'rdf:about'),
  258. 'author_name' => array('dc:creator', 'dc:publisher'),
  259. 'guid' => 'rdf:about',
  260. 'timestamp' => 'dc:date',
  261. 'tags' => 'dc:subject'
  262. ));
  263. // Special handling for the title:
  264. $item['title'] = _parser_common_syndication_title($item['title'], $item['description']);
  265. // Parse any date/time values into Unix timestamps:
  266. $item['timestamp'] = _parser_common_syndication_parse_date($item['timestamp']);
  267. // If no GUID found, use the URL of the feed.
  268. if (empty($item['guid'])) {
  269. $item['guid'] = $item['url'];
  270. }
  271. // Add every found RDF property to the feed item.
  272. $item['rdf'] = array();
  273. foreach ($rdf_data as $rdf_property => $rdf_value) {
  274. // looks nicer in the mapper UI
  275. // @todo Revisit, not used with feedapi mapper anymore.
  276. $rdf_property = str_replace(':', '_', $rdf_property);
  277. $item['rdf'][$rdf_property] = $rdf_value;
  278. }
  279. $parsed_source['items'][] = $item;
  280. }
  281. return $parsed_source;
  282. }
  283. function _parser_common_syndication_RDF10_property($rdf_data, $rdf_properties = array()) {
  284. $rdf_properties = is_array($rdf_properties) ? $rdf_properties : array_slice(func_get_args(), 1);
  285. foreach ($rdf_properties as $rdf_property) {
  286. if ($rdf_property && !empty($rdf_data[$rdf_property])) {
  287. // remove empty strings
  288. return array_filter($rdf_data[$rdf_property], 'strlen');
  289. }
  290. }
  291. }
  292. function _parser_common_syndication_RDF10_item($rdf_data, $mappings) {
  293. foreach ($mappings as $k => $v) {
  294. $values = _parser_common_syndication_RDF10_property($rdf_data, $v);
  295. $mappings[$k] = !is_array($values) || count($values) > 1 ? $values : reset($values);
  296. }
  297. return $mappings;
  298. }
  299. /**
  300. * Parse RSS2.0 feeds.
  301. */
  302. function _parser_common_syndication_RSS20_parse($feed_XML) {
  303. $ns = array(
  304. "content" => "http://purl.org/rss/1.0/modules/content/",
  305. "dc" => "http://purl.org/dc/elements/1.1/",
  306. "georss" => "http://www.georss.org/georss",
  307. );
  308. $parsed_source = array();
  309. // Detect the title.
  310. $parsed_source['title'] = isset($feed_XML->channel->title) ? _parser_common_syndication_title("{$feed_XML->channel->title}") : "";
  311. // Detect the description.
  312. $parsed_source['description'] = isset($feed_XML->channel->description) ? "{$feed_XML->channel->description}" : "";
  313. // Detect the link.
  314. $parsed_source['link'] = isset($feed_XML->channel->link) ? "{$feed_XML->channel->link}" : "";
  315. $parsed_source['items'] = array();
  316. foreach ($feed_XML->xpath('//item') as $news) {
  317. $title = $body = $original_author = $original_url = $guid = '';
  318. $category = $news->xpath('category');
  319. // Get children for current namespace.
  320. $content = (array)$news->children($ns["content"]);
  321. $dc = (array)$news->children($ns["dc"]);
  322. $georss = (array)$news->children($ns["georss"]);
  323. $news = (array) $news;
  324. $news['category'] = $category;
  325. if (isset($news['title'])) {
  326. $title = "{$news['title']}";
  327. }
  328. if (isset($news['description'])) {
  329. $body = "{$news['description']}";
  330. }
  331. // Some sources use content:encoded as description i.e.
  332. // PostNuke PageSetter module.
  333. if (isset($news['encoded'])) { // content:encoded for PHP < 5.1.2.
  334. if (strlen($body) < strlen("{$news['encoded']}")) {
  335. $body = "{$news['encoded']}";
  336. }
  337. }
  338. if (isset($content['encoded'])) { // content:encoded for PHP >= 5.1.2.
  339. if (strlen($body) < strlen("{$content['encoded']}")) {
  340. $body = "{$content['encoded']}";
  341. }
  342. }
  343. if (!isset($body)) {
  344. $body = "{$news['title']}";
  345. }
  346. if (!empty($news['author'])) {
  347. $original_author = "{$news['author']}";
  348. }
  349. elseif (!empty($dc["creator"])) {
  350. $original_author = (string)$dc["creator"];
  351. }
  352. if (!empty($news['link'])) {
  353. $original_url = "{$news['link']}";
  354. $guid = $original_url;
  355. }
  356. if (!empty($news['guid'])) {
  357. $guid = "{$news['guid']}";
  358. }
  359. if (!empty($georss['featureName'])) {
  360. $geoname = "{$georss['featureName']}";
  361. }
  362. $lat =
  363. $lon =
  364. $latlon =
  365. $geoname = NULL;
  366. if (!empty($georss['point'])) {
  367. $latlon = explode(' ', $georss['point']);
  368. $lat = "{$latlon[0]}";
  369. $lon = "{$latlon[1]}";
  370. if (!$geoname) {
  371. $geoname = "$lat $lon";
  372. }
  373. }
  374. $additional_taxonomies = array();
  375. $additional_taxonomies['RSS Categories'] = array();
  376. $additional_taxonomies['RSS Domains'] = array();
  377. if (isset($news['category'])) {
  378. foreach ($news['category'] as $category) {
  379. $additional_taxonomies['RSS Categories'][] = "{$category}";
  380. if (isset($category['domain'])) {
  381. $domain = "{$category['domain']}";
  382. if (!empty($domain)) {
  383. if (!isset($additional_taxonomies['RSS Domains'][$domain])) {
  384. $additional_taxonomies['RSS Domains'][$domain] = array();
  385. }
  386. $additional_taxonomies['RSS Domains'][$domain][] = count($additional_taxonomies['RSS Categories']) - 1;
  387. }
  388. }
  389. }
  390. }
  391. $item = array();
  392. $item['title'] = _parser_common_syndication_title($title, $body);
  393. $item['description'] = $body;
  394. $item['author_name'] = $original_author;
  395. if (!empty($news['pubDate'])) {
  396. $item['timestamp'] = _parser_common_syndication_parse_date($news['pubDate']);
  397. }
  398. elseif (!empty($dc['date'])) {
  399. $item['timestamp'] = _parser_common_syndication_parse_date($dc['date']);
  400. }
  401. else {
  402. $item['timestamp'] = time();
  403. }
  404. $item['url'] = trim($original_url);
  405. $item['guid'] = $guid;
  406. $item['geolocations'] = array();
  407. if (isset($geoname, $lat, $lon)) {
  408. $item['geolocations'] = array(
  409. array(
  410. 'name' => $geoname,
  411. 'lat' => $lat,
  412. 'lon' => $lon,
  413. ),
  414. );
  415. }
  416. $item['domains'] = $additional_taxonomies['RSS Domains'];
  417. $item['tags'] = $additional_taxonomies['RSS Categories'];
  418. $parsed_source['items'][] = $item;
  419. }
  420. return $parsed_source;
  421. }
  422. /**
  423. * Parse a date comes from a feed.
  424. *
  425. * @param $date_string
  426. * The date string in various formats.
  427. * @return
  428. * The timestamp of the string or the current time if can't be parsed
  429. */
  430. function _parser_common_syndication_parse_date($date_str) {
  431. // PHP < 5.3 doesn't like the GMT- notation for parsing timezones.
  432. $date_str = str_replace('GMT-', '-', $date_str);
  433. $date_str = str_replace('GMT+', '+', $date_str);
  434. $parsed_date = strtotime($date_str);
  435. if ($parsed_date === FALSE || $parsed_date == -1) {
  436. $parsed_date = _parser_common_syndication_parse_w3cdtf($date_str);
  437. }
  438. if (($parsed_date === FALSE || $parsed_date == -1)) {
  439. // PHP does not support the UT timezone. Fake it. The system that generated
  440. // this, Google Groups, probably meant UTC.
  441. $date_str = strtolower(trim($date_str));
  442. $last_three = substr($date_str, strlen($date_str) - 3, 3);
  443. if ($last_three == ' ut') {
  444. $parsed_date = strtotime($date_str . 'c');
  445. }
  446. }
  447. return $parsed_date === FALSE ? time() : $parsed_date;
  448. }
  449. /**
  450. * Parse the W3C date/time format, a subset of ISO 8601.
  451. *
  452. * PHP date parsing functions do not handle this format.
  453. * See http://www.w3.org/TR/NOTE-datetime for more information.
  454. * Originally from MagpieRSS (http://magpierss.sourceforge.net/).
  455. *
  456. * @param $date_str
  457. * A string with a potentially W3C DTF date.
  458. * @return
  459. * A timestamp if parsed successfully or FALSE if not.
  460. */
  461. function _parser_common_syndication_parse_w3cdtf($date_str) {
  462. if (preg_match('/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/', $date_str, $match)) {
  463. list($year, $month, $day, $hours, $minutes, $seconds) = array($match[1], $match[2], $match[3], $match[4], $match[5], $match[6]);
  464. // Calculate the epoch for current date assuming GMT.
  465. $epoch = gmmktime($hours, $minutes, $seconds, $month, $day, $year);
  466. if ($match[10] != 'Z') { // Z is zulu time, aka GMT
  467. list($tz_mod, $tz_hour, $tz_min) = array($match[8], $match[9], $match[10]);
  468. // Zero out the variables.
  469. if (!$tz_hour) {
  470. $tz_hour = 0;
  471. }
  472. if (!$tz_min) {
  473. $tz_min = 0;
  474. }
  475. $offset_secs = (($tz_hour * 60) + $tz_min) * 60;
  476. // Is timezone ahead of GMT? If yes, subtract offset.
  477. if ($tz_mod == '+') {
  478. $offset_secs *= -1;
  479. }
  480. $epoch += $offset_secs;
  481. }
  482. return $epoch;
  483. }
  484. else {
  485. return FALSE;
  486. }
  487. }
  488. /**
  489. * Extract the link that points to the original content (back to site or
  490. * original article)
  491. *
  492. * @param $links
  493. * Array of SimpleXML objects
  494. */
  495. function _parser_common_syndication_link($links) {
  496. $to_link = '';
  497. if (count($links) > 0) {
  498. foreach ($links as $link) {
  499. $link = $link->attributes();
  500. $to_link = isset($link["href"]) ? "{$link["href"]}" : "";
  501. if (isset($link["rel"])) {
  502. if ("{$link["rel"]}" == 'alternate') {
  503. break;
  504. }
  505. }
  506. }
  507. }
  508. return $to_link;
  509. }
  510. /**
  511. * Prepare raw data to be a title
  512. */
  513. function _parser_common_syndication_title($title, $body = FALSE) {
  514. if (empty($title) && !empty($body)) {
  515. // Explode to words and use the first 3 words.
  516. $words = preg_split('/[\s,]+/', strip_tags($body));
  517. $title = implode(' ', array_slice($words, 0, 3));
  518. }
  519. return $title;
  520. }