image.module 47.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
<?php

/**
 * @file
 * Exposes global functionality for creating image styles.
 */

/**
 * Image style constant for user presets in the database.
 */
define('IMAGE_STORAGE_NORMAL', 1);

/**
 * Image style constant for user presets that override module-defined presets.
 */
define('IMAGE_STORAGE_OVERRIDE', 2);

/**
 * Image style constant for module-defined presets in code.
 */
define('IMAGE_STORAGE_DEFAULT', 4);

/**
 * Image style constant to represent an editable preset.
 */
define('IMAGE_STORAGE_EDITABLE', IMAGE_STORAGE_NORMAL | IMAGE_STORAGE_OVERRIDE);

/**
 * Image style constant to represent any module-based preset.
 */
define('IMAGE_STORAGE_MODULE', IMAGE_STORAGE_OVERRIDE | IMAGE_STORAGE_DEFAULT);

/**
 * The name of the query parameter for image derivative tokens.
 */
define('IMAGE_DERIVATIVE_TOKEN', 'itok');

// Load all Field module hooks for Image.
require_once DRUPAL_ROOT . '/modules/image/image.field.inc';

/**
 * Implements hook_help().
 */
function image_help($path, $arg) {
  switch ($path) {
    case 'admin/help#image':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Image module allows you to manipulate images on your website. It exposes a setting for using the <em>Image toolkit</em>, allows you to configure <em>Image styles</em> that can be used for resizing or adjusting images on display, and provides an <em>Image</em> field for attaching images to content. For more information, see the online handbook entry for <a href="@image">Image module</a>.', array('@image' => 'http://drupal.org/documentation/modules/image')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Manipulating images') . '</dt>';
      $output .= '<dd>' . t('With the Image module you can scale, crop, resize, rotate and desaturate images without affecting the original image using <a href="@image">image styles</a>. When you change an image style, the module automatically refreshes all created images. Every image style must have a name, which will be used in the URL of the generated images. There are two common approaches to naming image styles (which you use will depend on how the image style is being applied):',array('@image' => url('admin/config/media/image-styles')));
      $output .= '<ul><li>' . t('Based on where it will be used: eg. <em>profile-picture</em>') . '</li>';
      $output .= '<li>' . t('Describing its appearance: eg. <em>square-85x85</em>') . '</li></ul>';
      $output .=  t('After you create an image style, you can add effects: crop, scale, resize, rotate, and desaturate (other contributed modules provide additional effects). For example, by combining effects as crop, scale, and desaturate, you can create square, grayscale thumbnails.') . '<dd>';
      $output .= '<dt>' . t('Attaching images to content as fields') . '</dt>';
      $output .= '<dd>' . t("Image module also allows you to attach images to content as fields. To add an image field to a <a href='@content-type'>content type</a>, go to the content type's <em>manage fields</em> page, and add a new field of type <em>Image</em>. Attaching images to content this way allows image styles to be applied and maintained, and also allows you more flexibility when theming.", array('@content-type' => url('admin/structure/types'))) . '</dd>';
      $output .= '</dl>';
      return $output;
    case 'admin/config/media/image-styles':
      return '<p>' . t('Image styles commonly provide thumbnail sizes by scaling and cropping images, but can also add various effects before an image is displayed. When an image is displayed with a style, a new file is created and the original image is left unchanged.') . '</p>';
    case 'admin/config/media/image-styles/edit/%/add/%':
      $effect = image_effect_definition_load($arg[7]);
      return isset($effect['help']) ? ('<p>' . $effect['help'] . '</p>') : NULL;
    case 'admin/config/media/image-styles/edit/%/effects/%':
      $effect = ($arg[5] == 'add') ? image_effect_definition_load($arg[6]) : image_effect_load($arg[6], $arg[4]);
      return isset($effect['help']) ? ('<p>' . $effect['help'] . '</p>') : NULL;
  }
}

/**
 * Implements hook_menu().
 */
function image_menu() {
  $items = array();

  // Generate image derivatives of publicly available files.
  // If clean URLs are disabled, image derivatives will always be served
  // through the menu system.
  // If clean URLs are enabled and the image derivative already exists,
  // PHP will be bypassed.
  $directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
  $items[$directory_path . '/styles/%image_style'] = array(
    'title' => 'Generate image style',
    'page callback' => 'image_style_deliver',
    'page arguments' => array(count(explode('/', $directory_path)) + 1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  // Generate and deliver image derivatives of private files.
  // These image derivatives are always delivered through the menu system.
  $items['system/files/styles/%image_style'] = array(
    'title' => 'Generate image style',
    'page callback' => 'image_style_deliver',
    'page arguments' => array(3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/media/image-styles'] = array(
    'title' => 'Image styles',
    'description' => 'Configure styles that can be used for resizing or adjusting images on display.',
    'page callback' => 'image_style_list',
    'access arguments' => array('administer image styles'),
    'file' => 'image.admin.inc',
  );
  $items['admin/config/media/image-styles/list'] = array(
    'title' => 'List',
    'description' => 'List the current image styles on the site.',
    'page callback' => 'image_style_list',
    'access arguments' => array('administer image styles'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => 1,
    'file' => 'image.admin.inc',
  );
  $items['admin/config/media/image-styles/add'] = array(
    'title' => 'Add style',
    'description' => 'Add a new image style.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('image_style_add_form'),
    'access arguments' => array('administer image styles'),
    'type' => MENU_LOCAL_ACTION,
    'weight' => 2,
    'file' => 'image.admin.inc',
  );
  $items['admin/config/media/image-styles/edit/%image_style'] = array(
    'title' => 'Edit style',
    'description' => 'Configure an image style.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('image_style_form', 5),
    'access arguments' => array('administer image styles'),
    'file' => 'image.admin.inc',
  );
  $items['admin/config/media/image-styles/delete/%image_style'] = array(
    'title' => 'Delete style',
    'description' => 'Delete an image style.',
    'load arguments' => array(NULL, (string) IMAGE_STORAGE_NORMAL),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('image_style_delete_form', 5),
    'access arguments' => array('administer image styles'),
    'file' => 'image.admin.inc',
  );
  $items['admin/config/media/image-styles/revert/%image_style'] = array(
    'title' => 'Revert style',
    'description' => 'Revert an image style.',
    'load arguments' => array(NULL, (string) IMAGE_STORAGE_OVERRIDE),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('image_style_revert_form', 5),
    'access arguments' => array('administer image styles'),
    'file' => 'image.admin.inc',
  );
  $items['admin/config/media/image-styles/edit/%image_style/effects/%image_effect'] = array(
    'title' => 'Edit image effect',
    'description' => 'Edit an existing effect within a style.',
    'load arguments' => array(5, (string) IMAGE_STORAGE_EDITABLE),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('image_effect_form', 5, 7),
    'access arguments' => array('administer image styles'),
    'file' => 'image.admin.inc',
  );
  $items['admin/config/media/image-styles/edit/%image_style/effects/%image_effect/delete'] = array(
    'title' => 'Delete image effect',
    'description' => 'Delete an existing effect from a style.',
    'load arguments' => array(5, (string) IMAGE_STORAGE_EDITABLE),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('image_effect_delete_form', 5, 7),
    'access arguments' => array('administer image styles'),
    'file' => 'image.admin.inc',
  );
  $items['admin/config/media/image-styles/edit/%image_style/add/%image_effect_definition'] = array(
    'title' => 'Add image effect',
    'description' => 'Add a new effect to a style.',
    'load arguments' => array(5),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('image_effect_form', 5, 7),
    'access arguments' => array('administer image styles'),
    'file' => 'image.admin.inc',
  );

  return $items;
}

/**
 * Implements hook_theme().
 */
function image_theme() {
  return array(
    // Theme functions in image.module.
    'image_style' => array(
      'variables' => array(
        'style_name' => NULL,
        'path' => NULL,
        'width' => NULL,
        'height' => NULL,
        'alt' => '',
        'title' => NULL,
        'attributes' => array(),
      ),
    ),

    // Theme functions in image.admin.inc.
    'image_style_list' => array(
      'variables' => array('styles' => NULL),
    ),
    'image_style_effects' => array(
      'render element' => 'form',
    ),
    'image_style_preview' => array(
      'variables' => array('style' => NULL),
    ),
    'image_anchor' => array(
      'render element' => 'element',
    ),
    'image_resize_summary' => array(
      'variables' => array('data' => NULL),
    ),
    'image_scale_summary' => array(
      'variables' => array('data' => NULL),
    ),
    'image_crop_summary' => array(
      'variables' => array('data' => NULL),
    ),
    'image_rotate_summary' => array(
      'variables' => array('data' => NULL),
    ),

    // Theme functions in image.field.inc.
    'image_widget' => array(
      'render element' => 'element',
    ),
    'image_formatter' => array(
      'variables' => array('item' => NULL, 'path' => NULL, 'image_style' => NULL),
    ),
  );
}

/**
 * Implements hook_permission().
 */
function image_permission() {
  return array(
    'administer image styles' => array(
      'title' => t('Administer image styles'),
      'description' => t('Create and modify styles for generating image modifications such as thumbnails.'),
    ),
  );
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function image_form_system_file_system_settings_alter(&$form, &$form_state) {
  $form['#submit'][] = 'image_system_file_system_settings_submit';
}

/**
 * Form submission handler for system_file_system_settings().
 *
 * Adds a menu rebuild after the public file path has been changed, so that the
 * menu router item depending on that file path will be regenerated.
 */
function image_system_file_system_settings_submit($form, &$form_state) {
  if ($form['file_public_path']['#default_value'] !== $form_state['values']['file_public_path']) {
    variable_set('menu_rebuild_needed', TRUE);
  }
}

/**
 * Implements hook_flush_caches().
 */
function image_flush_caches() {
  return array('cache_image');
}

/**
 * Implements hook_file_download().
 *
 * Control the access to files underneath the styles directory.
 */
function image_file_download($uri) {
  $path = file_uri_target($uri);

  // Private file access for image style derivatives.
  if (strpos($path, 'styles/') === 0) {
    $args = explode('/', $path);
    // Discard the first part of the path (styles).
    array_shift($args);
    // Get the style name from the second part.
    $style_name = array_shift($args);
    // Remove the scheme from the path.
    array_shift($args);

    // Then the remaining parts are the path to the image.
    $original_uri = file_uri_scheme($uri) . '://' . implode('/', $args);

    // Check that the file exists and is an image.
    if ($info = image_get_info($uri)) {
      // Check the permissions of the original to grant access to this image.
      $headers = module_invoke_all('file_download', $original_uri);
      // Confirm there's at least one module granting access and none denying access.
      if (!empty($headers) && !in_array(-1, $headers)) {
        return array(
          // Send headers describing the image's size, and MIME-type...
          'Content-Type' => $info['mime_type'],
          'Content-Length' => $info['file_size'],
          // By not explicitly setting them here, this uses normal Drupal
          // Expires, Cache-Control and ETag headers to prevent proxy or
          // browser caching of private images.
        );
      }
    }
    return -1;
  }

  // Private file access for the original files. Note that we only check access
  // for non-temporary images, since file.module will grant access for all
  // temporary files.
  $files = file_load_multiple(array(), array('uri' => $uri));
  if (count($files)) {
    $file = reset($files);
    if ($file->status) {
      return file_file_download($uri, 'image');
    }
  }
}

/**
 * Implements hook_file_move().
 */
function image_file_move($file, $source) {
  // Delete any image derivatives at the original image path.
  image_path_flush($source->uri);
}

/**
 * Implements hook_file_delete().
 */
function image_file_delete($file) {
  // Delete any image derivatives of this image.
  image_path_flush($file->uri);
}

/**
 * Implements hook_image_default_styles().
 */
function image_image_default_styles() {
  $styles = array();

  $styles['thumbnail'] = array(
    'label' => 'Thumbnail (100x100)',
    'effects' => array(
      array(
        'name' => 'image_scale',
        'data' => array('width' => 100, 'height' => 100, 'upscale' => 1),
        'weight' => 0,
      ),
    )
  );

  $styles['medium'] = array(
    'label' => 'Medium (220x220)',
    'effects' => array(
      array(
        'name' => 'image_scale',
        'data' => array('width' => 220, 'height' => 220, 'upscale' => 1),
        'weight' => 0,
      ),
    )
  );

  $styles['large'] = array(
    'label' => 'Large (480x480)',
    'effects' => array(
      array(
        'name' => 'image_scale',
        'data' => array('width' => 480, 'height' => 480, 'upscale' => 0),
        'weight' => 0,
      ),
    )
  );

  return $styles;
}

/**
 * Implements hook_image_style_save().
 */
function image_image_style_save($style) {
  if (isset($style['old_name']) && $style['old_name'] != $style['name']) {
    $instances = field_read_instances();
    // Loop through all fields searching for image fields.
    foreach ($instances as $instance) {
      if ($instance['widget']['module'] == 'image') {
        $instance_changed = FALSE;
        foreach ($instance['display'] as $view_mode => $display) {
          // Check if the formatter involves an image style.
          if ($display['type'] == 'image' && $display['settings']['image_style'] == $style['old_name']) {
            // Update display information for any instance using the image
            // style that was just deleted.
            $instance['display'][$view_mode]['settings']['image_style'] = $style['name'];
            $instance_changed = TRUE;
          }
        }
        if ($instance['widget']['settings']['preview_image_style'] == $style['old_name']) {
          $instance['widget']['settings']['preview_image_style'] = $style['name'];
          $instance_changed = TRUE;
        }
        if ($instance_changed) {
          field_update_instance($instance);
        }
      }
    }
  }
}

/**
 * Implements hook_image_style_delete().
 */
function image_image_style_delete($style) {
  image_image_style_save($style);
}

/**
 * Implements hook_field_delete_field().
 */
function image_field_delete_field($field) {
  if ($field['type'] != 'image') {
    return;
  }

  // The value of a managed_file element can be an array if #extended == TRUE.
  $fid = (is_array($field['settings']['default_image']) ? $field['settings']['default_image']['fid'] : $field['settings']['default_image']);
  if ($fid && ($file = file_load($fid))) {
    file_usage_delete($file, 'image', 'default_image', $field['id']);
  }
}

/**
 * Implements hook_field_update_field().
 */
function image_field_update_field($field, $prior_field, $has_data) {
  if ($field['type'] != 'image') {
    return;
  }

  // The value of a managed_file element can be an array if #extended == TRUE.
  $fid_new = (is_array($field['settings']['default_image']) ? $field['settings']['default_image']['fid'] : $field['settings']['default_image']);
  $fid_old = (is_array($prior_field['settings']['default_image']) ? $prior_field['settings']['default_image']['fid'] : $prior_field['settings']['default_image']);

  $file_new = $fid_new ? file_load($fid_new) : FALSE;

  if ($fid_new != $fid_old) {

    // Is there a new file?
    if ($file_new) {
      $file_new->status = FILE_STATUS_PERMANENT;
      file_save($file_new);
      file_usage_add($file_new, 'image', 'default_image', $field['id']);
    }

    // Is there an old file?
    if ($fid_old && ($file_old = file_load($fid_old))) {
      file_usage_delete($file_old, 'image', 'default_image', $field['id']);
    }
  }

  // If the upload destination changed, then move the file.
  if ($file_new && (file_uri_scheme($file_new->uri) != $field['settings']['uri_scheme'])) {
    $directory = $field['settings']['uri_scheme'] . '://default_images/';
    file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
    file_move($file_new, $directory . $file_new->filename);
  }
}

/**
 * Implements hook_field_delete_instance().
 */
function image_field_delete_instance($instance) {
  // Only act on image fields.
  $field = field_read_field($instance['field_name']);
  if ($field['type'] != 'image') {
    return;
  }

  // The value of a managed_file element can be an array if the #extended
  // property is set to TRUE.
  $fid = $instance['settings']['default_image'];
  if (is_array($fid)) {
    $fid = $fid['fid'];
  }

  // Remove the default image when the instance is deleted.
  if ($fid && ($file = file_load($fid))) {
    file_usage_delete($file, 'image', 'default_image', $instance['id']);
  }
}

/**
 * Implements hook_field_update_instance().
 */
function image_field_update_instance($instance, $prior_instance) {
  // Only act on image fields.
  $field = field_read_field($instance['field_name']);
  if ($field['type'] != 'image') {
    return;
  }

  // The value of a managed_file element can be an array if the #extended
  // property is set to TRUE.
  $fid_new = $instance['settings']['default_image'];
  if (is_array($fid_new)) {
    $fid_new = $fid_new['fid'];
  }
  $fid_old = $prior_instance['settings']['default_image'];
  if (is_array($fid_old)) {
    $fid_old = $fid_old['fid'];
  }

  // If the old and new files do not match, update the default accordingly.
  $file_new = $fid_new ? file_load($fid_new) : FALSE;
  if ($fid_new != $fid_old) {
    // Save the new file, if present.
    if ($file_new) {
      $file_new->status = FILE_STATUS_PERMANENT;
      file_save($file_new);
      file_usage_add($file_new, 'image', 'default_image', $instance['id']);
    }
    // Delete the old file, if present.
    if ($fid_old && ($file_old = file_load($fid_old))) {
      file_usage_delete($file_old, 'image', 'default_image', $instance['id']);
    }
  }

  // If the upload destination changed, then move the file.
  if ($file_new && (file_uri_scheme($file_new->uri) != $field['settings']['uri_scheme'])) {
    $directory = $field['settings']['uri_scheme'] . '://default_images/';
    file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
    file_move($file_new, $directory . $file_new->filename);
  }
}

/**
 * Clears cached versions of a specific file in all styles.
 *
 * @param $path
 *   The Drupal file path to the original image.
 */
function image_path_flush($path) {
  $styles = image_styles();
  foreach ($styles as $style) {
    $image_path = image_style_path($style['name'], $path);
    if (file_exists($image_path)) {
      file_unmanaged_delete($image_path);
    }
  }
}

/**
 * Gets an array of all styles and their settings.
 *
 * @return
 *   An array of styles keyed by the image style ID (isid).
 * @see image_style_load()
 */
function image_styles() {
  $styles = &drupal_static(__FUNCTION__);

  // Grab from cache or build the array.
  if (!isset($styles)) {
    if ($cache = cache_get('image_styles', 'cache')) {
      $styles = $cache->data;
    }
    else {
      $styles = array();

      // Select the module-defined styles.
      foreach (module_implements('image_default_styles') as $module) {
        $module_styles = module_invoke($module, 'image_default_styles');
        foreach ($module_styles as $style_name => $style) {
          $style['name'] = $style_name;
          $style['label'] = empty($style['label']) ? $style_name : $style['label'];
          $style['module'] = $module;
          $style['storage'] = IMAGE_STORAGE_DEFAULT;
          foreach ($style['effects'] as $key => $effect) {
            $definition = image_effect_definition_load($effect['name']);
            $effect = array_merge($definition, $effect);
            $style['effects'][$key] = $effect;
          }
          $styles[$style_name] = $style;
        }
      }

      // Select all the user-defined styles.
      $user_styles = db_select('image_styles', NULL, array('fetch' => PDO::FETCH_ASSOC))
        ->fields('image_styles')
        ->orderBy('name')
        ->execute()
        ->fetchAllAssoc('name', PDO::FETCH_ASSOC);

      // Allow the user styles to override the module styles.
      foreach ($user_styles as $style_name => $style) {
        $style['module'] = NULL;
        $style['storage'] = IMAGE_STORAGE_NORMAL;
        $style['effects'] = image_style_effects($style);
        if (isset($styles[$style_name]['module'])) {
          $style['module'] = $styles[$style_name]['module'];
          $style['storage'] = IMAGE_STORAGE_OVERRIDE;
        }
        $styles[$style_name] = $style;
      }

      drupal_alter('image_styles', $styles);
      cache_set('image_styles', $styles);
    }
  }

  return $styles;
}

/**
 * Loads a style by style name or ID.
 *
 * May be used as a loader for menu items.
 *
 * @param $name
 *   The name of the style.
 * @param $isid
 *   Optional. The numeric id of a style if the name is not known.
 * @param $include
 *   If set, this loader will restrict to a specific type of image style, may be
 *   one of the defined Image style storage constants.
 *
 * @return
 *   An image style array containing the following keys:
 *   - "isid": The unique image style ID.
 *   - "name": The unique image style name.
 *   - "effects": An array of image effects within this image style.
 *   If the image style name or ID is not valid, an empty array is returned.
 * @see image_effect_load()
 */
function image_style_load($name = NULL, $isid = NULL, $include = NULL) {
  $styles = image_styles();

  // If retrieving by name.
  if (isset($name) && isset($styles[$name])) {
    $style = $styles[$name];
  }

  // If retrieving by image style id.
  if (!isset($name) && isset($isid)) {
    foreach ($styles as $name => $database_style) {
      if (isset($database_style['isid']) && $database_style['isid'] == $isid) {
        $style = $database_style;
        break;
      }
    }
  }

  // Restrict to the specific type of flag. This bitwise operation basically
  // states "if the storage is X, then allow".
  if (isset($style) && (!isset($include) || ($style['storage'] & (int) $include))) {
    return $style;
  }

  // Otherwise the style was not found.
  return FALSE;
}

/**
 * Saves an image style.
 *
 * @param array $style
 *   An image style array containing:
 *   - name: A unique name for the style.
 *   - isid: (optional) An image style ID.
 *
 * @return array
 *   An image style array containing:
 *   - name: An unique name for the style.
 *   - old_name: The original name for the style.
 *   - isid: An image style ID.
 *   - is_new: TRUE if this is a new style, and FALSE if it is an existing
 *     style.
 */
function image_style_save($style) {
  if (isset($style['isid']) && is_numeric($style['isid'])) {
    // Load the existing style to make sure we account for renamed styles.
    $old_style = image_style_load(NULL, $style['isid']);
    image_style_flush($old_style);
    drupal_write_record('image_styles', $style, 'isid');
    if ($old_style['name'] != $style['name']) {
      $style['old_name'] = $old_style['name'];
    }
  }
  else {
    // Add a default label when not given.
    if (empty($style['label'])) {
      $style['label'] = $style['name'];
    }
    drupal_write_record('image_styles', $style);
    $style['is_new'] = TRUE;
  }

  // Let other modules update as necessary on save.
  module_invoke_all('image_style_save', $style);

  // Clear all caches and flush.
  image_style_flush($style);

  return $style;
}

/**
 * Deletes an image style.
 *
 * @param $style
 *   An image style array.
 * @param $replacement_style_name
 *   (optional) When deleting a style, specify a replacement style name so
 *   that existing settings (if any) may be converted to a new style.
 *
 * @return
 *   TRUE on success.
 */
function image_style_delete($style, $replacement_style_name = '') {
  image_style_flush($style);

  db_delete('image_effects')->condition('isid', $style['isid'])->execute();
  db_delete('image_styles')->condition('isid', $style['isid'])->execute();

  // Let other modules update as necessary on save.
  $style['old_name'] = $style['name'];
  $style['name'] = $replacement_style_name;
  module_invoke_all('image_style_delete', $style);

  return TRUE;
}

/**
 * Loads all the effects for an image style.
 *
 * @param array $style
 *   An image style array containing:
 *   - isid: The unique image style ID that contains this image effect.
 *
 * @return array
 *   An array of image effects associated with specified image style in the
 *   format array('isid' => array()), or an empty array if the specified style
 *   has no effects.
 * @see image_effects()
 */
function image_style_effects($style) {
  $effects = image_effects();
  $style_effects = array();
  foreach ($effects as $effect) {
    if ($style['isid'] == $effect['isid']) {
      $style_effects[$effect['ieid']] = $effect;
    }
  }

  return $style_effects;
}

/**
 * Gets an array of image styles suitable for using as select list options.
 *
 * @param $include_empty
 *   If TRUE a <none> option will be inserted in the options array.
 * @param $output
 *   Optional flag determining how the options will be sanitized on output.
 *   Leave this at the default (CHECK_PLAIN) if you are using the output of
 *   this function directly in an HTML context, such as for checkbox or radio
 *   button labels, and do not plan to sanitize it on your own. If using the
 *   output of this function as select list options (its primary use case), you
 *   should instead set this flag to PASS_THROUGH to avoid double-escaping of
 *   the output (the form API sanitizes select list options by default).
 *
 * @return
 *   Array of image styles with the machine name as key and the label as value.
 */
function image_style_options($include_empty = TRUE, $output = CHECK_PLAIN) {
  $styles = image_styles();
  $options = array();
  if ($include_empty && !empty($styles)) {
    $options[''] = t('<none>');
  }
  foreach ($styles as $name => $style) {
    $options[$name] = ($output == PASS_THROUGH) ? $style['label'] : check_plain($style['label']);
  }

  if (empty($options)) {
    $options[''] = t('No defined styles');
  }
  return $options;
}

/**
 * Page callback: Generates a derivative, given a style and image path.
 *
 * After generating an image, transfer it to the requesting agent.
 *
 * @param $style
 *   The image style
 */
function image_style_deliver($style, $scheme) {
  $args = func_get_args();
  array_shift($args);
  array_shift($args);
  $target = implode('/', $args);

  // Check that the style is defined, the scheme is valid, and the image
  // derivative token is valid. (Sites which require image derivatives to be
  // generated without a token can set the 'image_allow_insecure_derivatives'
  // variable to TRUE to bypass the latter check, but this will increase the
  // site's vulnerability to denial-of-service attacks. To prevent this
  // variable from leaving the site vulnerable to the most serious attacks, a
  // token is always required when a derivative of a derivative is requested.)
  $valid = !empty($style) && file_stream_wrapper_valid_scheme($scheme);
  if (!variable_get('image_allow_insecure_derivatives', FALSE) || strpos(ltrim($target, '\/'), 'styles/') === 0) {
    $valid = $valid && isset($_GET[IMAGE_DERIVATIVE_TOKEN]) && $_GET[IMAGE_DERIVATIVE_TOKEN] === image_style_path_token($style['name'], $scheme . '://' . $target);
  }
  if (!$valid) {
    return MENU_ACCESS_DENIED;
  }

  $image_uri = $scheme . '://' . $target;
  $derivative_uri = image_style_path($style['name'], $image_uri);

  // If using the private scheme, let other modules provide headers and
  // control access to the file.
  if ($scheme == 'private') {
    if (file_exists($derivative_uri)) {
      file_download($scheme, file_uri_target($derivative_uri));
    }
    else {
      $headers = module_invoke_all('file_download', $image_uri);
      if (in_array(-1, $headers) || empty($headers)) {
        return MENU_ACCESS_DENIED;
      }
      if (count($headers)) {
        foreach ($headers as $name => $value) {
          drupal_add_http_header($name, $value);
        }
      }
    }
  }

  // Confirm that the original source image exists before trying to process it.
  if (!is_file($image_uri)) {
    watchdog('image', 'Source image at %source_image_path not found while trying to generate derivative image at %derivative_path.',  array('%source_image_path' => $image_uri, '%derivative_path' => $derivative_uri));
    return MENU_NOT_FOUND;
  }

  // Don't start generating the image if the derivative already exists or if
  // generation is in progress in another thread.
  $lock_name = 'image_style_deliver:' . $style['name'] . ':' . drupal_hash_base64($image_uri);
  if (!file_exists($derivative_uri)) {
    $lock_acquired = lock_acquire($lock_name);
    if (!$lock_acquired) {
      // Tell client to retry again in 3 seconds. Currently no browsers are known
      // to support Retry-After.
      drupal_add_http_header('Status', '503 Service Unavailable');
      drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
      drupal_add_http_header('Retry-After', 3);
      print t('Image generation in progress. Try again shortly.');
      drupal_exit();
    }
  }

  // Try to generate the image, unless another thread just did it while we were
  // acquiring the lock.
  $success = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);

  if (!empty($lock_acquired)) {
    lock_release($lock_name);
  }

  if ($success) {
    $image = image_load($derivative_uri);
    file_transfer($image->source, array('Content-Type' => $image->info['mime_type'], 'Content-Length' => $image->info['file_size']));
  }
  else {
    watchdog('image', 'Unable to generate the derived image located at %path.', array('%path' => $derivative_uri));
    drupal_add_http_header('Status', '500 Internal Server Error');
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
    print t('Error generating image.');
    drupal_exit();
  }
}

/**
 * Creates a new image derivative based on an image style.
 *
 * Generates an image derivative by creating the destination folder (if it does
 * not already exist), applying all image effects defined in $style['effects'],
 * and saving a cached version of the resulting image.
 *
 * @param $style
 *   An image style array.
 * @param $source
 *   Path of the source file.
 * @param $destination
 *   Path or URI of the destination file.
 *
 * @return
 *   TRUE if an image derivative was generated, or FALSE if the image derivative
 *   could not be generated.
 *
 * @see image_style_load()
 */
function image_style_create_derivative($style, $source, $destination) {
  // If the source file doesn't exist, return FALSE without creating folders.
  if (!$image = image_load($source)) {
    return FALSE;
  }

  // Get the folder for the final location of this style.
  $directory = drupal_dirname($destination);

  // Build the destination folder tree if it doesn't already exist.
  if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
    watchdog('image', 'Failed to create style directory: %directory', array('%directory' => $directory), WATCHDOG_ERROR);
    return FALSE;
  }

  foreach ($style['effects'] as $effect) {
    image_effect_apply($image, $effect);
  }

  if (!image_save($image, $destination)) {
    if (file_exists($destination)) {
      watchdog('image', 'Cached image file %destination already exists. There may be an issue with your rewrite configuration.', array('%destination' => $destination), WATCHDOG_ERROR);
    }
    return FALSE;
  }

  return TRUE;
}

/**
 * Determines the dimensions of the styled image.
 *
 * Applies all of an image style's effects to $dimensions.
 *
 * @param $style_name
 *   The name of the style to be applied.
 * @param $dimensions
 *   Dimensions to be modified - an array with components width and height, in
 *   pixels.
 */
function image_style_transform_dimensions($style_name, array &$dimensions) {
  module_load_include('inc', 'image', 'image.effects');
  $style = image_style_load($style_name);

  if (!is_array($style)) {
    return;
  }

  foreach ($style['effects'] as $effect) {
    if (isset($effect['dimensions passthrough'])) {
      continue;
    }

    if (isset($effect['dimensions callback'])) {
      $effect['dimensions callback']($dimensions, $effect['data']);
    }
    else {
      $dimensions['width'] = $dimensions['height'] = NULL;
    }
  }
}

/**
 * Flushes cached media for a style.
 *
 * @param $style
 *   An image style array.
 */
function image_style_flush($style) {
  // Delete the style directory in each registered wrapper.
  $wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE);
  foreach ($wrappers as $wrapper => $wrapper_data) {
    if (file_exists($directory = $wrapper . '://styles/' . $style['name'])) {
      file_unmanaged_delete_recursive($directory);
    }
  }

  // Let other modules update as necessary on flush.
  module_invoke_all('image_style_flush', $style);

  // Clear image style and effect caches.
  cache_clear_all('image_styles', 'cache');
  cache_clear_all('image_effects:', 'cache', TRUE);
  drupal_static_reset('image_styles');
  drupal_static_reset('image_effects');

  // Clear field caches so that formatters may be added for this style.
  field_info_cache_clear();
  drupal_theme_rebuild();

  // Clear page caches when flushing.
  if (module_exists('block')) {
    cache_clear_all('*', 'cache_block', TRUE);
  }
  cache_clear_all('*', 'cache_page', TRUE);
}

/**
 * Returns the URL for an image derivative given a style and image path.
 *
 * @param $style_name
 *   The name of the style to be used with this image.
 * @param $path
 *   The path to the image.
 *
 * @return
 *   The absolute URL where a style image can be downloaded, suitable for use
 *   in an <img> tag. Requesting the URL will cause the image to be created.
 * @see image_style_deliver()
 */
function image_style_url($style_name, $path) {
  $uri = image_style_path($style_name, $path);

  // The passed-in $path variable can be either a relative path or a full URI.
  $original_uri = file_uri_scheme($path) ? file_stream_wrapper_uri_normalize($path) : file_build_uri($path);

  // The token query is added even if the 'image_allow_insecure_derivatives'
  // variable is TRUE, so that the emitted links remain valid if it is changed
  // back to the default FALSE.
  // However, sites which need to prevent the token query from being emitted at
  // all can additionally set the 'image_suppress_itok_output' variable to TRUE
  // to achieve that (if both are set, the security token will neither be
  // emitted in the image derivative URL nor checked for in
  // image_style_deliver()).
  $token_query = array();
  if (!variable_get('image_suppress_itok_output', FALSE)) {
    $token_query = array(IMAGE_DERIVATIVE_TOKEN => image_style_path_token($style_name, $original_uri));
  }

  // If not using clean URLs, the image derivative callback is only available
  // with the query string. If the file does not exist, use url() to ensure
  // that it is included. Once the file exists it's fine to fall back to the
  // actual file path, this avoids bootstrapping PHP once the files are built.
  if (!variable_get('clean_url') && file_uri_scheme($uri) == 'public' && !file_exists($uri)) {
    $directory_path = file_stream_wrapper_get_instance_by_uri($uri)->getDirectoryPath();
    return url($directory_path . '/' . file_uri_target($uri), array('absolute' => TRUE, 'query' => $token_query));
  }

  $file_url = file_create_url($uri);
  // Append the query string with the token, if necessary.
  if ($token_query) {
    $file_url .= (strpos($file_url, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($token_query);
  }

  return $file_url;
}

/**
 * Generates a token to protect an image style derivative.
 *
 * This prevents unauthorized generation of an image style derivative,
 * which can be costly both in CPU time and disk space.
 *
 * @param $style_name
 *   The name of the image style.
 * @param $uri
 *   The URI of the image for this style, for example as returned by
 *   image_style_path().
 *
 * @return
 *   An eight-character token which can be used to protect image style
 *   derivatives against denial-of-service attacks.
 */
function image_style_path_token($style_name, $uri) {
  // Return the first eight characters.
  return substr(drupal_hmac_base64($style_name . ':' . $uri, drupal_get_private_key() . drupal_get_hash_salt()), 0, 8);
}

/**
 * Returns the URI of an image when using a style.
 *
 * The path returned by this function may not exist. The default generation
 * method only creates images when they are requested by a user's browser.
 *
 * @param $style_name
 *   The name of the style to be used with this image.
 * @param $uri
 *   The URI or path to the image.
 *
 * @return
 *   The URI to an image style image.
 * @see image_style_url()
 */
function image_style_path($style_name, $uri) {
  $scheme = file_uri_scheme($uri);
  if ($scheme) {
    $path = file_uri_target($uri);
  }
  else {
    $path = $uri;
    $scheme = file_default_scheme();
  }
  return $scheme . '://styles/' . $style_name . '/' . $scheme . '/' . $path;
}

/**
 * Saves a default image style to the database.
 *
 * @param style
 *   An image style array provided by a module.
 *
 * @return
 *   An image style array. The returned style array will include the new 'isid'
 *   assigned to the style.
 */
function image_default_style_save($style) {
  $style = image_style_save($style);
  $effects = array();
  foreach ($style['effects'] as $effect) {
    $effect['isid'] = $style['isid'];
    $effect = image_effect_save($effect);
    $effects[$effect['ieid']] = $effect;
  }
  $style['effects'] = $effects;
  return $style;
}

/**
 * Reverts the changes made by users to a default image style.
 *
 * @param style
 *   An image style array.
 * @return
 *   Boolean TRUE if the operation succeeded.
 */
function image_default_style_revert($style) {
  image_style_flush($style);

  db_delete('image_effects')->condition('isid', $style['isid'])->execute();
  db_delete('image_styles')->condition('isid', $style['isid'])->execute();

  return TRUE;
}

/**
 * Returns a set of image effects.
 *
 * These image effects are exposed by modules implementing
 * hook_image_effect_info().
 *
 * @return
 *   An array of image effects to be used when transforming images.
 * @see hook_image_effect_info()
 * @see image_effect_definition_load()
 */
function image_effect_definitions() {
  global $language;

  // hook_image_effect_info() includes translated strings, so each language is
  // cached separately.
  $langcode = $language->language;

  $effects = &drupal_static(__FUNCTION__);

  if (!isset($effects)) {
    if ($cache = cache_get("image_effects:$langcode")) {
      $effects = $cache->data;
    }
    else {
      $effects = array();
      include_once DRUPAL_ROOT . '/modules/image/image.effects.inc';
      foreach (module_implements('image_effect_info') as $module) {
        foreach (module_invoke($module, 'image_effect_info') as $name => $effect) {
          // Ensure the current toolkit supports the effect.
          $effect['module'] = $module;
          $effect['name'] = $name;
          $effect['data'] = isset($effect['data']) ? $effect['data'] : array();
          $effects[$name] = $effect;
        }
      }
      uasort($effects, '_image_effect_definitions_sort');
      drupal_alter('image_effect_info', $effects);
      cache_set("image_effects:$langcode", $effects);
    }
  }

  return $effects;
}

/**
 * Loads the definition for an image effect.
 *
 * The effect definition is a set of core properties for an image effect, not
 * containing any user-settings. The definition defines various functions to
 * call when configuring or executing an image effect. This loader is mostly for
 * internal use within image.module. Use image_effect_load() or
 * image_style_load() to get image effects that contain configuration.
 *
 * @param $effect
 *   The name of the effect definition to load.
 * @param $style
 *   An image style array to which this effect will be added.
 *
 * @return
 *   An array containing the image effect definition with the following keys:
 *   - "effect": The unique name for the effect being performed. Usually prefixed
 *     with the name of the module providing the effect.
 *   - "module": The module providing the effect.
 *   - "help": A description of the effect.
 *   - "function": The name of the function that will execute the effect.
 *   - "form": (optional) The name of a function to configure the effect.
 *   - "summary": (optional) The name of a theme function that will display a
 *     one-line summary of the effect. Does not include the "theme_" prefix.
 */
function image_effect_definition_load($effect, $style_name = NULL) {
  $definitions = image_effect_definitions();

  // If a style is specified, do not allow loading of default style
  // effects.
  if (isset($style_name)) {
    $style = image_style_load($style_name, NULL);
    if ($style['storage'] == IMAGE_STORAGE_DEFAULT) {
      return FALSE;
    }
  }

  return isset($definitions[$effect]) ? $definitions[$effect] : FALSE;
}

/**
 * Loads all image effects from the database.
 *
 * @return
 *   An array of all image effects.
 * @see image_effect_load()
 */
function image_effects() {
  $effects = &drupal_static(__FUNCTION__);

  if (!isset($effects)) {
    $effects = array();

    // Add database image effects.
    $result = db_select('image_effects', NULL, array('fetch' => PDO::FETCH_ASSOC))
      ->fields('image_effects')
      ->orderBy('image_effects.weight', 'ASC')
      ->execute();
    foreach ($result as $effect) {
      $effect['data'] = unserialize($effect['data']);
      $definition = image_effect_definition_load($effect['name']);
      // Do not load image effects whose definition cannot be found.
      if ($definition) {
        $effect = array_merge($definition, $effect);
        $effects[$effect['ieid']] = $effect;
      }
    }
  }

  return $effects;
}

/**
 * Loads a single image effect.
 *
 * @param $ieid
 *   The image effect ID.
 * @param $style_name
 *   The image style name.
 * @param $include
 *   If set, this loader will restrict to a specific type of image style, may be
 *   one of the defined Image style storage constants.
 *
 * @return
 *   An image effect array, consisting of the following keys:
 *   - "ieid": The unique image effect ID.
 *   - "isid": The unique image style ID that contains this image effect.
 *   - "weight": The weight of this image effect within the image style.
 *   - "name": The name of the effect definition that powers this image effect.
 *   - "data": An array of configuration options for this image effect.
 *   Besides these keys, the entirety of the image definition is merged into
 *   the image effect array. Returns FALSE if the specified effect cannot be
 *   found.
 * @see image_style_load()
 * @see image_effect_definition_load()
 */
function image_effect_load($ieid, $style_name, $include = NULL) {
  if (($style = image_style_load($style_name, NULL, $include)) && isset($style['effects'][$ieid])) {
    return $style['effects'][$ieid];
  }
  return FALSE;
}

/**
 * Saves an image effect.
 *
 * @param $effect
 *   An image effect array.
 *
 * @return
 *   An image effect array. In the case of a new effect, 'ieid' will be set.
 */
function image_effect_save($effect) {
  if (!empty($effect['ieid'])) {
    drupal_write_record('image_effects', $effect, 'ieid');
  }
  else {
    drupal_write_record('image_effects', $effect);
  }
  $style = image_style_load(NULL, $effect['isid']);
  image_style_flush($style);
  return $effect;
}

/**
 * Deletes an image effect.
 *
 * @param $effect
 *   An image effect array.
 */
function image_effect_delete($effect) {
  db_delete('image_effects')->condition('ieid', $effect['ieid'])->execute();
  $style = image_style_load(NULL, $effect['isid']);
  image_style_flush($style);
}

/**
 * Applies an image effect to the image object.
 *
 * @param $image
 *   An image object returned by image_load().
 * @param $effect
 *   An image effect array.
 *
 * @return
 *   TRUE on success. FALSE if unable to perform the image effect on the image.
 */
function image_effect_apply($image, $effect) {
  module_load_include('inc', 'image', 'image.effects');
  $function = $effect['effect callback'];
  if (function_exists($function)) {
    return $function($image, $effect['data']);
  }
  return FALSE;
}

/**
 * Returns HTML for an image using a specific image style.
 *
 * @param $variables
 *   An associative array containing:
 *   - style_name: The name of the style to be used to alter the original image.
 *   - path: The path of the image file relative to the Drupal files directory.
 *     This function does not work with images outside the files directory nor
 *     with remotely hosted images. This should be in a format such as
 *     'images/image.jpg', or using a stream wrapper such as
 *     'public://images/image.jpg'.
 *   - width: The width of the source image (if known).
 *   - height: The height of the source image (if known).
 *   - alt: The alternative text for text-based browsers.
 *   - title: The title text is displayed when the image is hovered in some
 *     popular browsers.
 *   - attributes: Associative array of attributes to be placed in the img tag.
 *
 * @ingroup themeable
 */
function theme_image_style($variables) {
  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  image_style_transform_dimensions($variables['style_name'], $dimensions);

  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  // Determine the URL for the styled image.
  $variables['path'] = image_style_url($variables['style_name'], $variables['path']);
  return theme('image', $variables);
}

/**
 * Accepts a keyword (center, top, left, etc) and returns it as a pixel offset.
 *
 * @param $value
 * @param $current_pixels
 * @param $new_pixels
 */
function image_filter_keyword($value, $current_pixels, $new_pixels) {
  switch ($value) {
    case 'top':
    case 'left':
      return 0;

    case 'bottom':
    case 'right':
      return $current_pixels - $new_pixels;

    case 'center':
      return $current_pixels / 2 - $new_pixels / 2;
  }
  return $value;
}

/**
 * Internal function for sorting image effect definitions through uasort().
 *
 * @see image_effect_definitions()
 */
function _image_effect_definitions_sort($a, $b) {
  return strcasecmp($a['name'], $b['name']);
}