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.

67 lines
1.4 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) && parse_url($url, PHP_URL_PATH) != '/';
  12. }
  13. public static function parse($html, $url) {
  14. list($doc, $xpath) = self::_loadHTML($html);
  15. if(!$doc)
  16. return self::_unknown();
  17. $entry = [
  18. 'type' => 'entry',
  19. 'url' => $url,
  20. 'author' => [
  21. 'type' => 'card',
  22. 'name' => 'XKCD',
  23. 'photo' => Config::$base.'/images/xkcd.png',
  24. 'url' => 'https://xkcd.com/'
  25. ]
  26. ];
  27. $name = $doc->getElementById('ctitle');
  28. if(!$name)
  29. return self::_unknown();
  30. $entry['name'] = $name->nodeValue;
  31. $photo = $xpath->query("//div[@id='comic']/img");
  32. if($photo->length != 1)
  33. return self::_unknown();
  34. $photo = $photo->item(0);
  35. $img1 = $photo->getAttribute('src');
  36. $img2 = $photo->getAttribute('srcset');
  37. if($img2) {
  38. $img2 = explode(',', $img2)[0];
  39. if(preg_match('/([^ ]+)/', $img2, $match)) {
  40. $img2 = $match[1];
  41. }
  42. }
  43. $src = \Mf2\resolveUrl($url, $img2 ?: $img1);
  44. $entry['photo'] = [$src];
  45. $response = [
  46. 'data' => $entry
  47. ];
  48. return $response;
  49. }
  50. }