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 include_once('field_file.inc');
15 * Implementation of hook_init().
17 function filefield_init() {
18 // File hooks and callbacks may be used by any module.
19 module_load_include('inc', 'filefield', 'filefield_widget');
20 drupal_add_css(drupal_get_path('module', 'filefield') .
'/filefield.css');
22 // Conditional module support.
23 if (module_exists('token')) {
24 module_load_include('inc', 'filefield', 'filefield.token');
29 * Implementation of hook_menu().
31 function filefield_menu() {
34 $items['filefield/ahah/%/%/%'] = array(
35 'page callback' => 'filefield_js',
36 'page arguments' => array(2, 3, 4),
37 'access callback' => 'filefield_edit_access',
38 'access arguments' => array(3),
39 'type' => MENU_CALLBACK
,
45 * Implementation of hook_elements().
46 * @todo: autogenerate element registry entries for widgets.
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'),
56 '#description' => t('Changes made to the attachments are not permanent until you save this post.'),
62 * Implementation of hook_theme().
63 * @todo: autogenerate theme registry entrys for widgets.
65 function filefield_theme() {
67 'filefield_file' => array(
68 'arguments' => array('file' => NULL
),
69 'file' => 'filefield_formatter.inc',
71 'filefield_icon' => array(
72 'arguments' => array('file' => NULL
),
73 'file' => 'filefield.theme.inc',
75 'filefield_widget' => array(
76 'arguments' => array('element' => NULL
),
77 'file' => 'filefield_widget.inc',
79 'filefield_widget_item' => array(
80 'arguments' => array('element' => NULL
),
81 'file' => 'filefield_widget.inc',
83 'filefield_widget_preview' => array(
84 'arguments' => array('element' => NULL
),
85 'file' => 'filefield_widget.inc',
87 'filefield_widget_file' => array(
88 'arguments' => array('element' => NULL
),
89 'file' => 'filefield_widget.inc',
93 'filefield_formatter_default' => array(
94 'arguments' => array('element' => NULL
),
95 'file' => 'filefield_formatter.inc',
97 'filefield_formatter_url_plain' => array(
98 'arguments' => array('element' => NULL
),
99 'file' => 'filefield_formatter.inc',
101 'filefield_formatter_path_plain' => array(
102 'arguments' => array('element' => NULL
),
103 'file' => 'filefield_formatter.inc',
105 'filefield_item' => array(
106 'arguments' => array('file' => NULL
, 'field' => NULL
),
107 'file' => 'filefield_formatter.inc',
109 'filefield_file' => array(
110 'arguments' => array('file' => NULL
),
111 'file' => 'filefield_formatter.inc',
118 * Implementation of hook_file_download(). Yes, *that* hook that causes
119 * any attempt for file upload module interoperability to fail spectacularly.
121 function filefield_file_download($file) {
122 $file = file_create_path($file);
124 $result = db_query("SELECT * FROM {files} WHERE filepath = '%s'", $file);
125 if (!$file = db_fetch_object($result)) {
126 // We don't really care about this file.
130 // Find out if any filefield contains this file, and if so, which field
131 // and node it belongs to. Required for later access checking.
132 $cck_files = array();
133 foreach (content_fields() as
$field) {
134 if ($field['type'] == 'filefield' || $field['type'] == 'image') {
135 $db_info = content_database_info($field);
136 $table = $db_info['table'];
137 $fid_column = $db_info['columns']['fid']['column'];
139 $columns = array('vid', 'nid');
140 foreach ($db_info['columns'] as
$property_name => $column_info) {
141 $columns[] = $column_info['column'] .
' AS '.
$property_name;
143 $result = db_query("SELECT ".
implode(', ', $columns) .
"
145 WHERE ".
$fid_column .
" = %d", $file->fid
);
147 while ($content = db_fetch_array($result)) {
148 $content['field'] = $field;
149 $cck_files[$field['field_name']][$content['vid']] = $content;
153 // If no filefield item is involved with this file, we don't care about it.
154 if (empty($cck_files)) {
158 // If any node includes this file but the user may not view this field,
159 // then deny the download.
160 foreach ($cck_files as
$field_name => $field_files) {
161 if (!filefield_view_access($field_name)) {
166 // So the overall field view permissions are not denied, but if access is
167 // denied for a specific node containing the file, deny the download as well.
168 // It's probably a little too restrictive, but I can't think of a
169 // better way at the moment. Input appreciated.
170 // (And yeah, node access checks also include checking for 'access content'.)
172 foreach ($cck_files as
$field_name => $field_files) {
173 foreach ($field_files as
$revision_id => $content) {
174 // Checking separately for each revision is probably not the best idea -
175 // what if 'view revisions' is disabled? So, let's just check for the
176 // current revision of that node.
177 if (isset($nodes[$content['nid']])) {
178 continue; // don't check the same node twice
180 $node = node_load($content['nid']);
181 if (!node_access('view', $node)) {
182 // You don't have permission to view the node this file is attached to.
185 $nodes[$content['nid']] = $node;
189 // Well I guess you can see this file.
190 $name = mime_header_encode($file->filename
);
191 $type = mime_header_encode($file->filemime
);
192 // Serve images and text inline for the browser to display rather than download.
193 $disposition = ereg('^(text/|image/)', $file->filemime
) ?
'inline' : 'attachment';
195 'Content-Type: '.
$type .
'; name='.
$name,
196 'Content-Length: '.
$file->filesize,
197 'Content-Disposition: '.
$disposition .
'; filename='.
$name,
198 'Cache-Control: private',
203 * Implementation of hook_form_alter().
205 * Set the appropriate attibutes to allow file uploads on the field settings
208 function filefield_form_alter(&$form, $form_state, $form_id) {
209 if ($form_id == 'content_field_edit_form' && isset($form['#field']) && $form['#field']['type'] == 'filefield') {
210 $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 += field_file_references($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;