/**
  * {@inheritdoc}
  */
 public function validate($value, Constraint $constraint)
 {
     // Get the file to execute validators.
     $file = $value->get('entity')->getTarget()->getValue();
     // Get the validators.
     $validators = $value->getUploadValidators();
     // Checks that a file meets the criteria specified by the validators.
     if ($errors = file_validate($file, $validators)) {
         foreach ($errors as $error) {
             $this->context->addViolation($error);
         }
     }
 }
Beispiel #2
0
 /**
  * Test that the validators passed into are checked.
  */
 function testCallerValidation()
 {
     $file = $this->createFile();
     // Empty validators.
     $this->assertEqual(file_validate($file, array()), array(), 'Validating an empty array works successfully.');
     $this->assertFileHooksCalled(array('validate'));
     // Use the file_test.module's test validator to ensure that passing tests
     // return correctly.
     file_test_reset();
     file_test_set_return('validate', array());
     $passing = array('file_test_validator' => array(array()));
     $this->assertEqual(file_validate($file, $passing), array(), 'Validating passes.');
     $this->assertFileHooksCalled(array('validate'));
     // Now test for failures in validators passed in and by hook_validate.
     file_test_reset();
     file_test_set_return('validate', array('Epic fail'));
     $failing = array('file_test_validator' => array(array('Failed', 'Badly')));
     $this->assertEqual(file_validate($file, $failing), array('Failed', 'Badly', 'Epic fail'), 'Validating returns errors.');
     $this->assertFileHooksCalled(array('validate'));
 }
 /**
  * Sets widget file id values by validating and processing the submitted data.
  * Runs before processor callbacks.
  */
 public static function setWidgetValue($element, &$input, FormStateInterface $form_state)
 {
     if (empty($input['imce_paths'])) {
         return;
     }
     $paths = $input['imce_paths'];
     $input['imce_paths'] = '';
     // Remove excess data.
     $paths = array_unique(array_filter(explode(':', $paths)));
     if (isset($element['#cardinality']) && $element['#cardinality'] > -1) {
         $paths = array_slice($paths, 0, $element['#cardinality']);
     }
     // Check if paths are accessible by the current user with Imce.
     if (!($paths = Imce::accessFilePaths($paths, \Drupal::currentUser(), $element['#scheme']))) {
         return;
     }
     // Validate paths as file entities.
     $file_usage = \Drupal::service('file.usage');
     $errors = array();
     foreach ($paths as $path) {
         // Get entity by uri
         $file = Imce::getFileEntity($element['#scheme'] . '://' . $path, TRUE);
         if ($new_errors = file_validate($file, $element['#upload_validators'])) {
             $errors = array_merge($errors, $new_errors);
         } else {
             // Save the file record.
             if ($file->isNew()) {
                 $file->save();
             }
             if ($fid = $file->id()) {
                 // Make sure the file has usage otherwise it will be denied.
                 if (!$file_usage->listUsage($file)) {
                     $file_usage->add($file, 'imce', 'file', $fid);
                 }
                 $input['fids'][] = $fid;
             }
         }
     }
     // Set error messages.
     if ($errors) {
         $errors = array_unique($errors);
         if (count($errors) > 1) {
             $errors = array('#theme' => 'item_list', '#items' => $errors);
             $message = \Drupal::service('renderer')->render($errors);
         } else {
             $message = array_pop($errors);
         }
         // May break the widget flow if set as a form error.
         drupal_set_message($message, 'error');
     }
 }
Beispiel #4
0
 /**
  * @param ldap entry array $ldap_entry
  *
  * @return drupal file object image user's thumbnail or FALSE if none present or ERROR happens.
  */
 public function userPictureFromLdapEntry($ldap_entry, $drupal_username = FALSE)
 {
     if ($ldap_entry && $this->picture_attr) {
         //Check if ldap entry has been provisioned.
         $thumb = isset($ldap_entry[$this->picture_attr][0]) ? $ldap_entry[$this->picture_attr][0] : FALSE;
         if (!$thumb) {
             return FALSE;
         }
         //Create md5 check.
         $md5thumb = md5($thumb);
         /**
          * If existing account already has picture check if it has changed if so remove old file and create the new one
          * If picture is not set but account has md5 something is wrong exit.
          */
         if ($drupal_username && ($account = user_load_by_name($drupal_username))) {
             if ($account->uid == 0 || $account->uid == 1) {
                 return FALSE;
             }
             if (isset($account->picture)) {
                 // Check if image has changed
                 if (isset($account->data['ldap_user']['init']['thumb5md']) && $md5thumb === $account->data['ldap_user']['init']['thumb5md']) {
                     //No change return same image
                     return $account->picture;
                 } else {
                     //Image is different check wether is obj/str and remove fileobject
                     if (is_object($account->picture)) {
                         file_delete($account->picture, TRUE);
                     } elseif (is_string($account->picture)) {
                         $file = file_load(intval($account->picture));
                         file_delete($file, TRUE);
                     }
                 }
             } elseif (isset($account->data['ldap_user']['init']['thumb5md'])) {
                 watchdog('ldap_server', "Some error happened during thumbnailPhoto sync");
                 return FALSE;
             }
         }
         //Create tmp file to get image format.
         $filename = uniqid();
         $fileuri = file_directory_temp() . '/' . $filename;
         $size = file_put_contents($fileuri, $thumb);
         $info = image_get_info($fileuri);
         unlink($fileuri);
         // create file object
         $file = file_save_data($thumb, 'public://' . variable_get('user_picture_path') . '/' . $filename . '.' . $info['extension']);
         $file->md5Sum = $md5thumb;
         // standard Drupal validators for user pictures
         $validators = array('file_validate_is_image' => array(), 'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')), 'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024));
         $errors = file_validate($file, $validators);
         if (empty($errors)) {
             return $file;
         } else {
             foreach ($errors as $err => $err_val) {
                 watchdog('ldap_server', "Error storing picture: %{$err}", "%{$err_val}", WATCHDOG_ERROR);
             }
             return FALSE;
         }
     }
 }
 /**
  * Override. Handle the file upload process before creating an actual entity.
  * The file could be a straight replacement, and this is where we handle that.
  */
 public function createEntity()
 {
     if ($this->checkEntityAccess('create', 'file', NULL) === FALSE && $this->checkGroupAccess('create') === FALSE) {
         // User does not have access to create entity.
         $params = array('@resource' => $this->getPluginKey('label'));
         throw new RestfulForbiddenException(format_string('You do not have access to create a new @resource resource.', $params));
     }
     $destination = 'public://';
     // do spaces/private file stuff here
     if (isset($this->request['private'])) {
         $destination = 'private://';
     }
     if (isset($this->request['vsite'])) {
         $path = db_select('purl', 'p')->fields('p', array('value'))->condition('id', $this->request['vsite'])->execute()->fetchField();
         $destination .= $path . '/files';
     }
     $writable = file_prepare_directory($destination, FILE_MODIFY_PERMISSIONS | FILE_CREATE_DIRECTORY);
     if ($entity = file_save_upload('upload', $this->getValidators(), $destination, FILE_EXISTS_REPLACE)) {
         if (isset($this->request['vsite'])) {
             og_group('node', $this->request['vsite'], array('entity_type' => 'file', 'entity' => $entity));
             $entity = file_load($entity->fid);
         }
         if ($entity->status != FILE_STATUS_PERMANENT) {
             $entity->status = FILE_STATUS_PERMANENT;
             $entity = file_save($entity);
         }
         $wrapper = entity_metadata_wrapper($this->entityType, $entity);
         return array($this->viewEntity($wrapper->getIdentifier()));
     } elseif (isset($_FILES['files']) && $_FILES['files']['errors']['upload']) {
         throw new RestfulUnprocessableEntityException('Error uploading new file to server.');
     } elseif (isset($this->request['embed']) && module_exists('media_internet')) {
         $provider = media_internet_get_provider($this->request['embed']);
         $provider->validate();
         $validators = array();
         // TODO: How do we populate this?
         $file = $provider->getFileObject();
         if ($validators) {
             $file = $provider->getFileObject();
             // Check for errors. @see media_add_upload_validate calls file_save_upload().
             // this code is ripped from file_save_upload because we just want the validation part.
             // Call the validation functions specified by this function's caller.
             $errors = array_merge($errors, file_validate($file, $validators));
         }
         if (!empty($errors)) {
             throw new MediaInternetValidationException(implode("\n", $errors));
         } else {
             // Providers decide if they need to save locally or somewhere else.
             // This method returns a file object
             $entity = $provider->save();
             if ($entity->status != FILE_STATUS_PERMANENT) {
                 $entity->status = FILE_STATUS_PERMANENT;
                 $entity = file_save($entity);
             }
             if ($this->request['vsite']) {
                 og_group('node', $this->request['vsite'], array('entity_type' => 'file', 'entity' => $entity));
                 $entity = file_load($entity->fid);
             }
             $wrapper = entity_metadata_wrapper($this->entityType, $entity);
             return array($this->viewEntity($wrapper->getIdentifier()));
         }
     } else {
         if (!$writable) {
             throw new RestfulServerConfigurationException('Unable to create directory for target file.');
         } else {
             // we failed for some other reason. What?
             throw new RestfulBadRequestException('Unable to process request.');
         }
     }
 }
             unlink($cfg["file"]["base"]["maindir"] . $cfg["file"]["base"]["new"] . $file);
         }
     }
     header("Location: " . $header);
 }
 if ($environment["parameter"][3] == "verify" && ($_POST["send"] != "" || $_POST["extract"] != "" || $_POST["extension2"] != "")) {
     // form eingaben pruefen
     form_errors($form_options, $_POST);
     // evtl. zusaetzliche datensatz aendern
     if ($ausgaben["form_error"] == "") {
         if ($owner_error == "") {
             // funktions bereich fuer erweiterungen
             // ***
             // file ersetzen
             if ($_FILES["upload"]["name"] != "") {
                 $error = file_validate($_FILES["upload"]["tmp_name"], $_FILES["upload"]["size"], $cfg["file"]["filesize"], array($form_values["ffart"]), "upload");
                 if ($error == 0) {
                     $newname = $cfg["file"]["base"]["maindir"] . $cfg["file"]["base"]["new"] . $_SESSION["uid"] . "_" . $_FILES["upload"]["name"];
                     rename($_FILES["upload"]["tmp_name"], $newname);
                     $file_id = $form_values["fid"];
                     arrange($file_id, $newname, $_FILES["upload"]["name"]);
                 } else {
                     $ausgaben["form_error"] .= "#(error_replace) " . $file["name"] . " g(file_error" . $error . ")";
                 }
             }
             if ($_POST["extract"] != "") {
                 // naechste freie compilation-id suchen
                 if ($_POST["selection"] == -1) {
                     $buffer = compilation_list();
                     reset($buffer);
                     $compid = key($buffer) + 1;
  /**
   * An adaptation of file_save_upload() that includes more verbose errors.
   *
   * @param string $source
   *   A string specifying the filepath or URI of the uploaded file to save.
   *
   * @return stdClass
   *   The saved file object.
   *
   * @throws \RestfulBadRequestException
   * @throws \RestfulServiceUnavailable
   *
   * @see file_save_upload()
   */
  protected function fileSaveUpload($source) {
    static $upload_cache;

    $account = $this->getAccount();
    $options = $this->getPluginKey('options');

    $validators = $options['validators'];
    $destination = $options['scheme'] . "://";
    $replace = $options['replace'];

    // Return cached objects without processing since the file will have
    // already been processed and the paths in _FILES will be invalid.
    if (isset($upload_cache[$source])) {
      return $upload_cache[$source];
    }

    // Make sure there's an upload to process.
    if (empty($_FILES['files']['name'][$source])) {
      return NULL;
    }

    // Check for file upload errors and return FALSE if a lower level system
    // error occurred. For a complete list of errors:
    // See http://php.net/manual/features.file-upload.errors.php.
    switch ($_FILES['files']['error'][$source]) {
      case UPLOAD_ERR_INI_SIZE:
      case UPLOAD_ERR_FORM_SIZE:
        $message = format_string('The file %file could not be saved, because it exceeds %maxsize, the maximum allowed size for uploads.', array('%file' => $_FILES['files']['name'][$source], '%maxsize' => format_size(file_upload_max_size())));
        throw new \RestfulBadRequestException($message);

      case UPLOAD_ERR_PARTIAL:
      case UPLOAD_ERR_NO_FILE:
        $message = format_string('The file %file could not be saved, because the upload did not complete.', array('%file' => $_FILES['files']['name'][$source]));
        throw new \RestfulBadRequestException($message);

      case UPLOAD_ERR_OK:
        // Final check that this is a valid upload, if it isn't, use the
        // default error handler.
        if (is_uploaded_file($_FILES['files']['tmp_name'][$source])) {
          break;
        }

      // Unknown error
      default:
        $message = format_string('The file %file could not be saved. An unknown error has occurred.', array('%file' => $_FILES['files']['name'][$source]));
        throw new \RestfulServiceUnavailable($message);
    }

    // Begin building file object.
    $file = new stdClass();
    $file->uid      = $account->uid;
    $file->status   = 0;
    $file->filename = trim(drupal_basename($_FILES['files']['name'][$source]), '.');
    $file->uri      = $_FILES['files']['tmp_name'][$source];
    $file->filemime = file_get_mimetype($file->filename);
    $file->filesize = $_FILES['files']['size'][$source];

    $extensions = '';
    if (isset($validators['file_validate_extensions'])) {
      if (isset($validators['file_validate_extensions'][0])) {
        // Build the list of non-munged extensions if the caller provided them.
        $extensions = $validators['file_validate_extensions'][0];
      }
      else {
        // If 'file_validate_extensions' is set and the list is empty then the
        // caller wants to allow any extension. In this case we have to remove the
        // validator or else it will reject all extensions.
        unset($validators['file_validate_extensions']);
      }
    }
    else {
      // No validator was provided, so add one using the default list.
      // Build a default non-munged safe list for file_munge_filename().
      $extensions = 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp';
      $validators['file_validate_extensions'] = array();
      $validators['file_validate_extensions'][0] = $extensions;
    }

    if (!empty($extensions)) {
      // Munge the filename to protect against possible malicious extension hiding
      // within an unknown file type (ie: filename.html.foo).
      $file->filename = file_munge_filename($file->filename, $extensions);
    }

    // Rename potentially executable files, to help prevent exploits (i.e. will
    // rename filename.php.foo and filename.php to filename.php.foo.txt and
    // filename.php.txt, respectively). Don't rename if 'allow_insecure_uploads'
    // evaluates to TRUE.
    if (!variable_get('allow_insecure_uploads', 0) && preg_match('/\.(php|pl|py|cgi|asp|js)(\.|$)/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
      $file->filemime = 'text/plain';
      $file->uri .= '.txt';
      $file->filename .= '.txt';
      // The .txt extension may not be in the allowed list of extensions. We have
      // to add it here or else the file upload will fail.
      if (!empty($extensions)) {
        $validators['file_validate_extensions'][0] .= ' txt';

        // Unlike file_save_upload() we don't need to let the user know that
        // for security reasons, your upload has been renamed, since RESTful
        // will return the file name in the response.
      }
    }

    // If the destination is not provided, use the temporary directory.
    if (empty($destination)) {
      $destination = 'temporary://';
    }

    // Assert that the destination contains a valid stream.
    $destination_scheme = file_uri_scheme($destination);
    if (!$destination_scheme || !file_stream_wrapper_valid_scheme($destination_scheme)) {
      $message = format_string('The file could not be uploaded, because the destination %destination is invalid.', array('%destination' => $destination));
      throw new \RestfulServiceUnavailable($message);
    }

    $file->source = $source;
    // A URI may already have a trailing slash or look like "public://".
    if (substr($destination, -1) != '/') {
      $destination .= '/';
    }
    $file->destination = file_destination($destination . $file->filename, $replace);
    // If file_destination() returns FALSE then $replace == FILE_EXISTS_ERROR and
    // there's an existing file so we need to bail.
    if ($file->destination === FALSE) {
      $message = format_string('The file %source could not be uploaded because a file by that name already exists in the destination %directory.', array('%source' => $source, '%directory' => $destination));
      throw new \RestfulServiceUnavailable($message);
    }

    // Add in our check of the the file name length.
    $validators['file_validate_name_length'] = array();

    // Call the validation functions specified by this function's caller.
    $errors = file_validate($file, $validators);

    // Check for errors.
    if (!empty($errors)) {
      $message = format_string('The specified file %name could not be uploaded.', array('%name' => $file->filename));
      if (count($errors) > 1) {
        $message .= theme('item_list', array('items' => $errors));
      }
      else {
        $message .= ' ' . array_pop($errors);
      }

      throw new \RestfulServiceUnavailable($message);
    }

    // Move uploaded files from PHP's upload_tmp_dir to Drupal's temporary
    // directory. This overcomes open_basedir restrictions for future file
    // operations.
    $file->uri = $file->destination;
    if (!drupal_move_uploaded_file($_FILES['files']['tmp_name'][$source], $file->uri)) {
      watchdog('file', 'Upload error. Could not move uploaded file %file to destination %destination.', array('%file' => $file->filename, '%destination' => $file->uri));
      $message = 'File upload error. Could not move uploaded file.';
      throw new \RestfulServiceUnavailable($message);
    }

    // Set the permissions on the new file.
    drupal_chmod($file->uri);

    // If we are replacing an existing file re-use its database record.
    if ($replace == FILE_EXISTS_REPLACE) {
      $existing_files = file_load_multiple(array(), array('uri' => $file->uri));
      if (count($existing_files)) {
        $existing = reset($existing_files);
        $file->fid = $existing->fid;
      }
    }

    // If we made it this far it's safe to record this file in the database.
    if ($file = file_save($file)) {
      // Add file to the cache.
      $upload_cache[$source] = $file;
      return $file;
    }

    // Something went wrong, so throw a general exception.
    throw new \RestfulServiceUnavailable('Unknown error has occurred.');
  }
Beispiel #8
0
function formular_validate($form_data)
{
    $fieldsets_c = count($form_data[ks_all]);
    if (!empty($form_data)) {
        foreach ($form_data as $key => $value) {
            ${$key} = $value;
        }
    }
    if (strlen($meno) > 30 or strlen($meno) < 4) {
        $error_msg[] = "Meno je povinný údaj a môže mať od 4 do 30 znakov";
        $error_data[meno] = $meno;
    }
    if (strlen($adresa) > 30 or strlen($adresa) < 4) {
        $error_msg[] = "Adresa je povinný údaj a môže mať od 4 do 30 znakov";
        $error_data[adresa] = $adresa;
    }
    if (strlen($ico_icdph) > 18) {
        $error_msg[] = "IČO môže mať max 30 znakov";
        $error_data[ico_icdph] = $ico_icdph;
    }
    if (strlen($telefon) > 25 or strlen($telefon) < 8) {
        $error_msg[] = "Telefón je povinný údaj a môže mať max 30 znakov";
        $error_data[telefon] = $telefon;
    }
    if (strlen($email) > 50 or strlen($email) < 8) {
        $error_msg[] = "email je povinný údaj a môže mať od 8 do 50 znakov";
        $error_data[email] = $email;
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_msg[] = "email je v nesprávnom tvare";
        $error_data[email_valid] = $email;
    }
    if (empty($material) or !is_numeric($material) or $material < 0 or $material > 100) {
        $error_msg[] = "Materiál je povinný údaj";
        $error_data[material] = $material;
    }
    //if(!is_numeric($vyrobca) OR $vyrobca<0 OR $vyrobca>1000) $error_msg[] = "Zle zadaný údaj Výrobcu";
    if (strlen($dekor_vlastny) > 300) {
        $error_msg[] = "Vlastný dekor môže mať max 30 znakov a je možné ho zadať iba ak nie je vybratý žiaden výrobca";
        $error_data[dekor_vlastny] = $dekor_vlastny;
    }
    $hrubka_pocet = 1;
    for ($i = 0; $i < $fieldsets_c; $i++) {
        $error_line = 0;
        $error_line = $i + 1;
        if (empty($ks_all[$i]) or !is_numeric($ks_all[$i]) or $ks_all[$i] < 0 or $ks_all[$i] > 5000) {
            $error_msg[] = "Počet kusov je povinný číselný údaj - riadok {$error_line}";
            $error_data[ks_all] = $ks_all[$i] . " na riadku: " . $error_line;
        }
        if ($material == 12 or $material == 14) {
            if (empty($dlzka_all[$i]) or !is_numeric($dlzka_all[$i]) or $dlzka_all[$i] < 10 or $dlzka_all[$i] > 4100) {
                $error_msg[] = "Dĺžka je povinný číselný údaj od 10 do 4100mm - riadok {$error_line}";
                $error_data[dlzka_all] = $dlzka_all[$i] . " na riadku: " . $error_line;
            }
        } else {
            if ($material == 1 and $vyrobca == 9) {
                if (empty($dlzka_all[$i]) or !is_numeric($dlzka_all[$i]) or $dlzka_all[$i] < 10 or $dlzka_all[$i] > 4100) {
                    $error_msg[] = "Dĺžka je povinný číselný údaj od 10 do 4100mm - riadok {$error_line}";
                    $error_data[dlzka_all] = $dlzka_all[$i] . " na riadku: " . $error_line;
                }
            } else {
                if (empty($dlzka_all[$i]) or !is_numeric($dlzka_all[$i]) or $dlzka_all[$i] < 10 or $dlzka_all[$i] > 2800) {
                    $error_msg[] = "Dĺžka je povinný číselný údaj od 10 do 2800mm - riadok {$error_line}";
                    $error_data[dlzka_all] = $dlzka_all[$i] . " na riadku: " . $error_line;
                }
            }
        }
        if (empty($sirka_all[$i]) or !is_numeric($sirka_all[$i]) or $sirka_all[$i] < 10 or $sirka_all[$i] > 2070) {
            $error_msg[] = "Šírka je povinný číselný údaj od 10 do 2070mm - riadok {$error_line}";
            $error_data[sirka_all] = $sirka_all[$i] . " na riadku: " . $error_line;
        }
        if (strlen($nazov_all[$i]) > 31) {
            $error_msg[] = "Názov môže mať max 30 znakov - riadok {$error_line}";
            $error_data[nazov_all] = $nazov_all[$i] . " na riadku: " . $error_line;
        }
        if (strlen($poznamka_all[$i]) > 31) {
            $error_msg[] = "Poznámka môže mať max 30 znakov - riadok {$error_line}";
            $error_data[poznamka_all] = $poznamka_all[$i] . " na riadku: " . $error_line;
        }
        //if(!is_numeric($duplak_all[$i])) $error_msg[] = "Nesprávna hodnota Duplák - riadok $error_line";
        if (!is_numeric($orientacia_all[$i]) or $orientacia_all[$i] < 0 or $orientacia_all[$i] > 3) {
            $error_msg[] = "Zle zadaná Orientácia - riadok {$error_line}";
            $error_data[orientacia_all] = $orientacia_all[$i] . " na riadku: " . $error_line;
        }
        if (!empty($roh1x_all[$i])) {
            if ($roh1x_all[$i] < 10 or $roh1x_all[$i] > 2800) {
                $error_msg[] = "Roh (1x) môže byť iba číselný údaj od 10 do 2800mm - riadok {$error_line}";
                $error_data[roh1x_all] = $roh1x_all[$i] . " na riadku: " . $error_line;
            }
        }
        if (!empty($roh2x_all[$i])) {
            if (!is_numeric($roh2x_all[$i]) or $roh2x_all[$i] < 10 or $roh2x_all[$i] > 2800) {
                $error_msg[] = "Roh (2x) môže byť iba číselný údaj od 10 do 2800mm - riadok {$error_line}";
                $error_data[roh2x_all] = $roh2x_all[$i] . " na riadku: " . $error_line;
            }
        }
        if (!empty($roh3x_all[$i])) {
            if (!is_numeric($roh3x_all[$i]) or $roh3x_all[$i] < 10 or $roh3x_all[$i] > 2800) {
                $error_msg[] = "Roh (3x) môže byť iba číselný údaj od 10 do 2800mm - riadok {$error_line}";
                $error_data[roh3x_all] = $roh3x_all[$i] . " na riadku: " . $error_line;
            }
        }
        if (!empty($roh4x_all[$i])) {
            if (!is_numeric($roh4x_all[$i]) or $roh4x_all[$i] < 10 or $roh4x_all[$i] > 2800) {
                $error_msg[] = "Roh (4x) môže byť iba číselný údaj od 10 do 2800mm - riadok {$error_line}";
                $error_data[roh4x_all] = $roh4x_all[$i] . " na riadku: " . $error_line;
            }
        }
        if (!empty($roh1y_all[$i])) {
            if (!is_numeric($roh1y_all[$i]) or $roh1y_all[$i] < 10 or $roh1y_all[$i] > 2070) {
                $error_msg[] = "Roh (1y) môže byť iba číselný údaj od 10 do 2070mm - riadok {$error_line}";
                $error_data[roh1y_all] = $roh1y_all[$i] . " na riadku: " . $error_line;
            }
        }
        if (!empty($roh2y_all[$i])) {
            if (!is_numeric($roh2y_all[$i]) or $roh2y_all[$i] < 10 or $roh2y_all[$i] > 2070) {
                $error_msg[] = "Roh (2y) môže byť iba číselný údaj od 10 do 2070mm - riadok {$error_line}";
                $error_data[roh2y_all] = $roh2y_all[$i] . " na riadku: " . $error_line;
            }
        }
        if (!empty($roh3y_all[$i])) {
            if (!is_numeric($roh3y_all[$i]) or $roh3y_all[$i] < 10 or $roh3y_all[$i] > 2070) {
                $error_msg[] = "Roh (3y) môže byť iba číselný údaj od 10 do 2070mm - riadok {$error_line}";
                $error_data[roh3y_all] = $roh3y_all[$i] . " na riadku: " . $error_line;
            }
        }
        if (!empty($roh4y_all[$i])) {
            if (!is_numeric($roh4y_all[$i]) or $roh4y_all[$i] < 10 or $roh4y_all[$i] > 2070) {
                $error_msg[] = "Roh (4y) môže byť iba číselný údaj od 10 do 2070mm - riadok {$error_line}";
                $error_data[roh4y_all] = $roh4y_all[$i] . " na riadku: " . $error_line;
            }
        }
    }
    $form_data_file = array("file_name" => $form_data[file_name], "file_ext" => $form_data[file_ext], "file_size" => $form_data[file_size]);
    //var_dump($form_data);
    //var_dump($form_data_file);
    $file_validate = file_validate($form_data_file);
    if (count($file_validate) > 0) {
        foreach ($file_validate as $message) {
            $error_msg[] = $message;
            $error_data[file] = $message;
        }
    }
    //var_dump($error_msg);
    //die();
    $hrubka_unique = array_unique($hrubka_all);
    $hrubka_pocet = count($hrubka_unique);
    if (in_array(def_value("default_duplak", "hodnota"), $hrubka_unique)) {
        $hrubka_pocet = $hrubka_pocet - 1;
    }
    if ($hrubka_pocet > 1) {
        $error_msg[] = "V objednávke nie je možné vybrať 2 a viac rôznych hrúbok materiálu";
        $error_data[hrubka_pocet] = $hrubka_pocet . " ::: " . implode(",", $hrubka_unique);
    }
    /*
    if (!empty($error_msg)) {
        foreach ($error_data as $key=>$value) {
            $query = "INSERT INTO error_msg VALUES
                        (NULL, \"".$key."\", \"$value\", NULL)";
            sql_insert($query);
        }
    }
    */
    return $error_msg;
}
if (count($cfg["wizard"]["img_edit"]["cb_link_size"]) > 0) {
    foreach ($cfg["wizard"]["img_edit"]["cb_link_size"] as $value => $label) {
        $check = "";
        if ($ausgaben["tagwerte3"] == $value) {
            $check = " checked=\"checked\"";
        }
        $dataloop["size"][] = array("value" => $value, "label" => "#(" . $label . ")", "check" => $check);
    }
} else {
    $dataloop["size"][] = array("value" => $ausgaben["tagwerte3"], "label" => "not changeable", "check" => " checked=\"checked\"");
}
// abspeichern, part 2
// * * *
if ($environment["parameter"][7] == "verify" && ($_POST["send"] != "" || $_POST["add"] != "" || $_POST["sel"] != "" || $_POST["refresh"] != "" || $_POST["upload"] != "" || $_POST["uploaded"] != "" || $_POST["change_pic"] != "")) {
    // ggf bild einfuegen
    $error = file_validate($_FILES["new_file"]["tmp_name"], $_FILES["new_file"]["size"], $cfg["file"]["filesize"], $cfg["file"]["filetyp"], "new_file");
    if ($error == 0) {
        $newname = $cfg["file"]["base"]["maindir"] . $cfg["file"]["base"]["new"] . $_SESSION["uid"] . "_" . $_FILES["new_file"]["name"];
        rename($_FILES["new_file"]["tmp_name"], $newname);
    }
    // einzubauender content
    $tag_werte = array();
    for ($i = 0; $i <= 6; $i++) {
        if ($i == 0) {
            $tag_werte[] = str_replace("/tn/", "/" . $_POST["pic_size"] . "/", $_POST["tagwerte"][$i]);
        } else {
            $tag_werte[] = $_POST["tagwerte"][$i];
        }
    }
    $tag = str_replace(array("[", "/", "]"), "", $tag_meat[$tag_marken[0]][$tag_marken[1]]["tag_end"]);
    $to_insert = "[" . $tag . "=" . implode(";", $tag_werte) . "]" . $_POST["description"] . "[/" . $tag . "]";
 /**
  * {@inheritdoc}
  */
 public function validateFile(FileInterface $file, $extensions, array $additional_validators = [])
 {
     $validators = $additional_validators;
     if (!empty($extensions)) {
         $validators['file_validate_extensions'] = [$extensions];
     }
     $validators['file_validate_name_length'] = [];
     // Call the validation functions specified by this function's caller.
     return file_validate($file, $validators);
 }
 /* naechste Selektionsnummer finden */
 $buffer = compilation_list();
 reset($buffer);
 $compid = key($buffer) + 1;
 /* entpacken */
 $not_extracted = zip_handling($gal_file, $cfg["file"]["base"]["maindir"] . $cfg["file"]["base"]["new"], $cfg["migrate"]["filetyp"], $cfg["migrate"]["filesize"], "", $compid, $cfg["migrate"]["zip_handling"]["sektions"]);
 $i = 0;
 $sort = 0;
 $pics = array();
 if (count($_SESSION["zip_extracted"]) == 0) {
     continue;
 }
 foreach ($_SESSION["zip_extracted"] as $name => $value) {
     /* ueberpruefen */
     $file2insert = $cfg["file"]["base"]["maindir"] . $cfg["file"]["base"]["new"] . $name;
     $error = file_validate($file2insert, filesize($file2insert), $cfg["migrate"]["filesize"], $cfg["migrate"]["filetyp"]);
     if ($error == 0) {
         /* db-eintrag machen */
         $extension = strtolower(substr(strrchr($name, "."), 1));
         $sort++;
         $comp_tag = "#p" . $compid . "," . $sort * 10 . "#";
         /* testen, ob schon ein identischer eintrag vorhanden ist */
         $sql = "SELECT *\n                                              FROM site_file\n                                             WHERE fuid=1\n                                               AND ffname='" . str_replace($_SESSION["uid"] . "_", "", $name) . "'\n                                               AND ffart='" . $extension . "'\n                                               AND fdesc='" . $value["fdesc"] . "'\n                                               AND funder='" . $value["funder"] . "'\n                                               AND fhit LIKE '%from " . $file . "%'";
         $result = $db->query($sql);
         $num = $db->num_rows($result);
         if ($num == 0) {
             $sql = "INSERT INTO site_file (fuid,\n                                                                       ffname,\n                                                                       ffart,\n                                                                       fdesc,\n                                                                       funder,\n                                                                       fhit)\n                                                               VALUES (1,\n                                                                       '" . str_replace($_SESSION["uid"] . "_", "", $name) . "',\n                                                                       '" . $extension . "',\n                                                                       '" . $value["fdesc"] . "',\n                                                                       '" . $value["funder"] . "',\n                                                                       '" . $comp_tag . " from " . $file . "')";
             $result = $db->query($sql);
             /* zu dateiablage hinzufuegen */
             if ($result) {
                 $file_id = $db->lastid();
 /**
  * Render API callback: Validates the managed_file element.
  *
  * Note: based on plupload_element_validate().
  */
 public static function validatePlUploadFile(&$element, FormStateInterface $form_state, &$complete_form)
 {
     foreach ($element['#value'] as $file_info) {
         // Here we create a $file object for a file that doesn't exist yet,
         // because saving the file to its destination is done in a submit handler.
         // Using tmp path will give validators access to the actual file on disk and
         // filesize information. We manually modify filename and mime to allow
         // extension checks.
         $destination = \Drupal::config('system.file')->get('default_scheme') . '://' . $file_info['name'];
         $destination = file_stream_wrapper_uri_normalize($destination);
         $file = entity_create('file', array('uri' => $file_info['tmppath'], 'uid' => \Drupal::currentUser()->id(), 'status' => FILE_STATUS_PERMANENT, 'filename' => drupal_basename($destination), 'filemime' => \Drupal::service('file.mime_type.guesser')->guess($destination)));
         foreach (file_validate($file, $element['#upload_validators']) as $error_message) {
             $message = t('The specified file %name could not be uploaded.', array('%name' => $file->getFilename()));
             $concatenated_message = $message . ' ' . $error_message;
             $form_state->setError($element, $concatenated_message);
         }
     }
 }
Beispiel #13
0
     //var_dump($_FILES);
     $file_c = count($_FILES["subor"]["name"]);
     //echo $file_c;
     for ($i = 0; $i < $file_c; $i++) {
         if (!empty($_FILES["subor"]["name"][$i]) and strlen($_FILES["subor"]["name"][$i]) > 4) {
             //echo "ok<br>";
             $data[file_ext][] = strtolower(end(explode(".", $_FILES["subor"]["name"][$i])));
             $data[file_name][] = md5(microtime());
             $data[file_name_old][] = $_FILES["subor"]["name"][$i];
             $data[file_tmp_name][] = $_FILES["subor"]["tmp_name"][$i];
             $data[file_size][] = $_FILES["subor"]["size"][$i];
         }
     }
 }
 $form_data_file = array("file_name" => $data[file_name], "file_ext" => $data[file_ext], "file_size" => $data[file_size]);
 $file_validate = file_validate($form_data_file);
 if (count($file_validate) > 0) {
     foreach ($file_validate as $message) {
         $error_msg[] = $message;
     }
 }
 //var_dump($error_msg);
 //die();
 if (empty($error_msg)) {
     if (empty($_SESSION["posted_form"]) || !isset($_SESSION["posted_form"])) {
         die("nie su žiadne údaje na nahrávanie");
     }
     // vlozenie do objednávaok
     mysql_query("BEGIN");
     if ($_POST[submit_save]) {
         $status_cp = def_value("default_obj_status_rozpracovana", "hodnota");
function zip_handling($file, $extract_dest = "", $restrict_type = array(), $restrict_size = "", $restrict_dir = "", $compid = "", $section = array(), $wave_thru = 0)
{
    global $db, $pathvars, $cfg, $ausgaben;
    $text_files = array();
    $zip = new ZipArchive();
    if ($zip->open($file) == TRUE) {
        $zip_content = array();
        // beschraenkung, welche unterordner im zip bearbeitet werden sollen
        $restrict = explode(",", $restrict_dir);
        // zip durchgehen und dateien-informationen holen
        for ($i = 0; $i < $zip->numFiles; $i++) {
            $buffer = $zip->statIndex($i);
            $path = explode("/", $buffer["name"]);
            $name = str_replace(array("/", " "), array("--", "_"), array_pop($path));
            $dir = implode("/", $path);
            $extension = trim(strrchr($name, "."), ".");
            if ($name != "" && array_key_exists($extension, $cfg["file"]["filetyp"])) {
                $zip_content[$buffer["index"]] = array("name" => $name, "dir" => $dir, "file" => str_replace(array("/", " "), array("--", "_"), $buffer["name"]), "path" => $buffer["name"], "size" => $buffer["size"]);
            }
            // textdateien in eigenes array
            if (preg_match("/.*\\.txt\$/i", $name)) {
                $content = addslashes($zip->getFromIndex($buffer["index"]));
                $textfile = explode("\n", $content);
                $var_name = "";
                $array = array();
                // text wird in zeilen aufgesplittet und in abgelegt (vgl. $section bzw $cfg["fileed"]["zip_handling"]["sektions"])
                foreach ($textfile as $value) {
                    if (array_key_exists(strtolower(trim($value)), $section)) {
                        $var_name = $section[strtolower(trim($value))];
                        continue;
                    }
                    if ($var_name != "" && $value != "") {
                        if ($array[$var_name] != "") {
                            $array[$var_name] .= "\n";
                        }
                        $array[$var_name] .= trim($value);
                    }
                }
                $key = str_replace(array("/", " "), array("--", "_"), $buffer["name"]);
                $text_files[$key] = array("id" => $buffer["index"], "content" => addslashes(substr($zip->getFromIndex($buffer["index"]), 0, 400)));
                foreach ($array as $label => $value) {
                    $text_files[$key][$label] = $value;
                }
            } elseif (preg_match("/.*\\.csv\$/i", $name)) {
                $content = addslashes($zip->getFromIndex($buffer["index"]));
                $textfile = explode("\n", $content);
                foreach ($textfile as $value) {
                    if (trim($value) == "") {
                        continue;
                    }
                    $csv_info = explode(";", $value);
                    $key = str_replace(array("/", " "), array("--", "_"), array_shift($csv_info) . ".txt");
                    foreach ($section as $label) {
                        $text_files_csv[$key][$label] = array_shift($csv_info);
                    }
                }
            }
        }
        if (is_array($text_files) && is_array($text_files_csv)) {
            $text_files = array_merge($text_files, $text_files_csv);
        }
        // auspacken
        if ($extract_dest != "") {
            unset($_SESSION["zip_extracted"]);
            $i = 1;
            foreach ($zip_content as $key => $value) {
                // falls angegeben werden nur bestimmte unterordner abgearbeitet
                if (($restrict_dir == "" || in_array($value["dir"], $restrict)) && $value["name"] != "") {
                    // 1. datei auf den server schreiben
                    if (!is_array($text_files[$value["name"]])) {
                        $tmp_file = $extract_dest . str_replace(array("/", " "), array("--", "_"), $value["file"]);
                        $handle = fopen($tmp_file, "a");
                        fwrite($handle, $zip->getFromIndex($key));
                        fclose($handle);
                    } else {
                        // textdatei wird ausgelassen
                        unset($zip_content[$key]);
                        continue;
                    }
                    // 2. file ueberpruefen
                    $error = file_validate($tmp_file, $value["size"], $restrict_size, $restrict_type);
                    // 3. file weiterverarbeiten (umbenennen/loeschen)
                    if ($error == 0) {
                        $new_file = $_SESSION["uid"] . "_" . basename($tmp_file);
                        rename($tmp_file, dirname($tmp_file) . "/" . $new_file);
                        // session schreiben fuer weitere verarbeitung
                        if ($compid != "" && $restrict_type[strtolower(substr(strrchr($tmp_file, "."), 1))] == "img") {
                            $compilation = "#p" . $compid . "," . $i * 10 . "#";
                            $i++;
                        } else {
                            $compilation = "";
                        }
                        $new_file = $_SESSION["uid"] . "_" . basename($tmp_file);
                        $fdesc = $_POST["zip_fdesc"];
                        $funder = $_POST["zip_funder"];
                        $fhit = $_POST["zip_fhit"];
                        if ($text_files[basename($tmp_file) . ".txt"]["fdesc"] != "") {
                            $fdesc .= "\n" . $text_files[basename($tmp_file) . ".txt"]["fdesc"];
                        } elseif ($text_files[$value["name"] . ".txt"]["fdesc"] != "") {
                            $fdesc .= "\n" . $text_files[$value["name"] . ".txt"]["fdesc"];
                        }
                        if ($text_files[basename($tmp_file) . ".txt"]["funder"] != "") {
                            $funder .= "\n" . $text_files[basename($tmp_file) . ".txt"]["funder"];
                        } elseif ($text_files[$value["name"] . ".txt"]["funder"] != "") {
                            $funder .= "\n" . $text_files[$value["name"] . ".txt"]["funder"];
                        }
                        if ($text_files[basename($tmp_file) . ".txt"]["fhit"] != "") {
                            $fhit .= "\n" . $text_files[basename($tmp_file) . ".txt"]["fhit"];
                        } elseif ($text_files[$value["name"] . ".txt"]["fhit"] != "") {
                            $fhit .= "\n" . $text_files[$value["name"] . ".txt"]["fhit"];
                        }
                        $_SESSION["zip_extracted"][$new_file] = array("name" => $new_file, "compilation" => $compilation, "fdesc" => trim($fdesc), "funder" => trim($funder), "fhit" => trim($fhit), "wave_thru" => $wave_thru);
                        // zip_content soll die nicht auszupackenden dateien ausgeben
                        unset($zip_content[$key]);
                        if (is_array($text_files[basename($tmp_file) . ".txt"])) {
                            unset($zip_content[$text_files[basename($tmp_file) . ".txt"]["id"]]);
                        }
                    } else {
                        unlink($tmp_file);
                    }
                } else {
                    // echo "<p> Auspacken NICHT moeglich</p>";
                }
            }
        }
    }
    return $zip_content;
}
 // wohin schicken
 #n/a
 // +++
 // page basics
 if ($environment["parameter"][2] == "verify" && ($_POST["send"] != "" || $_POST["extension1"] != "" || $_POST["extension2"] != "")) {
     unset($dataloop["upload"]);
     // form eigaben pr�fen
     form_errors($form_options, $_POST);
     // evtl. zusaetzliche datensatz anlegen
     if ($ausgaben["form_error"] == "") {
         // funktions bereich fuer erweiterungen
         // ***
         ### put your code here ###
         foreach ($_FILES as $key => $value) {
             if ($value["name"] != "" || $value["size"] != 0) {
                 $error = file_validate($value["tmp_name"], $value["size"], $cfg["file"]["filesize"], $cfg["file"]["filetyp"], $key);
                 if ($error == 0) {
                     $newname = $cfg["file"]["base"]["maindir"] . $cfg["file"]["base"]["new"] . $_SESSION["uid"] . "_" . $value["name"];
                     rename($value["tmp_name"], $newname);
                     if (function_exists("zip_open")) {
                         // compilation
                         $buffer = compilation_list();
                         reset($buffer);
                         $new_comp = key($buffer) + 1;
                         zip_handling($newname, $cfg["file"]["base"]["maindir"] . $cfg["file"]["base"]["new"], $cfg["fileed"]["filetyp"], $cfg["fileed"]["filesize"], "selection", $new_comp, $cfg["fileed"]["zip_handling"]["sektions"]);
                     }
                 } else {
                     $ausgaben["form_error"] .= "Ergebnis: " . $file["name"] . " g(file_error" . $error . ")";
                 }
             }
         }