You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.6 KiB

  1. <?php
  2. namespace p3k\XRay\Formats;
  3. use DateTime, DateTimeZone;
  4. use Config;
  5. class XKCD extends Format {
  6. public static function matches_host($url) {
  7. $host = parse_url($url, PHP_URL_HOST);
  8. return $host == 'xkcd.com';
  9. }
  10. public static function matches($url) {
  11. return self::matches_host($url) && preg_match('/^\/\d+\/$/', ''.parse_url($url, PHP_URL_PATH));
  12. }
  13. public static function parse($http_response) {
  14. $html = $http_response['body'];
  15. $url = $http_response['url'];
  16. list($doc, $xpath) = self::_loadHTML($html);
  17. if(!$doc)
  18. return self::_unknown();
  19. $entry = [
  20. 'type' => 'entry',
  21. 'url' => $url,
  22. 'author' => [
  23. 'type' => 'card',
  24. 'name' => 'XKCD',
  25. 'photo' => Config::$base.'/images/xkcd.png',
  26. 'url' => 'https://xkcd.com/'
  27. ]
  28. ];
  29. $name = $doc->getElementById('ctitle');
  30. if(!$name)
  31. return self::_unknown();
  32. $entry['name'] = $name->nodeValue;
  33. $photo = $xpath->query("//div[@id='comic']/img");
  34. if($photo->length != 1)
  35. return self::_unknown();
  36. $photo = $photo->item(0);
  37. $img1 = $photo->getAttribute('src');
  38. $img2 = $photo->getAttribute('srcset');
  39. if($img2) {
  40. $img2 = explode(',', $img2)[0];
  41. if(preg_match('/([^ ]+)/', $img2, $match)) {
  42. $img2 = $match[1];
  43. }
  44. }
  45. $src = \Mf2\resolveUrl($url, $img2 ?: $img1);
  46. $entry['photo'] = [$src];
  47. $entry['post-type'] = \p3k\XRay\PostType::discover($entry);
  48. $response = [
  49. 'data' => $entry,
  50. 'source-format' => 'xkcd',
  51. ];
  52. return $response;
  53. }
  54. }