/[drupal]/contributions/modules/filefield/filefield.module
ViewVC logotype

Contents of /contributions/modules/filefield/filefield.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


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

  ViewVC Help
Powered by ViewVC 1.1.2