From 0526d9522082963eb0e5ef6f0016145b1679c7e2 Mon Sep 17 00:00:00 2001
From: Pierre Buyle <buyle@pheromone.ca>
Date: Wed, 9 Jul 2014 11:44:33 -0400
Subject: [PATCH] Issue #1695068: Allow Imagemagick to work with remote
 streamwrappers.

---
 imagemagick.module | 29 ++++++++++++++++++++++++++---
 1 file changed, 26 insertions(+), 3 deletions(-)

diff --git a/imagemagick.module b/imagemagick.module
index 804338f..c0d165f 100644
--- a/imagemagick.module
+++ b/imagemagick.module
@@ -347,7 +347,7 @@ function image_imagemagick_save(stdClass $image, $destination) {
  */
 function image_imagemagick_get_info(stdClass $image) {
   $details = FALSE;
-  $data = getimagesize(drupal_realpath($image->source));
+  $data = getimagesize($image->source);
 
   if (isset($data) && is_array($data)) {
     $extensions = array('1' => 'gif', '2' => 'jpg', '3' => 'png');
@@ -371,9 +371,27 @@ function _imagemagick_convert($source, $destination, $args) {
   $source_original = $source;
   $destination_original = $destination;
 
-  $source = drupal_realpath($source);
-  $destination = drupal_realpath($destination);
+  $source = drupal_realpath($source_original);
+  // If drupal_realpath() returned false, we're working with a remote file,
+  // so we need to use its URL.
+  if (!$source) {
+    $source = file_create_url($source_original);
+    if (!parse_url($source, PHP_URL_SCHEME)) {
+      global $is_https;
+      $source = ($is_https ? 'https:' : 'http:') . $source;
+    }
+  }
+  $destination = drupal_realpath($destination_original);
   $destination_format = '';
+  // If drupal_realpath() returned false, we're working with a remote file,
+  // so we need to create a temporary, local destination filename,
+  // since imagemagick won't write to a remote stream.
+  if (!$destination) {
+    $base = drupal_basename($destination_original);
+    $uniq = md5(time() + $destination_original);
+    $destination = file_directory_temp() . '/' . $uniq . '-' . $base;
+    $remote = TRUE;
+  }
 
   $args['quality'] = '-quality ' . escapeshellarg(variable_get('imagemagick_quality', 75));
 
@@ -418,6 +436,11 @@ function _imagemagick_convert($source, $destination, $args) {
   if (_imagemagick_convert_exec($command_args, $output, $error) !== TRUE) {
     return FALSE;
   }
+
+  // If the destination is remote, move the temporary file there.
+  if (!empty($remote)) {
+    return file_unmanaged_move($destination, $destination_original);
+  }
   return file_exists($destination);
 }
 
-- 
1.9.1

