<?php

/**
 * @file
 * Tests for core image handling API.
 */

/**
 * Base class for image manipulation testing.
 */
class ImageToolkitTestCase extends DrupalWebTestCase {
  protected $toolkit;
  protected $file;
  protected $image;

  function setUp() {
    $modules = func_get_args();
    if (isset($modules[0]) && is_array($modules[0])) {
      $modules = $modules[0];
    }
    $modules[] = 'image_test';

    parent::setUp($modules);

    // Use the image_test.module's test toolkit.
    $this->toolkit = 'test';

    // Pick a file for testing.
    $file = current($this->drupalGetTestFiles('image'));
    $this->file = $file->uri;

    // Setup a dummy image to work with, this replicate image_load() so we
    // can avoid calling it.
    $this->image = new stdClass();
    $this->image->source = $this->file;
    $this->image->info = image_get_info($this->file);
    $this->image->toolkit = $this->toolkit;

    // Clear out any hook calls.
    image_test_reset();
  }

  /**
   * Assert that all of the specified image toolkit operations were called
   * exactly once once, other values result in failure.
   *
   * @param $expected
   *   Array with string containing with the operation name, e.g. 'load',
   *   'save', 'crop', etc.
   */
  function assertToolkitOperationsCalled(array $expected) {
    // Determine which operations were called.
    $actual = array_keys(array_filter(image_test_get_all_calls()));

    // Determine if there were any expected that were not called.
    $uncalled = array_diff($expected, $actual);
    if (count($uncalled)) {
      $this->assertTrue(FALSE, format_string('Expected operations %expected to be called but %uncalled was not called.', array('%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled))));
    }
    else {
      $this->assertTrue(TRUE, format_string('All the expected operations were called: %expected', array('%expected' => implode(', ', $expected))));
    }

    // Determine if there were any unexpected calls.
    $unexpected = array_diff($actual, $expected);
    if (count($unexpected)) {
      $this->assertTrue(FALSE, format_string('Unexpected operations were called: %unexpected.', array('%unexpected' => implode(', ', $unexpected))));
    }
    else {
      $this->assertTrue(TRUE, 'No unexpected operations were called.');
    }
  }
}

/**
 * Test that the functions in image.inc correctly pass data to the toolkit.
 */
class ImageToolkitUnitTest extends ImageToolkitTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Image toolkit tests',
      'description' => 'Check image toolkit functions.',
      'group' => 'Image',
    );
  }

  /**
   * Check that hook_image_toolkits() is called and only available toolkits are
   * returned.
   */
  function testGetAvailableToolkits() {
    $toolkits = image_get_available_toolkits();
    $this->assertTrue(isset($toolkits['test']), 'The working toolkit was returned.');
    $this->assertFalse(isset($toolkits['broken']), 'The toolkit marked unavailable was not returned');
    $this->assertToolkitOperationsCalled(array());
  }

  /**
   * Test the image_load() function.
   */
  function testLoad() {
    $image = image_load($this->file, $this->toolkit);
    $this->assertTrue(is_object($image), 'Returned an object.');
    $this->assertEqual($this->toolkit, $image->toolkit, 'Image had toolkit set.');
    $this->assertToolkitOperationsCalled(array('load', 'get_info'));
  }

  /**
   * Test the image_save() function.
   */
  function testSave() {
    $this->assertFalse(image_save($this->image), 'Function returned the expected value.');
    $this->assertToolkitOperationsCalled(array('save'));
  }

  /**
   * Test the image_resize() function.
   */
  function testResize() {
    $this->assertTrue(image_resize($this->image, 1, 2), 'Function returned the expected value.');
    $this->assertToolkitOperationsCalled(array('resize'));

    // Check the parameters.
    $calls = image_test_get_all_calls();
    $this->assertEqual($calls['resize'][0][1], 1, 'Width was passed correctly');
    $this->assertEqual($calls['resize'][0][2], 2, 'Height was passed correctly');
  }

  /**
   * Test the image_scale() function.
   */
  function testScale() {
// TODO: need to test upscaling
    $this->assertTrue(image_scale($this->image, 10, 10), 'Function returned the expected value.');
    $this->assertToolkitOperationsCalled(array('resize'));

    // Check the parameters.
    $calls = image_test_get_all_calls();
    $this->assertEqual($calls['resize'][0][1], 10, 'Width was passed correctly');
    $this->assertEqual($calls['resize'][0][2], 5, 'Height was based off aspect ratio and passed correctly');
  }

  /**
   * Test the image_scale_and_crop() function.
   */
  function testScaleAndCrop() {
    $this->assertTrue(image_scale_and_crop($this->image, 5, 10), 'Function returned the expected value.');
    $this->assertToolkitOperationsCalled(array('resize', 'crop'));

    // Check the parameters.
    $calls = image_test_get_all_calls();

    $this->assertEqual($calls['crop'][0][1], 7.5, 'X was computed and passed correctly');
    $this->assertEqual($calls['crop'][0][2], 0, 'Y was computed and passed correctly');
    $this->assertEqual($calls['crop'][0][3], 5, 'Width was computed and passed correctly');
    $this->assertEqual($calls['crop'][0][4], 10, 'Height was computed and passed correctly');
  }

  /**
   * Test the image_rotate() function.
   */
  function testRotate() {
    $this->assertTrue(image_rotate($this->image, 90, 1), 'Function returned the expected value.');
    $this->assertToolkitOperationsCalled(array('rotate'));

    // Check the parameters.
    $calls = image_test_get_all_calls();
    $this->assertEqual($calls['rotate'][0][1], 90, 'Degrees were passed correctly');
    $this->assertEqual($calls['rotate'][0][2], 1, 'Background color was passed correctly');
  }

  /**
   * Test the image_crop() function.
   */
  function testCrop() {
    $this->assertTrue(image_crop($this->image, 1, 2, 3, 4), 'Function returned the expected value.');
    $this->assertToolkitOperationsCalled(array('crop'));

    // Check the parameters.
    $calls = image_test_get_all_calls();
    $this->assertEqual($calls['crop'][0][1], 1, 'X was passed correctly');
    $this->assertEqual($calls['crop'][0][2], 2, 'Y was passed correctly');
    $this->assertEqual($calls['crop'][0][3], 3, 'Width was passed correctly');
    $this->assertEqual($calls['crop'][0][4], 4, 'Height was passed correctly');
  }

  /**
   * Test the image_desaturate() function.
   */
  function testDesaturate() {
    $this->assertTrue(image_desaturate($this->image), 'Function returned the expected value.');
    $this->assertToolkitOperationsCalled(array('desaturate'));

    // Check the parameters.
    $calls = image_test_get_all_calls();
    $this->assertEqual(count($calls['desaturate'][0]), 1, 'Only the image was passed.');
  }
}

/**
 * Test the core GD image manipulation functions.
 */
class ImageToolkitGdTestCase extends DrupalWebTestCase {
  // Colors that are used in testing.
  protected $black       = array(0, 0, 0, 0);
  protected $red         = array(255, 0, 0, 0);
  protected $green       = array(0, 255, 0, 0);
  protected $blue        = array(0, 0, 255, 0);
  protected $yellow      = array(255, 255, 0, 0);
  protected $white       = array(255, 255, 255, 0);
  protected $transparent = array(0, 0, 0, 127);
  // Used as rotate background colors.
  protected $fuchsia            = array(255, 0, 255, 0);
  protected $rotate_transparent = array(255, 255, 255, 127);

  protected $width = 40;
  protected $height = 20;

  public static function getInfo() {
    return array(
      'name' => 'Image GD manipulation tests',
      'description' => 'Check that core image manipulations work properly: scale, resize, rotate, crop, scale and crop, and desaturate.',
      'group' => 'Image',
    );
  }

  /**
   * Function to compare two colors by RGBa.
   */
  function colorsAreEqual($color_a, $color_b) {
    // Fully transparent pixels are equal, regardless of RGB.
    if ($color_a[3] == 127 && $color_b[3] == 127) {
      return TRUE;
    }

    foreach ($color_a as $key => $value) {
      if ($color_b[$key] != $value) {
        return FALSE;
      }
    }

    return TRUE;
  }

  /**
   * Function for finding a pixel's RGBa values.
   */
  function getPixelColor($image, $x, $y) {
    $color_index = imagecolorat($image->resource, $x, $y);

    $transparent_index = imagecolortransparent($image->resource);
    if ($color_index == $transparent_index) {
      return array(0, 0, 0, 127);
    }

    return array_values(imagecolorsforindex($image->resource, $color_index));
  }

  /**
   * Since PHP can't visually check that our images have been manipulated
   * properly, build a list of expected color values for each of the corners and
   * the expected height and widths for the final images.
   */
  function testManipulations() {
    // If GD isn't available don't bother testing this.
    module_load_include('inc', 'system', 'image.gd');
    if (!function_exists('image_gd_check_settings') || !image_gd_check_settings()) {
      $this->pass(t('Image manipulations for the GD toolkit were skipped because the GD toolkit is not available.'));
      return;
    }

    // Typically the corner colors will be unchanged. These colors are in the
    // order of top-left, top-right, bottom-right, bottom-left.
    $default_corners = array($this->red, $this->green, $this->blue, $this->transparent);

    // A list of files that will be tested.
    $files = array(
      'image-test.png',
      'image-test.gif',
      'image-test-no-transparency.gif',
      'image-test.jpg',
    );

    // Setup a list of tests to perform on each type.
    $operations = array(
      'resize' => array(
        'function' => 'resize',
        'arguments' => array(20, 10),
        'width' => 20,
        'height' => 10,
        'corners' => $default_corners,
      ),
      'scale_x' => array(
        'function' => 'scale',
        'arguments' => array(20, NULL),
        'width' => 20,
        'height' => 10,
        'corners' => $default_corners,
      ),
      'scale_y' => array(
        'function' => 'scale',
        'arguments' => array(NULL, 10),
        'width' => 20,
        'height' => 10,
        'corners' => $default_corners,
      ),
      'upscale_x' => array(
        'function' => 'scale',
        'arguments' => array(80, NULL, TRUE),
        'width' => 80,
        'height' => 40,
        'corners' => $default_corners,
      ),
      'upscale_y' => array(
        'function' => 'scale',
        'arguments' => array(NULL, 40, TRUE),
        'width' => 80,
        'height' => 40,
        'corners' => $default_corners,
      ),
      'crop' => array(
        'function' => 'crop',
        'arguments' => array(12, 4, 16, 12),
        'width' => 16,
        'height' => 12,
        'corners' => array_fill(0, 4, $this->white),
      ),
      'scale_and_crop' => array(
        'function' => 'scale_and_crop',
        'arguments' => array(10, 8),
        'width' => 10,
        'height' => 8,
        'corners' => array_fill(0, 4, $this->black),
      ),
    );

    // Systems using non-bundled GD2 don't have imagerotate. Test if available.
    if (function_exists('imagerotate')) {
      $operations += array(
        'rotate_90' => array(
          'function' => 'rotate',
          'arguments' => array(90, 0xFF00FF), // Fuchsia background.
          'width' => 20,
          'height' => 40,
          'corners' => array($this->fuchsia, $this->red, $this->green, $this->blue),
        ),
        'rotate_transparent_90' => array(
          'function' => 'rotate',
          'arguments' => array(90),
          'width' => 20,
          'height' => 40,
          'corners' => array($this->transparent, $this->red, $this->green, $this->blue),
        ),
      );
      // As of PHP version 5.5, GD uses a different algorithm to rotate images
      // than version 5.4 and below, resulting in different dimensions.
      // See https://bugs.php.net/bug.php?id=65148.
      // For the 40x20 test images, the dimensions resulting from rotation will
      // be 1 pixel smaller in both width and height in PHP 5.5 and above.
      // @todo: If and when the PHP bug gets solved, add an upper limit
      //   version check.
      if (version_compare(PHP_VERSION, '5.5', '>=')) {
        $operations += array(
          'rotate_5' => array(
            'function' => 'rotate',
            'arguments' => array(5, 0xFF00FF), // Fuchsia background.
            'width' => 41,
            'height' => 23,
            'corners' => array_fill(0, 4, $this->fuchsia),
          ),
          'rotate_transparent_5' => array(
            'function' => 'rotate',
            'arguments' => array(5),
            'width' => 41,
            'height' => 23,
            'corners' => array_fill(0, 4, $this->rotate_transparent),
          ),
        );
      }
      else {
        $operations += array(
          'rotate_5' => array(
            'function' => 'rotate',
            'arguments' => array(5, 0xFF00FF), // Fuchsia background.
            'width' => 42,
            'height' => 24,
            'corners' => array_fill(0, 4, $this->fuchsia),
          ),
          'rotate_transparent_5' => array(
            'function' => 'rotate',
            'arguments' => array(5),
            'width' => 42,
            'height' => 24,
            'corners' => array_fill(0, 4, $this->rotate_transparent),
          ),
        );
      }
    }

    // Systems using non-bundled GD2 don't have imagefilter. Test if available.
    if (function_exists('imagefilter')) {
      $operations += array(
        'desaturate' => array(
          'function' => 'desaturate',
          'arguments' => array(),
          'height' => 20,
          'width' => 40,
          // Grayscale corners are a bit funky. Each of the corners are a shade of
          // gray. The values of these were determined simply by looking at the
          // final image to see what desaturated colors end up being.
          'corners' => array(
            array_fill(0, 3, 76) + array(3 => 0),
            array_fill(0, 3, 149) + array(3 => 0),
            array_fill(0, 3, 29) + array(3 => 0),
            array_fill(0, 3, 225) + array(3 => 127)
          ),
        ),
      );
    }

    foreach ($files as $file) {
      foreach ($operations as $op => $values) {
        // Load up a fresh image.
        $image = image_load(drupal_get_path('module', 'simpletest') . '/files/' . $file, 'gd');
        if (!$image) {
          $this->fail(t('Could not load image %file.', array('%file' => $file)));
          continue 2;
        }

        // All images should be converted to truecolor when loaded.
        $image_truecolor = imageistruecolor($image->resource);
        $this->assertTrue($image_truecolor, format_string('Image %file after load is a truecolor image.', array('%file' => $file)));

        if ($image->info['extension'] == 'gif') {
          if ($op == 'desaturate') {
            // Transparent GIFs and the imagefilter function don't work together.
            $values['corners'][3][3] = 0;
          }
        }

        // Perform our operation.
        $function = 'image_' . $values['function'];
        $arguments = array();
        $arguments[] = &$image;
        $arguments = array_merge($arguments, $values['arguments']);
        call_user_func_array($function, $arguments);

        // To keep from flooding the test with assert values, make a general
        // value for whether each group of values fail.
        $correct_dimensions_real = TRUE;
        $correct_dimensions_object = TRUE;
        $correct_colors = TRUE;

        // Check the real dimensions of the image first.
        if (imagesy($image->resource) != $values['height'] || imagesx($image->resource) != $values['width']) {
          $correct_dimensions_real = FALSE;
        }

        // Check that the image object has an accurate record of the dimensions.
        if ($image->info['width'] != $values['width'] || $image->info['height'] != $values['height']) {
          $correct_dimensions_object = FALSE;
        }
        // Now check each of the corners to ensure color correctness.
        foreach ($values['corners'] as $key => $corner) {
          // The test gif that does not have transparency has yellow where the
          // others have transparent.
          if ($file === 'image-test-no-transparency.gif' && $corner === $this->transparent) {
            $corner = $this->yellow;
          }
          // Get the location of the corner.
          switch ($key) {
            case 0:
              $x = 0;
              $y = 0;
              break;
            case 1:
              $x = $values['width'] - 1;
              $y = 0;
              break;
            case 2:
              $x = $values['width'] - 1;
              $y = $values['height'] - 1;
              break;
            case 3:
              $x = 0;
              $y = $values['height'] - 1;
              break;
          }
          $color = $this->getPixelColor($image, $x, $y);
          $correct_colors = $this->colorsAreEqual($color, $corner);
        }

        $directory = file_default_scheme() . '://imagetests';
        file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
        $file_path = $directory . '/' . $op . '.' . $image->info['extension'];
        image_save($image, $file_path);

        $this->assertTrue($correct_dimensions_real, format_string('Image %file after %action action has proper dimensions.', array('%file' => $file, '%action' => $op)));
        $this->assertTrue($correct_dimensions_object, format_string('Image %file object after %action action is reporting the proper height and width values.', array('%file' => $file, '%action' => $op)));
        // JPEG colors will always be messed up due to compression.
        if ($image->info['extension'] != 'jpg') {
          $this->assertTrue($correct_colors, format_string('Image %file object after %action action has the correct color placement.', array('%file' => $file, '%action' => $op)));
        }
      }

      // Check that saved image reloads without raising PHP errors.
      $image_reloaded = image_load($file_path);
    }
  }

  /**
   * Tests loading an image whose transparent color index is out of range.
   */
  function testTransparentColorOutOfRange() {
    // This image was generated by taking an initial image with a palette size
    // of 6 colors, and setting the transparent color index to 6 (one higher
    // than the largest allowed index), as follows:
    // @code
    // $image = imagecreatefromgif('modules/simpletest/files/image-test.gif');
    // imagecolortransparent($image, 6);
    // imagegif($image, 'modules/simpletest/files/image-test-transparent-out-of-range.gif');
    // @endcode
    // This allows us to test that an image with an out-of-range color index
    // can be loaded correctly.
    $file = 'image-test-transparent-out-of-range.gif';
    $image = image_load(drupal_get_path('module', 'simpletest') . '/files/' . $file);

    if (!$image) {
      $this->fail(format_string('Could not load image %file.', array('%file' => $file)));
    }
    else {
      // All images should be converted to truecolor when loaded.
      $image_truecolor = imageistruecolor($image->resource);
      $this->assertTrue($image_truecolor, format_string('Image %file after load is a truecolor image.', array('%file' => $file)));
    }
  }
}

/**
 * Tests the file move function for managed files.
 */
class ImageFileMoveTest extends ImageToolkitTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Image moving',
      'description' => 'Tests the file move function for managed files.',
      'group' => 'Image',
    );
  }

  /**
   * Tests moving a randomly generated image.
   */
  function testNormal() {
    // Pick a file for testing.
    $file = current($this->drupalGetTestFiles('image'));

    // Create derivative image.
    $style = image_style_load(key(image_styles()));
    $derivative_uri = image_style_path($style['name'], $file->uri);
    image_style_create_derivative($style, $file->uri, $derivative_uri);

    // Check if derivative image exists.
    $this->assertTrue(file_exists($derivative_uri), 'Make sure derivative image is generated successfully.');

    // Clone the object so we don't have to worry about the function changing
    // our reference copy.
    $desired_filepath = 'public://' . $this->randomName();
    $result = file_move(clone $file, $desired_filepath, FILE_EXISTS_ERROR);

    // Check if image has been moved.
    $this->assertTrue(file_exists($result->uri), 'Make sure image is moved successfully.');

    // Check if derivative image has been flushed.
    $this->assertFalse(file_exists($derivative_uri), 'Make sure derivative image has been flushed.');
  }
}

