You are here

function _webform_validate_file in Webform 5

Same name and namespace in other branches
  1. 5.2 components/file.inc \_webform_validate_file()
  2. 6.3 components/file.inc \_webform_validate_file()
  3. 6.2 components/file.inc \_webform_validate_file()

File

components/file.inc, line 206

Code

function _webform_validate_file($form_element, $form_key, $fieldname, $filters) {

  // Set the current file as the default.
  if (isset($form_element['#webform_current_file'])) {
    form_set_value(array(
      '#parents' => $form_element['#parents'],
    ), serialize($form_element['#webform_current_file']));
  }
  if (empty($_FILES['files']['name'][$form_key])) {
    return;
  }

  // Build a list of extensions.
  $extensions = array();
  if (is_array($filters['types'])) {
    foreach ($filters['types'] as $filtertype) {
      foreach ($filtertype as $extension) {
        $extensions[] = $extension;
      }
    }
  }
  $extras = str_replace(" ", "", $filters['addextensions']);
  if (!empty($extras)) {
    $extensions = array_merge($extensions, explode(",", $extras));
  }

  // Build a human readable list of extensions:
  if (count($extensions) > 1) {
    for ($n = 0; $n < count($extensions) - 1; $n++) {
      $extension_list .= $extensions[$n] . ", ";
    }
    $extension_list .= "or " . $extensions[count($extensions) - 1];
  }
  else {
    $extension_list = $extensions[0];
  }
  $dot = strrpos($_FILES['files']['name'][$form_key], '.');
  $extension = strtolower(substr($_FILES['files']['name'][$form_key], $dot + 1));
  if (!in_array($extension, $extensions)) {
    form_set_error($form_key, t("Files with the '%ext' extension are not allowed, please upload a file with a %exts extension.", array(
      '%ext' => $extension,
      '%exts' => $extension_list,
    )));
  }

  // Now let's check the file size (limit is set in KB).
  if ($_FILES['files']['size'][$form_key] > $filters['size'] * 1024) {
    form_set_error($form_key, t("The file '%filename' is too large (%filesize KB). Please upload a file %maxsize KB or smaller.", array(
      '%filename' => $_FILES['files']['name'][$form_key],
      '%filesize' => (int) ($_FILES['files']['size'][$form_key] / 1024),
      '%maxsize' => $filters['size'],
    )));
  }
}