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.

93 lines
2.4 KiB

  1. <?php
  2. use Symfony\Component\HttpFoundation\Request;
  3. use Symfony\Component\HttpFoundation\Response;
  4. class Rels {
  5. public $http;
  6. private $_pretty = false;
  7. public function __construct() {
  8. $this->http = new p3k\HTTP();
  9. }
  10. private function respond(Response $response, $code, $params, $headers=[]) {
  11. $response->setStatusCode($code);
  12. foreach($headers as $k=>$v) {
  13. $response->headers->set($k, $v);
  14. }
  15. $response->headers->set('Content-Type', 'application/json');
  16. $opts = JSON_UNESCAPED_SLASHES + JSON_FORCE_OBJECT;
  17. if($this->_pretty) $opts += JSON_PRETTY_PRINT;
  18. $response->setContent(json_encode($params, $opts)."\n");
  19. return $response;
  20. }
  21. public function fetch(Request $request, Response $response) {
  22. if($request->get('timeout')) {
  23. // We might make 2 HTTP requests, so each request gets half the desired timeout
  24. $this->http->timeout = $request->get('timeout') / 2;
  25. }
  26. if($request->get('max_redirects')) {
  27. $this->http->max_redirects = (int)$request->get('max_redirects');
  28. }
  29. if($request->get('pretty')) {
  30. $this->_pretty = true;
  31. }
  32. $url = $request->get('url');
  33. if(!$url) {
  34. return $this->respond($response, 400, [
  35. 'error' => 'missing_url',
  36. 'error_description' => 'Provide a URL to fetch'
  37. ]);
  38. }
  39. // Attempt some basic URL validation
  40. $scheme = parse_url($url, PHP_URL_SCHEME);
  41. if(!in_array($scheme, ['http','https'])) {
  42. return $this->respond($response, 400, [
  43. 'error' => 'invalid_url',
  44. 'error_description' => 'Only http and https URLs are supported'
  45. ]);
  46. }
  47. $host = parse_url($url, PHP_URL_HOST);
  48. if(!$host) {
  49. return $this->respond($response, 400, [
  50. 'error' => 'invalid_url',
  51. 'error_description' => 'The URL provided was not valid'
  52. ]);
  53. }
  54. $url = \normalize_url($url);
  55. $result = $this->http->get($url);
  56. $html = $result['body'];
  57. $mf2 = mf2\Parse($html, $result['url']);
  58. $rels = p3k\HTTP::link_rels($result['headers']);
  59. if(isset($mf2['rels'])) {
  60. $rels = array_merge($rels, $mf2['rels']);
  61. }
  62. // Resolve all relative URLs
  63. foreach($rels as $rel=>$values) {
  64. foreach($values as $i=>$value) {
  65. $value = \mf2\resolveUrl($result['url'], $value);
  66. $rels[$rel][$i] = $value;
  67. }
  68. }
  69. return $this->respond($response, 200, [
  70. 'url' => $result['url'],
  71. 'code' => $result['code'],
  72. 'rels' => $rels
  73. ]);
  74. }
  75. }