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