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.

62 lines
1.5 KiB

  1. <?php
  2. namespace Grav\Plugin;
  3. use Grav\Common\Plugin;
  4. use RocketTheme\Toolbox\Event\Event;
  5. class CloudinaryPlugin extends Plugin
  6. {
  7. protected $cloudinary;
  8. public static function getSubscribedEvents()
  9. {
  10. return [
  11. 'onPluginsInitialized' => ['onPluginsInitialized', 0],
  12. ];
  13. }
  14. /**
  15. * Activate plugin if path matches to the configured one.
  16. */
  17. public function onPluginsInitialized()
  18. {
  19. if (!$this->isAdmin()) {
  20. $this->active = false;
  21. return;
  22. }
  23. include __DIR__.'/vendor/autoload.php';
  24. \Cloudinary::config([
  25. "cloud_name" => $this->config->get('plugins.cloudinary.cloud_name'),
  26. "api_key" => $this->config->get('plugins.cloudinary.api_key'),
  27. "api_secret" => $this->config->get('plugins.cloudinary.api_secret'),
  28. ]);
  29. $this->enable([
  30. 'onImageMediumSaved' => ['onImageMediumSaved', 0],
  31. ]);
  32. }
  33. public function onImageMediumSaved(Event $event)
  34. {
  35. $path = $event['image'];
  36. try {
  37. $cloudinary_image = \Cloudinary\Uploader::upload($path);
  38. if (!empty($cloudinary_image)) {
  39. file_put_contents($path, $cloudinary_image['secure_url']);
  40. } else {
  41. $this->grav['log']->critical(sprintf('%s has failed its upload to Cloudinary', $path));
  42. }
  43. } catch (\Cloudinary\Error $e) {
  44. $this->grav['log']->critical(sprintf('Cloudinary API error : %s', $e->getMessage()));
  45. }
  46. }
  47. }