oembedhelper.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. <?php
  2. /*
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2008-2010, StatusNet, Inc.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. if (!defined('GNUSOCIAL')) { exit(1); }
  20. /**
  21. * Utility class to wrap basic oEmbed lookups.
  22. *
  23. * Blacklisted hosts will use an alternate lookup method:
  24. * - Twitpic
  25. *
  26. * Whitelisted hosts will use known oEmbed API endpoints:
  27. * - Flickr, YFrog
  28. *
  29. * Sites that provide discovery links will use them directly; a bug
  30. * in use of discovery links with query strings is worked around.
  31. *
  32. * Others will fall back to oohembed (unless disabled).
  33. * The API endpoint can be configured or disabled through config
  34. * as 'oohembed'/'endpoint'.
  35. */
  36. class oEmbedHelper
  37. {
  38. protected static $apiMap = array(
  39. 'flickr.com' => 'https://www.flickr.com/services/oembed/',
  40. 'youtube.com' => 'https://www.youtube.com/oembed',
  41. 'viddler.com' => 'http://lab.viddler.com/services/oembed/',
  42. 'revision3.com' => 'https://revision3.com/api/oembed/',
  43. 'vimeo.com' => 'https://vimeo.com/api/oembed.json',
  44. );
  45. /**
  46. * Perform or fake an oEmbed lookup for the given resource.
  47. *
  48. * Some known hosts are whitelisted with API endpoints where we
  49. * know they exist but autodiscovery data isn't available.
  50. * If autodiscovery links are missing and we don't recognize the
  51. * host, we'll pass it to noembed.com's public service which
  52. * will either proxy or fake info on a lot of sites.
  53. *
  54. * A few hosts are blacklisted due to known problems with oohembed,
  55. * in which case we'll look up the info another way and return
  56. * equivalent data.
  57. *
  58. * Throws exceptions on failure.
  59. *
  60. * @param string $url
  61. * @param array $params
  62. * @return object
  63. */
  64. public static function getObject($url, $params=array())
  65. {
  66. common_log(LOG_INFO, 'Checking for remote URL metadata for ' . $url);
  67. // TODO: Make this class something like UrlMetadata, or use a dataobject?
  68. $metadata = new stdClass();
  69. if (Event::handle('GetRemoteUrlMetadata', array($url, &$metadata))) {
  70. // If that event didn't return anything, try downloading the body and parse it
  71. // don't use quickGet since we want to check Content-Type header for utf-8
  72. $client = new HTTPClient();
  73. $response = $client->get($url);
  74. if (!$response->isOk()) {
  75. // TRANS: Exception. %s is the URL we tried to GET.
  76. throw new Exception(sprintf(_m('Could not GET URL %s.'), $url), $response->getStatus());
  77. }
  78. $body = $response->getBody();
  79. // DOMDocument::loadHTML may throw warnings on unrecognized elements,
  80. // and notices on unrecognized namespaces.
  81. $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
  82. // DOMDocument assumes ISO-8859-1 per HTML spec
  83. // use UTF-8 if we find any evidence of that encoding
  84. $utf8_evidence = false;
  85. $unicode_check_dom = new DOMDocument();
  86. $ok = $unicode_check_dom->loadHTML($body);
  87. if (!$ok) throw new oEmbedHelper_BadHtmlException();
  88. $metaNodes = $unicode_check_dom->getElementsByTagName('meta');
  89. foreach($metaNodes as $metaNode) {
  90. // case in-sensitive since Content-type and utf-8 can be written in many ways
  91. if(stristr($metaNode->getAttribute('http-equiv'),'content-type')
  92. && stristr($metaNode->getAttribute('content'),'utf-8')) {
  93. $utf8_evidence = true;
  94. break;
  95. } elseif(stristr($metaNode->getAttribute('charset'),'utf-8')) {
  96. $utf8_evidence = true;
  97. break;
  98. }
  99. }
  100. unset($unicode_check_dom);
  101. // The Content-Type HTTP response header overrides encoding metatags in DOM
  102. if(stristr($response->getHeader('Content-Type'),'utf-8')) {
  103. $utf8_evidence = true;
  104. }
  105. // add utf-8 encoding prolog if we have reason to believe this is utf-8 content
  106. // DOMDocument('1.0', 'UTF-8') does not work!
  107. $utf8_tag = $utf8_evidence ? '<?xml encoding="utf-8" ?>' : '';
  108. $dom = new DOMDocument();
  109. $ok = $dom->loadHTML($utf8_tag.$body);
  110. unset($body); // storing the DOM in memory is enough...
  111. error_reporting($old);
  112. if (!$ok) {
  113. throw new oEmbedHelper_BadHtmlException();
  114. }
  115. Event::handle('GetRemoteUrlMetadataFromDom', array($url, $dom, &$metadata));
  116. }
  117. return self::normalize($metadata);
  118. }
  119. /**
  120. * Partially ripped from OStatus' FeedDiscovery class.
  121. *
  122. * @param string $url source URL, used to resolve relative links
  123. * @param string $body HTML body text
  124. * @return mixed string with URL or false if no target found
  125. */
  126. static function oEmbedEndpointFromHTML(DOMDocument $dom)
  127. {
  128. // Ok... now on to the links!
  129. $feeds = array(
  130. 'application/json+oembed' => false,
  131. );
  132. $nodes = $dom->getElementsByTagName('link');
  133. for ($i = 0; $i < $nodes->length; $i++) {
  134. $node = $nodes->item($i);
  135. if ($node->hasAttributes()) {
  136. $rel = $node->attributes->getNamedItem('rel');
  137. $type = $node->attributes->getNamedItem('type');
  138. $href = $node->attributes->getNamedItem('href');
  139. if ($rel && $type && $href) {
  140. $rel = array_filter(explode(" ", $rel->value));
  141. $type = trim($type->value);
  142. $href = trim($href->value);
  143. if (in_array('alternate', $rel) && array_key_exists($type, $feeds) && empty($feeds[$type])) {
  144. // Save the first feed found of each type...
  145. $feeds[$type] = $href;
  146. }
  147. }
  148. }
  149. }
  150. // Return the highest-priority feed found
  151. foreach ($feeds as $type => $url) {
  152. if ($url) {
  153. return $url;
  154. }
  155. }
  156. throw new oEmbedHelper_DiscoveryException();
  157. }
  158. /**
  159. * Actually do an oEmbed lookup to a particular API endpoint.
  160. *
  161. * @param string $api oEmbed API endpoint URL
  162. * @param string $url target URL to look up info about
  163. * @param array $params
  164. * @return object
  165. */
  166. static function getOembedFrom($api, $url, $params=array())
  167. {
  168. if (empty($api)) {
  169. // TRANS: Server exception thrown in oEmbed action if no API endpoint is available.
  170. throw new ServerException(_('No oEmbed API endpoint available.'));
  171. }
  172. $params['url'] = $url;
  173. $params['format'] = 'json';
  174. $key=common_config('oembed','apikey');
  175. if(isset($key)) {
  176. $params['key'] = common_config('oembed','apikey');
  177. }
  178. $oembed_data = HTTPClient::quickGetJson($api, $params);
  179. if (isset($oembed_data->html)) {
  180. $oembed_data->html = common_purify($oembed_data->html);
  181. }
  182. return $oembed_data;
  183. }
  184. /**
  185. * Normalize oEmbed format.
  186. *
  187. * @param object $orig
  188. * @return object
  189. */
  190. static function normalize(stdClass $data)
  191. {
  192. if (empty($data->type)) {
  193. throw new Exception('Invalid oEmbed data: no type field.');
  194. }
  195. if ($data->type == 'image') {
  196. // YFrog does this.
  197. $data->type = 'photo';
  198. }
  199. if (isset($data->thumbnail_url)) {
  200. if (!isset($data->thumbnail_width)) {
  201. // !?!?!
  202. $data->thumbnail_width = common_config('thumbnail', 'width');
  203. $data->thumbnail_height = common_config('thumbnail', 'height');
  204. }
  205. }
  206. return $data;
  207. }
  208. }
  209. class oEmbedHelper_Exception extends Exception
  210. {
  211. public function __construct($message = "", $code = 0, $previous = null)
  212. {
  213. parent::__construct($message, $code);
  214. }
  215. }
  216. class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception
  217. {
  218. function __construct($previous=null)
  219. {
  220. return parent::__construct('Bad HTML in discovery data.', 0, $previous);
  221. }
  222. }
  223. class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception
  224. {
  225. function __construct($previous=null)
  226. {
  227. return parent::__construct('No oEmbed discovery data.', 0, $previous);
  228. }
  229. }