2017-07-27 09:29:47 +02:00
|
|
|
<?php
|
|
|
|
namespace Grav\Plugin;
|
|
|
|
|
|
|
|
use Grav\Common\Plugin;
|
|
|
|
use RocketTheme\Toolbox\Event\Event;
|
|
|
|
|
|
|
|
class CloudinaryPlugin extends Plugin
|
|
|
|
{
|
|
|
|
protected $cloudinary;
|
|
|
|
|
|
|
|
public static function getSubscribedEvents()
|
|
|
|
{
|
|
|
|
return [
|
|
|
|
'onPluginsInitialized' => ['onPluginsInitialized', 0],
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Activate plugin if path matches to the configured one.
|
|
|
|
*/
|
|
|
|
public function onPluginsInitialized()
|
|
|
|
{
|
2017-07-27 11:26:08 +02:00
|
|
|
if (!$this->isAdmin()) {
|
2017-07-27 09:29:47 +02:00
|
|
|
$this->active = false;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-07-27 11:08:31 +02:00
|
|
|
include __DIR__.'/vendor/autoload.php';
|
|
|
|
|
2017-07-27 09:29:47 +02:00
|
|
|
\Cloudinary::config([
|
2017-07-27 11:08:31 +02:00
|
|
|
"cloud_name" => $this->config->get('plugins.cloudinary.cloud_name'),
|
|
|
|
"api_key" => $this->config->get('plugins.cloudinary.api_key'),
|
|
|
|
"api_secret" => $this->config->get('plugins.cloudinary.api_secret'),
|
2017-07-27 09:29:47 +02:00
|
|
|
]);
|
|
|
|
|
|
|
|
$this->enable([
|
|
|
|
'onImageMediumSaved' => ['onImageMediumSaved', 0],
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public function onImageMediumSaved(Event $event)
|
|
|
|
{
|
|
|
|
|
|
|
|
$path = $event['image'];
|
2017-07-27 11:26:08 +02:00
|
|
|
try {
|
2017-07-27 09:29:47 +02:00
|
|
|
|
2017-07-27 11:26:08 +02:00
|
|
|
$cloudinary_image = \Cloudinary\Uploader::upload($path);
|
|
|
|
|
|
|
|
if (!empty($cloudinary_image)) {
|
|
|
|
file_put_contents($path, $cloudinary_image['secure_url']);
|
|
|
|
} else {
|
|
|
|
$this->grav['log']->critical(sprintf('%s has failed its upload to Cloudinary', $path));
|
|
|
|
}
|
|
|
|
|
|
|
|
} catch (\Cloudinary\Error $e) {
|
|
|
|
$this->grav['log']->critical(sprintf('Cloudinary API error : %s', $e->getMessage()));
|
2017-07-27 09:29:47 +02:00
|
|
|
}
|
2017-07-27 11:26:08 +02:00
|
|
|
|
2017-07-27 09:29:47 +02:00
|
|
|
}
|
|
|
|
}
|