Pony.fm/app/Models/Image.php

185 lines
5.9 KiB
PHP
Raw Normal View History

2015-08-30 14:29:12 +02:00
<?php
/**
* Pony.fm - A community for pony fan music.
* Copyright (C) 2015 Peter Deltchev
*
* 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.
*
* This program is distributed in the hope that it will be useful,
* 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.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Poniverse\Ponyfm\Models;
2015-08-31 14:35:47 +02:00
use External;
2015-08-30 14:29:12 +02:00
use Illuminate\Database\Eloquent\Model;
use Config;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\File\UploadedFile;
2015-08-30 14:29:12 +02:00
2016-01-01 01:36:08 +01:00
/**
* Poniverse\Ponyfm\Models\Image
*
* @property integer $id
* @property string $filename
* @property string $mime
* @property string $extension
* @property integer $size
* @property string $hash
* @property integer $uploaded_by
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*/
2015-08-30 14:29:12 +02:00
class Image extends Model
{
const NORMAL = 1;
const ORIGINAL = 2;
const THUMBNAIL = 3;
const SMALL = 4;
public static $ImageTypes = [
self::NORMAL => ['id' => self::NORMAL, 'name' => 'normal', 'width' => 350, 'height' => 350],
self::ORIGINAL => ['id' => self::ORIGINAL, 'name' => 'original', 'width' => null, 'height' => null],
self::SMALL => ['id' => self::SMALL, 'name' => 'small', 'width' => 100, 'height' => 100],
self::THUMBNAIL => ['id' => self::THUMBNAIL, 'name' => 'thumbnail', 'width' => 50, 'height' => 50]
];
public static function getImageTypeFromName($name)
{
foreach (self::$ImageTypes as $cover) {
if ($cover['name'] != $name) {
continue;
}
return $cover;
}
return null;
}
/**
* @param UploadedFile $file
* @param int|User $user
* @param bool $forceReupload forces the image to be re-processed even if a matching hash is found
* @return Image
* @throws \Exception
*/
public static function upload(UploadedFile $file, $user, bool $forceReupload = false)
2015-08-30 14:29:12 +02:00
{
$userId = $user;
if ($user instanceof User) {
$userId = $user->id;
}
$hash = md5_file($file->getPathname());
$image = Image::whereHash($hash)->whereUploadedBy($userId)->first();
if ($image) {
if ($forceReupload) {
// delete existing versions of the image
$filenames = scandir($image->getDirectory());
$imagePrefix = $image->id.'_';
Laravel 5.2 Update (#106) * Adopt PSR-2 coding style The Laravel framework adopts the PSR-2 coding style in version 5.1. Laravel apps *should* adopt this coding style as well. Read the [PSR-2 coding style guide][1] for more details and check out [PHPCS][2] to use as a code formatting tool. [1]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md [2]: https://github.com/squizlabs/PHP_CodeSniffer * Adopt PHP short array syntax Laravel 5 adopted the short array syntax which became available in PHP 5.4. * Remove SelfHandling from Jobs Jobs are self handling by default in Laravel 5.2. * Add new exceptions to `$dontReport` property * Shift core files * Shift Middleware Laravel 5.2 adjusts the `Guard` object used within middleware. In addition, new `can` and `throttles` middleware were added. * Shift Input to Request facade Laravel 5.2 no longer registers the `Input` facade by default. Laravel now prefers using the `Request` facade or the `$request` object within *Controllers* instead. Review the [HTTP Requests][1] documentation for more details. [1]: https://laravel.com/docs/5.2/requests * Shift configuration Laravel 5.2 introduces the `env` app configuration option and removes the `pretend` mail configuration option. In addition, a few of the default `providers` and `aliases` bindings were removed. * Shift Laravel dependencies * Shift cleanup * Updated composer.lock * Updated Middleware to 5.2 * Config update for Laravel 5.2 * [Laravel 5.2] Updated validation strings * Updated auth config * Updated to use middleware groups * Added laravel 5.2 sessions migration
2016-09-30 00:26:31 +02:00
$filenames = array_filter($filenames, function (string $filename) use ($imagePrefix) {
return Str::startsWith($filename, $imagePrefix);
});
foreach ($filenames as $filename) {
unlink($image->getDirectory().'/'.$filename);
}
} else {
return $image;
}
} else {
$image = new Image();
}
2015-08-30 14:29:12 +02:00
try {
$image->uploaded_by = $userId;
$image->size = $file->getSize();
$image->filename = $file->getClientOriginalName();
$image->extension = $file->getClientOriginalExtension();
$image->mime = $file->getMimeType();
$image->hash = $hash;
$image->save();
$image->ensureDirectoryExists();
foreach (self::$ImageTypes as $coverType) {
2015-12-27 10:43:43 +01:00
if ($coverType['id'] === self::ORIGINAL && $image->mime === 'image/jpeg') {
$command = 'cp "'.$file->getPathname().'" '.$image->getFile($coverType['id']);
2015-12-27 10:43:43 +01:00
} else {
// ImageMagick options reference: http://www.imagemagick.org/script/command-line-options.php
$command = 'convert 2>&1 "'.$file->getPathname().'" -background white -alpha remove -alpha off -strip';
2015-12-27 10:43:43 +01:00
if ($image->mime === 'image/jpeg') {
$command .= ' -quality 100 -format jpeg';
} else {
$command .= ' -quality 95 -format png';
}
if (isset($coverType['width']) && isset($coverType['height'])) {
$command .= " -thumbnail ${coverType['width']}x${coverType['height']}^ -gravity center -extent ${coverType['width']}x${coverType['height']}";
}
$command .= ' "'.$image->getFile($coverType['id']).'"';
2015-08-30 14:29:12 +02:00
}
External::execute($command);
2016-01-03 20:10:48 +01:00
chmod($image->getFile($coverType['id']), 0644);
2015-08-30 14:29:12 +02:00
}
return $image;
} catch (\Exception $e) {
$image->delete();
throw $e;
}
}
protected $table = 'images';
public function getUrl($type = self::NORMAL)
{
$type = self::$ImageTypes[$type];
2015-12-27 10:43:43 +01:00
return action('ImagesController@getImage', ['id' => $this->id, 'type' => $type['name'], 'extension' => $this->extension]);
2015-08-30 14:29:12 +02:00
}
public function getFile($type = self::NORMAL)
{
return $this->getDirectory().'/'.$this->getFilename($type);
2015-08-30 14:29:12 +02:00
}
public function getFilename($type = self::NORMAL)
{
$typeInfo = self::$ImageTypes[$type];
return $this->id.'_'.$typeInfo['name'].'.'.$this->extension;
2015-08-30 14:29:12 +02:00
}
public function getDirectory()
{
$dir = (string) (floor($this->id / 100) * 100);
2015-08-30 14:29:12 +02:00
return Config::get('ponyfm.files_directory').'/images/'.$dir;
2015-08-30 14:29:12 +02:00
}
public function ensureDirectoryExists()
{
$destination = $this->getDirectory();
umask(0);
if (!is_dir($destination)) {
mkdir($destination, 0777, true);
2015-08-30 14:29:12 +02:00
}
}
}