imagecache_coloractions.htaccess_creator.inc 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /**
  3. * @file Functions to create .htaccess files in public://styles/{image-style}
  4. * directories that force the correct Content-Type header.
  5. */
  6. /**
  7. * Checks for all image style if a .htaccess should be created to force a
  8. * correct Content-Type header.
  9. */
  10. function imagecache_coloractions_create_htaccess_all_styles() {
  11. $styles = image_styles();
  12. foreach ($styles as $style) {
  13. imagecache_coloractions_create_htaccess_for_style($style);
  14. }
  15. }
  16. /**
  17. * Checks if an image style has a convert format image effect and if so, creates
  18. * an .htaccess in the folder where the derivatives for this style are stored
  19. * to force the correct Content-Type header.
  20. *
  21. * @param array $style
  22. *
  23. * @return bool|null
  24. * True if .htaccess created successfully, false om error, null if no
  25. * .htaccess needed to be created.
  26. */
  27. function imagecache_coloractions_create_htaccess_for_style(array $style) {
  28. // If we have multiple convert effects in the same style (I found one during
  29. // testing) the last determines the mime type.
  30. $format = NULL;
  31. foreach ($style['effects'] as $effect) {
  32. if ($effect['name'] === 'coloractions_convert') {
  33. if (!empty($effect['data']['format'])) {
  34. $format = $effect['data']['format'];
  35. }
  36. }
  37. }
  38. return $format ? imagecache_coloractions_create_htaccess($style['name'], $format) : NULL;
  39. }
  40. /**
  41. * Creates an .htaccess file in the folder public://styles/%style_name.
  42. *
  43. * The folder itself will also be created if necessary.
  44. *
  45. * @param string $style_name
  46. * @param string $mimeType
  47. *
  48. * @return bool
  49. * True on success, false otherwise.
  50. */
  51. function imagecache_coloractions_create_htaccess($style_name, $mimeType) {
  52. $forceType = "ForceType $mimeType\n";
  53. $directory = "public://styles/$style_name";
  54. if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
  55. watchdog('imagecache_actions', 'Failed to create style directory: %directory', array('%directory' => $directory), WATCHDOG_ERROR);
  56. return FALSE;
  57. }
  58. if (!file_put_contents("$directory/.htaccess", $forceType)) {
  59. watchdog('imagecache_actions', 'Failed to create .htaccess in style directory: %directory', array('%directory' => $directory), WATCHDOG_ERROR);
  60. return FALSE;
  61. }
  62. return TRUE;
  63. }