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