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.

80 lines
1.5 KiB

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