6 * FileField: Defines a CCK file field type.
8 * Uses content.module to store the fid and field specific metadata,
9 * and Drupal's {files} table to store the actual file data.
12 // FileField API hooks should always be available.
13 include_once
dirname(__FILE__
) .
'/field_file.inc';
16 * Implementation of hook_init().
18 function filefield_init() {
19 // File hooks and callbacks may be used by any module.
20 module_load_include('inc', 'filefield', 'filefield_widget');
21 drupal_add_css(drupal_get_path('module', 'filefield') .
'/filefield.css');
23 // Conditional module support.
24 if (module_exists('token')) {
25 module_load_include('inc', 'filefield', 'filefield.token');
30 * Implementation of hook_menu().
32 function filefield_menu() {
35 $items['filefield/ahah/%/%/%'] = array(
36 'page callback' => 'filefield_js',
37 'page arguments' => array(2, 3, 4),
38 'access callback' => 'filefield_edit_access',
39 'access arguments' => array(3),
40 'type' => MENU_CALLBACK
,
46 * Implementation of hook_elements().
48 function filefield_elements() {
50 $elements['filefield_widget'] = array(
52 '#columns' => array('fid', 'list', 'data'),
53 '#process' => array('filefield_widget_process'),
54 '#value_callback' => 'filefield_widget_value',
55 '#element_validate' => array('filefield_widget_validate'),
61 * Implementation of hook_theme().
62 * @todo: autogenerate theme registry entrys for widgets.
64 function filefield_theme() {
66 'filefield_file' => array(
67 'arguments' => array('file' => NULL
),
68 'file' => 'filefield_formatter.inc',
70 'filefield_icon' => array(
71 'arguments' => array('file' => NULL
),
72 'file' => 'filefield.theme.inc',
74 'filefield_widget' => array(
75 'arguments' => array('element' => NULL
),
76 'file' => 'filefield_widget.inc',
78 'filefield_widget_item' => array(
79 'arguments' => array('element' => NULL
),
80 'file' => 'filefield_widget.inc',
82 'filefield_widget_preview' => array(
83 'arguments' => array('element' => NULL
),
84 'file' => 'filefield_widget.inc',
86 'filefield_widget_file' => array(
87 'arguments' => array('element' => NULL
),
88 'file' => 'filefield_widget.inc',
92 'filefield_formatter_default' => array(
93 'arguments' => array('element' => NULL
),
94 'file' => 'filefield_formatter.inc',
96 'filefield_formatter_url_plain' => array(
97 'arguments' => array('element' => NULL
),
98 'file' => 'filefield_formatter.inc',
100 'filefield_formatter_path_plain' => array(
101 'arguments' => array('element' => NULL
),
102 'file' => 'filefield_formatter.inc',
104 'filefield_item' => array(
105 'arguments' => array('file' => NULL
, 'field' => NULL
),
106 'file' => 'filefield_formatter.inc',
108 'filefield_file' => array(
109 'arguments' => array('file' => NULL
),
110 'file' => 'filefield_formatter.inc',
117 * Implementation of hook_file_download(). Yes, *that* hook that causes
118 * any attempt for file upload module interoperability to fail spectacularly.
120 function filefield_file_download($file) {
121 $file = file_create_path($file);
123 $result = db_query("SELECT * FROM {files} WHERE filepath = '%s'", $file);
124 if (!$file = db_fetch_object($result)) {
125 // We don't really care about this file.
129 // Find out if any filefield contains this file, and if so, which field
130 // and node it belongs to. Required for later access checking.
131 $cck_files = array();
132 foreach (content_fields() as
$field) {
133 if ($field['type'] == 'filefield' || $field['type'] == 'image') {
134 $db_info = content_database_info($field);
135 $table = $db_info['table'];
136 $fid_column = $db_info['columns']['fid']['column'];
138 $columns = array('vid', 'nid');
139 foreach ($db_info['columns'] as
$property_name => $column_info) {
140 $columns[] = $column_info['column'] .
' AS '.
$property_name;
142 $result = db_query("SELECT ".
implode(', ', $columns) .
"
144 WHERE ".
$fid_column .
" = %d", $file->fid
);
146 while ($content = db_fetch_array($result)) {
147 $content['field'] = $field;
148 $cck_files[$field['field_name']][$content['vid']] = $content;
152 // If no filefield item is involved with this file, we don't care about it.
153 if (empty($cck_files)) {
157 // If any node includes this file but the user may not view this field,
158 // then deny the download.
159 foreach ($cck_files as
$field_name => $field_files) {
160 if (!filefield_view_access($field_name)) {
165 // So the overall field view permissions are not denied, but if access is
166 // denied for a specific node containing the file, deny the download as well.
167 // It's probably a little too restrictive, but I can't think of a
168 // better way at the moment. Input appreciated.
169 // (And yeah, node access checks also include checking for 'access content'.)
171 foreach ($cck_files as
$field_name => $field_files) {
172 foreach ($field_files as
$revision_id => $content) {
173 // Checking separately for each revision is probably not the best idea -
174 // what if 'view revisions' is disabled? So, let's just check for the
175 // current revision of that node.
176 if (isset($nodes[$content['nid']])) {
177 continue; // don't check the same node twice
179 $node = node_load($content['nid']);
180 if (!node_access('view', $node)) {
181 // You don't have permission to view the node this file is attached to.
184 $nodes[$content['nid']] = $node;
188 // Well I guess you can see this file.
189 $name = mime_header_encode($file->filename
);
190 $type = mime_header_encode($file->filemime
);
191 // Serve images and text inline for the browser to display rather than download.
192 $disposition = ereg('^(text/|image/)', $file->filemime
) ?
'inline' : 'attachment';
194 'Content-Type: '.
$type .
'; name='.
$name,
195 'Content-Length: '.
$file->filesize,
196 'Content-Disposition: '.
$disposition .
'; filename='.
$name,
197 'Cache-Control: private',
202 * Implementation of hook_form_alter().
204 * Set the enctype on forms that need to accept file uploads.
206 function filefield_form_alter(&$form, $form_state, $form_id) {
207 // Field configuration (for default images).
208 if ($form_id == 'content_field_edit_form' && isset($form['#field']) && $form['#field']['type'] == 'filefield') {
209 $form['#attributes']['enctype'] = 'multipart/form-data';
213 if (preg_match('/_node_form$/', $form_id)) {
214 $form['#attributes']['enctype'] = 'multipart/form-data';
219 * Implementation of CCK's hook_field_info().
221 function filefield_field_info() {
223 'filefield' => array(
225 'description' => t('Store an arbitrary file.'),
231 * Implementation of hook_field_settings().
233 function filefield_field_settings($op, $field) {
236 module_load_include('inc', 'filefield', 'filefield_field');
237 $op = str_replace(' ', '_', $op);
238 // add filefield specific handlers...
239 $function = 'filefield_field_settings_'.
$op;
240 if (function_exists($function)) {
241 $result = $function($field);
242 if (isset($result) && is_array($result)) {
247 // dynamically load widgets file and callbacks for other fields utilizing
248 // filefield's hook_field_settings implementation.
249 module_load_include('inc', $field['module'], $field['type'] .
'_field');
250 $function = $field['module'] .
'_'.
$field['type'] .
'_field_settings_'.
$op;
251 if (function_exists($function)) {
252 $result = $function($field);
253 if (isset($result) && is_array($result)) {
254 $return = array_merge($return, $result);
263 * Implementtation of CCK's hook_field().
265 function filefield_field($op, $node, $field, &$items, $teaser, $page) {
266 module_load_include('inc', 'filefield', 'filefield_field');
267 $op = str_replace(' ', '_', $op);
268 // add filefield specific handlers...
269 $function = 'filefield_field_'.
$op;
270 if (function_exists($function)) {
271 return $function($node, $field, $items, $teaser, $page);
276 * Implementation of CCK's hook_widget_settings().
278 function filefield_widget_settings($op, $widget) {
281 return filefield_widget_settings_form($widget);
283 return filefield_widget_settings_save($widget);
288 * Implementation of hook_widget().
290 function filefield_widget(&$form, &$form_state, $field, $items, $delta = 0) {
291 // CCK doesn't give a validate callback at the field level...
292 // and FAPI's #require is naieve to complex structures...
293 // we validate at the field level ourselves.
294 if (empty($form['#validate']) || !in_array('filefield_node_form_validate', $form['#validate'])) {
295 $form['#validate'][] = 'filefield_node_form_validate';
297 if (empty($form['#submit']) || !in_array('filefield_node_form_submit', $form['#submit'])) {
298 $form['#submit'][] = 'filefield_node_form_submit';
300 $form['#attributes'] = array('enctype' => 'multipart/form-data');
302 module_load_include('inc', 'filefield', 'field_widget');
303 module_load_include('inc', $field['widget']['module'], $field['widget']['module'] .
'_widget');
305 $item = array('fid' => 0, 'list' => $field['list_default'], 'data' => array('description' => ''));
306 if (isset($items[$delta])) {
307 $item = array_merge($item, $items[$delta]);
310 '#title' => $field['widget']['label'],
311 '#type' => $field['widget']['type'],
312 '#default_value' => $item,
313 '#upload_validators' => filefield_widget_upload_validators($field),
320 * Get the upload validators for a file field.
325 * An array suitable for passing to file_save_upload() or the file field
326 * element's '#upload_validators' property.
328 function filefield_widget_upload_validators($field) {
329 $max_filesize = parse_size(file_upload_max_size());
330 if (!empty($field['widget']['max_filesize_per_file']) && parse_size($field['widget']['max_filesize_per_file']) < $max_filesize) {
331 $max_filesize = parse_size($field['widget']['max_filesize_per_file']);
335 // associate the field to the file on validation.
336 'filefield_validate_associate_field' => array($field),
337 'filefield_validate_size' => array($max_filesize),
338 // Override core since it excludes uid 1 on the extension check.
339 // Filefield only excuses uid 1 of quota requirements.
340 'filefield_validate_extensions' => array($field['widget']['file_extensions']),
346 * Implementation of CCK's hook_content_is_empty().
348 * The result of this determines whether content.module will save the value of
349 * the field. Note that content module has some interesting behaviors for empty
350 * values. It will always save at least one record for every node revision,
351 * even if the values are all NULL. If it is a multi-value field with an
352 * explicit limit, CCK will save that number of empty entries.
354 function filefield_content_is_empty($item, $field) {
355 return empty($item['fid']) || (int)$item['fid'] == 0;
359 * Implementation of CCK's hook_widget_info().
361 function filefield_widget_info() {
363 'filefield_widget' => array(
364 'label' => t('File Upload'),
365 'field types' => array('filefield'),
366 'multiple values' => CONTENT_HANDLE_CORE
,
367 'callbacks' => array('default value' => CONTENT_CALLBACK_CUSTOM
),
368 'description' => t('A plain file upload widget.'),
374 * Implementation of CCK's hook_field_formatter_info().
376 function filefield_field_formatter_info() {
379 'label' => t('Generic files'),
380 'field types' => array('filefield'),
381 'multiple values' => CONTENT_HANDLE_CORE
,
382 'description' => t('Displays all kinds of files with an icon and a linked file description.'),
384 'path_plain' => array(
385 'label' => t('Path to file'),
386 'field types' => array('filefield'),
387 'description' => t('Displays the file system path to the file.'),
389 'url_plain' => array(
390 'label' => t('URL to file'),
391 'field types' => array('filefield'),
392 'description' => t('Displays a full URL to the file.'),
398 * Determine the most appropriate icon for the given file's mimetype.
403 * The URL of the icon image file, or FALSE if no icon could be found.
405 function filefield_icon_url($file) {
406 include_once(drupal_get_path('module', 'filefield') .
'/filefield.theme.inc');
407 return _filefield_icon_url($file);
411 * Access callback for the JavaScript upload and deletion AHAH callbacks.
413 * The content_permissions module provides nice fine-grained permissions for
414 * us to check, so we can make sure that the user may actually edit the file.
416 function filefield_edit_access($field_name) {
417 if (module_exists('content_permissions')) {
418 return user_access('edit '.
$field_name);
420 // No content permissions to check, so let's fall back to a more general permission.
421 return user_access('access content');
425 * Access callback that checks if the current user may view the filefield.
427 function filefield_view_access($field_name) {
428 if (module_exists('content_permissions')) {
429 return user_access('view '.
$field_name);
431 // No content permissions to check, so let's fall back to a more general permission.
432 return user_access('access content');
436 * Menu callback; Shared AHAH callback for uploads and deletions.
438 * This rebuilds the form element for a particular field item. As long as the
439 * form processing is properly encapsulated in the widget element the form
440 * should rebuild correctly using FAPI without the need for additional callbacks
443 function filefield_js($type_name, $field_name, $delta) {
444 $field = content_fields($field_name, $type_name);
446 if (empty($field) || empty($_POST['form_build_id'])) {
448 print drupal_to_js(array('data' => ''));
452 // Build the new form.
453 $form_state = array('submitted' => FALSE
);
454 $form_build_id = $_POST['form_build_id'];
455 $form = form_get_cache($form_build_id, $form_state);
458 // Invalid form_build_id.
459 print drupal_to_js(array('data' => ''));
463 // Build the form. This calls the file field's #value_callback function and
464 // saves the uploaded file. Since this form is already marked as cached
465 // (the #cache property is TRUE), the cache is updated automatically and we
466 // don't need to call form_set_cache().
467 $args = $form['#parameters'];
468 $form_id = array_shift($args);
469 $form['#post'] = $_POST;
470 $form = form_builder($form_id, $form, $form_state);
472 // Update the cached form with the new element at the right place in the form.
473 if (module_exists('fieldgroup') && ($group_name = _fieldgroup_field_get_group($type_name, $field_name))) {
474 if (isset($form['#multigroups']) && isset($form['#multigroups'][$group_name][$field_name])) {
475 $form_element = $form[$group_name][$delta][$field_name];
478 $form_element = $form[$group_name][$field_name][$delta];
482 $form_element = $form[$field_name][$delta];
485 if (isset($form_element['_weight'])) {
486 unset($form_element['_weight']);
489 $output = drupal_render($form_element);
491 // AHAH is not being nice to us and doesn't know the "other" button (that is,
492 // either "Upload" or "Delete") yet. Which in turn causes it not to attach
493 // AHAH behaviours after replacing the element. So we need to tell it first.
495 // Loop through the JS settings and find the settings needed for our buttons.
496 $javascript = drupal_add_js(NULL
, NULL
);
497 $filefield_ahah_settings = array();
498 if (isset($javascript['setting'])) {
499 foreach ($javascript['setting'] as
$settings) {
500 if (isset($settings['ahah'])) {
501 foreach ($settings['ahah'] as
$id => $ahah_settings) {
502 if (strpos($id, 'filefield-upload') || strpos($id, 'filefield-remove')) {
503 $filefield_ahah_settings[$id] = $ahah_settings;
510 // Add the AHAH settings needed for our new buttons.
511 if (!empty($filefield_ahah_settings)) {
512 $output .
= '<script type="text/javascript">jQuery.extend(Drupal.settings.ahah, '.
drupal_to_js($filefield_ahah_settings) .
');</script>';
515 $output = theme('status_messages') .
$output;
517 // For some reason, file uploads don't like drupal_json() with its manual
518 // setting of the text/javascript HTTP header. So use this one instead.
519 $GLOBALS['devel_shutdown'] = FALSE
;
520 print drupal_to_js(array('status' => TRUE
, 'data' => $output));
525 * Implementation of hook_file_references().
527 function filefield_file_references($file) {
529 foreach (content_fields() as
$field) {
530 if ($field['type'] != 'filefield') {
533 $references += filefield_get_file_reference_count($file, $field);
535 return array('filefield' => $references);
539 * Implementation of hook_file_delete().
541 function filefield_file_delete($file) {
542 // foreach field... remove items referencing $file.
546 * An #upload_validators callback. Check the file matches an allowed extension.
548 * If the mimedetect module is available, this will also validate that the
549 * content of the file matches the extension. User #1 is included in this check.
552 * A Drupal file object.
554 * A string with a space separated list of allowed extensions.
556 * An array of any errors cause by this file if it failed validation.
558 function filefield_validate_extensions($file, $extensions) {
562 if (!empty($extensions)) {
563 $regex = '/\.('.
ereg_replace(' +', '|', preg_quote($extensions)) .
')$/i';
565 if (preg_match($regex, $file->filename
, $matches)) {
566 $extension = $matches[1];
567 // If the extension validates, check that the mimetype matches.
568 if (module_exists('mimedetect')) {
569 $type = mimedetect_mime($file);
570 if ($type != $file->filemime
) {
571 $errors[] = t('The file contents (@type) do not match its extension (@extension).', array('@type' => $type, '@extension' => $extension));
576 $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => $extensions));
584 * Help text automatically appended to fields that have extension validation.
586 function filefield_validate_extensions_help($extensions) {
587 if (!empty($extensions)) {
588 return t('Allowed Extensions: %ext', array('%ext' => $extensions));
596 * An #upload_validators callback. Check the file size does not exceed a limit.
599 * A Drupal file object.
601 * An integer value limiting the maximum file size in bytes.
603 * An integer value limiting the maximum size in bytes a user can upload on
606 * An array of any errors cause by this file if it failed validation.
608 function filefield_validate_size($file, $file_limit = 0, $user_limit = 0) {
613 if ($file_limit && $file->filesize > $file_limit) {
614 $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($file->filesize), '%maxsize' => format_size($file_limit)));
617 // Bypass user limits for uid = 1.
618 if ($user->uid
!= 1) {
619 $total_size = file_space_used($user->uid
) + $file->filesize;
620 if ($user_limit && $total_size > $user_limit) {
621 $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)));
628 * Automatic help text appended to fields that have file size validation.
630 function filefield_validate_size_help($size) {
631 return t('Maximum Filesize: %size', array('%size' => format_size(parse_size($size))));
635 * An #upload_validators callback. Check an image resolution.
638 * A Drupal file object.
640 * A string in the format WIDTHxHEIGHT. If the image is larger than this size
641 * the image will be scaled to fit within these dimensions.
643 * A string in the format WIDTHxHEIGHT. If the image is smaller than this size
644 * a validation error will be returned.
646 * An array of any errors cause by this file if it failed validation.
648 function filefield_validate_image_resolution(&$file, $maximum_dimensions = 0, $minimum_dimensions = 0) {
651 // Check first that the file is an image.
652 if ($info = image_get_info($file->filepath
)) {
653 if ($maximum_dimensions) {
654 // Check that it is smaller than the given dimensions.
655 list($width, $height) = explode('x', $maximum_dimensions);
656 if ($info['width'] > $width || $info['height'] > $height) {
657 // Try to resize the image to fit the dimensions.
658 if (image_get_toolkit() && image_scale($file->filepath
, $file->filepath
, $width, $height)) {
659 drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $maximum_dimensions)));
661 // Clear the cached filesize and refresh the image information.
663 $info = image_get_info($file->filepath
);
664 $file->filesize = $info['file_size'];
667 $errors[] = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $maximum_dimensions));
672 if ($minimum_dimensions) {
673 // Check that it is larger than the given dimensions.
674 list($width, $height) = explode('x', $minimum_dimensions);
675 if ($info['width'] < $width || $info['height'] < $height) {
676 $errors[] = t('The image is too small; the minimum dimensions are %dimensions pixels.', array('%dimensions' => $minimum_dimensions));
685 * Automatic help text appended to fields that have image resolution validation.
687 function filefield_validate_image_resolution_help($max_size = '0', $min_size = '0') {
688 if (!empty($max_size)) {
689 if (!empty($min_size)) {
690 if ($max_size == $min_size) {
691 return t('Images must be exactly @min_size pixels', array('@min_size' => $min_size));
694 return t('Images must be between @min_size pixels and @max_size', array('@max_size' => $max_size, '@min_size' => $min_size));
698 if (image_get_toolkit()) {
699 return t('Images larger than @max_size pixels will be scaled', array('@max_size' => $max_size));
702 return t('Images must be smaller than @max_size pixels', array('@max_size' => $max_size));
706 if (!empty($min_size)) {
707 return t('Images must be larger than @max_size pixels', array('@max_size' => $min_size));
713 * An #upload_validators callback. Check that a file is an image.
715 * This check should allow any image that PHP can identify, including png, jpg,
716 * gif, tif, bmp, psd, swc, iff, jpc, jp2, jpx, jb2, xbm, and wbmp.
718 * This check should be combined with filefield_validate_extensions() to ensure
719 * only web-based images are allowed, however it provides a better check than
720 * extension checking alone if the mimedetect module is not available.
723 * A Drupal file object.
725 * An array of any errors cause by this file if it failed validation.
727 function filefield_validate_is_image(&$file) {
729 $info = image_get_info($file->filepath
);
730 if (!$info || empty($info['extension'])) {
731 $errors[] = t('The file is not a known image format.');
737 * An #upload_validators callback. Add the field to the file object.
739 * This validation function adds the field to the file object for later
740 * use in field aware modules implementing hook_file. It's not truly a
741 * validation at all, rather a convient way to add properties to the uploaded
744 function filefield_validate_associate_field(&$file, $field) {
745 $file->field
= $field;
749 /*******************************************************************************
750 * Public API functions for FileField.
751 ******************************************************************************/
754 * Count the number of times the file is referenced within a field.
759 * The CCK field array.
763 function filefield_get_file_reference_count($file, $field) {
764 $db_info = content_database_info($field);
765 $references = db_result(db_query(
766 'SELECT count('.
$db_info['columns']['fid']['column'] .
')
767 FROM {'.
$db_info['table'] .
'}
768 WHERE '.
$db_info['columns']['fid']['column'] .
' = %d', $file->fid
771 // If a field_name is present in the file object, the file is being deleted
773 if (isset($file->field_name
) && $field['field_name'] == $file->field_name
) {
774 // If deleting the entire node, count how many references to decrement.
775 if (isset($file->delete_nid
)) {
776 $node_references = db_result(db_query(
777 'SELECT count('.
$db_info['columns']['fid']['column'] .
')
778 FROM {'.
$db_info['table'] .
'}
779 WHERE '.
$db_info['columns']['fid']['column'] .
' = %d AND nid = %d', $file->fid
, $file->delete_nid
781 $references = $references - $node_references;
784 $references = $references - 1;