_uploadFile

Uploads the file to the directory

@param \Cake\ORM\Entity $entity Entity to upload from.
@param string $field Field to use.
@param array $options Options.
@return bool
334332
protected function _uploadFile($entity, $field, $options = [])
    {
        $_upload = $this->_uploads[$field];
        $uploadPath = $this->_getPath($entity, $field, ['file' => true]);

        // creating the path if not exists
        if (!is_dir($this->_getPath($entity, $field, ['root' => false, 'file' => false]))) {
            $this->_mkdir($this->_getPath($entity, $field, ['root' => false, 'file' => false]), 0777, true);
        }

        // upload the file and return true
        if ($this->_moveUploadedFile($_upload['tmp_name'], $uploadPath)) {
            return true;
        }
        return false;
    }
612577
public function putFile($path, $file, $options = [])
    {
        return $this->putFileAs($path, $file, $file->hashName(), $options);
    }
690432
public function afterDelete(Event $event, EntityInterface $entity, ArrayObject $options) {
		$field = $this->getConfig('field');

		$value = $entity->get($field);
		if (!$value) {
			return;
		}

		$conditions = $this->buildConditions($entity);

		$order = $this->getConfig('findOrder');
		if ($order === null) {
			$order = [];
			if ($this->_table->getSchema()->getColumn('modified')) {
				$order['modified'] = 'DESC';
			}
		}
		$entity = $this->_table->find()->where($conditions)->order($order)->first();
		if (!$entity) {
			// This should be caught with a validation rule if at least one "primary" must exist
			return;
		}

		$entity->set($field, true);
		$this->_table->saveOrFail($entity);
	}
509002
public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options) {
		$formField = $this->_config['formField'];
		$field = $this->_config['field'];

		$PasswordHasher = $this->_getPasswordHasher($this->_config['passwordHasher']);

		if ($entity->get($formField) !== null) {
			$entity->set($field, $PasswordHasher->hash($entity->get($formField)));

			if (!$entity->get($field)) {
				throw new RuntimeException('Empty field');
			}

			$entity->unsetProperty($formField);
			//$entity->set($formField, null);

			if ($this->_config['confirm']) {
				$formFieldRepeat = $this->_config['formFieldRepeat'];
				$entity->unsetProperty($formFieldRepeat);
			}
			if ($this->_config['current']) {
				$formFieldCurrent = $this->_config['formFieldCurrent'];
				$entity->unsetProperty($formFieldCurrent);
			}
		} else {
			// To help mitigate timing-based user enumeration attacks.
			$PasswordHasher->hash('');
		}
	}
911890
public function scheduleForUpload($value, $entity, $field)
    {
        if (is_string($value)) {
            // try to locate the file on disk
            $value = new FixtureFile($this->fileManager->getFilePath($entity, $field, $value));
        }

        if ($value instanceof File) {
            $replaceFile = isset($value->metaData['keep_previous_filename']) and $value->metaData['keep_previous_filename'];
            $path = $this->fileManager->prepare($value, $entity, $field, !$replaceFile);
            $fileName = basename($path);
            PropertyHelper::setValue($entity, $field, $fileName);
            $this->unitOfWork[spl_object_hash($entity)][$field]['save'] = function ($fm) use ($value, $path) {
                $fm->save($value, $path);
            };
            return $fileName;
        } else {
            throw new \InvalidArgumentException("Invalid argument to scheduleForUpload(): " . gettype($value));
        }
    }
1304508
public function uploadImage($imageFile, $field = null)
    {
        $this->uploadFieldName = $this->getUploadFieldName($field);
        $this->uploadFieldOptions = $this->getUploadFieldOptions($this->uploadFieldName);

        // validate it
        $this->validateImage($imageFile, $this->uploadFieldName, $this->uploadFieldOptions);

        // handle upload
        $filePath = $this->hasFileField($this->uploadFieldName)
            ? $this->handleFileUpload($imageFile)
            : $this->handleImageUpload($imageFile);

        // hold old file
        $currentFile = $this->getOriginal($this->uploadFieldName);

        // update the model with field name
        $this->updateModel($filePath, $this->uploadFieldName);

        // delete old file
        if ($currentFile != $filePath) {
            $this->deleteImage($currentFile);
        }
    }
444282
public function getUploadFieldOptions($field = null)
    {
        // get first option if no field provided
        if (is_null($field)) {
            $imagesFields = $this->getDefinedUploadFields();

            if (!$imagesFields) {
                throw new InvalidUploadFieldException(
                    'No upload fields are defined in $imageFields/$fileFields array on model.'
                );
            }

            $fieldKey = array_first(array_keys($imagesFields));
            $options = is_int($fieldKey) ? [] : array_first($imagesFields);

            return $options;
        }

        // check if provided filed defined
        if (!$this->hasImageField($field)) {
            throw new InvalidUploadFieldException(
                'Image/File field `' . $field . '` is not defined in $imageFields/$fileFields array on model.'
            );
        }

        return array_get($this->getDefinedUploadFields(), $field, []);
    }
1052518
public function replaceFile(File $fileEntity, UploadedFile $file)
	{
		$entityManager = $this->getDoctrineEntityManager();
		$oldFileIsImage = $fileEntity instanceof Image;
		$newFileIsImage = $this->isMimeTypeImage($file->getMimeType());

		if ($oldFileIsImage !== $newFileIsImage) {
			throw new Exception\UploadFilterException(self::VALIDATION_IMAGE_TO_FILE_REPLACE_MESSAGE_KEY, 'New file should be image too');
		}

		$originalFile = clone($fileEntity);
		$entityManager->detach($originalFile);

		// setting new data
		// The name is not changed by Bug #6756
//		$fileEntity->setFileName($file['name']);
		$fileEntity->setSize($file->getSize());
		$fileEntity->setMimeType($file->getMimeType());

		// This must be call before removing the old file
		$this->validateFileUpload($fileEntity, $file->getPathname());

		$this->removeFileInFileSystem($originalFile);

		$this->storeFileData($fileEntity, $file->getPathname());

		// additional jobs for images
		if ($fileEntity instanceof Image) {
			
			$imageProcessor  = $this->getImageResizer();
			// store original size
			$imageInfo = $imageProcessor->getImageInfo($fileEntity);
			$fileEntity->setWidth($imageInfo->getWidth());
			$fileEntity->setHeight($imageInfo->getHeight());
			// reprocess sizes
			$this->recreateImageSizes($fileEntity);
		}

		$fileEntity->setModificationTime();

		$entityManager->flush();
	}
765249
public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options)
    {
        parent::beforeSave($event, $entity, $options);

        list($width, $height) = getimagesize($entity->path);
        $entity->size = compact('width', 'height');
    }
376224
public function fileOpen(string $path, string $mode, int $options)
    {
        $entity = $this->getEntity($path);

        $filePointer = null;
        if (null !== $entity) {
            $exists = $entity->file_exists();

            if ($exists && !$entity->is_file()) {
                $filePointer = null;
            } else {
                $fopenWillFail = false;
                $mode = strtolower($mode);
                if ('r' != $mode) {
                    $isVirtual = ($entity instanceof VirtualInterface);
                    if (!$exists || !$isVirtual) {
                        $tmpPath = $this->tempnam();
                        $basename = basename($path);

                        if ($exists) {
                            if ('x' == $mode || 'x+' == $mode) {
                                $fopenWillFail = true;
                            } else {
                                copy($entity->path(), $tmpPath);
                            }
                        }
                        if (!$fopenWillFail) {
                            $entity = Virtual::newInstance(
                                $entity, $tmpPath, $basename
                            );

                            $changes = $this->getChanges();
                            $changes->add($path, $entity);
                        }
                    }
                }

                if ($fopenWillFail) {
                    $entity = null;
                } else {
                    if ($options & STREAM_REPORT_ERRORS) {
                        $filePointer = fopen($entity->path(), $mode);
                    } else {
                        $filePointer = @fopen($entity->path(), $mode);
                    }
                }
            }
        }

        return $filePointer;
    }
306210
public function upload(ImageInterface $image, $path, array $options = [])
    {
        $itemLength  = $this->adapter->directoryLength($this->fileSystem->getCurrentDirectory());
        $image       = $this->fileSystem->hydrateImageInfo($image, $path);
        $destination = $this->fileSystem->defineImagePath($image, $itemLength);

        $this->adapter->upload($path, $destination, $options);
        $image->setPath($destination);

        return $image;
    }
1370553
protected function _injectEntity(EntityInterface $entity, ArrayObject $options, array $fields)
    {
        $new = $entity->isNew() !== false;

        foreach ($fields as $field => $when) {
            if (!in_array($when, ['always', 'new', 'existing'])) {
                throw new UnexpectedValueException(sprintf(
                    'When should be one of "always", "new" or "existing". The passed value "%s" is invalid',
                    $when
                ));
            }

            if ($entity->isDirty($field)) {
                continue;
            }

            if ($when === 'always' ||
                ($when === 'new' && $new) ||
                ($when === 'existing' && !$new)
            ) {
                $entity->set(
                    $field,
                    Hash::get(
                        $options,
                        $this->getConfig('propertiesMap.' . $field)
                    )
                );
            }
        }
    }
1322356
public function storeFile($file, array &$document, array $options = [])
    {
        $this->log([
            'storeFile' => true,
            'count' => count($document),
            'options' => $options,
        ]);

        return parent::storeFile($file, $document, $options);
    }
995870
public function autoIncrementFieldValue(Event $event, EntityInterface $entity, ArrayObject $options) : void
    {
        $table = $event->getSubject();

        if (!$table instanceof Table) {
            return;
        }

        $fields = $this->getAutoIncrementFields($table);

        // skip if no auto-increment fields are defined
        if (empty($fields)) {
            return;
        }

        // skip modifying auto-increment field(s) on existing records.
        if (! $entity->isNew()) {
            foreach (array_keys($fields) as $field) {
                $entity->unsetProperty((string)$field);
            }

            return;
        }

        foreach ($fields as $field => $options) {
            // get max value
            $query = $table->find('withTrashed');

            try {
                $max = $query->select([$field => $query->func()->max($field)])
                    ->enableHydration(true)
                    ->firstOrFail();
                Assert::isInstanceOf($max, EntityInterface::class);
                $max = (float)$max->get((string)$field);
            } catch (RecordNotFoundException $e) {
                $max = 0;
            }

            if (empty($options['min'])) {
                $entity->set((string)$field, $max + 1);

                continue;
            }

            // if value is less than the allowed minimum, then set it to the minimum.
            $max = $max < $options['min'] ? $options['min'] : $max + 1;

            $entity->set((string)$field, $max);
        }
    }
786263
public function setFieldValue($entity, $field, $value)
    {
        $this->reflFields[$field]->setValue($entity, $value);
    }
975618
public function save(EntityMetadata $entity, array $options = [])
    {
        return new TokenSequencer($this->tokenFactory, self::TYPE_SAVE, $entity, $options);
    }
609863
public static function saveAs($file, $options = [])
    {
        if (!($file instanceof UploadedFile)) {
            $file = UploadedFile::getInstanceByName($file);
        }
        $options['file'] = $file;
        $model = new static($options);
        return $model->save() ? $model : false;
    }