Thumbnailer.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace Shaarli;
  3. use Shaarli\Config\ConfigManager;
  4. use WebThumbnailer\Exception\WebThumbnailerException;
  5. use WebThumbnailer\WebThumbnailer;
  6. use WebThumbnailer\Application\ConfigManager as WTConfigManager;
  7. /**
  8. * Class Thumbnailer
  9. *
  10. * Utility class used to retrieve thumbnails using web-thumbnailer dependency.
  11. */
  12. class Thumbnailer
  13. {
  14. /**
  15. * @var WebThumbnailer instance.
  16. */
  17. protected $wt;
  18. /**
  19. * @var ConfigManager instance.
  20. */
  21. protected $conf;
  22. /**
  23. * Thumbnailer constructor.
  24. *
  25. * @param ConfigManager $conf instance.
  26. */
  27. public function __construct($conf)
  28. {
  29. $this->conf = $conf;
  30. if (! $this->checkRequirements()) {
  31. $this->conf->set('thumbnails.enabled', false);
  32. $this->conf->write(true);
  33. // TODO: create a proper error handling system able to catch exceptions...
  34. die(t('php-gd extension must be loaded to use thumbnails. Thumbnails are now disabled. Please reload the page.'));
  35. }
  36. $this->wt = new WebThumbnailer();
  37. WTConfigManager::addFile('inc/web-thumbnailer.json');
  38. $this->wt->maxWidth($this->conf->get('thumbnails.width'))
  39. ->maxHeight($this->conf->get('thumbnails.height'))
  40. ->crop(true)
  41. ->debug($this->conf->get('dev.debug', false));
  42. }
  43. /**
  44. * Retrieve a thumbnail for given URL
  45. *
  46. * @param string $url where to look for a thumbnail.
  47. *
  48. * @return bool|string The thumbnail relative cache file path, or false if none has been found.
  49. */
  50. public function get($url)
  51. {
  52. try {
  53. return $this->wt->thumbnail($url);
  54. } catch (WebThumbnailerException $e) {
  55. // Exceptions are only thrown in debug mode.
  56. error_log(get_class($e) .': '. $e->getMessage());
  57. return false;
  58. }
  59. }
  60. /**
  61. * Make sure that requirements are match to use thumbnails:
  62. * - php-gd is loaded
  63. */
  64. protected function checkRequirements()
  65. {
  66. return extension_loaded('gd');
  67. }
  68. }