Skip to content

Commit

Permalink
Added custom user avatars
Browse files Browse the repository at this point in the history
  • Loading branch information
ssddanbrown committed Dec 9, 2015
1 parent db3acab commit 8f7c642
Show file tree
Hide file tree
Showing 16 changed files with 228 additions and 66 deletions.
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ GOOGLE_APP_SECRET=false
# URL used for social login redirects, NO TRAILING SLASH
APP_URL=http://bookstack.dev

# External services
USE_GRAVATAR=true

# Mail settings
MAIL_DRIVER=smtp
MAIL_HOST=localhost
Expand Down
13 changes: 12 additions & 1 deletion app/Http/Controllers/ImageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function __construct(Image $image, File $file, ImageRepo $imageRepo)


/**
* Get all gallery images, Paginated
* Get all images for a specific type, Paginated
* @param int $page
* @return \Illuminate\Http\JsonResponse
*/
Expand All @@ -43,6 +43,17 @@ public function getAllByType($type, $page = 0)
return response()->json($imgData);
}

/**
* Get all images for a user.
* @param int $page
* @return \Illuminate\Http\JsonResponse
*/
public function getAllForUserType($page = 0)
{
$imgData = $this->imageRepo->getPaginatedByType('user', $page, 24, $this->currentUser->id);
return response()->json($imgData);
}


/**
* Handles image uploads for use on pages.
Expand Down
2 changes: 1 addition & 1 deletion app/Http/Controllers/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public function store(Request $request)
$this->checkPermission('user-create');
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:5',
'password-confirm' => 'required|same:password',
'role' => 'required|exists:roles,id'
Expand Down
3 changes: 3 additions & 0 deletions app/Http/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@

// Image routes
Route::group(['prefix' => 'images'], function() {
// Get for user images
Route::get('/user/all', 'ImageController@getAllForUserType');
Route::get('/user/all/{page}', 'ImageController@getAllForUserType');
// Standard get, update and deletion for all types
Route::get('/thumb/{id}/{width}/{height}/{crop}', 'ImageController@getThumbnail');
Route::put('/update/{imageId}', 'ImageController@update');
Expand Down
6 changes: 4 additions & 2 deletions app/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
namespace BookStack;


use Illuminate\Database\Eloquent\Model;
use Images;

class Image
class Image extends Model
{
use Ownable;

Expand All @@ -16,9 +17,10 @@ class Image
* @param int $width
* @param int $height
* @param bool|false $hardCrop
* @return string
*/
public function getThumb($width, $height, $hardCrop = false)
{
Images::getThumbnail($this, $width, $height, $hardCrop);
return Images::getThumbnail($this, $width, $height, $hardCrop);
}
}
18 changes: 12 additions & 6 deletions app/Repos/ImageRepo.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class ImageRepo
* @param Image $image
* @param ImageService $imageService
*/
public function __construct(Image $image,ImageService $imageService)
public function __construct(Image $image, ImageService $imageService)
{
$this->image = $image;
$this->imageService = $imageService;
Expand All @@ -40,12 +40,18 @@ public function getById($id)
* @param string $type
* @param int $page
* @param int $pageSize
* @param bool|int $userFilter
* @return array
*/
public function getPaginatedByType($type, $page = 0, $pageSize = 24)
public function getPaginatedByType($type, $page = 0, $pageSize = 24, $userFilter = false)
{
$images = $this->image->where('type', '=', strtolower($type))
->orderBy('created_at', 'desc')->skip($pageSize * $page)->take($pageSize + 1)->get();
$images = $this->image->where('type', '=', strtolower($type));

if ($userFilter !== false) {
$images = $images->where('created_by', '=', $userFilter);
}

$images = $images->orderBy('created_at', 'desc')->skip($pageSize * $page)->take($pageSize + 1)->get();
$hasMore = count($images) > $pageSize;

$returnImages = $images->take(24);
Expand All @@ -54,7 +60,7 @@ public function getPaginatedByType($type, $page = 0, $pageSize = 24)
});

return [
'images' => $returnImages,
'images' => $returnImages,
'hasMore' => $hasMore
];
}
Expand All @@ -67,7 +73,7 @@ public function getPaginatedByType($type, $page = 0, $pageSize = 24)
*/
public function saveNew(UploadedFile $uploadFile, $type)
{
$image = $this->imageService->saveNew($this->image, $uploadFile, $type);
$image = $this->imageService->saveNewFromUpload($uploadFile, $type);
$this->loadThumbs($image);
return $image;
}
Expand Down
74 changes: 66 additions & 8 deletions app/Services/ImageService.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php namespace BookStack\Services;

use BookStack\Image;
use BookStack\User;
use Intervention\Image\ImageManager;
use Illuminate\Contracts\Filesystem\Factory as FileSystem;
use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
Expand Down Expand Up @@ -34,11 +35,48 @@ public function __construct(ImageManager $imageTool, FileSystem $fileSystem, Cac
$this->cache = $cache;
}

public function saveNew(Image $image, UploadedFile $uploadedFile, $type)
/**
* Saves a new image from an upload.
* @param UploadedFile $uploadedFile
* @param string $type
* @return mixed
*/
public function saveNewFromUpload(UploadedFile $uploadedFile, $type)
{
$imageName = $uploadedFile->getClientOriginalName();
$imageData = file_get_contents($uploadedFile->getRealPath());
return $this->saveNew($imageName, $imageData, $type);
}


/**
* Gets an image from url and saves it to the database.
* @param $url
* @param string $type
* @param bool|string $imageName
* @return mixed
* @throws \Exception
*/
private function saveNewFromUrl($url, $type, $imageName = false)
{
$imageName = $imageName ? $imageName : basename($url);
$imageData = file_get_contents($url);
if($imageData === false) throw new \Exception('Cannot get image from ' . $url);
return $this->saveNew($imageName, $imageData, $type);
}

/**
* Saves a new image
* @param string $imageName
* @param string $imageData
* @param string $type
* @return Image
*/
private function saveNew($imageName, $imageData, $type)
{
$storage = $this->getStorage();
$secureUploads = Setting::get('app-secure-images');
$imageName = str_replace(' ', '-', $uploadedFile->getClientOriginalName());
$imageName = str_replace(' ', '-', $imageName);

if ($secureUploads) $imageName = str_random(16) . '-' . $imageName;

Expand All @@ -48,14 +86,14 @@ public function saveNew(Image $image, UploadedFile $uploadedFile, $type)
}
$fullPath = $imagePath . $imageName;

$storage->put($fullPath, file_get_contents($uploadedFile->getRealPath()));
$storage->put($fullPath, $imageData);

$userId = auth()->user()->id;
$image = $image->forceCreate([
'name' => $imageName,
'path' => $fullPath,
'url' => $this->getPublicUrl($fullPath),
'type' => $type,
$image = Image::forceCreate([
'name' => $imageName,
'path' => $fullPath,
'url' => $this->getPublicUrl($fullPath),
'type' => $type,
'created_by' => $userId,
'updated_by' => $userId
]);
Expand Down Expand Up @@ -137,6 +175,26 @@ public function destroyImage(Image $image)
return true;
}

/**
* Save a gravatar image and set a the profile image for a user.
* @param User $user
* @param int $size
* @return mixed
*/
public function saveUserGravatar(User $user, $size = 500)
{
if (!env('USE_GRAVATAR', false)) return false;
$emailHash = md5(strtolower(trim($user->email)));
$url = 'http://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
$imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
$image = $this->saveNewFromUrl($url, 'user', $imageName);
$image->created_by = $user->id;
$image->save();
$user->avatar()->associate($image);
$user->save();
return $image;
}

/**
* Get the storage that will be used for storing images.
* @return FileSystemInstance
Expand Down
15 changes: 12 additions & 3 deletions app/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordCon
*
* @var array
*/
protected $fillable = ['name', 'email', 'password'];
protected $fillable = ['name', 'email', 'password', 'image_id'];

/**
* The attributes excluded from the model's JSON form.
Expand Down Expand Up @@ -145,8 +145,17 @@ public function hasSocialAccount($socialDriver = false)
*/
public function getAvatar($size = 50)
{
$emailHash = md5(strtolower(trim($this->email)));
return '//www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
if ($this->image_id === 0 || $this->image_id === null) return '/user_avatar.png';
return $this->avatar->getThumb($size, $size, true);
}

/**
* Get the avatar for the user.
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function avatar()
{
return $this->belongsTo('BookStack\Image', 'image_id');
}

/**
Expand Down
31 changes: 31 additions & 0 deletions database/migrations/2015_12_09_195748_add_user_avatars.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddUserAvatars extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->integer('image_id')->default(0);
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('image_id');
});
}
}
Binary file added public/user_avatar.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 1 addition & 24 deletions resources/assets/js/components/image-manager.vue
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,6 @@
imageType: {
type: String,
required: true
},
resizeWidth: {
type: String
},
resizeHeight: {
type: String
},
resizeCrop: {
type: Boolean
}
},
Expand Down Expand Up @@ -137,21 +128,7 @@
},
returnCallback: function (image) {
var _this = this;
var isResized = _this.resizeWidth && _this.resizeHeight;
if (!isResized) {
_this.callback(image);
return;
}
var cropped = _this.resizeCrop ? 'true' : 'false';
var requestString = '/images/thumb/' + image.id + '/' + _this.resizeWidth + '/' + _this.resizeHeight + '/' + cropped;
_this.$http.get(requestString, function(data) {
image.thumbs.custom = data.url;
_this.callback(image);
});
this.callback(image);
},
imageClick: function (image) {
Expand Down
Loading

0 comments on commit 8f7c642

Please sign in to comment.