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.

76 lines
1.4 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. $entry['name'] = $name->nodeValue;
  23. $photo = $xpath->query("//div[@id='comic']/img");
  24. if($photo->length != 1)
  25. return self::_unknown();
  26. $photo = $photo->item(0);
  27. $img1 = $photo->getAttribute('src');
  28. $img2 = $photo->getAttribute('srcset');
  29. if($img2) {
  30. $img2 = explode(',', $img2)[0];
  31. if(preg_match('/([^ ]+)/', $img2, $match)) {
  32. $img2 = $match[1];
  33. }
  34. }
  35. $src = \Mf2\resolveUrl($url, $img2 ?: $img1);
  36. $entry['photo'] = [$src];
  37. $response = [
  38. 'data' => $entry
  39. ];
  40. return $response;
  41. }
  42. private static function _unknown() {
  43. return [
  44. 'data' => [
  45. 'type' => 'unknown'
  46. ]
  47. ];
  48. }
  49. private static function _loadHTML($html) {
  50. $doc = new DOMDocument();
  51. @$doc->loadHTML($html);
  52. if(!$doc) {
  53. return [null, null];
  54. }
  55. $xpath = new DOMXPath($doc);
  56. return [$doc, $xpath];
  57. }
  58. }