OembedPlugin.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. <?php
  2. /**
  3. * GNU social - a federating social network
  4. *
  5. * OembedPlugin implementation for GNU Social
  6. *
  7. * LICENCE: This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Affero General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Affero General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Affero General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. * @category Plugin
  21. * @package GNUsocial
  22. * @author GNU Social
  23. * @copyright 2010 Free Software Foundation http://fsf.org
  24. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  25. * @link https://www.gnu.org/software/social/
  26. */
  27. if (!defined ('GNUSOCIAL')) {
  28. exit (1);
  29. }
  30. // ============================================================================
  31. // OembedPlugin class
  32. // extends Plugin
  33. //
  34. // Base class for the oEmbed plugin that does most of the heavy lifting to get
  35. // and display representations for remote content.
  36. class OembedPlugin extends Plugin
  37. {
  38. // settings which can be set in config.php with addPlugin('Oembed', array('param'=>'value', ...));
  39. // WARNING, these are _regexps_ (slashes added later). Always escape your dots and end your strings
  40. public $domain_whitelist = array( // hostname => service provider
  41. '^i\d*\.ytimg\.com$' => 'YouTube',
  42. '^i\d*\.vimeocdn\.com$' => 'Vimeo',
  43. );
  44. public $append_whitelist = array(); // fill this array as domain_whitelist to add more trusted sources
  45. public $check_whitelist = false; // security/abuse precaution
  46. public $keep_original = false;
  47. protected $imgData = array();
  48. // ------------------------------------------------------------------------
  49. // OembedPlugin::initialize() function
  50. // Institiate the oEmbed plugin and set up the environment it needs for it.
  51. // Returns true if it initialized properly, the exception object if it
  52. // doesn't.
  53. public function initialize()
  54. {
  55. parent::initialize();
  56. $this->domain_whitelist = array_merge($this->domain_whitelist, $this->append_whitelist);
  57. }
  58. // ------------------------------------------------------------------------
  59. // OembedPlugin::onCheckSchema() function
  60. // The code executed on GNU Social checking the database schema, which in
  61. // this case is to make sure we have the plugin table we need.
  62. // Returns true if it ran successfully, the exception object if it doesn't.
  63. public function onCheckSchema()
  64. {
  65. $schema = Schema::get();
  66. $schema->ensureTable('file_oembed', File_oembed::schemaDef());
  67. return true;
  68. }
  69. // -------------------------------------------------------------------------
  70. // OembedPlugin::onRouterInitialized($m) function
  71. // args: $m (URLMapper) = the router that was initialized.
  72. // This code executes when GNU Social creates the page routing, and we hook
  73. // on this event to add our action handler for oEmbed.
  74. // Returns true if successful, the exception object if it isn't.
  75. public function onRouterInitialized(URLMapper $m)
  76. {
  77. $m->connect('main/oembed', array('action' => 'oembed'));
  78. }
  79. // --------------------------------------------------------------------------
  80. // OembedPlugin::onGetRemoteUrlMetadataFromDom($url, $dom, $metadata) function
  81. // args: $url = the remote URL we're looking at
  82. // $dom = the document we're getting metadata from
  83. // $metadata = class representing the metadata
  84. // This event executes when GNU Social encounters a remote URL we then decide
  85. // to interrogate for metadata. oEmbed gloms onto it to see if we have an
  86. // oEmbed endpoint or image to try to represent in the post.
  87. // Returns true if successful, the exception object if it isn't.
  88. public function onGetRemoteUrlMetadataFromDom($url, DOMDocument $dom, stdClass &$metadata)
  89. {
  90. try {
  91. common_log(LOG_INFO, 'Trying to discover an oEmbed endpoint using link headers.');
  92. $api = oEmbedHelper::oEmbedEndpointFromHTML($dom);
  93. common_log(LOG_INFO, 'Found oEmbed API endpoint ' . $api . ' for URL ' . $url);
  94. $params = array(
  95. 'maxwidth' => common_config('thumbnail', 'width'),
  96. 'maxheight' => common_config('thumbnail', 'height'),
  97. );
  98. $metadata = oEmbedHelper::getOembedFrom($api, $url, $params);
  99. // Facebook just gives us javascript in its oembed html,
  100. // so use the content of the title element instead
  101. if(strpos($url,'https://www.facebook.com/') === 0) {
  102. $metadata->html = @$dom->getElementsByTagName('title')->item(0)->nodeValue;
  103. }
  104. // Wordpress sometimes also just gives us javascript, use og:description if it is available
  105. $xpath = new DomXpath($dom);
  106. $generatorNode = @$xpath->query('//meta[@name="generator"][1]')->item(0);
  107. if ($generatorNode instanceof DomElement) {
  108. // when wordpress only gives us javascript, the html stripped from tags
  109. // is the same as the title, so this helps us to identify this (common) case
  110. if(strpos($generatorNode->getAttribute('content'),'WordPress') === 0
  111. && trim(strip_tags($metadata->html)) == trim($metadata->title)) {
  112. $propertyNode = @$xpath->query('//meta[@property="og:description"][1]')->item(0);
  113. if ($propertyNode instanceof DomElement) {
  114. $metadata->html = $propertyNode->getAttribute('content');
  115. }
  116. }
  117. }
  118. } catch (Exception $e) {
  119. // FIXME - make sure the error was because we couldn't get metadata, not something else! -mb
  120. common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers, trying OpenGraph from HTML.');
  121. // Just ignore it!
  122. $metadata = OpenGraphHelper::ogFromHtml($dom);
  123. }
  124. if (isset($metadata->thumbnail_url)) {
  125. // sometimes sites serve the path, not the full URL, for images
  126. // let's "be liberal in what you accept from others"!
  127. // add protocol and host if the thumbnail_url starts with /
  128. if(substr($metadata->thumbnail_url,0,1) == '/') {
  129. $thumbnail_url_parsed = parse_url($metadata->url);
  130. $metadata->thumbnail_url = $thumbnail_url_parsed['scheme']."://".$thumbnail_url_parsed['host'].$metadata->thumbnail_url;
  131. }
  132. // some wordpress opengraph implementations sometimes return a white blank image
  133. // no need for us to save that!
  134. if($metadata->thumbnail_url == 'https://s0.wp.com/i/blank.jpg') {
  135. unset($metadata->thumbnail_url);
  136. }
  137. // FIXME: this is also true of locally-installed wordpress so we should watch out for that.
  138. }
  139. return true;
  140. }
  141. public function onEndShowHeadElements(Action $action)
  142. {
  143. switch ($action->getActionName()) {
  144. case 'attachment':
  145. $action->element('link',array('rel'=>'alternate',
  146. 'type'=>'application/json+oembed',
  147. 'href'=>common_local_url(
  148. 'oembed',
  149. array(),
  150. array('format'=>'json', 'url'=>
  151. common_local_url('attachment',
  152. array('attachment' => $action->attachment->getID())))),
  153. 'title'=>'oEmbed'),null);
  154. $action->element('link',array('rel'=>'alternate',
  155. 'type'=>'text/xml+oembed',
  156. 'href'=>common_local_url(
  157. 'oembed',
  158. array(),
  159. array('format'=>'xml','url'=>
  160. common_local_url('attachment',
  161. array('attachment' => $action->attachment->getID())))),
  162. 'title'=>'oEmbed'),null);
  163. break;
  164. case 'shownotice':
  165. if (!$action->notice->isLocal()) {
  166. break;
  167. }
  168. try {
  169. $action->element('link',array('rel'=>'alternate',
  170. 'type'=>'application/json+oembed',
  171. 'href'=>common_local_url(
  172. 'oembed',
  173. array(),
  174. array('format'=>'json','url'=>$action->notice->getUrl())),
  175. 'title'=>'oEmbed'),null);
  176. $action->element('link',array('rel'=>'alternate',
  177. 'type'=>'text/xml+oembed',
  178. 'href'=>common_local_url(
  179. 'oembed',
  180. array(),
  181. array('format'=>'xml','url'=>$action->notice->getUrl())),
  182. 'title'=>'oEmbed'),null);
  183. } catch (InvalidUrlException $e) {
  184. // The notice is probably a share or similar, which don't
  185. // have a representational URL of their own.
  186. }
  187. break;
  188. }
  189. return true;
  190. }
  191. public function onEndShowStylesheets(Action $action) {
  192. $action->cssLink($this->path('css/oembed.css'));
  193. return true;
  194. }
  195. /**
  196. * Save embedding information for a File, if applicable.
  197. *
  198. * Normally this event is called through File::saveNew()
  199. *
  200. * @param File $file The newly inserted File object.
  201. *
  202. * @return boolean success
  203. */
  204. public function onEndFileSaveNew(File $file)
  205. {
  206. $fo = File_oembed::getKV('file_id', $file->getID());
  207. if ($fo instanceof File_oembed) {
  208. common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file {$file->getID()}", __FILE__);
  209. return true;
  210. }
  211. if (isset($file->mimetype)
  212. && (('text/html' === substr($file->mimetype, 0, 9)
  213. || 'application/xhtml+xml' === substr($file->mimetype, 0, 21)))) {
  214. try {
  215. $oembed_data = File_oembed::_getOembed($file->url);
  216. if ($oembed_data === false) {
  217. throw new Exception('Did not get oEmbed data from URL');
  218. }
  219. $file->setTitle($oembed_data->title);
  220. } catch (Exception $e) {
  221. common_log(LOG_WARNING, sprintf(__METHOD__.': %s thrown when getting oEmbed data: %s', get_class($e), _ve($e->getMessage())));
  222. return true;
  223. }
  224. File_oembed::saveNew($oembed_data, $file->getID());
  225. }
  226. return true;
  227. }
  228. public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
  229. {
  230. $oembed = File_oembed::getKV('file_id', $file->getID());
  231. if (empty($oembed->author_name) && empty($oembed->provider)) {
  232. return true;
  233. }
  234. $out->elementStart('div', array('id'=>'oembed_info', 'class'=>'e-content'));
  235. if (!empty($oembed->author_name)) {
  236. $out->elementStart('div', 'fn vcard author');
  237. if (empty($oembed->author_url)) {
  238. $out->text($oembed->author_name);
  239. } else {
  240. $out->element('a', array('href' => $oembed->author_url,
  241. 'class' => 'url'),
  242. $oembed->author_name);
  243. }
  244. }
  245. if (!empty($oembed->provider)) {
  246. $out->elementStart('div', 'fn vcard');
  247. if (empty($oembed->provider_url)) {
  248. $out->text($oembed->provider);
  249. } else {
  250. $out->element('a', array('href' => $oembed->provider_url,
  251. 'class' => 'url'),
  252. $oembed->provider);
  253. }
  254. }
  255. $out->elementEnd('div');
  256. }
  257. public function onFileEnclosureMetadata(File $file, &$enclosure)
  258. {
  259. // Never treat generic HTML links as an enclosure type!
  260. // But if we have oEmbed info, we'll consider it golden.
  261. $oembed = File_oembed::getKV('file_id', $file->getID());
  262. if (!$oembed instanceof File_oembed || !in_array($oembed->type, array('photo', 'video'))) {
  263. return true;
  264. }
  265. foreach (array('mimetype', 'url', 'title', 'modified', 'width', 'height') as $key) {
  266. if (isset($oembed->{$key}) && !empty($oembed->{$key})) {
  267. $enclosure->{$key} = $oembed->{$key};
  268. }
  269. }
  270. return true;
  271. }
  272. public function onStartShowAttachmentRepresentation(HTMLOutputter $out, File $file)
  273. {
  274. try {
  275. $oembed = File_oembed::getByFile($file);
  276. } catch (NoResultException $e) {
  277. return true;
  278. }
  279. // Show thumbnail as usual if it's a photo.
  280. if ($oembed->type === 'photo') {
  281. return true;
  282. }
  283. $out->elementStart('article', ['class'=>'h-entry oembed']);
  284. $out->elementStart('header');
  285. try {
  286. $thumb = $file->getThumbnail(128, 128);
  287. $out->element('img', $thumb->getHtmlAttrs(['class'=>'u-photo oembed']));
  288. unset($thumb);
  289. } catch (Exception $e) {
  290. $out->element('div', ['class'=>'error'], $e->getMessage());
  291. }
  292. $out->elementStart('h5', ['class'=>'p-name oembed']);
  293. $out->element('a', ['class'=>'u-url', 'href'=>$file->getUrl()], common_strip_html($oembed->title));
  294. $out->elementEnd('h5');
  295. $out->elementStart('div', ['class'=>'p-author oembed']);
  296. if (!empty($oembed->author_name)) {
  297. // TRANS: text before the author name of oEmbed attachment representation
  298. // FIXME: The whole "By x from y" should be i18n because of different language constructions.
  299. $out->text(_('By '));
  300. $attrs = ['class'=>'h-card p-author'];
  301. if (!empty($oembed->author_url)) {
  302. $attrs['href'] = $oembed->author_url;
  303. $tag = 'a';
  304. } else {
  305. $tag = 'span';
  306. }
  307. $out->element($tag, $attrs, $oembed->author_name);
  308. }
  309. if (!empty($oembed->provider)) {
  310. // TRANS: text between the oEmbed author name and provider url
  311. // FIXME: The whole "By x from y" should be i18n because of different language constructions.
  312. $out->text(_(' from '));
  313. $attrs = ['class'=>'h-card'];
  314. if (!empty($oembed->provider_url)) {
  315. $attrs['href'] = $oembed->provider_url;
  316. $tag = 'a';
  317. } else {
  318. $tag = 'span';
  319. }
  320. $out->element($tag, $attrs, $oembed->provider);
  321. }
  322. $out->elementEnd('div');
  323. $out->elementEnd('header');
  324. $out->elementStart('div', ['class'=>'p-summary oembed']);
  325. $out->raw(common_purify($oembed->html));
  326. $out->elementEnd('div');
  327. $out->elementStart('footer');
  328. $out->elementEnd('footer');
  329. $out->elementEnd('article');
  330. return false;
  331. }
  332. public function onShowUnsupportedAttachmentRepresentation(HTMLOutputter $out, File $file)
  333. {
  334. try {
  335. $oembed = File_oembed::getByFile($file);
  336. } catch (NoResultException $e) {
  337. return true;
  338. }
  339. // the 'photo' type is shown through ordinary means, using StartShowAttachmentRepresentation!
  340. switch ($oembed->type) {
  341. case 'video':
  342. case 'link':
  343. if (!empty($oembed->html)
  344. && (GNUsocial::isAjax() || common_config('attachments', 'show_html'))) {
  345. require_once INSTALLDIR.'/extlib/HTMLPurifier/HTMLPurifier.auto.php';
  346. $purifier = new HTMLPurifier();
  347. // FIXME: do we allow <object> and <embed> here? we did that when we used htmLawed, but I'm not sure anymore...
  348. $out->raw($purifier->purify($oembed->html));
  349. }
  350. return false;
  351. }
  352. return true;
  353. }
  354. // -------------------------------------------------------------------------
  355. // OembedPlugin::onCreateFileImageThumbnailSource($file, $imgPath, $media)
  356. // public function
  357. // args: $file = the file of the created thumbnail
  358. // $imgPath = the path to the created thumbnail
  359. // $media = media type the thumbnail was created for
  360. // This event executes when GNU Social is creating a file thumbnail entry in
  361. // the database. We glom onto this to create proper information for oEmbed
  362. // object thumbnails. Returns true if it succeeds (including non-action
  363. // states where it isn't oEmbed data, so it doesn't mess up the event handle
  364. // for other things hooked into it), or the exception if it fails.
  365. public function onCreateFileImageThumbnailSource(File $file, &$imgPath)
  366. {
  367. // If we are on a private node, we won't do any remote calls (just as a precaution until
  368. // we can configure this from config.php for the private nodes)
  369. if (common_config('site', 'private')) {
  370. return true;
  371. }
  372. // All our remote Oembed images lack a local filename property in the File object
  373. if (!is_null($file->filename)) {
  374. common_debug(sprintf('Filename of file id==%d is not null (%s), so nothing oEmbed should handle.', $file->getID(), _ve($file->filename)));
  375. return true;
  376. }
  377. try {
  378. // If we have proper oEmbed data, there should be an entry in the File_oembed
  379. // and File_thumbnail tables respectively. If not, we're not going to do anything.
  380. $thumbnail = File_thumbnail::byFile($file);
  381. } catch (NoResultException $e) {
  382. // Not Oembed data, or at least nothing we either can or want to use.
  383. common_debug('No oEmbed data found for file id=='.$file->getID());
  384. return true;
  385. }
  386. try {
  387. $this->storeRemoteFileThumbnail($thumbnail);
  388. } catch (AlreadyFulfilledException $e) {
  389. // aw yiss!
  390. } catch (Exception $e) {
  391. common_debug(sprintf('oEmbed encountered an exception (%s) for file id==%d: %s', get_class($e), $file->getID(), _ve($e->getMessage())));
  392. throw $e;
  393. }
  394. $imgPath = $thumbnail->getPath();
  395. return false;
  396. }
  397. /**
  398. * @return boolean false on no check made, provider name on success
  399. * @throws ServerException if check is made but fails
  400. */
  401. protected function checkWhitelist($url)
  402. {
  403. if (!$this->check_whitelist) {
  404. return false; // indicates "no check made"
  405. }
  406. $host = parse_url($url, PHP_URL_HOST);
  407. foreach ($this->domain_whitelist as $regex => $provider) {
  408. if (preg_match("/$regex/", $host)) {
  409. return $provider; // we trust this source, return provider name
  410. }
  411. }
  412. throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
  413. }
  414. // -------------------------------------------------------------------------
  415. // OembedFunction::getRemoteFileSize($url)
  416. // Check the file size of a remote file using a HEAD request and checking
  417. // the content-length variable returned. This isn't 100% foolproof but is
  418. // reliable enough for our purposes. Returns the file size if it succeeds
  419. // or the exception if it fails.
  420. private function getRemoteFileSize($url)
  421. {
  422. try {
  423. if (empty($url)) {
  424. return false;
  425. }
  426. stream_context_set_default(array('http' => array('method' => 'HEAD')));
  427. $head = @get_headers($url,1);
  428. if (gettype($head)=="array") {
  429. $head = array_change_key_case($head);
  430. $size = isset($head['content-length']) ? $head['content-length'] : 0;
  431. if (!$size) {
  432. return false;
  433. }
  434. } else {
  435. return false;
  436. }
  437. return $size; // return formatted size
  438. } catch (Exception $err) {
  439. common_log(LOG_ERR, __CLASS__.': getRemoteFileSize on URL : '._ve($url).' threw exception: '.$err->getMessage());
  440. return false;
  441. }
  442. }
  443. // -------------------------------------------------------------------------
  444. // OembedPlugin::isRemoteImage($url) private function.
  445. // A private helper function that uses a CURL lookup to check the mime type
  446. // of a remote URL to see it it's an image. Returns true if the remote URL
  447. // is an image, or false otherwise.
  448. private function isRemoteImage($url)
  449. {
  450. if (!filter_var ($url, FILTER_VALIDATE_URL)) {
  451. common_log (LOG_ERR,"Invalid URL in OEmbed::isRemoteImage()");
  452. return false;
  453. }
  454. if ($url==null) {
  455. common_log(LOG_ERR,"URL not specified in OEmbed::isRemoteImage()");
  456. return false;
  457. }
  458. try {
  459. $curl = curl_init($url);
  460. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  461. curl_setopt($curl, CURLOPT_HEADER, TRUE);
  462. curl_setopt($curl, CURLOPT_NOBODY, TRUE);
  463. curl_exec($curl);
  464. $type = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
  465. if (strpos($type, 'image') !== false) {
  466. return true;
  467. } else {
  468. return false;
  469. }
  470. } finally {
  471. return false;
  472. }
  473. }
  474. // -------------------------------------------------------------------------
  475. // OembedPlugin::getPHPUploadLimit() private function
  476. // An internal helper function that parses the php.ini file size limit from
  477. // the 'human-readable' shorthand into something we can use to test against
  478. // in conditionals.
  479. // Returns the php.ini upload limit in machine-readable format, or the
  480. // exception if it fails.
  481. // FIXME: We could probably move this to a public utility library.
  482. private function getPHPUploadLimit()
  483. {
  484. $size = ini_get("upload_max_filesize");
  485. $suffix = substr($size, -1);
  486. $size = substr($size, 0, -1);
  487. switch(strtoupper($suffix)) {
  488. case 'P':
  489. $size *= 1024;
  490. case 'T':
  491. $size *= 1024;
  492. case 'G':
  493. $size *= 1024;
  494. case 'M':
  495. $size *= 1024;
  496. case 'K':
  497. $size *= 1024;
  498. break;
  499. }
  500. return $size;
  501. }
  502. /**
  503. * Creates a dummy image with dimensions of original image in order to cheat
  504. * core GNU Social file handler. Used by remove_original.
  505. *
  506. * @author Diogo Cordeiro <diogo@fc.up.pt>
  507. * @param int32 $width Image's width
  508. * @param int32 $height Image's height
  509. * @return string dummy file's filename
  510. */
  511. private function create_dummy ($width, $height)
  512. {
  513. $filename = "oembed-dummy-".$width."-".$height.".png";
  514. $filepath = File_thumbnail::path ($filename);
  515. if (file_exists ($filepath)) {
  516. return $filename;
  517. }
  518. $im = @imagecreate ($width, $height)
  519. or exit ("Cannot Initialize new GD image stream");
  520. imagecolorallocate ($im, 0, 0, 0);
  521. imagepng ($im, File_thumbnail::path ($filename));
  522. imagedestroy ($im);
  523. return $filename;
  524. }
  525. /**
  526. * Removes the original thumbnail and updates the entry on database to the
  527. * dummy object. Depends on create_dummy.
  528. *
  529. * @author Diogo Cordeiro <diogo@fc.up.pt>
  530. * @param File_thumbnail $thumbnail object containing the file thumbnail
  531. * @return boolean true if had to remove, false if it was already all okay
  532. */
  533. private function remove_original ($thumbnail)
  534. {
  535. // Do not remove when original is needed
  536. if ($this->keep_original ||
  537. (isset ($config['thumbnail']) &&
  538. ($config['thumbnail']['width'] <= $thumbnail->width) &&
  539. ($config['thumbnail']['height'] <= $thumbnail->height))
  540. ) {
  541. return false;
  542. }
  543. $dummy_filename = $this->create_dummy ($thumbnail->width, $thumbnail->height);
  544. if ($thumbnail->filename == $dummy_filename) {
  545. return false;
  546. }
  547. $original_filepath = File_thumbnail::path ($thumbnail->filename);
  548. unlink ($original_filepath);
  549. $orig = clone ($thumbnail);
  550. $thumbnail->filename = $dummy_filename;
  551. // Throws exception on failure.
  552. $thumbnail->updateWithKeys ($orig);
  553. return true;
  554. }
  555. // -------------------------------------------------------------------------
  556. // OembedPlugin::storeRemoteFileThumbnail($thumbnail) protected function
  557. // args: $thumbnail = object containing the file thumbnail
  558. // Function to create and store a thumbnail representation of a remote image
  559. // Returns true if it succeeded, the exception if it fails, or false if it
  560. // is limited by system limits (ie the file is too large.)
  561. protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
  562. {
  563. if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
  564. $this->remove_original($thumbnail);
  565. throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->file_id));
  566. }
  567. $url = $thumbnail->getUrl();
  568. $this->checkWhitelist($url);
  569. try {
  570. $isImage = $this->isRemoteImage($url);
  571. if ($isImage==true) {
  572. $max_size = $this->getPHPUploadLimit();
  573. $file_size = $this->getRemoteFileSize($url);
  574. if (($file_size!=false) && ($file_size > $max_size)) {
  575. common_debug("Went to store remote thumbnail of size " . $file_size . " but the upload limit is " . $max_size . " so we aborted.");
  576. return false;
  577. }
  578. }
  579. } catch (Exception $err) {
  580. common_debug("Could not determine size of remote image, aborted local storage.");
  581. return $err;
  582. }
  583. // First we download the file to memory and test whether it's actually an image file
  584. // FIXME: To support remote video/whatever files, this needs reworking.
  585. common_debug(sprintf('Downloading remote thumbnail for file id==%u with thumbnail URL: %s', $thumbnail->file_id, $url));
  586. $imgData = HTTPClient::quickGet($url);
  587. $info = @getimagesizefromstring($imgData);
  588. if ($info === false) {
  589. throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
  590. } elseif (!$info[0] || !$info[1]) {
  591. throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
  592. }
  593. $ext = File::guessMimeExtension($info['mime']);
  594. try {
  595. // We'll trust sha256 (File::FILEHASH_ALG) not to have collision issues any time soon :)
  596. $filename = 'oembed-'.hash(File::FILEHASH_ALG, $imgData) . ".{$ext}";
  597. $fullpath = File_thumbnail::path($filename);
  598. // Write the file to disk. Throw Exception on failure
  599. if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
  600. throw new ServerException(_('Could not write downloaded file to disk.'));
  601. }
  602. } catch (Exception $err) {
  603. common_log(LOG_ERROR, "Went to write a thumbnail to disk in OembedPlugin::storeRemoteThumbnail but encountered error: ".$err);
  604. return $err;
  605. } finally {
  606. unset($imgData);
  607. }
  608. try {
  609. // Updated our database for the file record
  610. $orig = clone($thumbnail);
  611. $thumbnail->filename = $filename;
  612. $thumbnail->width = $info[0]; // array indexes documented on php.net:
  613. $thumbnail->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php
  614. // Throws exception on failure.
  615. $thumbnail->updateWithKeys($orig);
  616. } catch (exception $err) {
  617. common_log(LOG_ERROR, "Went to write a thumbnail entry to the database in OembedPlugin::storeRemoteThumbnail but encountered error: ".$err);
  618. return $err;
  619. }
  620. return true;
  621. }
  622. // -------------------------------------------------------------------------
  623. // onPluginVersion($versions) function
  624. // args: $versions - inherited from parent
  625. // Event raised when GNU Social polls the plugin for information about it.
  626. // Creates a $versions array with the info that GNU Social accesses for that
  627. // information.
  628. // Returns true if it execures successfully, the exception if it doesn't,
  629. // but if assigning an array fails, we uh, got issues.
  630. public function onPluginVersion(array &$versions)
  631. {
  632. $versions[] = array('name' => 'Oembed',
  633. 'version' => GNUSOCIAL_VERSION,
  634. 'author' => 'GNU Social',
  635. 'homepage' => 'http://gnu.io/social/',
  636. 'description' =>
  637. // TRANS: Plugin description.
  638. _m('Plugin for using and representing Oembed data.'));
  639. return true;
  640. }
  641. }