Issue #1088568 by Désiré: Docomentation mistake on
[project/filefield.git] / filefield.module
1 <?php
2
3 /**
4 * @file
5 * FileField: Defines a CCK file field type.
6 *
7 * Uses content.module to store the fid and field specific metadata,
8 * and Drupal's {files} table to store the actual file data.
9 */
10
11 // FileField API hooks should always be available.
12 require_once dirname(__FILE__) . '/field_file.inc';
13 require_once dirname(__FILE__) . '/filefield_widget.inc';
14
15 /**
16 * Implementation of hook_init().
17 */
18 function filefield_init() {
19 // File hooks and callbacks may be used by any module.
20 drupal_add_css(drupal_get_path('module', 'filefield') .'/filefield.css');
21
22 // Conditional module support.
23 if (module_exists('token')) {
24 module_load_include('inc', 'filefield', 'filefield.token');
25 }
26 }
27
28 /**
29 * Implementation of hook_menu().
30 */
31 function filefield_menu() {
32 $items = array();
33
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(2, 3),
39 'type' => MENU_CALLBACK,
40 );
41 $items['filefield/progress'] = array(
42 'page callback' => 'filefield_progress',
43 'access arguments' => array('access content'),
44 'type' => MENU_CALLBACK,
45 );
46
47 return $items;
48 }
49
50 /**
51 * Implementation of hook_elements().
52 */
53 function filefield_elements() {
54 $elements = array();
55 $elements['filefield_widget'] = array(
56 '#input' => TRUE,
57 '#columns' => array('fid', 'list', 'data'),
58 '#process' => array('filefield_widget_process'),
59 '#value_callback' => 'filefield_widget_value',
60 '#element_validate' => array('filefield_widget_validate'),
61 );
62 return $elements;
63 }
64
65 /**
66 * Implementation of hook_theme().
67 * @todo: autogenerate theme registry entrys for widgets.
68 */
69 function filefield_theme() {
70 return array(
71 'filefield_file' => array(
72 'arguments' => array('file' => NULL),
73 'file' => 'filefield_formatter.inc',
74 ),
75 'filefield_icon' => array(
76 'arguments' => array('file' => NULL),
77 'file' => 'filefield.theme.inc',
78 ),
79 'filefield_widget' => array(
80 'arguments' => array('element' => NULL),
81 'file' => 'filefield_widget.inc',
82 ),
83 'filefield_widget_item' => array(
84 'arguments' => array('element' => NULL),
85 'file' => 'filefield_widget.inc',
86 ),
87 'filefield_widget_preview' => array(
88 'arguments' => array('element' => NULL),
89 'file' => 'filefield_widget.inc',
90 ),
91 'filefield_widget_file' => array(
92 'arguments' => array('element' => NULL),
93 'file' => 'filefield_widget.inc',
94 ),
95
96
97 'filefield_formatter_default' => array(
98 'arguments' => array('element' => NULL),
99 'file' => 'filefield_formatter.inc',
100 ),
101 'filefield_formatter_url_plain' => array(
102 'arguments' => array('element' => NULL),
103 'file' => 'filefield_formatter.inc',
104 ),
105 'filefield_formatter_path_plain' => array(
106 'arguments' => array('element' => NULL),
107 'file' => 'filefield_formatter.inc',
108 ),
109 'filefield_item' => array(
110 'arguments' => array('file' => NULL, 'field' => NULL),
111 'file' => 'filefield_formatter.inc',
112 ),
113 );
114 }
115
116 /**
117 * Implementation of hook_file_download().
118 */
119 function filefield_file_download($filepath) {
120 $filepath = file_create_path($filepath);
121 $result = db_query("SELECT * FROM {files} WHERE filepath = '%s'", $filepath);
122
123 // Ensure case-sensitivity of uploaded file names.
124 while ($file = db_fetch_object($result)) {
125 if (strcmp($file->filepath, $filepath) == 0) {
126 break;
127 }
128 }
129
130 // If the file is not found in the database, we're not responsible for it.
131 if (empty($file)) {
132 return;
133 }
134
135 // See if this is a file on a newly created node, on which the user who
136 // uploaded it will immediately have access.
137 $new_node_file = $file->status == 0 && isset($_SESSION['filefield_access']) && in_array($file->fid, $_SESSION['filefield_access']);
138 if ($new_node_file) {
139 $denied = FALSE;
140 }
141 // Loop through all fields and find if this file is used by FileField.
142 else {
143 // Find out if any file field contains this file, and if so, which field
144 // and node it belongs to. Required for later access checking.
145 $cck_files = array();
146 foreach (content_fields() as $field) {
147 if ($field['type'] == 'filefield' || $field['type'] == 'image') {
148 $db_info = content_database_info($field);
149 $table = $db_info['table'];
150 $fid_column = $db_info['columns']['fid']['column'];
151
152 $columns = array('vid', 'nid');
153 foreach ($db_info['columns'] as $property_name => $column_info) {
154 $columns[] = $column_info['column'] .' AS '. $property_name;
155 }
156 $result = db_query("SELECT ". implode(', ', $columns) ."
157 FROM {". $table ."}
158 WHERE ". $fid_column ." = %d", $file->fid);
159
160 while ($content = db_fetch_array($result)) {
161 $content['field'] = $field;
162 $cck_files[$field['field_name']][$content['vid']] = $content;
163 }
164 }
165 }
166
167 // If no file field item is involved with this file, we don't care about it.
168 if (empty($cck_files)) {
169 return;
170 }
171
172 // So the overall field view permissions are not denied, but if access is
173 // denied for ALL nodes containing the file, deny the download as well.
174 // Node access checks also include checking for 'access content'.
175 $nodes = array();
176 $denied = TRUE;
177 foreach ($cck_files as $field_name => $field_files) {
178 foreach ($field_files as $revision_id => $content) {
179 // Checking separately for each revision is probably not the best idea -
180 // what if 'view revisions' is disabled? So, let's just check for the
181 // current revision of that node.
182 if (isset($nodes[$content['nid']])) {
183 continue; // Don't check the same node twice.
184 }
185 if (($node = node_load($content['nid'])) && (node_access('view', $node) && filefield_view_access($field_name, $node))) {
186 $denied = FALSE;
187 break 2;
188 }
189 $nodes[$content['nid']] = $node;
190 }
191 }
192 }
193
194 if ($denied) {
195 return -1;
196 }
197
198 // Access is granted.
199 $name = mime_header_encode($file->filename);
200 $type = mime_header_encode($file->filemime);
201 // By default, serve images, text, and flash content for display rather than
202 // download. Or if variable 'filefield_inline_types' is set, use its patterns.
203 $inline_types = variable_get('filefield_inline_types', array('^text/', '^image/', 'flash$'));
204 $disposition = 'attachment';
205 foreach ($inline_types as $inline_type) {
206 // Exclamation marks are used as delimiters to avoid escaping slashes.
207 if (preg_match('!' . $inline_type . '!', $file->filemime)) {
208 $disposition = 'inline';
209 }
210 }
211 return array(
212 'Content-Type: ' . $type . '; name="' . $name . '"',
213 'Content-Length: ' . $file->filesize,
214 'Content-Disposition: ' . $disposition . '; filename="' . $name . '"',
215 'Cache-Control: private',
216 );
217 }
218
219 /**
220 * Implementation of hook_views_api().
221 */
222 function filefield_views_api() {
223 return array(
224 'api' => 2.0,
225 'path' => drupal_get_path('module', 'filefield') . '/views',
226 );
227 }
228
229 /**
230 * Implementation of hook_form_alter().
231 *
232 * Set the enctype on forms that need to accept file uploads.
233 */
234 function filefield_form_alter(&$form, $form_state, $form_id) {
235 // Field configuration (for default images).
236 if ($form_id == 'content_field_edit_form' && isset($form['#field']) && $form['#field']['type'] == 'filefield') {
237 $form['#attributes']['enctype'] = 'multipart/form-data';
238 }
239
240 // Node forms.
241 if (preg_match('/_node_form$/', $form_id)) {
242 $form['#attributes']['enctype'] = 'multipart/form-data';
243 }
244 }
245
246 /**
247 * Implementation of CCK's hook_field_info().
248 */
249 function filefield_field_info() {
250 return array(
251 'filefield' => array(
252 'label' => t('File'),
253 'description' => t('Store an arbitrary file.'),
254 ),
255 );
256 }
257
258 /**
259 * Implementation of hook_field_settings().
260 */
261 function filefield_field_settings($op, $field) {
262 $return = array();
263
264 module_load_include('inc', 'filefield', 'filefield_field');
265 $op = str_replace(' ', '_', $op);
266 $function = 'filefield_field_settings_'. $op;
267 if (function_exists($function)) {
268 $result = $function($field);
269 if (isset($result) && is_array($result)) {
270 $return = $result;
271 }
272 }
273
274 return $return;
275
276 }
277
278 /**
279 * Implementation of CCK's hook_field().
280 */
281 function filefield_field($op, $node, $field, &$items, $teaser, $page) {
282 module_load_include('inc', 'filefield', 'filefield_field');
283 $op = str_replace(' ', '_', $op);
284 // add filefield specific handlers...
285 $function = 'filefield_field_'. $op;
286 if (function_exists($function)) {
287 return $function($node, $field, $items, $teaser, $page);
288 }
289 }
290
291 /**
292 * Implementation of CCK's hook_widget_settings().
293 */
294 function filefield_widget_settings($op, $widget) {
295 switch ($op) {
296 case 'form':
297 return filefield_widget_settings_form($widget);
298 case 'save':
299 return filefield_widget_settings_save($widget);
300 }
301 }
302
303 /**
304 * Implementation of hook_widget().
305 */
306 function filefield_widget(&$form, &$form_state, $field, $items, $delta = 0) {
307 // CCK doesn't give a validate callback at the field level...
308 // and FAPI's #require is naive to complex structures...
309 // we validate at the field level ourselves.
310 if (empty($form['#validate']) || !in_array('filefield_node_form_validate', $form['#validate'])) {
311 $form['#validate'][] = 'filefield_node_form_validate';
312 }
313 $form['#attributes']['enctype'] = 'multipart/form-data';
314
315 module_load_include('inc', $field['widget']['module'], $field['widget']['module'] .'_widget');
316
317 $item = array('fid' => 0, 'list' => $field['list_default'], 'data' => array('description' => ''));
318 if (isset($items[$delta])) {
319 $item = array_merge($item, $items[$delta]);
320 }
321 $element = array(
322 '#title' => $field['widget']['label'],
323 '#type' => $field['widget']['type'],
324 '#default_value' => $item,
325 '#upload_validators' => filefield_widget_upload_validators($field),
326 );
327
328 return $element;
329 }
330
331 /**
332 * Get the upload validators for a file field.
333 *
334 * @param $field
335 * A CCK field array.
336 * @return
337 * An array suitable for passing to file_save_upload() or the file field
338 * element's '#upload_validators' property.
339 */
340 function filefield_widget_upload_validators($field) {
341 $max_filesize = parse_size(file_upload_max_size());
342 if (!empty($field['widget']['max_filesize_per_file']) && parse_size($field['widget']['max_filesize_per_file']) < $max_filesize) {
343 $max_filesize = parse_size($field['widget']['max_filesize_per_file']);
344 }
345
346 // Match the default value if no file extensions have been saved at all.
347 if (!isset($field['widget']['file_extensions'])) {
348 $field['widget']['file_extensions'] = 'txt';
349 }
350
351 $validators = array(
352 // associate the field to the file on validation.
353 'filefield_validate_associate_field' => array($field),
354 'filefield_validate_size' => array($max_filesize),
355 // Override core since it excludes uid 1 on the extension check.
356 // Filefield only excuses uid 1 of quota requirements.
357 'filefield_validate_extensions' => array($field['widget']['file_extensions']),
358 );
359 return $validators;
360 }
361
362 /**
363 * Implementation of CCK's hook_content_is_empty().
364 *
365 * The result of this determines whether content.module will save the value of
366 * the field. Note that content module has some interesting behaviors for empty
367 * values. It will always save at least one record for every node revision,
368 * even if the values are all NULL. If it is a multi-value field with an
369 * explicit limit, CCK will save that number of empty entries.
370 */
371 function filefield_content_is_empty($item, $field) {
372 return empty($item['fid']) || (int)$item['fid'] == 0;
373 }
374
375 /**
376 * Implementation of CCK's hook_content_diff_values().
377 */
378 function filefield_content_diff_values($node, $field, $items) {
379 $return = array();
380 foreach ($items as $item) {
381 if (is_array($item) && !empty($item['filepath'])) {
382 $return[] = $item['filepath'];
383 }
384 }
385 return $return;
386 }
387
388 /**
389 * Implementation of CCK's hook_default_value().
390 *
391 * Note this is a widget-level hook, so it does not affect ImageField or other
392 * modules that extend FileField.
393 *
394 * @see content_default_value()
395 */
396 function filefield_default_value(&$form, &$form_state, $field, $delta) {
397 // Reduce the default number of upload fields to one. CCK 2 (but not 3) will
398 // automatically add one more field than necessary. We use the
399 // content_multiple_value_after_build function to determine the version.
400 if (!function_exists('content_multiple_value_after_build') && !isset($form_state['item_count'][$field['field_name']])) {
401 $form_state['item_count'][$field['field_name']] = 0;
402 }
403
404 // The default value is actually handled in hook_widget().
405 // hook_default_value() is only helpful for new nodes, and we need to affect
406 // all widgets, such as when a new field is added via "Add another item".
407 return array();
408 }
409
410 /**
411 * Implementation of CCK's hook_widget_info().
412 */
413 function filefield_widget_info() {
414 return array(
415 'filefield_widget' => array(
416 'label' => t('File Upload'),
417 'field types' => array('filefield'),
418 'multiple values' => CONTENT_HANDLE_CORE,
419 'callbacks' => array('default value' => CONTENT_CALLBACK_CUSTOM),
420 'description' => t('A plain file upload widget.'),
421 'file_extensions' => 'txt',
422 ),
423 );
424 }
425
426 /**
427 * Implementation of CCK's hook_field_formatter_info().
428 */
429 function filefield_field_formatter_info() {
430 return array(
431 'default' => array(
432 'label' => t('Generic files'),
433 'field types' => array('filefield'),
434 'multiple values' => CONTENT_HANDLE_CORE,
435 'description' => t('Displays all kinds of files with an icon and a linked file description.'),
436 ),
437 'path_plain' => array(
438 'label' => t('Path to file'),
439 'field types' => array('filefield'),
440 'description' => t('Displays the file system path to the file.'),
441 ),
442 'url_plain' => array(
443 'label' => t('URL to file'),
444 'field types' => array('filefield'),
445 'description' => t('Displays a full URL to the file.'),
446 ),
447 );
448 }
449
450 /**
451 * Implementation of CCK's hook_content_generate(). Used by generate.module.
452 */
453 function filefield_content_generate($node, $field) {
454 module_load_include('inc', 'filefield', 'filefield.devel');
455
456 if (content_handle('widget', 'multiple values', $field) == CONTENT_HANDLE_MODULE) {
457 return content_devel_multiple('_filefield_content_generate', $node, $field);
458 }
459 else {
460 return _filefield_content_generate($node, $field);
461 }
462 }
463
464 /**
465 * Get a list of possible information stored in a file field "data" column.
466 */
467 function filefield_data_info() {
468 static $columns;
469
470 if (!isset($columns)) {
471 $columns = array();
472 foreach (module_implements('filefield_data_info') as $module) {
473 $function = $module . '_filefield_data_info';
474 $data = (array) $function();
475 foreach ($data as $key => $value) {
476 $data[$key] = $value;
477 $data[$key]['module'] = $module;
478 }
479 $columns = array_merge($columns, $data);
480 }
481 }
482
483 return $columns;
484 }
485
486 /**
487 * Given an array of data options, dispatch the necessary callback function.
488 */
489 function filefield_data_value($key, $value) {
490 $info = filefield_data_info();
491 if (isset($info[$key]['callback'])) {
492 $callback = $info[$key]['callback'];
493 $value = $callback($value);
494 }
495 else {
496 $value = check_plain((string) $value);
497 }
498 return $value;
499 }
500
501 /**
502 * Implementation of hook_filefield_data_info().
503 *
504 * Define a list of values that this module stores in the "data" column of a
505 * file field. The callback function receives the portion of the data column
506 * defined by key and should return a value suitable for printing to the page.
507 */
508 function filefield_filefield_data_info() {
509 return array(
510 'description' => array(
511 'title' => t('Description'),
512 'callback' => 'check_plain',
513 ),
514 );
515 }
516
517 /**
518 * Determine the most appropriate icon for the given file's mimetype.
519 *
520 * @param $file
521 * A file object.
522 * @return
523 * The URL of the icon image file, or FALSE if no icon could be found.
524 */
525 function filefield_icon_url($file) {
526 module_load_include('inc', 'filefield', 'filefield.theme');
527 return _filefield_icon_url($file);
528 }
529
530 /**
531 * Implementation of hook_filefield_icon_sets().
532 *
533 * Define a list of icon sets and directories that contain the icons.
534 */
535 function filefield_filefield_icon_sets() {
536 return array(
537 'default' => drupal_get_path('module', 'filefield') . '/icons',
538 );
539 }
540
541 /**
542 * Access callback for the JavaScript upload and deletion AHAH callbacks.
543 *
544 * The content_permissions module provides nice fine-grained permissions for
545 * us to check, so we can make sure that the user may actually edit the file.
546 */
547 function filefield_edit_access($type_name, $field_name) {
548 if (!content_access('edit', content_fields($field_name, $type_name))) {
549 return FALSE;
550 }
551 // No content permissions to check, so let's fall back to a more general permission.
552 return user_access('access content') || user_access('administer nodes');
553 }
554
555 /**
556 * Access callback that checks if the current user may view the filefield.
557 */
558 function filefield_view_access($field_name, $node = NULL) {
559 if (!content_access('view', content_fields($field_name), NULL, $node)) {
560 return FALSE;
561 }
562 // No content permissions to check, so let's fall back to a more general permission.
563 return user_access('access content') || user_access('administer nodes');
564 }
565
566 /**
567 * Menu callback; Shared AHAH callback for uploads and deletions.
568 *
569 * This rebuilds the form element for a particular field item. As long as the
570 * form processing is properly encapsulated in the widget element the form
571 * should rebuild correctly using FAPI without the need for additional callbacks
572 * or processing.
573 */
574 function filefield_js($type_name, $field_name, $delta) {
575 $field = content_fields($field_name, $type_name);
576
577 // Immediately disable devel shutdown functions so that it doesn't botch our
578 // JSON output.
579 $GLOBALS['devel_shutdown'] = FALSE;
580
581 if (empty($field) || empty($_POST['form_build_id'])) {
582 // Invalid request.
583 drupal_set_message(t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', array('@size' => format_size(file_upload_max_size()))), 'error');
584 print drupal_to_js(array('data' => theme('status_messages')));
585 exit;
586 }
587
588 // Build the new form.
589 $form_state = array('submitted' => FALSE);
590 $form_build_id = $_POST['form_build_id'];
591 $form = form_get_cache($form_build_id, $form_state);
592
593 if (!$form) {
594 // Invalid form_build_id.
595 drupal_set_message(t('An unrecoverable error occurred. This form was missing from the server cache. Try reloading the page and submitting again.'), 'error');
596 print drupal_to_js(array('data' => theme('status_messages')));
597 exit;
598 }
599
600 // Build the form. This calls the file field's #value_callback function and
601 // saves the uploaded file. Since this form is already marked as cached
602 // (the #cache property is TRUE), the cache is updated automatically and we
603 // don't need to call form_set_cache().
604 $args = $form['#parameters'];
605 $form_id = array_shift($args);
606 $form['#post'] = $_POST;
607 $form = form_builder($form_id, $form, $form_state);
608
609 // Update the cached form with the new element at the right place in the form.
610 if (module_exists('fieldgroup') && ($group_name = _fieldgroup_field_get_group($type_name, $field_name))) {
611 if (isset($form['#multigroups']) && isset($form['#multigroups'][$group_name][$field_name])) {
612 $form_element = $form[$group_name][$delta][$field_name];
613 }
614 else {
615 $form_element = $form[$group_name][$field_name][$delta];
616 }
617 }
618
619 if (!isset($form_element)) {
620 $form_element = $form[$field_name][$delta];
621 }
622
623 if (isset($form_element['_weight'])) {
624 unset($form_element['_weight']);
625 }
626
627 $output = drupal_render($form_element);
628
629 // AHAH is not being nice to us and doesn't know the "other" button (that is,
630 // either "Upload" or "Delete") yet. Which in turn causes it not to attach
631 // AHAH behaviours after replacing the element. So we need to tell it first.
632
633 // Loop through the JS settings and find the settings needed for our buttons.
634 $javascript = drupal_add_js(NULL, NULL);
635 $filefield_ahah_settings = array();
636 if (isset($javascript['setting'])) {
637 foreach ($javascript['setting'] as $settings) {
638 if (isset($settings['ahah'])) {
639 foreach ($settings['ahah'] as $id => $ahah_settings) {
640 if (strpos($id, 'filefield-upload') || strpos($id, 'filefield-remove')) {
641 $filefield_ahah_settings[$id] = $ahah_settings;
642 }
643 }
644 }
645 }
646 }
647
648 // Add the AHAH settings needed for our new buttons.
649 if (!empty($filefield_ahah_settings)) {
650 $output .= '<script type="text/javascript">jQuery.extend(Drupal.settings.ahah, '. drupal_to_js($filefield_ahah_settings) .');</script>';
651 }
652
653 $output = theme('status_messages') . $output;
654
655 // For some reason, file uploads don't like drupal_json() with its manual
656 // setting of the text/javascript HTTP header. So use this one instead.
657 print drupal_to_js(array('status' => TRUE, 'data' => $output));
658 exit;
659 }
660
661 /**
662 * Menu callback for upload progress.
663 */
664 function filefield_progress($key) {
665 $progress = array(
666 'message' => t('Starting upload...'),
667 'percentage' => -1,
668 );
669
670 $implementation = filefield_progress_implementation();
671 if ($implementation == 'uploadprogress') {
672 $status = uploadprogress_get_info($key);
673 if (isset($status['bytes_uploaded']) && !empty($status['bytes_total'])) {
674 $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['bytes_uploaded']), '@total' => format_size($status['bytes_total'])));
675 $progress['percentage'] = round(100 * $status['bytes_uploaded'] / $status['bytes_total']);
676 }
677 }
678 elseif ($implementation == 'apc') {
679 $status = apc_fetch('upload_' . $key);
680 if (isset($status['current']) && !empty($status['total'])) {
681 $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['current']), '@total' => format_size($status['total'])));
682 $progress['percentage'] = round(100 * $status['current'] / $status['total']);
683 }
684 }
685
686 drupal_json($progress);
687 }
688
689 /**
690 * Determine which upload progress implementation to use, if any available.
691 */
692 function filefield_progress_implementation() {
693 static $implementation;
694 if (!isset($implementation)) {
695 $implementation = FALSE;
696
697 // We prefer the PECL extension uploadprogress because it supports multiple
698 // simultaneous uploads. APC only supports one at a time.
699 if (extension_loaded('uploadprogress')) {
700 $implementation = 'uploadprogress';
701 }
702 elseif (extension_loaded('apc') && ini_get('apc.rfc1867')) {
703 $implementation = 'apc';
704 }
705 }
706 return $implementation;
707 }
708
709 /**
710 * Implementation of hook_file_references().
711 */
712 function filefield_file_references($file) {
713 $count = filefield_get_file_reference_count($file);
714 return $count ? array('filefield' => $count) : NULL;
715 }
716
717 /**
718 * Implementation of hook_file_delete().
719 */
720 function filefield_file_delete($file) {
721 filefield_delete_file_references($file);
722 }
723
724 /**
725 * An #upload_validators callback. Check the file matches an allowed extension.
726 *
727 * If the mimedetect module is available, this will also validate that the
728 * content of the file matches the extension. User #1 is included in this check.
729 *
730 * @param $file
731 * A Drupal file object.
732 * @param $extensions
733 * A string with a space separated list of allowed extensions.
734 * @return
735 * An array of any errors cause by this file if it failed validation.
736 */
737 function filefield_validate_extensions($file, $extensions) {
738 global $user;
739 $errors = array();
740
741 if (!empty($extensions)) {
742 $regex = '/\.('. ereg_replace(' +', '|', preg_quote($extensions)) .')$/i';
743 $matches = array();
744 if (preg_match($regex, $file->filename, $matches)) {
745 $extension = $matches[1];
746 // If the extension validates, check that the mimetype matches.
747 if (module_exists('mimedetect')) {
748 $type = mimedetect_mime($file);
749 if ($type != $file->filemime) {
750 $errors[] = t('The file contents (@type) do not match its extension (@extension).', array('@type' => $type, '@extension' => $extension));
751 }
752 }
753 }
754 else {
755 $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => $extensions));
756 }
757 }
758
759 return $errors;
760 }
761
762 /**
763 * Help text automatically appended to fields that have extension validation.
764 */
765 function filefield_validate_extensions_help($extensions) {
766 if (!empty($extensions)) {
767 return t('Allowed extensions: %ext', array('%ext' => $extensions));
768 }
769 else {
770 return '';
771 }
772 }
773
774 /**
775 * An #upload_validators callback. Check the file size does not exceed a limit.
776 *
777 * @param $file
778 * A Drupal file object.
779 * @param $file_limit
780 * An integer value limiting the maximum file size in bytes.
781 * @param $file_limit
782 * An integer value limiting the maximum size in bytes a user can upload on
783 * the entire site.
784 * @return
785 * An array of any errors cause by this file if it failed validation.
786 */
787 function filefield_validate_size($file, $file_limit = 0, $user_limit = 0) {
788 global $user;
789
790 $errors = array();
791
792 if ($file_limit && $file->filesize > $file_limit) {
793 $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($file->filesize), '%maxsize' => format_size($file_limit)));
794 }
795
796 // Bypass user limits for uid = 1.
797 if ($user->uid != 1) {
798 $total_size = file_space_used($user->uid) + $file->filesize;
799 if ($user_limit && $total_size > $user_limit) {
800 $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)));
801 }
802 }
803 return $errors;
804 }
805
806 /**
807 * Automatic help text appended to fields that have file size validation.
808 */
809 function filefield_validate_size_help($size) {
810 return t('Maximum file size: %size', array('%size' => format_size(parse_size($size))));
811 }
812
813 /**
814 * An #upload_validators callback. Check an image resolution.
815 *
816 * @param $file
817 * A Drupal file object.
818 * @param $max_size
819 * A string in the format WIDTHxHEIGHT. If the image is larger than this size
820 * the image will be scaled to fit within these dimensions.
821 * @param $min_size
822 * A string in the format WIDTHxHEIGHT. If the image is smaller than this size
823 * a validation error will be returned.
824 * @return
825 * An array of any errors cause by this file if it failed validation.
826 */
827 function filefield_validate_image_resolution(&$file, $maximum_dimensions = 0, $minimum_dimensions = 0) {
828 $errors = array();
829
830 @list($max_width, $max_height) = explode('x', $maximum_dimensions);
831 @list($min_width, $min_height) = explode('x', $minimum_dimensions);
832
833 // Check first that the file is an image.
834 if ($info = image_get_info($file->filepath)) {
835 if ($maximum_dimensions) {
836 $resized = FALSE;
837
838 // Check that it is smaller than the given dimensions.
839 if ($info['width'] > $max_width || $info['height'] > $max_height) {
840 $ratio = min($max_width/$info['width'], $max_height/$info['height']);
841 // Check for exact dimension requirements (scaling allowed).
842 if (strcmp($minimum_dimensions, $maximum_dimensions) == 0 && $info['width']/$max_width != $info['height']/$max_height) {
843 $errors[] = t('The image must be exactly %dimensions pixels.', array('%dimensions' => $maximum_dimensions));
844 }
845 // Check that scaling won't drop the image below the minimum dimensions.
846 elseif ((image_get_toolkit() || module_exists('imageapi')) && (($info['width'] * $ratio < $min_width) || ($info['height'] * $ratio < $min_height))) {
847 $errors[] = t('The image will not fit between the dimensions of %min_dimensions and %max_dimensions pixels.', array('%min_dimensions' => $minimum_dimensions, '%max_dimensions' => $maximum_dimensions));
848 }
849 // Try resizing the image with ImageAPI if available.
850 elseif (module_exists('imageapi') && imageapi_default_toolkit()) {
851 $res = imageapi_image_open($file->filepath);
852 imageapi_image_scale($res, $max_width, $max_height);
853 imageapi_image_close($res, $file->filepath);
854 $resized = TRUE;
855 }
856 // Try to resize the image to fit the dimensions.
857 elseif (image_get_toolkit() && @image_scale($file->filepath, $file->filepath, $max_width, $max_height)) {
858 $resized = TRUE;
859 }
860 else {
861 $errors[] = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $maximum_dimensions));
862 }
863 }
864
865 // Clear the cached filesize and refresh the image information.
866 if ($resized) {
867 drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $maximum_dimensions)));
868 clearstatcache();
869 $file->filesize = filesize($file->filepath);
870 }
871 }
872
873 if ($minimum_dimensions && empty($errors)) {
874 // Check that it is larger than the given dimensions.
875 if ($info['width'] < $min_width || $info['height'] < $min_height) {
876 $errors[] = t('The image is too small; the minimum dimensions are %dimensions pixels.', array('%dimensions' => $minimum_dimensions));
877 }
878 }
879 }
880
881 return $errors;
882 }
883
884 /**
885 * Automatic help text appended to fields that have image resolution validation.
886 */
887 function filefield_validate_image_resolution_help($max_size = '0', $min_size = '0') {
888 if (!empty($max_size)) {
889 if (!empty($min_size)) {
890 if ($max_size == $min_size) {
891 return t('Images must be exactly @min_size pixels', array('@min_size' => $min_size));
892 }
893 else {
894 return t('Images must be between @min_size pixels and @max_size', array('@max_size' => $max_size, '@min_size' => $min_size));
895 }
896 }
897 else {
898 if (image_get_toolkit()) {
899 return t('Images larger than @max_size pixels will be scaled', array('@max_size' => $max_size));
900 }
901 else {
902 return t('Images must be smaller than @max_size pixels', array('@max_size' => $max_size));
903 }
904 }
905 }
906 if (!empty($min_size)) {
907 return t('Images must be larger than @max_size pixels', array('@max_size' => $min_size));
908 }
909 }
910
911
912 /**
913 * An #upload_validators callback. Check that a file is an image.
914 *
915 * This check should allow any image that PHP can identify, including png, jpg,
916 * gif, tif, bmp, psd, swc, iff, jpc, jp2, jpx, jb2, xbm, and wbmp.
917 *
918 * This check should be combined with filefield_validate_extensions() to ensure
919 * only web-based images are allowed, however it provides a better check than
920 * extension checking alone if the mimedetect module is not available.
921 *
922 * @param $file
923 * A Drupal file object.
924 * @return
925 * An array of any errors cause by this file if it failed validation.
926 */
927 function filefield_validate_is_image(&$file) {
928 $errors = array();
929 $info = image_get_info($file->filepath);
930 if (!$info || empty($info['extension'])) {
931 $errors[] = t('The file is not a known image format.');
932 }
933 return $errors;
934 }
935
936 /**
937 * An #upload_validators callback. Add the field to the file object.
938 *
939 * This validation function adds the field to the file object for later
940 * use in field aware modules implementing hook_file. It's not truly a
941 * validation at all, rather a convient way to add properties to the uploaded
942 * file.
943 */
944 function filefield_validate_associate_field(&$file, $field) {
945 $file->field = $field;
946 return array();
947 }
948
949 /*******************************************************************************
950 * Public API functions for FileField.
951 ******************************************************************************/
952
953 /**
954 * Return an array of file fields within a node type or by field name.
955 *
956 * @param $field
957 * Optional. May be either a field array or a field name.
958 * @param $node_type
959 * Optional. The node type to filter the list of fields.
960 */
961 function filefield_get_field_list($node_type = NULL, $field = NULL) {
962 // Build the list of fields to be used for retrieval.
963 if (isset($field)) {
964 if (is_string($field)) {
965 $field = content_fields($field, $node_type);
966 }
967 $fields = array($field['field_name'] => $field);
968 }
969 elseif (isset($node_type)) {
970 $type = content_types($node_type);
971 $fields = $type['fields'];
972 }
973 else {
974 $fields = content_fields();
975 }
976
977 // Filter down the list just to file fields.
978 foreach ($fields as $key => $field) {
979 if ($field['type'] != 'filefield') {
980 unset($fields[$key]);
981 }
982 }
983
984 return $fields;
985 }
986
987 /**
988 * Count the number of times the file is referenced within a field.
989 *
990 * @param $file
991 * A file object.
992 * @param $field
993 * Optional. The CCK field array or field name as a string.
994 * @return
995 * An integer value.
996 */
997 function filefield_get_file_reference_count($file, $field = NULL) {
998 $fields = filefield_get_field_list(NULL, $field);
999 $file = (object) $file;
1000
1001 $references = 0;
1002 foreach ($fields as $field) {
1003 $db_info = content_database_info($field);
1004 $references += db_result(db_query(
1005 'SELECT count('. $db_info['columns']['fid']['column'] .')
1006 FROM {'. $db_info['table'] .'}
1007 WHERE '. $db_info['columns']['fid']['column'] .' = %d', $file->fid
1008 ));
1009
1010 // If a field_name is present in the file object, the file is being deleted
1011 // from this field.
1012 if (isset($file->field_name) && $field['field_name'] == $file->field_name) {
1013 // If deleting the entire node, count how many references to decrement.
1014 if (isset($file->delete_nid)) {
1015 $node_references = db_result(db_query(
1016 'SELECT count('. $db_info['columns']['fid']['column'] .')
1017 FROM {'. $db_info['table'] .'}
1018 WHERE '. $db_info['columns']['fid']['column'] .' = %d AND nid = %d', $file->fid, $file->delete_nid
1019 ));
1020 $references = $references - $node_references;
1021 }
1022 else {
1023 $references = $references - 1;
1024 }
1025 }
1026 }
1027
1028 return $references;
1029 }
1030
1031 /**
1032 * Get a list of node IDs that reference a file.
1033 *
1034 * @param $file
1035 * The file object for which to find references.
1036 * @param $field
1037 * Optional. The CCK field array or field name as a string.
1038 * @return
1039 * An array of IDs grouped by NID: array([nid] => array([vid1], [vid2])).
1040 */
1041 function filefield_get_file_references($file, $field = NULL) {
1042 $fields = filefield_get_field_list(NULL, $field);
1043 $file = (object) $file;
1044
1045 $references = array();
1046 foreach ($fields as $field) {
1047 $db_info = content_database_info($field);
1048 $sql = 'SELECT nid, vid FROM {'. $db_info['table'] .'} WHERE '. $db_info['columns']['fid']['column'] .' = %d';
1049 $result = db_query($sql, $file->fid);
1050 while ($row = db_fetch_object($result)) {
1051 $references[$row->nid][$row->vid] = $row->vid;
1052 }
1053 }
1054
1055 return $references;
1056 }
1057
1058 /**
1059 * Get all FileField files connected to a node ID.
1060 *
1061 * @param $node
1062 * The node object.
1063 * @param $field
1064 * Optional. The CCK field array or field name as a string.
1065 * @return
1066 * An array of all files attached to that field (or all fields).
1067 */
1068 function filefield_get_node_files($node, $field = NULL) {
1069 $fields = filefield_get_field_list($node->type, $field);
1070 $files = array();
1071
1072 // Get the file rows.
1073 foreach ($fields as $field) {
1074 $db_info = content_database_info($field);
1075 $fields = 'f.*';
1076 $fields .= ', c.'. $db_info['columns']['list']['column'] .' AS list';
1077 $fields .= ', c.'. $db_info['columns']['data']['column'] .' AS data';
1078 $sql = 'SELECT '. $fields .' FROM {files} f INNER JOIN {' . $db_info['table'] . '} c ON f.fid = c.' . $db_info['columns']['fid']['column'] . ' AND c.vid = %d';
1079 $result = db_query($sql, $node->vid);
1080 while ($file = db_fetch_array($result)) {
1081 $file['data'] = unserialize($file['data']);
1082 $files[$file['fid']] = $file;
1083 }
1084 }
1085
1086 return $files;
1087 }
1088
1089 /**
1090 * Delete all node references of a file.
1091 *
1092 * @param $file
1093 * The file object for which to find references.
1094 * @param $field
1095 * Optional. The CCK field array or field name as a string.
1096 */
1097 function filefield_delete_file_references($file, $field = NULL) {
1098 $fields = filefield_get_field_list(NULL, $field);
1099 $file = (object) $file;
1100
1101 $references = filefield_get_file_references($file, $field);
1102 foreach ($references as $nid => $node_references) {
1103 // Do not update a node if it is already being deleted directly by the user.
1104 if (isset($file->delete_nid) && $file->delete_nid == $nid) {
1105 continue;
1106 }
1107
1108 foreach ($node_references as $vid) {
1109 // Do not update the node revision if that revision is already being
1110 // saved or deleted directly by the user.
1111 if (isset($file->delete_vid) && $file->delete_vid == $vid) {
1112 continue;
1113 }
1114
1115 $node = node_load(array('vid' => $vid));
1116 foreach ($fields as $field_name => $field) {
1117 if (isset($node->$field_name)) {
1118 foreach ($node->$field_name as $delta => $item) {
1119 if ($item['fid'] == $file->fid) {
1120 unset($node->{$field_name}[$delta]);
1121 }
1122 }
1123 $node->$field_name = array_values(array_filter($node->$field_name));
1124 }
1125 }
1126
1127 // Save the node after removing the file references. This flag prevents
1128 // FileField from attempting to delete the file again.
1129 $node->skip_filefield_delete = TRUE;
1130 node_save($node);
1131 }
1132 }
1133 }