utility.inc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. <?php
  2. /**
  3. * @file utility.inc: uitility form, conversion and rendering functions for
  4. * image processing.
  5. */
  6. /*
  7. * File field handling.
  8. */
  9. /**
  10. *
  11. * @param unknown_type $element
  12. * @param unknown_type $form_status
  13. */
  14. function imagecache_actions_file_field_description() {
  15. return t('File is either a file with one of the valid schemes (e.g. private://, public://, module://{module}/{component}, temporary://), or an absolute or relative path (relative to the current directory, probably the Drupal site root).');
  16. }
  17. /**
  18. *
  19. * Enter description here ...
  20. * @param unknown_type $element
  21. * @param unknown_type $form_status
  22. */
  23. function imagecache_actions_validate_file(&$element, &$form_status) {
  24. if (!imagecache_actions_find_file($element['#value'])) {
  25. form_error($element, t("Unable to find the file '%file'. Please check the path.", array('%file' => $element['#value'])) );
  26. }
  27. }
  28. /**
  29. * Looks up and returns the full path of the given file.
  30. *
  31. * We accept files with the following schemes:
  32. * - private://
  33. * - public://
  34. * - temporary://
  35. * - module://{module}/{component}
  36. *
  37. * Files without a scheme are looked up as are:
  38. * - relative: relative to the current directory (probably $drupal_root).
  39. * - absolute: as is.
  40. *
  41. * @param string $file
  42. * A file name, with a scheme, relative, or absolute.
  43. *
  44. * @return string|false
  45. * The full file path of the file, so the image toolkit knows exactly where it
  46. * is.
  47. */
  48. function imagecache_actions_find_file($file) {
  49. $result = FALSE;
  50. if (is_readable($file)) {
  51. $result = drupal_realpath($file);
  52. }
  53. return $result;
  54. }
  55. /**
  56. * Loads the given file as an image object.
  57. *
  58. * @param string $file
  59. * A file name, with a scheme, relative, or absolute.
  60. *
  61. * @return object|null
  62. * The image object.
  63. *
  64. * @see imagecache_actions_find_file()
  65. * @see image_load()
  66. */
  67. function imagecache_actions_image_load($file, $toolkit = FALSE) {
  68. $full_path = imagecache_actions_find_file($file);
  69. if (!$full_path) {
  70. trigger_error("Failed to find file $file.", E_USER_ERROR);
  71. return FALSE;
  72. }
  73. $image = image_load($full_path, $toolkit);
  74. if (!$image) {
  75. trigger_error("Failed to open file '$file' as an image resource.", E_USER_ERROR);
  76. }
  77. return $image;
  78. }
  79. /**
  80. * Return an array with context information about the image.
  81. *
  82. * This information can e.g. be used by effects that allow custom PHP like
  83. * - Custom action.
  84. * - Text from PHP code.
  85. * - Text from alt or title.
  86. *
  87. * @param object $image
  88. * The image object.
  89. * @param array $data
  90. * An associative array with the effect options.
  91. *
  92. * @return array
  93. * An associative array with context information about the image.
  94. */
  95. function imagecache_actions_get_image_context($image, $data) {
  96. // Store context about the image.
  97. $image_context = array(
  98. 'effect_data' => $data,
  99. 'managed_file' => NULL,
  100. 'referring_entities' => array(),
  101. 'entity' => NULL,
  102. 'image_field' => NULL,
  103. );
  104. // Find the managed file object (at most 1 object as 'uri' is a unique index).
  105. $managed_file = reset(file_load_multiple(array(), array('uri' => $image->source)));
  106. if ($managed_file !== FALSE) {
  107. $image_context['managed_file'] = $managed_file;
  108. // And find the entities referring to this managed file.
  109. $references = file_get_file_references($managed_file, NULL, FIELD_LOAD_CURRENT, 'image');
  110. if ($references) {
  111. // Load referring entities.
  112. foreach ($references as $field_name => $field_references) {
  113. foreach ($field_references as $entity_type => $entity_stubs) {
  114. $image_context['referring_entities'][$field_name][$entity_type] = entity_load($entity_type, array_keys($entity_stubs));
  115. }
  116. }
  117. // Make it easy to access the '1st' entity and its referring image field.
  118. reset($image_context['referring_entities']);
  119. list($field_name, $field_references) = each($image_context['referring_entities']);
  120. reset($field_references);
  121. list($entity_type, $entities) = each($field_references);
  122. reset($entities);
  123. list($entity_id, $image_context['entity']) = each($entities);
  124. $image_field = field_get_items($entity_type, $image_context['entity'], $field_name);
  125. if ($image_field !== FALSE) {
  126. // Get referring item
  127. foreach ($image_field as $image_field_value) {
  128. if ($image_field_value['fid'] === $managed_file->fid) {
  129. $image_context['image_field'] = $image_field_value;
  130. }
  131. }
  132. }
  133. }
  134. }
  135. // @todo: support for media module, or is that based upon managed files?
  136. return $image_context;
  137. }
  138. /**
  139. * Given two imageapi objects with dimensions, and some positioning values,
  140. * calculate a new x,y for the layer to be placed at.
  141. *
  142. * This is a different approach to imagecache_actions_keyword_filter() - more
  143. * like css.
  144. *
  145. * The $style is an array, and expected to have 'top,bottom, left,right'
  146. * attributes set. These values may be positive, negative, or in %.
  147. *
  148. * % is calculated relative to the base image dimensions.
  149. * Using % requires that the layer is positioned CENTERED on that location, so
  150. * some offsets are added to it. 'right-25%' is not lined up with a margin 25%
  151. * in, it's centered at a point 25% in - which is therefore identical with
  152. * left+75%
  153. *
  154. * @return a keyed array of absolute x,y co-ordinates to place the layer at.
  155. */
  156. function imagecache_actions_calculate_relative_position($base, $layer, $style) {
  157. // both images should now have size info available.
  158. if (isset($style['bottom'])) {
  159. $ypos = imagecache_actions_calculate_offset('bottom', $style['bottom'], $base->info['height'], $layer->info['height']);
  160. }
  161. if (isset($style['top'])) {
  162. $ypos = imagecache_actions_calculate_offset('top', $style['top'], $base->info['height'], $layer->info['height']);
  163. }
  164. if (isset($style['right'])) {
  165. $xpos = imagecache_actions_calculate_offset('right', $style['right'], $base->info['width'], $layer->info['width']);
  166. }
  167. if (isset($style['left'])) {
  168. $xpos = imagecache_actions_calculate_offset('left', $style['left'], $base->info['width'], $layer->info['width']);
  169. }
  170. if (! isset($ypos)) {
  171. // assume center
  172. $ypos = ($base->info['height'] / 2) - ($layer->info['height'] / 2);
  173. }
  174. if (! isset($xpos)) {
  175. // assume center
  176. $xpos = ($base->info['width'] / 2) - ($layer->info['width'] / 2);
  177. }
  178. #dpm(__FUNCTION__ . " Calculated offsets");
  179. #dpm(get_defined_vars());
  180. return array('x' => $xpos, 'y' => $ypos);
  181. }
  182. /**
  183. * Positive numbers are IN from the edge, negative offsets are OUT.
  184. *
  185. * $keyword, $value, $base_size, $layer_size
  186. * eg
  187. * left,20 200, 100 = 20
  188. * right,20 200, 100 = 80 (object 100 wide placed 20 px from the right = x=80)
  189. *
  190. * top,50%, 200, 100 = 50 (Object is centered when using %)
  191. * top,20%, 200, 100 = -10
  192. * bottom,-20, 200, 100 = 220
  193. * right, -25%, 200, 100 = 200 (this ends up just offscreen)
  194. *
  195. *
  196. * Also, the value can be a string, eg "bottom-100", or "center+25%"
  197. */
  198. function imagecache_actions_calculate_offset($keyword, $value, $base_size, $layer_size) {
  199. $offset = 0; // used to account for dimensions of the placed object
  200. $direction = 1;
  201. $base = 0;
  202. if ($keyword == 'right' || $keyword == 'bottom') {
  203. $direction = -1;
  204. $offset = -1 * $layer_size;
  205. $base = $base_size;
  206. }
  207. if ($keyword == 'middle' || $keyword == 'center') {
  208. $base = $base_size / 2;
  209. $offset = -1 * ($layer_size / 2);
  210. }
  211. // Keywords may be used to stand in for numeric values
  212. switch ($value) {
  213. case 'left':
  214. case 'top':
  215. $value = 0;
  216. break;
  217. case 'middle':
  218. case 'center':
  219. $value = $base_size / 2;
  220. break;
  221. case 'bottom':
  222. case 'right':
  223. $value = $base_size;
  224. }
  225. // Handle keyword-number cases
  226. // @see imagecache_actions_keyword_filter
  227. // top+50% or bottom-100px
  228. if (preg_match('/^(.+)([\+\-])(\d+)([^\d]*)$/', $value, $results)) {
  229. list($match, $value_key, $value_mod, $mod_value, $mod_unit) = $results;
  230. if ($mod_unit == '%') {
  231. $mod_value = $mod_value / 100 * $base_size;
  232. $mod_unit = 'px';
  233. }
  234. $mod_direction = ($value_mod == '-') ? -1 : + 1;
  235. switch ($value_key) {
  236. case 'left':
  237. case 'top':
  238. $mod_base = 0;
  239. break;
  240. case 'middle':
  241. case 'center':
  242. $mod_base = $base_size / 2;
  243. break;
  244. case 'bottom':
  245. case 'right':
  246. $mod_base = $base_size;
  247. }
  248. $modified_value = $mod_base + ($mod_direction * $mod_value);
  249. return $modified_value;
  250. }
  251. #dpm(get_defined_vars());
  252. // handle % values
  253. if (substr($value, strlen($value) -1, 1) == '%') {
  254. $value = intval($value / 100 * $base_size);
  255. $offset = -1 * ($layer_size / 2);
  256. }
  257. $value = $base + ($direction * $value);
  258. #dpm(__FUNCTION__ . " Placing an object $layer_size big on a range of $base_size at a position of $value , $offset");
  259. #dpm(get_defined_vars());
  260. // Add any extra offset to position the item
  261. return $value + $offset;
  262. }
  263. /**
  264. * Convert a hex string to its RGBA (Red, Green, Blue, Alpha) integer
  265. * components.
  266. *
  267. * Stolen from imageapi D6 2011-01
  268. *
  269. * @param $hex
  270. * A string specifing an RGB color in the formats:
  271. * '#ABC','ABC','#ABCD','ABCD','#AABBCC','AABBCC','#AABBCCDD','AABBCCDD'
  272. * @return
  273. * An array with four elements for red, green, blue, and alpha.
  274. */
  275. function imagecache_actions_hex2rgba($hex) {
  276. $hex = ltrim($hex, '#');
  277. if (preg_match('/^[0-9a-f]{3}$/i', $hex)) {
  278. // 'FA3' is the same as 'FFAA33' so r=FF, g=AA, b=33
  279. $r = str_repeat($hex{0}, 2);
  280. $g = str_repeat($hex{1}, 2);
  281. $b = str_repeat($hex{2}, 2);
  282. $a = '0';
  283. }
  284. elseif (preg_match('/^[0-9a-f]{6}$/i', $hex)) {
  285. // #FFAA33 or r=FF, g=AA, b=33
  286. list($r, $g, $b) = str_split($hex, 2);
  287. $a = '0';
  288. }
  289. elseif (preg_match('/^[0-9a-f]{8}$/i', $hex)) {
  290. // #FFAA33 or r=FF, g=AA, b=33
  291. list($r, $g, $b, $a) = str_split($hex, 2);
  292. }
  293. elseif (preg_match('/^[0-9a-f]{4}$/i', $hex)) {
  294. // 'FA37' is the same as 'FFAA3377' so r=FF, g=AA, b=33, a=77
  295. $r = str_repeat($hex{0}, 2);
  296. $g = str_repeat($hex{1}, 2);
  297. $b = str_repeat($hex{2}, 2);
  298. $a = str_repeat($hex{3}, 2);
  299. }
  300. else {
  301. //error: invalide hex string, TODO: set form error..
  302. return FALSE;
  303. }
  304. $r = hexdec($r);
  305. $g = hexdec($g);
  306. $b = hexdec($b);
  307. $a = hexdec($a);
  308. // alpha over 127 is illegal. assume they meant half that.
  309. if ($a > 127) {
  310. $a = (int)$a/2;
  311. }
  312. return array('red' => $r, 'green' => $g, 'blue' => $b, 'alpha' => $a);
  313. }
  314. /**
  315. * Accept a keyword (center, top, left, etc) and return it as an offset in pixels.
  316. * Called on either the x or y values.
  317. *
  318. * May be something like "20", "center", "left+20", "bottom+10". + values are
  319. * in from the sides, so bottom+10 is 10 UP from the bottom.
  320. *
  321. * "center+50" is also OK.
  322. *
  323. * "30%" will place the CENTER of the object at 30% across. to get a 30% margin,
  324. * use "left+30%"
  325. *
  326. * @param $value
  327. * string or int value.
  328. * @param $current_size
  329. * int size in pixels of the range this item is to be placed in
  330. * @param $object_size
  331. * int size in pixels of the object to be placed
  332. *
  333. *
  334. */
  335. function imagecache_actions_keyword_filter($value, $base_size, $layer_size) {
  336. // See above for the patterns this matches
  337. if (! preg_match('/([a-z]*)([\+\-]?)(\d*)([^\d]*)/', $value, $results) ) {
  338. trigger_error("imagecache_actions had difficulty parsing the string '$value' when calculating position. Please check the syntax.", E_USER_WARNING);
  339. }
  340. list($match, $keyword, $plusminus, $value, $unit) = $results;
  341. #dpm(__FUNCTION__ . " Placing an object $layer_size big on a range of $base_size at a position of $value");
  342. #dpm(get_defined_vars());
  343. return imagecache_actions_calculate_offset($keyword, $plusminus . $value . $unit, $base_size, $layer_size);
  344. }
  345. /**
  346. * imagecache is conservative with its inclusion of inc files, but sometimes I
  347. * need to use them - eg crop. This function finds and includes it if needed.
  348. */
  349. function imagecache_include_standard_actions() {
  350. //$cropaction = imagecache_action_definition('imagecache_crop');
  351. //include_once DRUPAL_ROOT . '/' . $cropaction['file'];
  352. }
  353. /**
  354. * Given a file path relative the default file scheme, tries to locate it and,
  355. * is successful, finds all fields that use it.
  356. *
  357. * @param $filepath Actually a Drupal file URI, probably.
  358. *
  359. * @return
  360. * A nested array of basic entity data, grouped by entity type and field name.
  361. */
  362. function imagecache_actions_fields_from_filepath($filepath, $load_entity = TRUE) {
  363. if (!module_exists('file')) {
  364. return;
  365. }
  366. // Unsure if we are given a real filepath (the normal assumption) or a
  367. // Drupal scheme URI. Resolve either.
  368. if (! file_valid_uri($filepath)) {
  369. $filepath = file_build_uri($filepath);
  370. }
  371. $files = file_load_multiple(array(), array('uri' => $filepath));
  372. if ($files) {
  373. $fields = array();
  374. foreach ($files as $fid => $file) {
  375. $references = file_get_file_references($file, NULL, FIELD_LOAD_CURRENT, 'image');
  376. $fields[$fid] = $references;
  377. }
  378. if ($load_entity) {
  379. // These references are pretty low on information. Load the actual nodes/entities too.
  380. imagecache_actions_entities_from_references($fields);
  381. }
  382. return $fields;
  383. }
  384. }
  385. /**
  386. * Load additional data - Fully load the entities that actually use the given file, with all their data.
  387. *
  388. * Replaces the full entity object in place of the placeholder object that file_get_file_references() gives us.
  389. */
  390. function imagecache_actions_entities_from_references(&$fields) {
  391. foreach ($fields as $fid => $field_ids) {
  392. foreach ($field_ids as $field_id => $entity_types) {
  393. foreach ($entity_types as $entity_type => $entity_instances) {
  394. #$entities = entity_load($entity_type, array_keys($entity_instances));
  395. foreach ($entity_instances as $entity_id => $entity) {
  396. $entity = entity_load_single($entity_type, $entity_id);
  397. // Add this extra data to the return info, replacing the lightweight version
  398. $fields[$fid][$field_id][$entity_type][$entity_id] = $entity;
  399. #// Also bubble up the field info so it's easier to get at? No, that's way too deep.
  400. #// Still, it would be a common use-case to fetch the 'title' from that file.
  401. #// Don't know WHICH of the files our target file is yet, so need to scan. Boring
  402. #$entity_refs = $references[$fid][$field_id][$entity_type][$entity_id][$field_id][$entity->language];
  403. #foreach ($entity_refs as $delta => $file_details) {
  404. # if ($file_details['fid'] == $fid) {
  405. # // Found it. This has the alt and title metadata we expect.
  406. # $file_info = $file_details;
  407. # // Now what?
  408. # }
  409. #} // Scan actual field data to find the file again.
  410. } // All actual entities
  411. } // All types of entity that ref the file
  412. } // All references to this file
  413. } // All entries for this file found in the db (expected to be only 1)
  414. }
  415. function imagecache_actions_percent_filter($value, $current_pixels) {
  416. if (strpos($value, '%') !== false) {
  417. $value = str_replace('%', '', $value) * 0.01 * $current_pixels;
  418. }
  419. return $value;
  420. }