summaryrefslogtreecommitdiffstats
path: root/filefield.module
blob: b82d7fe3f67175a5a34c57867e130efdef8ddc6e (plain)
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
<?php
// $Id$

/**
 * @file
 * FileField: Defines a CCK file field type.
 *
 * Uses content.module to store the fid and field specific metadata,
 * and Drupal's {files} table to store the actual file data.
 */

include_once('field_file.inc');

/**
 * Implementation of hook_init().
 */
function filefield_init() {
  // File hooks and callbacks may be used by any module.
  module_load_include('inc', 'filefield', 'filefield_widget');
  drupal_add_css(drupal_get_path('module', 'filefield') .'/filefield.css');

  // Conditional module support.
  if (module_exists('token')) {
    module_load_include('inc', 'filefield', 'filefield.token');
  }
}

/**
 * Implementation of hook_menu().
 */
function filefield_menu() {
  $items = array();

  $items['filefield/ahah/%/%/%'] = array(
    'page callback' => 'filefield_js',
    'page arguments' => array(2, 3, 4),
    'access callback' => 'filefield_edit_access',
    'access arguments' => array(3),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implementation of hook_elements().
 * @todo: autogenerate element registry entries for widgets.
 */
function filefield_elements() {
  $elements = array();
  $elements['filefield_widget'] =  array(
    '#input' => TRUE,
    '#columns' => array('fid', 'list', 'data'),
    '#process' => array('filefield_widget_process'),
    '#value_callback' => 'filefield_widget_value',
    '#element_validate' => array('filefield_widget_validate'),
    '#description' => t('Changes made to the attachments are not permanent until you save this post.'),
  );
  return $elements;
}

/**
 * Implementation of hook_theme().
 * @todo: autogenerate theme registry entrys for widgets.
 */
function filefield_theme() {
  return array(
    'filefield_file' => array(
      'arguments' => array('file' => NULL),
      'file' => 'filefield_formatter.inc',
    ),
    'filefield_icon' => array(
      'arguments' => array('file' => NULL),
      'file' => 'filefield.theme.inc',
    ),
    'filefield_widget' => array(
      'arguments' => array('element' => NULL),
      'file' => 'filefield_widget.inc',
    ),
    'filefield_widget_item' => array(
      'arguments' => array('element' => NULL),
      'file' => 'filefield_widget.inc',
    ),
    'filefield_widget_preview' => array(
      'arguments' => array('element' => NULL),
      'file' => 'filefield_widget.inc',
    ),
    'filefield_widget_file' => array(
      'arguments' => array('element' => NULL),
      'file' => 'filefield_widget.inc',
    ),


    'filefield_formatter_default' => array(
      'arguments' => array('element' => NULL),
      'file' => 'filefield_formatter.inc',
    ),
    'filefield_formatter_url_plain' => array(
      'arguments' => array('element' => NULL),
      'file' => 'filefield_formatter.inc',
    ),
    'filefield_formatter_path_plain' => array(
      'arguments' => array('element' => NULL),
      'file' => 'filefield_formatter.inc',
    ),
    'filefield_item' => array(
      'arguments' => array('file' => NULL, 'field' => NULL),
      'file' => 'filefield_formatter.inc',
    ),
    'filefield_file' => array(
      'arguments' => array('file' => NULL),
      'file' => 'filefield_formatter.inc',
    ),

 );
}

/**
 * Implementation of hook_file_download(). Yes, *that* hook that causes
 * any attempt for file upload module interoperability to fail spectacularly.
 */
function filefield_file_download($file) {
  $file = file_create_path($file);

  $result = db_query("SELECT * FROM {files} WHERE filepath = '%s'", $file);
  if (!$file = db_fetch_object($result)) {
    // We don't really care about this file.
    return;
  }

  // Find out if any filefield contains this file, and if so, which field
  // and node it belongs to. Required for later access checking.
  $cck_files = array();
  foreach (content_fields() as $field) {
    if ($field['type'] == 'filefield' || $field['type'] == 'image') {
      $db_info = content_database_info($field);
      $table = $db_info['table'];
      $fid_column = $db_info['columns']['fid']['column'];

      $columns = array('vid', 'nid');
      foreach ($db_info['columns'] as $property_name => $column_info) {
        $columns[] = $column_info['column'] .' AS '. $property_name;
      }
      $result = db_query("SELECT ". implode(', ', $columns) ."
                          FROM {". $table ."}
                          WHERE ". $fid_column ." = %d", $file->fid);

      while ($content = db_fetch_array($result)) {
        $content['field'] = $field;
        $cck_files[$field['field_name']][$content['vid']] = $content;
      }
    }
  }
  // If no filefield item is involved with this file, we don't care about it.
  if (empty($cck_files)) {
    return;
  }

  // If any node includes this file but the user may not view this field,
  // then deny the download.
  foreach ($cck_files as $field_name => $field_files) {
    if (!filefield_view_access($field_name)) {
      return -1;
    }
  }

  // So the overall field view permissions are not denied, but if access is
  // denied for a specific node containing the file, deny the download as well.
  // It's probably a little too restrictive, but I can't think of a
  // better way at the moment. Input appreciated.
  // (And yeah, node access checks also include checking for 'access content'.)
  $nodes = array();
  foreach ($cck_files as $field_name => $field_files) {
    foreach ($field_files as $revision_id => $content) {
      // Checking separately for each revision is probably not the best idea -
      // what if 'view revisions' is disabled? So, let's just check for the
      // current revision of that node.
      if (isset($nodes[$content['nid']])) {
        continue; // don't check the same node twice
      }
      $node = node_load($content['nid']);
      if (!node_access('view', $node)) {
        // You don't have permission to view the node this file is attached to.
        return -1;
      }
      $nodes[$content['nid']] = $node;
    }
  }

  // Well I guess you can see this file.
  $name = mime_header_encode($file->filename);
  $type = mime_header_encode($file->filemime);
  // Serve images and text inline for the browser to display rather than download.
  $disposition = ereg('^(text/|image/)', $file->filemime) ? 'inline' : 'attachment';
  return array(
    'Content-Type: '. $type .'; name='. $name,
    'Content-Length: '. $file->filesize,
    'Content-Disposition: '. $disposition .'; filename='. $name,
    'Cache-Control: private',
  );
}

/**
 * Implementation of hook_form_alter().
 *
 * Set the appropriate attibutes to allow file uploads on the field settings
 * form.
 */
function filefield_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'content_field_edit_form' && isset($form['#field']) && $form['#field']['type'] == 'filefield') {
    $form['#attributes']['enctype'] = 'multipart/form-data';
  }

  if (preg_match('/_node_form$/', $form_id)) {
    $form['#attributes']['enctype'] = 'multipart/form-data';
  }
}

/**
 * Implementation of CCK's hook_field_info().
 */
function filefield_field_info() {
  return array(
    'filefield' => array(
      'label' => 'File',
      'description' => t('Store an arbitrary file.'),
    ),
  );
}

/**
 * Implementation of hook_field_settings().
 */
function filefield_field_settings($op, $field) {
  $return = array();

  module_load_include('inc', 'filefield', 'filefield_field');
  $op = str_replace(' ', '_', $op);
  // add filefield specific handlers...
  $function = 'filefield_field_settings_'. $op;
  if (function_exists($function)) {
    $result = $function($field);
    if (isset($result) && is_array($result)) {
      $return = $result;
    }
  }

  // dynamically load widgets file and callbacks for other fields utilizing
  // filefield's hook_field_settings implementation.
  module_load_include('inc', $field['module'], $field['type'] .'_field');
  $function = $field['module'] .'_'. $field['type'] .'_field_settings_'. $op;
  if (function_exists($function)) {
    $result = $function($field);
    if (isset($result) && is_array($result)) {
      $return = array_merge($return, $result);
    }
  }

  return $return;

}

/**
 * Implementtation of CCK's hook_field().
 */
function filefield_field($op, $node, $field, &$items, $teaser, $page) {
  module_load_include('inc', 'filefield', 'filefield_field');
  $op = str_replace(' ', '_', $op);
  // add filefield specific handlers...
  $function = 'filefield_field_'. $op;
  if (function_exists($function)) {
    return $function($node, $field, $items, $teaser, $page);
  }
}

/**
 * Implementation of CCK's hook_widget_settings().
 */
function filefield_widget_settings($op, $widget) {
  switch ($op) {
    case 'form':
      return filefield_widget_settings_form($widget);
    case 'save':
      return filefield_widget_settings_save($widget);
  }
}

/**
 * Implementation of hook_widget().
 */
function filefield_widget(&$form, &$form_state, $field, $items, $delta = 0) {
  // CCK doesn't give a validate callback at the field level...
  // and FAPI's #require is naieve to complex structures...
  // we validate at the field level ourselves.
  if (empty($form['#validate']) || !in_array('filefield_node_form_validate', $form['#validate'])) {
    $form['#validate'][] = 'filefield_node_form_validate';
  }
  if (empty($form['#submit']) || !in_array('filefield_node_form_submit', $form['#submit'])) {
    $form['#submit'][] = 'filefield_node_form_submit';
  }
  $form['#attributes'] = array('enctype' => 'multipart/form-data');

  module_load_include('inc', 'filefield', 'field_widget');
  module_load_include('inc', $field['widget']['module'], $field['widget']['module'] .'_widget');

  $item = array('fid' => 0, 'list' => $field['list_default'], 'data' => array('description' => ''));
  if (isset($items[$delta])) {
    $item = array_merge($item, $items[$delta]);
  }
  $element = array(
    '#title' => $field['widget']['label'],
    '#type' => $field['widget']['type'],
    '#default_value' => $item,
    '#upload_validators' => filefield_widget_upload_validators($field),
  );

  return $element;
}

/**
 * Get the upload validators for a file field.
 *
 * @param $field
 *   A CCK field array.
 * @return
 *   An array suitable for passing to file_save_upload() or the file field
 *   element's '#upload_validators' property.
 */
function filefield_widget_upload_validators($field) {
  $max_filesize = parse_size(file_upload_max_size());
  if (!empty($field['widget']['max_filesize_per_file']) && parse_size($field['widget']['max_filesize_per_file']) < $max_filesize) {
    $max_filesize = parse_size($field['widget']['max_filesize_per_file']);
  }

  $validators = array(
    // associate the field to the file on validation.
    'filefield_validate_associate_field' => array($field),
    'filefield_validate_size' => array($max_filesize),
    // Override core since it excludes uid 1 on the extension check. 
    // Filefield only excuses uid 1 of quota requirements.
    'filefield_validate_extensions' => array($field['widget']['file_extensions']),
  );
  return $validators;
}

/**
 * Implementation of CCK's hook_content_is_empty().
 *
 * The result of this determines whether content.module will save the value of
 * the field. Note that content module has some interesting behaviors for empty
 * values. It will always save at least one record for every node revision,
 * even if the values are all NULL. If it is a multi-value field with an
 * explicit limit, CCK will save that number of empty entries.
 */
function filefield_content_is_empty($item, $field) {
  return empty($item['fid']) || (int)$item['fid'] == 0;
}

/**
 * Implementation of CCK's hook_widget_info().
 */
function filefield_widget_info() {
  return array(
    'filefield_widget' => array(
      'label' => t('File Upload'),
      'field types' => array('filefield'),
      'multiple values' => CONTENT_HANDLE_CORE,
      'callbacks' => array('default value' => CONTENT_CALLBACK_CUSTOM),
      'description' => t('A plain file upload widget.'),
    ),
  );
}

/**
 * Implementation of CCK's hook_field_formatter_info().
 */
function filefield_field_formatter_info() {
  return array(
    'default' => array(
      'label' => t('Generic files'),
      'field types' => array('filefield'),
      'multiple values' => CONTENT_HANDLE_CORE,
      'description' => t('Displays all kinds of files with an icon and a linked file description.'),
    ),
    'path_plain' => array(
      'label' => t('Path to file'),
      'field types' => array('filefield'),
      'description' => t('Displays the file system path to the file.'),
    ),
    'url_plain' => array(
      'label' => t('URL to file'),
      'field types' => array('filefield'),
      'description' => t('Displays a full URL to the file.'),
    ),
  );
}

/**
 * Determine the most appropriate icon for the given file's mimetype.
 *
 * @param $file
 *   A file object.
 * @return
 *   The URL of the icon image file, or FALSE if no icon could be found.
 */
function filefield_icon_url($file) {
  include_once(drupal_get_path('module', 'filefield') .'/filefield.theme.inc');
  return _filefield_icon_url($file);
}

/**
 * Access callback for the JavaScript upload and deletion AHAH callbacks.
 *
 * The content_permissions module provides nice fine-grained permissions for
 * us to check, so we can make sure that the user may actually edit the file.
 */
function filefield_edit_access($field_name) {
  if (module_exists('content_permissions')) {
    return user_access('edit '. $field_name);
  }
  // No content permissions to check, so let's fall back to a more general permission.
  return user_access('access content');
}

/**
 * Access callback that checks if the current user may view the filefield.
 */
function filefield_view_access($field_name) {
  if (module_exists('content_permissions')) {
    return user_access('view '. $field_name);
  }
  // No content permissions to check, so let's fall back to a more general permission.
  return user_access('access content');
}

/**
 * Menu callback; Shared AHAH callback for uploads and deletions.
 *
 * This rebuilds the form element for a particular field item. As long as the
 * form processing is properly encapsulated in the widget element the form
 * should rebuild correctly using FAPI without the need for additional callbacks
 * or processing.
 */
function filefield_js($type_name, $field_name, $delta) {
  $field = content_fields($field_name, $type_name);

  if (empty($field) || empty($_POST['form_build_id'])) {
    // Invalid request.
    print drupal_to_js(array('data' => ''));
    exit;
  }

  // Build the new form.
  $form_state = array('submitted' => FALSE);
  $form_build_id = $_POST['form_build_id'];
  $form = form_get_cache($form_build_id, $form_state);

  if (!$form) {
    // Invalid form_build_id.
    print drupal_to_js(array('data' => ''));
    exit;
  }

  // Build the form. This calls the file field's #value_callback function and
  // saves the uploaded file. Since this form is already marked as cached
  // (the #cache property is TRUE), the cache is updated automatically and we
  // don't need to call form_set_cache().
  $args = $form['#parameters'];
  $form_id = array_shift($args);
  $form['#post'] = $_POST;
  $form = form_builder($form_id, $form, $form_state);

  // Update the cached form with the new element at the right place in the form.
  if (module_exists('fieldgroup') && ($group_name = _fieldgroup_field_get_group($type_name, $field_name))) {
    if (isset($form['#multigroups']) && isset($form['#multigroups'][$group_name][$field_name])) {
      $form_element = $form[$group_name][$delta][$field_name];
    }
    else {
      $form_element = $form[$group_name][$field_name][$delta];
    }
  }
  else {
    $form_element = $form[$field_name][$delta];
  }

  if (isset($form_element['_weight'])) {
    unset($form_element['_weight']);
  }

  $output = drupal_render($form_element);

  // AHAH is not being nice to us and doesn't know the "other" button (that is,
  // either "Upload" or "Delete") yet. Which in turn causes it not to attach
  // AHAH behaviours after replacing the element. So we need to tell it first.

  // Loop through the JS settings and find the settings needed for our buttons.
  $javascript = drupal_add_js(NULL, NULL);
  $filefield_ahah_settings = array();
  if (isset($javascript['setting'])) {
    foreach ($javascript['setting'] as $settings) {
      if (isset($settings['ahah'])) {
        foreach ($settings['ahah'] as $id => $ahah_settings) {
          if (strpos($id, 'filefield-upload') || strpos($id, 'filefield-remove')) {
            $filefield_ahah_settings[$id] = $ahah_settings;
          }
        }
      }
    }
  }

  // Add the AHAH settings needed for our new buttons.
  if (!empty($filefield_ahah_settings)) {
    $output .= '<script type="text/javascript">jQuery.extend(Drupal.settings.ahah, '. drupal_to_js($filefield_ahah_settings) .');</script>';
  }

  $output = theme('status_messages') . $output;

  // For some reason, file uploads don't like drupal_json() with its manual
  // setting of the text/javascript HTTP header. So use this one instead.
  $GLOBALS['devel_shutdown'] = FALSE;
  print drupal_to_js(array('status' => TRUE, 'data' => $output));
  exit;
}

/**
 * Implementation of hook_file_references().
 */
function filefield_file_references($file) {
  $references = 0;
  foreach (content_fields() as $field) {
    if ($field['type'] != 'filefield') {
      continue;
    }
    $references += field_file_references($file, $field);
  }
  return array('filefield' => $references);
}

/**
 * Implementation of hook_file_delete().
 */
function filefield_file_delete($file) {
  // foreach  field... remove items referencing $file.
}

/**
 * An #upload_validators callback. Check the file matches an allowed extension.
 *
 * If the mimedetect module is available, this will also validate that the
 * content of the file matches the extension. User #1 is included in this check.
 *
 * @param $file
 *   A Drupal file object.
 * @param $extensions
 *   A string with a space separated list of allowed extensions.
 * @return
 *   An array of any errors cause by this file if it failed validation.
 */
function filefield_validate_extensions($file, $extensions) {
  global $user;
  $errors = array();

  if (!empty($extensions)) {
    $regex = '/\.('. ereg_replace(' +', '|', preg_quote($extensions)) .')$/i';
    $matches = array();
    if (preg_match($regex, $file->filename, $matches)) {
      $extension = $matches[1];
      // If the extension validates, check that the mimetype matches.
      if (module_exists('mimedetect')) {
        $type = mimedetect_mime($file);
        if ($type != $file->filemime) {
          $errors[] = t('The file contents (@type) do not match its extension (@extension).', array('@type' => $type, '@extension' => $extension));
        }
      }
    }
    else {
      $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => $extensions));
    }
  }

  return $errors;
}

/**
 * Help text automatically appended to fields that have extension validation.
 */
function filefield_validate_extensions_help($extensions) {
  if (!empty($extensions)) {
    return t('Allowed Extensions: %ext', array('%ext' => $extensions));
  }
  else {
    return '';
  }
}

/**
 * An #upload_validators callback. Check the file size does not exceed a limit.
 *
 * @param $file
 *   A Drupal file object.
 * @param $file_limit
 *   An integer value limiting the maximum file size in bytes.
 * @param $file_limit
 *   An integer value limiting the maximum size in bytes a user can upload on
 *   the entire site.
 * @return
 *   An array of any errors cause by this file if it failed validation.
 */
function filefield_validate_size($file, $file_limit = 0, $user_limit = 0) {
  global $user;

  $errors = array();

  if ($file_limit && $file->filesize > $file_limit) {
    $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($file->filesize), '%maxsize' => format_size($file_limit)));
  }

  // Bypass user limits for uid  = 1.
  if ($user->uid != 1) {
    $total_size = file_space_used($user->uid) + $file->filesize;
    if ($user_limit && $total_size > $user_limit) {
      $errors[] = t('The file is %filesize which would exceed your disk quota of %quota.', array('%filesize' => format_size($file->filesize), '%quota' => format_size($user_limit)));
    }
  }
  return $errors;
}

/**
 * Automatic help text appended to fields that have file size validation.
 */
function filefield_validate_size_help($size) {
  return t('Maximum Filesize: %size', array('%size' => format_size(parse_size($size))));
}

/**
 * An #upload_validators callback. Check an image resolution.
 *
 * @param $file
 *   A Drupal file object.
 * @param $max_size
 *   A string in the format WIDTHxHEIGHT. If the image is larger than this size
 *   the image will be scaled to fit within these dimensions.
 * @param $min_size
 *   A string in the format WIDTHxHEIGHT. If the image is smaller than this size
 *   a validation error will be returned.
 * @return
 *   An array of any errors cause by this file if it failed validation.
 */
function filefield_validate_image_resolution(&$file, $maximum_dimensions = 0, $minimum_dimensions = 0) {
  $errors = array();

  // Check first that the file is an image.
  if ($info = image_get_info($file->filepath)) {
    if ($maximum_dimensions) {
      // Check that it is smaller than the given dimensions.
      list($width, $height) = explode('x', $maximum_dimensions);
      if ($info['width'] > $width || $info['height'] > $height) {
        // Try to resize the image to fit the dimensions.
        if (image_get_toolkit() && image_scale($file->filepath, $file->filepath, $width, $height)) {
          drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $maximum_dimensions)));

          // Clear the cached filesize and refresh the image information.
          clearstatcache();
          $info = image_get_info($file->filepath);
          $file->filesize = $info['file_size'];
        }
        else {
          $errors[] = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $maximum_dimensions));
        }
      }
    }

    if ($minimum_dimensions) {
      // Check that it is larger than the given dimensions.
      list($width, $height) = explode('x', $minimum_dimensions);
      if ($info['width'] < $width || $info['height'] < $height) {
        $errors[] = t('The image is too small; the minimum dimensions are %dimensions pixels.', array('%dimensions' => $minimum_dimensions));
      }
    }
  }

  return $errors;
}

/**
 * Automatic help text appended to fields that have image resolution validation.
 */
function filefield_validate_image_resolution_help($max_size = '0', $min_size = '0') {
  if (!empty($max_size)) {
    if (!empty($min_size)) {
      if ($max_size == $min_size) {
        return t('Images must be exactly @min_size pixels', array('@min_size' => $min_size));
      }
      else {
        return t('Images must be between @min_size pixels and @max_size', array('@max_size' => $max_size, '@min_size' => $min_size));
      }
    }
    else {
      if (image_get_toolkit()) {
        return t('Images larger than @max_size pixels will be scaled', array('@max_size' => $max_size));
      }
      else {
        return t('Images must be smaller than @max_size pixels', array('@max_size' => $max_size));
      }
    }
  }
  if (!empty($min_size)) {
    return t('Images must be larger than @max_size pixels', array('@max_size' => $min_size));
  }
}


/**
 * An #upload_validators callback. Check that a file is an image.
 *
 * This check should allow any image that PHP can identify, including png, jpg,
 * gif, tif, bmp, psd, swc, iff, jpc, jp2, jpx, jb2, xbm, and wbmp.
 *
 * This check should be combined with filefield_validate_extensions() to ensure
 * only web-based images are allowed, however it provides a better check than
 * extension checking alone if the mimedetect module is not available.
 *
 * @param $file
 *   A Drupal file object.
 * @return
 *   An array of any errors cause by this file if it failed validation.
 */
function filefield_validate_is_image(&$file) {
  $errors = array();
  $info = image_get_info($file->filepath);
  if (!$info || empty($info['extension'])) {
    $errors[] = t('The file is not a known image format.');
  }
  return $errors;
}

/**
 * An #upload_validators callback. Add the field to the file object.
 *
 * This validation function adds the field to the file object for later 
 * use in field aware modules implementing hook_file. It's not truly a
 * validation at all, rather a convient way to add properties to the uploaded
 * file.
 */
function filefield_validate_associate_field(&$file, $field) {
  $file->field = $field;
  return array();
}