utility.inc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. <?php
  2. /**
  3. * @file utility.inc: uitility form, conversion and rendering functions for
  4. * image processing.
  5. */
  6. /**
  7. * Validates that the element is a positive number.
  8. *
  9. * This is a Form API #element_validate callback.
  10. *
  11. * @param array $element
  12. * param array $form_status
  13. */
  14. function imagecache_actions_validate_number_positive(&$element/*, &$form_status*/) {
  15. $value = $element['#value'];
  16. if ($value != '') {
  17. if (!is_numeric($value) || (float) $value <= 0.0) {
  18. form_error($element, t('%name must be a positive number.', array('%name' => $element['#title'])));
  19. }
  20. }
  21. }
  22. /**
  23. * Validates that the element is a non negative number.
  24. *
  25. * This is a Form API #element_validate callback.
  26. *
  27. * @param array $element
  28. * param array $form_status
  29. */
  30. function imagecache_actions_validate_number_non_negative(&$element/*, &$form_status*/) {
  31. $value = $element['#value'];
  32. if ($value != '') {
  33. if (!is_numeric($value) || (float) $value < 0.0) {
  34. form_error($element, t('%name must be a non negative number.', array('%name' => $element['#title'])));
  35. }
  36. }
  37. }
  38. /*
  39. * File field handling.
  40. */
  41. /**
  42. * @return string
  43. */
  44. function imagecache_actions_file_field_description() {
  45. return t('File is either a file with one of the valid schemes, an absolute path, or a relative path (relative to the current directory, probably the Drupal site root). Valid schemes are a.o. private://, public://, and if the !module module has been installed, also module:// and theme://.',
  46. array('!module' => l('System Stream Wrapper', 'https://drupal.org/project/system_stream_wrapper', array('external' => TRUE))));
  47. }
  48. /**
  49. * Validates that the file as specified in the element exists and is readable.
  50. *
  51. * This is a Form API #element_validate callback.
  52. *
  53. * @param array $element
  54. * param array $form_status
  55. */
  56. function imagecache_actions_validate_file(&$element/*, &$form_status*/) {
  57. if (!imagecache_actions_find_file($element['#value'])) {
  58. form_error($element, t("Unable to find the file '%file'. Please check the path.", array('%file' => $element['#value'])));
  59. }
  60. }
  61. /**
  62. * Looks up and returns the full path of the given file.
  63. *
  64. * @param string $file
  65. * A file name. We accept:
  66. * - stream wrapper notation like: private://, public://, temporary:// and
  67. * module:// (the latter provided by the system stream wrapper module).
  68. * - relative: relative to the current directory (probably DRUPAL_ROOT).
  69. * - absolute: as is.
  70. *
  71. * @return string|false
  72. * The full file path of the file, so the image toolkit knows exactly where it
  73. * is. False if the file cannot be found or is not readable.
  74. */
  75. function imagecache_actions_find_file($file) {
  76. $result = FALSE;
  77. if (is_readable($file)) {
  78. $result = drupal_realpath($file);
  79. }
  80. return $result;
  81. }
  82. /**
  83. * Loads the given file as an image object.
  84. *
  85. * @param string $file
  86. * A file name, with a scheme, relative, or absolute.
  87. * @param bool $toolkit
  88. *
  89. * @return object|FALSE
  90. * The image object.
  91. *
  92. * @see imagecache_actions_find_file()
  93. * @see image_load()
  94. */
  95. function imagecache_actions_image_load($file, $toolkit = FALSE) {
  96. $full_path = imagecache_actions_find_file($file);
  97. if (!$full_path) {
  98. trigger_error("Failed to find file $file.", E_USER_ERROR);
  99. return FALSE;
  100. }
  101. $image = image_load($full_path, $toolkit);
  102. if (!$image) {
  103. trigger_error("Failed to open file '$file' as an image resource.", E_USER_ERROR);
  104. }
  105. return $image;
  106. }
  107. /**
  108. * Returns the label for the given style name.
  109. *
  110. * As of D7.23 image styles can also have a human readable label besides their
  111. * machine readable name. This function returns that label if available, or the
  112. * name if the label is absent.
  113. *
  114. * @param string|null $style_name
  115. * The name of the image style.
  116. *
  117. * @return string
  118. * The label for the image style.
  119. */
  120. function imagecache_actions_get_style_label($style_name) {
  121. if (!empty($style_name)) {
  122. $style = image_style_load($style_name);
  123. $label = isset($style['label']) ? $style['label'] : $style['name'];
  124. if (!empty($style)) {
  125. return $label;
  126. }
  127. else {
  128. return $label . ' ' . t('<span class="error">Invalid reference. The referenced image style may have been deleted!</span>');
  129. }
  130. }
  131. else {
  132. return t('none');
  133. }
  134. }
  135. /**
  136. * Returns an array with context information about the image.
  137. *
  138. * This information is called by effects that need contextual information or
  139. * that allow custom PHP:
  140. * - Custom action.
  141. * - Text from image alt or title.
  142. * - Text with tokens.
  143. * - Text from PHP code.
  144. *
  145. * @param object $image
  146. * The image object.
  147. * @param array $data
  148. * An associative array with the effect options.
  149. *
  150. * @return array
  151. * An associative array with context information about the image. It contains
  152. * the following keys:
  153. * - effect_data: array with the effect data.
  154. * - managed_file: object|null, a managed file object for the current image.
  155. * This may be (an extended) media/file_entity file object.
  156. * - referring_entities: array, list of (loaded) entities that have an image
  157. * field referring to the managed file.
  158. * - entity: object|null, the 1st (and often only) entity that has an image
  159. * field referring to the managed file.
  160. * - image_field: array|null, the (1st and often only) image field item of
  161. * entity that refers to the managed file (single field item, not the
  162. * whole field value).
  163. */
  164. function imagecache_actions_get_image_context($image, $data) {
  165. // Store context about the image.
  166. $image_context = array(
  167. 'effect_data' => $data,
  168. 'managed_file' => NULL,
  169. 'referring_entities' => array(),
  170. 'entity' => NULL,
  171. 'image_field' => NULL,
  172. );
  173. // Find the managed file object (at most 1 object as 'uri' is a unique index).
  174. $managed_file = file_load_multiple(array(), array('uri' => $image->source));
  175. $managed_file = reset($managed_file);
  176. if ($managed_file !== FALSE) {
  177. $image_context['managed_file'] = $managed_file;
  178. // And find the entities referring to this managed file, image fields first,
  179. // then file fields (very specific use cases).
  180. $references = file_get_file_references($managed_file, NULL, FIELD_LOAD_CURRENT, 'image')
  181. + file_get_file_references($managed_file, NULL, FIELD_LOAD_CURRENT, 'file');
  182. if ($references) {
  183. // Load referring entities., keep track of 1st reference separately.
  184. $entity_type_first = '';
  185. $field_name_first = '';
  186. foreach ($references as $field_name => $field_references) {
  187. foreach ($field_references as $entity_type => $entity_stubs) {
  188. $entities = entity_load($entity_type, array_keys($entity_stubs));
  189. if (!empty($entities)) {
  190. $image_context['referring_entities'][$field_name][$entity_type] = $entities;
  191. // Make it easy to access the '1st' entity and its referring image
  192. // field, part 1: entity.
  193. if (empty($entity_type_first)) {
  194. $entity_type_first = $entity_type;
  195. $field_name_first = $field_name;
  196. $image_context['entity'] = reset($entities);
  197. }
  198. }
  199. }
  200. }
  201. // Make it easy to access the '1st' entity and its referring image field,
  202. // part 2: image field.
  203. /** @var array|false $image_field */
  204. $image_field = field_get_items($entity_type_first, $image_context['entity'], $field_name_first);
  205. if ($image_field) {
  206. // Get referring item.
  207. foreach ($image_field as $image_field_value) {
  208. if ($image_field_value['fid'] === $managed_file->fid) {
  209. $image_context['image_field'] = $image_field_value;
  210. break;
  211. }
  212. }
  213. }
  214. }
  215. }
  216. return $image_context;
  217. }
  218. /**
  219. * Returns information about the context, image style and image effect id, of
  220. * the current image effect.
  221. *
  222. * Note that this information is not alterable, that is, it will not have any
  223. * effect on the rest of the derivative image generation process including its
  224. * subsequent effects.
  225. *
  226. * This information is called by effects that may need contextual information or
  227. * that allow custom PHP:
  228. * - Custom action.
  229. * - Text from image alt or title.
  230. * - Text with tokens.
  231. * - Text from PHP code.
  232. *
  233. * This information is fetched by traversing the backtrace, looking for known
  234. * functions that have the image style or effect as argument..
  235. *
  236. * @return array
  237. * Array with keys 'image_style' and 'image_effect_id' pointing to the current
  238. * image style (array) resp. image effect id (int).
  239. */
  240. function imagecache_actions_get_image_effect_context() {
  241. $result = array();
  242. $backtrace = debug_backtrace();
  243. foreach ($backtrace as $function_call) {
  244. if ($function_call['function'] && $function_call['function'] === 'image_effect_apply') {
  245. $result['image_effect_id'] = isset($function_call['args'][1]['ieid']) ? $function_call['args'][1]['ieid'] : NULL;
  246. }
  247. else if ($function_call['function'] && $function_call['function'] === 'image_style_create_derivative') {
  248. $result['image_style'] = isset($function_call['args'][0]) ? $function_call['args'][0] : NULL;
  249. }
  250. if (count($result) === 2) {
  251. break;
  252. }
  253. }
  254. $result += array(
  255. 'image_effect_id' => NULL,
  256. 'image_style' => NULL,
  257. );
  258. return $result;
  259. }
  260. /**
  261. * Given two imageapi objects with dimensions, and some positioning values,
  262. * calculate a new x,y for the layer to be placed at.
  263. *
  264. * This is a different approach to imagecache_actions_keyword_filter() - more
  265. * like css.
  266. *
  267. * The $style is an array, and expected to have 'top, bottom, left, right'
  268. * attributes set. These values may be positive, negative, or in %.
  269. *
  270. * % is calculated relative to the base image dimensions.
  271. * Using % requires that the layer is positioned CENTERED on that location, so
  272. * some offsets are added to it. 'right-25%' is not lined up with a margin 25%
  273. * in, it's centered at a point 25% in - which is therefore identical with
  274. * left+75%
  275. *
  276. * @param $base
  277. * @param $layer
  278. * @param $style
  279. *
  280. * @return array
  281. * A keyed array of absolute x,y co-ordinates to place the layer at.
  282. */
  283. function imagecache_actions_calculate_relative_position($base, $layer, $style) {
  284. // Both images should now have size info available.
  285. if (isset($style['bottom'])) {
  286. $ypos = imagecache_actions_calculate_offset('bottom', $style['bottom'], $base->info['height'], $layer->info['height']);
  287. }
  288. if (isset($style['top'])) {
  289. $ypos = imagecache_actions_calculate_offset('top', $style['top'], $base->info['height'], $layer->info['height']);
  290. }
  291. if (isset($style['right'])) {
  292. $xpos = imagecache_actions_calculate_offset('right', $style['right'], $base->info['width'], $layer->info['width']);
  293. }
  294. if (isset($style['left'])) {
  295. $xpos = imagecache_actions_calculate_offset('left', $style['left'], $base->info['width'], $layer->info['width']);
  296. }
  297. if (!isset($ypos)) {
  298. // Assume center.
  299. $ypos = ($base->info['height'] / 2) - ($layer->info['height'] / 2);
  300. }
  301. if (!isset($xpos)) {
  302. // Assume center.
  303. $xpos = ($base->info['width'] / 2) - ($layer->info['width'] / 2);
  304. }
  305. // dpm(__FUNCTION__ . " Calculated offsets");
  306. // dpm(get_defined_vars());
  307. return array('x' => $xpos, 'y' => $ypos);
  308. }
  309. /**
  310. * Calculates an offset from an edge.
  311. *
  312. * Positive numbers are IN from the edge, negative offsets are OUT.
  313. *
  314. * Examples:
  315. * - left, 20, 200, 100 = 20
  316. * - right, 20, 200, 100 = 80 (object 100 wide placed 20px from the right)
  317. * - top, 50%, 200, 100 = 50 (Object is centered when using %)
  318. * - top, 20%, 200, 100 = -10
  319. * - bottom, -20, 200, 100 = 220
  320. * - right, -25%, 200, 100 = 200 (this ends up just off screen)
  321. *
  322. * Also, the value can be a string, eg "bottom-100", or "center+25%"
  323. * @param string $keyword
  324. * The edge to calculate the offset from. Can be one of: left, right, top,
  325. * bottom, middle, center.
  326. * @param string $value
  327. * The value to offset with: can be:
  328. * - a numeric value: offset in pixels
  329. * - a percentage value: offset with a percentage of the $base_size.
  330. * - a keyword indicating a pxiel size: left, right, top, bottom, middle,
  331. * center.
  332. * - an expression of the format: keyword +|- value[%], e.g. center+25%.
  333. * @param int $base_size
  334. * The size of the dimension. Used to calculate percentages of.
  335. * @param int $layer_size
  336. * The size of the canvas in the current dimension. The value to take for
  337. * $keyword will be based on this value.
  338. *
  339. * @return int
  340. */
  341. function imagecache_actions_calculate_offset($keyword, $value, $base_size, $layer_size) {
  342. $offset = 0;
  343. // Used to account for dimensions of the placed object.
  344. $direction = 1;
  345. $base = 0;
  346. if ($keyword == 'right' || $keyword == 'bottom') {
  347. $direction = -1;
  348. $offset = -1 * $layer_size;
  349. $base = $base_size;
  350. }
  351. if ($keyword == 'middle' || $keyword == 'center') {
  352. $base = $base_size / 2;
  353. $offset = -1 * ($layer_size / 2);
  354. }
  355. // Keywords may be used to stand in for numeric values.
  356. switch ($value) {
  357. case 'left':
  358. case 'top':
  359. $value = 0;
  360. break;
  361. case 'middle':
  362. case 'center':
  363. $value = $base_size / 2;
  364. break;
  365. case 'bottom':
  366. case 'right':
  367. $value = $base_size;
  368. }
  369. // Handle keyword-number cases like top+50% or bottom-100px,
  370. // @see imagecache_actions_keyword_filter().
  371. if (preg_match('/^([a-z]+) *([+-]) *(\d+)((px|%)?)$/', $value, $results)) {
  372. list(, $value_key, $value_mod, $mod_value, $mod_unit) = $results;
  373. if ($mod_unit == '%') {
  374. $mod_value = $mod_value / 100 * $base_size;
  375. }
  376. $mod_direction = ($value_mod == '-') ? -1 : +1;
  377. switch ($value_key) {
  378. case 'left':
  379. case 'top':
  380. default:
  381. $mod_base = 0;
  382. break;
  383. case 'middle':
  384. case 'center':
  385. $mod_base = $base_size / 2;
  386. break;
  387. case 'bottom':
  388. case 'right':
  389. $mod_base = $base_size;
  390. break;
  391. }
  392. $modified_value = $mod_base + ($mod_direction * $mod_value);
  393. return $modified_value;
  394. }
  395. // Handle % values.
  396. if (substr($value, -1) === '%') {
  397. // Explicitly convert $value to prevent warnings in PHP 7.1.
  398. $value = intval((int) $value / 100 * $base_size);
  399. $offset = -1 * ($layer_size / 2);
  400. }
  401. // $value may contain 'px' at the end: explicitly convert to prevent warnings
  402. // in PHP 7.1.
  403. $value = $base + ($direction * (int) $value);
  404. // Add any extra offset to position the item.
  405. return $value + $offset;
  406. }
  407. /**
  408. * Convert a hex string to its RGBA (Red, Green, Blue, Alpha) integer
  409. * components.
  410. *
  411. * Stolen from imageapi D6 2011-01
  412. *
  413. * @param string $hex
  414. * A string specifing an RGB color in the formats:
  415. * '#ABC','ABC','#ABCD','ABCD','#AABBCC','AABBCC','#AABBCCDD','AABBCCDD'
  416. *
  417. * @return array|false
  418. * An array with four elements for red, green, blue, and alpha.
  419. */
  420. function imagecache_actions_hex2rgba($hex) {
  421. $hex = ltrim($hex, '#');
  422. if (preg_match('/^[0-9a-f]{3}$/i', $hex)) {
  423. // 'FA3' is the same as 'FFAA33' so r=FF, g=AA, b=33
  424. $r = str_repeat($hex[0], 2);
  425. $g = str_repeat($hex[1], 2);
  426. $b = str_repeat($hex[2], 2);
  427. $a = '0';
  428. }
  429. elseif (preg_match('/^[0-9a-f]{6}$/i', $hex)) {
  430. // #FFAA33 or r=FF, g=AA, b=33
  431. list($r, $g, $b) = str_split($hex, 2);
  432. $a = '0';
  433. }
  434. elseif (preg_match('/^[0-9a-f]{8}$/i', $hex)) {
  435. // #FFAA33 or r=FF, g=AA, b=33
  436. list($r, $g, $b, $a) = str_split($hex, 2);
  437. }
  438. elseif (preg_match('/^[0-9a-f]{4}$/i', $hex)) {
  439. // 'FA37' is the same as 'FFAA3377' so r=FF, g=AA, b=33, a=77
  440. $r = str_repeat($hex[0], 2);
  441. $g = str_repeat($hex[1], 2);
  442. $b = str_repeat($hex[2], 2);
  443. $a = str_repeat($hex[3], 2);
  444. }
  445. else {
  446. // error: invalid hex string, @todo: set form error.
  447. return FALSE;
  448. }
  449. $r = hexdec($r);
  450. $g = hexdec($g);
  451. $b = hexdec($b);
  452. $a = hexdec($a);
  453. // Alpha over 127 is illegal. assume they meant half that.
  454. if ($a > 127) {
  455. $a = (int) $a / 2;
  456. }
  457. return array('red' => $r, 'green' => $g, 'blue' => $b, 'alpha' => $a);
  458. }
  459. /**
  460. * Accept a keyword (center, top, left, etc) and return it as an offset in pixels.
  461. * Called on either the x or y values.
  462. *
  463. * May be something like "20", "center", "left+20", "bottom+10". + values are
  464. * in from the sides, so bottom+10 is 10 UP from the bottom.
  465. *
  466. * "center+50" is also OK.
  467. *
  468. * "30%" will place the CENTER of the object at 30% across. to get a 30% margin,
  469. * use "left+30%"
  470. *
  471. * @param string|int $value
  472. * string or int value.
  473. * @param int $base_size
  474. * Size in pixels of the range this item is to be placed in.
  475. * @param int $layer_size
  476. * Size in pixels of the object to be placed.
  477. *
  478. * @return int
  479. */
  480. function imagecache_actions_keyword_filter($value, $base_size, $layer_size) {
  481. // See above for the patterns this matches.
  482. if (!preg_match('/([a-z]*) *([+-]?) *(\d*)((px|%)?)/', $value, $results)) {
  483. trigger_error("imagecache_actions had difficulty parsing the string '$value' when calculating position. Please check the syntax.", E_USER_WARNING);
  484. }
  485. list(, $keyword, $plusminus, $value, $unit) = $results;
  486. return imagecache_actions_calculate_offset($keyword, $plusminus . $value . $unit, $base_size, $layer_size);
  487. }
  488. /**
  489. * Computes a length based on a length specification and an actual length.
  490. *
  491. * Examples:
  492. * (50, 400) returns 50; (50px, 400) returns 50; (50%, 400) returns 200;
  493. * (50, null) returns 50; (50%, null) returns null;
  494. * (null, null) returns null; (null, 100) returns null.
  495. *
  496. * @param string|null $length_specification
  497. * The length specification. An integer constant optionally followed by 'px'
  498. * or '%'.
  499. * @param int|null $current_length
  500. * The current length. May be null.
  501. *
  502. * @return int|null
  503. */
  504. function imagecache_actions_percent_filter($length_specification, $current_length) {
  505. if (strpos($length_specification, '%') !== FALSE) {
  506. $length_specification = $current_length !== NULL ? str_replace('%', '', $length_specification) * 0.01 * $current_length : NULL;
  507. }
  508. else {
  509. // Strips 'px' if available.
  510. $length_specification = (int) $length_specification;
  511. }
  512. return $length_specification;
  513. }