Merge branch 'release/4.0.0'

This commit is contained in:
James Cole 2016-09-26 18:37:33 +02:00
commit 9bdfecbfdc
280 changed files with 5233 additions and 3369 deletions

View File

@ -3,14 +3,17 @@ APP_DEBUG=false
APP_FORCE_SSL=false APP_FORCE_SSL=false
APP_FORCE_ROOT= APP_FORCE_ROOT=
APP_KEY=SomeRandomStringOf32CharsExactly APP_KEY=SomeRandomStringOf32CharsExactly
LOG_LEVEL=warning APP_LOG_LEVEL=warning
APP_URL=http://localhost
DB_CONNECTION=mysql DB_CONNECTION=mysql
DB_HOST=localhost DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead DB_DATABASE=homestead
DB_USERNAME=homestead DB_USERNAME=homestead
DB_PASSWORD=secret DB_PASSWORD=secret
BROADCAST_DRIVER=log
CACHE_DRIVER=file CACHE_DRIVER=file
SESSION_DRIVER=file SESSION_DRIVER=file
QUEUE_DRIVER=sync QUEUE_DRIVER=sync
@ -19,17 +22,14 @@ COOKIE_PATH="/"
COOKIE_DOMAIN= COOKIE_DOMAIN=
COOKIE_SECURE=false COOKIE_SECURE=false
DEFAULT_CURRENCY=EUR REDIS_HOST=127.0.0.1
DEFAULT_LANGUAGE=en_US
REDIS_HOST=localhost
REDIS_PASSWORD=null REDIS_PASSWORD=null
REDIS_PORT=6379 REDIS_PORT=6379
MAIL_DRIVER=smtp MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io MAIL_HOST=mailtrap.io
MAIL_PORT=2525 MAIL_PORT=2525
MAIL_FROM=enter_your_email_here MAIL_FROM=changeme@example.com
MAIL_USERNAME=null MAIL_USERNAME=null
MAIL_PASSWORD=null MAIL_PASSWORD=null
MAIL_ENCRYPTION=null MAIL_ENCRYPTION=null
@ -38,7 +38,10 @@ SEND_REGISTRATION_MAIL=true
MUST_CONFIRM_ACCOUNT=false MUST_CONFIRM_ACCOUNT=false
SHOW_INCOMPLETE_TRANSLATIONS=false SHOW_INCOMPLETE_TRANSLATIONS=false
SHOW_DEMO_WARNING=false
ANALYTICS_ID= ANALYTICS_ID=
SITE_OWNER=mail@example.com SITE_OWNER=mail@example.com
PUSHER_KEY=
PUSHER_SECRET=
PUSHER_APP_ID=

View File

@ -1,38 +0,0 @@
APP_ENV=testing
APP_DEBUG=true
APP_FORCE_SSL=false
APP_KEY=SomeRandomStringOf32CharsExactly
LOG_LEVEL=debug
DB_CONNECTION=sqlite
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
CACHE_DRIVER=array
SESSION_DRIVER=array
QUEUE_DRIVER=array
DEFAULT_CURRENCY=EUR
DEFAULT_LANGUAGE=en_US
REDIS_HOST=localhost
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=log
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_FROM=your_address_here@example.com
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
SHOW_INCOMPLETE_TRANSLATIONS=false
ANALYTICS_ID=abcde
RUNCLEANUP=false
SITE_OWNER=your_address_here@example.com
BLOCKED_DOMAINS=

2
.gitattributes vendored
View File

@ -1,3 +1,3 @@
* text=auto * text=auto
*.css linguist-vendored *.css linguist-vendored
*.less linguist-vendored *.scss linguist-vendored

6
.gitignore vendored Normal file → Executable file
View File

@ -1,5 +1,9 @@
/vendor
/node_modules /node_modules
/public/storage
/vendor
/.idea
Homestead.json
Homestead.yaml
.env .env
_development _development
.env.local .env.local

View File

@ -5,3 +5,4 @@ filter:
excluded_paths: excluded_paths:
- app/Support/Migration/* - app/Support/Migration/*
- app/database/migrations/* - app/database/migrations/*
- database/migrations/*

View File

@ -2,10 +2,22 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/). This project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased] ## [4.0.0] - 2015-05-25
- No unreleased changes yet. ### Added
- Upgraded to Laravel 5.3, most other libraries upgraded as well.
- Added GBP as currency, thanks to @Mortalife
## [3.10.4] - 2015-05-25 ### Changed
- Jump to version 4.0.0.
- Firefly III is now subject to a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/) license. Previous versions of this software are still MIT licensed.
### Fixed
- Support for specific decimal places, thanks to @Mortalife
- Various CSS fixes
- Various bugs, thanks to @fuf, @sandermulders and @vissert
- Various queries optimized for MySQL 5.7
## [3.10.4] - 2015-09-14
### Fixed ### Fixed
- Migration fix by @sandermulders - Migration fix by @sandermulders
- Tricky import bug fix thanks to @vissert - Tricky import bug fix thanks to @vissert

View File

@ -1,7 +1,7 @@
Copyright (C) 2016 thegrumpydictator@gmail.com Copyright (C) 2016 thegrumpydictator@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. https://creativecommons.org/licenses/by-sa/4.0/
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -22,24 +22,40 @@ use Illuminate\Log\Writer;
*/ */
class ConfigureLogging extends IlluminateConfigureLogging class ConfigureLogging extends IlluminateConfigureLogging
{ {
/** /**
* @param Application $app * Configure the Monolog handlers for the application.
* @param Writer $log *
* @param \Illuminate\Contracts\Foundation\Application $app
* @param \Illuminate\Log\Writer $log
*
* @return void
*/ */
protected function configureDailyHandler(Application $app, Writer $log) protected function configureDailyHandler(Application $app, Writer $log)
{ {
$config = $app->make('config');
$maxFiles = $config->get('app.log_max_files');
$log->useDailyFiles( $log->useDailyFiles(
$app->storagePath() . '/logs/firefly-iii.log', $app->storagePath() . '/logs/firefly-iii.log', is_null($maxFiles) ? 5 : $maxFiles,
$app->make('config')->get('app.log_max_files', 5) $config->get('app.log_level', 'debug')
); );
} }
/** /**
* @param Application $app * Configure the Monolog handlers for the application.
* @param Writer $log *
* @param \Illuminate\Contracts\Foundation\Application $app
* @param \Illuminate\Log\Writer $log
*
* @return void
*/ */
protected function configureSingleHandler(Application $app, Writer $log) protected function configureSingleHandler(Application $app, Writer $log)
{ {
$log->useFiles($app->storagePath() . '/logs/firefly-iii.log'); $log->useFiles(
$app->storagePath() . '/logs/firefly-iii.log',
$app->make('config')->get('app.log_level', 'debug')
);
} }
} }

View File

@ -0,0 +1,99 @@
<?php
/**
* ScanAttachments.php
* Copyright (C) 2016 thegrumpydictator@gmail.com
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
declare(strict_types = 1);
namespace FireflyIII\Console\Commands;
use Crypt;
use FireflyIII\Models\Attachment;
use Illuminate\Console\Command;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Storage;
/**
* Class ScanAttachments
*
* @package FireflyIII\Console\Commands
*/
class ScanAttachments extends Command
{
/**
* The console command description.
*
* @var string
*/
protected $description = 'Rescan all attachments and re-set the MD5 hash and mime.';
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'firefly:scan-attachments';
/**
* Create a new command instance.
*
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*/
public function handle()
{
$attachments = Attachment::get();
$disk = Storage::disk('upload');
/** @var Attachment $attachment */
foreach ($attachments as $attachment) {
$fileName = $attachment->fileName();
// try to grab file content:
try {
$content = $disk->get($fileName);
} catch (FileNotFoundException $e) {
$this->error(sprintf('Could not find data for attachment #%d', $attachment->id));
continue;
}
// try to decrypt content.
try {
$decrypted = Crypt::decrypt($content);
} catch (DecryptException $e) {
$this->error(sprintf('Could not decrypt data of attachment #%d', $attachment->id));
continue;
}
// make temp file:
$tmpfname = tempnam(sys_get_temp_dir(), 'FireflyIII');
// store content in temp file:
file_put_contents($tmpfname, $decrypted);
// get md5 and mime
$md5 = md5_file($tmpfname);
$mime = mime_content_type($tmpfname);
// update attachment:
$attachment->md5 = $md5;
$attachment->mime = $mime;
$attachment->save();
$this->line(sprintf('Fixed attachment #%d', $attachment->id));
// find file:
}
}
}

View File

@ -51,7 +51,7 @@ class UpgradeFireflyInstructions extends Command
/** @var string $version */ /** @var string $version */
$version = config('firefly.version'); $version = config('firefly.version');
$config = config('upgrade.text'); $config = config('upgrade.text');
$text = null; $text = null;
foreach (array_keys($config) as $compare) { foreach (array_keys($config) as $compare) {
// if string starts with: // if string starts with:
$len = strlen($compare); $len = strlen($compare);

View File

@ -12,13 +12,13 @@ declare(strict_types = 1);
namespace FireflyIII\Console\Commands; namespace FireflyIII\Console\Commands;
use Crypt; use Crypt;
use DB;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
use FireflyIII\Models\Budget; use FireflyIII\Models\Budget;
use FireflyIII\Models\Category; use FireflyIII\Models\Category;
use FireflyIII\Models\Tag; use FireflyIII\Models\Tag;
use FireflyIII\Models\Transaction; use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Console\Command; use Illuminate\Console\Command;
@ -79,6 +79,9 @@ class VerifyDatabase extends Command
// report on journals with no transactions at all. // report on journals with no transactions at all.
$this->reportNoTransactions(); $this->reportNoTransactions();
// transfers with budgets.
$this->reportTransfersBudgets();
} }
/** /**
@ -89,11 +92,10 @@ class VerifyDatabase extends Command
$set = Account $set = Account
::leftJoin('transactions', 'transactions.account_id', '=', 'accounts.id') ::leftJoin('transactions', 'transactions.account_id', '=', 'accounts.id')
->leftJoin('users', 'accounts.user_id', '=', 'users.id') ->leftJoin('users', 'accounts.user_id', '=', 'users.id')
->groupBy('accounts.id') ->groupBy(['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email'])
->having('transaction_count', '=', 0) ->whereNull('transactions.account_id')
->get( ->get(
['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email', ['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email']
DB::raw('COUNT(`transactions`.`id`) AS `transaction_count`')]
); );
/** @var stdClass $entry */ /** @var stdClass $entry */
@ -113,9 +115,9 @@ class VerifyDatabase extends Command
$set = Budget $set = Budget
::leftJoin('budget_limits', 'budget_limits.budget_id', '=', 'budgets.id') ::leftJoin('budget_limits', 'budget_limits.budget_id', '=', 'budgets.id')
->leftJoin('users', 'budgets.user_id', '=', 'users.id') ->leftJoin('users', 'budgets.user_id', '=', 'users.id')
->groupBy('budgets.id') ->groupBy(['budgets.id', 'budgets.name', 'budgets.user_id', 'users.email'])
->having('budget_limit_count', '=', 0) ->whereNull('budget_limits.id')
->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'users.email', DB::raw('COUNT(`budget_limits`.`id`) AS `budget_limit_count`')]); ->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'users.email']);
/** @var stdClass $entry */ /** @var stdClass $entry */
foreach ($set as $entry) { foreach ($set as $entry) {
@ -225,19 +227,16 @@ class VerifyDatabase extends Command
} }
} }
/**
*
*/
private function reportNoTransactions() private function reportNoTransactions()
{ {
/*
* select transaction_journals.id, count(transactions.id) as transaction_count from transaction_journals
left join transactions ON transaction_journals.id = transactions.transaction_journal_id
group by transaction_journals.id
having transaction_count = 0
*/
$set = TransactionJournal $set = TransactionJournal
::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->groupBy('transaction_journals.id') ->groupBy('transaction_journals.id')
->having('transaction_count', '=', 0) ->whereNull('transactions.transaction_journal_id')
->get(['transaction_journals.id', DB::raw('COUNT(`transactions`.`id`) as `transaction_count`')]); ->get(['transaction_journals.id']);
foreach ($set as $entry) { foreach ($set as $entry) {
$this->error( $this->error(
@ -306,4 +305,29 @@ having transaction_count = 0
); );
} }
} }
/**
*
*/
private function reportTransfersBudgets()
{
$set = TransactionJournal
::distinct()
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
->leftJoin('budget_transaction_journal', 'transaction_journals.id', '=', 'budget_transaction_journal.transaction_journal_id')
->where('transaction_types.type', TransactionType::TRANSFER)
->whereNotNull('budget_transaction_journal.budget_id')->get(['transaction_journals.id']);
/** @var TransactionJournal $entry */
foreach ($set as $entry) {
$this->error(
sprintf(
'Error: Transaction journal #%d is a transfer, but has a budget. Edit it without changing anything, so the budget will be removed.',
$entry->id
)
);
}
}
} }

28
app/Console/Kernel.php Normal file → Executable file
View File

@ -13,8 +13,10 @@ namespace FireflyIII\Console;
use FireflyIII\Console\Commands\EncryptFile; use FireflyIII\Console\Commands\EncryptFile;
use FireflyIII\Console\Commands\Import; use FireflyIII\Console\Commands\Import;
use FireflyIII\Console\Commands\ScanAttachments;
use FireflyIII\Console\Commands\UpgradeFireflyInstructions; use FireflyIII\Console\Commands\UpgradeFireflyInstructions;
use FireflyIII\Console\Commands\VerifyDatabase; use FireflyIII\Console\Commands\VerifyDatabase;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel; use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
/** /**
@ -24,11 +26,10 @@ use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
*/ */
class Kernel extends ConsoleKernel class Kernel extends ConsoleKernel
{ {
/** /**
* The bootstrap classes for the application. * The bootstrap classes for the application.
* *
* This needs to be for with the next upgrade. * Next upgrade verify these are the same.
* *
* @var array * @var array
*/ */
@ -55,5 +56,28 @@ class Kernel extends ConsoleKernel
VerifyDatabase::class, VerifyDatabase::class,
Import::class, Import::class,
EncryptFile::class, EncryptFile::class,
ScanAttachments::class,
]; ];
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('routes/console.php');
}
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
*
* @return void
*/
protected function schedule(Schedule $schedule)
{
}
} }

View File

@ -148,16 +148,20 @@ class AccountCrud implements AccountCrudInterface
if (count($types) > 0) { if (count($types) > 0) {
$query->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id'); $query->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id');
$query->whereIn('account_types.type', $types); $query->whereIn('account_types.type', $types);
} }
Log::debug(sprintf('Searching for account named %s of the following type(s)', $name), ['types' => $types]);
$accounts = $query->get(['accounts.*']); $accounts = $query->get(['accounts.*']);
/** @var Account $account */ /** @var Account $account */
foreach ($accounts as $account) { foreach ($accounts as $account) {
if ($account->name === $name) { if ($account->name === $name) {
Log::debug(sprintf('Found #%d (%s) with type id %d', $account->id, $account->name, $account->account_type_id));
return $account; return $account;
} }
} }
Log::debug('Found nothing.');
return new Account; return new Account;
} }

33
app/Exceptions/Handler.php Normal file → Executable file
View File

@ -10,14 +10,15 @@
declare(strict_types = 1); declare(strict_types = 1);
namespace FireflyIII\Exceptions; namespace FireflyIII\Exceptions;
use Auth;
use ErrorException; use ErrorException;
use Exception; use Exception;
use FireflyIII\Jobs\MailError; use FireflyIII\Jobs\MailError;
use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Request; use Illuminate\Session\TokenMismatchException;
use Illuminate\Validation\ValidationException as ValException;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
/** /**
@ -34,9 +35,12 @@ class Handler extends ExceptionHandler
*/ */
protected $dontReport protected $dontReport
= [ = [
AuthenticationException::class,
AuthorizationException::class, AuthorizationException::class,
HttpException::class, HttpException::class,
ModelNotFoundException::class, ModelNotFoundException::class,
TokenMismatchException::class,
ValException::class,
]; ];
/** /**
@ -71,15 +75,14 @@ class Handler extends ExceptionHandler
*/ */
public function report(Exception $exception) public function report(Exception $exception)
{ {
if ($exception instanceof FireflyException || $exception instanceof ErrorException) { if ($exception instanceof FireflyException || $exception instanceof ErrorException) {
$userData = [ $userData = [
'id' => 0, 'id' => 0,
'email' => 'unknown@example.com', 'email' => 'unknown@example.com',
]; ];
if (Auth::check()) { if (auth()->check()) {
$userData['id'] = Auth::user()->id; $userData['id'] = auth()->user()->id;
$userData['email'] = Auth::user()->email; $userData['email'] = auth()->user()->email;
} }
$data = [ $data = [
'class' => get_class($exception), 'class' => get_class($exception),
@ -92,10 +95,26 @@ class Handler extends ExceptionHandler
]; ];
// create job that will mail. // create job that will mail.
$job = new MailError($userData, env('SITE_OWNER'), Request::ip(), $data); $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
$job = new MailError($userData, env('SITE_OWNER', ''), $ip, $data);
dispatch($job); dispatch($job);
} }
parent::report($exception); parent::report($exception);
} }
/**
* Convert an authentication exception into an unauthenticated response.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
protected function unauthenticated($request)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest('login');
}
} }

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Export\Collector; namespace FireflyIII\Export\Collector;
use Auth;
use Crypt; use Crypt;
use FireflyIII\Models\ExportJob; use FireflyIII\Models\ExportJob;
use Illuminate\Contracts\Encryption\DecryptException; use Illuminate\Contracts\Encryption\DecryptException;
@ -50,7 +49,7 @@ class UploadCollector extends BasicCollector implements CollectorInterface
$this->exportDisk = Storage::disk('export'); $this->exportDisk = Storage::disk('export');
// file names associated with the old import routine. // file names associated with the old import routine.
$this->expected = 'csv-upload-' . Auth::user()->id . '-'; $this->expected = 'csv-upload-' . auth()->user()->id . '-';
// for the new import routine: // for the new import routine:
$this->getImportKeys(); $this->getImportKeys();
@ -76,7 +75,7 @@ class UploadCollector extends BasicCollector implements CollectorInterface
*/ */
private function getImportKeys() private function getImportKeys()
{ {
$set = Auth::user()->importJobs()->where('status', 'import_complete')->get(['import_jobs.*']); $set = auth()->user()->importJobs()->where('status', 'import_complete')->get(['import_jobs.*']);
if ($set->count() > 0) { if ($set->count() > 0) {
$keys = $set->pluck('key')->toArray(); $keys = $set->pluck('key')->toArray();
$this->importKeys = $keys; $this->importKeys = $keys;
@ -158,7 +157,7 @@ class UploadCollector extends BasicCollector implements CollectorInterface
{ {
// find job associated with import file: // find job associated with import file:
$name = str_replace('.upload', '', $entry); $name = str_replace('.upload', '', $entry);
$job = Auth::user()->importJobs()->where('key', $name)->first(); $job = auth()->user()->importJobs()->where('key', $name)->first();
$content = ''; $content = '';
try { try {
$content = Crypt::decrypt($this->uploadDisk->get($entry)); $content = Crypt::decrypt($this->uploadDisk->get($entry));

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Handlers\Events; namespace FireflyIII\Handlers\Events;
use Auth;
use FireflyIII\Events\TransactionJournalStored; use FireflyIII\Events\TransactionJournalStored;
use FireflyIII\Models\PiggyBank; use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankEvent; use FireflyIII\Models\PiggyBankEvent;
@ -39,7 +38,7 @@ class ConnectJournalToPiggyBank
$piggyBankId = $event->piggyBankId; $piggyBankId = $event->piggyBankId;
/** @var PiggyBank $piggyBank */ /** @var PiggyBank $piggyBank */
$piggyBank = Auth::user()->piggyBanks()->where('piggy_banks.id', $piggyBankId)->first(['piggy_banks.*']); $piggyBank = auth()->user()->piggyBanks()->where('piggy_banks.id', $piggyBankId)->first(['piggy_banks.*']);
if (is_null($piggyBank)) { if (is_null($piggyBank)) {
return true; return true;

View File

@ -17,7 +17,6 @@ use FireflyIII\Models\Rule;
use FireflyIII\Models\RuleGroup; use FireflyIII\Models\RuleGroup;
use FireflyIII\Rules\Processor; use FireflyIII\Rules\Processor;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Support\Facades\Auth;
/** /**
* Class FireRulesForStore * Class FireRulesForStore
@ -38,7 +37,7 @@ class FireRulesForStore
{ {
// get all the user's rule groups, with the rules, order by 'order'. // get all the user's rule groups, with the rules, order by 'order'.
/** @var User $user */ /** @var User $user */
$user = Auth::user(); $user = auth()->user();
$groups = $user->ruleGroups()->where('rule_groups.active', 1)->orderBy('order', 'ASC')->get(); $groups = $user->ruleGroups()->where('rule_groups.active', 1)->orderBy('order', 'ASC')->get();
// //
/** @var RuleGroup $group */ /** @var RuleGroup $group */

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Handlers\Events; namespace FireflyIII\Handlers\Events;
use Auth;
use FireflyIII\Events\TransactionJournalUpdated; use FireflyIII\Events\TransactionJournalUpdated;
use FireflyIII\Models\Rule; use FireflyIII\Models\Rule;
use FireflyIII\Models\RuleGroup; use FireflyIII\Models\RuleGroup;
@ -36,7 +35,7 @@ class FireRulesForUpdate
{ {
// get all the user's rule groups, with the rules, order by 'order'. // get all the user's rule groups, with the rules, order by 'order'.
/** @var User $user */ /** @var User $user */
$user = Auth::user(); $user = auth()->user();
$groups = $user->ruleGroups()->where('rule_groups.active', 1)->orderBy('order', 'ASC')->get(); $groups = $user->ruleGroups()->where('rule_groups.active', 1)->orderBy('order', 'ASC')->get();
// //
/** @var RuleGroup $group */ /** @var RuleGroup $group */

View File

@ -10,7 +10,6 @@
declare(strict_types = 1); declare(strict_types = 1);
namespace FireflyIII\Helpers\Attachments; namespace FireflyIII\Helpers\Attachments;
use Auth;
use Crypt; use Crypt;
use FireflyIII\Models\Attachment; use FireflyIII\Models\Attachment;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@ -60,7 +59,7 @@ class AttachmentHelper implements AttachmentHelperInterface
*/ */
public function getAttachmentLocation(Attachment $attachment): string public function getAttachmentLocation(Attachment $attachment): string
{ {
$path = storage_path('upload') . DIRECTORY_SEPARATOR . 'at-' . $attachment->id . '.data'; $path = sprintf('%s%sat-%d.data', storage_path('upload'), DIRECTORY_SEPARATOR, intval($attachment->id));
return $path; return $path;
} }
@ -112,7 +111,7 @@ class AttachmentHelper implements AttachmentHelperInterface
$md5 = md5_file($file->getRealPath()); $md5 = md5_file($file->getRealPath());
$name = $file->getClientOriginalName(); $name = $file->getClientOriginalName();
$class = get_class($model); $class = get_class($model);
$count = Auth::user()->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count(); $count = auth()->user()->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count();
if ($count > 0) { if ($count > 0) {
$msg = (string)trans('validation.file_already_attached', ['name' => $name]); $msg = (string)trans('validation.file_already_attached', ['name' => $name]);
@ -139,7 +138,7 @@ class AttachmentHelper implements AttachmentHelperInterface
} }
$attachment = new Attachment; // create Attachment object. $attachment = new Attachment; // create Attachment object.
$attachment->user()->associate(Auth::user()); $attachment->user()->associate(auth()->user());
$attachment->attachable()->associate($model); $attachment->attachable()->associate($model);
$attachment->md5 = md5_file($file->getRealPath()); $attachment->md5 = md5_file($file->getRealPath());
$attachment->filename = $file->getClientOriginalName(); $attachment->filename = $file->getClientOriginalName();

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Helpers\Report; namespace FireflyIII\Helpers\Report;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
use DB; use DB;
use FireflyIII\Helpers\Collection\Balance; use FireflyIII\Helpers\Collection\Balance;
@ -102,34 +101,34 @@ class BalanceReportHelper implements BalanceReportHelperInterface
private function allCoveredByBalancingActs(Collection $accounts, Carbon $start, Carbon $end): Collection private function allCoveredByBalancingActs(Collection $accounts, Carbon $start, Carbon $end): Collection
{ {
$ids = $accounts->pluck('id')->toArray(); $ids = $accounts->pluck('id')->toArray();
$set = Auth::user()->tags() $set = auth()->user()->tags()
->leftJoin('tag_transaction_journal', 'tag_transaction_journal.tag_id', '=', 'tags.id') ->leftJoin('tag_transaction_journal', 'tag_transaction_journal.tag_id', '=', 'tags.id')
->leftJoin('transaction_journals', 'tag_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id') ->leftJoin('transaction_journals', 'tag_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id')
->leftJoin('transaction_types', 'transaction_journals.transaction_type_id', '=', 'transaction_types.id') ->leftJoin('transaction_types', 'transaction_journals.transaction_type_id', '=', 'transaction_types.id')
->leftJoin( ->leftJoin(
'transactions AS t_source', function (JoinClause $join) { 'transactions AS t_source', function (JoinClause $join) {
$join->on('transaction_journals.id', '=', 't_source.transaction_journal_id')->where('t_source.amount', '<', 0); $join->on('transaction_journals.id', '=', 't_source.transaction_journal_id')->where('t_source.amount', '<', 0);
} }
) )
->leftJoin( ->leftJoin(
'transactions AS t_destination', function (JoinClause $join) { 'transactions AS t_destination', function (JoinClause $join) {
$join->on('transaction_journals.id', '=', 't_destination.transaction_journal_id')->where('t_destination.amount', '>', 0); $join->on('transaction_journals.id', '=', 't_destination.transaction_journal_id')->where('t_destination.amount', '>', 0);
} }
) )
->where('tags.tagMode', 'balancingAct') ->where('tags.tagMode', 'balancingAct')
->where('transaction_types.type', TransactionType::TRANSFER) ->where('transaction_types.type', TransactionType::TRANSFER)
->where('transaction_journals.date', '>=', $start->format('Y-m-d')) ->where('transaction_journals.date', '>=', $start->format('Y-m-d'))
->where('transaction_journals.date', '<=', $end->format('Y-m-d')) ->where('transaction_journals.date', '<=', $end->format('Y-m-d'))
->whereNull('transaction_journals.deleted_at') ->whereNull('transaction_journals.deleted_at')
->whereIn('t_source.account_id', $ids) ->whereIn('t_source.account_id', $ids)
->whereIn('t_destination.account_id', $ids) ->whereIn('t_destination.account_id', $ids)
->groupBy('t_destination.account_id') ->groupBy('t_destination.account_id')
->get( ->get(
[ [
't_destination.account_id', 't_destination.account_id',
DB::raw('SUM(`t_destination`.`amount`) as `sum`'), DB::raw('SUM(`t_destination`.`amount`) as `sum`'),
] ]
); );
return $set; return $set;
} }

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Controllers; namespace FireflyIII\Http\Controllers;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
use ExpandedForm; use ExpandedForm;
use FireflyIII\Crud\Account\AccountCrudInterface; use FireflyIII\Crud\Account\AccountCrudInterface;
@ -173,9 +172,9 @@ class AccountController extends Controller
$types = config('firefly.accountTypesByIdentifier.' . $what); $types = config('firefly.accountTypesByIdentifier.' . $what);
$accounts = $crud->getAccountsByType($types); $accounts = $crud->getAccountsByType($types);
/** @var Carbon $start */ /** @var Carbon $start */
$start = clone session('start', Carbon::now()->startOfMonth()); $start = clone session('start', Carbon::now()->startOfMonth());
/** @var Carbon $end */ /** @var Carbon $end */
$end = clone session('end', Carbon::now()->endOfMonth()); $end = clone session('end', Carbon::now()->endOfMonth());
$start->subDay(); $start->subDay();
$ids = $accounts->pluck('id')->toArray(); $ids = $accounts->pluck('id')->toArray();
@ -207,16 +206,16 @@ class AccountController extends Controller
$subTitle = $account->name; $subTitle = $account->name;
$range = Preferences::get('viewRange', '1M')->data; $range = Preferences::get('viewRange', '1M')->data;
/** @var Carbon $start */ /** @var Carbon $start */
$start = session('start', Navigation::startOfPeriod(new Carbon, $range)); $start = session('start', Navigation::startOfPeriod(new Carbon, $range));
/** @var Carbon $end */ /** @var Carbon $end */
$end = session('end', Navigation::endOfPeriod(new Carbon, $range)); $end = session('end', Navigation::endOfPeriod(new Carbon, $range));
$page = intval(Input::get('page')); $page = intval(Input::get('page'));
$pageSize = Preferences::get('transactionPageSize', 50)->data; $pageSize = Preferences::get('transactionPageSize', 50)->data;
$offset = ($page - 1) * $pageSize; $offset = ($page - 1) * $pageSize;
$set = $repository->journalsInPeriod(new Collection([$account]), [], $start, $end); $set = $repository->journalsInPeriod(new Collection([$account]), [], $start, $end);
$count = $set->count(); $count = $set->count();
$subSet = $set->splice($offset, $pageSize); $subSet = $set->splice($offset, $pageSize);
$journals = new LengthAwarePaginator($subSet, $count, $pageSize, $page); $journals = new LengthAwarePaginator($subSet, $count, $pageSize, $page);
$journals->setPath('accounts/show/' . $account->id); $journals->setPath('accounts/show/' . $account->id);
// grouped other months thing: // grouped other months thing:
@ -301,7 +300,7 @@ class AccountController extends Controller
'virtualBalance' => round($request->input('virtualBalance'), 2), 'virtualBalance' => round($request->input('virtualBalance'), 2),
'virtualBalanceCurrency' => intval($request->input('amount_currency_id_virtualBalance')), 'virtualBalanceCurrency' => intval($request->input('amount_currency_id_virtualBalance')),
'active' => true, 'active' => true,
'user' => Auth::user()->id, 'user' => auth()->user()->id,
'iban' => $request->input('iban'), 'iban' => $request->input('iban'),
'accountNumber' => $request->input('accountNumber'), 'accountNumber' => $request->input('accountNumber'),
'accountRole' => $request->input('accountRole'), 'accountRole' => $request->input('accountRole'),
@ -347,7 +346,7 @@ class AccountController extends Controller
$accountData = [ $accountData = [
'name' => $request->input('name'), 'name' => $request->input('name'),
'active' => $request->input('active'), 'active' => $request->input('active'),
'user' => Auth::user()->id, 'user' => auth()->user()->id,
'iban' => $request->input('iban'), 'iban' => $request->input('iban'),
'accountNumber' => $request->input('accountNumber'), 'accountNumber' => $request->input('accountNumber'),
'accountRole' => $request->input('accountRole'), 'accountRole' => $request->input('accountRole'),

View File

@ -58,7 +58,7 @@ class DomainController extends Controller
return redirect(route('admin.users.domains')); return redirect(route('admin.users.domains'));
} }
$domain = $request->get('domain'); $domain = strtolower($request->get('domain'));
$blocked = FireflyConfig::get('blocked-domains', [])->data; $blocked = FireflyConfig::get('blocked-domains', [])->data;
if (in_array($domain, $blocked)) { if (in_array($domain, $blocked)) {

View File

@ -11,22 +11,10 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Controllers\Auth; namespace FireflyIII\Http\Controllers\Auth;
use Auth;
use Config;
use FireflyIII\Events\UserRegistration;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Support\Facades\FireflyConfig;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers; use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins; use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Lang;
use Log;
use Mail;
use Session;
use Swift_TransportException;
use Validator; use Validator;
@ -56,144 +44,6 @@ class AuthController extends Controller
parent::__construct(); parent::__construct();
} }
/**
* Handle a login request to the application.
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\Response
*/
public function login(Request $request)
{
$this->validate($request, [$this->loginUsername() => 'required', 'password' => 'required',]);
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
$credentials['blocked'] = 0; // most not be blocked.
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// check if user is blocked:
$errorMessage = '';
/** @var User $foundUser */
$foundUser = User::where('email', $credentials['email'])->where('blocked', 1)->first();
if (!is_null($foundUser)) {
// if it exists, show message:
$code = strlen(strval($foundUser->blocked_code)) > 0 ? $foundUser->blocked_code : 'general_blocked';
$errorMessage = strval(trans('firefly.' . $code . '_error', ['email' => $credentials['email']]));
$this->reportBlockedUserLoginAttempt($foundUser, $code, $request->ip());
}
if ($throttles) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request, $errorMessage);
}
/**
* Handle a registration request for the application.
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\Response
* @throws FireflyException
* @throws \Illuminate\Foundation\Validation\ValidationException
*/
public function register(Request $request)
{
// is allowed to?
$singleUserMode = FireflyConfig::get('single_user_mode', Config::get('firefly.configuration.single_user_mode'))->data;
$userCount = User::count();
if ($singleUserMode === true && $userCount > 0) {
$message = 'Registration is currently not available.';
return view('error', compact('message'));
}
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
$data = $request->all();
$data['password'] = bcrypt($data['password']);
// is user email domain blocked?
if ($this->isBlockedDomain($data['email'])) {
$validator->getMessageBag()->add('email', (string)trans('validation.invalid_domain'));
$this->reportBlockedDomainRegistrationAttempt($data['email'], $request->ip());
$this->throwValidationException(
$request, $validator
);
}
$user = $this->create($request->all());
// trigger user registration event:
event(new UserRegistration($user, $request->ip()));
Auth::login($user);
Session::flash('success', strval(trans('firefly.registered')));
Session::flash('gaEventCategory', 'user');
Session::flash('gaEventAction', 'new-registration');
return redirect($this->redirectPath());
}
/**
* Show the application login form.
*
* @return \Illuminate\Http\Response
*/
public function showLoginForm()
{
// is allowed to?
$singleUserMode = FireflyConfig::get('single_user_mode', Config::get('firefly.configuration.single_user_mode'))->data;
$userCount = User::count();
$allowRegistration = true;
if ($singleUserMode === true && $userCount > 0) {
$allowRegistration = false;
}
return view('auth.login', compact('allowRegistration'));
}
/**
* Show the application registration form.
*
* @return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
$showDemoWarning = env('SHOW_DEMO_WARNING', false);
// is allowed to?
$singleUserMode = FireflyConfig::get('single_user_mode', Config::get('firefly.configuration.single_user_mode'))->data;
$userCount = User::count();
if ($singleUserMode === true && $userCount > 0) {
$message = 'Registration is currently not available.';
return view('error', compact('message'));
}
return view('auth.register', compact('showDemoWarning'));
}
/** /**
* Create a new user instance after a valid registration. * Create a new user instance after a valid registration.
@ -212,67 +62,6 @@ class AuthController extends Controller
); );
} }
/**
* @return array
*/
protected function getBlockedDomains()
{
return FireflyConfig::get('blocked-domains', [])->data;
}
/**
* Get the failed login message.
*
* @param string $message
*
* @return string
*/
protected function getFailedLoginMessage(string $message)
{
if (strlen($message) > 0) {
return $message;
}
return Lang::has('auth.failed')
? Lang::get('auth.failed')
: 'These credentials do not match our records.';
}
/**
* @param string $email
*
* @return bool
*/
protected function isBlockedDomain(string $email)
{
$parts = explode('@', $email);
$blocked = $this->getBlockedDomains();
if (isset($parts[1]) && in_array($parts[1], $blocked)) {
return true;
}
return false;
}
/**
* Get the failed login response instance.
*
* @param \Illuminate\Http\Request $request
* @param string $message
*
* @return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request, string $message)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors(
[
$this->loginUsername() => $this->getFailedLoginMessage($message),
]
);
}
/** /**
* Get a validator for an incoming registration request. * Get a validator for an incoming registration request.
@ -291,61 +80,5 @@ class AuthController extends Controller
); );
} }
/**
* Send a message home about a blocked domain and the address attempted to register.
*
* @param string $registrationMail
* @param string $ipAddress
*/
private function reportBlockedDomainRegistrationAttempt(string $registrationMail, string $ipAddress)
{
try {
$email = env('SITE_OWNER', false);
$parts = explode('@', $registrationMail);
$domain = $parts[1];
$fields = [
'email_address' => $registrationMail,
'blocked_domain' => $domain,
'ip' => $ipAddress,
];
Mail::send(
['emails.blocked-registration-html', 'emails.blocked-registration'], $fields, function (Message $message) use ($email, $domain) {
$message->to($email, $email)->subject('Blocked a registration attempt with domain ' . $domain . '.');
}
);
} catch (Swift_TransportException $e) {
Log::error($e->getMessage());
}
}
/**
* Send a message home about the blocked attempt to login.
* Perhaps in a later stage, simply log these messages.
*
* @param User $user
* @param string $code
* @param string $ipAddress
*/
private function reportBlockedUserLoginAttempt(User $user, string $code, string $ipAddress)
{
try {
$email = env('SITE_OWNER', false);
$fields = [
'user_id' => $user->id,
'user_address' => $user->email,
'code' => $code,
'ip' => $ipAddress,
];
Mail::send(
['emails.blocked-login-html', 'emails.blocked-login'], $fields, function (Message $message) use ($email, $user) {
$message->to($email, $email)->subject('Blocked a login attempt from ' . trim($user->email) . '.');
}
);
} catch (Swift_TransportException $e) {
Log::error($e->getMessage());
}
}
} }

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Controllers\Auth; namespace FireflyIII\Http\Controllers\Auth;
use Auth;
use FireflyIII\Events\ResendConfirmation; use FireflyIII\Events\ResendConfirmation;
use FireflyIII\Events\UserIsConfirmed; use FireflyIII\Events\UserIsConfirmed;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
@ -55,10 +54,10 @@ class ConfirmationController extends Controller
if ($database === $code && ($now - $time <= $maxDiff)) { if ($database === $code && ($now - $time <= $maxDiff)) {
// trigger user registration event: // trigger user registration event:
event(new UserIsConfirmed(Auth::user(), $request->ip())); event(new UserIsConfirmed(auth()->user(), $request->ip()));
Preferences::setForUser(Auth::user(), 'user_confirmed', true); Preferences::setForUser(auth()->user(), 'user_confirmed', true);
Preferences::setForUser(Auth::user(), 'user_confirmed_confirmed', time()); Preferences::setForUser(auth()->user(), 'user_confirmed_confirmed', time());
Session::flash('success', strval(trans('firefly.account_is_confirmed'))); Session::flash('success', strval(trans('firefly.account_is_confirmed')));
return redirect(route('home')); return redirect(route('home'));
@ -79,7 +78,7 @@ class ConfirmationController extends Controller
$owner = env('SITE_OWNER', 'mail@example.com'); $owner = env('SITE_OWNER', 'mail@example.com');
$view = 'auth.confirmation.no-resent'; $view = 'auth.confirmation.no-resent';
if ($now - $time > $maxDiff) { if ($now - $time > $maxDiff) {
event(new ResendConfirmation(Auth::user(), $request->ip())); event(new ResendConfirmation(auth()->user(), $request->ip()));
$view = 'auth.confirmation.resent'; $view = 'auth.confirmation.resent';
} }

View File

@ -0,0 +1,34 @@
<?php
/**
* ForgotPasswordController.php
* Copyright (C) 2016 thegrumpydictator@gmail.com
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
declare(strict_types = 1);
namespace FireflyIII\Http\Controllers\Auth;
use FireflyIII\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
/**
* Class ForgotPasswordController
*
* @package FireflyIII\Http\Controllers\Auth
*/
class ForgotPasswordController extends Controller
{
use SendsPasswordResetEmails;
/**
* Create a new controller instance.
*
*/
public function __construct()
{
parent::__construct();
$this->middleware('guest');
}
}

View File

@ -0,0 +1,195 @@
<?php
/**
* LoginController.php
* Copyright (C) 2016 thegrumpydictator@gmail.com
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
declare(strict_types = 1);
namespace FireflyIII\Http\Controllers\Auth;
use Config;
use FireflyConfig;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\User;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Lang;
use Log;
use Mail;
use Swift_TransportException;
/**
* Class LoginController
*
* @package FireflyIII\Http\Controllers\Auth
*/
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login / registration.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
*/
public function __construct()
{
parent::__construct();
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Handle a login request to the application.
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\Response
*/
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->credentials($request);
$credentials['blocked'] = 0; // most not be blocked.
if ($this->guard()->attempt($credentials, $request->has('remember'))) {
return $this->sendLoginResponse($request);
}
// check if user is blocked:
$errorMessage = '';
/** @var User $foundUser */
$foundUser = User::where('email', $credentials['email'])->where('blocked', 1)->first();
if (!is_null($foundUser)) {
// if it exists, show message:
$code = strlen(strval($foundUser->blocked_code)) > 0 ? $foundUser->blocked_code : 'general_blocked';
$errorMessage = strval(trans('firefly.' . $code . '_error', ['email' => $credentials['email']]));
$this->reportBlockedUserLoginAttempt($foundUser, $code, $request->ip());
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if (!$lockedOut) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request, $errorMessage);
}
/**
* Show the application login form.
*
* @return \Illuminate\Http\Response
*/
public function showLoginForm(Request $request)
{
// is allowed to?
$singleUserMode = FireflyConfig::get('single_user_mode', Config::get('firefly.configuration.single_user_mode'))->data;
$userCount = User::count();
$allowRegistration = true;
if ($singleUserMode === true && $userCount > 0) {
$allowRegistration = false;
}
$email = $request->old('email');
$remember = $request->old('remember');
return view('auth.login', compact('allowRegistration', 'email', 'remember'));
}
/**
* Get the failed login message.
*
* @param string $message
*
* @return string
*/
protected function getFailedLoginMessage(string $message)
{
if (strlen($message) > 0) {
return $message;
}
return Lang::has('auth.failed') ? Lang::get('auth.failed') : 'These credentials do not match our records.';
}
/**
* Get the failed login response instance.
*
* @param \Illuminate\Http\Request $request
* @param string $message
*
* @return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request, string $message)
{
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors(
[
$this->username() => $this->getFailedLoginMessage($message),
]
);
}
/**
* Send a message home about the blocked attempt to login.
* Perhaps in a later stage, simply log these messages.
*
* @param User $user
* @param string $code
* @param string $ipAddress
*/
private function reportBlockedUserLoginAttempt(User $user, string $code, string $ipAddress)
{
try {
$email = env('SITE_OWNER', false);
$fields = [
'user_id' => $user->id,
'user_address' => $user->email,
'code' => $code,
'ip' => $ipAddress,
];
Mail::send(
['emails.blocked-login-html', 'emails.blocked-login'], $fields, function (Message $message) use ($email, $user) {
$message->to($email, $email)->subject('Blocked a login attempt from ' . trim($user->email) . '.');
}
);
} catch (Swift_TransportException $e) {
Log::error($e->getMessage());
}
}
}

View File

@ -23,6 +23,7 @@ use Illuminate\Support\Facades\Password;
* Class PasswordController * Class PasswordController
* *
* @package FireflyIII\Http\Controllers\Auth * @package FireflyIII\Http\Controllers\Auth
* @method getEmailSubject
*/ */
class PasswordController extends Controller class PasswordController extends Controller
{ {

View File

@ -0,0 +1,224 @@
<?php
/**
* RegisterController.php
* Copyright (C) 2016 thegrumpydictator@gmail.com
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
declare(strict_types = 1);
namespace FireflyIII\Http\Controllers\Auth;
use Auth;
use Config;
use FireflyIII\Events\UserRegistration;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Support\Facades\FireflyConfig;
use FireflyIII\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Log;
use Mail;
use Session;
use Swift_TransportException;
use Validator;
/**
* Class RegisterController
*
* @package FireflyIII\Http\Controllers\Auth
*/
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after login / registration.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*/
public function __construct()
{
parent::__construct();
$this->middleware('guest');
}
/**
* @param Request $request
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
*/
public function register(Request $request)
{
// is allowed to?
$singleUserMode = FireflyConfig::get('single_user_mode', Config::get('firefly.configuration.single_user_mode'))->data;
$userCount = User::count();
if ($singleUserMode === true && $userCount > 0) {
$message = 'Registration is currently not available.';
return view('error', compact('message'));
}
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException($request, $validator);
}
$data = $request->all();
$data['password'] = bcrypt($data['password']);
// is user email domain blocked?
if ($this->isBlockedDomain($data['email'])) {
$validator->getMessageBag()->add('email', (string)trans('validation.invalid_domain'));
$this->reportBlockedDomainRegistrationAttempt($data['email'], $request->ip());
$this->throwValidationException($request, $validator);
}
$user = $this->create($request->all());
// trigger user registration event:
event(new UserRegistration($user, $request->ip()));
Auth::login($user);
Session::flash('success', strval(trans('firefly.registered')));
Session::flash('gaEventCategory', 'user');
Session::flash('gaEventAction', 'new-registration');
return redirect($this->redirectPath());
}
/**
* OLD
* Show the application registration form.
*
* @return \Illuminate\Http\Response
*/
public function showRegistrationForm(Request $request)
{
$showDemoWarning = config('firefly.show-demo-warning', false);
// is allowed to?
$singleUserMode = FireflyConfig::get('single_user_mode', Config::get('firefly.configuration.single_user_mode'))->data;
$userCount = User::count();
if ($singleUserMode === true && $userCount > 0) {
$message = 'Registration is currently not available.';
return view('error', compact('message'));
}
$email = $request->old('email');
return view('auth.register', compact('showDemoWarning', 'email'));
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
*
* @return User
*/
protected function create(array $data)
{
return User::create(
[
'email' => $data['email'],
'password' => bcrypt($data['password']),
]
);
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
*
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make(
$data, [
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]
);
}
/**
* @return array
*/
private function getBlockedDomains()
{
return FireflyConfig::get('blocked-domains', [])->data;
}
/**
* @param string $email
*
* @return bool
*/
private function isBlockedDomain(string $email)
{
$parts = explode('@', $email);
$blocked = $this->getBlockedDomains();
if (isset($parts[1]) && in_array($parts[1], $blocked)) {
return true;
}
return false;
}
/**
* Send a message home about a blocked domain and the address attempted to register.
*
* @param string $registrationMail
* @param string $ipAddress
*/
private function reportBlockedDomainRegistrationAttempt(string $registrationMail, string $ipAddress)
{
try {
$email = env('SITE_OWNER', false);
$parts = explode('@', $registrationMail);
$domain = $parts[1];
$fields = [
'email_address' => $registrationMail,
'blocked_domain' => $domain,
'ip' => $ipAddress,
];
Mail::send(
['emails.blocked-registration-html', 'emails.blocked-registration'], $fields, function (Message $message) use ($email, $domain) {
$message->to($email, $email)->subject('Blocked a registration attempt with domain ' . $domain . '.');
}
);
} catch (Swift_TransportException $e) {
Log::error($e->getMessage());
}
}
}

View File

@ -0,0 +1,44 @@
<?php
/**
* ResetPasswordController.php
* Copyright (C) 2016 thegrumpydictator@gmail.com
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
declare(strict_types = 1);
namespace FireflyIII\Http\Controllers\Auth;
use FireflyIII\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
/**
* Class ResetPasswordController
*
* @package FireflyIII\Http\Controllers\Auth
*/
class ResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Create a new controller instance.
*
*/
public function __construct()
{
$this->middleware('guest');
}
}

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Controllers\Auth; namespace FireflyIII\Http\Controllers\Auth;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
@ -34,7 +33,7 @@ class TwoFactorController extends Controller
*/ */
public function index() public function index()
{ {
$user = Auth::user(); $user = auth()->user();
// to make sure the validator in the next step gets the secret, we push it in session // to make sure the validator in the next step gets the secret, we push it in session
$secret = Preferences::get('twoFactorAuthSecret', '')->data; $secret = Preferences::get('twoFactorAuthSecret', '')->data;
@ -54,7 +53,7 @@ class TwoFactorController extends Controller
*/ */
public function lostTwoFactor() public function lostTwoFactor()
{ {
$user = Auth::user(); $user = auth()->user();
$siteOwner = env('SITE_OWNER', ''); $siteOwner = env('SITE_OWNER', '');
$title = strval(trans('firefly.two_factor_forgot_title')); $title = strval(trans('firefly.two_factor_forgot_title'));

View File

@ -130,7 +130,7 @@ class BillController extends Controller
/** @var Carbon $start */ /** @var Carbon $start */
$start = session('start'); $start = session('start');
/** @var Carbon $end */ /** @var Carbon $end */
$end = session('end'); $end = session('end');
$bills = $repository->getBills(); $bills = $repository->getBills();
$bills->each( $bills->each(

View File

@ -12,7 +12,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Controllers; namespace FireflyIII\Http\Controllers;
use Amount; use Amount;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
use Config; use Config;
use FireflyIII\Crud\Account\AccountCrudInterface; use FireflyIII\Crud\Account\AccountCrudInterface;
@ -252,7 +251,8 @@ class BudgetController extends Controller
$count = $journals->count(); $count = $journals->count();
$journals = $journals->slice($offset, $pageSize); $journals = $journals->slice($offset, $pageSize);
$list = new LengthAwarePaginator($journals, $count, $pageSize); $list = new LengthAwarePaginator($journals, $count, $pageSize);
$subTitle = trans('firefly.without_budget_between', $subTitle = trans(
'firefly.without_budget_between',
['start' => $start->formatLocalized($this->monthAndDayFormat), 'end' => $end->formatLocalized($this->monthAndDayFormat)] ['start' => $start->formatLocalized($this->monthAndDayFormat), 'end' => $end->formatLocalized($this->monthAndDayFormat)]
); );
$list->setPath('/budgets/list/noBudget'); $list->setPath('/budgets/list/noBudget');
@ -358,7 +358,7 @@ class BudgetController extends Controller
{ {
$budgetData = [ $budgetData = [
'name' => $request->input('name'), 'name' => $request->input('name'),
'user' => Auth::user()->id, 'user' => auth()->user()->id,
]; ];
$budget = $repository->store($budgetData); $budget = $repository->store($budgetData);

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Controllers; namespace FireflyIII\Http\Controllers;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Crud\Account\AccountCrudInterface; use FireflyIII\Crud\Account\AccountCrudInterface;
use FireflyIII\Http\Requests\CategoryFormRequest; use FireflyIII\Http\Requests\CategoryFormRequest;
@ -166,9 +165,9 @@ class CategoryController extends Controller
*/ */
public function show(CRI $repository, AccountCrudInterface $crud, Category $category) public function show(CRI $repository, AccountCrudInterface $crud, Category $category)
{ {
$range = Preferences::get('viewRange', '1M')->data; $range = Preferences::get('viewRange', '1M')->data;
/** @var Carbon $start */ /** @var Carbon $start */
$start = session('start', Navigation::startOfPeriod(new Carbon, $range)); $start = session('start', Navigation::startOfPeriod(new Carbon, $range));
/** @var Carbon $end */ /** @var Carbon $end */
$end = session('end', Navigation::endOfPeriod(new Carbon, $range)); $end = session('end', Navigation::endOfPeriod(new Carbon, $range));
$hideCategory = true; // used in list. $hideCategory = true; // used in list.
@ -184,7 +183,7 @@ class CategoryController extends Controller
$journals->setPath('categories/show/' . $category->id); $journals->setPath('categories/show/' . $category->id);
// oldest transaction in category: // oldest transaction in category:
$start = $repository->firstUseDate($category, new Collection); $start = $repository->firstUseDate($category);
if ($start->year == 1900) { if ($start->year == 1900) {
$start = new Carbon; $start = new Carbon;
} }
@ -265,7 +264,7 @@ class CategoryController extends Controller
{ {
$categoryData = [ $categoryData = [
'name' => $request->input('name'), 'name' => $request->input('name'),
'user' => Auth::user()->id, 'user' => auth()->user()->id,
]; ];
$category = $repository->store($categoryData); $category = $repository->store($categoryData);

View File

@ -20,6 +20,7 @@ use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Support\CacheProperties; use FireflyIII\Support\CacheProperties;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Log;
use Navigation; use Navigation;
use Preferences; use Preferences;
use Response; use Response;
@ -35,19 +36,14 @@ class BudgetController extends Controller
/** @var BudgetChartGeneratorInterface */ /** @var BudgetChartGeneratorInterface */
protected $generator; protected $generator;
/** @var BudgetRepositoryInterface */
protected $repository;
/** /**
* * BudgetController constructor.
*/ */
public function __construct() public function __construct()
{ {
parent::__construct(); parent::__construct();
// create chart generator: // create chart generator:
$this->generator = app(BudgetChartGeneratorInterface::class); $this->generator = app(BudgetChartGeneratorInterface::class);
$this->repository = app(BudgetRepositoryInterface::class);
} }
/** /**
@ -143,8 +139,9 @@ class BudgetController extends Controller
* *
* @return \Symfony\Component\HttpFoundation\Response * @return \Symfony\Component\HttpFoundation\Response
*/ */
public function frontpage() public function frontpage(BudgetRepositoryInterface $repository)
{ {
Log::debug('Hello');
$start = session('start', Carbon::now()->startOfMonth()); $start = session('start', Carbon::now()->startOfMonth());
$end = session('end', Carbon::now()->endOfMonth()); $end = session('end', Carbon::now()->endOfMonth());
// chart properties for cache: // chart properties for cache:
@ -156,8 +153,8 @@ class BudgetController extends Controller
if ($cache->has()) { if ($cache->has()) {
return Response::json($cache->get()); return Response::json($cache->get());
} }
$budgets = $this->repository->getActiveBudgets(); $budgets = $repository->getActiveBudgets();
$repetitions = $this->repository->getAllBudgetLimitRepetitions($start, $end); $repetitions = $repository->getAllBudgetLimitRepetitions($start, $end);
$allEntries = new Collection; $allEntries = new Collection;
/** @var Budget $budget */ /** @var Budget $budget */
@ -166,15 +163,15 @@ class BudgetController extends Controller
$reps = $this->filterRepetitions($repetitions, $budget, $start, $end); $reps = $this->filterRepetitions($repetitions, $budget, $start, $end);
if ($reps->count() === 0) { if ($reps->count() === 0) {
$collection = $this->spentInPeriodSingle($budget, $start, $end); $collection = $this->spentInPeriodSingle($repository, $budget, $start, $end);
$allEntries = $allEntries->merge($collection); $allEntries = $allEntries->merge($collection);
continue; continue;
} }
$collection = $this->spentInPeriodMulti($budget, $reps); $collection = $this->spentInPeriodMulti($repository, $budget, $reps);
$allEntries = $allEntries->merge($collection); $allEntries = $allEntries->merge($collection);
} }
$entry = $this->spentInPeriodWithout($start, $end); $entry = $this->spentInPeriodWithout($repository, $start, $end);
$allEntries->push($entry); $allEntries->push($entry);
$data = $this->generator->frontpage($allEntries); $data = $this->generator->frontpage($allEntries);
$cache->store($data); $cache->store($data);
@ -216,6 +213,7 @@ class BudgetController extends Controller
if (in_array(strval($repetition->budget_id), $budgetIds)) { if (in_array(strval($repetition->budget_id), $budgetIds)) {
return true; return true;
} }
return false; return false;
} }
); );
@ -292,6 +290,7 @@ class BudgetController extends Controller
if ($repetition->budget_id === $budget->id && $repetition->startdate == $currentStart) { if ($repetition->budget_id === $budget->id && $repetition->startdate == $currentStart) {
return true; return true;
} }
return false; return false;
} }
); );
@ -329,28 +328,31 @@ class BudgetController extends Controller
if ($repetition->startdate < $end && $repetition->enddate > $start && $repetition->budget_id === $budget->id) { if ($repetition->startdate < $end && $repetition->enddate > $start && $repetition->budget_id === $budget->id) {
return true; return true;
} }
return false; return false;
} }
); );
} }
/** /**
* @param Budget $budget * @param BudgetRepositoryInterface $repository
* @param Collection $repetitions * @param Budget $budget
* @param Collection $repetitions
* *
* @return Collection * @return Collection
*/ */
private function spentInPeriodMulti(Budget $budget, Collection $repetitions): Collection private function spentInPeriodMulti(BudgetRepositoryInterface $repository, Budget $budget, Collection $repetitions): Collection
{ {
$format = strval(trans('config.month_and_day')); $format = strval(trans('config.month_and_day'));
$collection = new Collection; $collection = new Collection;
$name = $budget->name; $name = $budget->name;
/** @var LimitRepetition $repetition */ /** @var LimitRepetition $repetition */
foreach ($repetitions as $repetition) { foreach ($repetitions as $repetition) {
$expenses = $this->repository->spentInPeriod(new Collection([$budget]), new Collection, $repetition->startdate, $repetition->enddate); $expenses = $repository->spentInPeriod(new Collection([$budget]), new Collection, $repetition->startdate, $repetition->enddate);
if ($repetitions->count() > 1) { if ($repetitions->count() > 1) {
$name = $budget->name . ' ' . trans('firefly.between_dates', $name = $budget->name . ' ' . trans(
'firefly.between_dates',
['start' => $repetition->startdate->formatLocalized($format), 'end' => $repetition->enddate->formatLocalized($format)] ['start' => $repetition->startdate->formatLocalized($format), 'end' => $repetition->enddate->formatLocalized($format)]
); );
} }
@ -366,18 +368,19 @@ class BudgetController extends Controller
} }
/** /**
* @param Budget $budget * @param BudgetRepositoryInterface $repository
* @param Carbon $start * @param Budget $budget
* @param Carbon $end * @param Carbon $start
* @param Carbon $end
* *
* @return Collection * @return Collection
*/ */
private function spentInPeriodSingle(Budget $budget, Carbon $start, Carbon $end): Collection private function spentInPeriodSingle(BudgetRepositoryInterface $repository, Budget $budget, Carbon $start, Carbon $end): Collection
{ {
$collection = new Collection; $collection = new Collection;
$amount = '0'; $amount = '0';
$left = '0'; $left = '0';
$spent = $this->repository->spentInPeriod(new Collection([$budget]), new Collection, $start, $end); $spent = $repository->spentInPeriod(new Collection([$budget]), new Collection, $start, $end);
$overspent = '0'; $overspent = '0';
$array = [$budget->name, $left, $spent, $overspent, $amount, $spent]; $array = [$budget->name, $left, $spent, $overspent, $amount, $spent];
$collection->push($array); $collection->push($array);
@ -386,14 +389,15 @@ class BudgetController extends Controller
} }
/** /**
* @param Carbon $start * @param BudgetRepositoryInterface $repository
* @param Carbon $end * @param Carbon $start
* @param Carbon $end
* *
* @return array * @return array
*/ */
private function spentInPeriodWithout(Carbon $start, Carbon $end):array private function spentInPeriodWithout(BudgetRepositoryInterface $repository, Carbon $start, Carbon $end):array
{ {
$list = $this->repository->journalsInPeriodWithoutBudget(new Collection, $start, $end); $list = $repository->journalsInPeriodWithoutBudget(new Collection, $start, $end);
$sum = '0'; $sum = '0';
/** @var TransactionJournal $entry */ /** @var TransactionJournal $entry */
foreach ($list as $entry) { foreach ($list as $entry) {

View File

@ -58,7 +58,7 @@ class CategoryController extends Controller
*/ */
public function all(CRI $repository, AccountCrudInterface $crud, Category $category) public function all(CRI $repository, AccountCrudInterface $crud, Category $category)
{ {
$start = $repository->firstUseDate($category, new Collection); $start = $repository->firstUseDate($category);
$range = Preferences::get('viewRange', '1M')->data; $range = Preferences::get('viewRange', '1M')->data;
$start = Navigation::startOfPeriod($start, $range); $start = Navigation::startOfPeriod($start, $range);
$categoryCollection = new Collection([$category]); $categoryCollection = new Collection([$category]);
@ -108,13 +108,12 @@ class CategoryController extends Controller
} }
/** /**
* Show this month's category overview. * @param CRI $repository
* @param AccountCrudInterface $crud
* *
* @param CRI $repository * @return \Illuminate\Http\JsonResponse
*
* @return \Symfony\Component\HttpFoundation\Response
*/ */
public function frontpage(CRI $repository) public function frontpage(CRI $repository, AccountCrudInterface $crud)
{ {
$start = session('start', Carbon::now()->startOfMonth()); $start = session('start', Carbon::now()->startOfMonth());
$end = session('end', Carbon::now()->endOfMonth()); $end = session('end', Carbon::now()->endOfMonth());
@ -128,10 +127,11 @@ class CategoryController extends Controller
return Response::json($cache->get()); return Response::json($cache->get());
} }
$categories = $repository->getCategories(); $categories = $repository->getCategories();
$accounts = $crud->getAccountsByType([AccountType::ASSET, AccountType::DEFAULT]);
$set = new Collection; $set = new Collection;
/** @var Category $category */ /** @var Category $category */
foreach ($categories as $category) { foreach ($categories as $category) {
$spent = $repository->spentInPeriod(new Collection([$category]), new Collection, $start, $end); $spent = $repository->spentInPeriod(new Collection([$category]), $accounts, $start, $end);
if (bccomp($spent, '0') === -1) { if (bccomp($spent, '0') === -1) {
$category->spent = $spent; $category->spent = $spent;
$set->push($category); $set->push($category);

38
app/Http/Controllers/Controller.php Normal file → Executable file
View File

@ -11,15 +11,11 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Controllers; namespace FireflyIII\Http\Controllers;
use App;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController; use Illuminate\Routing\Controller as BaseController;
use NumberFormatter;
use Preferences;
use View; use View;
/** /**
@ -48,36 +44,11 @@ class Controller extends BaseController
View::share('hideBills', false); View::share('hideBills', false);
View::share('hideTags', false); View::share('hideTags', false);
if (Auth::check()) { // save some formats:
$pref = Preferences::get('language', env('DEFAULT_LANGUAGE', 'en_US')); $this->monthFormat = (string)trans('config.month');
$lang = $pref->data; $this->monthAndDayFormat = (string)trans('config.month_and_day');
$this->dateTimeFormat = (string)trans('config.date_time');
App::setLocale($lang);
Carbon::setLocale(substr($lang, 0, 2));
$locale = explode(',', trans('config.locale'));
$locale = array_map('trim', $locale);
setlocale(LC_TIME, $locale);
setlocale(LC_MONETARY, $locale);
// save some formats:
$this->monthFormat = (string)trans('config.month');
$this->monthAndDayFormat = (string)trans('config.month_and_day');
$this->dateTimeFormat = (string)trans('config.date_time');
// change localeconv to a new array:
$numberFormatter = numfmt_create($lang, NumberFormatter::CURRENCY);
$localeconv = [
'mon_decimal_point' => $numberFormatter->getSymbol($numberFormatter->getAttribute(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL)),
'mon_thousands_sep' => $numberFormatter->getSymbol($numberFormatter->getAttribute(NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL)),
'frac_digits' => $numberFormatter->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS),
];
View::share('monthFormat', $this->monthFormat);
View::share('monthAndDayFormat', $this->monthAndDayFormat);
View::share('dateTimeFormat', $this->dateTimeFormat);
View::share('language', $lang);
View::share('localeconv', $localeconv);
}
} }
/** /**
@ -107,5 +78,4 @@ class Controller extends BaseController
return $sum; return $sum;
} }
} }

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Controllers; namespace FireflyIII\Http\Controllers;
use Auth;
use Cache; use Cache;
use FireflyIII\Http\Requests\CurrencyFormRequest; use FireflyIII\Http\Requests\CurrencyFormRequest;
use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionCurrency;
@ -81,7 +80,7 @@ class CurrencyController extends Controller
} }
/** /**
* @param TransactionCurrency $currency * @param TransactionCurrency $currency
* *
* @return \Illuminate\Http\RedirectResponse|View * @return \Illuminate\Http\RedirectResponse|View
*/ */
@ -105,7 +104,7 @@ class CurrencyController extends Controller
} }
/** /**
* @param TransactionCurrency $currency * @param TransactionCurrency $currency
* *
* @return \Illuminate\Http\RedirectResponse * @return \Illuminate\Http\RedirectResponse
* @throws \Exception * @throws \Exception
@ -119,7 +118,7 @@ class CurrencyController extends Controller
} }
Session::flash('success', trans('firefly.deleted_currency', ['name' => $currency->name])); Session::flash('success', trans('firefly.deleted_currency', ['name' => $currency->name]));
if (Auth::user()->hasRole('owner')) { if (auth()->user()->hasRole('owner')) {
$currency->delete(); $currency->delete();
} }
@ -157,10 +156,10 @@ class CurrencyController extends Controller
public function index(CurrencyRepositoryInterface $repository) public function index(CurrencyRepositoryInterface $repository)
{ {
$currencies = $repository->get(); $currencies = $repository->get();
$defaultCurrency = $repository->getCurrencyByPreference(Preferences::get('currencyPreference', env('DEFAULT_CURRENCY', 'EUR'))); $defaultCurrency = $repository->getCurrencyByPreference(Preferences::get('currencyPreference', config('firefly.default_currency', 'EUR')));
if (!Auth::user()->hasRole('owner')) { if (!auth()->user()->hasRole('owner')) {
Session::flash('warning', trans('firefly.ask_site_owner', ['owner' => env('SITE_OWNER')])); Session::flash('warning', trans('firefly.ask_site_owner', ['owner' => env('SITE_OWNER')]));
} }
@ -177,8 +176,8 @@ class CurrencyController extends Controller
*/ */
public function store(CurrencyFormRequest $request, CurrencyRepositoryInterface $repository) public function store(CurrencyFormRequest $request, CurrencyRepositoryInterface $repository)
{ {
if (!Auth::user()->hasRole('owner')) { if (!auth()->user()->hasRole('owner')) {
Log::error('User ' . Auth::user()->id . ' is not admin, but tried to store a currency.'); Log::error('User ' . auth()->user()->id . ' is not admin, but tried to store a currency.');
return redirect(session('currency.create.url')); return redirect(session('currency.create.url'));
} }
@ -209,7 +208,7 @@ class CurrencyController extends Controller
public function update(CurrencyFormRequest $request, CurrencyRepositoryInterface $repository, TransactionCurrency $currency) public function update(CurrencyFormRequest $request, CurrencyRepositoryInterface $repository, TransactionCurrency $currency)
{ {
$data = $request->getCurrencyData(); $data = $request->getCurrencyData();
if (Auth::user()->hasRole('owner')) { if (auth()->user()->hasRole('owner')) {
$currency = $repository->update($currency, $data); $currency = $repository->update($currency, $data);
} }
Session::flash('success', trans('firefly.updated_currency', ['name' => $currency->name])); Session::flash('success', trans('firefly.updated_currency', ['name' => $currency->name]));
@ -247,13 +246,13 @@ class CurrencyController extends Controller
} }
// is the default currency for the user or the system // is the default currency for the user or the system
$defaultCode = Preferences::get('currencyPreference', env('DEFAULT_CURRENCY', 'EUR'))->data; $defaultCode = Preferences::get('currencyPreference', config('firefly.default_currency', 'EUR'))->data;
if ($currency->code === $defaultCode) { if ($currency->code === $defaultCode) {
return false; return false;
} }
// is the default currency for the system // is the default currency for the system
$defaultSystemCode = env('DEFAULT_CURRENCY', 'EUR'); $defaultSystemCode = config('firefly.default_currency', 'EUR');
if ($currency->code === $defaultSystemCode) { if ($currency->code === $defaultSystemCode) {
return false; return false;
} }

View File

@ -39,7 +39,7 @@ class HelpController extends Controller
*/ */
public function show(HelpInterface $help, string $route) public function show(HelpInterface $help, string $route)
{ {
$language = Preferences::get('language', env('DEFAULT_LANGUAGE', 'en_US'))->data; $language = Preferences::get('language', config('firefly.default_language', 'en_US'))->data;
$content = [ $content = [
'text' => '<p>' . strval(trans('firefly.route_has_no_help')) . '</p>', 'text' => '<p>' . strval(trans('firefly.route_has_no_help')) . '</p>',
'title' => 'Help', 'title' => 'Help',

View File

@ -222,4 +222,5 @@ class HomeController extends Controller
return false; return false;
} }
} }

View File

@ -6,6 +6,7 @@
* This software may be modified and distributed under the terms * This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details. * of the MIT license. See the LICENSE file for details.
*/ */
declare(strict_types = 1);
namespace FireflyIII\Http\Controllers; namespace FireflyIII\Http\Controllers;
@ -306,7 +307,7 @@ class ImportController extends Controller
public function start(ImportJob $job) public function start(ImportJob $job)
{ {
set_time_limit(0); set_time_limit(0);
if ($job->status == "settings_complete") { if ($job->status == 'settings_complete') {
ImportProcedure::runImport($job); ImportProcedure::runImport($job);
} }
} }
@ -415,16 +416,25 @@ class ImportController extends Controller
* @param ImportJob $job * @param ImportJob $job
* *
* @return SetupInterface * @return SetupInterface
* @throws FireflyException
*/ */
private function makeImporter(ImportJob $job): SetupInterface private function makeImporter(ImportJob $job): SetupInterface
{ {
// create proper importer (depends on job) // create proper importer (depends on job)
$type = $job->file_type; $type = strtolower($job->file_type);
/** @var SetupInterface $importer */
$importer = app('FireflyIII\Import\Setup\\' . ucfirst($type) . 'Setup');
$importer->setJob($job);
return $importer; // validate type:
$validTypes = array_keys(config('firefly.import_formats'));
if (in_array($type, $validTypes)) {
/** @var SetupInterface $importer */
$importer = app('FireflyIII\Import\Setup\\' . ucfirst($type) . 'Setup');
$importer->setJob($job);
return $importer;
}
throw new FireflyException(sprintf('"%s" is not a valid file type', $type));
} }
@ -450,8 +460,7 @@ class ImportController extends Controller
Log::debug('Will redirect to complete()'); Log::debug('Will redirect to complete()');
return redirect(route('import.complete', [$job->key])); return redirect(route('import.complete', [$job->key]));
case case 'import_complete':
'import_complete':
Log::debug('Will redirect to finished()'); Log::debug('Will redirect to finished()');
return redirect(route('import.finished', [$job->key])); return redirect(route('import.finished', [$job->key]));

View File

@ -10,7 +10,6 @@
declare(strict_types = 1); declare(strict_types = 1);
namespace FireflyIII\Http\Controllers; namespace FireflyIII\Http\Controllers;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Crud\Account\AccountCrudInterface; use FireflyIII\Crud\Account\AccountCrudInterface;
use FireflyIII\Http\Requests\NewUserFormRequest; use FireflyIII\Http\Requests\NewUserFormRequest;
@ -107,7 +106,7 @@ class NewUserController extends Controller
'accountType' => 'asset', 'accountType' => 'asset',
'virtualBalance' => 0, 'virtualBalance' => 0,
'active' => true, 'active' => true,
'user' => Auth::user()->id, 'user' => auth()->user()->id,
'accountRole' => 'defaultAsset', 'accountRole' => 'defaultAsset',
'openingBalance' => round($request->input('bank_balance'), 2), 'openingBalance' => round($request->input('bank_balance'), 2),
'openingBalanceDate' => new Carbon, 'openingBalanceDate' => new Carbon,
@ -133,7 +132,7 @@ class NewUserController extends Controller
'accountType' => 'asset', 'accountType' => 'asset',
'virtualBalance' => 0, 'virtualBalance' => 0,
'active' => true, 'active' => true,
'user' => Auth::user()->id, 'user' => auth()->user()->id,
'accountRole' => 'savingAsset', 'accountRole' => 'savingAsset',
'openingBalance' => round($request->input('savings_balance'), 2), 'openingBalance' => round($request->input('savings_balance'), 2),
'openingBalanceDate' => new Carbon, 'openingBalanceDate' => new Carbon,
@ -158,7 +157,7 @@ class NewUserController extends Controller
'accountType' => 'asset', 'accountType' => 'asset',
'virtualBalance' => round($request->get('credit_card_limit'), 2), 'virtualBalance' => round($request->get('credit_card_limit'), 2),
'active' => true, 'active' => true,
'user' => Auth::user()->id, 'user' => auth()->user()->id,
'accountRole' => 'ccAsset', 'accountRole' => 'ccAsset',
'openingBalance' => null, 'openingBalance' => null,
'openingBalanceDate' => null, 'openingBalanceDate' => null,

View File

@ -253,7 +253,7 @@ class PiggyBankController extends Controller
*/ */
public function postAdd(PiggyBankRepositoryInterface $repository, ARI $accounts, PiggyBank $piggyBank) public function postAdd(PiggyBankRepositoryInterface $repository, ARI $accounts, PiggyBank $piggyBank)
{ {
$amount = strval(round(Input::get('amount'), 2)); $amount = strval(round(Input::get('amount'), 2));
/** @var Carbon $date */ /** @var Carbon $date */
$date = session('end', Carbon::now()->endOfMonth()); $date = session('end', Carbon::now()->endOfMonth());
$leftOnAccount = $accounts->leftOnAccount($piggyBank->account, $date); $leftOnAccount = $accounts->leftOnAccount($piggyBank->account, $date);

View File

@ -13,6 +13,7 @@ namespace FireflyIII\Http\Controllers\Popup;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Crud\Account\AccountCrudInterface;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Helpers\Collection\BalanceLine; use FireflyIII\Helpers\Collection\BalanceLine;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
@ -112,6 +113,7 @@ class ReportController extends Controller
if ($tags === 0) { if ($tags === 0) {
return true; return true;
} }
return false; return false;
} }
); );
@ -183,7 +185,7 @@ class ReportController extends Controller
{ {
/** @var AccountRepositoryInterface $repository */ /** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class); $repository = app(AccountRepositoryInterface::class);
$crud = app('FireflyIII\Crud\Account\AccountCrudInterface'); $crud = app(AccountCrudInterface::class);
$account = $crud->find(intval($attributes['accountId'])); $account = $crud->find(intval($attributes['accountId']));
$types = [TransactionType::WITHDRAWAL, TransactionType::TRANSFER]; $types = [TransactionType::WITHDRAWAL, TransactionType::TRANSFER];
$journals = $repository->journalsInPeriod($attributes['accounts'], $types, $attributes['startDate'], $attributes['endDate']); $journals = $repository->journalsInPeriod($attributes['accounts'], $types, $attributes['startDate'], $attributes['endDate']);
@ -191,9 +193,11 @@ class ReportController extends Controller
// filter for transfers and withdrawals TO the given $account // filter for transfers and withdrawals TO the given $account
$journals = $journals->filter( $journals = $journals->filter(
function (TransactionJournal $journal) use ($account) { function (TransactionJournal $journal) use ($account) {
if ($journal->destination_account_id === $account->id) { $destinations = TransactionJournal::destinationAccountList($journal)->pluck('id')->toArray();
if (in_array($account->id, $destinations)) {
return true; return true;
} }
return false; return false;
} }
); );
@ -221,14 +225,18 @@ class ReportController extends Controller
$journals = $repository->journalsInPeriod(new Collection([$account]), $types, $attributes['startDate'], $attributes['endDate']); $journals = $repository->journalsInPeriod(new Collection([$account]), $types, $attributes['startDate'], $attributes['endDate']);
$destinations = $attributes['accounts']->pluck('id')->toArray(); $destinations = $attributes['accounts']->pluck('id')->toArray();
// filter for transfers and withdrawals FROM the given $account // filter for transfers and withdrawals FROM the given $account
$journals = $journals->filter( $journals = $journals->filter(
function (TransactionJournal $journal) use ($account, $destinations) { function (TransactionJournal $journal) use ($account, $destinations) {
$currentSources = TransactionJournal::sourceAccountList($journal)->pluck('id')->toArray();
$currentDest = TransactionJournal::destinationAccountList($journal)->pluck('id')->toArray();
if ( if (
$journal->source_account_id === $account->id !empty(array_intersect([$account->id], $currentSources))
&& in_array($journal->destination_account_id, $destinations) && !empty(array_intersect($destinations, $currentDest))
) { ) {
return true; return true;
} }
return false; return false;
} }
); );

View File

@ -10,7 +10,6 @@
declare(strict_types = 1); declare(strict_types = 1);
namespace FireflyIII\Http\Controllers; namespace FireflyIII\Http\Controllers;
use Auth;
use FireflyIII\Crud\Account\AccountCrudInterface; use FireflyIII\Crud\Account\AccountCrudInterface;
use FireflyIII\Http\Requests\TokenFormRequest; use FireflyIII\Http\Requests\TokenFormRequest;
use FireflyIII\Models\AccountType; use FireflyIII\Models\AccountType;
@ -47,7 +46,7 @@ class PreferencesController extends Controller
{ {
$domain = $this->getDomain(); $domain = $this->getDomain();
/** @noinspection PhpMethodParametersCountMismatchInspection */ /** @noinspection PhpMethodParametersCountMismatchInspection */
$secret = $google2fa->generateSecretKey(16, Auth::user()->id); $secret = $google2fa->generateSecretKey(16, auth()->user()->id);
Session::flash('two-factor-secret', $secret); Session::flash('two-factor-secret', $secret);
$image = $google2fa->getQRCodeInline('Firefly III at ' . $domain, null, $secret, 150); $image = $google2fa->getQRCodeInline('Firefly III at ' . $domain, null, $secret, 150);
@ -79,7 +78,7 @@ class PreferencesController extends Controller
$viewRangePref = Preferences::get('viewRange', '1M'); $viewRangePref = Preferences::get('viewRange', '1M');
$viewRange = $viewRangePref->data; $viewRange = $viewRangePref->data;
$frontPageAccounts = Preferences::get('frontPageAccounts', []); $frontPageAccounts = Preferences::get('frontPageAccounts', []);
$language = Preferences::get('language', env('DEFAULT_LANGUAGE', 'en_US'))->data; $language = Preferences::get('language', config('firefly.default_language', 'en_US'))->data;
$transactionPageSize = Preferences::get('transactionPageSize', 50)->data; $transactionPageSize = Preferences::get('transactionPageSize', 50)->data;
$customFiscalYear = Preferences::get('customFiscalYear', 0)->data; $customFiscalYear = Preferences::get('customFiscalYear', 0)->data;
$fiscalYearStartStr = Preferences::get('fiscalYearStart', '01-01')->data; $fiscalYearStartStr = Preferences::get('fiscalYearStart', '01-01')->data;

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Controllers; namespace FireflyIII\Http\Controllers;
use Auth;
use FireflyIII\Events\UserIsDeleted; use FireflyIII\Events\UserIsDeleted;
use FireflyIII\Http\Requests\DeleteAccountFormRequest; use FireflyIII\Http\Requests\DeleteAccountFormRequest;
use FireflyIII\Http\Requests\ProfileFormRequest; use FireflyIII\Http\Requests\ProfileFormRequest;
@ -41,7 +40,7 @@ class ProfileController extends Controller
*/ */
public function changePassword() public function changePassword()
{ {
return view('profile.change-password')->with('title', Auth::user()->email)->with('subTitle', trans('firefly.change_your_password'))->with( return view('profile.change-password')->with('title', auth()->user()->email)->with('subTitle', trans('firefly.change_your_password'))->with(
'mainTitleIcon', 'fa-user' 'mainTitleIcon', 'fa-user'
); );
} }
@ -51,7 +50,7 @@ class ProfileController extends Controller
*/ */
public function deleteAccount() public function deleteAccount()
{ {
return view('profile.delete-account')->with('title', Auth::user()->email)->with('subTitle', trans('firefly.delete_account'))->with( return view('profile.delete-account')->with('title', auth()->user()->email)->with('subTitle', trans('firefly.delete_account'))->with(
'mainTitleIcon', 'fa-user' 'mainTitleIcon', 'fa-user'
); );
} }
@ -62,7 +61,7 @@ class ProfileController extends Controller
*/ */
public function index() public function index()
{ {
return view('profile.index')->with('title', trans('firefly.profile'))->with('subTitle', Auth::user()->email)->with('mainTitleIcon', 'fa-user'); return view('profile.index')->with('title', trans('firefly.profile'))->with('subTitle', auth()->user()->email)->with('mainTitleIcon', 'fa-user');
} }
/** /**
@ -73,7 +72,7 @@ class ProfileController extends Controller
public function postChangePassword(ProfileFormRequest $request) public function postChangePassword(ProfileFormRequest $request)
{ {
// old, new1, new2 // old, new1, new2
if (!Hash::check($request->get('current_password'), Auth::user()->password)) { if (!Hash::check($request->get('current_password'), auth()->user()->password)) {
Session::flash('error', strval(trans('firefly.invalid_current_password'))); Session::flash('error', strval(trans('firefly.invalid_current_password')));
return redirect(route('profile.change-password')); return redirect(route('profile.change-password'));
@ -86,8 +85,8 @@ class ProfileController extends Controller
} }
// update the user with the new password. // update the user with the new password.
Auth::user()->password = bcrypt($request->get('new_password')); auth()->user()->password = bcrypt($request->get('new_password'));
Auth::user()->save(); auth()->user()->save();
Session::flash('success', strval(trans('firefly.password_changed'))); Session::flash('success', strval(trans('firefly.password_changed')));
@ -103,22 +102,22 @@ class ProfileController extends Controller
public function postDeleteAccount(DeleteAccountFormRequest $request) public function postDeleteAccount(DeleteAccountFormRequest $request)
{ {
// old, new1, new2 // old, new1, new2
if (!Hash::check($request->get('password'), Auth::user()->password)) { if (!Hash::check($request->get('password'), auth()->user()->password)) {
Session::flash('error', strval(trans('firefly.invalid_password'))); Session::flash('error', strval(trans('firefly.invalid_password')));
return redirect(route('profile.delete-account')); return redirect(route('profile.delete-account'));
} }
// respond to deletion: // respond to deletion:
event(new UserIsDeleted(Auth::user(), $request->ip())); event(new UserIsDeleted(auth()->user(), $request->ip()));
// store some stuff for the future: // store some stuff for the future:
$registration = Preferences::get('registration_ip_address')->data; $registration = Preferences::get('registration_ip_address')->data;
$confirmation = Preferences::get('confirmation_ip_address')->data; $confirmation = Preferences::get('confirmation_ip_address')->data;
// DELETE! // DELETE!
$email = Auth::user()->email; $email = auth()->user()->email;
Auth::user()->delete(); auth()->user()->delete();
Session::flush(); Session::flush();
Session::flash('gaEventCategory', 'user'); Session::flash('gaEventCategory', 'user');
Session::flash('gaEventAction', 'delete-account'); Session::flash('gaEventAction', 'delete-account');

View File

@ -50,18 +50,11 @@ class ReportController extends Controller
/** /**
* *
*
* @param ReportHelperInterface $helper
*/ */
public function __construct(ReportHelperInterface $helper) public function __construct()
{ {
parent::__construct(); parent::__construct();
$this->helper = $helper;
$this->accountHelper = app(AccountReportHelperInterface::class);
$this->budgetHelper = app(BudgetReportHelperInterface::class);
$this->balanceHelper = app(BalanceReportHelperInterface::class);
View::share('title', trans('firefly.reports')); View::share('title', trans('firefly.reports'));
View::share('mainTitleIcon', 'fa-line-chart'); View::share('mainTitleIcon', 'fa-line-chart');
@ -74,6 +67,7 @@ class ReportController extends Controller
*/ */
public function index(AccountCrudInterface $crud) public function index(AccountCrudInterface $crud)
{ {
$this->createRepositories();
/** @var Carbon $start */ /** @var Carbon $start */
$start = clone session('first'); $start = clone session('first');
$months = $this->helper->listOfMonths($start); $months = $this->helper->listOfMonths($start);
@ -104,6 +98,7 @@ class ReportController extends Controller
*/ */
public function report(string $reportType, Carbon $start, Carbon $end, Collection $accounts) public function report(string $reportType, Carbon $start, Carbon $end, Collection $accounts)
{ {
$this->createRepositories();
// throw an error if necessary. // throw an error if necessary.
if ($end < $start) { if ($end < $start) {
throw new FireflyException('End date cannot be before start date, silly!'); throw new FireflyException('End date cannot be before start date, silly!');
@ -192,8 +187,9 @@ class ReportController extends Controller
$transactionAmount = $journal->source_amount; $transactionAmount = $journal->source_amount;
// get currently relevant transaction: // get currently relevant transaction:
if (intval($journal->destination_account_id) === $account->id) { $destinations = TransactionJournal::destinationAccountList($journal)->pluck('id')->toArray();
$transactionAmount = $journal->destination_amount; if (in_array($account->id, $destinations)) {
$transactionAmount = TransactionJournal::amountPositive($journal);
} }
$newBalance = bcadd($startBalance, $transactionAmount); $newBalance = bcadd($startBalance, $transactionAmount);
$journal->after = $newBalance; $journal->after = $newBalance;
@ -216,7 +212,7 @@ class ReportController extends Controller
$accountIds = join(',', $accounts->pluck('id')->toArray()); $accountIds = join(',', $accounts->pluck('id')->toArray());
$hideable = ['buttons', 'icon', 'description', 'balance_before', 'amount', 'balance_after', 'date', $hideable = ['buttons', 'icon', 'description', 'balance_before', 'amount', 'balance_after', 'date',
'interest_date','book_date', 'process_date', 'interest_date', 'book_date', 'process_date',
// three new optional fields. // three new optional fields.
'due_date', 'payment_date', 'invoice_date', 'due_date', 'payment_date', 'invoice_date',
'from', 'to', 'budget', 'category', 'bill', 'from', 'to', 'budget', 'category', 'bill',
@ -230,6 +226,17 @@ class ReportController extends Controller
return view('reports.audit.report', compact('start', 'end', 'reportType', 'accountIds', 'accounts', 'auditData', 'hideable', 'defaultShow')); return view('reports.audit.report', compact('start', 'end', 'reportType', 'accountIds', 'accounts', 'auditData', 'hideable', 'defaultShow'));
} }
/**
*
*/
private function createRepositories()
{
$this->helper = app(ReportHelperInterface::class);
$this->accountHelper = app(AccountReportHelperInterface::class);
$this->budgetHelper = app(BudgetReportHelperInterface::class);
$this->balanceHelper = app(BalanceReportHelperInterface::class);
}
/** /**
* @param $reportType * @param $reportType
* @param Carbon $start * @param Carbon $start

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Controllers; namespace FireflyIII\Http\Controllers;
use Auth;
use FireflyIII\Http\Requests\RuleFormRequest; use FireflyIII\Http\Requests\RuleFormRequest;
use FireflyIII\Http\Requests\TestRuleFormRequest; use FireflyIII\Http\Requests\TestRuleFormRequest;
use FireflyIII\Models\Rule; use FireflyIII\Models\Rule;
@ -189,7 +188,7 @@ class RuleController extends Controller
{ {
$this->createDefaultRuleGroup(); $this->createDefaultRuleGroup();
$this->createDefaultRule(); $this->createDefaultRule();
$ruleGroups = $repository->getRuleGroupsWithRules(Auth::user()); $ruleGroups = $repository->getRuleGroupsWithRules(auth()->user());
return view('rules.index', compact('ruleGroups')); return view('rules.index', compact('ruleGroups'));
} }
@ -243,7 +242,7 @@ class RuleController extends Controller
$data = [ $data = [
'rule_group_id' => $ruleGroup->id, 'rule_group_id' => $ruleGroup->id,
'title' => $request->get('title'), 'title' => $request->get('title'),
'user_id' => Auth::user()->id, 'user_id' => auth()->user()->id,
'trigger' => $request->get('trigger'), 'trigger' => $request->get('trigger'),
'description' => $request->get('description'), 'description' => $request->get('description'),
'rule-triggers' => $request->get('rule-trigger'), 'rule-triggers' => $request->get('rule-trigger'),
@ -380,7 +379,7 @@ class RuleController extends Controller
$data = [ $data = [
'rule_group_id' => $repository->getFirstRuleGroup()->id, 'rule_group_id' => $repository->getFirstRuleGroup()->id,
'stop_processing' => 0, 'stop_processing' => 0,
'user_id' => Auth::user()->id, 'user_id' => auth()->user()->id,
'title' => trans('firefly.default_rule_name'), 'title' => trans('firefly.default_rule_name'),
'description' => trans('firefly.default_rule_description'), 'description' => trans('firefly.default_rule_description'),
'trigger' => 'store-journal', 'trigger' => 'store-journal',
@ -413,7 +412,7 @@ class RuleController extends Controller
if ($repository->count() === 0) { if ($repository->count() === 0) {
$data = [ $data = [
'user_id' => Auth::user()->id, 'user_id' => auth()->user()->id,
'title' => trans('firefly.default_rule_group_name'), 'title' => trans('firefly.default_rule_group_name'),
'description' => trans('firefly.default_rule_group_description'), 'description' => trans('firefly.default_rule_group_description'),
]; ];

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Controllers; namespace FireflyIII\Http\Controllers;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
use ExpandedForm; use ExpandedForm;
use FireflyIII\Crud\Account\AccountCrudInterface; use FireflyIII\Crud\Account\AccountCrudInterface;
@ -96,7 +95,7 @@ class RuleGroupController extends Controller
{ {
$title = $ruleGroup->title; $title = $ruleGroup->title;
$moveTo = Auth::user()->ruleGroups()->find(intval(Input::get('move_rules_before_delete'))); $moveTo = auth()->user()->ruleGroups()->find(intval(Input::get('move_rules_before_delete')));
$repository->destroy($ruleGroup, $moveTo); $repository->destroy($ruleGroup, $moveTo);
@ -163,7 +162,7 @@ class RuleGroupController extends Controller
$job = new ExecuteRuleGroupOnExistingTransactions($ruleGroup); $job = new ExecuteRuleGroupOnExistingTransactions($ruleGroup);
// Apply parameters to the job // Apply parameters to the job
$job->setUser(Auth::user()); $job->setUser(auth()->user());
$job->setAccounts($accounts); $job->setAccounts($accounts);
$job->setStartDate($startDate); $job->setStartDate($startDate);
$job->setEndDate($endDate); $job->setEndDate($endDate);
@ -207,7 +206,7 @@ class RuleGroupController extends Controller
$data = [ $data = [
'title' => $request->input('title'), 'title' => $request->input('title'),
'description' => $request->input('description'), 'description' => $request->input('description'),
'user_id' => Auth::user()->id, 'user_id' => auth()->user()->id,
]; ];
$ruleGroup = $repository->store($data); $ruleGroup = $repository->store($data);

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Controllers; namespace FireflyIII\Http\Controllers;
use Auth;
use FireflyIII\Http\Requests\TagFormRequest; use FireflyIII\Http\Requests\TagFormRequest;
use FireflyIII\Models\Preference; use FireflyIII\Models\Preference;
use FireflyIII\Models\Tag; use FireflyIII\Models\Tag;
@ -194,7 +193,7 @@ class TagController extends Controller
foreach ($types as $type) { foreach ($types as $type) {
/** @var Collection $tags */ /** @var Collection $tags */
$tags = Auth::user()->tags()->where('tagMode', $type)->orderBy('date', 'ASC')->get(); $tags = auth()->user()->tags()->where('tagMode', $type)->orderBy('date', 'ASC')->get();
$tags = $tags->sortBy( $tags = $tags->sortBy(
function (Tag $tag) { function (Tag $tag) {
$date = !is_null($tag->date) ? $tag->date->format('Ymd') : '000000'; $date = !is_null($tag->date) ? $tag->date->format('Ymd') : '000000';
@ -218,18 +217,17 @@ class TagController extends Controller
} }
/** /**
* @param Tag $tag * @param Tag $tag
* @param TagRepositoryInterface $repository
* *
* @return View * @return View
*/ */
public function show(Tag $tag) public function show(Tag $tag, TagRepositoryInterface $repository)
{ {
$subTitle = $tag->tag; $subTitle = $tag->tag;
$subTitleIcon = 'fa-tag'; $subTitleIcon = 'fa-tag';
/** @var Collection $journals */ $journals = $repository->getJournals($tag);
$journals = $tag->transactionJournals()->sortCorrectly()->expanded()->get(TransactionJournal::queryFields()); $sum = $journals->sum(
$sum = $journals->sum(
function (TransactionJournal $journal) { function (TransactionJournal $journal) {
return TransactionJournal::amount($journal); return TransactionJournal::amount($journal);
} }

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Controllers\Transaction; namespace FireflyIII\Http\Controllers\Transaction;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
use ExpandedForm; use ExpandedForm;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
@ -201,11 +200,11 @@ class MassController extends Controller
'what' => $what, 'what' => $what,
'description' => $request->get('description')[$journal->id], 'description' => $request->get('description')[$journal->id],
'source_account_id' => intval($sourceAccountId), 'source_account_id' => intval($sourceAccountId),
'source_account_name' => intval($destAccountId), 'source_account_name' => $sourceAccountName,
'destination_account_id' => $sourceAccountName, 'destination_account_id' => intval($destAccountId),
'destination_account_name' => $destAccountName, 'destination_account_name' => $destAccountName,
'amount' => round($request->get('amount')[$journal->id], 4), 'amount' => round($request->get('amount')[$journal->id], 4),
'user' => Auth::user()->id, 'user' => auth()->user()->id,
'amount_currency_id_amount' => intval($request->get('amount_currency_id_amount_' . $journal->id)), 'amount_currency_id_amount' => intval($request->get('amount_currency_id_amount_' . $journal->id)),
'date' => new Carbon($request->get('date')[$journal->id]), 'date' => new Carbon($request->get('date')[$journal->id]),
'interest_date' => $journal->interest_date, 'interest_date' => $journal->interest_date,

18
app/Http/Kernel.php Normal file → Executable file
View File

@ -6,7 +6,6 @@
* This software may be modified and distributed under the terms * This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details. * of the MIT license. See the LICENSE file for details.
*/ */
declare(strict_types = 1); declare(strict_types = 1);
namespace FireflyIII\Http; namespace FireflyIII\Http;
@ -23,9 +22,11 @@ use FireflyIII\Http\Middleware\RedirectIfAuthenticated;
use FireflyIII\Http\Middleware\RedirectIfTwoFactorAuthenticated; use FireflyIII\Http\Middleware\RedirectIfTwoFactorAuthenticated;
use FireflyIII\Http\Middleware\VerifyCsrfToken; use FireflyIII\Http\Middleware\VerifyCsrfToken;
use Illuminate\Auth\Middleware\AuthenticateWithBasicAuth; use Illuminate\Auth\Middleware\AuthenticateWithBasicAuth;
use Illuminate\Auth\Middleware\Authorize;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse; use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Foundation\Http\Kernel as HttpKernel; use Illuminate\Foundation\Http\Kernel as HttpKernel;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode; use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Routing\Middleware\ThrottleRequests; use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Session\Middleware\StartSession; use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession; use Illuminate\View\Middleware\ShareErrorsFromSession;
@ -37,10 +38,11 @@ use Illuminate\View\Middleware\ShareErrorsFromSession;
*/ */
class Kernel extends HttpKernel class Kernel extends HttpKernel
{ {
/** /**
* The bootstrap classes for the application. * The bootstrap classes for the application.
* *
* Next upgrade should verify these are all here. * Next upgrade verify these are the same.
* *
* @var array * @var array
*/ */
@ -83,6 +85,7 @@ class Kernel extends HttpKernel
StartSession::class, StartSession::class,
ShareErrorsFromSession::class, ShareErrorsFromSession::class,
VerifyCsrfToken::class, VerifyCsrfToken::class,
SubstituteBindings::class,
], ],
// MUST NOT be logged in. Does not care about 2FA or confirmation. // MUST NOT be logged in. Does not care about 2FA or confirmation.
'user-not-logged-in' => [ 'user-not-logged-in' => [
@ -91,9 +94,9 @@ class Kernel extends HttpKernel
StartSession::class, StartSession::class,
ShareErrorsFromSession::class, ShareErrorsFromSession::class,
VerifyCsrfToken::class, VerifyCsrfToken::class,
SubstituteBindings::class,
RedirectIfAuthenticated::class, RedirectIfAuthenticated::class,
], ],
// MUST be logged in. // MUST be logged in.
// MUST NOT have 2FA // MUST NOT have 2FA
// don't care about confirmation: // don't care about confirmation:
@ -103,6 +106,7 @@ class Kernel extends HttpKernel
StartSession::class, StartSession::class,
ShareErrorsFromSession::class, ShareErrorsFromSession::class,
VerifyCsrfToken::class, VerifyCsrfToken::class,
SubstituteBindings::class,
Authenticate::class, Authenticate::class,
RedirectIfTwoFactorAuthenticated::class, RedirectIfTwoFactorAuthenticated::class,
], ],
@ -115,6 +119,7 @@ class Kernel extends HttpKernel
StartSession::class, StartSession::class,
ShareErrorsFromSession::class, ShareErrorsFromSession::class,
VerifyCsrfToken::class, VerifyCsrfToken::class,
SubstituteBindings::class,
Authenticate::class, Authenticate::class,
AuthenticateTwoFactor::class, AuthenticateTwoFactor::class,
IsNotConfirmed::class, IsNotConfirmed::class,
@ -129,6 +134,7 @@ class Kernel extends HttpKernel
StartSession::class, StartSession::class,
ShareErrorsFromSession::class, ShareErrorsFromSession::class,
VerifyCsrfToken::class, VerifyCsrfToken::class,
SubstituteBindings::class,
Authenticate::class, Authenticate::class,
], ],
@ -142,6 +148,7 @@ class Kernel extends HttpKernel
StartSession::class, StartSession::class,
ShareErrorsFromSession::class, ShareErrorsFromSession::class,
VerifyCsrfToken::class, VerifyCsrfToken::class,
SubstituteBindings::class,
Authenticate::class, Authenticate::class,
AuthenticateTwoFactor::class, AuthenticateTwoFactor::class,
IsConfirmed::class, IsConfirmed::class,
@ -159,6 +166,7 @@ class Kernel extends HttpKernel
StartSession::class, StartSession::class,
ShareErrorsFromSession::class, ShareErrorsFromSession::class,
VerifyCsrfToken::class, VerifyCsrfToken::class,
SubstituteBindings::class,
Authenticate::class, Authenticate::class,
AuthenticateTwoFactor::class, AuthenticateTwoFactor::class,
IsConfirmed::class, IsConfirmed::class,
@ -168,8 +176,10 @@ class Kernel extends HttpKernel
], ],
'api' => [ 'api' => [
'throttle:60,1', 'throttle:60,1',
'bindings',
], ],
]; ];
@ -184,6 +194,8 @@ class Kernel extends HttpKernel
= [ = [
'auth' => Authenticate::class, 'auth' => Authenticate::class,
'auth.basic' => AuthenticateWithBasicAuth::class, 'auth.basic' => AuthenticateWithBasicAuth::class,
'bindings' => SubstituteBindings::class,
'can' => Authorize::class,
'guest' => RedirectIfAuthenticated::class, 'guest' => RedirectIfAuthenticated::class,
'throttle' => ThrottleRequests::class, 'throttle' => ThrottleRequests::class,
'range' => Range::class, 'range' => Range::class,

View File

@ -41,7 +41,7 @@ class Authenticate
return redirect()->guest('login'); return redirect()->guest('login');
} }
if (intval(Auth::user()->blocked) === 1) { if (intval(auth()->user()->blocked) === 1) {
Auth::guard($guard)->logout(); Auth::guard($guard)->logout();
Session::flash('logoutMessage', trans('firefly.block_account_logout')); Session::flash('logoutMessage', trans('firefly.block_account_logout'));

View File

@ -45,7 +45,7 @@ class AuthenticateTwoFactor
return redirect()->guest('login'); return redirect()->guest('login');
} }
if (intval(Auth::user()->blocked) === 1) { if (intval(auth()->user()->blocked) === 1) {
Auth::guard($guard)->logout(); Auth::guard($guard)->logout();
Session::flash('logoutMessage', trans('firefly.block_account_logout')); Session::flash('logoutMessage', trans('firefly.block_account_logout'));

1
app/Http/Middleware/EncryptCookies.php Normal file → Executable file
View File

@ -6,7 +6,6 @@
* This software may be modified and distributed under the terms * This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details. * of the MIT license. See the LICENSE file for details.
*/ */
declare(strict_types = 1); declare(strict_types = 1);
namespace FireflyIII\Http\Middleware; namespace FireflyIII\Http\Middleware;

View File

@ -43,7 +43,7 @@ class IsAdmin
return redirect()->guest('login'); return redirect()->guest('login');
} }
/** @var User $user */ /** @var User $user */
$user = Auth::user(); $user = auth()->user();
if (!$user->hasRole('owner')) { if (!$user->hasRole('owner')) {
return redirect(route('home')); return redirect(route('home'));
} }

View File

@ -11,6 +11,7 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Middleware; namespace FireflyIII\Http\Middleware;
use App;
use Carbon\Carbon; use Carbon\Carbon;
use Closure; use Closure;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
@ -19,6 +20,7 @@ use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Navigation; use Navigation;
use NumberFormatter;
use Preferences; use Preferences;
use Session; use Session;
use View; use View;
@ -62,36 +64,56 @@ class Range
public function handle(Request $request, Closure $theNext, $guard = null) public function handle(Request $request, Closure $theNext, $guard = null)
{ {
if (!Auth::guard($guard)->guest()) { if (!Auth::guard($guard)->guest()) {
// ignore preference. set the range to be the current month:
if (!Session::has('start') && !Session::has('end')) {
$viewRange = Preferences::get('viewRange', '1M')->data; // set start, end and finish:
$start = new Carbon; $this->setRange();
$start = Navigation::updateStartDate($viewRange, $start);
$end = Navigation::updateEndDate($viewRange, $start);
Session::put('start', $start); // get variables for date range:
Session::put('end', $end); $this->datePicker();
}
if (!Session::has('first')) {
/** @var JournalRepositoryInterface $repository */
$repository = app(JournalRepositoryInterface::class);
$journal = $repository->first();
$first = Carbon::now()->startOfYear();
if (!is_null($journal->id)) {
$first = $journal->date;
}
Session::put('first', $first);
}
// set view variables.
$this->configureView();
} }
$this->datePicker();
return $theNext($request); return $theNext($request);
} }
private function configureView()
{
$pref = Preferences::get('language', config('firefly.default_language', 'en_US'));
$lang = $pref->data;
App::setLocale($lang);
Carbon::setLocale(substr($lang, 0, 2));
$locale = explode(',', trans('config.locale'));
$locale = array_map('trim', $locale);
setlocale(LC_TIME, $locale);
setlocale(LC_MONETARY, $locale);
// save some formats:
$monthFormat = (string)trans('config.month');
$monthAndDayFormat = (string)trans('config.month_and_day');
$dateTimeFormat = (string)trans('config.date_time');
// change localeconv to a new array:
$numberFormatter = numfmt_create($lang, NumberFormatter::CURRENCY);
$localeconv = [
'mon_decimal_point' => $numberFormatter->getSymbol($numberFormatter->getAttribute(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL)),
'mon_thousands_sep' => $numberFormatter->getSymbol($numberFormatter->getAttribute(NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL)),
'frac_digits' => $numberFormatter->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS),
];
View::share('monthFormat', $monthFormat);
View::share('monthAndDayFormat', $monthAndDayFormat);
View::share('dateTimeFormat', $dateTimeFormat);
View::share('language', $lang);
View::share('localeconv', $localeconv);
}
/**
* @throws FireflyException
*/
private function datePicker() private function datePicker()
{ {
$viewRange = Preferences::get('viewRange', '1M')->data; $viewRange = Preferences::get('viewRange', '1M')->data;
@ -141,4 +163,33 @@ class Range
View::share('dpRanges', $ranges); View::share('dpRanges', $ranges);
} }
/**
*
*/
private function setRange()
{
// ignore preference. set the range to be the current month:
if (!Session::has('start') && !Session::has('end')) {
$viewRange = Preferences::get('viewRange', '1M')->data;
$start = new Carbon;
$start = Navigation::updateStartDate($viewRange, $start);
$end = Navigation::updateEndDate($viewRange, $start);
Session::put('start', $start);
Session::put('end', $end);
}
if (!Session::has('first')) {
/** @var JournalRepositoryInterface $repository */
$repository = app(JournalRepositoryInterface::class);
$journal = $repository->first();
$first = Carbon::now()->startOfYear();
if (!is_null($journal->id)) {
$first = $journal->date;
}
Session::put('first', $first);
}
}
} }

2
app/Http/Middleware/RedirectIfAuthenticated.php Normal file → Executable file
View File

@ -6,7 +6,6 @@
* This software may be modified and distributed under the terms * This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details. * of the MIT license. See the LICENSE file for details.
*/ */
declare(strict_types = 1); declare(strict_types = 1);
namespace FireflyIII\Http\Middleware; namespace FireflyIII\Http\Middleware;
@ -33,7 +32,6 @@ class RedirectIfAuthenticated
public function handle($request, Closure $next, $guard = null) public function handle($request, Closure $next, $guard = null)
{ {
if (Auth::guard($guard)->check()) { if (Auth::guard($guard)->check()) {
return redirect('/'); return redirect('/');
} }

2
app/Http/Middleware/VerifyCsrfToken.php Normal file → Executable file
View File

@ -6,8 +6,8 @@
* This software may be modified and distributed under the terms * This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details. * of the MIT license. See the LICENSE file for details.
*/ */
declare(strict_types = 1); declare(strict_types = 1);
namespace FireflyIII\Http\Middleware; namespace FireflyIII\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
use Input; use Input;
@ -29,7 +28,7 @@ class AccountFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,8 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
/** /**
* Class AttachmentFormRequest * Class AttachmentFormRequest
* *
@ -27,7 +25,7 @@ class AttachmentFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
use Input; use Input;
@ -29,7 +28,7 @@ class BillFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**
@ -45,7 +44,7 @@ class BillFormRequest extends Request
'amount_currency_id_amount_max' => intval($this->get('amount_currency_id_amount_max')), 'amount_currency_id_amount_max' => intval($this->get('amount_currency_id_amount_max')),
'amount_max' => round($this->get('amount_max'), 2), 'amount_max' => round($this->get('amount_max'), 2),
'date' => new Carbon($this->get('date')), 'date' => new Carbon($this->get('date')),
'user' => Auth::user()->id, 'user' => auth()->user()->id,
'repeat_freq' => $this->get('repeat_freq'), 'repeat_freq' => $this->get('repeat_freq'),
'skip' => intval($this->get('skip')), 'skip' => intval($this->get('skip')),
'automatch' => intval($this->get('automatch')) === 1, 'automatch' => intval($this->get('automatch')) === 1,

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
use FireflyIII\Models\Budget; use FireflyIII\Models\Budget;
use Input; use Input;
@ -29,7 +28,7 @@ class BudgetFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
use FireflyIII\Models\Category; use FireflyIII\Models\Category;
use Input; use Input;
@ -29,7 +28,7 @@ class CategoryFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,8 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
/** /**
* Class ConfigurationRequest * Class ConfigurationRequest
* *
@ -27,7 +25,7 @@ class ConfigurationRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users and admins // Only allow logged in users and admins
return Auth::check() && Auth::user()->hasRole('owner'); return auth()->check() && auth()->user()->hasRole('owner');
} }
/** /**

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
use Input; use Input;
/** /**
@ -28,7 +27,7 @@ class CurrencyFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,8 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
/** /**
* Class DeleteAccountFormRequest * Class DeleteAccountFormRequest
* *
@ -27,7 +25,7 @@ class DeleteAccountFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
/** /**
@ -28,7 +27,7 @@ class ExportFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,8 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
/** /**
* Class ImportUploadRequest * Class ImportUploadRequest
* *
@ -27,7 +25,7 @@ class ImportUploadRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
use Exception; use Exception;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
@ -32,7 +31,7 @@ class JournalFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**
@ -40,31 +39,31 @@ class JournalFormRequest extends Request
*/ */
public function getJournalData() public function getJournalData()
{ {
$tags = $this->get('tags') ?? ''; $tags = $this->getFieldOrEmptyString('tags');
return [ return [
'what' => $this->get('what'), 'what' => $this->get('what'),
'description' => $this->get('description'), 'description' => $this->get('description'),
'source_account_id' => intval($this->get('source_account_id')), 'source_account_id' => intval($this->get('source_account_id')),
'source_account_name' => $this->get('source_account_name') ?? '', 'source_account_name' => $this->getFieldOrEmptyString('source_account_name'),
'destination_account_id' => intval($this->get('destination_account_id')), 'destination_account_id' => intval($this->get('destination_account_id')),
'destination_account_name' => $this->get('destination_account_name') ?? '', 'destination_account_name' => $this->getFieldOrEmptyString('destination_account_name'),
'amount' => round($this->get('amount'), 2), 'amount' => round($this->get('amount'), 2),
'user' => Auth::user()->id, 'user' => auth()->user()->id,
'amount_currency_id_amount' => intval($this->get('amount_currency_id_amount')), 'amount_currency_id_amount' => intval($this->get('amount_currency_id_amount')),
'date' => new Carbon($this->get('date')), 'date' => new Carbon($this->get('date')),
'interest_date' => $this->get('interest_date') ? new Carbon($this->get('interest_date')) : null, 'interest_date' => $this->getDateOrNull('interest_date'),
'book_date' => $this->get('book_date') ? new Carbon($this->get('book_date')) : null, 'book_date' => $this->getDateOrNull('book_date'),
'process_date' => $this->get('process_date') ? new Carbon($this->get('process_date')) : null, 'process_date' => $this->getDateOrNull('process_date'),
'budget_id' => intval($this->get('budget_id')), 'budget_id' => intval($this->get('budget_id')),
'category' => $this->get('category') ?? '', 'category' => $this->getFieldOrEmptyString('category'),
'tags' => explode(',', $tags), 'tags' => explode(',', $tags),
'piggy_bank_id' => $this->get('piggy_bank_id') ? intval($this->get('piggy_bank_id')) : 0, 'piggy_bank_id' => intval($this->get('piggy_bank_id')),
// new custom fields here: // new custom fields here:
'due_date' => $this->get('due_date') ? new Carbon($this->get('due_date')) : null, 'due_date' => $this->getDateOrNull('due_date'),
'payment_date' => $this->get('payment_date') ? new Carbon($this->get('payment_date')) : null, 'payment_date' => $this->getDateOrNull('payment_date'),
'invoice_date' => $this->get('invoice_date') ? new Carbon($this->get('invoice_date')) : null, 'invoice_date' => $this->getDateOrNull('invoice_date'),
'internal_reference' => $this->get('internal_reference'), 'internal_reference' => $this->get('internal_reference'),
'notes' => $this->get('notes'), 'notes' => $this->get('notes'),
@ -120,4 +119,24 @@ class JournalFormRequest extends Request
return $rules; return $rules;
} }
/**
* @param string $field
*
* @return Carbon|null
*/
private function getDateOrNull(string $field)
{
return $this->get($field) ? new Carbon($this->get($field)) : null;
}
/**
* @param string $field
*
* @return string
*/
private function getFieldOrEmptyString(string $field): string
{
return $this->get($field) ?? '';
}
} }

View File

@ -11,8 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
/** /**
* Class MassDeleteJournalRequest * Class MassDeleteJournalRequest
* *
@ -27,7 +25,7 @@ class MassDeleteJournalRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,8 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
/** /**
* Class MassEditJournalRequest * Class MassEditJournalRequest
* *
@ -27,7 +25,7 @@ class MassEditJournalRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,8 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
/** /**
* Class NewUserFormRequest * Class NewUserFormRequest
* *
@ -27,7 +25,7 @@ class NewUserFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
use Input; use Input;
/** /**
@ -28,7 +27,7 @@ class PiggyBankFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,8 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
/** /**
* Class ProfileFormRequest * Class ProfileFormRequest
* *
@ -27,7 +25,7 @@ class ProfileFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
use FireflyIII\Models\RuleGroup; use FireflyIII\Models\RuleGroup;
use Input; use Input;
@ -29,7 +28,7 @@ class RuleFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -18,7 +18,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
use FireflyIII\Models\RuleGroup; use FireflyIII\Models\RuleGroup;
use Input; use Input;
@ -36,7 +35,7 @@ class RuleGroupFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
/** /**
@ -28,7 +27,7 @@ class SelectTransactionsRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
@ -28,7 +27,7 @@ class SplitJournalFormRequest extends Request
public function authorize(): bool public function authorize(): bool
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -10,7 +10,6 @@
declare(strict_types = 1); declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Models\Tag; use FireflyIII\Models\Tag;
use Input; use Input;
@ -29,7 +28,7 @@ class TagFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,8 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
/** /**
* Class RuleFormRequest * Class RuleFormRequest
* *
@ -27,7 +25,7 @@ class TestRuleFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -11,8 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Http\Requests; namespace FireflyIII\Http\Requests;
use Auth;
/** /**
* Class TokenFormRequest * Class TokenFormRequest
* *
@ -27,7 +25,7 @@ class TokenFormRequest extends Request
public function authorize() public function authorize()
{ {
// Only allow logged in users // Only allow logged in users
return Auth::check(); return auth()->check();
} }
/** /**

View File

@ -23,6 +23,7 @@ class Amount extends BasicConverter implements ConverterInterface
* Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. * Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
* - Jamie Zawinski * - Jamie Zawinski
* *
*
* @param $value * @param $value
* *
* @return float * @return float
@ -33,7 +34,7 @@ class Amount extends BasicConverter implements ConverterInterface
$decimalPosition = $len - 3; $decimalPosition = $len - 3;
$decimal = null; $decimal = null;
if ($len > 2 && $value{$decimalPosition} == '.') { if (($len > 2 && $value{$decimalPosition} == '.') || ($len > 2 && strpos($value, '.') > $decimalPosition)) {
$decimal = '.'; $decimal = '.';
} }
if ($len > 2 && $value{$decimalPosition} == ',') { if ($len > 2 && $value{$decimalPosition} == ',') {

View File

@ -293,7 +293,7 @@ class ImportStorage
private function storeJournal($entry): TransactionJournal private function storeJournal($entry): TransactionJournal
{ {
$billId = is_null($entry->fields['bill']) ? null : $entry->fields['bill']->id; $billId = is_null($entry->fields['bill']) || intval($entry->fields['bill']->id) === 0 ? null : intval($entry->fields['bill']->id);
$journalData = [ $journalData = [
'user_id' => $entry->user->id, 'user_id' => $entry->user->id,
'transaction_type_id' => $entry->fields['transaction-type']->id, 'transaction_type_id' => $entry->fields['transaction-type']->id,
@ -310,7 +310,7 @@ class ImportStorage
$journal = TransactionJournal::create($journalData); $journal = TransactionJournal::create($journalData);
foreach ($journal->getErrors()->all() as $err) { foreach ($journal->getErrors()->all() as $err) {
Log::error($err); Log::error('Error when storing journal: ' . $err);
} }
Log::debug('Created journal', ['id' => $journal->id]); Log::debug('Created journal', ['id' => $journal->id]);

View File

@ -178,10 +178,25 @@ class ImportValidator
$result = $repository->findByName($account->name, [$type]); $result = $repository->findByName($account->name, [$type]);
if (is_null($result->id)) { if (is_null($result->id)) {
// can convert account: // can convert account:
Log::debug(sprintf('No account named %s of type %s, will convert.', $account->name, $type)); Log::debug(sprintf('No account named %s of type %s, create new account.', $account->name, $type));
$result = $repository->updateAccountType($account, $type); $result = $repository->store(
[
'user' => $this->user->id,
'accountType' => config('firefly.shortNamesByFullName.' . $type),
'name' => $account->name,
'virtualBalance' => 0,
'active' => true,
'iban' => null,
'openingBalance' => 0,
]
);
} }
Log::debug(
sprintf(
'Using another account named %s (#%d) of type %s, will use that one instead of %s (#%d)', $account->name, $result->id, $type, $account->name,
$account->id
)
);
return $result; return $result;
@ -360,7 +375,7 @@ class ImportValidator
/** @var CurrencyRepositoryInterface $repository */ /** @var CurrencyRepositoryInterface $repository */
$repository = app(CurrencyRepositoryInterface::class, [$this->user]); $repository = app(CurrencyRepositoryInterface::class, [$this->user]);
// is the default currency for the user or the system // is the default currency for the user or the system
$defaultCode = Preferences::getForUser($this->user, 'currencyPreference', env('DEFAULT_CURRENCY', 'EUR'))->data; $defaultCode = Preferences::getForUser($this->user, 'currencyPreference', config('firefly.default_currency', 'EUR'))->data;
$entry->fields['currency'] = $repository->findByCode($defaultCode); $entry->fields['currency'] = $repository->findByCode($defaultCode);
Log::debug(sprintf('Set currency to %s', $defaultCode)); Log::debug(sprintf('Set currency to %s', $defaultCode));

View File

@ -11,6 +11,7 @@ declare(strict_types = 1);
namespace FireflyIII\Import\Importer; namespace FireflyIII\Import\Importer;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Import\Converter\ConverterInterface; use FireflyIII\Import\Converter\ConverterInterface;
use FireflyIII\Import\ImportEntry; use FireflyIII\Import\ImportEntry;
use FireflyIII\Import\Specifics\SpecificInterface; use FireflyIII\Import\Specifics\SpecificInterface;
@ -31,12 +32,15 @@ class CsvImporter implements ImporterInterface
/** @var ImportJob */ /** @var ImportJob */
public $job; public $job;
public $validSpecifics = [];
/** /**
* CsvImporter constructor. * CsvImporter constructor.
*/ */
public function __construct() public function __construct()
{ {
$this->collection = new Collection; $this->collection = new Collection;
$this->validSpecifics = array_keys(config('csv.import_specifics'));
} }
/** /**
@ -111,6 +115,11 @@ class CsvImporter implements ImporterInterface
// and this is the point where the specifix go to work. // and this is the point where the specifix go to work.
foreach ($config['specifics'] as $name => $enabled) { foreach ($config['specifics'] as $name => $enabled) {
if (!in_array($name, $this->validSpecifics)) {
throw new FireflyException(sprintf('"%s" is not a valid class name', $name));
}
/** @var SpecificInterface $specific */ /** @var SpecificInterface $specific */
$specific = app('FireflyIII\Import\Specifics\\' . $name); $specific = app('FireflyIII\Import\Specifics\\' . $name);
@ -120,12 +129,19 @@ class CsvImporter implements ImporterInterface
foreach ($row as $rowIndex => $value) { foreach ($row as $rowIndex => $value) {
// find the role for this column: // find the role for this column:
$role = $config['column-roles'][$rowIndex] ?? '_ignore'; $role = $config['column-roles'][$rowIndex] ?? '_ignore';
$doMap = $config['column-do-mapping'][$rowIndex] ?? false; $doMap = $config['column-do-mapping'][$rowIndex] ?? false;
$validConverters = array_keys(config('csv.import_roles'));
// throw error when not a valid converter.
if (!in_array($role, $validConverters)) {
throw new FireflyException(sprintf('"%s" is not a valid role.', $role));
}
$converterClass = config('csv.import_roles.' . $role . '.converter'); $converterClass = config('csv.import_roles.' . $role . '.converter');
$mapping = $config['column-mapping-config'][$rowIndex] ?? []; $mapping = $config['column-mapping-config'][$rowIndex] ?? [];
$className = sprintf('FireflyIII\\Import\\Converter\\%s', $converterClass);
/** @var ConverterInterface $converter */ /** @var ConverterInterface $converter */
$converter = app('FireflyIII\\Import\\Converter\\' . $converterClass); $converter = app($className);
// set some useful values for the converter: // set some useful values for the converter:
$converter->setMapping($mapping); $converter->setMapping($mapping);
$converter->setDoMap($doMap); $converter->setDoMap($doMap);

View File

@ -13,7 +13,6 @@ namespace FireflyIII\Import\Logging;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Monolog\Handler\AbstractProcessingHandler; use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;
/** /**
* Class CommandHandler * Class CommandHandler
@ -55,31 +54,9 @@ class CommandHandler extends AbstractProcessingHandler
*/ */
private function changeLevel(string $level) private function changeLevel(string $level)
{ {
switch ($level) { $level = strtoupper($level);
case 'debug': if (defined(sprintf('Logger::%s', $level))) {
$this->setLevel(Logger::DEBUG); $this->setLevel(constant(sprintf('Logger::%s', $level)));
break;
case 'info':
$this->setLevel(Logger::INFO);
break;
case 'notice':
$this->setLevel(Logger::NOTICE);
break;
case 'warning':
$this->setLevel(Logger::WARNING);
break;
case 'error':
$this->setLevel(Logger::ERROR);
break;
case 'critical':
$this->setLevel(Logger::CRITICAL);
break;
case 'alert':
$this->setLevel(Logger::ALERT);
break;
case 'emergency':
$this->setLevel(Logger::EMERGENCY);
break;
} }
} }
} }

View File

@ -14,6 +14,7 @@ namespace FireflyIII\Import\Setup;
use ExpandedForm; use ExpandedForm;
use FireflyIII\Crud\Account\AccountCrud; use FireflyIII\Crud\Account\AccountCrud;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Import\Mapper\MapperInterface; use FireflyIII\Import\Mapper\MapperInterface;
use FireflyIII\Import\MapperPreProcess\PreProcessorInterface; use FireflyIII\Import\MapperPreProcess\PreProcessorInterface;
use FireflyIII\Import\Specifics\SpecificInterface; use FireflyIII\Import\Specifics\SpecificInterface;
@ -32,7 +33,6 @@ use Symfony\Component\HttpFoundation\FileBag;
*/ */
class CsvSetup implements SetupInterface class CsvSetup implements SetupInterface
{ {
const EXAMPLE_ROWS = 5;
/** @var Account */ /** @var Account */
public $defaultImportAccount; public $defaultImportAccount;
/** @var ImportJob */ /** @var ImportJob */
@ -49,29 +49,13 @@ class CsvSetup implements SetupInterface
/** /**
* Create initial (empty) configuration array. * Create initial (empty) configuration array.
* *
*
*
* @return bool * @return bool
*/ */
public function configure(): bool public function configure(): bool
{ {
if (is_null($this->job->configuration) || (is_array($this->job->configuration) && count($this->job->configuration) === 0)) { if (is_null($this->job->configuration) || (is_array($this->job->configuration) && count($this->job->configuration) === 0)) {
Log::debug('No config detected, will create empty one.'); Log::debug('No config detected, will create empty one.');
$this->job->configuration = config('csv.default_config');
$config = [
'has-headers' => false, // assume
'date-format' => 'Ymd', // assume
'delimiter' => ',', // assume
'import-account' => 0, // none,
'specifics' => [], // none
'column-count' => 0, // unknown
'column-roles' => [], // unknown
'column-do-mapping' => [], // not yet set which columns must be mapped
'column-roles-complete' => false, // not yet configured roles for columns
'column-mapping-config' => [], // no mapping made yet.
'column-mapping-complete' => false, // so mapping is not complete.
];
$this->job->configuration = $config;
$this->job->save(); $this->job->save();
return true; return true;
@ -148,6 +132,7 @@ class CsvSetup implements SetupInterface
* the import job. * the import job.
* *
* @return string * @return string
* @throws FireflyException
*/ */
public function getViewForSettings(): string public function getViewForSettings(): string
{ {
@ -158,9 +143,7 @@ class CsvSetup implements SetupInterface
if ($this->doColumnMapping()) { if ($this->doColumnMapping()) {
return 'import.csv.map'; return 'import.csv.map';
} }
throw new FireflyException('There is no view for the current CSV import step.');
echo 'no view for settings';
exit;
} }
/** /**
@ -171,8 +154,8 @@ class CsvSetup implements SetupInterface
*/ */
public function requireUserSettings(): bool public function requireUserSettings(): bool
{ {
Log::debug('doColumnMapping is ' . ($this->doColumnMapping() ? 'true' : 'false')); Log::debug(sprintf('doColumnMapping is %s', $this->doColumnMapping()));
Log::debug('doColumnRoles is ' . ($this->doColumnRoles() ? 'true' : 'false')); Log::debug(sprintf('doColumnRoles is %s', $this->doColumnRoles()));
if ($this->doColumnMapping() || $this->doColumnRoles()) { if ($this->doColumnMapping() || $this->doColumnRoles()) {
Log::debug('Return true'); Log::debug('Return true');
@ -216,7 +199,11 @@ class CsvSetup implements SetupInterface
// loop specifics. // loop specifics.
if (isset($data['specifics']) && is_array($data['specifics'])) { if (isset($data['specifics']) && is_array($data['specifics'])) {
foreach ($data['specifics'] as $name => $enabled) { foreach ($data['specifics'] as $name => $enabled) {
$config['specifics'][$name] = 1; // verify their content.
$className = sprintf('FireflyIII\Import\Specifics\%s', $name);
if (class_exists($className)) {
$config['specifics'][$name] = 1;
}
} }
} }
$this->job->configuration = $config; $this->job->configuration = $config;
@ -322,6 +309,7 @@ class CsvSetup implements SetupInterface
/** /**
* @return array * @return array
* @throws FireflyException
*/ */
private function getDataForColumnMapping(): array private function getDataForColumnMapping(): array
{ {
@ -331,11 +319,19 @@ class CsvSetup implements SetupInterface
foreach ($config['column-do-mapping'] as $index => $mustBeMapped) { foreach ($config['column-do-mapping'] as $index => $mustBeMapped) {
if ($mustBeMapped) { if ($mustBeMapped) {
$column = $config['column-roles'][$index] ?? '_ignore'; $column = $config['column-roles'][$index] ?? '_ignore';
// is valid column?
$validColumns = array_keys(config('csv.import_roles'));
if (!in_array($column, $validColumns)) {
throw new FireflyException(sprintf('"%s" is not a valid column.', $column));
}
$canBeMapped = config('csv.import_roles.' . $column . '.mappable'); $canBeMapped = config('csv.import_roles.' . $column . '.mappable');
$preProcessMap = config('csv.import_roles.' . $column . '.pre-process-map'); $preProcessMap = config('csv.import_roles.' . $column . '.pre-process-map');
if ($canBeMapped) { if ($canBeMapped) {
$mapperName = '\FireflyIII\Import\Mapper\\' . config('csv.import_roles.' . $column . '.mapper'); $mapperClass = config('csv.import_roles.' . $column . '.mapper');
$mapperName = sprintf('\\FireflyIII\\Import\Mapper\\%s', $mapperClass);
/** @var MapperInterface $mapper */ /** @var MapperInterface $mapper */
$mapper = new $mapperName; $mapper = new $mapperName;
$indexes[] = $index; $indexes[] = $index;
@ -348,8 +344,11 @@ class CsvSetup implements SetupInterface
'values' => [], 'values' => [],
]; ];
if ($preProcessMap) { if ($preProcessMap) {
$data[$index]['preProcessMap'] = '\FireflyIII\Import\MapperPreProcess\\' . $preClass = sprintf(
config('csv.import_roles.' . $column . '.pre-process-mapper'); '\\FireflyIII\\Import\\MapperPreProcess\\%s',
config('csv.import_roles.' . $column . '.pre-process-mapper')
);
$data[$index]['preProcessMap'] = $preClass;
} }
} }
@ -361,15 +360,21 @@ class CsvSetup implements SetupInterface
/** @var Reader $reader */ /** @var Reader $reader */
$reader = Reader::createFromString($content); $reader = Reader::createFromString($content);
$reader->setDelimiter($config['delimiter']); $reader->setDelimiter($config['delimiter']);
$results = $reader->fetch(); $results = $reader->fetch();
$validSpecifics = array_keys(config('csv.import_specifics'));
foreach ($results as $rowIndex => $row) { foreach ($results as $rowIndex => $row) {
// run specifics here: // run specifics here:
// and this is the point where the specifix go to work. // and this is the point where the specifix go to work.
foreach ($config['specifics'] as $name => $enabled) { foreach ($config['specifics'] as $name => $enabled) {
if (!in_array($name, $validSpecifics)) {
throw new FireflyException(sprintf('"%s" is not a valid class name', $name));
}
$class = config('csv.import_specifics.' . $name);
/** @var SpecificInterface $specific */ /** @var SpecificInterface $specific */
$specific = app('FireflyIII\Import\Specifics\\' . $name); $specific = app($class);
// it returns the row, possibly modified: // it returns the row, possibly modified:
$row = $specific->run($row); $row = $specific->run($row);
@ -425,7 +430,7 @@ class CsvSetup implements SetupInterface
$reader = Reader::createFromString($content); $reader = Reader::createFromString($content);
$reader->setDelimiter($config['delimiter']); $reader->setDelimiter($config['delimiter']);
$start = $config['has-headers'] ? 1 : 0; $start = $config['has-headers'] ? 1 : 0;
$end = $start + self::EXAMPLE_ROWS; // first X rows $end = $start + config('csv.example_rows');
// collect example data in $data['columns'] // collect example data in $data['columns']
while ($start < $end) { while ($start < $end) {

View File

@ -0,0 +1,59 @@
<?php
/**
* PresidentsChoice.php
* Copyright (C) 2016 thegrumpydictator@gmail.com
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
declare(strict_types = 1);
namespace FireflyIII\Import\Specifics;
/**
* Class PresidentsChoice
*
* @package FireflyIII\Import\Specifics
*/
class PresidentsChoice implements SpecificInterface
{
/**
* @return string
*/
public static function getDescription(): string
{
return 'Fixes problems with files from Presidents Choice Financial.';
}
/**
* @return string
*/
public static function getName(): string
{
return 'Presidents "Choice"';
}
/**
* @param array $row
*
* @return array
*/
public function run(array $row): array
{
// first, if column 2 is empty and 3 is not, do nothing.
// if column 3 is empty and column 2 is not, move amount to column 3, *-1
if (isset($row[3]) && strlen($row[3]) === 0) {
$row[3] = bcmul($row[2], '-1');
}
if (isset($row[1])) {
// copy description into column 2, which is now usable.
$row[2] = $row[1];
}
return $row;
}
}

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use Auth;
use Crypt; use Crypt;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use Illuminate\Contracts\Encryption\DecryptException; use Illuminate\Contracts\Encryption\DecryptException;
@ -153,8 +152,8 @@ class Account extends Model
public static function routeBinder(Account $value) public static function routeBinder(Account $value)
{ {
if (Auth::check()) { if (auth()->check()) {
if ($value->user_id == Auth::user()->id) { if ($value->user_id == auth()->user()->id) {
return $value; return $value;
} }
} }

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use Auth;
use Crypt; use Crypt;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
@ -69,9 +68,9 @@ class Attachment extends Model
*/ */
public static function routeBinder(Attachment $value) public static function routeBinder(Attachment $value)
{ {
if (Auth::check()) { if (auth()->check()) {
if ($value->user_id == Auth::user()->id) { if ($value->user_id == auth()->user()->id) {
return $value; return $value;
} }
} }
@ -105,7 +104,7 @@ class Attachment extends Model
*/ */
public function getDescriptionAttribute($value) public function getDescriptionAttribute($value)
{ {
if (is_null($value)) { if (is_null($value) || strlen($value) === 0) {
return null; return null;
} }
@ -119,7 +118,7 @@ class Attachment extends Model
*/ */
public function getFilenameAttribute($value) public function getFilenameAttribute($value)
{ {
if (is_null($value)) { if (is_null($value) || strlen($value) === 0) {
return null; return null;
} }
@ -133,7 +132,7 @@ class Attachment extends Model
*/ */
public function getMimeAttribute($value) public function getMimeAttribute($value)
{ {
if (is_null($value)) { if (is_null($value) || strlen($value) === 0) {
return null; return null;
} }
@ -148,7 +147,7 @@ class Attachment extends Model
*/ */
public function getNotesAttribute($value) public function getNotesAttribute($value)
{ {
if (is_null($value)) { if (is_null($value) || strlen($value) === 0) {
return null; return null;
} }
@ -163,7 +162,7 @@ class Attachment extends Model
*/ */
public function getTitleAttribute($value) public function getTitleAttribute($value)
{ {
if (is_null($value)) { if (is_null($value) || strlen($value) === 0) {
return null; return null;
} }

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use Auth;
use Crypt; use Crypt;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
@ -81,8 +80,8 @@ class Bill extends Model
*/ */
public static function routeBinder(Bill $value) public static function routeBinder(Bill $value)
{ {
if (Auth::check()) { if (auth()->check()) {
if ($value->user_id == Auth::user()->id) { if ($value->user_id == auth()->user()->id) {
return $value; return $value;
} }
} }

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use Auth;
use Crypt; use Crypt;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
@ -94,8 +93,8 @@ class Budget extends Model
*/ */
public static function routeBinder(Budget $value) public static function routeBinder(Budget $value)
{ {
if (Auth::check()) { if (auth()->check()) {
if ($value->user_id == Auth::user()->id) { if ($value->user_id == auth()->user()->id) {
return $value; return $value;
} }
} }

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use Auth;
use Crypt; use Crypt;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
@ -89,8 +88,8 @@ class Category extends Model
*/ */
public static function routeBinder(Category $value) public static function routeBinder(Category $value)
{ {
if (Auth::check()) { if (auth()->check()) {
if ($value->user_id == Auth::user()->id) { if ($value->user_id == auth()->user()->id) {
return $value; return $value;
} }
} }

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use Auth;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@ -44,8 +43,8 @@ class ExportJob extends Model
*/ */
public static function routeBinder($value) public static function routeBinder($value)
{ {
if (Auth::check()) { if (auth()->check()) {
$model = self::where('key', $value)->where('user_id', Auth::user()->id)->first(); $model = self::where('key', $value)->where('user_id', auth()->user()->id)->first();
if (!is_null($model)) { if (!is_null($model)) {
return $model; return $model;
} }

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use Auth;
use Crypt; use Crypt;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Storage; use Storage;
@ -62,8 +61,8 @@ class ImportJob extends Model
*/ */
public static function routeBinder($value) public static function routeBinder($value)
{ {
if (Auth::check()) { if (auth()->check()) {
$model = self::where('key', $value)->where('user_id', Auth::user()->id)->first(); $model = self::where('key', $value)->where('user_id', auth()->user()->id)->first();
if (!is_null($model)) { if (!is_null($model)) {
return $model; return $model;
} }
@ -111,6 +110,9 @@ class ImportJob extends Model
*/ */
public function getConfigurationAttribute($value) public function getConfigurationAttribute($value)
{ {
if (is_null($value)) {
return [];
}
if (strlen($value) == 0) { if (strlen($value) == 0) {
return []; return [];
} }

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use Auth;
use Carbon\Carbon; use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@ -54,11 +53,11 @@ class LimitRepetition extends Model
*/ */
public static function routeBinder($value) public static function routeBinder($value)
{ {
if (Auth::check()) { if (auth()->check()) {
$object = LimitRepetition::where('limit_repetitions.id', $value) $object = LimitRepetition::where('limit_repetitions.id', $value)
->leftJoin('budget_limits', 'budget_limits.id', '=', 'limit_repetitions.budget_limit_id') ->leftJoin('budget_limits', 'budget_limits.id', '=', 'limit_repetitions.budget_limit_id')
->leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') ->leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
->where('budgets.user_id', Auth::user()->id) ->where('budgets.user_id', auth()->user()->id)
->first(['limit_repetitions.*']); ->first(['limit_repetitions.*']);
if ($object) { if ($object) {
return $object; return $object;

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use Auth;
use Crypt; use Crypt;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
@ -70,8 +69,8 @@ class PiggyBank extends Model
*/ */
public static function routeBinder(PiggyBank $value) public static function routeBinder(PiggyBank $value)
{ {
if (Auth::check()) { if (auth()->check()) {
if ($value->account->user_id == Auth::user()->id) { if ($value->account->user_id == auth()->user()->id) {
return $value; return $value;
} }
} }

View File

@ -42,7 +42,7 @@ class Preference extends Model
{ {
protected $dates = ['created_at', 'updated_at']; protected $dates = ['created_at', 'updated_at'];
protected $fillable = ['user_id', 'data', 'name']; protected $fillable = ['user_id', 'data', 'name','data'];
/** /**
* @param $value * @param $value
@ -55,7 +55,7 @@ class Preference extends Model
try { try {
$data = Crypt::decrypt($value); $data = Crypt::decrypt($value);
} catch (DecryptException $e) { } catch (DecryptException $e) {
Log::error('Could not decrypt preference.', ['id' => $this->id, 'name' => $this->name, 'data' => $this->data]); Log::error('Could not decrypt preference.', ['id' => $this->id, 'name' => $this->name, 'data' => $value]);
throw new FireflyException('Could not decrypt preference #' . $this->id . '.'); throw new FireflyException('Could not decrypt preference #' . $this->id . '.');
} }

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use Auth;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@ -59,8 +58,8 @@ class Rule extends Model
*/ */
public static function routeBinder(Rule $value) public static function routeBinder(Rule $value)
{ {
if (Auth::check()) { if (auth()->check()) {
if ($value->user_id == Auth::user()->id) { if ($value->user_id == auth()->user()->id) {
return $value; return $value;
} }
} }

View File

@ -11,7 +11,6 @@ declare(strict_types = 1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use Auth;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@ -55,8 +54,8 @@ class RuleGroup extends Model
*/ */
public static function routeBinder(RuleGroup $value) public static function routeBinder(RuleGroup $value)
{ {
if (Auth::check()) { if (auth()->check()) {
if ($value->user_id == Auth::user()->id) { if ($value->user_id == auth()->user()->id) {
return $value; return $value;
} }
} }

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