aggregator.parser.inc 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. <?php
  2. /**
  3. * @file
  4. * Parser functions for the aggregator module.
  5. */
  6. /**
  7. * Implements hook_aggregator_parse_info().
  8. */
  9. function aggregator_aggregator_parse_info() {
  10. return array(
  11. 'title' => t('Default parser'),
  12. 'description' => t('Parses RSS, Atom and RDF feeds.'),
  13. );
  14. }
  15. /**
  16. * Implements hook_aggregator_parse().
  17. */
  18. function aggregator_aggregator_parse($feed) {
  19. global $channel, $image;
  20. // Filter the input data.
  21. if (aggregator_parse_feed($feed->source_string, $feed)) {
  22. $modified = empty($feed->http_headers['last-modified']) ? 0 : strtotime($feed->http_headers['last-modified']);
  23. // Prepare the channel data.
  24. foreach ($channel as $key => $value) {
  25. $channel[$key] = trim($value);
  26. }
  27. // Prepare the image data (if any).
  28. foreach ($image as $key => $value) {
  29. $image[$key] = trim($value);
  30. }
  31. $etag = empty($feed->http_headers['etag']) ? '' : $feed->http_headers['etag'];
  32. // Add parsed data to the feed object.
  33. $feed->link = !empty($channel['link']) ? $channel['link'] : '';
  34. $feed->description = !empty($channel['description']) ? $channel['description'] : '';
  35. $feed->image = !empty($image['url']) ? $image['url'] : '';
  36. $feed->etag = $etag;
  37. $feed->modified = $modified;
  38. // Clear the cache.
  39. cache_clear_all();
  40. return TRUE;
  41. }
  42. return FALSE;
  43. }
  44. /**
  45. * Parses a feed and stores its items.
  46. *
  47. * @param $data
  48. * The feed data.
  49. * @param $feed
  50. * An object describing the feed to be parsed.
  51. *
  52. * @return
  53. * FALSE on error, TRUE otherwise.
  54. */
  55. function aggregator_parse_feed(&$data, $feed) {
  56. global $items, $image, $channel;
  57. // Unset the global variables before we use them.
  58. unset($GLOBALS['element'], $GLOBALS['item'], $GLOBALS['tag']);
  59. $items = array();
  60. $image = array();
  61. $channel = array();
  62. // Parse the data.
  63. $xml_parser = drupal_xml_parser_create($data);
  64. xml_set_element_handler($xml_parser, 'aggregator_element_start', 'aggregator_element_end');
  65. xml_set_character_data_handler($xml_parser, 'aggregator_element_data');
  66. if (!xml_parse($xml_parser, $data, 1)) {
  67. watchdog('aggregator', 'The feed from %site seems to be broken, due to an error "%error" on line %line.', array('%site' => $feed->title, '%error' => xml_error_string(xml_get_error_code($xml_parser)), '%line' => xml_get_current_line_number($xml_parser)), WATCHDOG_WARNING);
  68. drupal_set_message(t('The feed from %site seems to be broken, because of error "%error" on line %line.', array('%site' => $feed->title, '%error' => xml_error_string(xml_get_error_code($xml_parser)), '%line' => xml_get_current_line_number($xml_parser))), 'error');
  69. return FALSE;
  70. }
  71. xml_parser_free($xml_parser);
  72. // We reverse the array such that we store the first item last, and the last
  73. // item first. In the database, the newest item should be at the top.
  74. $items = array_reverse($items);
  75. // Initialize items array.
  76. $feed->items = array();
  77. foreach ($items as $item) {
  78. // Prepare the item:
  79. foreach ($item as $key => $value) {
  80. $item[$key] = trim($value);
  81. }
  82. // Resolve the item's title. If no title is found, we use up to 40
  83. // characters of the description ending at a word boundary, but not
  84. // splitting potential entities.
  85. if (!empty($item['title'])) {
  86. $item['title'] = $item['title'];
  87. }
  88. elseif (!empty($item['description'])) {
  89. $item['title'] = preg_replace('/^(.*)[^\w;&].*?$/', "\\1", truncate_utf8($item['description'], 40));
  90. }
  91. else {
  92. $item['title'] = '';
  93. }
  94. // Resolve the items link.
  95. if (!empty($item['link'])) {
  96. $item['link'] = $item['link'];
  97. }
  98. else {
  99. $item['link'] = $feed->link;
  100. }
  101. // Atom feeds have an ID tag instead of a GUID tag.
  102. if (!isset($item['guid'])) {
  103. $item['guid'] = isset($item['id']) ? $item['id'] : '';
  104. }
  105. // Atom feeds have a content and/or summary tag instead of a description tag.
  106. if (!empty($item['content:encoded'])) {
  107. $item['description'] = $item['content:encoded'];
  108. }
  109. elseif (!empty($item['summary'])) {
  110. $item['description'] = $item['summary'];
  111. }
  112. elseif (!empty($item['content'])) {
  113. $item['description'] = $item['content'];
  114. }
  115. // Try to resolve and parse the item's publication date.
  116. $date = '';
  117. foreach (array('pubdate', 'dc:date', 'dcterms:issued', 'dcterms:created', 'dcterms:modified', 'issued', 'created', 'modified', 'published', 'updated') as $key) {
  118. if (!empty($item[$key])) {
  119. $date = $item[$key];
  120. break;
  121. }
  122. }
  123. $item['timestamp'] = strtotime($date);
  124. if ($item['timestamp'] === FALSE) {
  125. $item['timestamp'] = aggregator_parse_w3cdtf($date); // Aggregator_parse_w3cdtf() returns FALSE on failure.
  126. }
  127. // Resolve dc:creator tag as the item author if author tag is not set.
  128. if (empty($item['author']) && !empty($item['dc:creator'])) {
  129. $item['author'] = $item['dc:creator'];
  130. }
  131. $item += array('author' => '', 'description' => '');
  132. // Store on $feed object. This is where processors will look for parsed items.
  133. $feed->items[] = $item;
  134. }
  135. return TRUE;
  136. }
  137. /**
  138. * Performs an action when an opening tag is encountered.
  139. *
  140. * Callback function used by xml_parse() within aggregator_parse_feed().
  141. */
  142. function aggregator_element_start($parser, $name, $attributes) {
  143. global $item, $element, $tag, $items, $channel;
  144. $name = strtolower($name);
  145. switch ($name) {
  146. case 'image':
  147. case 'textinput':
  148. case 'summary':
  149. case 'tagline':
  150. case 'subtitle':
  151. case 'logo':
  152. case 'info':
  153. $element = $name;
  154. break;
  155. case 'id':
  156. case 'content':
  157. if ($element != 'item') {
  158. $element = $name;
  159. }
  160. case 'link':
  161. // According to RFC 4287, link elements in Atom feeds without a 'rel'
  162. // attribute should be interpreted as though the relation type is
  163. // "alternate".
  164. if (!empty($attributes['HREF']) && (empty($attributes['REL']) || $attributes['REL'] == 'alternate')) {
  165. if ($element == 'item') {
  166. $items[$item]['link'] = $attributes['HREF'];
  167. }
  168. else {
  169. $channel['link'] = $attributes['HREF'];
  170. }
  171. }
  172. break;
  173. case 'item':
  174. $element = $name;
  175. $item += 1;
  176. break;
  177. case 'entry':
  178. $element = 'item';
  179. $item += 1;
  180. break;
  181. }
  182. $tag = $name;
  183. }
  184. /**
  185. * Performs an action when a closing tag is encountered.
  186. *
  187. * Callback function used by xml_parse() within aggregator_parse_feed().
  188. */
  189. function aggregator_element_end($parser, $name) {
  190. global $element;
  191. switch ($name) {
  192. case 'image':
  193. case 'textinput':
  194. case 'item':
  195. case 'entry':
  196. case 'info':
  197. $element = '';
  198. break;
  199. case 'id':
  200. case 'content':
  201. if ($element == $name) {
  202. $element = '';
  203. }
  204. }
  205. }
  206. /**
  207. * Performs an action when data is encountered.
  208. *
  209. * Callback function used by xml_parse() within aggregator_parse_feed().
  210. */
  211. function aggregator_element_data($parser, $data) {
  212. global $channel, $element, $items, $item, $image, $tag;
  213. $items += array($item => array());
  214. switch ($element) {
  215. case 'item':
  216. $items[$item] += array($tag => '');
  217. $items[$item][$tag] .= $data;
  218. break;
  219. case 'image':
  220. case 'logo':
  221. $image += array($tag => '');
  222. $image[$tag] .= $data;
  223. break;
  224. case 'link':
  225. if ($data) {
  226. $items[$item] += array($tag => '');
  227. $items[$item][$tag] .= $data;
  228. }
  229. break;
  230. case 'content':
  231. $items[$item] += array('content' => '');
  232. $items[$item]['content'] .= $data;
  233. break;
  234. case 'summary':
  235. $items[$item] += array('summary' => '');
  236. $items[$item]['summary'] .= $data;
  237. break;
  238. case 'tagline':
  239. case 'subtitle':
  240. $channel += array('description' => '');
  241. $channel['description'] .= $data;
  242. break;
  243. case 'info':
  244. case 'id':
  245. case 'textinput':
  246. // The sub-element is not supported. However, we must recognize
  247. // it or its contents will end up in the item array.
  248. break;
  249. default:
  250. $channel += array($tag => '');
  251. $channel[$tag] .= $data;
  252. }
  253. }
  254. /**
  255. * Parses the W3C date/time format, a subset of ISO 8601.
  256. *
  257. * PHP date parsing functions do not handle this format. See
  258. * http://www.w3.org/TR/NOTE-datetime for more information. Originally from
  259. * MagpieRSS (http://magpierss.sourceforge.net/).
  260. *
  261. * @param $date_str
  262. * A string with a potentially W3C DTF date.
  263. *
  264. * @return
  265. * A timestamp if parsed successfully or FALSE if not.
  266. */
  267. function aggregator_parse_w3cdtf($date_str) {
  268. if (preg_match('/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/', $date_str, $match)) {
  269. list($year, $month, $day, $hours, $minutes, $seconds) = array($match[1], $match[2], $match[3], $match[4], $match[5], $match[6]);
  270. // Calculate the epoch for current date assuming GMT.
  271. $epoch = gmmktime($hours, $minutes, $seconds, $month, $day, $year);
  272. if ($match[10] != 'Z') { // Z is zulu time, aka GMT
  273. list($tz_mod, $tz_hour, $tz_min) = array($match[8], $match[9], $match[10]);
  274. // Zero out the variables.
  275. if (!$tz_hour) {
  276. $tz_hour = 0;
  277. }
  278. if (!$tz_min) {
  279. $tz_min = 0;
  280. }
  281. $offset_secs = (($tz_hour * 60) + $tz_min) * 60;
  282. // Is timezone ahead of GMT? If yes, subtract offset.
  283. if ($tz_mod == '+') {
  284. $offset_secs *= -1;
  285. }
  286. $epoch += $offset_secs;
  287. }
  288. return $epoch;
  289. }
  290. else {
  291. return FALSE;
  292. }
  293. }