| [ Index ] |
PHP Cross Reference of Drupal 6 (gatewave) |
[Summary view] [Print] [Text view]
1 <?php 2 // $Id: filefield_widget.inc,v 1.105 2010/12/08 21:57:49 quicksketch Exp $ 3 4 /** 5 * @file 6 * This file contains CCK widget related functionality. 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 /** 13 * Implementation of CCK's hook_widget_settings($op == 'form'). 14 */ 15 function filefield_widget_settings_form($widget) { 16 $form = array(); 17 18 // Convert the extensions list to be a human-friendly comma-separated list. 19 $extensions = is_string($widget['file_extensions']) ? $widget['file_extensions'] : 'txt'; 20 $form['file_extensions'] = array( 21 '#type' => 'textfield', 22 '#title' => t('Permitted upload file extensions'), 23 '#default_value' => $extensions, 24 '#size' => 64, 25 '#maxlength' => 512, 26 '#description' => t('Extensions a user can upload to this field. Separate extensions with a space and do not include the leading dot. Leaving this blank will allow users to upload a file with any extension.'), 27 '#element_validate' => array('_filefield_widget_settings_extensions_validate'), 28 '#pre_render' => array('_filefield_widget_settings_extensions_value'), 29 '#weight' => 1, 30 ); 31 32 $form['progress_indicator'] = array( 33 '#type' => 'radios', 34 '#title' => t('Progress indicator'), 35 '#options' => array( 36 'bar' => t('Bar with progress meter'), 37 'throbber' => t('Throbber'), 38 ), 39 '#default_value' => empty($widget['progress_indicator']) ? 'bar' : $widget['progress_indicator'], 40 '#description' => t('Your server supports upload progress capabilities. The "throbber" display does not indicate progress but takes up less room on the form, you may want to use it if you\'ll only be uploading small files or if experiencing problems with the progress bar.'), 41 '#weight' => 5, 42 '#access' => filefield_progress_implementation(), 43 ); 44 45 $form['path_settings'] = array( 46 '#type' => 'fieldset', 47 '#title' => t('Path settings'), 48 '#collapsible' => TRUE, 49 '#collapsed' => TRUE, 50 '#weight' => 6, 51 ); 52 $form['path_settings']['file_path'] = array( 53 '#type' => 'textfield', 54 '#title' => t('File path'), 55 '#default_value' => is_string($widget['file_path']) ? $widget['file_path'] : '', 56 '#description' => t('Optional subdirectory within the "%directory" directory where files will be stored. Do not include preceding or trailing slashes.', array('%directory' => variable_get('file_directory_path', 'files') . '/')), 57 '#element_validate' => array('_filefield_widget_settings_file_path_validate'), 58 '#suffix' => theme('token_help', 'user'), 59 ); 60 61 $form['max_filesize'] = array( 62 '#type' => 'fieldset', 63 '#title' => t('File size restrictions'), 64 '#description' => t('Limits for the size of files that a user can upload. Note that these settings only apply to newly uploaded files, whereas existing files are not affected.'), 65 '#weight' => 6, 66 '#collapsible' => TRUE, 67 '#collapsed' => TRUE, 68 ); 69 $form['max_filesize']['max_filesize_per_file'] = array( 70 '#type' => 'textfield', 71 '#title' => t('Maximum upload size per file'), 72 '#default_value' => is_string($widget['max_filesize_per_file']) 73 ? $widget['max_filesize_per_file'] 74 : '', 75 '#description' => t('Specify the size limit that applies to each file separately. Enter a value like "512" (bytes), "80K" (kilobytes) or "50M" (megabytes) in order to restrict the allowed file size. If you leave this empty the file sizes will be limited only by PHP\'s maximum post and file upload sizes (current limit <strong>%limit</strong>).', array('%limit' => format_size(file_upload_max_size()))), 76 '#element_validate' => array('_filefield_widget_settings_max_filesize_per_file_validate'), 77 ); 78 $form['max_filesize']['max_filesize_per_node'] = array( 79 '#type' => 'textfield', 80 '#title' => t('Maximum upload size per node'), 81 '#default_value' => is_string($widget['max_filesize_per_node']) 82 ? $widget['max_filesize_per_node'] 83 : '', 84 '#description' => t('Specify the total size limit for all files in field on a given node. Enter a value like "512" (bytes), "80K" (kilobytes) or "50M" (megabytes) in order to restrict the total size of a node. Leave this empty if there should be no size restriction.'), 85 '#element_validate' => array('_filefield_widget_settings_max_filesize_per_node_validate'), 86 ); 87 88 return $form; 89 } 90 91 /** 92 * Implementation of CCK's hook_widget_settings($op == 'save'). 93 */ 94 function filefield_widget_settings_save($widget) { 95 return array('file_extensions', 'file_path', 'progress_indicator', 'max_filesize_per_file', 'max_filesize_per_node'); 96 } 97 98 /** 99 * A FAPI #pre_render() function to set a cosmetic default value for extensions. 100 */ 101 function _filefield_widget_settings_extensions_value($element) { 102 $element['#value'] = implode(', ', array_filter(explode(' ', str_replace(',', ' ', $element['#value'])))); 103 return $element; 104 } 105 106 /** 107 * A FAPI #element_validate callback to strip commas from extension lists. 108 */ 109 function _filefield_widget_settings_extensions_validate($element, &$form_state) { 110 // Remove commas and leading dots from file extensions. 111 $value = str_replace(',', ' ', $element['#value']); 112 $value = str_replace(' .', ' ', $value); 113 $value = array_filter(explode(' ', $value)); 114 $value = implode(' ', $value); 115 form_set_value($element, $value, $form_state); 116 } 117 118 function _filefield_widget_settings_file_path_validate($element, &$form_state) { 119 // Strip slashes from the beginning and end of $widget['file_path'] 120 $form_state['values']['file_path'] = trim($form_state['values']['file_path'], '\\/'); 121 122 // Do not allow the file path to be the same as the file_directory_path(). 123 // This causes all sorts of problems with things like file_create_url(). 124 if (strpos($form_state['values']['file_path'], file_directory_path()) === 0) { 125 form_error($element, t('The file path (@file_path) cannot start with the system files directory (@files_directory), as this may cause conflicts when building file URLs.', array('@file_path' => $form_state['values']['file_path'], '@files_directory' => file_directory_path()))); 126 } 127 } 128 129 function _filefield_widget_settings_max_filesize_per_file_validate($element, &$form_state) { 130 if (empty($form_state['values']['max_filesize_per_file'])) { 131 return; // Empty means no size restrictions, so don't throw an error. 132 } 133 elseif (!is_numeric(parse_size($form_state['values']['max_filesize_per_file']))) { 134 form_error($element, t('The "@field" option must contain a valid value. You can either leave the text field empty or enter a string like "512" (bytes), "80K" (kilobytes) or "50M" (megabytes).', array('@field' => t('Maximum upload size per file')))); 135 } 136 } 137 138 function _filefield_widget_settings_max_filesize_per_node_validate($element, &$form_state) { 139 if (empty($form_state['values']['max_filesize_per_node'])) { 140 return; // Empty means no size restrictions, so don't throw an error. 141 } 142 elseif (!is_numeric(parse_size($form_state['values']['max_filesize_per_node']))) { 143 form_error($element, t('The "@field" option must contain a valid value. You can either leave the text field empty or enter a string like "512" (bytes), "80K" (kilobytes) or "50M" (megabytes).', array('@field' => t('Maximum upload size per node')))); 144 } 145 } 146 147 /** 148 * Determine the widget's files directory 149 * 150 * @param $field 151 * A CCK field array. 152 * @param $account 153 * The user account object to calculate the file path for. 154 * @return 155 * The files directory path, with any tokens replaced. 156 */ 157 function filefield_widget_file_path($field, $account = NULL) { 158 $account = isset($account) ? $account : $GLOBALS['user']; 159 $dest = $field['widget']['file_path']; 160 // Replace user level tokens. 161 // Node level tokens require a lot of complexity like temporary storage 162 // locations when values don't exist. See the filefield_paths module. 163 if (module_exists('token')) { 164 $dest = token_replace($dest, 'user', $account); 165 } 166 // Replace nasty characters in the path if possible. 167 if (module_exists('transliteration')) { 168 module_load_include('inc', 'transliteration'); 169 $dest_array = array_filter(explode('/', $dest)); 170 foreach ($dest_array as $key => $directory) { 171 $dest_array[$key] = transliteration_clean_filename($directory); 172 } 173 $dest = implode('/', $dest_array); 174 } 175 176 return file_directory_path() .'/'. $dest; 177 } 178 179 /** 180 * Given a FAPI element, save any files that may have been uploaded into it. 181 * 182 * This function should only be called during validate, submit, or 183 * value_callback functions. 184 * 185 * @param $element 186 * The FAPI element whose values are being saved. 187 */ 188 function filefield_save_upload($element) { 189 $upload_name = implode('_', $element['#array_parents']); 190 $field = content_fields($element['#field_name'], $element['#type_name']); 191 192 if (empty($_FILES['files']['name'][$upload_name])) { 193 return 0; 194 } 195 196 $dest = filefield_widget_file_path($field); 197 if (!field_file_check_directory($dest, FILE_CREATE_DIRECTORY)) { 198 watchdog('filefield', 'The upload directory %directory for the file field %field (content type %type) could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.', array('%directory' => $dest, '%field' => $element['#field_name'], '%type' => $element['#type_name'])); 199 form_set_error($upload_name, t('The file could not be uploaded.')); 200 return 0; 201 } 202 203 if (!$file = field_file_save_upload($upload_name, $element['#upload_validators'], $dest)) { 204 watchdog('filefield', 'The file upload failed. %upload', array('%upload' => $upload_name)); 205 form_set_error($upload_name, t('The file in the @field field was unable to be uploaded.', array('@field' => $element['#title']))); 206 return 0; 207 } 208 return $file['fid']; 209 } 210 211 /** 212 * The #value_callback for the filefield_widget type element. 213 */ 214 function filefield_widget_value($element, $edit = FALSE) { 215 if (!$edit) { 216 $file = field_file_load($element['#default_value']['fid']); 217 $item = $element['#default_value']; 218 } 219 else { 220 $item = $edit; 221 $field = content_fields($element['#field_name'], $element['#type_name']); 222 223 // Uploads take priority over value of fid text field. 224 if ($fid = filefield_save_upload($element)) { 225 $item['fid'] = $fid; 226 } 227 // Check for #filefield_value_callback values. 228 // Because FAPI does not allow multiple #value_callback values like it does 229 // for #element_validate and #process, this fills the missing functionality 230 // to allow FileField to be extended purely through FAPI. 231 elseif (isset($element['#filefield_value_callback'])) { 232 foreach ($element['#filefield_value_callback'] as $callback) { 233 $callback($element, $item); 234 } 235 } 236 237 // Load file if the FID has changed so that it can be saved by CCK. 238 $file = field_file_load($item['fid']); 239 240 // If the file entry doesn't exist, don't save anything. 241 if (empty($file)) { 242 $item = array(); 243 } 244 245 // Checkboxes loose their value when empty. 246 // If the list field is present make sure its unchecked value is saved. 247 if (!empty($field['list_field']) && empty($edit['list'])) { 248 $item['list'] = 0; 249 } 250 } 251 // Merge file and item data so it is available to all widgets. 252 if (isset($item['data']) && isset($file['data'])) { 253 $file['data'] = array_merge($item['data'], $file['data']); 254 } 255 $item = array_merge($item, $file); 256 257 return $item; 258 } 259 260 /** 261 * An element #process callback for the filefield_widget field type. 262 * 263 * Expands the filefield_widget type to include the upload field, upload and 264 * remove buttons, and the description field. 265 */ 266 function filefield_widget_process($element, $edit, &$form_state, $form) { 267 static $settings_added; 268 269 $item = $element['#value']; 270 $field_name = $element['#field_name']; 271 $delta = $element['#delta']; 272 $element['#theme'] = 'filefield_widget_item'; 273 274 $field = $form['#field_info'][$field_name]; 275 276 // The widget is being presented, so apply the JavaScript. 277 drupal_add_js(drupal_get_path('module', 'filefield') .'/filefield.js'); 278 if (!isset($settings_added[$field_name]) && isset($element['#upload_validators']['filefield_validate_extensions'])) { 279 $settings_added[$field_name] = TRUE; 280 $settings = array( 281 'filefield' => array( 282 $field_name => $element['#upload_validators']['filefield_validate_extensions'][0], 283 ), 284 ); 285 drupal_add_js($settings, 'setting'); 286 } 287 288 // Title is not necessary for each individual field. 289 if ($field['multiple'] > 0) { 290 unset($element['#title']); 291 } 292 293 // Set up the buttons first since we need to check if they were clicked. 294 $element['filefield_upload'] = array( 295 '#type' => 'submit', 296 '#value' => t('Upload'), 297 '#submit' => array('node_form_submit_build_node'), 298 '#ahah' => array( // with JavaScript 299 'path' => 'filefield/ahah/'. $element['#type_name'] .'/'. $element['#field_name'] .'/'. $element['#delta'], 300 'wrapper' => $element['#id'] .'-ahah-wrapper', 301 'method' => 'replace', 302 'effect' => 'fade', 303 ), 304 '#field_name' => $element['#field_name'], 305 '#delta' => $element['#delta'], 306 '#type_name' => $element['#type_name'], 307 '#upload_validators' => $element['#upload_validators'], 308 '#weight' => 100, 309 '#post' => $element['#post'], 310 ); 311 $element['filefield_remove'] = array( 312 // With default CCK edit forms, $element['#parents'] is array($element['#field_name'], $element['#delta']). 313 // However, if some module (for example, flexifield) places our widget deeper in the tree, we want to 314 // use that information in constructing the button name. 315 '#name' => implode('_', $element['#parents']) .'_filefield_remove', 316 '#type' => 'submit', 317 '#value' => t('Remove'), 318 '#submit' => array('node_form_submit_build_node'), 319 '#ahah' => array( // with JavaScript 320 'path' => 'filefield/ahah/'. $element['#type_name'] .'/'. $element['#field_name'] .'/'. $element['#delta'], 321 'wrapper' => $element['#id'] .'-ahah-wrapper', 322 'method' => 'replace', 323 'effect' => 'fade', 324 ), 325 '#field_name' => $element['#field_name'], 326 '#delta' => $element['#delta'], 327 '#weight' => 101, 328 '#post' => $element['#post'], 329 ); 330 331 // Because the output of this field changes depending on the button clicked, 332 // we need to ask FAPI immediately if the remove button was clicked. 333 // It's not good that we call this private function, but 334 // $form_state['clicked_button'] is only available after this #process 335 // callback is finished. 336 if (_form_button_was_clicked($element['filefield_remove'])) { 337 // Delete the file if it is currently unused. Note that field_file_delete() 338 // does a reference check in addition to our basic status check. 339 if (isset($edit['fid'])) { 340 $removed_file = field_file_load($edit['fid']); 341 if ($removed_file['status'] == 0) { 342 field_file_delete($removed_file); 343 } 344 } 345 $item = array('fid' => 0, 'list' => $field['list_default'], 'data' => array('description' => '')); 346 } 347 348 // Set access on the buttons. 349 $element['filefield_upload']['#access'] = empty($item['fid']); 350 $element['filefield_remove']['#access'] = !empty($item['fid']); 351 352 // Add progress bar support to the upload if possible. 353 $progress_indicator = isset($field['widget']['progress_indicator']) ? $field['widget']['progress_indicator'] : 'bar'; 354 if ($progress_indicator != 'throbber' && $implementation = filefield_progress_implementation()) { 355 $upload_progress_key = md5(mt_rand()); 356 357 if ($implementation == 'uploadprogress') { 358 $element['UPLOAD_IDENTIFIER'] = array( 359 '#type' => 'hidden', 360 '#value' => $upload_progress_key, 361 '#attributes' => array('class' => 'filefield-progress'), 362 ); 363 } 364 elseif ($implementation == 'apc') { 365 $element['APC_UPLOAD_PROGRESS'] = array( 366 '#type' => 'hidden', 367 '#value' => $upload_progress_key, 368 '#attributes' => array('class' => 'filefield-progress'), 369 ); 370 } 371 372 // Add the upload progress callback. 373 $element['filefield_upload']['#ahah']['progress']['type'] = 'bar'; 374 $element['filefield_upload']['#ahah']['progress']['path'] = 'filefield/progress/' . $upload_progress_key; 375 } 376 377 // Set the FID. 378 $element['fid'] = array( 379 '#type' => 'hidden', 380 '#value' => $item['fid'], 381 ); 382 383 if ($item['fid'] != 0) { 384 $element['preview'] = array( 385 '#type' => 'markup', 386 '#value' => theme('filefield_widget_preview', $item), 387 ); 388 } 389 390 // Grant access to temporary files. 391 if ($item['fid'] && isset($item['status']) && $item['status'] == 0 && variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PRIVATE) { 392 $_SESSION['filefield_access'][] = $item['fid']; 393 } 394 395 // placeholder.. will be serialized into the data column. this is a place for widgets 396 // to put additional data. 397 $element['data'] = array( 398 '#tree' => 'true', 399 '#access' => !empty($item['fid']), 400 ); 401 402 if (!empty($field['description_field'])) { 403 $element['data']['description'] = array( 404 '#type' => 'textfield', 405 '#title' => t('Description'), 406 '#value' => isset($item['data']['description']) ? $item['data']['description'] : '', 407 '#type' => variable_get('filefield_description_type', 'textfield'), 408 '#maxlength' => variable_get('filefield_description_length', 128), 409 ); 410 } 411 412 if (!empty($field['list_field'])) { 413 $element['list'] = array( 414 '#type' => empty($item['fid']) ? 'hidden' : 'checkbox', 415 '#title' => t('List'), 416 '#value' => isset($item['list']) && !empty($item['fid']) ? $item['list'] : $field['list_default'], 417 '#attributes' => array('class' => 'filefield-list'), 418 ); 419 } 420 else { 421 $element['list'] = array( 422 '#type' => 'hidden', 423 '#value' => '1', 424 ); 425 } 426 427 foreach ($element['#upload_validators'] as $callback => $arguments) { 428 $help_func = $callback .'_help'; 429 if (function_exists($help_func)) { 430 $desc[] = call_user_func_array($help_func, $arguments); 431 } 432 } 433 434 $element['upload'] = array( 435 '#name' => 'files[' . implode('_', $element['#array_parents']) . ']', 436 '#type' => 'file', 437 '#description' => implode('<br />', $desc), 438 '#size' => 22, 439 '#access' => empty($item['fid']), 440 ); 441 442 $element['#attributes']['id'] = $element['#id'] .'-ahah-wrapper'; 443 $element['#prefix'] = '<div '. drupal_attributes($element['#attributes']) .'>'; 444 $element['#suffix'] = '</div>'; 445 446 return $element; 447 } 448 449 /** 450 * An #element_validate callback for the filefield_widget field. 451 */ 452 function filefield_widget_validate(&$element, &$form_state) { 453 // If referencing an existing file, only allow if there are existing 454 // references. This prevents unmanaged files (outside of FileField) from 455 // being deleted if this node were to be deleted. 456 if (!empty($element['fid']['#value'])) { 457 $field = content_fields($element['#field_name'], $element['#type_name']); 458 if ($file = field_file_load($element['fid']['#value'])) { 459 $file = (object) $file; 460 if ($file->status == FILE_STATUS_PERMANENT) { 461 if (field_file_references($file) == 0) { 462 form_error($element, t('Referencing to the file used in the %field field is not allowed.', array('%field' => $element['#title']))); 463 } 464 } 465 } 466 else { 467 form_error($element, t('The file referenced by the %field field does not exist.', array('%field' => $element['#title']))); 468 } 469 } 470 } 471 472 /** 473 * FormAPI theme function. Theme the output of an image field. 474 */ 475 function theme_filefield_widget($element) { 476 $element['#id'] .= '-upload'; // Link the label to the upload field. 477 return theme('form_element', $element, $element['#children']); 478 } 479 480 function theme_filefield_widget_preview($item) { 481 // Remove the current description so that we get the filename as the link. 482 if (isset($item['data']['description'])) { 483 unset($item['data']['description']); 484 } 485 486 return '<div class="filefield-file-info">'. 487 '<div class="filename">'. theme('filefield_file', $item) .'</div>'. 488 '<div class="filesize">'. format_size($item['filesize']) .'</div>'. 489 '<div class="filemime">'. $item['filemime'] .'</div>'. 490 '</div>'; 491 } 492 493 function theme_filefield_widget_item($element) { 494 // Put the upload button directly after the upload field. 495 $element['upload']['#field_suffix'] = drupal_render($element['filefield_upload']); 496 $element['upload']['#theme'] = 'filefield_widget_file'; 497 498 $output = ''; 499 $output .= '<div class="filefield-element clear-block">'; 500 501 if ($element['fid']['#value'] != 0) { 502 $output .= '<div class="widget-preview">'; 503 $output .= drupal_render($element['preview']); 504 $output .= '</div>'; 505 } 506 507 $output .= '<div class="widget-edit">'; 508 $output .= drupal_render($element); 509 $output .= '</div>'; 510 $output .= '</div>'; 511 512 return $output; 513 } 514 515 /** 516 * Custom theme function for FileField upload elements. 517 * 518 * This function allows us to put the "Upload" button immediately after the 519 * file upload field by respecting the #field_suffix property. 520 */ 521 function theme_filefield_widget_file($element) { 522 $output = ''; 523 524 $output .= '<div class="filefield-upload clear-block">'; 525 526 if (isset($element['#field_prefix'])) { 527 $output .= $element['#field_prefix']; 528 } 529 530 _form_set_class($element, array('form-file')); 531 $output .= '<input type="file" name="'. $element['#name'] .'"'. ($element['#attributes'] ? ' '. drupal_attributes($element['#attributes']) : '') .' id="'. $element['#id'] .'" size="'. $element['#size'] ."\" />\n"; 532 533 if (isset($element['#field_suffix'])) { 534 $output .= $element['#field_suffix']; 535 } 536 537 $output .= '</div>'; 538 539 return theme('form_element', $element, $output); 540 } 541 542 /** 543 * Additional #validate handler for the node form. 544 * 545 * This function checks the #required properties on file fields and calculates 546 * node upload totals for all file fields. The #required property is not 547 * properly supported on file fields by Drupal core, so we do this manually. 548 */ 549 function filefield_node_form_validate($form, &$form_state) { 550 foreach ($form['#field_info'] as $field_name => $field) { 551 if (!(in_array($field['module'], array('imagefield', 'filefield')))) continue; 552 $empty = $field['module'] .'_content_is_empty'; 553 $valid = FALSE; 554 $total_filesize = 0; 555 if (!empty($form_state['values'][$field_name])) { 556 foreach ($form_state['values'][$field_name] as $delta => $item) { 557 if ($empty($item, $field)) continue; 558 $valid = TRUE; 559 $total_filesize += (int)$item['filesize']; 560 } 561 } 562 563 if (!$valid && $field['required'] && filefield_edit_access($field['type_name'], $field_name)) { 564 form_set_error($field_name, t('%title field is required.', array('%title' => $field['widget']['label']))); 565 } 566 $max_filesize = parse_size($field['widget']['max_filesize_per_node']); 567 if ($max_filesize && $total_filesize > $max_filesize) { 568 form_set_error($field_name, t('Total filesize for %title, %tsize, exceeds field settings of %msize.', 569 array( 570 '%title' => $field['widget']['label'], 571 '%tsize' => format_size($total_filesize), 572 '%msize' => format_size($max_filesize) 573 ) 574 )); 575 } 576 } 577 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated: Thu Mar 24 11:18:33 2011 | Cross-referenced by PHPXref 0.7 |