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
This commit is contained in:
Laravel Shift 2016-09-29 18:26:31 -04:00 committed by Adam Lavin
parent 9b31b48f37
commit 00f24a5c12
244 changed files with 40326 additions and 40363 deletions

1
.gitignore vendored
View file

@ -3,6 +3,7 @@
/public/build /public/build
/logs /logs
Homestead.yaml Homestead.yaml
/public/storage
.env .env
.vagrant .vagrant
_ide_helper.php _ide_helper.php

View file

@ -77,11 +77,15 @@ class AlbumDownloader
if ($isLosslessFormatWithLossyTracks && $track->isMasterLossy()) { if ($isLosslessFormatWithLossyTracks && $track->isMasterLossy()) {
$masterFormatName = $track->getMasterFormatName(); $masterFormatName = $track->getMasterFormatName();
$zip->addLargeFile($track->getFileFor($masterFormatName), $zip->addLargeFile(
$directory . $track->getDownloadFilenameFor($masterFormatName)); $track->getFileFor($masterFormatName),
$directory . $track->getDownloadFilenameFor($masterFormatName)
);
} else { } else {
$zip->addLargeFile($track->getFileFor($this->_format), $zip->addLargeFile(
$directory . $track->getDownloadFilenameFor($this->_format)); $track->getFileFor($this->_format),
$directory . $track->getDownloadFilenameFor($this->_format)
);
} }
$notes .= $notes .=

View file

@ -22,7 +22,7 @@ namespace Poniverse\Ponyfm\Commands;
abstract class CommandBase abstract class CommandBase
{ {
private $_listeners = array(); private $_listeners = [];
public function listen($listener) public function listen($listener)
{ {
@ -47,5 +47,5 @@ abstract class CommandBase
/** /**
* @return CommandResponse * @return CommandResponse
*/ */
public abstract function execute(); abstract public function execute();
} }

View file

@ -44,7 +44,6 @@ class CommandResponse
if (is_array($validatorOrMessages)) { if (is_array($validatorOrMessages)) {
$response->_messages = $validatorOrMessages; $response->_messages = $validatorOrMessages;
$response->_validator = null; $response->_validator = null;
} else { } else {
$response->_validator = $validatorOrMessages; $response->_validator = $validatorOrMessages;
} }
@ -102,7 +101,6 @@ class CommandResponse
{ {
if ($this->_validator !== null) { if ($this->_validator !== null) {
return $this->_validator->messages()->getMessages(); return $this->_validator->messages()->getMessages();
} else { } else {
return $this->_messages; return $this->_messages;
} }

View file

@ -100,16 +100,12 @@ class CreateCommentCommand extends CommandBase
// Recount the track's comments, if this is a track comment // Recount the track's comments, if this is a track comment
if ($this->_type === 'track') { if ($this->_type === 'track') {
$entity = Track::find($this->_id); $entity = Track::find($this->_id);
} elseif ($this->_type === 'album') { } elseif ($this->_type === 'album') {
$entity = Album::find($this->_id); $entity = Album::find($this->_id);
} elseif ($this->_type === 'playlist') { } elseif ($this->_type === 'playlist') {
$entity = Playlist::find($this->_id); $entity = Playlist::find($this->_id);
} elseif ($this->_type === 'user') { } elseif ($this->_type === 'user') {
$entity = User::find($this->_id); $entity = User::find($this->_id);
} else { } else {
App::abort(400, 'This comment is being added to an invalid entity!'); App::abort(400, 'This comment is being added to an invalid entity!');
} }

View file

@ -35,7 +35,8 @@ class DeleteGenreCommand extends CommandBase
private $_genreToDelete; private $_genreToDelete;
private $_destinationGenre; private $_destinationGenre;
public function __construct($genreId, $destinationGenreId) { public function __construct($genreId, $destinationGenreId)
{
$this->_genreToDelete = Genre::find($genreId); $this->_genreToDelete = Genre::find($genreId);
$this->_destinationGenre = Genre::find($destinationGenreId); $this->_destinationGenre = Genre::find($destinationGenreId);
} }
@ -43,7 +44,8 @@ class DeleteGenreCommand extends CommandBase
/** /**
* @return bool * @return bool
*/ */
public function authorize() { public function authorize()
{
return Gate::allows('delete', $this->_genreToDelete); return Gate::allows('delete', $this->_genreToDelete);
} }
@ -51,7 +53,8 @@ class DeleteGenreCommand extends CommandBase
* @throws \Exception * @throws \Exception
* @return CommandResponse * @return CommandResponse
*/ */
public function execute() { public function execute()
{
$rules = [ $rules = [
'genre_to_delete' => 'required', 'genre_to_delete' => 'required',
'destination_genre' => 'required', 'destination_genre' => 'required',

View file

@ -35,7 +35,8 @@ class DeleteShowSongCommand extends CommandBase
private $_songToDelete; private $_songToDelete;
private $_destinationSong; private $_destinationSong;
public function __construct($songId, $destinationSongId) { public function __construct($songId, $destinationSongId)
{
$this->_songToDelete = ShowSong::find($songId); $this->_songToDelete = ShowSong::find($songId);
$this->_destinationSong = ShowSong::find($destinationSongId); $this->_destinationSong = ShowSong::find($destinationSongId);
} }
@ -43,7 +44,8 @@ class DeleteShowSongCommand extends CommandBase
/** /**
* @return bool * @return bool
*/ */
public function authorize() { public function authorize()
{
return Gate::allows('delete', $this->_destinationSong); return Gate::allows('delete', $this->_destinationSong);
} }
@ -51,7 +53,8 @@ class DeleteShowSongCommand extends CommandBase
* @throws \Exception * @throws \Exception
* @return CommandResponse * @return CommandResponse
*/ */
public function execute() { public function execute()
{
$rules = [ $rules = [
'song_to_delete' => 'required', 'song_to_delete' => 'required',
'destination_song' => 'required', 'destination_song' => 'required',

View file

@ -84,13 +84,10 @@ class GenerateTrackFilesCommand extends CommandBase
if ($isLossyUpload) { if ($isLossyUpload) {
if ($codecString === 'mp3') { if ($codecString === 'mp3') {
$masterFormat = 'MP3'; $masterFormat = 'MP3';
} else if (Str::startsWith($codecString, 'aac')) { } else if (Str::startsWith($codecString, 'aac')) {
$masterFormat = 'AAC'; $masterFormat = 'AAC';
} else if ($codecString === 'vorbis') { } else if ($codecString === 'vorbis') {
$masterFormat = 'OGG Vorbis'; $masterFormat = 'OGG Vorbis';
} else { } else {
$this->track->delete(); $this->track->delete();
return CommandResponse::fail(['track' => "The track does not contain audio in a known lossy format. The format read from the file is: {$codecString}"]); return CommandResponse::fail(['track' => "The track does not contain audio in a known lossy format. The format read from the file is: {$codecString}"]);
@ -156,7 +153,6 @@ class GenerateTrackFilesCommand extends CommandBase
} }
$this->dispatch(new EncodeTrackFile($trackFile, false, false, $this->isForUpload, $this->isReplacingTrack)); $this->dispatch(new EncodeTrackFile($trackFile, false, false, $this->isForUpload, $this->isReplacingTrack));
} }
} catch (InvalidEncodeOptionsException $e) { } catch (InvalidEncodeOptionsException $e) {
// Only delete the track if the track is not being replaced // Only delete the track if the track is not being replaced
if ($this->isReplacingTrack) { if ($this->isReplacingTrack) {
@ -167,7 +163,6 @@ class GenerateTrackFilesCommand extends CommandBase
} }
return CommandResponse::fail(['track' => [$e->getMessage()]]); return CommandResponse::fail(['track' => [$e->getMessage()]]);
} }
} catch (\Exception $e) { } catch (\Exception $e) {
if ($this->isReplacingTrack) { if ($this->isReplacingTrack) {
$this->track->version_upload_status = Track::STATUS_ERROR; $this->track->version_upload_status = Track::STATUS_ERROR;

View file

@ -35,7 +35,6 @@ use Poniverse\Ponyfm\Models\User;
use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class ParseTrackTagsCommand extends CommandBase class ParseTrackTagsCommand extends CommandBase
{ {
private $track; private $track;
@ -107,7 +106,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param Track * @param Track
* @return Track * @return Track
*/ */
private function unsetNullVariables($track) { private function unsetNullVariables($track)
{
$vars = $track->getAttributes(); $vars = $track->getAttributes();
foreach ($vars as $key => $value) { foreach ($vars as $key => $value) {
@ -125,7 +125,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param string $genreName * @param string $genreName
* @return int * @return int
*/ */
protected function getGenreId(string $genreName) { protected function getGenreId(string $genreName)
{
$existingGenre = Genre::withTrashed() $existingGenre = Genre::withTrashed()
->where('name', $genreName)->first(); ->where('name', $genreName)->first();
@ -165,7 +166,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param integer|null $coverId * @param integer|null $coverId
* @return int|null * @return int|null
*/ */
protected function getAlbumId(int $artistId, $albumName, $coverId = null) { protected function getAlbumId(int $artistId, $albumName, $coverId = null)
{
if (null !== $albumName) { if (null !== $albumName) {
$album = Album::firstOrNew([ $album = Album::firstOrNew([
'user_id' => $artistId, 'user_id' => $artistId,
@ -194,7 +196,8 @@ class ParseTrackTagsCommand extends CommandBase
* @return array the "processed" and raw tags extracted from the file * @return array the "processed" and raw tags extracted from the file
* @throws \Exception * @throws \Exception
*/ */
protected function parseOriginalTags(\Symfony\Component\HttpFoundation\File\File $file, User $artist, string $audioCodec) { protected function parseOriginalTags(\Symfony\Component\HttpFoundation\File\File $file, User $artist, string $audioCodec)
{
//========================================================================================================== //==========================================================================================================
// Extract the original tags. // Extract the original tags.
//========================================================================================================== //==========================================================================================================
@ -208,16 +211,12 @@ class ParseTrackTagsCommand extends CommandBase
if ($audioCodec === 'mp3') { if ($audioCodec === 'mp3') {
list($parsedTags, $rawTags) = $this->getId3Tags($allTags); list($parsedTags, $rawTags) = $this->getId3Tags($allTags);
} elseif (Str::startsWith($audioCodec, ['aac', 'alac'])) { } elseif (Str::startsWith($audioCodec, ['aac', 'alac'])) {
list($parsedTags, $rawTags) = $this->getAtomTags($allTags); list($parsedTags, $rawTags) = $this->getAtomTags($allTags);
} elseif (in_array($audioCodec, ['vorbis', 'flac'])) { } elseif (in_array($audioCodec, ['vorbis', 'flac'])) {
list($parsedTags, $rawTags) = $this->getVorbisTags($allTags); list($parsedTags, $rawTags) = $this->getVorbisTags($allTags);
} elseif (Str::startsWith($audioCodec, ['pcm', 'adpcm'])) { } elseif (Str::startsWith($audioCodec, ['pcm', 'adpcm'])) {
list($parsedTags, $rawTags) = $this->getAtomTags($allTags); list($parsedTags, $rawTags) = $this->getAtomTags($allTags);
} else { } else {
// Assume the file is untagged if it's in an unknown format. // Assume the file is untagged if it's in an unknown format.
$parsedTags = [ $parsedTags = [
@ -255,7 +254,6 @@ class ParseTrackTagsCommand extends CommandBase
if ($genreName !== null) { if ($genreName !== null) {
$parsedTags['genre_id'] = $this->getGenreId($genreName); $parsedTags['genre_id'] = $this->getGenreId($genreName);
} else { } else {
$parsedTags['genre_id'] = null; $parsedTags['genre_id'] = null;
} }
@ -270,10 +268,8 @@ class ParseTrackTagsCommand extends CommandBase
if ($image['image_mime'] === 'image/png') { if ($image['image_mime'] === 'image/png') {
$extension = 'png'; $extension = 'png';
} elseif ($image['image_mime'] === 'image/jpeg') { } elseif ($image['image_mime'] === 'image/jpeg') {
$extension = 'jpg'; $extension = 'jpg';
} else { } else {
throw new BadRequestHttpException('Unknown cover format embedded in the track file!'); throw new BadRequestHttpException('Unknown cover format embedded in the track file!');
} }
@ -289,7 +285,6 @@ class ParseTrackTagsCommand extends CommandBase
$cover = Image::upload($imageFile, $artist); $cover = Image::upload($imageFile, $artist);
$coverId = $cover->id; $coverId = $cover->id;
} else { } else {
// no cover art was found - carry on // no cover art was found - carry on
} }
@ -318,7 +313,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param array $rawTags * @param array $rawTags
* @return array * @return array
*/ */
protected function getId3Tags($rawTags) { protected function getId3Tags($rawTags)
{
if (array_key_exists('tags', $rawTags) && array_key_exists('id3v2', $rawTags['tags'])) { if (array_key_exists('tags', $rawTags) && array_key_exists('id3v2', $rawTags['tags'])) {
$tags = $rawTags['tags']['id3v2']; $tags = $rawTags['tags']['id3v2'];
} elseif (array_key_exists('tags', $rawTags) && array_key_exists('id3v1', $rawTags['tags'])) { } elseif (array_key_exists('tags', $rawTags) && array_key_exists('id3v1', $rawTags['tags'])) {
@ -364,7 +360,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param array $rawTags * @param array $rawTags
* @return array * @return array
*/ */
protected function getAtomTags($rawTags) { protected function getAtomTags($rawTags)
{
if (array_key_exists('tags', $rawTags) && array_key_exists('quicktime', $rawTags['tags'])) { if (array_key_exists('tags', $rawTags) && array_key_exists('quicktime', $rawTags['tags'])) {
$tags = $rawTags['tags']['quicktime']; $tags = $rawTags['tags']['quicktime'];
} else { } else {
@ -379,7 +376,6 @@ class ParseTrackTagsCommand extends CommandBase
if (isset($tags['release_date'])) { if (isset($tags['release_date'])) {
$releaseDate = $this->parseDateString($tags['release_date'][0]); $releaseDate = $this->parseDateString($tags['release_date'][0]);
} elseif (isset($tags['creation_date'])) { } elseif (isset($tags['creation_date'])) {
$releaseDate = $this->parseDateString($tags['creation_date'][0]); $releaseDate = $this->parseDateString($tags['creation_date'][0]);
} else { } else {
@ -408,7 +404,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param array $rawTags * @param array $rawTags
* @return array * @return array
*/ */
protected function getVorbisTags($rawTags) { protected function getVorbisTags($rawTags)
{
if (array_key_exists('tags', $rawTags) && array_key_exists('vorbiscomment', $rawTags['tags'])) { if (array_key_exists('tags', $rawTags) && array_key_exists('vorbiscomment', $rawTags['tags'])) {
$tags = $rawTags['tags']['vorbiscomment']; $tags = $rawTags['tags']['vorbiscomment'];
} else { } else {
@ -452,7 +449,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param string $dateString * @param string $dateString
* @return null|Carbon * @return null|Carbon
*/ */
protected function parseDateString(string $dateString) { protected function parseDateString(string $dateString)
{
switch (Str::length($dateString)) { switch (Str::length($dateString)) {
// YYYY // YYYY
case 4: case 4:
@ -475,7 +473,6 @@ class ParseTrackTagsCommand extends CommandBase
// If not, give up. // If not, give up.
try { try {
return Carbon::createFromFormat(Carbon::ISO8601, $dateString); return Carbon::createFromFormat(Carbon::ISO8601, $dateString);
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
return null; return null;
} }

View file

@ -94,10 +94,8 @@ class SaveAccountSettingsCommand extends CommandBase
if (isset($this->_input['avatar_id'])) { if (isset($this->_input['avatar_id'])) {
$this->_user->avatar_id = $this->_input['avatar_id']; $this->_user->avatar_id = $this->_input['avatar_id'];
} elseif (isset($this->_input['avatar'])) { } elseif (isset($this->_input['avatar'])) {
$this->_user->avatar_id = Image::upload($this->_input['avatar'], $this->_user)->id; $this->_user->avatar_id = Image::upload($this->_input['avatar'], $this->_user)->id;
} else { } else {
$this->_user->avatar_id = null; $this->_user->avatar_id = null;
} }

View file

@ -25,7 +25,7 @@ use Carbon\Carbon;
use Config; use Config;
use Gate; use Gate;
use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Bus\DispatchesJobs;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use Validator; use Validator;
@ -73,7 +73,7 @@ class UploadTrackCommand extends CommandBase
int $version = 1, int $version = 1,
$track = null $track = null
) { ) {
$userSlug = Input::get('user_slug', null); $userSlug = Request::get('user_slug', null);
$this->_artist = $this->_artist =
$userSlug !== null $userSlug !== null
? User::where('slug', $userSlug)->first() ? User::where('slug', $userSlug)->first()
@ -94,9 +94,9 @@ class UploadTrackCommand extends CommandBase
*/ */
public function execute() public function execute()
{ {
$trackFile = Input::file('track', null); $trackFile = Request::file('track', null);
if (!$this->_isReplacingTrack) { if (!$this->_isReplacingTrack) {
$coverFile = Input::file('cover', null); $coverFile = Request::file('cover', null);
} }
if (null === $trackFile) { if (null === $trackFile) {
@ -114,7 +114,7 @@ class UploadTrackCommand extends CommandBase
$this->_track->user_id = $this->_artist->id; $this->_track->user_id = $this->_artist->id;
// The title set here is a placeholder; it'll be replaced by ParseTrackTagsCommand // The title set here is a placeholder; it'll be replaced by ParseTrackTagsCommand
// if the file contains a title tag. // if the file contains a title tag.
$this->_track->title = Input::get('title', pathinfo($trackFile->getClientOriginalName(), PATHINFO_FILENAME)); $this->_track->title = Request::get('title', pathinfo($trackFile->getClientOriginalName(), PATHINFO_FILENAME));
// The duration/version of the track cannot be changed until the encoding is successful // The duration/version of the track cannot be changed until the encoding is successful
$this->_track->duration = $audio->getDuration(); $this->_track->duration = $audio->getDuration();
$this->_track->current_version = $this->_version; $this->_track->current_version = $this->_version;
@ -131,7 +131,7 @@ class UploadTrackCommand extends CommandBase
} }
$trackFile = $trackFile->move(Config::get('ponyfm.files_directory').'/queued-tracks', $this->_track->id . 'v' . $this->_version); $trackFile = $trackFile->move(Config::get('ponyfm.files_directory').'/queued-tracks', $this->_track->id . 'v' . $this->_version);
$input = Input::all(); $input = Request::all();
$input['track'] = $trackFile; $input['track'] = $trackFile;
if (!$this->_isReplacingTrack) { if (!$this->_isReplacingTrack) {
$input['cover'] = $coverFile; $input['cover'] = $coverFile;
@ -180,7 +180,7 @@ class UploadTrackCommand extends CommandBase
if (!$this->_isReplacingTrack) { if (!$this->_isReplacingTrack) {
// If json_decode() isn't called here, Laravel will surround the JSON // If json_decode() isn't called here, Laravel will surround the JSON
// string with quotes when storing it in the database, which breaks things. // string with quotes when storing it in the database, which breaks things.
$this->_track->metadata = json_decode(Input::get('metadata', null)); $this->_track->metadata = json_decode(Request::get('metadata', null));
} }
$autoPublish = (bool)($input['auto_publish'] ?? $this->_autoPublishByDefault); $autoPublish = (bool)($input['auto_publish'] ?? $this->_autoPublishByDefault);
$this->_track->source = $this->_customTrackSource ?? 'direct_upload'; $this->_track->source = $this->_customTrackSource ?? 'direct_upload';

View file

@ -108,8 +108,12 @@ class ClassifyMLPMA extends Command
if (Str::contains(Str::lower($track->filename), 'ingram')) { if (Str::contains(Str::lower($track->filename), 'ingram')) {
$this->info('This is an official song remix!'); $this->info('This is an official song remix!');
list($trackType, $linkedSongIds) = $this->classifyTrack($track->filename, $officialSongs, true, list($trackType, $linkedSongIds) = $this->classifyTrack(
$parsedTags); $track->filename,
$officialSongs,
true,
$parsedTags
);
// If it has "remix" in the name, it's definitely a remix. // If it has "remix" in the name, it's definitely a remix.
@ -117,13 +121,21 @@ class ClassifyMLPMA extends Command
if (Str::contains(Str::lower($sanitizedTrackTitle), 'remix')) { if (Str::contains(Str::lower($sanitizedTrackTitle), 'remix')) {
$this->info('This is some kind of remix!'); $this->info('This is some kind of remix!');
list($trackType, $linkedSongIds) = $this->classifyTrack($track->filename, $officialSongs, false, list($trackType, $linkedSongIds) = $this->classifyTrack(
$parsedTags); $track->filename,
$officialSongs,
false,
$parsedTags
);
// No idea what this is. Have the pony at the terminal figure it out! // No idea what this is. Have the pony at the terminal figure it out!
} else { } else {
list($trackType, $linkedSongIds) = $this->classifyTrack($track->filename, $officialSongs, false, list($trackType, $linkedSongIds) = $this->classifyTrack(
$parsedTags); $track->filename,
$officialSongs,
false,
$parsedTags
);
} }
} }
@ -144,7 +156,6 @@ class ClassifyMLPMA extends Command
echo PHP_EOL; echo PHP_EOL;
} }
} }
/** /**
@ -169,19 +180,15 @@ class ClassifyMLPMA extends Command
if ($isRemixOfOfficialTrack && sizeof($officialSongs) === 1) { if ($isRemixOfOfficialTrack && sizeof($officialSongs) === 1) {
$linkedSongIds = [$officialSongs[0]->id]; $linkedSongIds = [$officialSongs[0]->id];
} else { } else {
if ($isRemixOfOfficialTrack && sizeof($officialSongs) > 1) { if ($isRemixOfOfficialTrack && sizeof($officialSongs) > 1) {
$this->question('Multiple official songs matched! Please enter the ID of the correct one.'); $this->question('Multiple official songs matched! Please enter the ID of the correct one.');
} else { } else {
if (sizeof($officialSongs) > 0) { if (sizeof($officialSongs) > 0) {
$this->question('This looks like a remix of an official song!'); $this->question('This looks like a remix of an official song!');
$this->question('Press "r" if the match above is right!'); $this->question('Press "r" if the match above is right!');
} else { } else {
$this->question('Exactly what kind of track is this?'); $this->question('Exactly what kind of track is this?');
} }
} }
$this->question('If this is a medley, multiple song ID\'s can be separated by commas. '); $this->question('If this is a medley, multiple song ID\'s can be separated by commas. ');

View file

@ -76,13 +76,10 @@ class ClearTrackCache extends Command
if (count($trackFiles) === 0) { if (count($trackFiles) === 0) {
$this->info('No tracks found. Exiting.'); $this->info('No tracks found. Exiting.');
} else { } else {
if ($this->option('force') || $this->confirm(count($trackFiles) . ' cacheable track files found. Proceed to delete their files if they exist? [y|N]', false)) { if ($this->option('force') || $this->confirm(count($trackFiles) . ' cacheable track files found. Proceed to delete their files if they exist? [y|N]', false)) {
$count = 0; $count = 0;
foreach ($trackFiles as $trackFile) { foreach ($trackFiles as $trackFile) {
// Set expiration to null (so can be re-cached upon request) // Set expiration to null (so can be re-cached upon request)
$trackFile->expires_at = null; $trackFile->expires_at = null;
$trackFile->update(); $trackFile->update();
@ -94,14 +91,11 @@ class ClearTrackCache extends Command
$this->info('Deleted ' . $trackFile->getFile()); $this->info('Deleted ' . $trackFile->getFile());
} }
} }
$this->info($count . ' files deleted. Deletion complete. Exiting.'); $this->info($count . ' files deleted. Deletion complete. Exiting.');
} else { } else {
$this->info('Deletion cancelled. Exiting.'); $this->info('Deletion cancelled. Exiting.');
} }
} }
} }
} }

View file

@ -144,7 +144,6 @@ class FixMLPMAImages extends Command
$imageFile = new UploadedFile($imageFilePath, $imageFilename, $image['image_mime']); $imageFile = new UploadedFile($imageFilePath, $imageFilename, $image['image_mime']);
$cover = Image::upload($imageFile, $artistId, true); $cover = Image::upload($imageFile, $artistId, true);
$coverId = $cover->id; $coverId = $cover->id;
} else { } else {
$this->comment('No cover art found!'); $this->comment('No cover art found!');
} }

View file

@ -101,8 +101,10 @@ class MigrateOldData extends Command
if (!$user->uses_gravatar) { if (!$user->uses_gravatar) {
try { try {
$coverFile = $this->getIdDirectory('users', $user->id).'/'.$user->id.'_.png'; $coverFile = $this->getIdDirectory('users', $user->id).'/'.$user->id.'_.png';
$coverId = Image::upload(new UploadedFile($coverFile, $coverId = Image::upload(new UploadedFile(
$user->id.'_.png'), $user->id)->id; $coverFile,
$user->id.'_.png'
), $user->id)->id;
DB::table('users')->where('id', $user->id)->update(['avatar_id' => $coverId]); DB::table('users')->where('id', $user->id)->update(['avatar_id' => $coverId]);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error('Could copy user avatar '.$user->id.' because '.$e->getMessage()); $this->error('Could copy user avatar '.$user->id.' because '.$e->getMessage());
@ -176,10 +178,14 @@ class MigrateOldData extends Command
$coverId = null; $coverId = null;
if ($track->cover) { if ($track->cover) {
try { try {
$coverFile = $this->getIdDirectory('tracks', $coverFile = $this->getIdDirectory(
$track->id).'/'.$track->id.'_'.$track->cover.'.png'; 'tracks',
$coverId = Image::upload(new UploadedFile($coverFile, $track->id
$track->id.'_'.$track->cover.'.png'), $track->user_id)->id; ).'/'.$track->id.'_'.$track->cover.'.png';
$coverId = Image::upload(new UploadedFile(
$coverFile,
$track->id.'_'.$track->cover.'.png'
), $track->user_id)->id;
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error('Could copy track cover '.$track->id.' because '.$e->getMessage()); $this->error('Could copy track cover '.$track->id.' because '.$e->getMessage());
} }
@ -396,5 +402,4 @@ class MigrateOldData extends Command
return \Config::get('ponyfm.files_directory').'/'.$type.'/'.$dir; return \Config::get('ponyfm.files_directory').'/'.$type.'/'.$dir;
} }
} }

View file

@ -76,12 +76,10 @@ class PoniverseApiSetup extends Command
'auth' => [$username, $password], 'auth' => [$username, $password],
'query' => ['app' => 'Pony.fm'] 'query' => ['app' => 'Pony.fm']
]); ]);
} catch (ClientException $e) { } catch (ClientException $e) {
if ($e->getResponse()->getStatusCode() === 401) { if ($e->getResponse()->getStatusCode() === 401) {
$this->error('Incorrect username or password! Please try again.'); $this->error('Incorrect username or password! Please try again.');
exit(); exit();
} else { } else {
var_dump($e->getResponse()->getBody()); var_dump($e->getResponse()->getBody());
throw $e; throw $e;
@ -100,16 +98,20 @@ class PoniverseApiSetup extends Command
} }
protected function setEnvironmentVariable($key, $oldValue, $newValue) { protected function setEnvironmentVariable($key, $oldValue, $newValue)
{
$path = base_path('.env'); $path = base_path('.env');
// Detect the specific "null" value. // Detect the specific "null" value.
if ($oldValue === null) if ($oldValue === null) {
$oldValue = 'null'; $oldValue = 'null';
}
if (file_exists($path)) { if (file_exists($path)) {
file_put_contents($path, str_replace( file_put_contents($path, str_replace(
"$key=".$oldValue, "$key=".$newValue, file_get_contents($path) "$key=".$oldValue,
"$key=".$newValue,
file_get_contents($path)
)); ));
} else { } else {
$this->error('Please run `vagrant up`!'); $this->error('Please run `vagrant up`!');

View file

@ -59,10 +59,11 @@ class RebuildFilesizes extends Command
{ {
$this->info('This will only rebuild the cache for track files which exist on disk; non-existent files will be skipped.'); $this->info('This will only rebuild the cache for track files which exist on disk; non-existent files will be skipped.');
if ($this->option('force') || $this->confirm('Are you sure you want to rebuild the filesize cache? [y|N]', if ($this->option('force') || $this->confirm(
false) 'Are you sure you want to rebuild the filesize cache? [y|N]',
false
)
) { ) {
TrackFile::chunk(200, function ($trackFiles) { TrackFile::chunk(200, function ($trackFiles) {
$this->info('========== Start Chunk =========='); $this->info('========== Start Chunk ==========');
@ -79,11 +80,9 @@ class RebuildFilesizes extends Command
} }
$this->info('=========== End Chunk ==========='); $this->info('=========== End Chunk ===========');
}); });
$this->info('Rebuild complete. Exiting.'); $this->info('Rebuild complete. Exiting.');
} else { } else {
$this->info('Rebuild cancelled. Exiting.'); $this->info('Rebuild cancelled. Exiting.');
} }

View file

@ -59,7 +59,6 @@ class RebuildTags extends Command
if ($this->argument('trackId')) { if ($this->argument('trackId')) {
$track = Track::findOrFail($this->argument('trackId')); $track = Track::findOrFail($this->argument('trackId'));
$tracks = [$track]; $tracks = [$track];
} else { } else {
$tracks = Track::whereNotNull('published_at')->withTrashed()->orderBy('id', 'asc')->get(); $tracks = Track::whereNotNull('published_at')->withTrashed()->orderBy('id', 'asc')->get();
} }

View file

@ -81,7 +81,6 @@ class RebuildTrack extends Command
$this->error("Something went wrong!"); $this->error("Something went wrong!");
print_r($result->getMessages()); print_r($result->getMessages());
} }
} else { } else {
$this->info("Re-encoding this track's files - there should be a line of output for each format!"); $this->info("Re-encoding this track's files - there should be a line of output for each format!");
@ -94,7 +93,8 @@ class RebuildTrack extends Command
} }
} }
private function printTrackInfo(Track $track) { private function printTrackInfo(Track $track)
{
$this->comment("Track info:"); $this->comment("Track info:");
$this->comment(" Title: {$track->title}"); $this->comment(" Title: {$track->title}");
$this->comment(" Uploaded at: {$track->created_at}"); $this->comment(" Uploaded at: {$track->created_at}");

View file

@ -67,10 +67,11 @@ class RebuildTrackCache extends Command
$this->info('If this is your first time running this command, it is *highly* recommended that you ensure the file sizes for all track files have been populated.'); $this->info('If this is your first time running this command, it is *highly* recommended that you ensure the file sizes for all track files have been populated.');
$this->info('***'); $this->info('***');
if ($this->option('force') || $this->confirm('Are you sure you want to delete all to-be-cached track files and encode missing non-cached track files?', if ($this->option('force') || $this->confirm(
false) 'Are you sure you want to delete all to-be-cached track files and encode missing non-cached track files?',
false
)
) { ) {
//========================================================================================================== //==========================================================================================================
// Delete previously cached track files // Delete previously cached track files
//========================================================================================================== //==========================================================================================================
@ -252,7 +253,6 @@ class RebuildTrackCache extends Command
$this->output->newLine(1); $this->output->newLine(1);
$this->info('Rebuild complete. Exiting.'); $this->info('Rebuild complete. Exiting.');
} else { } else {
$this->info('Rebuild cancelled. Exiting.'); $this->info('Rebuild cancelled. Exiting.');
} }

View file

@ -61,7 +61,6 @@ class VersionFiles extends Command
$this->info('This will only version track files which exist on disk; non-existent files will be skipped.'); $this->info('This will only version track files which exist on disk; non-existent files will be skipped.');
if ($this->option('force') || $this->confirm('Are you sure you want to rename all unversioned track files? [y|N]', false)) { if ($this->option('force') || $this->confirm('Are you sure you want to rename all unversioned track files? [y|N]', false)) {
TrackFile::chunk(200, function ($trackFiles) { TrackFile::chunk(200, function ($trackFiles) {
$this->info('========== Start Chunk =========='); $this->info('========== Start Chunk ==========');
@ -81,15 +80,12 @@ class VersionFiles extends Command
} else { } else {
$this->error('ID ' . $trackFile->id . ' was unable to be renamed'); $this->error('ID ' . $trackFile->id . ' was unable to be renamed');
} }
} }
$this->info('=========== End Chunk ==========='); $this->info('=========== End Chunk ===========');
}); });
$this->info('Rebuild complete. Exiting.'); $this->info('Rebuild complete. Exiting.');
} else { } else {
$this->info('Rebuild cancelled. Exiting.'); $this->info('Rebuild cancelled. Exiting.');
} }

View file

@ -28,7 +28,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
* *
* @package Poniverse\Ponyfm\Contracts * @package Poniverse\Ponyfm\Contracts
*/ */
interface Commentable extends GeneratesNotifications { interface Commentable extends GeneratesNotifications
{
/** /**
* This method returns an Eloquent relation to the entity's comments. * This method returns an Eloquent relation to the entity's comments.
* *

View file

@ -28,7 +28,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
* *
* @package Poniverse\Ponyfm\Contracts * @package Poniverse\Ponyfm\Contracts
*/ */
interface Favouritable extends GeneratesNotifications { interface Favouritable extends GeneratesNotifications
{
/** /**
* This method returns an Eloquent relation to the entity's favourites. * This method returns an Eloquent relation to the entity's favourites.
* *

View file

@ -29,7 +29,8 @@ use Poniverse\Ponyfm\Models\User;
* *
* @package Poniverse\Ponyfm\Contracts * @package Poniverse\Ponyfm\Contracts
*/ */
interface GeneratesNotifications { interface GeneratesNotifications
{
/** /**
* Returns a human-friendly string (lowercase & singular) representing this * Returns a human-friendly string (lowercase & singular) representing this
* type of resource. * type of resource.

View file

@ -33,7 +33,8 @@ use Poniverse\Ponyfm\Models\User;
* type of notification, add a method for it to this interface and every class * type of notification, add a method for it to this interface and every class
* that implements it. Your IDE should be able to help with this. * that implements it. Your IDE should be able to help with this.
*/ */
interface NotificationHandler { interface NotificationHandler
{
/** /**
* @param Track $track * @param Track $track
* @return void * @return void

View file

@ -20,7 +20,8 @@
namespace Poniverse\Ponyfm\Contracts; namespace Poniverse\Ponyfm\Contracts;
interface Searchable { interface Searchable
{
/** /**
* Returns this model in Elasticsearch-friendly form. The array returned by * Returns this model in Elasticsearch-friendly form. The array returned by
* this method should match the current mapping for this model's ES type. * this method should match the current mapping for this model's ES type.

View file

@ -22,6 +22,8 @@ namespace Poniverse\Ponyfm\Exceptions;
use Exception; use Exception;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Validation\ValidationException;
use GrahamCampbell\Exceptions\ExceptionHandler as ExceptionHandler; use GrahamCampbell\Exceptions\ExceptionHandler as ExceptionHandler;
class Handler extends ExceptionHandler class Handler extends ExceptionHandler
@ -32,6 +34,8 @@ class Handler extends ExceptionHandler
* @var array * @var array
*/ */
protected $dontReport = [ protected $dontReport = [
AuthorizationException::class,
ValidationException::class,
HttpException::class, HttpException::class,
]; ];
@ -45,7 +49,7 @@ class Handler extends ExceptionHandler
*/ */
public function report(Exception $e) public function report(Exception $e)
{ {
return parent::report($e); parent::report($e);
} }
/** /**

View file

@ -29,4 +29,6 @@ use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
* This exception indicates that an access token we attempted to introspect * This exception indicates that an access token we attempted to introspect
* through the Poniverse API is expired or otherwise unusable. * through the Poniverse API is expired or otherwise unusable.
*/ */
class InvalidAccessTokenException extends AccessDeniedHttpException {}; class InvalidAccessTokenException extends AccessDeniedHttpException
{
};

View file

@ -22,4 +22,6 @@ namespace Poniverse\Ponyfm\Exceptions;
use InvalidArgumentException; use InvalidArgumentException;
class InvalidEncodeOptionsException extends InvalidArgumentException {} class InvalidEncodeOptionsException extends InvalidArgumentException
{
}

View file

@ -31,4 +31,6 @@ use Illuminate\Database\Eloquent\ModelNotFoundException;
* contain tracks for which no lossless master is available (and thus, lossless * contain tracks for which no lossless master is available (and thus, lossless
* `TrackFiles` don't exist for). * `TrackFiles` don't exist for).
*/ */
class TrackFileNotFoundException extends ModelNotFoundException {} class TrackFileNotFoundException extends ModelNotFoundException
{
}

View file

@ -19,10 +19,13 @@
*/ */
namespace Poniverse\Ponyfm\Facades; namespace Poniverse\Ponyfm\Facades;
use Illuminate\Support\Facades\Facade; use Illuminate\Support\Facades\Facade;
class Notification extends Facade { class Notification extends Facade
protected static function getFacadeAccessor() { {
protected static function getFacadeAccessor()
{
return 'notification'; return 'notification';
} }
} }

View file

@ -28,7 +28,8 @@ use Response;
class TracksController extends ApiControllerBase class TracksController extends ApiControllerBase
{ {
public function postUploadTrack() { public function postUploadTrack()
{
session_write_close(); session_write_close();
$response = $this->execute(new UploadTrackCommand(true, true, session('api_client_id'), true)); $response = $this->execute(new UploadTrackCommand(true, true, session('api_client_id'), true));
@ -53,13 +54,13 @@ class TracksController extends ApiControllerBase
} }
public function getUploadStatus($trackId) { public function getUploadStatus($trackId)
{
$track = Track::findOrFail($trackId); $track = Track::findOrFail($trackId);
$this->authorize('edit', $track); $this->authorize('edit', $track);
if ($track->status === Track::STATUS_PROCESSING) { if ($track->status === Track::STATUS_PROCESSING) {
return Response::json(['message' => 'Processing...'], 202); return Response::json(['message' => 'Processing...'], 202);
} elseif ($track->status === Track::STATUS_COMPLETE) { } elseif ($track->status === Track::STATUS_COMPLETE) {
return Response::json([ return Response::json([
'message' => $track->published_at 'message' => $track->published_at
@ -68,7 +69,6 @@ class TracksController extends ApiControllerBase
'edit_url' => action('ContentController@getTracks', ['id' => $trackId]), 'edit_url' => action('ContentController@getTracks', ['id' => $trackId]),
'track_url' => $track->url 'track_url' => $track->url
], 201); ], 201);
} else { } else {
// something went wrong // something went wrong
return Response::json(['error' => 'Processing failed! Please contact logic@pony.fm to figure out what went wrong.'], 500); return Response::json(['error' => 'Processing failed! Please contact logic@pony.fm to figure out what went wrong.'], 500);

View file

@ -26,7 +26,7 @@ use Poniverse\Ponyfm\Commands\SaveAccountSettingsCommand;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use Gate; use Gate;
use Auth; use Auth;
use Input; use Illuminate\Support\Facades\Request;
use Response; use Response;
class AccountController extends ApiControllerBase class AccountController extends ApiControllerBase
@ -77,6 +77,6 @@ class AccountController extends ApiControllerBase
public function postSave(User $user) public function postSave(User $user)
{ {
return $this->execute(new SaveAccountSettingsCommand(Input::all(), $user)); return $this->execute(new SaveAccountSettingsCommand(Request::all(), $user));
} }
} }

View file

@ -30,7 +30,7 @@ use Poniverse\Ponyfm\Models\Image;
use Poniverse\Ponyfm\Models\ResourceLogItem; use Poniverse\Ponyfm\Models\ResourceLogItem;
use Auth; use Auth;
use Gate; use Gate;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use Response; use Response;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
@ -39,12 +39,12 @@ class AlbumsController extends ApiControllerBase
{ {
public function postCreate() public function postCreate()
{ {
return $this->execute(new CreateAlbumCommand(Input::all())); return $this->execute(new CreateAlbumCommand(Request::all()));
} }
public function postEdit($id) public function postEdit($id)
{ {
return $this->execute(new EditAlbumCommand($id, Input::all())); return $this->execute(new EditAlbumCommand($id, Request::all()));
} }
public function postDelete($id) public function postDelete($id)
@ -75,7 +75,7 @@ class AlbumsController extends ApiControllerBase
App::abort(404); App::abort(404);
} }
if (Input::get('log')) { if (Request::get('log')) {
ResourceLogItem::logItem('album', $id, ResourceLogItem::VIEW); ResourceLogItem::logItem('album', $id, ResourceLogItem::VIEW);
$album->view_count++; $album->view_count++;
} }
@ -96,7 +96,6 @@ class AlbumsController extends ApiControllerBase
try { try {
/** @var Album $album */ /** @var Album $album */
$album = Album::with('tracks.trackFiles')->findOrFail($id); $album = Album::with('tracks.trackFiles')->findOrFail($id);
} catch (ModelNotFoundException $e) { } catch (ModelNotFoundException $e) {
return $this->notFound('Album not found!'); return $this->notFound('Album not found!');
} }
@ -121,8 +120,8 @@ class AlbumsController extends ApiControllerBase
public function getIndex() public function getIndex()
{ {
$page = 1; $page = 1;
if (Input::has('page')) { if (Request::has('page')) {
$page = Input::get('page'); $page = Request::get('page');
} }
$query = Album::summary() $query = Album::summary()
@ -144,8 +143,10 @@ class AlbumsController extends ApiControllerBase
$albums[] = Album::mapPublicAlbumSummary($album); $albums[] = Album::mapPublicAlbumSummary($album);
} }
return Response::json(["albums" => $albums, "current_page" => $page, "total_pages" => ceil($count / $perPage)], return Response::json(
200); ["albums" => $albums, "current_page" => $page, "total_pages" => ceil($count / $perPage)],
200
);
} }
public function getOwned(User $user) public function getOwned(User $user)

View file

@ -31,7 +31,7 @@ use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use Poniverse\Ponyfm\Models\Follower; use Poniverse\Ponyfm\Models\Follower;
use App; use App;
use Input; use Illuminate\Support\Facades\Request;
use Response; use Response;
use ColorThief\ColorThief; use ColorThief\ColorThief;
use Helpers; use Helpers;
@ -209,8 +209,8 @@ class ArtistsController extends ApiControllerBase
public function getIndex() public function getIndex()
{ {
$page = 1; $page = 1;
if (Input::has('page')) { if (Request::has('page')) {
$page = Input::get('page'); $page = Request::get('page');
} }
$query = User::where('track_count', '>', 0); $query = User::where('track_count', '>', 0);
@ -227,12 +227,15 @@ class ArtistsController extends ApiControllerBase
$users[] = User::mapPublicUserSummary($user); $users[] = User::mapPublicUserSummary($user);
} }
return Response::json(["artists" => $users, "current_page" => $page, "total_pages" => ceil($count / $perPage)], return Response::json(
200); ["artists" => $users, "current_page" => $page, "total_pages" => ceil($count / $perPage)],
200
);
} }
public function postIndex() { public function postIndex()
$name = Input::json('username'); {
$name = Request::json('username');
return $this->execute(new CreateUserCommand($name, $name, null, true)); return $this->execute(new CreateUserCommand($name, $name, null, true));
} }
} }

View file

@ -24,14 +24,14 @@ use App;
use Poniverse\Ponyfm\Commands\CreateCommentCommand; use Poniverse\Ponyfm\Commands\CreateCommentCommand;
use Poniverse\Ponyfm\Models\Comment; use Poniverse\Ponyfm\Models\Comment;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Input; use Illuminate\Support\Facades\Request;
use Response; use Response;
class CommentsController extends ApiControllerBase class CommentsController extends ApiControllerBase
{ {
public function postCreate($type, $id) public function postCreate($type, $id)
{ {
return $this->execute(new CreateCommentCommand($type, $id, Input::all())); return $this->execute(new CreateCommentCommand($type, $id, Request::all()));
} }
public function getIndex($type, $id) public function getIndex($type, $id)

View file

@ -27,14 +27,14 @@ use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Poniverse\Ponyfm\Models\Playlist; use Poniverse\Ponyfm\Models\Playlist;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use Auth; use Auth;
use Input; use Illuminate\Support\Facades\Request;
use Response; use Response;
class FavouritesController extends ApiControllerBase class FavouritesController extends ApiControllerBase
{ {
public function postToggle() public function postToggle()
{ {
return $this->execute(new ToggleFavouriteCommand(Input::get('type'), Input::get('id'))); return $this->execute(new ToggleFavouriteCommand(Request::get('type'), Request::get('id')));
} }
public function getTracks() public function getTracks()
@ -58,8 +58,7 @@ class FavouritesController extends ApiControllerBase
$tracks = []; $tracks = [];
foreach ($query->get() as $fav) { foreach ($query->get() as $fav) {
if ($fav->track == null) // deleted track if ($fav->track == null) { // deleted track
{
continue; continue;
} }
@ -86,8 +85,7 @@ class FavouritesController extends ApiControllerBase
$albums = []; $albums = [];
foreach ($query->get() as $fav) { foreach ($query->get() as $fav) {
if ($fav->album == null) // deleted album if ($fav->album == null) { // deleted album
{
continue; continue;
} }
@ -115,8 +113,7 @@ class FavouritesController extends ApiControllerBase
$playlists = []; $playlists = [];
foreach ($query->get() as $fav) { foreach ($query->get() as $fav) {
if ($fav->playlist == null) // deleted playlist if ($fav->playlist == null) { // deleted playlist
{
continue; continue;
} }

View file

@ -22,12 +22,12 @@ namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Poniverse\Ponyfm\Commands\ToggleFollowingCommand; use Poniverse\Ponyfm\Commands\ToggleFollowingCommand;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Input; use Illuminate\Support\Facades\Request;
class FollowController extends ApiControllerBase class FollowController extends ApiControllerBase
{ {
public function postToggle() public function postToggle()
{ {
return $this->execute(new ToggleFollowingCommand(Input::get('type'), Input::get('id'))); return $this->execute(new ToggleFollowingCommand(Request::get('type'), Request::get('id')));
} }
} }

View file

@ -20,7 +20,7 @@
namespace Poniverse\Ponyfm\Http\Controllers\Api\Web; namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Commands\CreateGenreCommand; use Poniverse\Ponyfm\Commands\CreateGenreCommand;
use Poniverse\Ponyfm\Commands\DeleteGenreCommand; use Poniverse\Ponyfm\Commands\DeleteGenreCommand;
use Poniverse\Ponyfm\Commands\RenameGenreCommand; use Poniverse\Ponyfm\Commands\RenameGenreCommand;
@ -28,7 +28,6 @@ use Poniverse\Ponyfm\Models\Genre;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Response; use Response;
class GenresController extends ApiControllerBase class GenresController extends ApiControllerBase
{ {
public function getIndex() public function getIndex()
@ -48,20 +47,20 @@ class GenresController extends ApiControllerBase
public function postCreate() public function postCreate()
{ {
$command = new CreateGenreCommand(Input::get('name')); $command = new CreateGenreCommand(Request::get('name'));
return $this->execute($command); return $this->execute($command);
} }
public function putRename($genreId) public function putRename($genreId)
{ {
$command = new RenameGenreCommand($genreId, Input::get('name')); $command = new RenameGenreCommand($genreId, Request::get('name'));
return $this->execute($command); return $this->execute($command);
} }
public function deleteGenre($genreId) public function deleteGenre($genreId)
{ {
$command = new DeleteGenreCommand($genreId, Input::get('destination_genre_id')); $command = new DeleteGenreCommand($genreId, Request::get('destination_genre_id'));
return $this->execute($command); return $this->execute($command);
} }
} }

View file

@ -21,7 +21,7 @@
namespace Poniverse\Ponyfm\Http\Controllers\Api\Web; namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Auth; use Auth;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Poniverse\Ponyfm\Models\Notification; use Poniverse\Ponyfm\Models\Notification;
use Poniverse\Ponyfm\Models\Subscription; use Poniverse\Ponyfm\Models\Subscription;
@ -56,7 +56,7 @@ class NotificationsController extends ApiControllerBase
*/ */
public function putMarkAsRead() public function putMarkAsRead()
{ {
$notificationIds = Input::json('notification_ids'); $notificationIds = Request::json('notification_ids');
$numberOfUpdatedRows = Auth::user() $numberOfUpdatedRows = Auth::user()
->notifications() ->notifications()
->whereIn('id', $notificationIds) ->whereIn('id', $notificationIds)
@ -74,7 +74,7 @@ class NotificationsController extends ApiControllerBase
*/ */
public function postSubscribe() public function postSubscribe()
{ {
$input = json_decode(Input::json('subscription')); $input = json_decode(Request::json('subscription'));
if ($input != 'null') { if ($input != 'null') {
$existing = Subscription::where('endpoint', '=', $input->endpoint) $existing = Subscription::where('endpoint', '=', $input->endpoint)
->where('user_id', '=', Auth::user()->id) ->where('user_id', '=', Auth::user()->id)
@ -104,7 +104,7 @@ class NotificationsController extends ApiControllerBase
*/ */
public function postUnsubscribe() public function postUnsubscribe()
{ {
$input = json_decode(Input::json('subscription')); $input = json_decode(Request::json('subscription'));
$existing = Subscription::where('endpoint', '=', $input->endpoint) $existing = Subscription::where('endpoint', '=', $input->endpoint)
->where('user_id', '=', Auth::user()->id) ->where('user_id', '=', Auth::user()->id)

View file

@ -31,7 +31,7 @@ use Poniverse\Ponyfm\Models\Image;
use Poniverse\Ponyfm\Models\Playlist; use Poniverse\Ponyfm\Models\Playlist;
use Poniverse\Ponyfm\Models\ResourceLogItem; use Poniverse\Ponyfm\Models\ResourceLogItem;
use Auth; use Auth;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use Response; use Response;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
@ -40,12 +40,12 @@ class PlaylistsController extends ApiControllerBase
{ {
public function postCreate() public function postCreate()
{ {
return $this->execute(new CreatePlaylistCommand(Input::all())); return $this->execute(new CreatePlaylistCommand(Request::all()));
} }
public function postEdit($id) public function postEdit($id)
{ {
return $this->execute(new EditPlaylistCommand($id, Input::all())); return $this->execute(new EditPlaylistCommand($id, Request::all()));
} }
public function postDelete($id) public function postDelete($id)
@ -55,27 +55,29 @@ class PlaylistsController extends ApiControllerBase
public function postAddTrack($id) public function postAddTrack($id)
{ {
return $this->execute(new AddTrackToPlaylistCommand($id, Input::get('track_id'))); return $this->execute(new AddTrackToPlaylistCommand($id, Request::get('track_id')));
} }
public function postRemoveTrack($id) public function postRemoveTrack($id)
{ {
return $this->execute(new RemoveTrackFromPlaylistCommand($id, Input::get('track_id'))); return $this->execute(new RemoveTrackFromPlaylistCommand($id, Request::get('track_id')));
} }
public function getIndex() public function getIndex()
{ {
$page = Input::has('page') ? Input::get('page') : 1; $page = Request::has('page') ? Request::get('page') : 1;
$query = Playlist::summary() $query = Playlist::summary()
->with('user', ->with(
'user',
'user.avatar', 'user.avatar',
'tracks', 'tracks',
'tracks.cover', 'tracks.cover',
'tracks.user', 'tracks.user',
'tracks.user.avatar', 'tracks.user.avatar',
'tracks.album', 'tracks.album',
'tracks.album.user') 'tracks.album.user'
)
->userDetails() ->userDetails()
// A playlist with only one track is not much of a list. // A playlist with only one track is not much of a list.
->where('track_count', '>', 1) ->where('track_count', '>', 1)
@ -117,7 +119,7 @@ class PlaylistsController extends ApiControllerBase
App::abort('404'); App::abort('404');
} }
if (Input::get('log')) { if (Request::get('log')) {
ResourceLogItem::logItem('playlist', $id, ResourceLogItem::VIEW); ResourceLogItem::logItem('playlist', $id, ResourceLogItem::VIEW);
$playlist->view_count++; $playlist->view_count++;
} }
@ -221,8 +223,8 @@ class PlaylistsController extends ApiControllerBase
*/ */
private function applyOrdering($query) private function applyOrdering($query)
{ {
if (Input::has('order')) { if (Request::has('order')) {
$order = \Input::get('order'); $order = \Request::get('order');
$parts = explode(',', $order); $parts = explode(',', $order);
$query->orderBy($parts[0], $parts[1]); $query->orderBy($parts[0], $parts[1]);
} }

View file

@ -22,7 +22,7 @@ namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Elasticsearch; use Elasticsearch;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Library\Search; use Poniverse\Ponyfm\Library\Search;
use Response; use Response;
@ -30,7 +30,7 @@ class SearchController extends ApiControllerBase
{ {
public function getSearch(Search $search) public function getSearch(Search $search)
{ {
$results = $search->searchAllContent(Input::query('query')); $results = $search->searchAllContent(Request::query('query'));
return Response::json([ return Response::json([
'results' => $results, 'results' => $results,

View file

@ -20,7 +20,7 @@
namespace Poniverse\Ponyfm\Http\Controllers\Api\Web; namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Commands\CreateShowSongCommand; use Poniverse\Ponyfm\Commands\CreateShowSongCommand;
use Poniverse\Ponyfm\Commands\DeleteShowSongCommand; use Poniverse\Ponyfm\Commands\DeleteShowSongCommand;
use Poniverse\Ponyfm\Commands\RenameShowSongCommand; use Poniverse\Ponyfm\Commands\RenameShowSongCommand;
@ -28,7 +28,6 @@ use Poniverse\Ponyfm\Models\ShowSong;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Response; use Response;
class ShowSongsController extends ApiControllerBase class ShowSongsController extends ApiControllerBase
{ {
public function getIndex() public function getIndex()
@ -49,20 +48,20 @@ class ShowSongsController extends ApiControllerBase
public function postCreate() public function postCreate()
{ {
$command = new CreateShowSongCommand(Input::get('title')); $command = new CreateShowSongCommand(Request::get('title'));
return $this->execute($command); return $this->execute($command);
} }
public function putRename($songId) public function putRename($songId)
{ {
$command = new RenameShowSongCommand($songId, Input::get('title')); $command = new RenameShowSongCommand($songId, Request::get('title'));
return $this->execute($command); return $this->execute($command);
} }
public function deleteSong($songId) public function deleteSong($songId)
{ {
$command = new DeleteShowSongCommand($songId, Input::get('destination_song_id')); $command = new DeleteShowSongCommand($songId, Request::get('destination_song_id'));
return $this->execute($command); return $this->execute($command);
} }
} }

View file

@ -32,7 +32,8 @@ use Carbon\Carbon;
class StatsController extends ApiControllerBase class StatsController extends ApiControllerBase
{ {
private function getStatsData($id, $hourly = false) { private function getStatsData($id, $hourly = false)
{
$playRange = "'1 MONTH'"; $playRange = "'1 MONTH'";
if ($hourly) { if ($hourly) {
@ -51,7 +52,8 @@ class StatsController extends ApiControllerBase
return $statQuery; return $statQuery;
} }
private function sortTrackStatsArray($query, $hourly = false) { private function sortTrackStatsArray($query, $hourly = false)
{
$now = Carbon::now(); $now = Carbon::now();
$playsArray = []; $playsArray = [];
$output = []; $output = [];
@ -104,7 +106,8 @@ class StatsController extends ApiControllerBase
} }
} }
public function getTrackStats($id) { public function getTrackStats($id)
{
$cachedOutput = Cache::remember('track_stats'.$id, 5, function () use ($id) { $cachedOutput = Cache::remember('track_stats'.$id, 5, function () use ($id) {
try { try {
$track = Track::published()->findOrFail($id); $track = Track::published()->findOrFail($id);

View file

@ -37,12 +37,18 @@ class TaxonomiesController extends ApiControllerBase
->orderBy('name') ->orderBy('name')
->get() ->get()
->toArray(), ->toArray(),
'track_types' => TrackType::select('track_types.*', 'track_types' => TrackType::select(
DB::raw('(SELECT COUNT(id) FROM tracks WHERE tracks.track_type_id = track_types.id AND tracks.published_at IS NOT NULL) AS track_count')) 'track_types.*',
DB::raw('(SELECT COUNT(id) FROM tracks WHERE tracks.track_type_id = track_types.id AND tracks.published_at IS NOT NULL) AS track_count')
)
->where('id', '!=', TrackType::UNCLASSIFIED_TRACK) ->where('id', '!=', TrackType::UNCLASSIFIED_TRACK)
->get()->toArray(), ->get()->toArray(),
'show_songs' => ShowSong::select('title', 'id', 'slug', 'show_songs' => ShowSong::select(
DB::raw('(SELECT COUNT(tracks.id) FROM show_song_track INNER JOIN tracks ON tracks.id = show_song_track.track_id WHERE show_song_track.show_song_id = show_songs.id AND tracks.published_at IS NOT NULL) AS track_count'))->orderBy('title')->get()->toArray() 'title',
'id',
'slug',
DB::raw('(SELECT COUNT(tracks.id) FROM show_song_track INNER JOIN tracks ON tracks.id = show_song_track.track_id WHERE show_song_track.show_song_id = show_songs.id AND tracks.published_at IS NOT NULL) AS track_count')
)->orderBy('title')->get()->toArray()
], 200); ], 200);
} }
} }

View file

@ -23,7 +23,7 @@ namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Auth; use Auth;
use File; use File;
use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\Eloquent\ModelNotFoundException;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Commands\DeleteTrackCommand; use Poniverse\Ponyfm\Commands\DeleteTrackCommand;
use Poniverse\Ponyfm\Commands\EditTrackCommand; use Poniverse\Ponyfm\Commands\EditTrackCommand;
use Poniverse\Ponyfm\Commands\GenerateTrackFilesCommand; use Poniverse\Ponyfm\Commands\GenerateTrackFilesCommand;
@ -55,10 +55,8 @@ class TracksController extends ApiControllerBase
if ($track->status === Track::STATUS_PROCESSING) { if ($track->status === Track::STATUS_PROCESSING) {
return Response::json(['message' => 'Processing...'], 202); return Response::json(['message' => 'Processing...'], 202);
} elseif ($track->status === Track::STATUS_COMPLETE) { } elseif ($track->status === Track::STATUS_COMPLETE) {
return Response::json(['message' => 'Processing complete!'], 201); return Response::json(['message' => 'Processing complete!'], 201);
} else { } else {
// something went wrong // something went wrong
return Response::json(['error' => 'Processing failed!'], 500); return Response::json(['error' => 'Processing failed!'], 500);
@ -72,7 +70,7 @@ class TracksController extends ApiControllerBase
public function postEdit($id) public function postEdit($id)
{ {
return $this->execute(new EditTrackCommand($id, Input::all())); return $this->execute(new EditTrackCommand($id, Request::all()));
} }
public function postUploadNewVersion($trackId) public function postUploadNewVersion($trackId)
@ -97,10 +95,8 @@ class TracksController extends ApiControllerBase
if ($track->version_upload_status === Track::STATUS_PROCESSING) { if ($track->version_upload_status === Track::STATUS_PROCESSING) {
return Response::json(['message' => 'Processing...'], 202); return Response::json(['message' => 'Processing...'], 202);
} elseif ($track->version_upload_status === Track::STATUS_COMPLETE) { } elseif ($track->version_upload_status === Track::STATUS_COMPLETE) {
return Response::json(['message' => 'Processing complete!'], 201); return Response::json(['message' => 'Processing complete!'], 201);
} else { } else {
// something went wrong // something went wrong
return Response::json(['error' => 'Processing failed!'], 500); return Response::json(['error' => 'Processing failed!'], 500);
@ -151,7 +147,7 @@ class TracksController extends ApiControllerBase
return $this->notFound('Track not found!'); return $this->notFound('Track not found!');
} }
if (Input::get('log')) { if (Request::get('log')) {
ResourceLogItem::logItem('track', $id, ResourceLogItem::VIEW); ResourceLogItem::logItem('track', $id, ResourceLogItem::VIEW);
$track->view_count++; $track->view_count++;
} }
@ -209,8 +205,8 @@ class TracksController extends ApiControllerBase
$page = 1; $page = 1;
$perPage = 45; $perPage = 45;
if (Input::has('page')) { if (Request::has('page')) {
$page = Input::get('page'); $page = Request::get('page');
} }
if ($all) { if ($all) {
@ -295,8 +291,8 @@ class TracksController extends ApiControllerBase
*/ */
private function applyOrdering($query) private function applyOrdering($query)
{ {
if (Input::has('order')) { if (Request::has('order')) {
$order = \Input::get('order'); $order = \Request::get('order');
$parts = explode(',', $order); $parts = explode(',', $order);
$query->orderBy($parts[0], $parts[1]); $query->orderBy($parts[0], $parts[1]);
} }
@ -312,8 +308,8 @@ class TracksController extends ApiControllerBase
*/ */
private function applyFilters($query, $unknown = false) private function applyFilters($query, $unknown = false)
{ {
if (Input::has('is_vocal')) { if (Request::has('is_vocal')) {
$isVocal = \Input::get('is_vocal'); $isVocal = \Request::get('is_vocal');
if ($isVocal == 'true') { if ($isVocal == 'true') {
$query->whereIsVocal(true); $query->whereIsVocal(true);
} else { } else {
@ -321,20 +317,20 @@ class TracksController extends ApiControllerBase
} }
} }
if (Input::has('in_album')) { if (Request::has('in_album')) {
if (Input::get('in_album') == 'true') { if (Request::get('in_album') == 'true') {
$query->whereNotNull('album_id'); $query->whereNotNull('album_id');
} else { } else {
$query->whereNull('album_id'); $query->whereNull('album_id');
} }
} }
if (Input::has('genres')) { if (Request::has('genres')) {
$query->whereIn('genre_id', Input::get('genres')); $query->whereIn('genre_id', Request::get('genres'));
} }
if (Input::has('types') && !$unknown) { if (Request::has('types') && !$unknown) {
$query->whereIn('track_type_id', Input::get('types')); $query->whereIn('track_type_id', Request::get('types'));
} }
if ($unknown) { if ($unknown) {
@ -351,14 +347,14 @@ class TracksController extends ApiControllerBase
$query->join('mlpma_tracks', 'tracks.id', '=', 'mlpma_tracks.track_id'); $query->join('mlpma_tracks', 'tracks.id', '=', 'mlpma_tracks.track_id');
} }
if (Input::has('songs')) { if (Request::has('songs')) {
// DISTINCT is needed here to avoid duplicate results // DISTINCT is needed here to avoid duplicate results
// when a track is associated with multiple show songs. // when a track is associated with multiple show songs.
$query->distinct(); $query->distinct();
$query->join('show_song_track', function ($join) { $query->join('show_song_track', function ($join) {
$join->on('tracks.id', '=', 'show_song_track.track_id'); $join->on('tracks.id', '=', 'show_song_track.track_id');
}); });
$query->whereIn('show_song_track.show_song_id', Input::get('songs')); $query->whereIn('show_song_track.show_song_id', Request::get('songs'));
} }
return $query; return $query;

View file

@ -32,11 +32,13 @@ class ArtistsController extends Controller
return View::make('artists.index'); return View::make('artists.index');
} }
public function getFavourites($slug) { public function getFavourites($slug)
{
return $this->getProfile($slug); return $this->getProfile($slug);
} }
public function getContent($slug) { public function getContent($slug)
{
return $this->getProfile($slug); return $this->getProfile($slug);
} }
@ -53,7 +55,7 @@ class ArtistsController extends Controller
public function getShortlink($id) public function getShortlink($id)
{ {
$user = User::find($id); $user = User::find($id);
if (!$user || $user->disabled_at !== NULL) { if (!$user || $user->disabled_at !== null) {
App::abort('404'); App::abort('404');
} }

View file

@ -24,7 +24,7 @@ use Poniverse\Ponyfm\Models\User;
use Auth; use Auth;
use Config; use Config;
use DB; use DB;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse; use Poniverse;
use Redirect; use Redirect;
@ -60,23 +60,29 @@ class AuthController extends Controller
Config::get('poniverse.urls')['token'], Config::get('poniverse.urls')['token'],
'authorization_code', 'authorization_code',
[ [
'code' => Input::query('code'), 'code' => Request::query('code'),
'redirect_uri' => action('AuthController@getOAuth') 'redirect_uri' => action('AuthController@getOAuth')
]); ]
);
if ($code['code'] != 200) { if ($code['code'] != 200) {
if ($code['code'] == 400 && $code['result']['error_description'] == 'The authorization code has expired' && !isset($this->request['login_attempt'])) { if ($code['code'] == 400 && $code['result']['error_description'] == 'The authorization code has expired' && !isset($this->request['login_attempt'])) {
return Redirect::to($this->poniverse->getAuthenticationUrl('login_attempt')); return Redirect::to($this->poniverse->getAuthenticationUrl('login_attempt'));
} }
return Redirect::to('/')->with('message', return Redirect::to('/')->with(
'Unfortunately we are having problems attempting to log you in at the moment. Please try again at a later time.'); 'message',
'Unfortunately we are having problems attempting to log you in at the moment. Please try again at a later time.'
);
} }
$this->poniverse->setAccessToken($code['result']['access_token']); $this->poniverse->setAccessToken($code['result']['access_token']);
$poniverseUser = $this->poniverse->getUser(); $poniverseUser = $this->poniverse->getUser();
$token = DB::table('oauth2_tokens')->where('external_user_id', '=', $poniverseUser['id'])->where('service', '=', $token = DB::table('oauth2_tokens')->where('external_user_id', '=', $poniverseUser['id'])->where(
'poniverse')->first(); 'service',
'=',
'poniverse'
)->first();
$setData = [ $setData = [
'access_token' => $code['result']['access_token'], 'access_token' => $code['result']['access_token'],

View file

@ -21,11 +21,12 @@
namespace Poniverse\Ponyfm\Http\Controllers; namespace Poniverse\Ponyfm\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController; use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Validation\ValidatesRequests;
abstract class Controller extends BaseController class Controller extends BaseController
{ {
use DispatchesJobs, ValidatesRequests, AuthorizesRequests; use DispatchesJobs, ValidatesRequests, AuthorizesRequests;
} }

View file

@ -153,12 +153,16 @@ class TracksController extends Controller
if (Config::get('app.sendfile')) { if (Config::get('app.sendfile')) {
$response->header('X-Sendfile', $filename); $response->header('X-Sendfile', $filename);
$response->header('Content-Disposition', $response->header(
'attachment; filename="'.$trackFile->getDownloadFilename().'"'); 'Content-Disposition',
'attachment; filename="'.$trackFile->getDownloadFilename().'"'
);
} else { } else {
$response->header('X-Accel-Redirect', $filename); $response->header('X-Accel-Redirect', $filename);
$response->header('Content-Disposition', $response->header(
'attachment; filename="'.$trackFile->getDownloadFilename().'"'); 'Content-Disposition',
'attachment; filename="'.$trackFile->getDownloadFilename().'"'
);
} }
$time = gmdate(filemtime($filename)); $time = gmdate(filemtime($filename));

View file

@ -31,12 +31,17 @@ class Kernel extends HttpKernel
*/ */
protected $middleware = [ protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
protected $middlewareGroups = [
'web' => [
\Poniverse\Ponyfm\Http\Middleware\EncryptCookies::class, \Poniverse\Ponyfm\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class, \Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Poniverse\Ponyfm\Http\Middleware\VerifyCsrfToken::class, \Poniverse\Ponyfm\Http\Middleware\VerifyCsrfToken::class,
\Poniverse\Ponyfm\Http\Middleware\DisabledAccountCheck::class, \Poniverse\Ponyfm\Http\Middleware\DisabledAccountCheck::class,
]
]; ];
/** /**
@ -48,8 +53,10 @@ class Kernel extends HttpKernel
'auth' => \Poniverse\Ponyfm\Http\Middleware\Authenticate::class, 'auth' => \Poniverse\Ponyfm\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.oauth' => \Poniverse\Ponyfm\Http\Middleware\AuthenticateOAuth::class, 'auth.oauth' => \Poniverse\Ponyfm\Http\Middleware\AuthenticateOAuth::class,
'can' => \Poniverse\Ponyfm\Http\Middleware\Authorize::class, // 'can' => \Poniverse\Ponyfm\Http\Middleware\Authorize::class,
'json-exceptions' => \Poniverse\Ponyfm\Http\Middleware\JsonExceptions::class, 'json-exceptions' => \Poniverse\Ponyfm\Http\Middleware\JsonExceptions::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \Poniverse\Ponyfm\Http\Middleware\RedirectIfAuthenticated::class, 'guest' => \Poniverse\Ponyfm\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
]; ];
} }

View file

@ -46,7 +46,8 @@ class AuthenticateOAuth
*/ */
private $session; private $session;
public function __construct(Poniverse $poniverse, Guard $auth, Store $session) { public function __construct(Poniverse $poniverse, Guard $auth, Store $session)
{
$this->poniverse = $poniverse; $this->poniverse = $poniverse;
$this->auth = $auth; $this->auth = $auth;
$this->session = $session; $this->session = $session;

View file

@ -37,7 +37,8 @@ class DisabledAccountCheck
* *
* @param Guard $auth * @param Guard $auth
*/ */
public function __construct(Guard $auth) { public function __construct(Guard $auth)
{
$this->auth = $auth; $this->auth = $auth;
} }

View file

@ -43,7 +43,6 @@ class JsonExceptions
{ {
try { try {
$response = $next($request); $response = $next($request);
} catch (HttpException $e) { } catch (HttpException $e) {
return \Response::json([ return \Response::json([
'message' => $e->getMessage() 'message' => $e->getMessage()

View file

@ -21,40 +21,24 @@
namespace Poniverse\Ponyfm\Http\Middleware; namespace Poniverse\Ponyfm\Http\Middleware;
use Closure; use Closure;
use Illuminate\Contracts\Auth\Guard; use Illuminate\Auth\AuthManager;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated class RedirectIfAuthenticated
{ {
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/** /**
* Handle an incoming request. * Handle an incoming request.
* *
* @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Request $request
* @param \Closure $next * @param \Closure $next
* @param string|null $guard
* @return mixed * @return mixed
*/ */
public function handle($request, Closure $next) public function handle($request, Closure $next, $guard = null)
{ {
if ($this->auth->check()) { if (Auth::guard($guard)->check()) {
return redirect('/home'); return redirect('/home');
} }
return $next($request); return $next($request);
} }
} }

View file

@ -55,9 +55,15 @@ Route::get('/login', 'AuthController@getLogin');
Route::post('/auth/logout', 'AuthController@postLogout'); Route::post('/auth/logout', 'AuthController@postLogout');
Route::get('/auth/oauth', 'AuthController@getOAuth'); Route::get('/auth/oauth', 'AuthController@getOAuth');
Route::get('/about', function() { return View::make('pages.about'); }); Route::get('/about', function () {
Route::get('/faq', function() { return View::make('pages.faq'); }); return View::make('pages.about');
Route::get('/mlpforums-advertising-program', function() { return View::make('pages.mlpforums-advertising-program'); }); });
Route::get('/faq', function () {
return View::make('pages.faq');
});
Route::get('/mlpforums-advertising-program', function () {
return View::make('pages.mlpforums-advertising-program');
});
Route::get('i{id}/{type}.{extension}', 'ImagesController@getImage')->where('id', '\d+'); Route::get('i{id}/{type}.{extension}', 'ImagesController@getImage')->where('id', '\d+');

View file

@ -24,12 +24,11 @@ use Auth;
use DB; use DB;
use Poniverse\Ponyfm\Models\Genre; use Poniverse\Ponyfm\Models\Genre;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use SerializesModels; use SerializesModels;
class DeleteGenre extends Job implements SelfHandling, ShouldQueue class DeleteGenre extends Job implements ShouldQueue
{ {
use InteractsWithQueue, SerializesModels; use InteractsWithQueue, SerializesModels;

View file

@ -24,12 +24,11 @@ use Auth;
use DB; use DB;
use Poniverse\Ponyfm\Models\ShowSong; use Poniverse\Ponyfm\Models\ShowSong;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use SerializesModels; use SerializesModels;
class DeleteShowSong extends Job implements SelfHandling, ShouldQueue class DeleteShowSong extends Job implements ShouldQueue
{ {
use InteractsWithQueue, SerializesModels; use InteractsWithQueue, SerializesModels;

View file

@ -25,7 +25,6 @@ use Carbon\Carbon;
use Config; use Config;
use DB; use DB;
use File; use File;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
@ -36,7 +35,7 @@ use Poniverse\Ponyfm\Models\TrackFile;
use Symfony\Component\Process\Exception\ProcessFailedException; use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
class EncodeTrackFile extends Job implements SelfHandling, ShouldQueue class EncodeTrackFile extends Job implements ShouldQueue
{ {
use InteractsWithQueue, SerializesModels; use InteractsWithQueue, SerializesModels;
/** /**
@ -70,8 +69,7 @@ class EncodeTrackFile extends Job implements SelfHandling, ShouldQueue
*/ */
public function __construct(TrackFile $trackFile, $isExpirable, $autoPublish = false, $isForUpload = false, $isReplacingTrack = false) public function __construct(TrackFile $trackFile, $isExpirable, $autoPublish = false, $isForUpload = false, $isReplacingTrack = false)
{ {
if ( if ((!$isForUpload && $trackFile->is_master) ||
(!$isForUpload && $trackFile->is_master) ||
($isForUpload && $trackFile->is_master && !$trackFile->getFormat()['is_lossless']) ($isForUpload && $trackFile->is_master && !$trackFile->getFormat()['is_lossless'])
) { ) {
throw new InvalidEncodeOptionsException("Master files cannot be encoded unless we're generating a lossless master file during the upload process."); throw new InvalidEncodeOptionsException("Master files cannot be encoded unless we're generating a lossless master file during the upload process.");
@ -97,7 +95,6 @@ class EncodeTrackFile extends Job implements SelfHandling, ShouldQueue
if ($this->trackFile->status === TrackFile::STATUS_PROCESSING) { if ($this->trackFile->status === TrackFile::STATUS_PROCESSING) {
Log::warning('Track file #'.$this->trackFile->id.' (track #'.$this->trackFile->track_id.') is already being processed!'); Log::warning('Track file #'.$this->trackFile->id.' (track #'.$this->trackFile->track_id.') is already being processed!');
return; return;
} elseif (!$this->trackFile->is_expired && File::exists($this->trackFile->getFile())) { } elseif (!$this->trackFile->is_expired && File::exists($this->trackFile->getFile())) {
Log::warning('Track file #'.$this->trackFile->id.' (track #'.$this->trackFile->track_id.') is still valid! No need to re-encode it.'); Log::warning('Track file #'.$this->trackFile->id.' (track #'.$this->trackFile->track_id.') is still valid! No need to re-encode it.');
return; return;

View file

@ -44,7 +44,8 @@ abstract class Job
* method. It ensures that we don't lose the in-memory database during * method. It ensures that we don't lose the in-memory database during
* testing by disconnecting from it - which causes tests to fail. * testing by disconnecting from it - which causes tests to fail.
*/ */
protected function beforeHandle() { protected function beforeHandle()
{
if (App::environment() !== 'testing') { if (App::environment() !== 'testing') {
DB::reconnect(); DB::reconnect();
} }

View file

@ -23,14 +23,13 @@ namespace Poniverse\Ponyfm\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Poniverse\Ponyfm\Jobs\Job; use Poniverse\Ponyfm\Jobs\Job;
use Illuminate\Contracts\Bus\SelfHandling;
use Poniverse\Ponyfm\Library\Notifications\Drivers\AbstractDriver; use Poniverse\Ponyfm\Library\Notifications\Drivers\AbstractDriver;
use Poniverse\Ponyfm\Library\Notifications\Drivers\NativeDriver; use Poniverse\Ponyfm\Library\Notifications\Drivers\NativeDriver;
use Poniverse\Ponyfm\Library\Notifications\Drivers\PonyfmDriver; use Poniverse\Ponyfm\Library\Notifications\Drivers\PonyfmDriver;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use SerializesModels; use SerializesModels;
class SendNotifications extends Job implements SelfHandling, ShouldQueue class SendNotifications extends Job implements ShouldQueue
{ {
use InteractsWithQueue, SerializesModels; use InteractsWithQueue, SerializesModels;

View file

@ -26,10 +26,9 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Poniverse\Ponyfm\Contracts\Searchable; use Poniverse\Ponyfm\Contracts\Searchable;
use Poniverse\Ponyfm\Jobs\Job; use Poniverse\Ponyfm\Jobs\Job;
use Illuminate\Contracts\Bus\SelfHandling;
use SerializesModels; use SerializesModels;
class UpdateSearchIndexForEntity extends Job implements SelfHandling, ShouldQueue class UpdateSearchIndexForEntity extends Job implements ShouldQueue
{ {
use InteractsWithQueue, SerializesModels; use InteractsWithQueue, SerializesModels;

View file

@ -26,7 +26,6 @@ use DB;
use Log; use Log;
use Poniverse\Ponyfm\Models\Genre; use Poniverse\Ponyfm\Models\Genre;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use SerializesModels; use SerializesModels;
@ -39,7 +38,7 @@ use SerializesModels;
* *
* @package Poniverse\Ponyfm\Jobs * @package Poniverse\Ponyfm\Jobs
*/ */
class UpdateTagsForRenamedGenre extends Job implements SelfHandling, ShouldQueue class UpdateTagsForRenamedGenre extends Job implements ShouldQueue
{ {
use InteractsWithQueue, SerializesModels; use InteractsWithQueue, SerializesModels;
@ -77,7 +76,6 @@ class UpdateTagsForRenamedGenre extends Job implements SelfHandling, ShouldQueue
Log::info("Tag updates for the \"{$this->genreThatWasRenamed->name}\" genre are currently in progress! Will try again in 30 seconds."); Log::info("Tag updates for the \"{$this->genreThatWasRenamed->name}\" genre are currently in progress! Will try again in 30 seconds.");
$this->release(30); $this->release(30);
return; return;
} else { } else {
Cache::forever($this->lockKey, true); Cache::forever($this->lockKey, true);
} }

View file

@ -25,7 +25,6 @@ use Cache;
use Log; use Log;
use Poniverse\Ponyfm\Models\ShowSong; use Poniverse\Ponyfm\Models\ShowSong;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use SerializesModels; use SerializesModels;
@ -38,7 +37,7 @@ use SerializesModels;
* *
* @package Poniverse\Ponyfm\Jobs * @package Poniverse\Ponyfm\Jobs
*/ */
class UpdateTagsForRenamedShowSong extends Job implements SelfHandling, ShouldQueue class UpdateTagsForRenamedShowSong extends Job implements ShouldQueue
{ {
use InteractsWithQueue, SerializesModels; use InteractsWithQueue, SerializesModels;
@ -76,7 +75,6 @@ class UpdateTagsForRenamedShowSong extends Job implements SelfHandling, ShouldQu
Log::info("Tag updates for the \"{$this->songThatWasRenamed->title}\" song are currently in progress! Will try again in 30 seconds."); Log::info("Tag updates for the \"{$this->songThatWasRenamed->title}\" song are currently in progress! Will try again in 30 seconds.");
$this->release(30); $this->release(30);
return; return;
} else { } else {
Cache::forever($this->lockKey, true); Cache::forever($this->lockKey, true);
} }

View file

@ -20,7 +20,8 @@
class Assets class Assets
{ {
public static function scriptIncludes(string $area) { public static function scriptIncludes(string $area)
{
$scriptTags = ''; $scriptTags = '';
if ('app' === $area) { if ('app' === $area) {

View file

@ -20,7 +20,7 @@
class AudioCache class AudioCache
{ {
private static $_movieCache = array(); private static $_movieCache = [];
public static function get(string $filename):FFmpegMovie public static function get(string $filename):FFmpegMovie
{ {

View file

@ -28,5 +28,4 @@ class File extends \Illuminate\Support\Facades\File
return $response; return $response;
} }
} }

View file

@ -47,7 +47,7 @@ class Helpers
return '0 MB'; return '0 MB';
} }
$units = array('B', 'KB', 'MB', 'GB', 'TB'); $units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0); $bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024)); $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
@ -82,7 +82,8 @@ class Helpers
* @param array[int] $rgb RGB values in an array * @param array[int] $rgb RGB values in an array
* @return string * @return string
*/ */
public static function rgb2hex($rgb) { public static function rgb2hex($rgb)
{
$hex = "#"; $hex = "#";
$hex .= str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT); $hex .= str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT); $hex .= str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT);

View file

@ -25,10 +25,12 @@ use Poniverse\Ponyfm\Contracts\NotificationHandler;
use Poniverse\Ponyfm\Library\Notifications\RecipientFinder; use Poniverse\Ponyfm\Library\Notifications\RecipientFinder;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
abstract class AbstractDriver implements NotificationHandler { abstract class AbstractDriver implements NotificationHandler
{
private $recipientFinder; private $recipientFinder;
public function __construct() { public function __construct()
{
$this->recipientFinder = new RecipientFinder(get_class($this)); $this->recipientFinder = new RecipientFinder(get_class($this));
} }
@ -41,7 +43,8 @@ abstract class AbstractDriver implements NotificationHandler {
* @param array $notificationData * @param array $notificationData
* @return User[] collection of {@link User} objects * @return User[] collection of {@link User} objects
*/ */
protected function getRecipients(string $notificationType, array $notificationData) { protected function getRecipients(string $notificationType, array $notificationData)
{
return call_user_func_array([$this->recipientFinder, $notificationType], $notificationData); return call_user_func_array([$this->recipientFinder, $notificationType], $notificationData);
} }
} }

View file

@ -20,7 +20,6 @@
namespace Poniverse\Ponyfm\Library\Notifications\Drivers; namespace Poniverse\Ponyfm\Library\Notifications\Drivers;
use Config; use Config;
use Poniverse\Ponyfm\Contracts\Favouritable; use Poniverse\Ponyfm\Contracts\Favouritable;
use Poniverse\Ponyfm\Models\Activity; use Poniverse\Ponyfm\Models\Activity;
@ -30,7 +29,8 @@ use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use Minishlink\WebPush\WebPush; use Minishlink\WebPush\WebPush;
class NativeDriver extends AbstractDriver { class NativeDriver extends AbstractDriver
{
/** /**
* Method for sending notifications to devices * Method for sending notifications to devices
* *
@ -40,9 +40,9 @@ class NativeDriver extends AbstractDriver {
private function pushNotifications(Activity $activity, $recipients) private function pushNotifications(Activity $activity, $recipients)
{ {
if (Config::get('ponyfm.gcm_key') != 'default') { if (Config::get('ponyfm.gcm_key') != 'default') {
$apiKeys = array( $apiKeys = [
'GCM' => Config::get('ponyfm.gcm_key'), 'GCM' => Config::get('ponyfm.gcm_key'),
); ];
$webPush = new WebPush($apiKeys); $webPush = new WebPush($apiKeys);
@ -72,7 +72,8 @@ class NativeDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewTrack(Track $track) { public function publishedNewTrack(Track $track)
{
$activity = Activity::where('user_id', $track->user_id) $activity = Activity::where('user_id', $track->user_id)
->where('activity_type', Activity::TYPE_PUBLISHED_TRACK) ->where('activity_type', Activity::TYPE_PUBLISHED_TRACK)
->where('resource_id', $track->id) ->where('resource_id', $track->id)
@ -85,7 +86,8 @@ class NativeDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewPlaylist(Playlist $playlist) { public function publishedNewPlaylist(Playlist $playlist)
{
$activity = Activity::where('user_id', $playlist->user_id) $activity = Activity::where('user_id', $playlist->user_id)
->where('activity_type', Activity::TYPE_PUBLISHED_PLAYLIST) ->where('activity_type', Activity::TYPE_PUBLISHED_PLAYLIST)
->where('resource_id', $playlist->id) ->where('resource_id', $playlist->id)
@ -94,7 +96,8 @@ class NativeDriver extends AbstractDriver {
$this->pushNotifications($activity, $this->getRecipients(__FUNCTION__, func_get_args())); $this->pushNotifications($activity, $this->getRecipients(__FUNCTION__, func_get_args()));
} }
public function newFollower(User $userBeingFollowed, User $follower) { public function newFollower(User $userBeingFollowed, User $follower)
{
$activity = Activity::where('user_id', $follower->id) $activity = Activity::where('user_id', $follower->id)
->where('activity_type', Activity::TYPE_NEW_FOLLOWER) ->where('activity_type', Activity::TYPE_NEW_FOLLOWER)
->where('resource_id', $userBeingFollowed->id) ->where('resource_id', $userBeingFollowed->id)
@ -106,7 +109,8 @@ class NativeDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newComment(Comment $comment) { public function newComment(Comment $comment)
{
$activity = Activity::where('user_id', $comment->user_id) $activity = Activity::where('user_id', $comment->user_id)
->where('activity_type', Activity::TYPE_NEW_COMMENT) ->where('activity_type', Activity::TYPE_NEW_COMMENT)
->where('resource_id', $comment->id) ->where('resource_id', $comment->id)
@ -118,7 +122,8 @@ class NativeDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) { public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter)
{
$activity = Activity::where('user_id', $favouriter->id) $activity = Activity::where('user_id', $favouriter->id)
->where('activity_type', Activity::TYPE_CONTENT_FAVOURITED) ->where('activity_type', Activity::TYPE_CONTENT_FAVOURITED)
->where('resource_id', $entityBeingFavourited->id) ->where('resource_id', $entityBeingFavourited->id)

View file

@ -20,7 +20,6 @@
namespace Poniverse\Ponyfm\Library\Notifications\Drivers; namespace Poniverse\Ponyfm\Library\Notifications\Drivers;
use ArrayAccess; use ArrayAccess;
use Carbon\Carbon; use Carbon\Carbon;
use Poniverse\Ponyfm\Contracts\Favouritable; use Poniverse\Ponyfm\Contracts\Favouritable;
@ -31,14 +30,16 @@ use Poniverse\Ponyfm\Models\Playlist;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
class PonyfmDriver extends AbstractDriver { class PonyfmDriver extends AbstractDriver
{
/** /**
* A helper method for bulk insertion of notification records. * A helper method for bulk insertion of notification records.
* *
* @param int $activityId * @param int $activityId
* @param User[] $recipients collection of {@link User} objects * @param User[] $recipients collection of {@link User} objects
*/ */
private function insertNotifications(int $activityId, $recipients) { private function insertNotifications(int $activityId, $recipients)
{
$notifications = []; $notifications = [];
foreach ($recipients as $recipient) { foreach ($recipients as $recipient) {
$notifications[] = [ $notifications[] = [
@ -52,7 +53,8 @@ class PonyfmDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewTrack(Track $track) { public function publishedNewTrack(Track $track)
{
$activity = Activity::create([ $activity = Activity::create([
'created_at' => Carbon::now(), 'created_at' => Carbon::now(),
'user_id' => $track->user_id, 'user_id' => $track->user_id,
@ -67,7 +69,8 @@ class PonyfmDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewPlaylist(Playlist $playlist) { public function publishedNewPlaylist(Playlist $playlist)
{
$activity = Activity::create([ $activity = Activity::create([
'created_at' => Carbon::now(), 'created_at' => Carbon::now(),
'user_id' => $playlist->user_id, 'user_id' => $playlist->user_id,
@ -79,7 +82,8 @@ class PonyfmDriver extends AbstractDriver {
$this->insertNotifications($activity->id, $this->getRecipients(__FUNCTION__, func_get_args())); $this->insertNotifications($activity->id, $this->getRecipients(__FUNCTION__, func_get_args()));
} }
public function newFollower(User $userBeingFollowed, User $follower) { public function newFollower(User $userBeingFollowed, User $follower)
{
$activity = Activity::create([ $activity = Activity::create([
'created_at' => Carbon::now(), 'created_at' => Carbon::now(),
'user_id' => $follower->id, 'user_id' => $follower->id,
@ -94,7 +98,8 @@ class PonyfmDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newComment(Comment $comment) { public function newComment(Comment $comment)
{
$activity = Activity::create([ $activity = Activity::create([
'created_at' => Carbon::now(), 'created_at' => Carbon::now(),
'user_id' => $comment->user_id, 'user_id' => $comment->user_id,
@ -109,7 +114,8 @@ class PonyfmDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) { public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter)
{
$activity = Activity::create([ $activity = Activity::create([
'created_at' => Carbon::now(), 'created_at' => Carbon::now(),
'user_id' => $favouriter->id, 'user_id' => $favouriter->id,

View file

@ -20,7 +20,6 @@
namespace Poniverse\Ponyfm\Library\Notifications; namespace Poniverse\Ponyfm\Library\Notifications;
use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Bus\DispatchesJobs;
use Poniverse\Ponyfm\Contracts\Favouritable; use Poniverse\Ponyfm\Contracts\Favouritable;
use Poniverse\Ponyfm\Contracts\NotificationHandler; use Poniverse\Ponyfm\Contracts\NotificationHandler;
@ -39,45 +38,52 @@ use Poniverse\Ponyfm\Models\User;
* All the heavy lifting happens asynchronously in the {@link SendNotifications} * All the heavy lifting happens asynchronously in the {@link SendNotifications}
* job and the notification drivers. * job and the notification drivers.
*/ */
class NotificationManager implements NotificationHandler { class NotificationManager implements NotificationHandler
{
use DispatchesJobs; use DispatchesJobs;
private function dispatchNotification(string $notificationType, array $notificationData) { private function dispatchNotification(string $notificationType, array $notificationData)
{
$this->dispatch((new SendNotifications($notificationType, $notificationData))->onQueue('notifications')); $this->dispatch((new SendNotifications($notificationType, $notificationData))->onQueue('notifications'));
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewTrack(Track $track) { public function publishedNewTrack(Track $track)
{
$this->dispatchNotification(__FUNCTION__, func_get_args()); $this->dispatchNotification(__FUNCTION__, func_get_args());
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewPlaylist(Playlist $playlist) { public function publishedNewPlaylist(Playlist $playlist)
{
$this->dispatchNotification(__FUNCTION__, func_get_args()); $this->dispatchNotification(__FUNCTION__, func_get_args());
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newFollower(User $userBeingFollowed, User $follower) { public function newFollower(User $userBeingFollowed, User $follower)
{
$this->dispatchNotification(__FUNCTION__, func_get_args()); $this->dispatchNotification(__FUNCTION__, func_get_args());
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newComment(Comment $comment) { public function newComment(Comment $comment)
{
$this->dispatchNotification(__FUNCTION__, func_get_args()); $this->dispatchNotification(__FUNCTION__, func_get_args());
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) { public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter)
{
$this->dispatchNotification(__FUNCTION__, func_get_args()); $this->dispatchNotification(__FUNCTION__, func_get_args());
} }
} }

View file

@ -20,7 +20,6 @@
namespace Poniverse\Ponyfm\Library\Notifications; namespace Poniverse\Ponyfm\Library\Notifications;
use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Bus\DispatchesJobs;
use Poniverse\Ponyfm\Contracts\Favouritable; use Poniverse\Ponyfm\Contracts\Favouritable;
use Poniverse\Ponyfm\Contracts\NotificationHandler; use Poniverse\Ponyfm\Contracts\NotificationHandler;
@ -40,24 +39,28 @@ use Poniverse\Ponyfm\Models\User;
* This class returns a list of users who are to receive a particular notification. * This class returns a list of users who are to receive a particular notification.
* It is instantiated on a per-driver basis. * It is instantiated on a per-driver basis.
*/ */
class RecipientFinder implements NotificationHandler { class RecipientFinder implements NotificationHandler
{
/** /**
* @var string class name of a notification driver * @var string class name of a notification driver
*/ */
private $notificationDriver; private $notificationDriver;
public function __construct(string $notificationDriver) { public function __construct(string $notificationDriver)
{
$this->notificationDriver = $notificationDriver; $this->notificationDriver = $notificationDriver;
} }
private function fail() { private function fail()
{
throw new \InvalidArgumentException("Unknown notification driver given: {$this->notificationDriver}"); throw new \InvalidArgumentException("Unknown notification driver given: {$this->notificationDriver}");
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewTrack(Track $track) { public function publishedNewTrack(Track $track)
{
switch ($this->notificationDriver) { switch ($this->notificationDriver) {
case PonyfmDriver::class: case PonyfmDriver::class:
return $track->user->followers; return $track->user->followers;
@ -84,7 +87,8 @@ class RecipientFinder implements NotificationHandler {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewPlaylist(Playlist $playlist) { public function publishedNewPlaylist(Playlist $playlist)
{
switch ($this->notificationDriver) { switch ($this->notificationDriver) {
case PonyfmDriver::class: case PonyfmDriver::class:
return $playlist->user->followers; return $playlist->user->followers;
@ -111,7 +115,8 @@ class RecipientFinder implements NotificationHandler {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newFollower(User $userBeingFollowed, User $follower) { public function newFollower(User $userBeingFollowed, User $follower)
{
switch ($this->notificationDriver) { switch ($this->notificationDriver) {
case PonyfmDriver::class: case PonyfmDriver::class:
return [$userBeingFollowed]; return [$userBeingFollowed];
@ -125,7 +130,8 @@ class RecipientFinder implements NotificationHandler {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newComment(Comment $comment) { public function newComment(Comment $comment)
{
switch ($this->notificationDriver) { switch ($this->notificationDriver) {
case PonyfmDriver::class: case PonyfmDriver::class:
return return
@ -142,7 +148,8 @@ class RecipientFinder implements NotificationHandler {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) { public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter)
{
switch ($this->notificationDriver) { switch ($this->notificationDriver) {
case PonyfmDriver::class: case PonyfmDriver::class:
return return

View file

@ -257,7 +257,7 @@ class PfmValidator extends Illuminate\Validation\Validator
/** OLD CODE /** OLD CODE
* public function validate_required_when($attribute, $value, $parameters) * public function validate_required_when($attribute, $value, $parameters)
* { * {
* if ( Input::get($parameters[0]) === $parameters[1] && static::required($attribute, $value) ){ * if ( Request::get($parameters[0]) === $parameters[1] && static::required($attribute, $value) ){
* return true; * return true;
* *
* } else { * } else {
@ -269,7 +269,7 @@ class PfmValidator extends Illuminate\Validation\Validator
// custom required_when validator // custom required_when validator
public function validateRequiredWhen($attribute, $value, $parameters) public function validateRequiredWhen($attribute, $value, $parameters)
{ {
if (Input::get($parameters[0]) == $parameters[1]) { if (Request::get($parameters[0]) == $parameters[1]) {
return $this->validate_required($attribute, $value); return $this->validate_required($attribute, $value);
} }

View file

@ -28,7 +28,8 @@ namespace Poniverse;
* @link https://tools.ietf.org/html/draft-richer-oauth-introspection-06 * @link https://tools.ietf.org/html/draft-richer-oauth-introspection-06
* @package Poniverse * @package Poniverse
*/ */
class AccessTokenInfo { class AccessTokenInfo
{
protected $token; protected $token;
protected $isActive; protected $isActive;
@ -42,21 +43,24 @@ class AccessTokenInfo {
protected $issuer; protected $issuer;
protected $tokenType; protected $tokenType;
public function __construct($accessToken) { public function __construct($accessToken)
{
$this->token = $accessToken; $this->token = $accessToken;
} }
/** /**
* @return mixed * @return mixed
*/ */
public function getToken() { public function getToken()
{
return $this->token; return $this->token;
} }
/** /**
* @return bool * @return bool
*/ */
public function getIsActive() { public function getIsActive()
{
return $this->isActive; return $this->isActive;
} }
@ -64,7 +68,8 @@ class AccessTokenInfo {
* @param bool $isActive * @param bool $isActive
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setIsActive($isActive) { public function setIsActive($isActive)
{
$this->isActive = $isActive; $this->isActive = $isActive;
return $this; return $this;
} }
@ -72,7 +77,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getExpiresAt() { public function getExpiresAt()
{
return $this->expiresAt; return $this->expiresAt;
} }
@ -80,7 +86,8 @@ class AccessTokenInfo {
* @param mixed $expiresAt * @param mixed $expiresAt
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setExpiresAt($expiresAt) { public function setExpiresAt($expiresAt)
{
$this->expiresAt = $expiresAt; $this->expiresAt = $expiresAt;
return $this; return $this;
} }
@ -88,7 +95,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getIssuedAt() { public function getIssuedAt()
{
return $this->issuedAt; return $this->issuedAt;
} }
@ -96,7 +104,8 @@ class AccessTokenInfo {
* @param mixed $issuedAt * @param mixed $issuedAt
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setIssuedAt($issuedAt) { public function setIssuedAt($issuedAt)
{
$this->issuedAt = $issuedAt; $this->issuedAt = $issuedAt;
return $this; return $this;
} }
@ -104,7 +113,8 @@ class AccessTokenInfo {
/** /**
* @return array * @return array
*/ */
public function getScopes() { public function getScopes()
{
return $this->scopes; return $this->scopes;
} }
@ -112,7 +122,8 @@ class AccessTokenInfo {
* @param array|string $scopes * @param array|string $scopes
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setScopes($scopes) { public function setScopes($scopes)
{
if (is_array($scopes)) { if (is_array($scopes)) {
$this->scopes = $scopes; $this->scopes = $scopes;
} else { } else {
@ -125,7 +136,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getClientId() { public function getClientId()
{
return $this->clientId; return $this->clientId;
} }
@ -133,7 +145,8 @@ class AccessTokenInfo {
* @param mixed $clientId * @param mixed $clientId
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setClientId($clientId) { public function setClientId($clientId)
{
$this->clientId = $clientId; $this->clientId = $clientId;
return $this; return $this;
} }
@ -141,7 +154,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getSub() { public function getSub()
{
return $this->sub; return $this->sub;
} }
@ -149,7 +163,8 @@ class AccessTokenInfo {
* @param mixed $sub * @param mixed $sub
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setSub($sub) { public function setSub($sub)
{
$this->sub = $sub; $this->sub = $sub;
return $this; return $this;
} }
@ -157,7 +172,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getUserId() { public function getUserId()
{
return $this->userId; return $this->userId;
} }
@ -165,7 +181,8 @@ class AccessTokenInfo {
* @param mixed $userId * @param mixed $userId
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setUserId($userId) { public function setUserId($userId)
{
$this->userId = $userId; $this->userId = $userId;
return $this; return $this;
} }
@ -173,7 +190,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getIntendedAudience() { public function getIntendedAudience()
{
return $this->intendedAudience; return $this->intendedAudience;
} }
@ -181,7 +199,8 @@ class AccessTokenInfo {
* @param mixed $intendedAudience * @param mixed $intendedAudience
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setIntendedAudience($intendedAudience) { public function setIntendedAudience($intendedAudience)
{
$this->intendedAudience = $intendedAudience; $this->intendedAudience = $intendedAudience;
return $this; return $this;
} }
@ -189,7 +208,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getIssuer() { public function getIssuer()
{
return $this->issuer; return $this->issuer;
} }
@ -197,7 +217,8 @@ class AccessTokenInfo {
* @param mixed $issuer * @param mixed $issuer
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setIssuer($issuer) { public function setIssuer($issuer)
{
$this->issuer = $issuer; $this->issuer = $issuer;
return $this; return $this;
} }
@ -205,7 +226,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getTokenType() { public function getTokenType()
{
return $this->tokenType; return $this->tokenType;
} }
@ -213,7 +235,8 @@ class AccessTokenInfo {
* @param mixed $tokenType * @param mixed $tokenType
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setTokenType($tokenType) { public function setTokenType($tokenType)
{
$this->tokenType = $tokenType; $this->tokenType = $tokenType;
return $this; return $this;
} }

View file

@ -28,7 +28,8 @@ use Poniverse\Ponyfm\Exceptions\InvalidAccessTokenException;
* this class is going to be a simple flat api class. * this class is going to be a simple flat api class.
*/ */
class Poniverse { class Poniverse
{
protected $clientId; protected $clientId;
protected $clientSecret; protected $clientSecret;
protected $accessToken; protected $accessToken;

View file

@ -102,7 +102,7 @@ class SplClassLoader
*/ */
public function register() public function register()
{ {
spl_autoload_register(array($this, 'loadClass')); spl_autoload_register([$this, 'loadClass']);
} }
/** /**
@ -110,7 +110,7 @@ class SplClassLoader
*/ */
public function unregister() public function unregister()
{ {
spl_autoload_unregister(array($this, 'loadClass')); spl_autoload_unregister([$this, 'loadClass']);
} }
/** /**

View file

@ -5,7 +5,7 @@ require(__DIR__ . '/../bootstrap.php');
// a parser with different configuration options for a particular mime type // a parser with different configuration options for a particular mime type
// Example setting a namespace for the XMLHandler parser // Example setting a namespace for the XMLHandler parser
$conf = array('namespace' => 'http://example.com'); $conf = ['namespace' => 'http://example.com'];
\Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf)); \Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf));
// We can also add the parsers with our own... // We can also add the parsers with our own...

View file

@ -14,7 +14,7 @@ $response = Request::get($uri)
echo "The event {$response->body->event} will take place on {$response->body->event_start}\n"; echo "The event {$response->body->event} will take place on {$response->body->event_start}\n";
// Example overriding the default JSON handler with one that encodes the response as an array // Example overriding the default JSON handler with one that encodes the response as an array
\Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(array('decode_as_array' => true))); \Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(['decode_as_array' => true]));
$response = Request::get($uri) $response = Request::get($uri)
->expectsType('json') ->expectsType('json')

View file

@ -21,7 +21,7 @@ class Bootstrap
*/ */
public static function init() public static function init()
{ {
spl_autoload_register(array('\Httpful\Bootstrap', 'autoload')); spl_autoload_register(['\Httpful\Bootstrap', 'autoload']);
self::registerHandlers(); self::registerHandlers();
} }
@ -40,7 +40,7 @@ class Bootstrap
*/ */
public static function pharInit() public static function pharInit()
{ {
spl_autoload_register(array('\Httpful\Bootstrap', 'pharAutoload')); spl_autoload_register(['\Httpful\Bootstrap', 'pharAutoload']);
self::registerHandlers(); self::registerHandlers();
} }
@ -78,17 +78,18 @@ class Bootstrap
// @todo check a conf file to load from that instead of // @todo check a conf file to load from that instead of
// hardcoding into the library? // hardcoding into the library?
$handlers = array( $handlers = [
\Httpful\Mime::JSON => new \Httpful\Handlers\JsonHandler(), \Httpful\Mime::JSON => new \Httpful\Handlers\JsonHandler(),
\Httpful\Mime::XML => new \Httpful\Handlers\XmlHandler(), \Httpful\Mime::XML => new \Httpful\Handlers\XmlHandler(),
\Httpful\Mime::FORM => new \Httpful\Handlers\FormHandler(), \Httpful\Mime::FORM => new \Httpful\Handlers\FormHandler(),
\Httpful\Mime::CSV => new \Httpful\Handlers\CsvHandler(), \Httpful\Mime::CSV => new \Httpful\Handlers\CsvHandler(),
); ];
foreach ($handlers as $mime => $handler) { foreach ($handlers as $mime => $handler) {
// Don't overwrite if the handler has already been registered // Don't overwrite if the handler has already been registered
if (Httpful::hasParserRegistered($mime)) if (Httpful::hasParserRegistered($mime)) {
continue; continue;
}
Httpful::register($mime, $handler); Httpful::register($mime, $handler);
} }

View file

@ -14,17 +14,19 @@ class CsvHandler extends MimeHandlerAdapter
*/ */
public function parse($body) public function parse($body)
{ {
if (empty($body)) if (empty($body)) {
return null; return null;
}
$parsed = array(); $parsed = [];
$fp = fopen('data://text/plain;base64,' . base64_encode($body), 'r'); $fp = fopen('data://text/plain;base64,' . base64_encode($body), 'r');
while (($r = fgetcsv($fp)) !== FALSE) { while (($r = fgetcsv($fp)) !== false) {
$parsed[] = $r; $parsed[] = $r;
} }
if (empty($parsed)) if (empty($parsed)) {
throw new \Exception("Unable to parse response as CSV"); throw new \Exception("Unable to parse response as CSV");
}
return $parsed; return $parsed;
} }

View file

@ -14,7 +14,7 @@ class FormHandler extends MimeHandlerAdapter
*/ */
public function parse($body) public function parse($body)
{ {
$parsed = array(); $parsed = [];
parse_str($body, $parsed); parse_str($body, $parsed);
return $parsed; return $parsed;
} }

View file

@ -21,11 +21,13 @@ class JsonHandler extends MimeHandlerAdapter
*/ */
public function parse($body) public function parse($body)
{ {
if (empty($body)) if (empty($body)) {
return null; return null;
}
$parsed = json_decode($body, $this->decode_as_array); $parsed = json_decode($body, $this->decode_as_array);
if (is_null($parsed)) if (is_null($parsed)) {
throw new \Exception("Unable to parse response as JSON"); throw new \Exception("Unable to parse response as JSON");
}
return $parsed; return $parsed;
} }

View file

@ -10,7 +10,7 @@ namespace Httpful\Handlers;
class MimeHandlerAdapter class MimeHandlerAdapter
{ {
public function __construct(array $args = array()) public function __construct(array $args = [])
{ {
$this->init($args); $this->init($args);
} }

View file

@ -23,7 +23,7 @@ class XmlHandler extends MimeHandlerAdapter
/** /**
* @param array $conf sets configuration options * @param array $conf sets configuration options
*/ */
public function __construct(array $conf = array()) public function __construct(array $conf = [])
{ {
$this->namespace = isset($conf['namespace']) ? $conf['namespace'] : ''; $this->namespace = isset($conf['namespace']) ? $conf['namespace'] : '';
$this->libxml_opts = isset($conf['libxml_opts']) ? $conf['libxml_opts'] : 0; $this->libxml_opts = isset($conf['libxml_opts']) ? $conf['libxml_opts'] : 0;
@ -36,11 +36,13 @@ class XmlHandler extends MimeHandlerAdapter
*/ */
public function parse($body) public function parse($body)
{ {
if (empty($body)) if (empty($body)) {
return null; return null;
}
$parsed = simplexml_load_string($body, null, $this->libxml_opts, $this->namespace); $parsed = simplexml_load_string($body, null, $this->libxml_opts, $this->namespace);
if ($parsed === false) if ($parsed === false) {
throw new \Exception("Unable to parse response as XML"); throw new \Exception("Unable to parse response as XML");
}
return $parsed; return $parsed;
} }
@ -84,7 +86,7 @@ class XmlHandler extends MimeHandlerAdapter
} else { } else {
$node->appendChild($dom->createTextNode($value)); $node->appendChild($dom->createTextNode($value));
} }
return array($node, $dom); return [$node, $dom];
} }
/** /**
* @author Zack Douglas <zack@zackerydouglas.info> * @author Zack Douglas <zack@zackerydouglas.info>
@ -100,7 +102,7 @@ class XmlHandler extends MimeHandlerAdapter
$parent->appendChild($el); $parent->appendChild($el);
$this->_future_serializeAsXml($v, $el, $dom); $this->_future_serializeAsXml($v, $el, $dom);
} }
return array($parent, $dom); return [$parent, $dom];
} }
/** /**
* @author Zack Douglas <zack@zackerydouglas.info> * @author Zack Douglas <zack@zackerydouglas.info>
@ -115,6 +117,6 @@ class XmlHandler extends MimeHandlerAdapter
$this->_future_serializeAsXml($pr->getValue($value), $el, $dom); $this->_future_serializeAsXml($pr->getValue($value), $el, $dom);
} }
} }
return array($parent, $dom); return [$parent, $dom];
} }
} }

View file

@ -21,7 +21,7 @@ class Http
*/ */
public static function safeMethods() public static function safeMethods()
{ {
return array(self::HEAD, self::GET, self::OPTIONS, self::TRACE); return [self::HEAD, self::GET, self::OPTIONS, self::TRACE];
} }
/** /**
@ -50,7 +50,7 @@ class Http
// Though it is possible to be idempotent, POST // Though it is possible to be idempotent, POST
// is not guarunteed to be, and more often than // is not guarunteed to be, and more often than
// not, it is not. // not, it is not.
return array(self::HEAD, self::GET, self::PUT, self::DELETE, self::OPTIONS, self::TRACE, self::PATCH); return [self::HEAD, self::GET, self::PUT, self::DELETE, self::OPTIONS, self::TRACE, self::PATCH];
} }
/** /**
@ -80,7 +80,6 @@ class Http
*/ */
public static function canHaveBody() public static function canHaveBody()
{ {
return array(self::POST, self::PUT, self::PATCH, self::OPTIONS); return [self::POST, self::PUT, self::PATCH, self::OPTIONS];
} }
} }

View file

@ -2,10 +2,11 @@
namespace Httpful; namespace Httpful;
class Httpful { class Httpful
{
const VERSION = '0.2.4'; const VERSION = '0.2.4';
private static $mimeRegistrar = array(); private static $mimeRegistrar = [];
private static $default = null; private static $default = null;
/** /**

View file

@ -22,7 +22,7 @@ class Mime
* Map short name for a mime type * Map short name for a mime type
* to a full proper mime type * to a full proper mime type
*/ */
public static $mimes = array( public static $mimes = [
'json' => self::JSON, 'json' => self::JSON,
'xml' => self::XML, 'xml' => self::XML,
'form' => self::FORM, 'form' => self::FORM,
@ -34,7 +34,7 @@ class Mime
'javascript'=> self::JS, 'javascript'=> self::JS,
'yaml' => self::YAML, 'yaml' => self::YAML,
'csv' => self::CSV, 'csv' => self::CSV,
); ];
/** /**
* Get the full Mime Type name from a "short name". * Get the full Mime Type name from a "short name".

View file

@ -30,12 +30,12 @@ class Request
public $uri, public $uri,
$method = Http::GET, $method = Http::GET,
$headers = array(), $headers = [],
$raw_headers = '', $raw_headers = '',
$strict_ssl = false, $strict_ssl = false,
$content_type, $content_type,
$expected_type, $expected_type,
$additional_curl_opts = array(), $additional_curl_opts = [],
$auto_parse = true, $auto_parse = true,
$serialize_payload_method = self::SERIALIZE_PAYLOAD_SMART, $serialize_payload_method = self::SERIALIZE_PAYLOAD_SMART,
$username, $username,
@ -46,7 +46,7 @@ class Request
$error_callback, $error_callback,
$follow_redirects = false, $follow_redirects = false,
$max_redirects = self::MAX_REDIRECTS_DEFAULT, $max_redirects = self::MAX_REDIRECTS_DEFAULT,
$payload_serializers = array(); $payload_serializers = [];
// Options // Options
// private $_options = array( // private $_options = array(
@ -70,7 +70,9 @@ class Request
*/ */
private function __construct($attrs = null) private function __construct($attrs = null)
{ {
if (!is_array($attrs)) return; if (!is_array($attrs)) {
return;
}
foreach ($attrs as $attr => $value) { foreach ($attrs as $attr => $value) {
$this->$attr = $value; $this->$attr = $value;
} }
@ -195,8 +197,9 @@ class Request
*/ */
public function send() public function send()
{ {
if (!$this->hasBeenInitialized()) if (!$this->hasBeenInitialized()) {
$this->_curlPrep(); $this->_curlPrep();
}
$result = curl_exec($this->_ch); $result = curl_exec($this->_ch);
@ -275,7 +278,8 @@ class Request
/** /**
* @return is this request setup for client side cert? * @return is this request setup for client side cert?
*/ */
public function hasClientSideCert() { public function hasClientSideCert()
{
return isset($this->client_cert) && isset($this->client_key); return isset($this->client_cert) && isset($this->client_key);
} }
@ -326,7 +330,9 @@ class Request
*/ */
public function mime($mime) public function mime($mime)
{ {
if (empty($mime)) return $this; if (empty($mime)) {
return $this;
}
$this->content_type = $this->expected_type = Mime::getFullMime($mime); $this->content_type = $this->expected_type = Mime::getFullMime($mime);
return $this; return $this;
} }
@ -349,7 +355,9 @@ class Request
*/ */
public function method($method) public function method($method)
{ {
if (empty($method)) return $this; if (empty($method)) {
return $this;
}
$this->method = $method; $this->method = $method;
return $this; return $this;
} }
@ -360,7 +368,9 @@ class Request
*/ */
public function expects($mime) public function expects($mime)
{ {
if (empty($mime)) return $this; if (empty($mime)) {
return $this;
}
$this->expected_type = Mime::getFullMime($mime); $this->expected_type = Mime::getFullMime($mime);
return $this; return $this;
} }
@ -376,7 +386,9 @@ class Request
*/ */
public function contentType($mime) public function contentType($mime)
{ {
if (empty($mime)) return $this; if (empty($mime)) {
return $this;
}
$this->content_type = Mime::getFullMime($mime); $this->content_type = Mime::getFullMime($mime);
return $this; return $this;
} }
@ -419,9 +431,10 @@ class Request
* @param string $auth_username Authentication username. Default null * @param string $auth_username Authentication username. Default null
* @param string $auth_password Authentication password. Default null * @param string $auth_password Authentication password. Default null
*/ */
public function useProxy($proxy_host, $proxy_port = 80, $auth_type = null, $auth_username = null, $auth_password = null){ public function useProxy($proxy_host, $proxy_port = 80, $auth_type = null, $auth_username = null, $auth_password = null)
{
$this->addOnCurlOption(CURLOPT_PROXY, "{$proxy_host}:{$proxy_port}"); $this->addOnCurlOption(CURLOPT_PROXY, "{$proxy_host}:{$proxy_port}");
if(in_array($auth_type, array(CURLAUTH_BASIC,CURLAUTH_NTLM)) ){ if (in_array($auth_type, [CURLAUTH_BASIC,CURLAUTH_NTLM])) {
$this->addOnCurlOption(CURLOPT_PROXYAUTH, $auth_type) $this->addOnCurlOption(CURLOPT_PROXYAUTH, $auth_type)
->addOnCurlOption(CURLOPT_PROXYUSERPWD, "{$auth_username}:{$auth_password}"); ->addOnCurlOption(CURLOPT_PROXYUSERPWD, "{$auth_username}:{$auth_password}");
} }
@ -431,7 +444,8 @@ class Request
/** /**
* @return is this request setup for using proxy? * @return is this request setup for using proxy?
*/ */
public function hasProxy(){ public function hasProxy()
{
return is_string($this->additional_curl_opts[CURLOPT_PROXY]); return is_string($this->additional_curl_opts[CURLOPT_PROXY]);
} }
@ -646,15 +660,17 @@ class Request
// This method also adds the custom header support as described in the // This method also adds the custom header support as described in the
// method comments // method comments
if (count($args) === 0) if (count($args) === 0) {
return; return;
}
// Strip the sugar. If it leads with "with", strip. // Strip the sugar. If it leads with "with", strip.
// This is okay because: No defined HTTP headers begin with with, // This is okay because: No defined HTTP headers begin with with,
// and if you are defining a custom header, the standard is to prefix it // and if you are defining a custom header, the standard is to prefix it
// with an "X-", so that should take care of any collisions. // with an "X-", so that should take care of any collisions.
if (substr($method, 0, 4) === 'with') if (substr($method, 0, 4) === 'with') {
$method = substr($method, 4); $method = substr($method, 4);
}
// Precede upper case letters with dashes, uppercase the first letter of method // Precede upper case letters with dashes, uppercase the first letter of method
$header = ucwords(implode('-', preg_split('/([A-Z][^A-Z]*)/', $method, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY))); $header = ucwords(implode('-', preg_split('/([A-Z][^A-Z]*)/', $method, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY)));
@ -681,7 +697,7 @@ class Request
// recusion. Do not use this syntax elsewhere. // recusion. Do not use this syntax elsewhere.
// It goes against the whole readability // It goes against the whole readability
// and transparency idea. // and transparency idea.
self::$_template = new Request(array('method' => Http::GET)); self::$_template = new Request(['method' => Http::GET]);
// This is more like it... // This is more like it...
self::$_template self::$_template
@ -695,12 +711,14 @@ class Request
*/ */
private function _setDefaults() private function _setDefaults()
{ {
if (!isset(self::$_template)) if (!isset(self::$_template)) {
self::_initializeDefaults(); self::_initializeDefaults();
}
foreach (self::$_template as $k => $v) { foreach (self::$_template as $k => $v) {
if ($k[0] != '_') if ($k[0] != '_') {
$this->$k = $v; $this->$k = $v;
} }
}
return $this; return $this;
} }
@ -725,8 +743,9 @@ class Request
Bootstrap::init(); Bootstrap::init();
// Setup the default template if need be // Setup the default template if need be
if (!isset(self::$_template)) if (!isset(self::$_template)) {
self::_initializeDefaults(); self::_initializeDefaults();
}
$request = new Request(); $request = new Request();
return $request return $request
@ -745,8 +764,9 @@ class Request
public function _curlPrep() public function _curlPrep()
{ {
// Check for required stuff // Check for required stuff
if (!isset($this->uri)) if (!isset($this->uri)) {
throw new \Exception('Attempting to send a request before defining a URI endpoint.'); throw new \Exception('Attempting to send a request before defining a URI endpoint.');
}
$ch = curl_init($this->uri); $ch = curl_init($this->uri);
@ -757,12 +777,13 @@ class Request
} }
if ($this->hasClientSideCert()) { if ($this->hasClientSideCert()) {
if (!file_exists($this->client_key)) {
if (!file_exists($this->client_key))
throw new \Exception('Could not read Client Key'); throw new \Exception('Could not read Client Key');
}
if (!file_exists($this->client_cert)) if (!file_exists($this->client_cert)) {
throw new \Exception('Could not read Client Certificate'); throw new \Exception('Could not read Client Certificate');
}
curl_setopt($ch, CURLOPT_SSLCERTTYPE, $this->client_encoding); curl_setopt($ch, CURLOPT_SSLCERTTYPE, $this->client_encoding);
curl_setopt($ch, CURLOPT_SSLKEYTYPE, $this->client_encoding); curl_setopt($ch, CURLOPT_SSLKEYTYPE, $this->client_encoding);
@ -792,7 +813,7 @@ class Request
$this->headers['Content-Length'] = strlen($this->serialized_payload); $this->headers['Content-Length'] = strlen($this->serialized_payload);
} }
$headers = array(); $headers = [];
// https://github.com/nategood/httpful/issues/37 // https://github.com/nategood/httpful/issues/37
// Except header removes any HTTP 1.1 Continue from response headers // Except header removes any HTTP 1.1 Continue from response headers
$headers[] = 'Expect:'; $headers[] = 'Expect:';
@ -851,7 +872,8 @@ class Request
return $this; return $this;
} }
public function buildUserAgent() { public function buildUserAgent()
{
$user_agent = 'User-Agent: Httpful/' . Httpful::VERSION . ' (cURL/'; $user_agent = 'User-Agent: Httpful/' . Httpful::VERSION . ' (cURL/';
$curl = \curl_version(); $curl = \curl_version();
@ -864,8 +886,11 @@ class Request
$user_agent .= ' PHP/'. PHP_VERSION . ' (' . PHP_OS . ')'; $user_agent .= ' PHP/'. PHP_VERSION . ' (' . PHP_OS . ')';
if (isset($_SERVER['SERVER_SOFTWARE'])) { if (isset($_SERVER['SERVER_SOFTWARE'])) {
$user_agent .= ' ' . \preg_replace('~PHP/[\d\.]+~U', '', $user_agent .= ' ' . \preg_replace(
$_SERVER['SERVER_SOFTWARE']); '~PHP/[\d\.]+~U',
'',
$_SERVER['SERVER_SOFTWARE']
);
} else { } else {
if (isset($_SERVER['TERM_PROGRAM'])) { if (isset($_SERVER['TERM_PROGRAM'])) {
$user_agent .= " {$_SERVER['TERM_PROGRAM']}"; $user_agent .= " {$_SERVER['TERM_PROGRAM']}";
@ -915,12 +940,14 @@ class Request
*/ */
private function _serializePayload($payload) private function _serializePayload($payload)
{ {
if (empty($payload) || $this->serialize_payload_method === self::SERIALIZE_PAYLOAD_NEVER) if (empty($payload) || $this->serialize_payload_method === self::SERIALIZE_PAYLOAD_NEVER) {
return $payload; return $payload;
}
// When we are in "smart" mode, don't serialize strings/scalars, assume they are already serialized // When we are in "smart" mode, don't serialize strings/scalars, assume they are already serialized
if ($this->serialize_payload_method === self::SERIALIZE_PAYLOAD_SMART && is_scalar($payload)) if ($this->serialize_payload_method === self::SERIALIZE_PAYLOAD_SMART && is_scalar($payload)) {
return $payload; return $payload;
}
// Use a custom serializer if one is registered for this mime type // Use a custom serializer if one is registered for this mime type
if (isset($this->payload_serializers['*']) || isset($this->payload_serializers[$this->content_type])) { if (isset($this->payload_serializers['*']) || isset($this->payload_serializers[$this->content_type])) {

View file

@ -112,7 +112,7 @@ class Response
public function _parseHeaders($headers) public function _parseHeaders($headers)
{ {
$headers = preg_split("/(\r|\n)+/", $headers, -1, \PREG_SPLIT_NO_EMPTY); $headers = preg_split("/(\r|\n)+/", $headers, -1, \PREG_SPLIT_NO_EMPTY);
$parse_headers = array(); $parse_headers = [];
for ($i = 1; $i < count($headers); $i++) { for ($i = 1; $i < count($headers); $i++) {
list($key, $raw_value) = explode(':', $headers[$i], 2); list($key, $raw_value) = explode(':', $headers[$i], 2);
$key = trim($key); $key = trim($key);

View file

@ -2,7 +2,8 @@
namespace Httpful\Response; namespace Httpful\Response;
final class Headers implements \ArrayAccess, \Countable { final class Headers implements \ArrayAccess, \Countable
{
private $headers; private $headers;
@ -15,7 +16,7 @@ final class Headers implements \ArrayAccess, \Countable {
{ {
$lines = preg_split("/(\r|\n)+/", $string, -1, PREG_SPLIT_NO_EMPTY); $lines = preg_split("/(\r|\n)+/", $string, -1, PREG_SPLIT_NO_EMPTY);
array_shift($lines); // HTTP HEADER array_shift($lines); // HTTP HEADER
$headers = array(); $headers = [];
foreach ($lines as $line) { foreach ($lines as $line) {
list($name, $value) = explode(':', $line, 2); list($name, $value) = explode(':', $line, 2);
$headers[strtolower(trim($name))] = trim($value); $headers[strtolower(trim($name))] = trim($value);
@ -54,5 +55,4 @@ final class Headers implements \ArrayAccess, \Countable {
{ {
return $this->headers; return $this->headers;
} }
} }

View file

@ -67,10 +67,10 @@ X-My-Header:Value2\r\n";
function testMethods() function testMethods()
{ {
$valid_methods = array('get', 'post', 'delete', 'put', 'options', 'head'); $valid_methods = ['get', 'post', 'delete', 'put', 'options', 'head'];
$url = 'http://example.com/'; $url = 'http://example.com/';
foreach ($valid_methods as $method) { foreach ($valid_methods as $method) {
$r = call_user_func(array('Httpful\Request', $method), $url); $r = call_user_func(['Httpful\Request', $method], $url);
$this->assertEquals('Httpful\Request', get_class($r)); $this->assertEquals('Httpful\Request', get_class($r));
$this->assertEquals(strtoupper($method), $r->method); $this->assertEquals(strtoupper($method), $r->method);
} }
@ -407,10 +407,13 @@ Content-Type: text/plain; charset=utf-8\r\n", $req);
{ {
// Parent type // Parent type
$request = Request::init()->sendsAndExpects(Mime::XML); $request = Request::init()->sendsAndExpects(Mime::XML);
$response = new Response('<xml><name>Nathan</name></xml>', $response = new Response(
'<xml><name>Nathan</name></xml>',
"HTTP/1.1 200 OK "HTTP/1.1 200 OK
Connection: keep-alive Connection: keep-alive
Transfer-Encoding: chunked\r\n", $request); Transfer-Encoding: chunked\r\n",
$request
);
$this->assertEquals("", $response->content_type); $this->assertEquals("", $response->content_type);
} }
@ -443,16 +446,17 @@ Transfer-Encoding: chunked\r\n", $request);
// Lazy test... // Lazy test...
$prev = \Httpful\Httpful::get(\Httpful\Mime::XML); $prev = \Httpful\Httpful::get(\Httpful\Mime::XML);
$this->assertEquals($prev, new \Httpful\Handlers\XmlHandler()); $this->assertEquals($prev, new \Httpful\Handlers\XmlHandler());
$conf = array('namespace' => 'http://example.com'); $conf = ['namespace' => 'http://example.com'];
\Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf)); \Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf));
$new = \Httpful\Httpful::get(\Httpful\Mime::XML); $new = \Httpful\Httpful::get(\Httpful\Mime::XML);
$this->assertNotEquals($prev, $new); $this->assertNotEquals($prev, $new);
} }
} }
class DemoMimeHandler extends \Httpful\Handlers\MimeHandlerAdapter { class DemoMimeHandler extends \Httpful\Handlers\MimeHandlerAdapter
public function parse($body) { {
public function parse($body)
{
return 'custom parse'; return 'custom parse';
} }
} }

View file

@ -135,7 +135,7 @@ class Client
* *
* @var array * @var array
*/ */
protected $curl_options = array(); protected $curl_options = [];
/** /**
* Construct * Construct
@ -189,13 +189,13 @@ class Client
* @param array $extra_parameters Array of extra parameters like scope or state (Ex: array('scope' => null, 'state' => '')) * @param array $extra_parameters Array of extra parameters like scope or state (Ex: array('scope' => null, 'state' => ''))
* @return string URL used for authentication * @return string URL used for authentication
*/ */
public function getAuthenticationUrl($auth_endpoint, $redirect_uri, array $extra_parameters = array()) public function getAuthenticationUrl($auth_endpoint, $redirect_uri, array $extra_parameters = [])
{ {
$parameters = array_merge(array( $parameters = array_merge([
'response_type' => 'code', 'response_type' => 'code',
'client_id' => $this->client_id, 'client_id' => $this->client_id,
'redirect_uri' => $redirect_uri 'redirect_uri' => $redirect_uri
), $extra_parameters); ], $extra_parameters);
return $auth_endpoint . '?' . http_build_query($parameters, null, '&'); return $auth_endpoint . '?' . http_build_query($parameters, null, '&');
} }
@ -224,7 +224,7 @@ class Client
throw new Exception('Unknown constant GRANT_TYPE for class ' . $grantTypeClassName, Exception::GRANT_TYPE_ERROR); throw new Exception('Unknown constant GRANT_TYPE for class ' . $grantTypeClassName, Exception::GRANT_TYPE_ERROR);
} }
$parameters['grant_type'] = $grantTypeClass::GRANT_TYPE; $parameters['grant_type'] = $grantTypeClass::GRANT_TYPE;
$http_headers = array(); $http_headers = [];
switch ($this->client_auth) { switch ($this->client_auth) {
case self::AUTH_TYPE_URI: case self::AUTH_TYPE_URI:
case self::AUTH_TYPE_FORM: case self::AUTH_TYPE_FORM:
@ -313,7 +313,7 @@ class Client
* @param int $form_content_type HTTP form content type to use * @param int $form_content_type HTTP form content type to use
* @return array * @return array
*/ */
public function fetch($protected_resource_url, $parameters = array(), $http_method = self::HTTP_METHOD_GET, array $http_headers = array(), $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART) public function fetch($protected_resource_url, $parameters = [], $http_method = self::HTTP_METHOD_GET, array $http_headers = [], $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART)
{ {
if ($this->access_token) { if ($this->access_token) {
switch ($this->access_token_type) { switch ($this->access_token_type) {
@ -357,8 +357,7 @@ class Client
$timestamp = time(); $timestamp = time();
$nonce = uniqid(); $nonce = uniqid();
$parsed_url = parse_url($url); $parsed_url = parse_url($url);
if (!isset($parsed_url['port'])) if (!isset($parsed_url['port'])) {
{
$parsed_url['port'] = ($parsed_url['scheme'] == 'https') ? 443 : 80; $parsed_url['port'] = ($parsed_url['scheme'] == 'https') ? 443 : 80;
} }
if ($http_method == self::HTTP_METHOD_GET) { if ($http_method == self::HTTP_METHOD_GET) {
@ -369,14 +368,17 @@ class Client
} }
} }
$signature = base64_encode(hash_hmac($this->access_token_algorithm, $signature = base64_encode(hash_hmac(
$this->access_token_algorithm,
$timestamp . "\n" $timestamp . "\n"
. $nonce . "\n" . $nonce . "\n"
. $http_method . "\n" . $http_method . "\n"
. $parsed_url['path'] . "\n" . $parsed_url['path'] . "\n"
. $parsed_url['host'] . "\n" . $parsed_url['host'] . "\n"
. $parsed_url['port'] . "\n\n" . $parsed_url['port'] . "\n\n",
, $this->access_token_secret, true)); $this->access_token_secret,
true
));
return 'id="' . $this->access_token . '", ts="' . $timestamp . '", nonce="' . $nonce . '", mac="' . $signature . '"'; return 'id="' . $this->access_token . '", ts="' . $timestamp . '", nonce="' . $nonce . '", mac="' . $signature . '"';
} }
@ -391,13 +393,13 @@ class Client
* @param int $form_content_type HTTP form content type to use * @param int $form_content_type HTTP form content type to use
* @return array * @return array
*/ */
private function executeRequest($url, $parameters = array(), $http_method = self::HTTP_METHOD_GET, array $http_headers = null, $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART) private function executeRequest($url, $parameters = [], $http_method = self::HTTP_METHOD_GET, array $http_headers = null, $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART)
{ {
$curl_options = array( $curl_options = [
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_CUSTOMREQUEST => $http_method CURLOPT_CUSTOMREQUEST => $http_method
); ];
switch ($http_method) { switch ($http_method) {
case self::HTTP_METHOD_POST: case self::HTTP_METHOD_POST:
@ -405,7 +407,6 @@ class Client
/* No break */ /* No break */
case self::HTTP_METHOD_PUT: case self::HTTP_METHOD_PUT:
case self::HTTP_METHOD_PATCH: case self::HTTP_METHOD_PATCH:
/** /**
* Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, * Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data,
* while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded. * while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.
@ -434,7 +435,7 @@ class Client
$curl_options[CURLOPT_URL] = $url; $curl_options[CURLOPT_URL] = $url;
if (is_array($http_headers)) { if (is_array($http_headers)) {
$header = array(); $header = [];
foreach ($http_headers as $key => $parsed_urlvalue) { foreach ($http_headers as $key => $parsed_urlvalue) {
$header[] = "$key: $parsed_urlvalue"; $header[] = "$key: $parsed_urlvalue";
} }
@ -466,11 +467,11 @@ class Client
} }
curl_close($ch); curl_close($ch);
return array( return [
'result' => (null === $json_decode) ? $result : $json_decode, 'result' => (null === $json_decode) ? $result : $json_decode,
'code' => $http_code, 'code' => $http_code,
'content_type' => $content_type 'content_type' => $content_type
); ];
} }
/** /**
@ -493,7 +494,9 @@ class Client
private function convertToCamelCase($grant_type) private function convertToCamelCase($grant_type)
{ {
$parts = explode('_', $grant_type); $parts = explode('_', $grant_type);
array_walk($parts, function(&$item) { $item = ucfirst($item);}); array_walk($parts, function (&$item) {
$item = ucfirst($item);
});
return implode('', $parts); return implode('', $parts);
} }
} }

View file

@ -23,15 +23,12 @@ class AuthorizationCode implements IGrantType
*/ */
public function validateParameters(&$parameters) public function validateParameters(&$parameters)
{ {
if (!isset($parameters['code'])) if (!isset($parameters['code'])) {
{
throw new InvalidArgumentException( throw new InvalidArgumentException(
'The \'code\' parameter must be defined for the Authorization Code grant type', 'The \'code\' parameter must be defined for the Authorization Code grant type',
InvalidArgumentException::MISSING_PARAMETER InvalidArgumentException::MISSING_PARAMETER
); );
} } elseif (!isset($parameters['redirect_uri'])) {
elseif (!isset($parameters['redirect_uri']))
{
throw new InvalidArgumentException( throw new InvalidArgumentException(
'The \'redirect_uri\' parameter must be defined for the Authorization Code grant type', 'The \'redirect_uri\' parameter must be defined for the Authorization Code grant type',
InvalidArgumentException::MISSING_PARAMETER InvalidArgumentException::MISSING_PARAMETER

View file

@ -1,5 +1,6 @@
<?php <?php
namespace OAuth2\GrantType; namespace OAuth2\GrantType;
/** /**
* Specific GrantType Interface * Specific GrantType Interface
*/ */

View file

@ -23,15 +23,12 @@ class Password implements IGrantType
*/ */
public function validateParameters(&$parameters) public function validateParameters(&$parameters)
{ {
if (!isset($parameters['username'])) if (!isset($parameters['username'])) {
{
throw new InvalidArgumentException( throw new InvalidArgumentException(
'The \'username\' parameter must be defined for the Password grant type', 'The \'username\' parameter must be defined for the Password grant type',
InvalidArgumentException::MISSING_PARAMETER InvalidArgumentException::MISSING_PARAMETER
); );
} } elseif (!isset($parameters['password'])) {
elseif (!isset($parameters['password']))
{
throw new InvalidArgumentException( throw new InvalidArgumentException(
'The \'password\' parameter must be defined for the Password grant type', 'The \'password\' parameter must be defined for the Password grant type',
InvalidArgumentException::MISSING_PARAMETER InvalidArgumentException::MISSING_PARAMETER

View file

@ -23,8 +23,7 @@ class RefreshToken implements IGrantType
*/ */
public function validateParameters(&$parameters) public function validateParameters(&$parameters)
{ {
if (!isset($parameters['refresh_token'])) if (!isset($parameters['refresh_token'])) {
{
throw new InvalidArgumentException( throw new InvalidArgumentException(
'The \'refresh_token\' parameter must be defined for the refresh token grant type', 'The \'refresh_token\' parameter must be defined for the refresh token grant type',
InvalidArgumentException::MISSING_PARAMETER InvalidArgumentException::MISSING_PARAMETER

View file

@ -29,11 +29,13 @@ use Poniverse\Ponyfm\Models\Playlist;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
class Search { class Search
{
protected $elasticsearch; protected $elasticsearch;
protected $index; protected $index;
public function __construct(Client $connection, string $indexName) { public function __construct(Client $connection, string $indexName)
{
$this->elasticsearch = $connection; $this->elasticsearch = $connection;
$this->index = $indexName; $this->index = $indexName;
} }
@ -43,7 +45,8 @@ class Search {
* @param int $resultsPerContentType * @param int $resultsPerContentType
* @return array * @return array
*/ */
public function searchAllContent(string $query) { public function searchAllContent(string $query)
{
$results = $this->elasticsearch->msearch([ $results = $this->elasticsearch->msearch([
'index' => $this->index, 'index' => $this->index,
'body' => [ 'body' => [
@ -131,7 +134,8 @@ class Search {
]; ];
} }
protected function transformTracks(array $searchHits) { protected function transformTracks(array $searchHits)
{
$tracks = $this->transformToEloquent(Track::class, $searchHits); $tracks = $this->transformToEloquent(Track::class, $searchHits);
$tracks = $tracks->map(function (Track $track) { $tracks = $tracks->map(function (Track $track) {
return Track::mapPublicTrackSummary($track); return Track::mapPublicTrackSummary($track);
@ -139,7 +143,8 @@ class Search {
return $tracks; return $tracks;
} }
protected function transformAlbums(array $searchHits) { protected function transformAlbums(array $searchHits)
{
$albums = $this->transformToEloquent(Album::class, $searchHits); $albums = $this->transformToEloquent(Album::class, $searchHits);
$albums = $albums->map(function (Album $album) { $albums = $albums->map(function (Album $album) {
return Album::mapPublicAlbumSummary($album); return Album::mapPublicAlbumSummary($album);
@ -147,7 +152,8 @@ class Search {
return $albums; return $albums;
} }
protected function transformPlaylists(array $searchHits) { protected function transformPlaylists(array $searchHits)
{
$playlists = $this->transformToEloquent(Playlist::class, $searchHits); $playlists = $this->transformToEloquent(Playlist::class, $searchHits);
$playlists = $playlists->map(function (Playlist $playlist) { $playlists = $playlists->map(function (Playlist $playlist) {
return Playlist::mapPublicPlaylistSummary($playlist); return Playlist::mapPublicPlaylistSummary($playlist);
@ -155,7 +161,8 @@ class Search {
return $playlists; return $playlists;
} }
protected function transformUsers(array $searchHits) { protected function transformUsers(array $searchHits)
{
$users = $this->transformToEloquent(User::class, $searchHits); $users = $this->transformToEloquent(User::class, $searchHits);
$users = $users->map(function (User $user) { $users = $users->map(function (User $user) {
return User::mapPublicUserSummary($user); return User::mapPublicUserSummary($user);
@ -173,7 +180,8 @@ class Search {
* @param array $searchHits * @param array $searchHits
* @return \Illuminate\Database\Eloquent\Collection * @return \Illuminate\Database\Eloquent\Collection
*/ */
protected function transformToEloquent(string $modelClass, array $searchHits) { protected function transformToEloquent(string $modelClass, array $searchHits)
{
if (empty($searchHits)) { if (empty($searchHits)) {
return new Collection(); return new Collection();
} }

View file

@ -27,7 +27,8 @@ use Illuminate\Contracts\Database\ModelIdentifier;
* *
* @link https://github.com/laravel/framework/issues/9347#issuecomment-120803564 * @link https://github.com/laravel/framework/issues/9347#issuecomment-120803564
*/ */
trait SerializesModels { trait SerializesModels
{
use \Illuminate\Queue\SerializesModels; use \Illuminate\Queue\SerializesModels;
/** /**
@ -36,7 +37,8 @@ trait SerializesModels {
* @param mixed $value * @param mixed $value
* @return mixed * @return mixed
*/ */
protected function getRestoredPropertyValue($value) { protected function getRestoredPropertyValue($value)
{
if ($value instanceof ModelIdentifier) { if ($value instanceof ModelIdentifier) {
return method_exists($value->class, 'withTrashed') return method_exists($value->class, 'withTrashed')
? (new $value->class)->withTrashed()->findOrFail($value->id) ? (new $value->class)->withTrashed()->findOrFail($value->id)

View file

@ -19,7 +19,8 @@
* @link https://github.com/Grandt/PHPZip * @link https://github.com/Grandt/PHPZip
* @version 1.37 * @version 1.37
*/ */
class ZipStream { class ZipStream
{
const VERSION = 1.37; const VERSION = 1.37;
const ZIP_LOCAL_FILE_HEADER = "\x50\x4b\x03\x04"; // Local file header signature const ZIP_LOCAL_FILE_HEADER = "\x50\x4b\x03\x04"; // Local file header signature
@ -35,10 +36,10 @@ class ZipStream {
private $zipMemoryThreshold = 1048576; // Autocreate tempfile if the zip data exceeds 1048576 bytes (1 MB) private $zipMemoryThreshold = 1048576; // Autocreate tempfile if the zip data exceeds 1048576 bytes (1 MB)
private $zipComment = null; private $zipComment = null;
private $cdRec = array(); // central directory private $cdRec = []; // central directory
private $offset = 0; private $offset = 0;
private $isFinalized = FALSE; private $isFinalized = false;
private $addExtraField = TRUE; private $addExtraField = true;
private $streamChunkSize = 16384; // 65536; private $streamChunkSize = 16384; // 65536;
private $streamFilePath = null; private $streamFilePath = null;
@ -54,7 +55,8 @@ class ZipStream {
* @param String $archiveName Name to send to the HTTP client. * @param String $archiveName Name to send to the HTTP client.
* @param String $contentType Content mime type. Optional, defaults to "application/zip". * @param String $contentType Content mime type. Optional, defaults to "application/zip".
*/ */
function __construct($archiveName = "", $contentType = "application/zip") { function __construct($archiveName = "", $contentType = "application/zip")
{
if (!function_exists('sys_get_temp_dir')) { if (!function_exists('sys_get_temp_dir')) {
die("ERROR: ZipStream " . self::VERSION . " requires PHP version 5.2.1 or above."); die("ERROR: ZipStream " . self::VERSION . " requires PHP version 5.2.1 or above.");
} }
@ -62,7 +64,7 @@ class ZipStream {
$headerFile = null; $headerFile = null;
$headerLine = null; $headerLine = null;
if (!headers_sent($headerFile, $headerLine) or die("<p><strong>Error:</strong> Unable to send file $archiveName. HTML Headers have already been sent from <strong>$headerFile</strong> in line <strong>$headerLine</strong></p>")) { if (!headers_sent($headerFile, $headerLine) or die("<p><strong>Error:</strong> Unable to send file $archiveName. HTML Headers have already been sent from <strong>$headerFile</strong> in line <strong>$headerLine</strong></p>")) {
if ((ob_get_contents() === FALSE || ob_get_contents() == '') or die("\n<p><strong>Error:</strong> Unable to send file <strong>$archiveName.epub</strong>. Output buffer contains the following text (typically warnings or errors):<br>" . ob_get_contents() . "</p>")) { if ((ob_get_contents() === false || ob_get_contents() == '') or die("\n<p><strong>Error:</strong> Unable to send file <strong>$archiveName.epub</strong>. Output buffer contains the following text (typically warnings or errors):<br>" . ob_get_contents() . "</p>")) {
if (ini_get('zlib.output_compression')) { if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off'); ini_set('zlib.output_compression', 'Off');
} }
@ -80,8 +82,9 @@ class ZipStream {
} }
} }
function __destruct() { function __destruct()
$this->isFinalized = TRUE; {
$this->isFinalized = true;
$this->cdRec = null; $this->cdRec = null;
exit; exit;
} }
@ -92,8 +95,9 @@ class ZipStream {
* *
* @param bool $setExtraField TRUE (default) will enable adding of extra fields, anything else will disable it. * @param bool $setExtraField TRUE (default) will enable adding of extra fields, anything else will disable it.
*/ */
function setExtraField($setExtraField = TRUE) { function setExtraField($setExtraField = true)
$this->addExtraField = ($setExtraField === TRUE); {
$this->addExtraField = ($setExtraField === true);
} }
/** /**
@ -102,13 +106,14 @@ class ZipStream {
* @param string $newComment New comment. null to clear. * @param string $newComment New comment. null to clear.
* @return bool $success * @return bool $success
*/ */
public function setComment($newComment = null) { public function setComment($newComment = null)
{
if ($this->isFinalized) { if ($this->isFinalized) {
return FALSE; return false;
} }
$this->zipComment = $newComment; $this->zipComment = $newComment;
return TRUE; return true;
} }
/** /**
@ -120,9 +125,10 @@ class ZipStream {
* @param string $fileComment (Optional) Comment to be added to the archive for this directory. To use fileComment, timestamp must be given. * @param string $fileComment (Optional) Comment to be added to the archive for this directory. To use fileComment, timestamp must be given.
* @return bool $success * @return bool $success
*/ */
public function addDirectory($directoryPath, $timestamp = 0, $fileComment = null) { public function addDirectory($directoryPath, $timestamp = 0, $fileComment = null)
{
if ($this->isFinalized) { if ($this->isFinalized) {
return FALSE; return false;
} }
$directoryPath = str_replace("\\", "/", $directoryPath); $directoryPath = str_replace("\\", "/", $directoryPath);
@ -130,9 +136,9 @@ class ZipStream {
if (strlen($directoryPath) > 0) { if (strlen($directoryPath) > 0) {
$this->buildZipEntry($directoryPath.'/', $fileComment, "\x00\x00", "\x00\x00", $timestamp, "\x00\x00\x00\x00", 0, 0, self::EXT_FILE_ATTR_DIR); $this->buildZipEntry($directoryPath.'/', $fileComment, "\x00\x00", "\x00\x00", $timestamp, "\x00\x00\x00\x00", 0, 0, self::EXT_FILE_ATTR_DIR);
return TRUE; return true;
} }
return FALSE; return false;
} }
/** /**
@ -144,14 +150,15 @@ class ZipStream {
* @param string $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given. * @param string $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given.
* @return bool $success * @return bool $success
*/ */
public function addFile($data, $filePath, $timestamp = 0, $fileComment = null) { public function addFile($data, $filePath, $timestamp = 0, $fileComment = null)
{
if ($this->isFinalized) { if ($this->isFinalized) {
return FALSE; return false;
} }
if (is_resource($data) && get_resource_type($data) == "stream") { if (is_resource($data) && get_resource_type($data) == "stream") {
$this->addLargeFile($data, $filePath, $timestamp, $fileComment); $this->addLargeFile($data, $filePath, $timestamp, $fileComment);
return FALSE; return false;
} }
$gzType = "\x08\x00"; // Compression type 8 = deflate $gzType = "\x08\x00"; // Compression type 8 = deflate
@ -175,7 +182,7 @@ class ZipStream {
print ($gzData); print ($gzData);
return TRUE; return true;
} }
/** /**
@ -192,7 +199,8 @@ class ZipStream {
* If you start the function by parsing an array, the array will be populated with the realPath * If you start the function by parsing an array, the array will be populated with the realPath
* and zipPath kay/value pairs added to the archive by the function. * and zipPath kay/value pairs added to the archive by the function.
*/ */
public function addDirectoryContent($realPath, $zipPath, $recursive = TRUE, $followSymlinks = TRUE, &$addedFiles = array()) { public function addDirectoryContent($realPath, $zipPath, $recursive = true, $followSymlinks = true, &$addedFiles = [])
{
if (file_exists($realPath) && !isset($addedFiles[realpath($realPath)])) { if (file_exists($realPath) && !isset($addedFiles[realpath($realPath)])) {
if (is_dir($realPath)) { if (is_dir($realPath)) {
$this->addDirectory($zipPath); $this->addDirectory($zipPath);
@ -208,11 +216,11 @@ class ZipStream {
$newRealPath = $file->getPathname(); $newRealPath = $file->getPathname();
$newZipPath = self::pathJoin($zipPath, $file->getFilename()); $newZipPath = self::pathJoin($zipPath, $file->getFilename());
if (file_exists($newRealPath) && ($followSymlinks === TRUE || !is_link($newRealPath))) { if (file_exists($newRealPath) && ($followSymlinks === true || !is_link($newRealPath))) {
if ($file->isFile()) { if ($file->isFile()) {
$addedFiles[realpath($newRealPath)] = $newZipPath; $addedFiles[realpath($newRealPath)] = $newZipPath;
$this->addLargeFile($newRealPath, $newZipPath); $this->addLargeFile($newRealPath, $newZipPath);
} else if ($recursive === TRUE) { } else if ($recursive === true) {
$this->addDirectoryContent($newRealPath, $newZipPath, $recursive); $this->addDirectoryContent($newRealPath, $newZipPath, $recursive);
} else { } else {
$this->addDirectory($zipPath); $this->addDirectory($zipPath);
@ -231,9 +239,10 @@ class ZipStream {
* @param string $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given. * @param string $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given.
* @return bool $success * @return bool $success
*/ */
public function addLargeFile($dataFile, $filePath, $timestamp = 0, $fileComment = null) { public function addLargeFile($dataFile, $filePath, $timestamp = 0, $fileComment = null)
{
if ($this->isFinalized) { if ($this->isFinalized) {
return FALSE; return false;
} }
if (is_string($dataFile) && is_file($dataFile)) { if (is_string($dataFile) && is_file($dataFile)) {
@ -247,7 +256,7 @@ class ZipStream {
} }
$this->closeStream($this->addExtraField); $this->closeStream($this->addExtraField);
} }
return TRUE; return true;
} }
/** /**
@ -258,13 +267,14 @@ class ZipStream {
* @param string $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given. * @param string $fileComment (Optional) Comment to be added to the archive for this file. To use fileComment, timestamp must be given.
* @return bool $success * @return bool $success
*/ */
public function openStream($filePath, $timestamp = 0, $fileComment = null) { public function openStream($filePath, $timestamp = 0, $fileComment = null)
{
if (!function_exists('sys_get_temp_dir')) { if (!function_exists('sys_get_temp_dir')) {
die("ERROR: Zip " . self::VERSION . " requires PHP version 5.2.1 or above if large files are used."); die("ERROR: Zip " . self::VERSION . " requires PHP version 5.2.1 or above if large files are used.");
} }
if ($this->isFinalized) { if ($this->isFinalized) {
return FALSE; return false;
} }
if (strlen($this->streamFilePath) > 0) { if (strlen($this->streamFilePath) > 0) {
@ -278,7 +288,7 @@ class ZipStream {
$this->streamFileComment = $fileComment; $this->streamFileComment = $fileComment;
$this->streamFileLength = 0; $this->streamFileLength = 0;
return TRUE; return true;
} }
/** /**
@ -287,9 +297,10 @@ class ZipStream {
* @param String $data * @param String $data
* @return $length bytes added or FALSE if the archive is finalized or there are no open stream. * @return $length bytes added or FALSE if the archive is finalized or there are no open stream.
*/ */
public function addStreamData($data) { public function addStreamData($data)
{
if ($this->isFinalized || strlen($this->streamFilePath) == 0) { if ($this->isFinalized || strlen($this->streamFilePath) == 0) {
return FALSE; return false;
} }
$length = fwrite($this->streamData, $data, strlen($data)); $length = fwrite($this->streamData, $data, strlen($data));
@ -306,9 +317,10 @@ class ZipStream {
* *
* @return bool $success * @return bool $success
*/ */
public function closeStream() { public function closeStream()
{
if ($this->isFinalized || strlen($this->streamFilePath) == 0) { if ($this->isFinalized || strlen($this->streamFilePath) == 0) {
return FALSE; return false;
} }
fflush($this->streamData); fflush($this->streamData);
@ -327,18 +339,19 @@ class ZipStream {
$this->streamFile = null; $this->streamFile = null;
return TRUE; return true;
} }
private function processFile($dataFile, $filePath, $timestamp = 0, $fileComment = null) { private function processFile($dataFile, $filePath, $timestamp = 0, $fileComment = null)
{
if ($this->isFinalized) { if ($this->isFinalized) {
return FALSE; return false;
} }
$tempzip = tempnam(sys_get_temp_dir(), 'ZipStream'); $tempzip = tempnam(sys_get_temp_dir(), 'ZipStream');
$zip = new ZipArchive; $zip = new ZipArchive;
if ($zip->open($tempzip) === TRUE) { if ($zip->open($tempzip) === true) {
$zip->addFile($dataFile, 'file'); $zip->addFile($dataFile, 'file');
$zip->close(); $zip->close();
} }
@ -382,7 +395,8 @@ class ZipStream {
* A closed archive can no longer have new files added to it. * A closed archive can no longer have new files added to it.
* @return bool $success * @return bool $success
*/ */
public function finalize() { public function finalize()
{
if (!$this->isFinalized) { if (!$this->isFinalized) {
if (strlen($this->streamFilePath) > 0) { if (strlen($this->streamFilePath) > 0) {
$this->closeStream(); $this->closeStream();
@ -404,13 +418,13 @@ class ZipStream {
flush(); flush();
$this->isFinalized = TRUE; $this->isFinalized = true;
$cd = null; $cd = null;
$this->cdRec = null; $this->cdRec = null;
return TRUE; return true;
} }
return FALSE; return false;
} }
/** /**
@ -419,7 +433,8 @@ class ZipStream {
* @param int $timestamp * @param int $timestamp
* @return 2-byte encoded DOS Date * @return 2-byte encoded DOS Date
*/ */
private function getDosTime($timestamp = 0) { private function getDosTime($timestamp = 0)
{
$timestamp = (int)$timestamp; $timestamp = (int)$timestamp;
$oldTZ = @date_default_timezone_get(); $oldTZ = @date_default_timezone_get();
date_default_timezone_set('UTC'); date_default_timezone_set('UTC');
@ -445,7 +460,8 @@ class ZipStream {
* @param int $dataLength * @param int $dataLength
* @param integer $extFileAttr Use self::EXT_FILE_ATTR_FILE for files, self::EXT_FILE_ATTR_DIR for Directories. * @param integer $extFileAttr Use self::EXT_FILE_ATTR_FILE for files, self::EXT_FILE_ATTR_DIR for Directories.
*/ */
private function buildZipEntry($filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, $extFileAttr) { private function buildZipEntry($filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, $extFileAttr)
{
$filePath = str_replace("\\", "/", $filePath); $filePath = str_replace("\\", "/", $filePath);
$fileCommentLength = (empty($fileComment) ? 0 : strlen($fileComment)); $fileCommentLength = (empty($fileComment) ? 0 : strlen($fileComment));
$timestamp = (int)$timestamp; $timestamp = (int)$timestamp;
@ -516,7 +532,8 @@ class ZipStream {
* @param String $dir * @param String $dir
* @param String $file * @param String $file
*/ */
public static function pathJoin($dir, $file) { public static function pathJoin($dir, $file)
{
if (empty($dir) || empty($file)) { if (empty($dir) || empty($file)) {
return self::getRelativePath($dir . $file); return self::getRelativePath($dir . $file);
} }
@ -531,7 +548,8 @@ class ZipStream {
* @param String $path The path to clean up * @param String $path The path to clean up
* @return String the clean path * @return String the clean path
*/ */
public static function getRelativePath($path) { public static function getRelativePath($path)
{
$path = preg_replace("#/+\.?/+#", "/", str_replace("\\", "/", $path)); $path = preg_replace("#/+\.?/+#", "/", str_replace("\\", "/", $path));
$dirs = explode("/", rtrim(preg_replace('#^(?:\./)+#', '', $path), '/')); $dirs = explode("/", rtrim(preg_replace('#^(?:\./)+#', '', $path), '/'));
@ -548,7 +566,7 @@ class ZipStream {
$dirs = array_splice($dirs, 1); $dirs = array_splice($dirs, 1);
} }
$newDirs = array(); $newDirs = [];
foreach ($dirs as $dir) { foreach ($dirs as $dir) {
if ($dir !== "..") { if ($dir !== "..") {
$subOffset--; $subOffset--;
@ -570,4 +588,3 @@ class ZipStream {
return $root . implode("/", array_slice($newDirs, 0, $offset)); return $root . implode("/", array_slice($newDirs, 0, $offset));
} }
} }
?>

Some files were not shown because too many files have changed in this diff Show more