firefly-iii/app/Helpers/Attachments/AttachmentHelper.php

391 lines
12 KiB
PHP
Raw Normal View History

2015-07-18 02:49:29 -05:00
<?php
/**
* AttachmentHelper.php
2020-01-28 01:46:01 -06:00
* Copyright (c) 2019 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
2017-10-21 01:40:00 -05:00
*
* This program is distributed in the hope that it will be useful,
2017-10-21 01:40:00 -05:00
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
2017-10-21 01:40:00 -05:00
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
2015-07-18 02:49:29 -05:00
namespace FireflyIII\Helpers\Attachments;
use Crypt;
2018-09-27 06:54:59 -05:00
use FireflyIII\Exceptions\FireflyException;
2015-07-18 02:49:29 -05:00
use FireflyIII\Models\Attachment;
use Illuminate\Contracts\Encryption\DecryptException;
2019-02-13 10:38:41 -06:00
use Illuminate\Contracts\Filesystem\FileNotFoundException;
2015-07-18 02:49:29 -05:00
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
2019-02-13 10:38:41 -06:00
use Illuminate\Support\Facades\Storage;
2015-07-18 02:49:29 -05:00
use Illuminate\Support\MessageBag;
2017-06-12 12:58:32 -05:00
use Log;
2016-02-16 11:39:03 -06:00
use Symfony\Component\HttpFoundation\File\UploadedFile;
2017-06-05 04:12:50 -05:00
2015-07-18 02:49:29 -05:00
/**
2017-11-15 05:25:49 -06:00
* Class AttachmentHelper.
2015-07-18 02:49:29 -05:00
*/
class AttachmentHelper implements AttachmentHelperInterface
{
2018-07-07 14:17:46 -05:00
/** @var Collection All attachments */
public $attachments;
2018-07-07 14:17:46 -05:00
/** @var MessageBag All errors */
2015-07-18 02:49:29 -05:00
public $errors;
2018-07-07 14:17:46 -05:00
/** @var MessageBag All messages */
2015-07-18 02:49:29 -05:00
public $messages;
2018-07-07 14:17:46 -05:00
/** @var array Allowed mimes */
2017-01-14 12:43:33 -06:00
protected $allowedMimes = [];
2018-07-07 14:17:46 -05:00
/** @var int Max upload size. */
2017-01-14 12:43:33 -06:00
protected $maxUploadSize = 0;
2015-07-18 02:49:29 -05:00
2018-07-07 14:17:46 -05:00
/** @var \Illuminate\Contracts\Filesystem\Filesystem The disk where attachments are stored. */
protected $uploadDisk;
2018-02-28 14:32:59 -06:00
2015-07-18 02:49:29 -05:00
/**
2018-02-28 14:32:59 -06:00
* AttachmentHelper constructor.
2019-06-21 12:10:02 -05:00
* @codeCoverageIgnore
2015-07-18 02:49:29 -05:00
*/
public function __construct()
{
2018-04-02 07:42:07 -05:00
$this->maxUploadSize = (int)config('firefly.maxUploadSize');
2017-02-16 23:42:36 -06:00
$this->allowedMimes = (array)config('firefly.allowedMimes');
2015-07-18 15:17:31 -05:00
$this->errors = new MessageBag;
$this->messages = new MessageBag;
$this->attachments = new Collection;
$this->uploadDisk = Storage::disk('upload');
if ('testing' === config('app.env')) {
2019-06-07 11:20:15 -05:00
Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this)));
}
2015-07-18 02:49:29 -05:00
}
/**
2018-07-07 14:17:46 -05:00
* Returns the content of an attachment.
*
2018-06-01 15:04:52 -05:00
* @codeCoverageIgnore
*
* @param Attachment $attachment
*
* @return string
*/
public function getAttachmentContent(Attachment $attachment): string
{
$encryptedData = '';
try {
$encryptedData = $this->uploadDisk->get(sprintf('at-%d.data', $attachment->id));
} catch (FileNotFoundException $e) {
Log::error($e->getMessage());
}
try {
$unencryptedData = Crypt::decrypt($encryptedData); // verified
2019-02-13 10:38:41 -06:00
} catch (DecryptException|FileNotFoundException $e) {
2018-07-07 14:17:46 -05:00
Log::error(sprintf('Could not decrypt data of attachment #%d: %s', $attachment->id, $e->getMessage()));
$unencryptedData = $encryptedData;
}
return $unencryptedData;
}
2015-07-18 14:32:31 -05:00
/**
* Returns the file path relative to upload disk for an attachment,
2018-07-07 14:17:46 -05:00
*
2015-07-18 14:32:31 -05:00
* @param Attachment $attachment
2019-06-21 12:10:02 -05:00
* @codeCoverageIgnore
2015-07-18 15:17:31 -05:00
* @return string
2015-07-18 14:32:31 -05:00
*/
2016-02-18 00:21:48 -06:00
public function getAttachmentLocation(Attachment $attachment): string
2015-07-18 14:32:31 -05:00
{
2019-02-13 10:38:41 -06:00
return sprintf('%sat-%d.data', DIRECTORY_SEPARATOR, (int)$attachment->id);
2015-07-18 14:32:31 -05:00
}
/**
2018-07-07 14:17:46 -05:00
* Get all attachments.
2019-06-21 12:10:02 -05:00
* @codeCoverageIgnore
* @return Collection
*/
public function getAttachments(): Collection
{
return $this->attachments;
}
2016-01-19 06:59:54 -06:00
/**
2018-07-07 14:17:46 -05:00
* Get all errors.
*
2016-01-19 06:59:54 -06:00
* @return MessageBag
2019-06-21 12:10:02 -05:00
* @codeCoverageIgnore
2016-01-19 06:59:54 -06:00
*/
2016-02-18 00:21:48 -06:00
public function getErrors(): MessageBag
2016-01-19 06:59:54 -06:00
{
return $this->errors;
}
/**
2018-07-07 14:17:46 -05:00
* Get all messages.
*
2016-01-19 06:59:54 -06:00
* @return MessageBag
2019-06-21 12:10:02 -05:00
* @codeCoverageIgnore
2016-01-19 06:59:54 -06:00
*/
2016-02-18 00:21:48 -06:00
public function getMessages(): MessageBag
2016-01-19 06:59:54 -06:00
{
return $this->messages;
}
2018-06-23 23:51:22 -05:00
/**
* Uploads a file as a string.
*
* @param Attachment $attachment
* @param string $content
*
* @return bool
*/
public function saveAttachmentFromApi(Attachment $attachment, string $content): bool
{
$resource = tmpfile();
if (false === $resource) {
2018-08-25 13:45:42 -05:00
// @codeCoverageIgnoreStart
2018-06-23 23:51:22 -05:00
Log::error('Cannot create temp-file for file upload.');
return false;
2018-08-25 13:45:42 -05:00
// @codeCoverageIgnoreEnd
2018-06-23 23:51:22 -05:00
}
2019-10-20 09:17:43 -05:00
if ('' === $content) {
Log::error('Cannot upload empty file.');
return false;
}
2018-06-23 23:51:22 -05:00
$path = stream_get_meta_data($resource)['uri'];
fwrite($resource, $content);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path);
$allowedMime = config('firefly.allowedMimes');
2019-06-21 12:10:02 -05:00
if (!in_array($mime, $allowedMime, true)) {
2018-06-23 23:51:22 -05:00
Log::error(sprintf('Mime type %s is not allowed for API file upload.', $mime));
return false;
}
// is allowed? Save the file, without encryption.
$this->uploadDisk->put($attachment->fileName(), $content);
2018-06-23 23:51:22 -05:00
// update attachment.
$attachment->md5 = md5_file($path);
$attachment->mime = $mime;
2019-06-07 10:58:11 -05:00
$attachment->size = strlen($content);
$attachment->uploaded = true;
2018-06-23 23:51:22 -05:00
$attachment->save();
return true;
}
2015-07-18 02:49:29 -05:00
/**
2018-07-07 14:17:46 -05:00
* Save attachments that get uploaded with models, through the app.
*
2018-09-22 23:57:37 -05:00
* @param object $model
2016-12-28 06:02:56 -06:00
* @param array|null $files
2015-07-18 02:49:29 -05:00
*
* @return bool
2019-02-13 10:38:41 -06:00
* @throws FireflyException
2015-07-18 02:49:29 -05:00
*/
2018-09-22 23:57:37 -05:00
public function saveAttachmentsForModel(object $model, ?array $files): bool
2015-07-18 02:49:29 -05:00
{
2019-02-13 10:38:41 -06:00
if (!($model instanceof Model)) {
2018-09-30 04:57:51 -05:00
return false; // @codeCoverageIgnore
2018-09-22 23:57:37 -05:00
}
2019-10-20 09:17:43 -05:00
2019-06-07 11:20:15 -05:00
Log::debug(sprintf('Now in saveAttachmentsForModel for model %s', get_class($model)));
if (is_array($files)) {
2017-11-26 02:54:09 -06:00
Log::debug('$files is an array.');
2017-10-27 05:59:43 -05:00
/** @var UploadedFile $entry */
2016-12-28 06:02:56 -06:00
foreach ($files as $entry) {
2017-11-15 05:25:49 -06:00
if (null !== $entry) {
2016-12-28 06:02:56 -06:00
$this->processFile($entry, $model);
}
}
2017-10-27 05:59:43 -05:00
Log::debug('Done processing uploads.');
2015-07-18 02:49:29 -05:00
}
if (!is_array($files) || (is_array($files) && 0 === count($files))) {
2018-07-07 14:17:46 -05:00
Log::debug('Array of files is not an array. Probably nothing uploaded. Will not store attachments.');
}
2015-07-18 02:49:29 -05:00
return true;
}
/**
2018-07-07 14:17:46 -05:00
* Check if a model already has this file attached.
*
2015-07-18 02:49:29 -05:00
* @param UploadedFile $file
* @param Model $model
*
* @return bool
*/
2016-02-18 00:21:48 -06:00
protected function hasFile(UploadedFile $file, Model $model): bool
2015-07-18 02:49:29 -05:00
{
$md5 = md5_file($file->getRealPath());
$name = $file->getClientOriginalName();
2019-06-07 11:20:15 -05:00
$class = get_class($model);
2018-07-07 14:17:46 -05:00
/** @noinspection PhpUndefinedFieldInspection */
$count = $model->user->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count();
$result = false;
if ($count > 0) {
$msg = (string)trans('validation.file_already_attached', ['name' => $name]);
2015-07-18 15:17:31 -05:00
$this->errors->add('attachments', $msg);
2017-10-27 05:59:43 -05:00
Log::error($msg);
2018-07-07 14:17:46 -05:00
$result = true;
}
2018-07-07 14:17:46 -05:00
return $result;
2015-07-18 02:49:29 -05:00
}
2015-07-18 15:17:31 -05:00
/**
2018-07-07 14:17:46 -05:00
* Process the upload of a file.
*
2015-07-18 15:17:31 -05:00
* @param UploadedFile $file
* @param Model $model
*
2018-07-07 14:17:46 -05:00
* @return Attachment|null
* @throws \Illuminate\Contracts\Encryption\EncryptException
2018-09-27 06:54:59 -05:00
* @throws FireflyException
2015-07-18 15:17:31 -05:00
*/
2018-07-07 14:17:46 -05:00
protected function processFile(UploadedFile $file, Model $model): ?Attachment
2015-07-18 15:17:31 -05:00
{
2017-11-26 02:54:09 -06:00
Log::debug('Now in processFile()');
2015-07-18 15:17:31 -05:00
$validation = $this->validateUpload($file, $model);
2018-07-07 14:17:46 -05:00
$attachment = null;
if (false !== $validation) {
$attachment = new Attachment; // create Attachment object.
/** @noinspection PhpUndefinedFieldInspection */
$attachment->user()->associate($model->user);
$attachment->attachable()->associate($model);
$attachment->md5 = md5_file($file->getRealPath());
$attachment->filename = $file->getClientOriginalName();
$attachment->mime = $file->getMimeType();
$attachment->size = $file->getSize();
$attachment->uploaded = false;
2018-07-07 14:17:46 -05:00
$attachment->save();
Log::debug('Created attachment:', $attachment->toArray());
2019-02-13 10:38:41 -06:00
$fileObject = $file->openFile();
2018-07-07 14:17:46 -05:00
$fileObject->rewind();
2018-09-27 06:54:59 -05:00
2019-02-13 10:38:41 -06:00
if (0 === $file->getSize()) {
2018-09-30 04:57:51 -05:00
throw new FireflyException('Cannot upload empty or non-existent file.'); // @codeCoverageIgnore
2018-09-27 06:54:59 -05:00
}
2018-07-07 14:17:46 -05:00
$content = $fileObject->fread($file->getSize());
2019-06-07 10:58:11 -05:00
Log::debug(sprintf('Full file length is %d and upload size is %d.', strlen($content), $file->getSize()));
2018-07-07 14:17:46 -05:00
// store it:
$this->uploadDisk->put($attachment->fileName(), $content);
2018-07-24 23:45:25 -05:00
$attachment->uploaded = true; // update attachment
2018-07-07 14:17:46 -05:00
$attachment->save();
$this->attachments->push($attachment);
$name = e($file->getClientOriginalName()); // add message:
$msg = (string)trans('validation.file_attached', ['name' => $name]);
$this->messages->add('attachments', $msg);
2015-07-18 15:17:31 -05:00
}
2015-07-18 02:49:29 -05:00
return $attachment;
}
/**
2018-07-07 14:17:46 -05:00
* Verify if the mime of a file is valid.
*
* @param UploadedFile $file
*
* @return bool
*/
2016-02-18 00:21:48 -06:00
protected function validMime(UploadedFile $file): bool
2015-07-18 02:49:29 -05:00
{
2017-11-26 02:54:09 -06:00
Log::debug('Now in validMime()');
2015-07-18 15:17:31 -05:00
$mime = e($file->getMimeType());
$name = e($file->getClientOriginalName());
Log::debug(sprintf('Name is %s, and mime is %s', $name, $mime));
2017-11-26 02:54:09 -06:00
Log::debug('Valid mimes are', $this->allowedMimes);
2018-07-07 14:17:46 -05:00
$result = true;
2015-07-18 02:49:29 -05:00
2019-06-21 12:10:02 -05:00
if (!in_array($mime, $this->allowedMimes, true)) {
$msg = (string)trans('validation.file_invalid_mime', ['name' => $name, 'mime' => $mime]);
2015-07-18 15:17:31 -05:00
$this->errors->add('attachments', $msg);
2017-10-27 05:59:43 -05:00
Log::error($msg);
2015-07-18 02:49:29 -05:00
2018-07-07 14:17:46 -05:00
$result = false;
2015-07-18 02:49:29 -05:00
}
2018-07-07 14:17:46 -05:00
return $result;
2015-07-18 02:49:29 -05:00
}
/**
2018-07-07 14:17:46 -05:00
* Verify if the size of a file is valid.
*
* @codeCoverageIgnore
2017-06-05 04:12:50 -05:00
*
* @param UploadedFile $file
*
* @return bool
*/
2016-02-18 00:21:48 -06:00
protected function validSize(UploadedFile $file): bool
2015-07-18 02:49:29 -05:00
{
2018-07-07 14:17:46 -05:00
$size = $file->getSize();
$name = e($file->getClientOriginalName());
$result = true;
2015-07-18 02:49:29 -05:00
if ($size > $this->maxUploadSize) {
$msg = (string)trans('validation.file_too_large', ['name' => $name]);
2015-07-18 15:17:31 -05:00
$this->errors->add('attachments', $msg);
2017-10-27 05:59:43 -05:00
Log::error($msg);
2015-07-18 02:49:29 -05:00
2018-07-07 14:17:46 -05:00
$result = false;
2015-07-18 02:49:29 -05:00
}
2018-07-07 14:17:46 -05:00
return $result;
2015-07-18 02:49:29 -05:00
}
/**
2018-07-07 14:17:46 -05:00
* Verify if the file was uploaded correctly.
*
2016-01-19 06:59:54 -06:00
* @param UploadedFile $file
* @param Model $model
*
* @return bool
2015-07-18 02:49:29 -05:00
*/
2016-02-18 00:21:48 -06:00
protected function validateUpload(UploadedFile $file, Model $model): bool
2015-07-18 02:49:29 -05:00
{
2017-11-26 02:54:09 -06:00
Log::debug('Now in validateUpload()');
2018-07-07 14:17:46 -05:00
$result = true;
2016-01-19 06:59:54 -06:00
if (!$this->validMime($file)) {
2018-07-07 14:17:46 -05:00
$result = false;
2016-01-19 06:59:54 -06:00
}
2019-10-20 09:17:43 -05:00
if (0 === $file->getSize()) {
Log::error('Cannot upload empty file.');
$result = false;
}
2018-08-25 13:45:42 -05:00
// @codeCoverageIgnoreStart
// can't seem to reach this point.
2018-07-07 14:17:46 -05:00
if (true === $result && !$this->validSize($file)) {
$result = false;
2016-01-19 06:59:54 -06:00
}
2018-08-25 13:45:42 -05:00
// @codeCoverageIgnoreEnd
2018-07-07 14:17:46 -05:00
if (true === $result && $this->hasFile($file, $model)) {
$result = false;
2016-01-19 06:59:54 -06:00
}
2015-07-18 02:49:29 -05:00
2018-07-07 14:17:46 -05:00
return $result;
2015-07-18 02:49:29 -05:00
}
2015-07-19 02:38:44 -05:00
}