language
stringclasses 1
value | code
stringlengths 101
1.92M
| content
stringclasses 1
value |
|---|---|---|
php
|
<?php
namespace Spatie\Activitylog\Test;
use AddBatchUuidColumnToActivityLogTable;
use AddEventColumnToActivityLogTable;
use CreateActivityLogTable;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Encryption\Encrypter;
use Illuminate\Support\Facades\Schema;
use Orchestra\Testbench\TestCase as OrchestraTestCase;
use Spatie\Activitylog\ActivitylogServiceProvider;
use Spatie\Activitylog\Models\Activity;
use Spatie\Activitylog\Test\Models\Article;
use Spatie\Activitylog\Test\Models\User;
abstract class TestCase extends OrchestraTestCase
{
protected function setUp(): void
{
parent::setUp();
$this->setUpDatabase();
}
protected function getPackageProviders($app)
{
return [
ActivitylogServiceProvider::class,
];
}
public function getEnvironmentSetUp($app)
{
config()->set('activitylog.table_name', 'activity_log');
config()->set('activitylog.database_connection', 'sqlite');
config()->set('database.default', 'sqlite');
config()->set('database.connections.sqlite', [
'driver' => 'sqlite',
'database' => ':memory:',
]);
config()->set('auth.providers.users.model', User::class);
config()->set('app.key', 'base64:'.base64_encode(
Encrypter::generateKey(config()['app.cipher'])
));
}
protected function setUpDatabase(): void
{
$this->migrateActivityLogTable();
$this->createTables('articles', 'users');
$this->seedModels(Article::class, User::class);
}
protected function migrateActivityLogTable(): void
{
require_once __DIR__.'/../database/migrations/create_activity_log_table.php.stub';
require_once __DIR__.'/../database/migrations/add_event_column_to_activity_log_table.php.stub';
require_once __DIR__.'/../database/migrations/add_batch_uuid_column_to_activity_log_table.php.stub';
(new CreateActivityLogTable())->up();
(new AddEventColumnToActivityLogTable())->up();
(new AddBatchUuidColumnToActivityLogTable())->up();
}
protected function createTables(...$tableNames): void
{
collect($tableNames)->each(function (string $tableName) {
Schema::create($tableName, function (Blueprint $table) use ($tableName) {
$table->increments('id');
$table->string('name')->nullable();
$table->string('text')->nullable();
$table->timestamps();
$table->softDeletes();
if ($tableName === 'articles') {
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->text('json')->nullable();
$table->string('interval')->nullable();
$table->decimal('price')->nullable();
$table->string('status')->nullable();
}
});
});
}
protected function seedModels(...$modelClasses): void
{
collect($modelClasses)->each(function (string $modelClass) {
foreach (range(1, 0) as $index) {
$modelClass::create(['name' => "name {$index}"]);
}
});
}
public function getLastActivity(): ?Activity
{
return Activity::all()->last();
}
public function markTestAsPassed(): void
{
$this->assertTrue(true);
}
public function createArticle(): Article
{
$article = new $this->article();
$article->name = 'my name';
$article->save();
return $article;
}
public function loginWithFakeUser()
{
$user = new $this->user();
$user::find(1);
$this->be($user);
return $user;
}
}
| |
php
|
<?php
use Carbon\Carbon;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Application;
use Illuminate\Support\Collection;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Models\Activity;
use Spatie\Activitylog\Test\Enums\NonBackedEnum;
use Spatie\Activitylog\Test\Models\Article;
use Spatie\Activitylog\Test\Models\ArticleWithLogDescriptionClosure;
use Spatie\Activitylog\Test\Models\Issue733;
use Spatie\Activitylog\Test\Models\User;
use Spatie\Activitylog\Traits\LogsActivity;
beforeEach(function () {
$this->article = new class() extends Article {
use LogsActivity;
use SoftDeletes;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults();
}
};
$this->user = new class() extends User {
use LogsActivity;
use SoftDeletes;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults();
}
};
$this->assertCount(0, Activity::all());
});
it('will log the creation of the model', function () {
$article = $this->createArticle();
$this->assertCount(1, Activity::all());
$this->assertInstanceOf(get_class($this->article), $this->getLastActivity()->subject);
$this->assertEquals($article->id, $this->getLastActivity()->subject->id);
$this->assertEquals('created', $this->getLastActivity()->description);
$this->assertEquals('created', $this->getLastActivity()->event);
});
it('can skip logging model events if asked to', function () {
$article = new $this->article();
$article->disableLogging();
$article->name = 'my name';
$article->save();
$this->assertCount(0, Activity::all());
$this->assertNull($this->getLastActivity());
});
it('can switch on activity logging after disabling it', function () {
$article = new $this->article();
$article->disableLogging();
$article->name = 'my name';
$article->save();
$article->enableLogging();
$article->name = 'my new name';
$article->save();
$this->assertCount(1, Activity::all());
$this->assertInstanceOf(get_class($this->article), $this->getLastActivity()->subject);
$this->assertEquals($article->id, $this->getLastActivity()->subject->id);
$this->assertEquals('updated', $this->getLastActivity()->description);
$this->assertEquals('updated', $this->getLastActivity()->event);
});
it('can skip logging if asked to for update method', function () {
$article = new $this->article();
$article->disableLogging()->update(['name' => 'How to log events']);
$this->assertCount(0, Activity::all());
$this->assertNull($this->getLastActivity());
});
it('will log an update of the model', function () {
$article = $this->createArticle();
$article->name = 'changed name';
$article->save();
$this->assertCount(2, Activity::all());
$this->assertInstanceOf(get_class($this->article), $this->getLastActivity()->subject);
$this->assertEquals($article->id, $this->getLastActivity()->subject->id);
$this->assertEquals('updated', $this->getLastActivity()->description);
$this->assertEquals('updated', $this->getLastActivity()->event);
});
it('it will log the replication of a model with softdeletes', function () {
$article = $this->createArticle();
$replicatedArticle = $this->article::find($article->id)->replicate();
$replicatedArticle->save();
$activityItems = Activity::all();
$this->assertCount(2, $activityItems);
$this->assertTrue($activityItems->every(fn (Activity $item): bool => $item->event === 'created' &&
$item->description === 'created' &&
get_class($this->article) === $item->subject_type &&
in_array($item->subject_id, [$article->id, $replicatedArticle->id])));
$this->assertEquals($article->id, $activityItems->first()->subject_id);
$this->assertEquals($replicatedArticle->id, $activityItems->last()->subject_id);
});
it('will log the deletion of a model without softdeletes', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()->logOnly(['name']);
}
};
$article = new $articleClass();
$article->name = 'my name';
$article->save();
$this->assertEquals('created', $this->getLastActivity()->description);
$this->assertEquals('created', $this->getLastActivity()->event);
$article->delete();
$activity = $this->getLastActivity();
$this->assertEquals('deleted', $activity->description);
$this->assertArrayHasKey('old', $activity->changes());
$this->assertEquals('my name', $activity->changes()['old']['name']);
$this->assertArrayNotHasKey('attributes', $activity->changes());
$this->assertEquals('deleted', $activity->description);
$this->assertEquals('deleted', $activity->event);
});
it('will log the deletion of a model with softdeletes', function () {
$article = $this->createArticle();
$article->delete();
$this->assertCount(2, Activity::all());
$this->assertEquals(get_class($this->article), $this->getLastActivity()->subject_type);
$this->assertEquals($article->id, $this->getLastActivity()->subject_id);
$this->assertEquals('deleted', $this->getLastActivity()->description);
$this->assertEquals('deleted', $this->getLastActivity()->event);
$article->forceDelete();
$this->assertCount(3, Activity::all());
$this->assertEquals('deleted', $this->getLastActivity()->description);
$this->assertEquals('deleted', $this->getLastActivity()->event);
$this->assertNull($article->fresh());
});
it('will log the restoring of a model with softdeletes', function () {
$article = $this->createArticle();
$article->delete();
$article->restore();
$this->assertCount(3, Activity::all());
$this->assertEquals(get_class($this->article), $this->getLastActivity()->subject_type);
$this->assertEquals($article->id, $this->getLastActivity()->subject_id);
$this->assertEquals('restored', $this->getLastActivity()->description);
$this->assertEquals('restored', $this->getLastActivity()->event);
});
it('can fetch all activity for a model', function () {
$article = $this->createArticle();
$article->name = 'changed name';
$article->save();
$activities = $article->activities;
$this->assertCount(2, $activities);
});
it('can fetch soft deleted models', function () {
app()['config']->set('activitylog.subject_returns_soft_deleted_models', true);
$article = $this->createArticle();
$article->name = 'changed name';
$article->save();
$article->delete();
$activities = $article->activities;
$this->assertCount(3, $activities);
$this->assertEquals(get_class($this->article), $this->getLastActivity()->subject_type);
$this->assertEquals($article->id, $this->getLastActivity()->subject_id);
$this->assertEquals('deleted', $this->getLastActivity()->description);
$this->assertEquals('deleted', $this->getLastActivity()->event);
$this->assertEquals('changed name', $this->getLastActivity()->subject->name);
});
it('can log activity to log named in the model', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->useLogName('custom_log');
}
};
$article = new $articleClass();
$article->name = 'my name';
$article->save();
$this->assertSame('custom_log', Activity::latest()->first()->log_name);
});
it('will not log an update of the model if only ignored attributes are changed', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->dontLogIfAttributesChangedOnly(['text']);
}
};
$article = new $articleClass();
$article->name = 'my name';
$article->save();
$article->text = 'ignore me';
$article->save();
$this->assertCount(1, Activity::all());
$this->assertInstanceOf(get_class($articleClass), $this->getLastActivity()->subject);
$this->assertEquals($article->id, $this->getLastActivity()->subject->id);
$this->assertEquals('created', $this->getLastActivity()->description);
$this->assertEquals('created', $this->getLastActivity()->event);
});
it('will not fail if asked to replace from empty attribute', function () {
$model = new class() extends Article {
use LogsActivity;
use SoftDeletes;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->setDescriptionForEvent(fn (string $eventName): string => ":causer.name $eventName");
}
};
$entity = new $model();
$entity->save();
$entity->name = 'my name';
$entity->save();
$activities = $entity->activities;
$this->assertCount(2, $activities);
$this->assertEquals($entity->id, $activities[0]->subject->id);
$this->assertEquals($entity->id, $activities[1]->subject->id);
$this->assertEquals(':causer.name created', $activities[0]->description);
$this->assertEquals(':causer.name updated', $activities[1]->description);
});
it('can log activity on subject by same causer', function () {
$user = $this->loginWithFakeUser();
$user->name = 'LogsActivity Name';
$user->save();
$this->assertCount(1, Activity::all());
$this->assertInstanceOf(get_class($this->user), $this->getLastActivity()->subject);
$this->assertEquals($user->id, $this->getLastActivity()->subject->id);
$this->assertEquals($user->id, $this->getLastActivity()->causer->id);
$this->assertCount(1, $user->activities);
$this->assertCount(1, $user->actions);
});
it('can log activity when attributes are changed with tap', function () {
$model = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults();
}
protected $properties = [
'property' => [
'subProperty' => 'value',
],
];
public function tapActivity(Activity $activity, string $eventName)
{
$properties = $this->properties;
$properties['event'] = $eventName;
$activity->properties = collect($properties);
$activity->created_at = Carbon::yesterday()->startOfDay();
}
};
$entity = new $model();
$entity->save();
$firstActivity = $entity->activities()->first();
$this->assertInstanceOf(Collection::class, $firstActivity->properties);
$this->assertEquals('value', $firstActivity->getExtraProperty('property.subProperty'));
$this->assertEquals('created', $firstActivity->description);
$this->assertEquals('created', $firstActivity->event);
$this->assertEquals(Carbon::yesterday()->startOfDay()->format('Y-m-d H:i:s'), $firstActivity->created_at->format('Y-m-d H:i:s'));
});
it('can log activity when description is changed with tap', function () {
$model = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults();
}
public function tapActivity(Activity $activity, string $eventName)
{
$activity->description = 'my custom description';
}
};
$entity = new $model();
$entity->save();
$firstActivity = $entity->activities()->first();
$this->assertEquals('my custom description', $firstActivity->description);
});
it('can log activity when event is changed with tap', function () {
$model = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults();
}
public function tapActivity(Activity $activity, string $eventName)
{
$activity->event = 'my custom event';
}
};
$entity = new $model();
$entity->save();
$firstActivity = $entity->activities()->first();
$this->assertEquals('my custom event', $firstActivity->event);
});
it('will not submit log when there is no changes', function () {
$model = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['text'])
->dontSubmitEmptyLogs()
->logOnlyDirty();
}
};
$entity = new $model(['text' => 'test']);
$entity->save();
$this->assertCount(1, Activity::all());
$entity->name = 'my name';
$entity->save();
$this->assertCount(1, Activity::all());
});
it('will submit a log with json changes', function () {
$model = new class() extends Article {
use LogsActivity;
protected $casts = [
'json' => 'collection',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['text', 'json->data'])
->dontSubmitEmptyLogs()
->logOnlyDirty();
}
};
$entity = new $model([
'text' => 'test',
'json' => [
'data' => 'oldish',
],
]);
$entity->save();
$this->assertCount(1, Activity::all());
$entity->json = [
'data' => 'chips',
'irrelevant' => 'should not be',
];
$entity->save();
$expectedChanges = [
'attributes' => [
'json' => [
'data' => 'chips',
],
],
'old' => [
'json' => [
'data' => 'oldish',
],
],
];
$changes = $this->getLastActivity()->changes()->toArray();
$this->assertCount(2, Activity::all());
$this->assertSame($expectedChanges, $changes);
});
it('will log the retrieval of the model', function () {
$article = Issue733::create(['name' => 'my name']);
$retrieved = Issue733::whereKey($article->getKey())->first();
$this->assertTrue($article->is($retrieved));
$activity = $this->getLastActivity();
$this->assertInstanceOf(get_class($article), $activity->subject);
$this->assertTrue($article->is($activity->subject));
$this->assertEquals('retrieved', $activity->description);
});
it('will not log casted attribute of the model if attribute raw values is used', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = [
'name' => 'encrypted',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()->logOnly(['name'])->useAttributeRawValues(['name']);
}
};
$article = new $articleClass();
$article->name = 'my name';
$article->save();
$this->assertInstanceOf(get_class($articleClass), $this->getLastActivity()->subject);
$this->assertEquals($article->id, $this->getLastActivity()->subject->id);
$this->assertNotEquals($article->name, $this->getLastActivity()->properties['attributes']['name']);
$this->assertEquals('created', $this->getLastActivity()->description);
$this->assertEquals('created', $this->getLastActivity()->event);
});
it('can be serialized', function () {
$model = ArticleWithLogDescriptionClosure::create(['name' => 'foo']);
$this->assertNotNull(serialize($model));
});
it('logs non backed enum casted attribute', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = [
'status' => NonBackedEnum::class,
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()->logOnly(['status']);
}
};
$article = new $articleClass();
$article->status = NonBackedEnum::Draft;
$article->save();
$this->assertInstanceOf(get_class($articleClass), $this->getLastActivity()->subject);
$this->assertEquals($article->id, $this->getLastActivity()->subject->id);
$this->assertSame('Draft', $this->getLastActivity()->properties['attributes']['status']);
$this->assertEquals('created', $this->getLastActivity()->description);
$this->assertEquals('created', $this->getLastActivity()->event);
})->skip(
version_compare(PHP_VERSION, '8.1', '<') || version_compare(Application::VERSION, '9.0', '<'),
"PHP < 8.1 doesn't support enums && Laravel < 9.0 doesn't support non-backed-enum casting"
);
it('logs int backed enum casted attribute', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = [
'status' => \Spatie\Activitylog\Test\Enums\IntBackedEnum::class,
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()->logOnly(['status']);
}
};
$article = new $articleClass();
$article->status = \Spatie\Activitylog\Test\Enums\IntBackedEnum::Published;
$article->save();
$this->assertInstanceOf(get_class($articleClass), $this->getLastActivity()->subject);
$this->assertEquals($article->id, $this->getLastActivity()->subject->id);
$this->assertSame(1, $this->getLastActivity()->properties['attributes']['status']);
$this->assertEquals('created', $this->getLastActivity()->description);
$this->assertEquals('created', $this->getLastActivity()->event);
})->skip(version_compare(PHP_VERSION, '8.1', '<'), "PHP < 8.1 doesn't support enum");
it('logs string backed enum casted attribute', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = [
'status' => \Spatie\Activitylog\Test\Enums\StringBackedEnum::class,
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()->logOnly(['status']);
}
};
$article = new $articleClass();
$article->status = \Spatie\Activitylog\Test\Enums\StringBackedEnum::Draft;
$article->save();
$this->assertInstanceOf(get_class($articleClass), $this->getLastActivity()->subject);
$this->assertEquals($article->id, $this->getLastActivity()->subject->id);
$this->assertSame('draft', $this->getLastActivity()->properties['attributes']['status']);
$this->assertEquals('created', $this->getLastActivity()->description);
$this->assertEquals('created', $this->getLastActivity()->event);
})->skip(version_compare(PHP_VERSION, '8.1', '<'), "PHP < 8.1 doesn't support enum");
| |
php
|
<?php
use Spatie\Activitylog\Models\Activity;
use Spatie\Activitylog\Test\Models\CustomTableNameOnActivityModel;
it('uses the table name from the configuration', function () {
$model = new Activity();
expect(config('activitylog.table_name'))->toEqual($model->getTable());
});
it('uses a custom table name', function () {
$model = new Activity();
$newTableName = 'my_personal_activities';
$model->setTable($newTableName);
$this->assertNotEquals($model->getTable(), config('activitylog.table_name'));
expect($newTableName)->toEqual($model->getTable());
});
it('uses the table name from the model', function () {
$model = new CustomTableNameOnActivityModel();
$this->assertNotEquals($model->getTable(), config('activitylog.table_name'));
expect('custom_table_name')->toEqual($model->getTable());
});
| |
php
|
<?php
use Spatie\Activitylog\Test\Models\User;
it('can get all activity for the causer', function () {
$causer = User::first();
activity()->by($causer)->log('perform activity');
activity()->by($causer)->log('perform another activity');
expect($causer->actions)->toHaveCount(2);
});
| |
php
|
<?php
use Carbon\Carbon;
use Illuminate\Database\Eloquent\JsonEncodingException;
use Illuminate\Support\Collection;
use Spatie\Activitylog\Exceptions\CouldNotLogActivity;
use Spatie\Activitylog\Facades\Activity as ActivityFacade;
use Spatie\Activitylog\Facades\CauserResolver;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Models\Activity;
use Spatie\Activitylog\Test\Enums\NonBackedEnum;
use Spatie\Activitylog\Test\Models\Article;
use Spatie\Activitylog\Test\Models\User;
use Spatie\Activitylog\Traits\LogsActivity;
beforeEach(function () {
$this->activityDescription = 'My activity';
});
it('can log an activity', function () {
activity()->log($this->activityDescription);
expect($this->getLastActivity()->description)->toEqual($this->activityDescription);
});
it('can log an activity with facade', function () {
ActivityFacade::log($this->activityDescription);
expect($this->getLastActivity()->description)->toEqual($this->activityDescription);
});
it('will not log an activity when the log is not enabled', function () {
config(['activitylog.enabled' => false]);
activity()->log($this->activityDescription);
expect($this->getLastActivity())->toBeNull();
});
it('will log activity with a null log name', function () {
config(['activitylog.default_log_name' => null]);
activity()->log($this->activityDescription);
expect($this->getLastActivity()->log_name)->toBeNull();
});
it('will log an activity when enabled option is null', function () {
config(['activitylog.enabled' => null]);
activity()->log($this->activityDescription);
expect($this->getLastActivity()->description)->toEqual($this->activityDescription);
});
it('will log to the default log by default', function () {
activity()->log($this->activityDescription);
expect($this->getLastActivity()->log_name)->toEqual(config('activitylog.default_log_name'));
});
it('can log an activity to a specific log', function () {
$customLogName = 'secondLog';
activity($customLogName)->log($this->activityDescription);
expect($this->getLastActivity()->log_name)->toEqual($customLogName);
activity()->useLog($customLogName)->log($this->activityDescription);
expect($this->getLastActivity()->log_name)->toEqual($customLogName);
});
it('can log an activity with a subject', function () {
$subject = Article::first();
activity()
->performedOn($subject)
->log($this->activityDescription);
$firstActivity = Activity::first();
expect($firstActivity->subject->id)->toEqual($subject->id);
expect($firstActivity->subject)->toBeInstanceOf(Article::class);
});
it('can log an activity with a causer', function () {
$user = User::first();
activity()
->causedBy($user)
->log($this->activityDescription);
$firstActivity = Activity::first();
expect($firstActivity->causer->id)->toEqual($user->id);
expect($firstActivity->causer)->toBeInstanceOf(User::class);
});
it('can log an activity with a causer other than user model', function () {
$article = Article::first();
activity()
->causedBy($article)
->log($this->activityDescription);
$firstActivity = Activity::first();
expect($firstActivity->causer->id)->toEqual($article->id);
expect($firstActivity->causer)->toBeInstanceOf(Article::class);
});
it('can log an activity with a causer that has been set from other context', function () {
$causer = Article::first();
CauserResolver::setCauser($causer);
$article = Article::first();
activity()
->log($this->activityDescription);
$firstActivity = Activity::first();
expect($firstActivity->causer->id)->toEqual($article->id);
expect($firstActivity->causer)->toBeInstanceOf(Article::class);
});
it('can log an activity with a causer when there is no web guard', function () {
config(['auth.guards.web' => null]);
config(['auth.guards.foo' => ['driver' => 'session', 'provider' => 'users']]);
config(['activitylog.default_auth_driver' => 'foo']);
$user = User::first();
activity()
->causedBy($user)
->log($this->activityDescription);
$firstActivity = Activity::first();
expect($firstActivity->causer->id)->toEqual($user->id);
expect($firstActivity->causer)->toBeInstanceOf(User::class);
});
it('can log activity with properties', function () {
$properties = [
'property' => [
'subProperty' => 'value',
],
];
activity()
->withProperties($properties)
->log($this->activityDescription);
$firstActivity = Activity::first();
expect($firstActivity->properties)->toBeInstanceOf(Collection::class);
expect($firstActivity->getExtraProperty('property.subProperty'))->toEqual('value');
});
it('can log activity with null properties', function () {
$properties = [
'property' => null,
];
activity()
->withProperties($properties)
->log($this->activityDescription);
$firstActivity = Activity::first();
expect($firstActivity->properties)->toBeInstanceOf(Collection::class);
expect($firstActivity->getExtraProperty('property'))->toBeNull();
});
it('can log activity with a single properties', function () {
activity()
->withProperty('key', 'value')
->log($this->activityDescription);
$firstActivity = Activity::first();
expect($firstActivity->properties)->toBeInstanceOf(Collection::class);
expect($firstActivity->getExtraProperty('key'))->toEqual('value');
expect($firstActivity->getExtraProperty('non_existant', 'default value'))->toEqual('default value');
});
it('can translate a given causer id to an object', function () {
$userId = User::first()->id;
activity()
->causedBy($userId)
->log($this->activityDescription);
$firstActivity = Activity::first();
expect($firstActivity->causer)->toBeInstanceOf(User::class);
expect($firstActivity->causer->id)->toEqual($userId);
});
it('will throw an exception if it cannot translate a causer id', function () {
$this->expectException(CouldNotLogActivity::class);
activity()->causedBy(999);
});
it('will use the logged in user as the causer by default', function () {
$userId = 1;
Auth::login(User::find($userId));
activity()->log('hello poetsvrouwman');
expect($this->getLastActivity()->causer)->toBeInstanceOf(User::class);
expect($this->getLastActivity()->causer->id)->toEqual($userId);
});
it('can log activity using an anonymous causer', function () {
activity()
->causedByAnonymous()
->log('hello poetsvrouwman');
expect($this->getLastActivity()->causer_id)->toBeNull();
expect($this->getLastActivity()->causer_type)->toBeNull();
});
it('will override the logged in user as the causer when an anonymous causer is specified', function () {
$userId = 1;
Auth::login(User::find($userId));
activity()
->byAnonymous()
->log('hello poetsvrouwman');
expect($this->getLastActivity()->causer_id)->toBeNull();
expect($this->getLastActivity()->causer_type)->toBeNull();
});
it('can replace the placeholders', function () {
$article = Article::create(['name' => 'article name']);
$user = Article::create(['name' => 'user name']);
activity()
->performedOn($article)
->causedBy($user)
->withProperties(['key' => 'value', 'key2' => ['subkey' => 'subvalue']])
->log('Subject name is :subject.name, causer name is :causer.name and property key is :properties.key and sub key :properties.key2.subkey');
$expectedDescription = 'Subject name is article name, causer name is user name and property key is value and sub key subvalue';
expect($this->getLastActivity()->description)->toEqual($expectedDescription);
});
it('can replace the placeholders with object properties and accessors', function () {
$article = Article::create([
'name' => 'article name',
'user_id' => User::first()->id,
]);
$article->foo = new stdClass();
$article->foo->bar = new stdClass();
$article->foo->bar->baz = 'zal';
activity()
->performedOn($article)
->withProperties(['key' => 'value', 'key2' => ['subkey' => 'subvalue']])
->log('Subject name is :subject.name, deeply nested property is :subject.foo.bar.baz, accessor property is :subject.owner_name');
$expectedDescription = 'Subject name is article name, deeply nested property is zal, accessor property is name 1';
expect($this->getLastActivity()->description)->toEqual($expectedDescription);
});
it('can log an activity with event', function () {
$article = Article::create(['name' => 'article name']);
activity()
->performedOn($article)
->event('create')
->log('test event');
expect($this->getLastActivity()->event)->toEqual('create');
});
it('will not replace non placeholders', function () {
$description = 'hello: :hello';
activity()->log($description);
expect($this->getLastActivity()->description)->toEqual($description);
});
it('returns an instance of the activity log after logging when using a custom model', function () {
$activityClass = new class() extends Activity {
};
$activityClassName = get_class($activityClass);
app()['config']->set('activitylog.activity_model', $activityClassName);
$activityModel = activity()->log('test');
expect($activityModel)->toBeInstanceOf($activityClassName);
});
it('will not log an activity when the log is manually disabled', function () {
activity()->disableLogging();
activity()->log($this->activityDescription);
expect($this->getLastActivity())->toBeNull();
});
it('will log an activity when the log is manually enabled', function () {
config(['activitylog.enabled' => false]);
activity()->enableLogging();
activity()->log($this->activityDescription);
expect($this->getLastActivity()->description)->toEqual($this->activityDescription);
});
it('accepts null parameter for caused by', function () {
activity()->causedBy(null)->log('nothing');
$this->markTestAsPassed();
});
it('can log activity when attributes are changed with tap', function () {
$properties = [
'property' => [
'subProperty' => 'value',
],
];
activity()
->tap(function (Activity $activity) use ($properties) {
$activity->properties = collect($properties);
$activity->created_at = Carbon::yesterday()->startOfDay();
})
->log($this->activityDescription);
$firstActivity = Activity::first();
expect($firstActivity->properties)->toBeInstanceOf(Collection::class);
expect($firstActivity->getExtraProperty('property.subProperty'))->toEqual('value');
expect($firstActivity->created_at->format('Y-m-d H:i:s'))->toEqual(Carbon::yesterday()->startOfDay()->format('Y-m-d H:i:s'));
});
it('will tap a subject', function () {
$model = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults();
}
public function tapActivity(Activity $activity, string $eventName)
{
$activity->description = 'my custom description';
}
};
activity()
->on($model)
->log($this->activityDescription);
$firstActivity = Activity::first();
$this->assertEquals('my custom description', $firstActivity->description);
});
it('will log a custom created at date time', function () {
$activityDateTime = now()->subDays(10);
activity()
->createdAt($activityDateTime)
->log('created');
$firstActivity = Activity::first();
expect($firstActivity->created_at->toAtomString())->toEqual($activityDateTime->toAtomString());
});
it('will disable logs for a callback', function () {
$result = activity()->withoutLogs(function () {
activity()->log('created');
return 'hello';
});
expect($this->getLastActivity())->toBeNull();
expect($result)->toEqual('hello');
});
it('will disable logs for a callback without affecting previous state', function () {
activity()->withoutLogs(function () {
activity()->log('created');
});
expect($this->getLastActivity())->toBeNull();
activity()->log('outer');
expect($this->getLastActivity()->description)->toEqual('outer');
});
it('will disable logs for a callback without affecting previous state even when already disabled', function () {
activity()->disableLogging();
activity()->withoutLogs(function () {
activity()->log('created');
});
expect($this->getLastActivity())->toBeNull();
activity()->log('outer');
expect($this->getLastActivity())->toBeNull();
});
it('will disable logs for a callback without affecting previous state even with exception', function () {
activity()->disableLogging();
try {
activity()->withoutLogs(function () {
activity()->log('created');
throw new Exception('OH NO');
});
} catch (Exception $ex) {
//
}
expect($this->getLastActivity())->toBeNull();
activity()->log('outer');
expect($this->getLastActivity())->toBeNull();
});
it('logs backed enums in properties', function () {
activity()
->withProperties(['int_backed_enum' => \Spatie\Activitylog\Test\Enums\IntBackedEnum::Draft])
->withProperty('string_backed_enum', \Spatie\Activitylog\Test\Enums\StringBackedEnum::Published)
->log($this->activityDescription);
$this->assertSame(0, $this->getLastActivity()->properties['int_backed_enum']);
$this->assertSame('published', $this->getLastActivity()->properties['string_backed_enum']);
})->skip(version_compare(PHP_VERSION, '8.1', '<'), "PHP < 8.1 doesn't support enum");
it('does not log non backed enums in properties', function () {
activity()
->withProperty('non_backed_enum', NonBackedEnum::Published)
->log($this->activityDescription);
})
->throws(JsonEncodingException::class)
->skip(version_compare(PHP_VERSION, '8.1', '<'), "PHP < 8.1 doesn't support enum");
| |
php
|
<?php
use Spatie\Activitylog\Models\Activity;
use Spatie\Activitylog\Test\Models\CustomDatabaseConnectionOnActivityModel;
it('uses the database connection from the configuration', function () {
$model = new Activity();
expect(config('activitylog.database_connection'))->toEqual($model->getConnectionName());
});
it('uses a custom database connection', function () {
$model = new Activity();
$model->setConnection('custom_sqlite');
$this->assertNotEquals($model->getConnectionName(), config('activitylog.database_connection'));
expect('custom_sqlite')->toEqual($model->getConnectionName());
});
it('uses the default database connection when the one from configuration is null', function () {
app()['config']->set('activitylog.database_connection', null);
$model = new Activity();
expect($model->getConnection())->toBeInstanceOf('Illuminate\Database\SQLiteConnection');
});
it('uses the database connection from model', function () {
$model = new CustomDatabaseConnectionOnActivityModel();
$this->assertNotEquals($model->getConnectionName(), config('activitylog.database_connection'));
expect('custom_connection_name')->toEqual($model->getConnectionName());
});
| |
php
|
<?php
use Illuminate\Database\Eloquent\Relations\Relation;
use Spatie\Activitylog\Models\Activity;
use Spatie\Activitylog\Test\Models\Article;
use Spatie\Activitylog\Test\Models\User;
beforeEach(function () {
collect(range(1, 5))->each(function (int $index) {
$logName = "log{$index}";
activity($logName)->log('hello everybody');
});
});
it('provides a scope to get activities from a specific log', function () {
$activityInLog3 = Activity::inLog('log3')->get();
expect($activityInLog3)->toHaveCount(1);
expect($activityInLog3->first()->log_name)->toEqual('log3');
});
it('provides a scope to get log items from multiple logs', function () {
$activity = Activity::inLog('log2', 'log4')->get();
expect($activity)->toHaveCount(2);
expect($activity->first()->log_name)->toEqual('log2');
expect($activity->last()->log_name)->toEqual('log4');
});
it('provides a scope to get log items from multiple logs using an array', function () {
$activity = Activity::inLog(['log1', 'log2'])->get();
expect($activity)->toHaveCount(2);
expect($activity->first()->log_name)->toEqual('log1');
expect($activity->last()->log_name)->toEqual('log2');
});
it('provides a scope to get log items for a specific causer', function () {
$subject = Article::first();
$causer = User::first();
activity()->on($subject)->by($causer)->log('Foo');
activity()->on($subject)->by(User::create([
'name' => 'Another User',
]))->log('Bar');
$activities = Activity::causedBy($causer)->get();
expect($activities)->toHaveCount(1);
expect($activities->first()->causer_id)->toEqual($causer->getKey());
expect($activities->first()->causer_type)->toEqual(get_class($causer));
expect($activities->first()->description)->toEqual('Foo');
});
it('provides a scope to get log items for a specific event', function () {
$subject = Article::first();
activity()
->on($subject)
->event('create')
->log('Foo');
$activities = Activity::forEvent('create')->get();
expect($activities)->toHaveCount(1);
expect($activities->first()->event)->toEqual('create');
});
it('provides a scope to get log items for a specific subject', function () {
$subject = Article::first();
$causer = User::first();
activity()->on($subject)->by($causer)->log('Foo');
activity()->on(Article::create([
'name' => 'Another article',
]))->by($causer)->log('Bar');
$activities = Activity::forSubject($subject)->get();
expect($activities)->toHaveCount(1);
expect($activities->first()->subject_id)->toEqual($subject->getKey());
expect($activities->first()->subject_type)->toEqual(get_class($subject));
expect($activities->first()->description)->toEqual('Foo');
});
it('provides a scope to get log items for a specific morphmapped causer', function () {
Relation::morphMap([
'articles' => 'Spatie\Activitylog\Test\Models\Article',
'users' => 'Spatie\Activitylog\Test\Models\User',
]);
$subject = Article::first();
$causer = User::first();
activity()->on($subject)->by($causer)->log('Foo');
activity()->on($subject)->by(User::create([
'name' => 'Another User',
]))->log('Bar');
$activities = Activity::causedBy($causer)->get();
expect($activities)->toHaveCount(1);
expect($activities->first()->causer_id)->toEqual($causer->getKey());
expect($activities->first()->causer_type)->toEqual('users');
expect($activities->first()->description)->toEqual('Foo');
Relation::morphMap([], false);
});
it('provides a scope to get log items for a specific morphmapped subject', function () {
Relation::morphMap([
'articles' => 'Spatie\Activitylog\Test\Models\Article',
'users' => 'Spatie\Activitylog\Test\Models\User',
]);
$subject = Article::first();
$causer = User::first();
activity()->on($subject)->by($causer)->log('Foo');
activity()->on(Article::create([
'name' => 'Another article',
]))->by($causer)->log('Bar');
$activities = Activity::forSubject($subject)->get();
expect($activities)->toHaveCount(1);
expect($activities->first()->subject_id)->toEqual($subject->getKey());
expect($activities->first()->subject_type)->toEqual('articles');
expect($activities->first()->description)->toEqual('Foo');
Relation::morphMap([], false);
});
| |
php
|
<?php
use Spatie\Activitylog\Facades\LogBatch;
use Illuminate\Support\Str;
it('generates uuid after start and end batch properely', function () {
LogBatch::startBatch();
$uuid = LogBatch::getUuid();
LogBatch::endBatch();
expect(LogBatch::isopen())->toBeFalse();
expect($uuid)->toBeString();
});
it('returns null uuid after end batch properely', function () {
LogBatch::startBatch();
$uuid = LogBatch::getUuid();
LogBatch::endBatch();
expect(LogBatch::isopen())->toBeFalse();
$this->assertNotNull($uuid);
expect(LogBatch::getUuid())->toBeNull();
});
it('generates a new uuid after starting new batch properly', function () {
LogBatch::startBatch();
$firstBatchUuid = LogBatch::getUuid();
LogBatch::endBatch();
LogBatch::startBatch();
LogBatch::startBatch();
$secondBatchUuid = LogBatch::getUuid();
LogBatch::endBatch();
expect(LogBatch::isopen())->toBeTrue();
$this->assertNotNull($firstBatchUuid);
$this->assertNotNull($secondBatchUuid);
$this->assertNotEquals($firstBatchUuid, $secondBatchUuid);
});
it('will not generate new uuid if start already started batch', function () {
LogBatch::startBatch();
$firstUuid = LogBatch::getUuid();
LogBatch::startBatch();
$secondUuid = LogBatch::getUuid();
LogBatch::endBatch();
expect(LogBatch::isopen())->toBeTrue();
expect($secondUuid)->toEqual($firstUuid);
});
it('will not generate uuid if end batch before starting', function () {
LogBatch::endBatch();
$uuid = LogBatch::getUuid();
LogBatch::startBatch();
expect($uuid)->toBeNull();
});
it('can set uuid and start a batch', function () {
$uuid = Str::uuid();
LogBatch::setBatch($uuid);
expect(LogBatch::isOpen())->toBeTrue();
expect(LogBatch::getUuid())->toEqual($uuid);
LogBatch::endBatch();
expect(LogBatch::isOpen())->toBeFalse();
});
it('can set uuid for already started batch', function () {
$uuid = Str::uuid();
LogBatch::startBatch();
expect(LogBatch::isOpen())->toBeTrue();
$this->assertNotEquals($uuid, LogBatch::getUuid());
LogBatch::setBatch($uuid);
expect(LogBatch::isOpen())->toBeTrue();
expect(LogBatch::getUuid())->toEqual($uuid);
LogBatch::endBatch();
expect(LogBatch::isOpen())->toBeFalse();
});
it('will not return null uuid if end batch that started twice', function () {
LogBatch::startBatch();
$firstUuid = LogBatch::getUuid();
LogBatch::startBatch();
LogBatch::endBatch();
$notNullUuid = LogBatch::getUuid();
$this->assertNotNull($firstUuid);
$this->assertNotNull($notNullUuid);
expect($notNullUuid)->toBe($firstUuid);
});
it('will return null uuid if end batch that started twice properly', function () {
LogBatch::startBatch();
$firstUuid = LogBatch::getUuid();
LogBatch::startBatch();
LogBatch::endBatch();
LogBatch::endBatch();
$nullUuid = LogBatch::getUuid();
$this->assertNotNull($firstUuid);
expect($nullUuid)->toBeNull();
$this->assertNotSame($firstUuid, $nullUuid);
});
| |
php
|
<?php
use Carbon\Carbon;
use Carbon\CarbonInterval;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Arr;
use Spatie\Activitylog\Contracts\LoggablePipe;
use Spatie\Activitylog\EventLogBag;
use Spatie\Activitylog\LogBatch;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Models\Activity;
use Spatie\Activitylog\Test\Casts\IntervalCasts;
use Spatie\Activitylog\Test\Models\Article;
use Spatie\Activitylog\Test\Models\User;
use Spatie\Activitylog\Traits\LogsActivity;
beforeEach(function () {
$this->article = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text']);
}
};
$this->assertCount(0, Activity::all());
});
it('can store the values when creating a model', function () {
$this->createArticle();
$expectedChanges = [
'attributes' => [
'name' => 'my name',
'text' => null,
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('deep diff check json field', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = [
'json' => 'collection',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->dontSubmitEmptyLogs()
->logOnlyDirty()
->logOnly(['json->phone', 'json->details', 'json->address']);
}
};
$articleClass::addLogChange(new class() implements LoggablePipe {
public function handle(EventLogBag $event, Closure $next): EventLogBag
{
if ($event->event === 'updated') {
$event->changes['attributes']['json'] = array_udiff_assoc(
$event->changes['attributes']['json'],
$event->changes['old']['json'],
function ($new, $old) {
if ($old === null || $new === null) {
return 0;
}
return $new <=> $old;
}
);
$event->changes['old']['json'] = collect($event->changes['old']['json'])
->only(array_keys($event->changes['attributes']['json']))
->all();
}
return $next($event);
}
});
$article = $articleClass::create([
'name' => 'Hamburg',
'json' => ['details' => '', 'phone' => '1231231234', 'address' => 'new address'],
]);
$article->update(['json' => ['details' => 'new details']]);
$expectedChanges = [
'attributes' => [
'json' => [
'details' => 'new details',
],
],
'old' => [
'json' => [
'details' => '',
],
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('detect changes for date inteval attributes', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = [
'interval' => IntervalCasts::class,
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'interval'])
->logOnlyDirty();
}
};
$article = $articleClass::create([
'name' => 'Hamburg',
'interval' => CarbonInterval::minute(),
]);
$article->update(['name' => 'New name', 'interval' => CarbonInterval::month()]);
$expectedChanges = [
'attributes' => [
'name' => 'New name',
'interval' => '1 month',
],
'old' => [
'name' => 'Hamburg',
'interval' => '1 minute',
],
];
// test case when intervals changing from interval to another
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('detect changes for null date inteval attributes', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = [
'interval' => IntervalCasts::class,
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logAll()
->dontLogIfAttributesChangedOnly(['created_at', 'updated_at', 'deleted_at'])
->logOnlyDirty();
}
};
$nullIntevalArticle = $articleClass::create([
'name' => 'Hamburg',
]);
$nullIntevalArticle->update(['name' => 'New name', 'interval' => CarbonInterval::month()]);
$expectedChangesForNullInterval = [
'attributes' => [
'name' => 'New name',
'interval' => '1 month',
],
'old' => [
'name' => 'Hamburg',
'interval' => null,
],
];
$this->assertEquals($expectedChangesForNullInterval, $this->getLastActivity()->changes()->toArray());
$intervalArticle = $articleClass::create([
'name' => 'Hamburg',
'interval' => CarbonInterval::month(),
]);
$intervalArticle->update(['name' => 'New name', 'interval' => null]);
$expectedChangesForInterval = [
'attributes' => [
'name' => 'New name',
'interval' => null,
],
'old' => [
'name' => 'Hamburg',
'interval' => '1 month',
],
];
$this->assertEquals($expectedChangesForInterval, $this->getLastActivity()->changes()->toArray());
});
it('can store the relation values when creating a model', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text', 'user.name']);
}
};
$user = User::create([
'name' => 'user name',
]);
$article = $articleClass::create([
'name' => 'original name',
'text' => 'original text',
'user_id' => $user->id,
]);
$article->name = 'updated name';
$article->text = 'updated text';
$article->save();
$expectedChanges = [
'attributes' => [
'name' => 'updated name',
'text' => 'updated text',
'user.name' => 'user name',
],
'old' => [
'name' => 'original name',
'text' => 'original text',
'user.name' => 'user name',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('retruns same uuid for all log changes under one batch', function () {
$articleClass = new class() extends Article {
use LogsActivity;
use SoftDeletes;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text']);
}
};
app(LogBatch::class)->startBatch();
$user = User::create([
'name' => 'user name',
]);
$article = $articleClass::create([
'name' => 'original name',
'text' => 'original text',
'user_id' => $user->id,
]);
$article->name = 'updated name';
$article->text = 'updated text';
$article->save();
$article->delete();
$article->forceDelete();
$batchUuid = app(LogBatch::class)->getUuid();
app(LogBatch::class)->endBatch();
$this->assertTrue(Activity::pluck('batch_uuid')->every(fn ($uuid) => $uuid === $batchUuid));
});
it('assigns new uuid for multiple change logs in different batches', function () {
$articleClass = new class() extends Article {
use LogsActivity;
use SoftDeletes;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text']);
}
};
app(LogBatch::class)->startBatch();
$uuidForCreatedEvent = app(LogBatch::class)->getUuid();
$user = User::create([
'name' => 'user name',
]);
$article = $articleClass::create([
'name' => 'original name',
'text' => 'original text',
'user_id' => $user->id,
]);
app(LogBatch::class)->endBatch();
$this->assertTrue(Activity::pluck('batch_uuid')->every(fn ($uuid) => $uuid === $uuidForCreatedEvent));
app(LogBatch::class)->startBatch();
$article->name = 'updated name';
$article->text = 'updated text';
$article->save();
$uuidForUpdatedEvents = app(LogBatch::class)->getUuid();
app(LogBatch::class)->endBatch();
$this->assertCount(1, Activity::where('description', 'updated')->get());
$this->assertEquals($uuidForUpdatedEvents, Activity::where('description', 'updated')->first()->batch_uuid);
app(LogBatch::class)->startBatch();
$article->delete();
$article->forceDelete();
$uuidForDeletedEvents = app(LogBatch::class)->getUuid();
app(LogBatch::class)->endBatch();
$this->assertCount(2, Activity::where('batch_uuid', $uuidForDeletedEvents)->get());
$this->assertNotSame($uuidForCreatedEvent, $uuidForDeletedEvents);
});
it('can removes key event if it was loggable', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text', 'user.name']);
}
};
$user = User::create([
'name' => 'user name',
]);
$articleClass::addLogChange(new class() implements LoggablePipe {
public function handle(EventLogBag $event, Closure $next): EventLogBag
{
Arr::forget($event->changes, ['attributes.name', 'old.name']);
return $next($event);
}
});
$article = $articleClass::create([
'name' => 'original name',
'text' => 'original text',
'user_id' => $user->id,
]);
$article->name = 'updated name';
$article->text = 'updated text';
$article->save();
$expectedChanges = [
'attributes' => [
'text' => 'updated text',
'user.name' => 'user name',
],
'old' => [
'text' => 'original text',
'user.name' => 'user name',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can store empty relation when creating a model', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text', 'user.name']);
}
};
$user = User::create([
'name' => 'user name',
]);
$article = $articleClass::create([
'name' => 'original name',
'text' => 'original text',
]);
$article->name = 'updated name';
$article->text = 'updated text';
$article->save();
$expectedChanges = [
'attributes' => [
'name' => 'updated name',
'text' => 'updated text',
'user.name' => null,
],
'old' => [
'name' => 'original name',
'text' => 'original text',
'user.name' => null,
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can store the changes when updating a model', function () {
$article = $this->createArticle();
$article->name = 'updated name';
$article->text = 'updated text';
$article->save();
$expectedChanges = [
'attributes' => [
'name' => 'updated name',
'text' => 'updated text',
],
'old' => [
'name' => 'my name',
'text' => null,
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can store dirty changes only', function () {
$article = createDirtyArticle();
$article->name = 'updated name';
$article->save();
$expectedChanges = [
'attributes' => [
'name' => 'updated name',
],
'old' => [
'name' => 'my name',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can store dirty changes for swapping values', function () {
$article = createDirtyArticle();
$originalName = $article->name;
$originalText = $article->text;
$article->text = $originalName;
$article->name = $originalText;
$article->save();
$expectedChanges = [
'attributes' => [
'name' => $originalText,
'text' => $originalName,
],
'old' => [
'name' => $originalName,
'text' => $originalText,
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can store the changes when updating a related model', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text', 'user.name']);
}
};
$user = User::create([
'name' => 'a name',
]);
$anotherUser = User::create([
'name' => 'another name',
]);
$article = $articleClass::create([
'name' => 'name',
'text' => 'text',
'user_id' => $user->id,
]);
$article->user()->associate($anotherUser)->save();
$expectedChanges = [
'attributes' => [
'name' => 'name',
'text' => 'text',
'user.name' => 'another name',
],
'old' => [
'name' => 'name',
'text' => 'text',
'user.name' => 'a name',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can store the changes when updating a snake case related model', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text', 'snakeUser.name']);
}
public function snake_user()
{
return $this->belongsTo(User::class, 'user_id');
}
};
$user = User::create([
'name' => 'a name',
]);
$anotherUser = User::create([
'name' => 'another name',
]);
$article = $articleClass::create([
'name' => 'name',
'text' => 'text',
'user_id' => $user->id,
]);
$article->user()->associate($anotherUser)->save();
$expectedChanges = [
'attributes' => [
'name' => 'name',
'text' => 'text',
'snake_user.name' => 'another name',
],
'old' => [
'name' => 'name',
'text' => 'text',
'snake_user.name' => 'a name',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can store the changes when updating a camel case related model', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text', 'camel_user.name']);
}
public function camelUser()
{
return $this->belongsTo(User::class, 'user_id');
}
};
$user = User::create([
'name' => 'a name',
]);
$anotherUser = User::create([
'name' => 'another name',
]);
$article = $articleClass::create([
'name' => 'name',
'text' => 'text',
'user_id' => $user->id,
]);
$article->user()->associate($anotherUser)->save();
$expectedChanges = [
'attributes' => [
'name' => 'name',
'text' => 'text',
'camelUser.name' => 'another name',
],
'old' => [
'name' => 'name',
'text' => 'text',
'camelUser.name' => 'a name',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can store the changes when updating a custom case related model', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text', 'Custom_Case_User.name']);
}
public function Custom_Case_User()
{
return $this->belongsTo(User::class, 'user_id');
}
};
$user = User::create([
'name' => 'a name',
]);
$anotherUser = User::create([
'name' => 'another name',
]);
$article = $articleClass::create([
'name' => 'name',
'text' => 'text',
'user_id' => $user->id,
]);
$article->user()->associate($anotherUser)->save();
$expectedChanges = [
'attributes' => [
'name' => 'name',
'text' => 'text',
'Custom_Case_User.name' => 'another name',
],
'old' => [
'name' => 'name',
'text' => 'text',
'Custom_Case_User.name' => 'a name',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can store the dirty changes when updating a related model', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text', 'user.name'])
->logOnlyDirty();
}
};
$user = User::create([
'name' => 'a name',
]);
$anotherUser = User::create([
'name' => 'another name',
]);
$article = $articleClass::create([
'name' => 'name',
'text' => 'text',
'user_id' => $user->id,
]);
$article->user()->associate($anotherUser)->save();
$expectedChanges = [
'attributes' => [
'user.name' => 'another name',
],
'old' => [
'user.name' => 'a name',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can store the changes when saving including multi level related model', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text', 'user.latest_article.name'])
->logOnlyDirty();
}
};
$user = User::create([
'name' => 'a name',
]);
$articleClass::create([
'name' => 'name #1',
'text' => 'text #1',
'user_id' => $user->id,
]);
$articleClass::create([
'name' => 'name #2',
'text' => 'text #2',
'user_id' => $user->id,
]);
$expectedChanges = [
'attributes' => [
'name' => 'name #2',
'text' => 'text #2',
'user.latestArticle.name' => 'name #1',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('will store no changes when not logging attributes', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly([]);
}
};
$article = new $articleClass();
$article->name = 'updated name';
$article->save();
$this->assertEquals(collect(), $this->getLastActivity()->changes());
});
it('will store the values when deleting the model', function () {
$article = $this->createArticle();
$article->delete();
$expectedChanges = collect([
'old' => [
'name' => 'my name',
'text' => null,
],
]);
$this->assertEquals('deleted', $this->getLastActivity()->description);
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes());
});
it('will store the values when deleting the model with softdeletes', function () {
$articleClass = new class() extends Article {
use LogsActivity;
use SoftDeletes;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text']);
}
};
$article = new $articleClass();
$article->name = 'my name';
$article->save();
$article->delete();
$expectedChanges = collect([
'old' => [
'name' => 'my name',
'text' => null,
],
]);
$this->assertEquals('deleted', $this->getLastActivity()->description);
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes());
$article->forceDelete();
$expectedChanges = collect([
'old' => [
'name' => 'my name',
'text' => null,
],
]);
$activities = $article->activities;
$this->assertCount(3, $activities);
$this->assertEquals('deleted', $this->getLastActivity()->description);
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes());
});
it('can store the changes of collection casted properties', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = ['json' => 'collection'];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['json'])
->logOnlyDirty();
}
};
$article = $articleClass::create([
'json' => ['value' => 'original'],
]);
$article->json = collect(['value' => 'updated']);
$article->save();
$expectedChanges = [
'attributes' => [
'json' => [
'value' => 'updated',
],
],
'old' => [
'json' => [
'value' => 'original',
],
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can store the changes of array casted properties', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = ['json' => 'array'];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['json'])
->logOnlyDirty();
}
};
$article = $articleClass::create([
'json' => ['value' => 'original'],
]);
$article->json = collect(['value' => 'updated']);
$article->save();
$expectedChanges = [
'attributes' => [
'json' => [
'value' => 'updated',
],
],
'old' => [
'json' => [
'value' => 'original',
],
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can store the changes of json casted properties', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = ['json' => 'json'];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['json'])
->logOnlyDirty();
}
};
$article = $articleClass::create([
'json' => ['value' => 'original'],
]);
$article->json = collect(['value' => 'updated']);
$article->save();
$expectedChanges = [
'attributes' => [
'json' => [
'value' => 'updated',
],
],
'old' => [
'json' => [
'value' => 'original',
],
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use nothing as loggable attributes', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $fillable = ['name', 'text'];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->dontLogFillable();
}
};
$article = new $articleClass();
$article->name = 'my name';
$article->text = 'my text';
$article->save();
$expectedChanges = [];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use text as loggable attributes', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $fillable = ['name', 'text'];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['text'])
->dontLogFillable();
}
};
$article = new $articleClass();
$article->name = 'my name';
$article->text = 'my text';
$article->save();
$expectedChanges = [
'attributes' => [
'text' => 'my text',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use fillable as loggable attributes', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $fillable = ['name', 'text'];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logFillable();
}
};
$article = new $articleClass();
$article->name = 'my name';
$article->save();
$expectedChanges = [
'attributes' => [
'name' => 'my name',
'text' => null,
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use both fillable and log attributes', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $fillable = ['name'];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['text'])
->logFillable();
}
};
$article = new $articleClass();
$article->name = 'my name';
$article->text = 'my text';
$article->save();
$expectedChanges = [
'attributes' => [
'name' => 'my name',
'text' => 'my text',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use wildcard for loggable attributes', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logAll();
}
};
$article = new $articleClass();
$article->name = 'my name';
Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0));
$article->save();
$expectedChanges = [
'attributes' => [
'name' => 'my name',
'text' => null,
'deleted_at' => null,
'id' => $article->id,
'user_id' => null,
'json' => null,
'price' => null,
'interval' => null,
'status' => null,
'created_at' => '2017-01-01T12:00:00.000000Z',
'updated_at' => '2017-01-01T12:00:00.000000Z',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use wildcard with relation', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['*', 'user.name']);
}
};
$user = User::create([
'name' => 'user name',
]);
Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0));
$article = $articleClass::create([
'name' => 'article name',
'text' => 'article text',
'user_id' => $user->id,
]);
$expectedChanges = [
'attributes' => [
'id' => $article->id,
'name' => 'article name',
'text' => 'article text',
'deleted_at' => null,
'user_id' => $user->id,
'json' => null,
'price' => null,
'created_at' => '2017-01-01T12:00:00.000000Z',
'updated_at' => '2017-01-01T12:00:00.000000Z',
'user.name' => 'user name',
'interval' => null,
'status' => null,
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use wildcard when updating model', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logAll()
->logOnlyDirty();
}
};
$user = User::create([
'name' => 'user name',
]);
Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0));
$article = $articleClass::create([
'name' => 'article name',
'text' => 'article text',
'user_id' => $user->id,
]);
$article->name = 'changed name';
Carbon::setTestNow(Carbon::create(2018, 1, 1, 12, 0, 0));
$article->save();
$expectedChanges = [
'attributes' => [
'name' => 'changed name',
'updated_at' => '2018-01-01T12:00:00.000000Z',
],
'old' => [
'name' => 'article name',
'updated_at' => '2017-01-01T12:00:00.000000Z',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can store the changes when a boolean field is changed from false to null', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = [
'text' => 'boolean',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logAll()
->logOnlyDirty();
}
};
$user = User::create([
'name' => 'user name',
]);
Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0));
$article = $articleClass::create([
'name' => 'article name',
'text' => false,
'user_id' => $user->id,
]);
$article->text = null;
Carbon::setTestNow(Carbon::create(2018, 1, 1, 12, 0, 0));
$article->save();
$expectedChanges = [
'attributes' => [
'text' => null,
'updated_at' => '2018-01-01T12:00:00.000000Z',
],
'old' => [
'text' => false,
'updated_at' => '2017-01-01T12:00:00.000000Z',
],
];
$this->assertSame($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use ignored attributes while updating', function () {
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logAll()
->logExcept(['name', 'updated_at']);
}
};
$article = new $articleClass();
$article->name = 'my name';
Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0));
$article->save();
$expectedChanges = [
'attributes' => [
'text' => null,
'deleted_at' => null,
'id' => $article->id,
'user_id' => null,
'json' => null,
'price' => null,
'interval' => null,
'status' => null,
'created_at' => '2017-01-01T12:00:00.000000Z',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use unguarded as loggable attributes', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $guarded = ['text', 'json'];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logUnguarded()
->logExcept(['id', 'created_at', 'updated_at', 'deleted_at']);
}
};
$article = new $articleClass();
$article->name = 'my name';
$article->text = 'my new text';
$article->save();
$expectedChanges = [
'attributes' => [
'name' => 'my name',
'user_id' => null,
'price' => null,
'interval' => null,
'status' => null,
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('will store no changes when wildcard guard and log unguarded attributes', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $guarded = ['*'];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logUnguarded();
}
};
$article = new $articleClass();
$article->name = 'my name';
$article->text = 'my new text';
$article->save();
$this->assertEquals([], $this->getLastActivity()->changes()->toArray());
});
it('can use hidden as loggable attributes', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $hidden = ['text'];
protected $fillable = ['name', 'text'];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text']);
}
};
$article = new $articleClass();
$article->name = 'my name';
$article->text = 'my text';
$article->save();
$expectedChanges = [
'attributes' => [
'name' => 'my name',
'text' => 'my text',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use overloaded as loggable attributes', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $fillable = ['name', 'text'];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text', 'description']);
}
public function setDescriptionAttribute($value)
{
$this->attributes['json'] = json_encode(['description' => $value]);
}
public function getDescriptionAttribute()
{
return Arr::get(json_decode($this->attributes['json'], true), 'description');
}
};
$article = new $articleClass();
$article->name = 'my name';
$article->text = 'my text';
$article->description = 'my description';
$article->save();
$expectedChanges = [
'attributes' => [
'name' => 'my name',
'text' => 'my text',
'description' => 'my description',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use mutated as loggable attributes', function () {
$userClass = new class() extends User {
use LogsActivity;
protected $fillable = ['name', 'text'];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logAll();
}
public function setNameAttribute($value)
{
$this->attributes['name'] = strtoupper($value);
}
};
Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0));
$user = new $userClass();
$user->name = 'my name';
$user->text = 'my text';
$user->save();
$expectedChanges = [
'attributes' => [
'id' => $user->id,
'name' => 'MY NAME',
'text' => 'my text',
'created_at' => '2017-01-01T12:00:00.000000Z',
'updated_at' => '2017-01-01T12:00:00.000000Z',
'deleted_at' => null,
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
$user->name = 'my name 2';
$user->save();
$expectedChanges = [
'old' => [
'id' => $user->id,
'name' => 'MY NAME',
'text' => 'my text',
'created_at' => '2017-01-01T12:00:00.000000Z',
'updated_at' => '2017-01-01T12:00:00.000000Z',
'deleted_at' => null,
],
'attributes' => [
'id' => $user->id,
'name' => 'MY NAME 2',
'text' => 'my text',
'created_at' => '2017-01-01T12:00:00.000000Z',
'updated_at' => '2017-01-01T12:00:00.000000Z',
'deleted_at' => null,
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use accessor as loggable attributes', function () {
$userClass = new class() extends User {
use LogsActivity;
protected $fillable = ['name', 'text'];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logAll();
}
public function getNameAttribute($value)
{
return strtoupper($value);
}
};
Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0));
$user = new $userClass();
$user->name = 'my name';
$user->text = 'my text';
$user->save();
$expectedChanges = [
'attributes' => [
'id' => $user->id,
'name' => 'MY NAME',
'text' => 'my text',
'created_at' => '2017-01-01T12:00:00.000000Z',
'updated_at' => '2017-01-01T12:00:00.000000Z',
'deleted_at' => null,
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
$user->name = 'my name 2';
$user->save();
$expectedChanges = [
'old' => [
'id' => $user->id,
'name' => 'MY NAME',
'text' => 'my text',
'created_at' => '2017-01-01T12:00:00.000000Z',
'updated_at' => '2017-01-01T12:00:00.000000Z',
'deleted_at' => null,
],
'attributes' => [
'id' => $user->id,
'name' => 'MY NAME 2',
'text' => 'my text',
'created_at' => '2017-01-01T12:00:00.000000Z',
'updated_at' => '2017-01-01T12:00:00.000000Z',
'deleted_at' => null,
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use encrypted as loggable attributes', function () {
$userClass = new class() extends User {
use LogsActivity;
protected $fillable = ['name', 'text'];
protected $encryptable = ['name', 'text'];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text']);
}
public function getAttributeValue($key)
{
$value = parent::getAttributeValue($key);
if (in_array($key, $this->encryptable)) {
$value = decrypt($value);
}
return $value;
}
public function setAttribute($key, $value)
{
if (in_array($key, $this->encryptable)) {
$value = encrypt($value);
}
return parent::setAttribute($key, $value);
}
};
Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0));
$user = new $userClass();
$user->name = 'my name';
$user->text = 'my text';
$user->save();
$expectedChanges = [
'attributes' => [
'name' => 'my name',
'text' => 'my text',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
$user->name = 'my name 2';
$user->save();
$expectedChanges = [
'old' => [
'name' => 'my name',
'text' => 'my text',
],
'attributes' => [
'name' => 'my name 2',
'text' => 'my text',
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use casted as loggable attribute', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = [
'price' => 'float',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text', 'price'])
->logOnlyDirty();
}
};
$article = new $articleClass();
$article->name = 'my name';
$article->text = 'my text';
$article->price = '9.99';
$article->save();
$expectedChanges = [
'attributes' => [
'name' => 'my name',
'text' => 'my text',
'price' => 9.99,
],
];
$changes = $this->getLastActivity()->changes()->toArray();
$this->assertSame($expectedChanges, $changes);
$this->assertIsFloat($changes['attributes']['price']);
$article->price = 19.99;
$article->save();
$expectedChanges = [
'attributes' => [
'price' => 19.99,
],
'old' => [
'price' => 9.99,
],
];
$changes = $this->getLastActivity()->changes()->toArray();
$this->assertSame($expectedChanges, $changes);
$this->assertIsFloat($changes['attributes']['price']);
});
it('can use nullable date as loggable attributes', function () {
$userClass = new class() extends User {
use LogsActivity;
use SoftDeletes;
protected $fillable = ['name', 'text'];
protected $dates = [
'created_at',
'updated_at',
'deleted_at',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logAll();
}
};
Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0));
$user = new $userClass();
$user->name = 'my name';
$user->text = 'my text';
$user->save();
$expectedChanges = [
'attributes' => [
'id' => $user->getKey(),
'name' => 'my name',
'text' => 'my text',
'created_at' => '2017-01-01T12:00:00.000000Z',
'updated_at' => '2017-01-01T12:00:00.000000Z',
'deleted_at' => null,
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use custom date cast as loggable attributes', function () {
$userClass = new class() extends User {
use LogsActivity;
protected $fillable = ['name', 'text'];
protected $casts = [
'created_at' => 'date:d.m.Y',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logAll();
}
};
Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0));
$user = new $userClass();
$user->name = 'my name';
$user->text = 'my text';
$user->save();
$expectedChanges = [
'attributes' => [
'id' => $user->getKey(),
'name' => 'my name',
'text' => 'my text',
'created_at' => '01.01.2017',
'updated_at' => '2017-01-01T12:00:00.000000Z',
'deleted_at' => null,
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can use custom immutable date cast as loggable attributes', function () {
$userClass = new class() extends User {
use LogsActivity;
protected $fillable = ['name', 'text'];
protected $casts = [
'created_at' => 'immutable_date:d.m.Y',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logAll();
}
};
Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0));
$user = new $userClass();
$user->name = 'my name';
$user->text = 'my text';
$user->save();
$expectedChanges = [
'attributes' => [
'id' => $user->getKey(),
'name' => 'my name',
'text' => 'my text',
'created_at' => '01.01.2017',
'updated_at' => '2017-01-01T12:00:00.000000Z',
'deleted_at' => null,
],
];
$this->assertEquals($expectedChanges, $this->getLastActivity()->changes()->toArray());
});
it('can store the changes of json attributes', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = [
'json' => 'collection',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'json->data'])
->logOnlyDirty();
}
};
$article = new $articleClass();
$article->json = ['data' => 'test'];
$article->name = 'I am JSON';
$article->save();
$expectedChanges = [
'attributes' => [
'name' => 'I am JSON',
'json' => [
'data' => 'test',
],
],
];
$changes = $this->getLastActivity()->changes()->toArray();
$this->assertSame($expectedChanges, $changes);
});
it('will not store changes to untracked json', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = [
'json' => 'collection',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'json->data'])
->logOnlyDirty();
}
};
$article = new $articleClass();
$article->json = ['unTracked' => 'test'];
$article->name = 'a name';
$article->save();
$article->name = 'I am JSON';
$article->json = ['unTracked' => 'different string'];
$article->save();
$expectedChanges = [
'attributes' => [
'name' => 'I am JSON',
],
'old' => [
'name' => 'a name',
],
];
$changes = $this->getLastActivity()->changes()->toArray();
$this->assertSame($expectedChanges, $changes);
});
it('will return null for missing json attribute', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = [
'json' => 'collection',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'json->data->missing'])
->logOnlyDirty();
}
};
$jsonToStore = [];
$article = new $articleClass();
$article->json = $jsonToStore;
$article->name = 'I am JSON';
$article->save();
data_set($jsonToStore, 'data.missing', 'I wasn\'t here');
$article->json = $jsonToStore;
$article->save();
$expectedChanges = [
'attributes' => [
'json' => [
'data' => [
'missing' => 'I wasn\'t here',
],
],
],
'old' => [
'json' => [
'data' => [
'missing' => null,
],
],
],
];
$changes = $this->getLastActivity()->changes()->toArray();
$this->assertSame($expectedChanges, $changes);
});
it('will return an array for sub key in json attribute', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = [
'json' => 'collection',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'json->data'])
->logOnlyDirty();
}
};
$jsonToStore = [
'data' => [
'data_a' => 1,
'data_b' => 2,
'data_c' => 3,
'data_d' => 4,
'data_e' => 5,
],
];
$article = new $articleClass();
$article->json = $jsonToStore;
$article->name = 'I am JSON';
$article->save();
data_set($jsonToStore, 'data.data_c', 'I Got The Key');
$article->json = $jsonToStore;
$article->save();
$expectedChanges = [
'attributes' => [
'json' => [
'data' => [
'data_a' => 1,
'data_b' => 2,
'data_c' => 'I Got The Key',
'data_d' => 4,
'data_e' => 5,
],
],
],
'old' => [
'json' => [
'data' => [
'data_a' => 1,
'data_b' => 2,
'data_c' => 3,
'data_d' => 4,
'data_e' => 5,
],
],
],
];
$changes = $this->getLastActivity()->changes()->toArray();
$this->assertSame($expectedChanges, $changes);
});
it('will access further than level one json attribute', function () {
$articleClass = new class() extends Article {
use LogsActivity;
protected $casts = [
'json' => 'collection',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'json->data->can->go->how->far'])
->logOnlyDirty();
}
};
$jsonToStore = [];
// data_set($jsonToStore, 'data.can.go.how.far', 'Data');
$article = new $articleClass();
$article->json = $jsonToStore;
$article->name = 'I am JSON';
$article->save();
data_set($jsonToStore, 'data.can.go.how.far', 'This far');
$article->json = $jsonToStore;
$article->save();
$expectedChanges = [
'attributes' => [
'json' => [
'data' => [
'can' => [
'go' => [
'how' => [
'far' => 'This far',
],
],
],
],
],
],
'old' => [
'json' => [
'data' => [
'can' => [
'go' => [
'how' => [
'far' => null,
],
],
],
],
],
],
];
$changes = $this->getLastActivity()->changes()->toArray();
$this->assertSame($expectedChanges, $changes);
});
function createDirtyArticle(): Article
{
$articleClass = new class() extends Article {
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text'])
->logOnlyDirty();
}
};
$article = new $articleClass();
$article->name = 'my name';
$article->save();
return $article;
}
function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['name', 'text'])
->logOnlyDirty();
}
| |
php
|
<?php
use Spatie\Activitylog\Exceptions\InvalidConfiguration;
use Spatie\Activitylog\Test\Models\Activity;
use Spatie\Activitylog\Test\Models\AnotherInvalidActivity;
use Spatie\Activitylog\Test\Models\InvalidActivity;
beforeEach(function () {
$this->activityDescription = 'My activity';
collect(range(1, 5))->each(function (int $index) {
$logName = "log{$index}";
activity($logName)->log('hello everybody');
});
});
it('can log activity using a custom model', function () {
app()['config']->set('activitylog.activity_model', Activity::class);
$activity = activity()->log($this->activityDescription);
expect($activity->description)->toEqual($this->activityDescription);
expect($activity)->toBeInstanceOf(Activity::class);
});
it('does not throw an exception when model config is null', function () {
app()['config']->set('activitylog.activity_model', null);
activity()->log($this->activityDescription);
$this->markTestAsPassed();
});
it('throws an exception when model doesnt implements activity', function () {
app()['config']->set('activitylog.activity_model', InvalidActivity::class);
$this->expectException(InvalidConfiguration::class);
activity()->log($this->activityDescription);
});
it('throws an exception when model doesnt extend model', function () {
app()['config']->set('activitylog.activity_model', AnotherInvalidActivity::class);
$this->expectException(InvalidConfiguration::class);
activity()->log($this->activityDescription);
});
it('doesnt conlict with laravel change tracking', function () {
app()['config']->set('activitylog.activity_model', Activity::class);
$properties = [
'attributes' => [
'name' => 'my name',
'text' => null,
],
];
$activity = activity()->withProperties($properties)->log($this->activityDescription);
expect($activity->changes()->toArray())->toEqual($properties);
expect($activity->custom_property->toArray())->toEqual($properties);
});
| |
php
|
<?php
use Illuminate\Support\Facades\Auth;
use Spatie\Activitylog\Exceptions\CouldNotLogActivity;
use Spatie\Activitylog\Facades\CauserResolver;
use Spatie\Activitylog\Test\Models\Article;
use Spatie\Activitylog\Test\Models\User;
it('can resolve current logged in user', function () {
Auth::login($user = User::first());
$causer = CauserResolver::resolve();
expect($causer)->toBeInstanceOf(User::class);
expect($causer->id)->toEqual($user->id);
});
it('will throw an exception if it cannot resolve user by id', function () {
$this->expectException(CouldNotLogActivity::class);
CauserResolver::resolve(9999);
});
it('can resloved user from passed id', function () {
$causer = CauserResolver::resolve(1);
expect($causer)->toBeInstanceOf(User::class);
expect($causer->id)->toEqual(1);
});
it('will resolve the provided override callback', function () {
CauserResolver::resolveUsing(fn () => Article::first());
$causer = CauserResolver::resolve();
expect($causer)->toBeInstanceOf(Article::class);
expect($causer->id)->toEqual(1);
});
it('will resolve any model', function () {
$causer = CauserResolver::resolve($article = Article::first());
expect($causer)->toBeInstanceOf(Article::class);
expect($causer->id)->toEqual($article->id);
});
| |
php
|
<?php
use Carbon\Carbon;
use Spatie\Activitylog\Models\Activity;
beforeEach(function () {
Carbon::setTestNow(Carbon::create(2016, 1, 1, 00, 00, 00));
app()['config']->set('activitylog.delete_records_older_than_days', 31);
});
it('can clean the activity log', function () {
collect(range(1, 60))->each(function (int $index) {
Activity::create([
'description' => "item {$index}",
'created_at' => Carbon::now()->subDays($index)->startOfDay(),
]);
});
expect(Activity::all())->toHaveCount(60);
Artisan::call('activitylog:clean');
expect(Activity::all())->toHaveCount(31);
$cutOffDate = Carbon::now()->subDays(31)->format('Y-m-d H:i:s');
expect(Activity::where('created_at', '<', $cutOffDate)->get())->toHaveCount(0);
});
it('can accept days as option to override config setting', function () {
collect(range(1, 60))->each(function (int $index) {
Activity::create([
'description' => "item {$index}",
'created_at' => Carbon::now()->subDays($index)->startOfDay(),
]);
});
expect(Activity::all())->toHaveCount(60);
Artisan::call('activitylog:clean', ['--days' => 7]);
expect(Activity::all())->toHaveCount(7);
$cutOffDate = Carbon::now()->subDays(7)->format('Y-m-d H:i:s');
expect(Activity::where('created_at', '<', $cutOffDate)->get())->toHaveCount(0);
});
| |
php
|
<?php
namespace Spatie\Activitylog\Test\Enums;
enum StringBackedEnum: string
{
case Published = 'published';
case Draft = 'draft';
}
| |
php
|
<?php
namespace Spatie\Activitylog\Test\Enums;
enum IntBackedEnum: int
{
case Published = 1;
case Draft = 0;
}
| |
php
|
<?php
namespace Spatie\Activitylog\Test\Enums;
enum NonBackedEnum
{
case Published;
case Draft;
}
| |
php
|
<?php
namespace Spatie\Activitylog\Test\Casts;
use Carbon\CarbonInterval;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class IntervalCasts implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes)
{
if (empty($value)) {
return null;
}
return (string) CarbonInterval::create($value);
}
public function set($model, string $key, $value, array $attributes)
{
if (empty($value)) {
return null;
}
$value = is_string($value) ? CarbonInterval::create($value) : $value;
return CarbonInterval::getDateIntervalSpec($value);
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Test\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Spatie\Activitylog\Contracts\Activity as ActivityContract;
class Activity extends Model implements ActivityContract
{
protected $table;
public $guarded = [];
protected $casts = [
'properties' => 'collection',
];
public function __construct(array $attributes = [])
{
$this->table = config('activitylog.table_name');
parent::__construct($attributes);
}
public function subject(): MorphTo
{
if (config('activitylog.subject_returns_soft_deleted_models')) {
return $this->morphTo()->withTrashed();
}
return $this->morphTo();
}
public function causer(): MorphTo
{
return $this->morphTo();
}
public function getExtraProperty(string $propertyName, mixed $defaultValue = null): mixed
{
return Arr::get($this->properties->toArray(), $propertyName, $defaultValue);
}
public function changes(): Collection
{
if (! $this->properties instanceof Collection) {
return new Collection();
}
return collect(array_filter($this->properties->toArray(), function ($key) {
return in_array($key, ['attributes', 'old']);
}, ARRAY_FILTER_USE_KEY));
}
public function scopeInLog(Builder $query, ...$logNames): Builder
{
if (is_array($logNames[0])) {
$logNames = $logNames[0];
}
return $query->whereIn('log_name', $logNames);
}
public function scopeCausedBy(Builder $query, Model $causer): Builder
{
return $query
->where('causer_type', $causer->getMorphClass())
->where('causer_id', $causer->getKey());
}
public function scopeForSubject(Builder $query, Model $subject): Builder
{
return $query
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey());
}
public function scopeForEvent(Builder $query, string $event): Builder
{
return $query->where('event', $event);
}
public function getCustomPropertyAttribute()
{
return $this->changes();
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Test\Models;
use Spatie\Activitylog\Models\Activity;
class CustomDatabaseConnectionOnActivityModel extends Activity
{
protected $connection = 'custom_connection_name';
}
| |
php
|
<?php
namespace Spatie\Activitylog\Test\Models;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
class ArticleWithLogDescriptionClosure extends Article
{
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->setDescriptionForEvent(function ($eventName) {
return $eventName;
});
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Test\Models;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
class Issue733 extends Article
{
use LogsActivity;
protected static $recordEvents = [
'retrieved',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->dontSubmitEmptyLogs()
->logOnly(['name']);
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Test\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Spatie\Activitylog\Contracts\Activity as ActivityContract;
class AnotherInvalidActivity implements ActivityContract
{
protected $table;
public $guarded = [];
protected $casts = [
'properties' => 'collection',
];
public function __construct(array $attributes = [])
{
$this->table = config('activitylog.table_name');
}
public function subject(): MorphTo
{
if (config('activitylog.subject_returns_soft_deleted_models')) {
return $this->morphTo()->withTrashed();
}
return $this->morphTo();
}
public function causer(): MorphTo
{
return $this->morphTo();
}
/**
* Get the extra properties with the given name.
*
* @param string $propertyName
* @param mixed $defaultValue
*
* @return mixed
*/
public function getExtraProperty(string $propertyName, mixed $defaultValue = null): mixed
{
return Arr::get($this->properties->toArray(), $propertyName, $defaultValue);
}
public function changes(): Collection
{
if (! $this->properties instanceof Collection) {
return new Collection();
}
return collect(array_filter($this->properties->toArray(), function ($key) {
return in_array($key, ['attributes', 'old']);
}, ARRAY_FILTER_USE_KEY));
}
public function scopeInLog(Builder $query, ...$logNames): Builder
{
if (is_array($logNames[0])) {
$logNames = $logNames[0];
}
return $query->whereIn('log_name', $logNames);
}
/**
* Scope a query to only include activities by a given causer.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Illuminate\Database\Eloquent\Model $causer
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeCausedBy(Builder $query, Model $causer): Builder
{
return $query
->where('causer_type', $causer->getMorphClass())
->where('causer_id', $causer->getKey());
}
/**
* Scope a query to only include activities for a given subject.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Illuminate\Database\Eloquent\Model $subject
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeForSubject(Builder $query, Model $subject): Builder
{
return $query
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey());
}
public function getCustomPropertyAttribute()
{
return $this->changes();
}
public function scopeForEvent(Builder $query, string $event): Builder
{
return $query->where('event', $event);
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Test\Models;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\CausesActivity;
class User extends Model implements Authenticatable
{
use CausesActivity;
protected $table = 'users';
protected $guarded = [];
protected $fillable = ['id', 'name'];
public function getAuthIdentifierName()
{
return 'id';
}
public function getAuthIdentifier()
{
$name = $this->getAuthIdentifierName();
return $this->attributes[$name];
}
public function getAuthPasswordName()
{
return 'password';
}
public function getAuthPassword()
{
return $this->attributes['password'];
}
public function getRememberToken()
{
return 'token';
}
public function setRememberToken($value)
{
}
public function getRememberTokenName()
{
return 'tokenName';
}
public function articles()
{
return $this->hasMany(Article::class);
}
public function latestArticle()
{
return $this->hasOne(Article::class)->latest()->limit(1);
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Test\Models;
use Spatie\Activitylog\Models\Activity;
class CustomTableNameOnActivityModel extends Activity
{
protected $table = 'custom_table_name';
}
| |
php
|
<?php
namespace Spatie\Activitylog\Test\Models;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
protected $table = 'articles';
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function getOwnerNameAttribute()
{
return $this->user?->name;
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Test\Models;
use Illuminate\Database\Eloquent\Model;
class InvalidActivity extends Model
{
}
| |
php
|
<?php
return [
/*
* If set to false, no activities will be saved to the database.
*/
'enabled' => env('ACTIVITY_LOGGER_ENABLED', true),
/*
* When the clean-command is executed, all recording activities older than
* the number of days specified here will be deleted.
*/
'delete_records_older_than_days' => 365,
/*
* If no log name is passed to the activity() helper
* we use this default log name.
*/
'default_log_name' => 'default',
/*
* You can specify an auth driver here that gets user models.
* If this is null we'll use the current Laravel auth driver.
*/
'default_auth_driver' => null,
/*
* If set to true, the subject returns soft deleted models.
*/
'subject_returns_soft_deleted_models' => false,
/*
* This model will be used to log activity.
* It should implement the Spatie\Activitylog\Contracts\Activity interface
* and extend Illuminate\Database\Eloquent\Model.
*/
'activity_model' => \Spatie\Activitylog\Models\Activity::class,
/*
* This is the name of the table that will be created by the migration and
* used by the Activity model shipped with this package.
*/
'table_name' => env('ACTIVITY_LOGGER_TABLE_NAME', 'activity_log'),
/*
* This is the database connection that will be used by the migration and
* the Activity model shipped with this package. In case it's not set
* Laravel's database.default will be used instead.
*/
'database_connection' => env('ACTIVITY_LOGGER_DB_CONNECTION'),
];
| |
php
|
<?php
namespace Spatie\Activitylog;
use Closure;
use Illuminate\Auth\AuthManager;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Exceptions\CouldNotLogActivity;
class CauserResolver
{
protected AuthManager $authManager;
protected string | null $authDriver;
protected Closure | null $resolverOverride = null;
protected Model | null $causerOverride = null;
public function __construct(Repository $config, AuthManager $authManager)
{
$this->authManager = $authManager;
$this->authDriver = $config['activitylog']['default_auth_driver'];
}
public function resolve(Model | int | string | null $subject = null): ?Model
{
if ($this->causerOverride !== null) {
return $this->causerOverride;
}
if ($this->resolverOverride !== null) {
$resultCauser = ($this->resolverOverride)($subject);
if (! $this->isResolvable($resultCauser)) {
throw CouldNotLogActivity::couldNotDetermineUser($resultCauser);
}
return $resultCauser;
}
return $this->getCauser($subject);
}
protected function resolveUsingId(int | string $subject): Model
{
$guard = $this->authManager->guard($this->authDriver);
$provider = method_exists($guard, 'getProvider') ? $guard->getProvider() : null;
$model = method_exists($provider, 'retrieveById') ? $provider->retrieveById($subject) : null;
throw_unless($model instanceof Model, CouldNotLogActivity::couldNotDetermineUser($subject));
return $model;
}
protected function getCauser(Model | int | string | null $subject = null): ?Model
{
if ($subject instanceof Model) {
return $subject;
}
if (is_null($subject)) {
return $this->getDefaultCauser();
}
return $this->resolveUsingId($subject);
}
/**
* Override the resover using callback.
*/
public function resolveUsing(Closure $callback): static
{
$this->resolverOverride = $callback;
return $this;
}
/**
* Override default causer.
*/
public function setCauser(?Model $causer): static
{
$this->causerOverride = $causer;
return $this;
}
protected function isResolvable(mixed $model): bool
{
return $model instanceof Model || is_null($model);
}
protected function getDefaultCauser(): ?Model
{
return $this->authManager->guard($this->authDriver)->user();
}
}
| |
php
|
<?php
namespace Spatie\Activitylog;
use Illuminate\Database\Eloquent\Model;
class EventLogBag
{
public function __construct(
public string $event,
public Model $model,
public array $changes,
public ?LogOptions $options = null
) {
$this->options ??= $model->getActivitylogOptions();
}
}
| |
php
|
<?php
namespace Spatie\Activitylog;
use Closure;
use Ramsey\Uuid\Uuid;
class LogBatch
{
public ?string $uuid = null;
public int $transactions = 0;
protected function generateUuid(): string
{
return Uuid::uuid4()->toString();
}
public function getUuid(): ?string
{
return $this->uuid;
}
public function setBatch(string $uuid): void
{
$this->uuid = $uuid;
$this->transactions = 1;
}
public function withinBatch(Closure $callback): mixed
{
$this->startBatch();
$result = $callback($this->getUuid());
$this->endBatch();
return $result;
}
public function startBatch(): void
{
if (! $this->isOpen()) {
$this->uuid = $this->generateUuid();
}
$this->transactions++;
}
public function isOpen(): bool
{
return $this->transactions > 0;
}
public function endBatch(): void
{
$this->transactions = max(0, $this->transactions - 1);
if ($this->transactions === 0) {
$this->uuid = null;
}
}
}
| |
php
|
<?php
namespace Spatie\Activitylog;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Contracts\Activity;
use Spatie\Activitylog\Contracts\Activity as ActivityContract;
use Spatie\Activitylog\Exceptions\InvalidConfiguration;
use Spatie\Activitylog\Models\Activity as ActivityModel;
use Spatie\LaravelPackageTools\Package;
use Spatie\LaravelPackageTools\PackageServiceProvider;
class ActivitylogServiceProvider extends PackageServiceProvider
{
public function configurePackage(Package $package): void
{
$package
->name('laravel-activitylog')
->hasConfigFile('activitylog')
->hasMigrations([
'create_activity_log_table',
'add_event_column_to_activity_log_table',
'add_batch_uuid_column_to_activity_log_table',
])
->hasCommand(CleanActivitylogCommand::class);
}
public function registeringPackage()
{
$this->app->bind(ActivityLogger::class);
$this->app->scoped(LogBatch::class);
$this->app->scoped(CauserResolver::class);
$this->app->scoped(ActivityLogStatus::class);
}
public static function determineActivityModel(): string
{
$activityModel = config('activitylog.activity_model') ?? ActivityModel::class;
if (! is_a($activityModel, Activity::class, true)
|| ! is_a($activityModel, Model::class, true)) {
throw InvalidConfiguration::modelIsNotValid($activityModel);
}
return $activityModel;
}
public static function getActivityModelInstance(): ActivityContract
{
$activityModelClassName = self::determineActivityModel();
return new $activityModelClassName();
}
}
| |
php
|
<?php
namespace Spatie\Activitylog;
use Closure;
class LogOptions
{
public ?string $logName = null;
public bool $submitEmptyLogs = true;
public bool $logFillable = false;
public bool $logOnlyDirty = false;
public bool $logUnguarded = false;
public array $logAttributes = [];
public array $logExceptAttributes = [];
public array $dontLogIfAttributesChangedOnly = [];
public array $attributeRawValues = [];
public ?Closure $descriptionForEvent = null;
/**
* Start configuring model with the default options.
*/
public static function defaults(): self
{
return new static();
}
/**
* Log all attributes on the model.
*/
public function logAll(): self
{
return $this->logOnly(['*']);
}
/**
* Log all attributes that are not listed in $guarded.
*/
public function logUnguarded(): self
{
$this->logUnguarded = true;
return $this;
}
/**
* log changes to all the $fillable attributes of the model.
*/
public function logFillable(): self
{
$this->logFillable = true;
return $this;
}
/**
* Stop logging $fillable attributes of the model.
*/
public function dontLogFillable(): self
{
$this->logFillable = false;
return $this;
}
/**
* Log changes that has actually changed after the update.
*/
public function logOnlyDirty(): self
{
$this->logOnlyDirty = true;
return $this;
}
/**
* Log changes only if these attributes changed.
*/
public function logOnly(array $attributes): self
{
$this->logAttributes = $attributes;
return $this;
}
/**
* Exclude these attributes from being logged.
*/
public function logExcept(array $attributes): self
{
$this->logExceptAttributes = $attributes;
return $this;
}
/**
* Don't trigger an activity if these attributes changed logged.
*/
public function dontLogIfAttributesChangedOnly(array $attributes): self
{
$this->dontLogIfAttributesChangedOnly = $attributes;
return $this;
}
/**
* Don't store empty logs. Storing empty logs can happen when you only
* want to log a certain attribute but only another changes.
*/
public function dontSubmitEmptyLogs(): self
{
$this->submitEmptyLogs = false;
return $this;
}
/**
* Allow storing empty logs. Storing empty logs can happen when you only
* want to log a certain attribute but only another changes.
*/
public function submitEmptyLogs(): self
{
$this->submitEmptyLogs = true;
return $this;
}
/**
* Customize log name.
*/
public function useLogName(?string $logName): self
{
$this->logName = $logName;
return $this;
}
/**
* Customize log description using callback.
*/
public function setDescriptionForEvent(Closure $callback): self
{
$this->descriptionForEvent = $callback;
return $this;
}
/**
* Exclude these attributes from being casted.
*/
public function useAttributeRawValues(array $attributes): self
{
$this->attributeRawValues = $attributes;
return $this;
}
}
| |
php
|
<?php
use Spatie\Activitylog\ActivityLogger;
use Spatie\Activitylog\PendingActivityLog;
if (! function_exists('activity')) {
function activity(?string $logName = null): ActivityLogger
{
/** @var PendingActivityLog $log */
$log = app(PendingActivityLog::class);
if ($logName) {
$log->useLog($logName);
}
return $log->logger();
}
}
| |
php
|
<?php
namespace Spatie\Activitylog;
use Illuminate\Support\Traits\ForwardsCalls;
/**
* @mixin \Spatie\Activitylog\ActivityLogger
*/
class PendingActivityLog
{
use ForwardsCalls;
protected ActivityLogger $logger;
public function __construct(ActivityLogger $logger, ActivityLogStatus $status)
{
$this->logger = $logger
->setLogStatus($status)
->useLog(config('activitylog.default_log_name'));
}
public function logger(): ActivityLogger
{
return $this->logger;
}
public function __call(string $method, array $parameters): mixed
{
return $this->forwardCallTo($this->logger, $method, $parameters);
}
}
| |
php
|
<?php
namespace Spatie\Activitylog;
use Illuminate\Contracts\Config\Repository;
class ActivityLogStatus
{
protected $enabled = true;
public function __construct(Repository $config)
{
$this->enabled = $config['activitylog.enabled'];
}
public function enable(): bool
{
return $this->enabled = true;
}
public function disable(): bool
{
return $this->enabled = false;
}
public function disabled(): bool
{
return $this->enabled === false;
}
}
| |
php
|
<?php
namespace Spatie\Activitylog;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
use Illuminate\Database\Eloquent\Builder;
class CleanActivitylogCommand extends Command
{
use ConfirmableTrait;
protected $signature = 'activitylog:clean
{log? : (optional) The log name that will be cleaned.}
{--days= : (optional) Records older than this number of days will be cleaned.}
{--force : (optional) Force the operation to run when in production.}';
protected $description = 'Clean up old records from the activity log.';
public function handle()
{
if (! $this->confirmToProceed()) {
return 1;
}
$this->comment('Cleaning activity log...');
$log = $this->argument('log');
$maxAgeInDays = $this->option('days') ?? config('activitylog.delete_records_older_than_days');
$cutOffDate = Carbon::now()->subDays($maxAgeInDays)->format('Y-m-d H:i:s');
$activity = ActivitylogServiceProvider::getActivityModelInstance();
$amountDeleted = $activity::query()
->where('created_at', '<', $cutOffDate)
->when($log !== null, function (Builder $query) use ($log) {
$query->inLog($log);
})
->delete();
$this->info("Deleted {$amountDeleted} record(s) from the activity log.");
$this->comment('All done!');
}
}
| |
php
|
<?php
namespace Spatie\Activitylog;
use Closure;
use DateTimeInterface;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Conditionable;
use Illuminate\Support\Traits\Macroable;
use Spatie\Activitylog\Contracts\Activity as ActivityContract;
class ActivityLogger
{
use Conditionable;
use Macroable;
protected ?string $defaultLogName = null;
protected CauserResolver $causerResolver;
protected ActivityLogStatus $logStatus;
protected ?ActivityContract $activity = null;
protected LogBatch $batch;
public function __construct(Repository $config, ActivityLogStatus $logStatus, LogBatch $batch, CauserResolver $causerResolver)
{
$this->causerResolver = $causerResolver;
$this->batch = $batch;
$this->defaultLogName = $config['activitylog']['default_log_name'];
$this->logStatus = $logStatus;
}
public function setLogStatus(ActivityLogStatus $logStatus): static
{
$this->logStatus = $logStatus;
return $this;
}
public function performedOn(Model $model): static
{
$this->getActivity()->subject()->associate($model);
return $this;
}
public function on(Model $model): static
{
return $this->performedOn($model);
}
public function causedBy(Model | int | string | null $modelOrId): static
{
if ($modelOrId === null) {
return $this;
}
$model = $this->causerResolver->resolve($modelOrId);
$this->getActivity()->causer()->associate($model);
return $this;
}
public function by(Model | int | string | null $modelOrId): static
{
return $this->causedBy($modelOrId);
}
public function causedByAnonymous(): static
{
$this->activity->causer_id = null;
$this->activity->causer_type = null;
return $this;
}
public function byAnonymous(): static
{
return $this->causedByAnonymous();
}
public function event(string $event): static
{
return $this->setEvent($event);
}
public function setEvent(string $event): static
{
$this->activity->event = $event;
return $this;
}
public function withProperties(mixed $properties): static
{
$this->getActivity()->properties = collect($properties);
return $this;
}
public function withProperty(string $key, mixed $value): static
{
$this->getActivity()->properties = $this->getActivity()->properties->put($key, $value);
return $this;
}
public function createdAt(DateTimeInterface $dateTime): static
{
$this->getActivity()->created_at = Carbon::instance($dateTime);
return $this;
}
public function useLog(?string $logName): static
{
$this->getActivity()->log_name = $logName;
return $this;
}
public function inLog(?string $logName): static
{
return $this->useLog($logName);
}
public function tap(callable $callback, ?string $eventName = null): static
{
call_user_func($callback, $this->getActivity(), $eventName);
return $this;
}
public function enableLogging(): static
{
$this->logStatus->enable();
return $this;
}
public function disableLogging(): static
{
$this->logStatus->disable();
return $this;
}
public function log(string $description): ?ActivityContract
{
if ($this->logStatus->disabled()) {
return null;
}
$activity = $this->activity;
$activity->description = $this->replacePlaceholders(
$activity->description ?? $description,
$activity
);
if (isset($activity->subject) && method_exists($activity->subject, 'tapActivity')) {
$this->tap([$activity->subject, 'tapActivity'], $activity->event ?? '');
}
$activity->save();
$this->activity = null;
return $activity;
}
public function withoutLogs(Closure $callback): mixed
{
if ($this->logStatus->disabled()) {
return $callback();
}
$this->logStatus->disable();
try {
return $callback();
} finally {
$this->logStatus->enable();
}
}
protected function replacePlaceholders(string $description, ActivityContract $activity): string
{
return preg_replace_callback('/:[a-z0-9._-]+(?<![.])/i', function ($match) use ($activity) {
$match = $match[0];
$attribute = Str::before(Str::after($match, ':'), '.');
if (! in_array($attribute, ['subject', 'causer', 'properties'])) {
return $match;
}
$propertyName = substr($match, strpos($match, '.') + 1);
$attributeValue = $activity->$attribute;
if (is_null($attributeValue)) {
return $match;
}
return data_get($attributeValue, $propertyName, $match);
}, $description);
}
protected function getActivity(): ActivityContract
{
if (! $this->activity instanceof ActivityContract) {
$this->activity = ActivitylogServiceProvider::getActivityModelInstance();
$this
->useLog($this->defaultLogName)
->withProperties([])
->causedBy($this->causerResolver->resolve());
$this->activity->batch_uuid = $this->batch->getUuid();
}
return $this->activity;
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Traits;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Spatie\Activitylog\ActivitylogServiceProvider;
use Spatie\Activitylog\Models\Activity;
trait CausesActivity
{
/** @return MorphMany<Activity, $this> */
public function actions(): MorphMany
{
return $this->morphMany(
ActivitylogServiceProvider::determineActivityModel(),
'causer'
);
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Traits;
use Carbon\CarbonInterval;
use DateInterval;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Pipeline\Pipeline;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Spatie\Activitylog\ActivityLogger;
use Spatie\Activitylog\ActivitylogServiceProvider;
use Spatie\Activitylog\ActivityLogStatus;
use Spatie\Activitylog\Contracts\LoggablePipe;
use Spatie\Activitylog\EventLogBag;
use Spatie\Activitylog\LogOptions;
trait LogsActivity
{
public static array $changesPipes = [];
protected array $oldAttributes = [];
protected ?LogOptions $activitylogOptions;
public bool $enableLoggingModelsEvents = true;
abstract public function getActivitylogOptions(): LogOptions;
protected static function bootLogsActivity(): void
{
// Hook into eloquent events that only specified in $eventToBeRecorded array,
// checking for "updated" event hook explicitly to temporary hold original
// attributes on the model as we'll need them later to compare against.
static::eventsToBeRecorded()->each(function ($eventName) {
if ($eventName === 'updated') {
static::updating(function (Model $model) {
$oldValues = (new static())->setRawAttributes($model->getRawOriginal());
$model->oldAttributes = static::logChanges($oldValues);
});
}
static::$eventName(function (Model $model) use ($eventName) {
$model->activitylogOptions = $model->getActivitylogOptions();
if (! $model->shouldLogEvent($eventName)) {
return;
}
$changes = $model->attributeValuesToBeLogged($eventName);
$description = $model->getDescriptionForEvent($eventName);
$logName = $model->getLogNameToUse();
// Submitting empty description will cause place holder replacer to fail.
if ($description == '') {
return;
}
if ($model->isLogEmpty($changes) && ! $model->activitylogOptions->submitEmptyLogs) {
return;
}
// User can define a custom pipelines to mutate, add or remove from changes
// each pipe receives the event carrier bag with changes and the model in
// question every pipe should manipulate new and old attributes.
$event = app(Pipeline::class)
->send(new EventLogBag($eventName, $model, $changes, $model->activitylogOptions))
->through(static::$changesPipes)
->thenReturn();
// Actual logging
$logger = app(ActivityLogger::class)
->useLog($logName)
->event($eventName)
->performedOn($model)
->withProperties($event->changes);
if (method_exists($model, 'tapActivity')) {
$logger->tap([$model, 'tapActivity'], $eventName);
}
$logger->log($description);
// Reset log options so the model can be serialized.
$model->activitylogOptions = null;
});
});
}
public static function addLogChange(LoggablePipe $pipe): void
{
static::$changesPipes[] = $pipe;
}
public function isLogEmpty(array $changes): bool
{
return empty($changes['attributes'] ?? []) && empty($changes['old'] ?? []);
}
public function disableLogging(): self
{
$this->enableLoggingModelsEvents = false;
return $this;
}
public function enableLogging(): self
{
$this->enableLoggingModelsEvents = true;
return $this;
}
public function activities(): MorphMany
{
return $this->morphMany(ActivitylogServiceProvider::determineActivityModel(), 'subject');
}
public function getDescriptionForEvent(string $eventName): string
{
if (! empty($this->activitylogOptions->descriptionForEvent)) {
return ($this->activitylogOptions->descriptionForEvent)($eventName);
}
return $eventName;
}
public function getLogNameToUse(): ?string
{
if (! empty($this->activitylogOptions->logName)) {
return $this->activitylogOptions->logName;
}
return config('activitylog.default_log_name');
}
/**
* Get the event names that should be recorded.
**/
protected static function eventsToBeRecorded(): Collection
{
if (isset(static::$recordEvents)) {
return collect(static::$recordEvents);
}
$events = collect([
'created',
'updated',
'deleted',
]);
if (collect(class_uses_recursive(static::class))->contains(SoftDeletes::class)) {
$events->push('restored');
}
return $events;
}
protected function shouldLogEvent(string $eventName): bool
{
$logStatus = app(ActivityLogStatus::class);
if (! $this->enableLoggingModelsEvents || $logStatus->disabled()) {
return false;
}
if (! in_array($eventName, ['created', 'updated'])) {
return true;
}
// Do not log update event if the model is restoring
if ($this->isRestoring()) {
return false;
}
// Do not log update event if only ignored attributes are changed.
return (bool) count(Arr::except($this->getDirty(), $this->activitylogOptions->dontLogIfAttributesChangedOnly));
}
/**
* Determines if the model is restoring.
**/
protected function isRestoring(): bool
{
$deletedAtColumn = method_exists($this, 'getDeletedAtColumn')
? $this->getDeletedAtColumn()
: 'deleted_at';
return $this->isDirty($deletedAtColumn) && count($this->getDirty()) === 1;
}
/**
* Determines what attributes needs to be logged based on the configuration.
**/
public function attributesToBeLogged(): array
{
$this->activitylogOptions = $this->getActivitylogOptions();
$attributes = [];
// Check if fillable attributes will be logged then merge it to the local attributes array.
if ($this->activitylogOptions->logFillable) {
$attributes = array_merge($attributes, $this->getFillable());
}
// Determine if unguarded attributes will be logged.
if ($this->shouldLogUnguarded()) {
// Get only attribute names, not intrested in the values here then guarded
// attributes. get only keys than not present in guarded array, because
// we are logging the unguarded attributes and we cant have both!
$attributes = array_merge($attributes, array_diff(array_keys($this->getAttributes()), $this->getGuarded()));
}
if (! empty($this->activitylogOptions->logAttributes)) {
// Filter * from the logAttributes because will deal with it separately
$attributes = array_merge($attributes, array_diff($this->activitylogOptions->logAttributes, ['*']));
// If there's * get all attributes then merge it, dont respect $guarded or $fillable.
if (in_array('*', $this->activitylogOptions->logAttributes)) {
$attributes = array_merge($attributes, array_keys($this->getAttributes()));
}
}
if ($this->activitylogOptions->logExceptAttributes) {
// Filter out the attributes defined in ignoredAttributes out of the local array
$attributes = array_diff($attributes, $this->activitylogOptions->logExceptAttributes);
}
return $attributes;
}
public function shouldLogUnguarded(): bool
{
if (! $this->activitylogOptions->logUnguarded) {
return false;
}
// This case means all of the attributes are guarded
// so we'll not have any unguarded anyway.
if (in_array('*', $this->getGuarded())) {
return false;
}
return true;
}
/**
* Determines values that will be logged based on the difference.
**/
public function attributeValuesToBeLogged(string $processingEvent): array
{
// no loggable attributes, no values to be logged!
if (! count($this->attributesToBeLogged())) {
return [];
}
$properties['attributes'] = static::logChanges(
// if the current event is retrieved, get the model itself
// else get the fresh default properties from database
// as wouldn't be part of the saved model instance.
$processingEvent == 'retrieved'
? $this
: (
$this->exists
? $this->fresh() ?? $this
: $this
)
);
if (static::eventsToBeRecorded()->contains('updated') && $processingEvent == 'updated') {
// Fill the attributes with null values.
$nullProperties = array_fill_keys(array_keys($properties['attributes']), null);
// Populate the old key with keys from database and from old attributes.
$properties['old'] = array_merge($nullProperties, $this->oldAttributes);
// Fail safe.
$this->oldAttributes = [];
}
if ($this->activitylogOptions->logOnlyDirty && isset($properties['old'])) {
// Get difference between the old and new attributes.
$properties['attributes'] = array_udiff_assoc(
$properties['attributes'],
$properties['old'],
function ($new, $old) {
// Strict check for php's weird behaviors
if ($old === null || $new === null) {
return $new === $old ? 0 : 1;
}
// Handles Date interval comparisons since php cannot use spaceship
// Operator to compare them and will throw ErrorException.
if ($old instanceof DateInterval) {
return CarbonInterval::make($old)->equalTo($new) ? 0 : 1;
} elseif ($new instanceof DateInterval) {
return CarbonInterval::make($new)->equalTo($old) ? 0 : 1;
}
return $new <=> $old;
}
);
$properties['old'] = collect($properties['old'])
->only(array_keys($properties['attributes']))
->all();
}
if (static::eventsToBeRecorded()->contains('deleted') && $processingEvent == 'deleted') {
$properties['old'] = $properties['attributes'];
unset($properties['attributes']);
}
return $properties;
}
public static function logChanges(Model $model): array
{
$changes = [];
$attributes = $model->attributesToBeLogged();
foreach ($attributes as $attribute) {
if (Str::contains($attribute, '.')) {
$changes += self::getRelatedModelAttributeValue($model, $attribute);
continue;
}
if (Str::contains($attribute, '->')) {
Arr::set(
$changes,
str_replace('->', '.', $attribute),
static::getModelAttributeJsonValue($model, $attribute)
);
continue;
}
$changes[$attribute] = in_array($attribute, $model->activitylogOptions->attributeRawValues)
? $model->getAttributeFromArray($attribute)
: $model->getAttribute($attribute);
if (is_null($changes[$attribute])) {
continue;
}
if ($model->isDateAttribute($attribute)) {
$changes[$attribute] = $model->serializeDate(
$model->asDateTime($changes[$attribute])
);
}
if ($model->hasCast($attribute)) {
$cast = $model->getCasts()[$attribute];
if ($model->isEnumCastable($attribute)) {
try {
$changes[$attribute] = $model->getStorableEnumValue($changes[$attribute]);
} catch (\ArgumentCountError $e) {
// In Laravel 11, this method has an extra argument
// https://github.com/laravel/framework/pull/47465
$changes[$attribute] = $model->getStorableEnumValue($cast, $changes[$attribute]);
}
}
if ($model->isCustomDateTimeCast($cast) || $model->isImmutableCustomDateTimeCast($cast)) {
$changes[$attribute] = $model->asDateTime($changes[$attribute])->format(explode(':', $cast, 2)[1]);
}
}
}
return $changes;
}
protected static function getRelatedModelAttributeValue(Model $model, string $attribute): array
{
$relatedModelNames = explode('.', $attribute);
$relatedAttribute = array_pop($relatedModelNames);
$attributeName = [];
$relatedModel = $model;
do {
$attributeName[] = $relatedModelName = static::getRelatedModelRelationName($relatedModel, array_shift($relatedModelNames));
$relatedModel = $relatedModel->$relatedModelName ?? $relatedModel->$relatedModelName();
} while (! empty($relatedModelNames));
$attributeName[] = $relatedAttribute;
return [implode('.', $attributeName) => $relatedModel->$relatedAttribute ?? null];
}
protected static function getRelatedModelRelationName(Model $model, string $relation): string
{
return Arr::first([
$relation,
Str::snake($relation),
Str::camel($relation),
], function (string $method) use ($model): bool {
return method_exists($model, $method);
}, $relation);
}
protected static function getModelAttributeJsonValue(Model $model, string $attribute): mixed
{
$path = explode('->', $attribute);
$modelAttribute = array_shift($path);
$modelAttribute = collect($model->getAttribute($modelAttribute));
return data_get($modelAttribute, implode('.', $path));
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Facades;
use Illuminate\Support\Facades\Facade;
use Spatie\Activitylog\PendingActivityLog;
/**
* @method static \Spatie\Activitylog\ActivityLogger setLogStatus(\Spatie\Activitylog\ActivityLogStatus $logStatus)
* @method static \Spatie\Activitylog\ActivityLogger performedOn(\Illuminate\Database\Eloquent\Model $model)
* @method static \Spatie\Activitylog\ActivityLogger on(\Illuminate\Database\Eloquent\Model $model)
* @method static \Spatie\Activitylog\ActivityLogger causedBy(\Illuminate\Database\Eloquent\Model|string|int|null $modelOrId)
* @method static \Spatie\Activitylog\ActivityLogger by(\Illuminate\Database\Eloquent\Model|string|int|null $modelOrId)
* @method static \Spatie\Activitylog\ActivityLogger causedByAnonymous()
* @method static \Spatie\Activitylog\ActivityLogger byAnonymous()
* @method static \Spatie\Activitylog\ActivityLogger event(string $event)
* @method static \Spatie\Activitylog\ActivityLogger setEvent(string $event)
* @method static \Spatie\Activitylog\ActivityLogger withProperties(mixed $properties)
* @method static \Spatie\Activitylog\ActivityLogger withProperty(string $key, mixed $value)
* @method static \Spatie\Activitylog\ActivityLogger createdAt(\DateTimeInterface $dateTime)
* @method static \Spatie\Activitylog\ActivityLogger useLog(string|null $logName)
* @method static \Spatie\Activitylog\ActivityLogger inLog(string|null $logName)
* @method static \Spatie\Activitylog\ActivityLogger tap(callable $callback, string|null $eventName = null)
* @method static \Spatie\Activitylog\ActivityLogger enableLogging()
* @method static \Spatie\Activitylog\ActivityLogger disableLogging()
* @method static \Spatie\Activitylog\Contracts\Activity|null log(string $description)
* @method static mixed withoutLogs(\Closure $callback)
* @method static \Spatie\Activitylog\ActivityLogger|mixed when(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static \Spatie\Activitylog\ActivityLogger|mixed unless(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Spatie\Activitylog\PendingActivityLog
*/
class Activity extends Facade
{
protected static function getFacadeAccessor(): string
{
return PendingActivityLog::class;
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Facades;
use Illuminate\Support\Facades\Facade;
use Spatie\Activitylog\CauserResolver as ActivitylogCauserResolver;
/**
* @method static \Illuminate\Database\Eloquent\Model|null resolve(\Illuminate\Database\Eloquent\Model|int|string|null $subject = null)
* @method static \Spatie\Activitylog\CauserResolver resolveUsing(\Closure $callback)
* @method static \Spatie\Activitylog\CauserResolver setCauser(\Illuminate\Database\Eloquent\Model|null $causer)
*
* @see \Spatie\Activitylog\CauserResolver
*/
class CauserResolver extends Facade
{
protected static function getFacadeAccessor(): string
{
return ActivitylogCauserResolver::class;
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Facades;
use Illuminate\Support\Facades\Facade;
use Spatie\Activitylog\LogBatch as ActivityLogBatch;
/**
* @method static string getUuid()
* @method static mixed withinBatch(\Closure $callback)
* @method static void startBatch()
* @method static void setBatch(string $uuid): void
* @method static bool isOpen()
* @method static void endBatch()
*
* @see \Spatie\Activitylog\LogBatch
*/
class LogBatch extends Facade
{
protected static function getFacadeAccessor(): string
{
return ActivityLogBatch::class;
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Contracts;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Collection;
interface Activity
{
public function subject(): MorphTo;
public function causer(): MorphTo;
public function getExtraProperty(string $propertyName, mixed $defaultValue): mixed;
public function changes(): Collection;
public function scopeInLog(Builder $query, ...$logNames): Builder;
public function scopeCausedBy(Builder $query, Model $causer): Builder;
public function scopeForEvent(Builder $query, string $event): Builder;
public function scopeForSubject(Builder $query, Model $subject): Builder;
}
| |
php
|
<?php
namespace Spatie\Activitylog\Contracts;
use Closure;
use Spatie\Activitylog\EventLogBag;
interface LoggablePipe
{
public function handle(EventLogBag $event, Closure $next): EventLogBag;
}
| |
php
|
<?php
namespace Spatie\Activitylog\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Spatie\Activitylog\Contracts\Activity as ActivityContract;
/**
* Spatie\Activitylog\Models\Activity.
*
* @property int $id
* @property string|null $log_name
* @property string $description
* @property string|null $subject_type
* @property int|null $subject_id
* @property string|null $causer_type
* @property int|null $causer_id
* @property string|null $event
* @property string|null $batch_uuid
* @property \Illuminate\Support\Collection|null $properties
* @property \Carbon\Carbon|null $created_at
* @property \Carbon\Carbon|null $updated_at
* @property-read \Illuminate\Database\Eloquent\Model|\Eloquent|null $causer
* @property-read \Illuminate\Support\Collection $changes
* @property-read \Illuminate\Database\Eloquent\Model|\Eloquent|null $subject
*
* @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity causedBy(\Illuminate\Database\Eloquent\Model $causer)
* @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity forBatch(string $batchUuid)
* @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity forEvent(string $event)
* @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity forSubject(\Illuminate\Database\Eloquent\Model $subject)
* @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity hasBatch()
* @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity inLog($logNames)
* @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\Spatie\Activitylog\Models\Activity query()
*/
class Activity extends Model implements ActivityContract
{
public $guarded = [];
protected $casts = [
'properties' => 'collection',
];
public function __construct(array $attributes = [])
{
if (! isset($this->connection)) {
$this->setConnection(config('activitylog.database_connection'));
}
if (! isset($this->table)) {
$this->setTable(config('activitylog.table_name'));
}
parent::__construct($attributes);
}
/**
* @return MorphTo<Model, $this>
*/
public function subject(): MorphTo
{
if (config('activitylog.subject_returns_soft_deleted_models')) {
return $this->morphTo()->withTrashed();
}
return $this->morphTo();
}
/**
* @return MorphTo<Model, $this>
*/
public function causer(): MorphTo
{
return $this->morphTo();
}
public function getExtraProperty(string $propertyName, mixed $defaultValue = null): mixed
{
return Arr::get($this->properties->toArray(), $propertyName, $defaultValue);
}
public function changes(): Collection
{
if (! $this->properties instanceof Collection) {
return new Collection();
}
return $this->properties->only(['attributes', 'old']);
}
public function getChangesAttribute(): Collection
{
return $this->changes();
}
public function scopeInLog(Builder $query, ...$logNames): Builder
{
if (is_array($logNames[0])) {
$logNames = $logNames[0];
}
return $query->whereIn('log_name', $logNames);
}
public function scopeCausedBy(Builder $query, Model $causer): Builder
{
return $query
->where('causer_type', $causer->getMorphClass())
->where('causer_id', $causer->getKey());
}
public function scopeForSubject(Builder $query, Model $subject): Builder
{
return $query
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey());
}
public function scopeForEvent(Builder $query, string $event): Builder
{
return $query->where('event', $event);
}
public function scopeHasBatch(Builder $query): Builder
{
return $query->whereNotNull('batch_uuid');
}
public function scopeForBatch(Builder $query, string $batchUuid): Builder
{
return $query->where('batch_uuid', $batchUuid);
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Exceptions;
use Exception;
class CouldNotLogActivity extends Exception
{
public static function couldNotDetermineUser($id): self
{
return new static("Could not determine a user with identifier `{$id}`.");
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Exceptions;
use Exception;
class CouldNotLogChanges extends Exception
{
public static function invalidAttribute($attribute): self
{
return new static("Cannot log attribute `{$attribute}`. Can only log attributes of a model or a directly related model.");
}
}
| |
php
|
<?php
namespace Spatie\Activitylog\Exceptions;
use Exception;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Contracts\Activity;
class InvalidConfiguration extends Exception
{
public static function modelIsNotValid(string $className): self
{
return new static("The given model class `{$className}` does not implement `".Activity::class.'` or it does not extend `'.Model::class.'`');
}
}
| |
php
|
<?php
$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
// This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Lumen
// application without having installed a "real" server software here.
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
return false;
}
require_once __DIR__.'/public/index.php';
| |
php
|
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Model::unguard();
// $this->call('UserTableSeeder');
Model::reguard();
}
}
| |
php
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateClicksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('clicks', function(Blueprint $table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('ip');
$table->string('country')->nullable();
$table->string('referer')->nullable();
$table->string('referer_host')->nullable();
$table->text('user_agent')->nullable();
$table->integer('link_id')->unsigned();
$table->index('ip');
$table->index('referer_host');
$table->index('link_id');
$table->foreign('link_id')->references('id')->on('links')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('clicks');
}
}
| |
php
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLinkTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('links', function(Blueprint $table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('short_url');
$table->longText('long_url');
$table->string('ip');
$table->string('creator');
$table->string('clicks')->default(0);
$table->string('secret_key');
$table->boolean('is_disabled')->default(0);
$table->boolean('is_custom')->default(0);
$table->boolean('is_api')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('links');
}
}
| |
php
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddLinkTableIndexes extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('links', function (Blueprint $table)
{
// Add long_url hashes
$table->unique('short_url');
$table->string('long_url_hash', 10)->nullable();
$table->index('long_url_hash', 'links_long_url_index');
});
// MySQL only statement
// DB::statement("UPDATE links SET long_url_hash = crc32(long_url);");
DB::table('links')->select(['id', 'long_url_hash', 'long_url'])
->chunk(100, function($links) {
foreach ($links as $link) {
DB::table('links')
->where('id', $link->id)
->update([
'long_url_hash' => sprintf('%u', crc32($link->long_url))
]);
}
});
}
public function down()
{
Schema::table('links', function (Blueprint $table)
{
$table->dropUnique('links_short_url_unique');
$table->dropIndex('links_long_url_index');
$table->dropColumn('long_url_hash');
});
}
}
| |
php
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('username')->unique();
$table->string('password');
$table->string('email');
$table->text('ip');
$table->string('recovery_key');
$table->string('role');
$table->string('active');
$table->string('api_key')->nullable();
$table->boolean('api_active')->default(0);
$table->string('api_quota')->default(60);
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
| |
php
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterLinkClicksToInteger extends Migration
{
/**
* Run the migrations.
* Changes the "clicks" field in the link table to
* an integer field rather than a string field.
*
* @return void
*/
public function up()
{
Schema::table('links', function (Blueprint $table)
{
$table->integer('clicks')->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('links', function (Blueprint $table)
{
$table->string('clicks')->change();
});
}
}
| |
php
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateApiQuotaIndex extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('links', function (Blueprint $table)
{
$table->index(
['created_at', 'creator', 'is_api'],
'api_quota_index'
);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('links', function (Blueprint $table)
{
$table->dropIndex('api_quota_index');
});
}
}
| |
php
|
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
$factory->define(App\User::class, function ($faker) {
return [
'name' => $faker->name,
'email' => $faker->email,
'password' => str_random(10),
'remember_token' => str_random(10),
];
});
| |
php
|
<?php
require_once __DIR__.'/../vendor/autoload.php';
Dotenv::load(__DIR__.'/../');
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/
$app = new Laravel\Lumen\Application(
realpath(__DIR__.'/../')
);
$app->withFacades();
$app->withEloquent();
$app->configure('geoip');
/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/
$app->middleware([
Illuminate\Cookie\Middleware\EncryptCookies::class,
// Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
Illuminate\Session\Middleware\StartSession::class,
Illuminate\View\Middleware\ShareErrorsFromSession::class,
App\Http\Middleware\VerifyCsrfToken::class,
]);
$app->routeMiddleware([
'api' => App\Http\Middleware\ApiMiddleware::class,
]);
/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/
$app->register(App\Providers\AppServiceProvider::class);
$app->register(\Yajra\Datatables\DatatablesServiceProvider::class);
$app->register(\Torann\GeoIP\GeoIPServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);
/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/
$app->group(['namespace' => 'App\Http\Controllers'], function ($app) {
require __DIR__.'/../app/Http/routes.php';
});
return $app;
| |
php
|
<?php
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class TestCase extends Laravel\Lumen\Testing\TestCase
{
/**
* Creates the application.
*
* @return \Laravel\Lumen\Application
*/
use DatabaseTransactions;
public function createApplication() {
return require __DIR__.'/../bootstrap/app.php';
}
}
| |
php
|
<?php
class LinkControllerTest extends TestCase
{
/**
* Test LinkController
*
* @return void
*/
public function testRequestGetNotExistShortUrl() {
$response = $this->call('GET', '/notexist');
$this->assertTrue($response->isRedirection());
$this->assertRedirectedTo(env('SETTING_INDEX_REDIRECT'));
}
}
| |
php
|
<?php
class AuthTest extends TestCase
{
/**
* Test Authentication (sign up and sign in)
*
* @return void
*/
public function testLogin() {
// $this->visit('/')
// ->type('polrci', 'username')
// ->type('polrci', 'password ')
// ->press('Sign In')
// ->dontSee('name="login" value="Sign In" />')
// ->see('>Dashboard</a>');
}
}
| |
php
|
<?php
use App\Helpers\LinkHelper;
use App\Factories\LinkFactory;
class LinkHelperTest extends TestCase
{
/**
* Test LinkHelper
*
* @return void
*/
public function testLinkHelperAlreadyShortened() {
$not_short = [
'https://google.com',
'https://example.com/google',
'https://cydrobolt.com',
'http://github.com/cydrobolt/polr'
];
$shortened = [
'https://polr.me/1',
'http://bit.ly/1PUf6Sw',
'http://'.env('APP_ADDRESS').'/1',
'https://goo.gl/2pSp9f'
];
foreach ($not_short as $u) {
$this->assertEquals(false, LinkHelper::checkIfAlreadyShortened($u));
}
foreach ($shortened as $u) {
$this->assertEquals(true, LinkHelper::checkIfAlreadyShortened($u));
}
}
public function testLinkExists() {
$link = LinkFactory::createLink('http://example.com/ci', true, null, '127.0.0.1', false, true);
// assert that existent link ending returns true
$this->assertNotEquals(LinkHelper::linkExists($link->short_url), false);
// assert that nonexistent link ending returns false
$this->assertEquals(LinkHelper::linkExists('nonexistent'), false);
}
}
| |
php
|
<?php
use App\Helpers\BaseHelper;
class BaseHelperTest extends TestCase
{
/**
* Test BaseHelper
*
* @return void
*/
private static function checkBaseGen($num) {
$toBase32 = BaseHelper::toBase($num, 32);
$toBase62 = BaseHelper::toBase($num, 62);
$fromBase32 = BaseHelper::toBase10($toBase32, 32);
$fromBase62 = BaseHelper::toBase10($toBase62, 62);
if ($fromBase62 == $num && $fromBase32 == $num) {
return true;
}
return false;
}
public function testLogin() {
$nums = [
523002,
1204,
23,
0,
1,
45
];
foreach ($nums as $n) {
$this->assertEquals(true, self::checkBaseGen($n));
}
}
}
| |
php
|
<?php
class IndexTest extends TestCase
{
/**
* Test Index
*
* @return void
*/
public function testIndex() {
$this->visit('/')
->see('<h1 class=\'title\'>'. env('APP_NAME') .'</h1>') // Ensure page loads correctly
->see('<meta name="csrf-token"') // Ensure CSRF protection is enabled
->see('>Sign In</a>') // Ensure log in buttons are shown when user is logged out
->dontSee('SQLSTATE'); // Ensure database connection is correct
}
}
| |
php
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
'accepted' => 'The :attribute must be accepted.',
'active_url' => 'The :attribute is not a valid URL.',
'after' => 'The :attribute must be a date after :date.',
'alpha' => 'The :attribute may only contain letters.',
'alpha_dash' => 'The :attribute may only contain letters, numbers, and dashes.',
'alpha_num' => 'The :attribute may only contain letters and numbers.',
'array' => 'The :attribute must be an array.',
'before' => 'The :attribute must be a date before :date.',
'between' => [
'numeric' => 'The :attribute must be between :min and :max.',
'file' => 'The :attribute must be between :min and :max kilobytes.',
'string' => 'The :attribute must be between :min and :max characters.',
'array' => 'The :attribute must have between :min and :max items.',
],
'boolean' => 'The :attribute field must be true or false.',
'confirmed' => 'The :attribute confirmation does not match.',
'date' => 'The :attribute is not a valid date.',
'date_format' => 'The :attribute does not match the format :format.',
'different' => 'The :attribute and :other must be different.',
'digits' => 'The :attribute must be :digits digits.',
'digits_between' => 'The :attribute must be between :min and :max digits.',
'email' => 'The :attribute must be a valid email address.',
'filled' => 'The :attribute field is required.',
'exists' => 'The selected :attribute is invalid.',
'image' => 'The :attribute must be an image.',
'in' => 'The selected :attribute is invalid.',
'integer' => 'The :attribute must be an integer.',
'ip' => 'The :attribute must be a valid IP address.',
'max' => [
'numeric' => 'The :attribute may not be greater than :max.',
'file' => 'The :attribute may not be greater than :max kilobytes.',
'string' => 'The :attribute may not be greater than :max characters.',
'array' => 'The :attribute may not have more than :max items.',
],
'mimes' => 'The :attribute must be a file of type: :values.',
'min' => [
'numeric' => 'The :attribute must be at least :min.',
'file' => 'The :attribute must be at least :min kilobytes.',
'string' => 'The :attribute must be at least :min characters.',
'array' => 'The :attribute must have at least :min items.',
],
'not_in' => 'The selected :attribute is invalid.',
'numeric' => 'The :attribute must be a number.',
'regex' => 'The :attribute format is invalid.',
'required' => 'The :attribute field is required.',
'required_if' => 'The :attribute field is required when :other is :value.',
'required_with' => 'The :attribute field is required when :values is present.',
'required_with_all' => 'The :attribute field is required when :values is present.',
'required_without' => 'The :attribute field is required when :values is not present.',
'required_without_all' => 'The :attribute field is required when none of :values are present.',
'same' => 'The :attribute and :other must match.',
'size' => [
'numeric' => 'The :attribute must be :size.',
'file' => 'The :attribute must be :size kilobytes.',
'string' => 'The :attribute must be :size characters.',
'array' => 'The :attribute must contain :size items.',
],
'unique' => 'The :attribute has already been taken.',
'url' => 'The :attribute format is invalid.',
'timezone' => 'The :attribute must be a valid zone.',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => [
'link-url' => 'link URL'
],
];
| |
php
|
<?php
namespace App\Events;
use Illuminate\Queue\SerializesModels;
abstract class Event
{
use SerializesModels;
}
| |
php
|
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
| |
php
|
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
];
}
| |
php
|
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
*/
/* Optional endpoints */
if (env('POLR_ALLOW_ACCT_CREATION')) {
$app->get('/signup', ['as' => 'signup', 'uses' => 'UserController@displaySignupPage']);
$app->post('/signup', ['as' => 'psignup', 'uses' => 'UserController@performSignup']);
}
/* GET endpoints */
$app->get('/', ['as' => 'index', 'uses' => 'IndexController@showIndexPage']);
$app->get('/logout', ['as' => 'logout', 'uses' => 'UserController@performLogoutUser']);
$app->get('/login', ['as' => 'login', 'uses' => 'UserController@displayLoginPage']);
$app->get('/about-polr', ['as' => 'about', 'uses' => 'StaticPageController@displayAbout']);
$app->get('/lost_password', ['as' => 'lost_password', 'uses' => 'UserController@displayLostPasswordPage']);
$app->get('/activate/{username}/{recovery_key}', ['as' => 'activate', 'uses' => 'UserController@performActivation']);
$app->get('/reset_password/{username}/{recovery_key}', ['as' => 'reset_password', 'uses' => 'UserController@performPasswordReset']);
$app->get('/admin', ['as' => 'admin', 'uses' => 'AdminController@displayAdminPage']);
$app->get('/setup', ['as' => 'setup', 'uses' => 'SetupController@displaySetupPage']);
$app->post('/setup', ['as' => 'psetup', 'uses' => 'SetupController@performSetup']);
$app->get('/setup/finish', ['as' => 'setup_finish', 'uses' => 'SetupController@finishSetup']);
$app->get('/{short_url}', ['uses' => 'LinkController@performRedirect']);
$app->get('/{short_url}/{secret_key}', ['uses' => 'LinkController@performRedirect']);
$app->get('/admin/stats/{short_url}', ['uses' => 'StatsController@displayStats']);
/* POST endpoints */
$app->post('/login', ['as' => 'plogin', 'uses' => 'UserController@performLogin']);
$app->post('/shorten', ['as' => 'pshorten', 'uses' => 'LinkController@performShorten']);
$app->post('/lost_password', ['as' => 'plost_password', 'uses' => 'UserController@performSendPasswordResetCode']);
$app->post('/reset_password/{username}/{recovery_key}', ['as' => 'preset_password', 'uses' => 'UserController@performPasswordReset']);
$app->post('/admin/action/change_password', ['as' => 'change_password', 'uses' => 'AdminController@changePassword']);
$app->group(['prefix' => '/api/v2', 'namespace' => 'App\Http\Controllers'], function ($app) {
/* API internal endpoints */
$app->post('link_avail_check', ['as' => 'api_link_check', 'uses' => 'AjaxController@checkLinkAvailability']);
$app->post('admin/toggle_api_active', ['as' => 'api_toggle_api_active', 'uses' => 'AjaxController@toggleAPIActive']);
$app->post('admin/generate_new_api_key', ['as' => 'api_generate_new_api_key', 'uses' => 'AjaxController@generateNewAPIKey']);
$app->post('admin/edit_api_quota', ['as' => 'api_edit_quota', 'uses' => 'AjaxController@editAPIQuota']);
$app->post('admin/toggle_user_active', ['as' => 'api_toggle_user_active', 'uses' => 'AjaxController@toggleUserActive']);
$app->post('admin/change_user_role', ['as' => 'api_change_user_role', 'uses' => 'AjaxController@changeUserRole']);
$app->post('admin/add_new_user', ['as' => 'api_add_new_user', 'uses' => 'AjaxController@addNewUser']);
$app->post('admin/delete_user', ['as' => 'api_delete_user', 'uses' => 'AjaxController@deleteUser']);
$app->post('admin/toggle_link', ['as' => 'api_toggle_link', 'uses' => 'AjaxController@toggleLink']);
$app->post('admin/delete_link', ['as' => 'api_delete_link', 'uses' => 'AjaxController@deleteLink']);
$app->post('admin/edit_link_long_url', ['as' => 'api_edit_link_long_url', 'uses' => 'AjaxController@editLinkLongUrl']);
$app->get('admin/get_admin_users', ['as' => 'api_get_admin_users', 'uses' => 'AdminPaginationController@paginateAdminUsers']);
$app->get('admin/get_admin_links', ['as' => 'api_get_admin_links', 'uses' => 'AdminPaginationController@paginateAdminLinks']);
$app->get('admin/get_user_links', ['as' => 'api_get_user_links', 'uses' => 'AdminPaginationController@paginateUserLinks']);
});
$app->group(['prefix' => '/api/v2', 'namespace' => 'App\Http\Controllers\Api', 'middleware' => 'api'], function ($app) {
/* API shorten endpoints */
$app->post('action/shorten', ['as' => 'api_shorten_url', 'uses' => 'ApiLinkController@shortenLink']);
$app->get('action/shorten', ['as' => 'api_shorten_url', 'uses' => 'ApiLinkController@shortenLink']);
$app->post('action/shorten_bulk', ['as' => 'api_shorten_url_bulk', 'uses' => 'ApiLinkController@shortenLinksBulk']);
/* API lookup endpoints */
$app->post('action/lookup', ['as' => 'api_lookup_url', 'uses' => 'ApiLinkController@lookupLink']);
$app->get('action/lookup', ['as' => 'api_lookup_url', 'uses' => 'ApiLinkController@lookupLink']);
/* API data endpoints */
$app->get('data/link', ['as' => 'api_link_analytics', 'uses' => 'ApiAnalyticsController@lookupLinkStats']);
$app->post('data/link', ['as' => 'api_link_analytics', 'uses' => 'ApiAnalyticsController@lookupLinkStats']);
});
| |
php
|
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class Controller extends BaseController {
protected static function currIsAdmin() {
$role = session('role');
if ($role == 'admin') {
return true;
}
else {
return false;
}
}
protected static function isLoggedIn() {
$username = session('username');
if (!isset($username)) {
return false;
}
else {
return true;
}
}
protected static function checkRequiredArgs($required_args=[]) {
foreach($required_args as $arg) {
if ($arg == NULL) {
return false;
}
}
return true;
}
protected static function ensureAdmin() {
if (!self::currIsAdmin()) {
abort(401, 'User not admin.');
}
return true;
}
protected static function ensureLoggedIn() {
if (!self::isLoggedIn()) {
abort (401, 'User must be authenticated.');
}
return true;
}
}
| |
php
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Helpers\LinkHelper;
use App\Helpers\CryptoHelper;
use App\Helpers\UserHelper;
use App\Models\User;
use App\Factories\UserFactory;
class AjaxController extends Controller {
/**
* Process AJAX requests.
*
* @return Response
*/
public function checkLinkAvailability(Request $request) {
$link_ending = $request->input('link_ending');
$ending_conforms = LinkHelper::validateEnding($link_ending);
if (!$ending_conforms) {
return "invalid";
}
else if (LinkHelper::linkExists($link_ending)) {
// if ending already exists
return "unavailable";
}
else {
return "available";
}
}
public function toggleAPIActive(Request $request) {
self::ensureAdmin();
$user_id = $request->input('user_id');
$user = UserHelper::getUserById($user_id);
if (!$user) {
abort(404, 'User not found.');
}
$current_status = $user->api_active;
if ($current_status == 1) {
$new_status = 0;
}
else {
$new_status = 1;
}
$user->api_active = $new_status;
$user->save();
return $user->api_active;
}
public function generateNewAPIKey(Request $request) {
/**
* If user is an admin, allow resetting of any API key
*
* If user is not an admin, allow resetting of own key only, and only if
* API is enabled for the account.
* @return string; new API key
*/
$user_id = $request->input('user_id');
$user = UserHelper::getUserById($user_id);
$username_user_requesting = session('username');
$user_requesting = UserHelper::getUserByUsername($username_user_requesting);
if (!$user) {
abort(404, 'User not found.');
}
if ($user != $user_requesting) {
// if user is attempting to reset another user's API key,
// ensure they are an admin
self::ensureAdmin();
}
else {
// user is attempting to reset own key
// ensure that user is permitted to access the API
$user_api_enabled = $user->api_active;
if (!$user_api_enabled) {
// if the user does not have API access toggled on,
// allow only if user is an admin
self::ensureAdmin();
}
}
$new_api_key = CryptoHelper::generateRandomHex(env('_API_KEY_LENGTH'));
$user->api_key = $new_api_key;
$user->save();
return $user->api_key;
}
public function editAPIQuota(Request $request) {
/**
* If user is an admin, allow the user to edit the per minute API quota of
* any user.
*/
self::ensureAdmin();
$user_id = $request->input('user_id');
$new_quota = $request->input('new_quota');
$user = UserHelper::getUserById($user_id);
if (!$user) {
abort(404, 'User not found.');
}
$user->api_quota = $new_quota;
$user->save();
return "OK";
}
public function toggleUserActive(Request $request) {
self::ensureAdmin();
$user_id = $request->input('user_id');
$user = UserHelper::getUserById($user_id, true);
if (!$user) {
abort(404, 'User not found.');
}
$current_status = $user->active;
if ($current_status == 1) {
$new_status = 0;
}
else {
$new_status = 1;
}
$user->active = $new_status;
$user->save();
return $user->active;
}
public function changeUserRole(Request $request) {
self::ensureAdmin();
$user_id = $request->input('user_id');
$role = $request->input('role');
$user = UserHelper::getUserById($user_id, true);
if (!$user) {
abort(404, 'User not found.');
}
$user->role = $role;
$user->save();
return "OK";
}
public function addNewUser(Request $request) {
self::ensureAdmin();
$ip = $request->ip();
$username = $request->input('username');
$user_password = $request->input('user_password');
$user_email = $request->input('user_email');
$user_role = $request->input('user_role');
UserFactory::createUser($username, $user_email, $user_password, 1, $ip, false, 0, $user_role);
return "OK";
}
public function deleteUser(Request $request) {
self::ensureAdmin();
$user_id = $request->input('user_id');
$user = UserHelper::getUserById($user_id, true);
if (!$user) {
abort(404, 'User not found.');
}
$user->delete();
return "OK";
}
public function deleteLink(Request $request) {
self::ensureAdmin();
$link_ending = $request->input('link_ending');
$link = LinkHelper::linkExists($link_ending);
if (!$link) {
abort(404, 'Link not found.');
}
$link->delete();
return "OK";
}
public function toggleLink(Request $request) {
self::ensureAdmin();
$link_ending = $request->input('link_ending');
$link = LinkHelper::linkExists($link_ending);
if (!$link) {
abort(404, 'Link not found.');
}
$current_status = $link->is_disabled;
$new_status = 1;
if ($current_status == 1) {
// if currently disabled, then enable
$new_status = 0;
}
$link->is_disabled = $new_status;
$link->save();
return ($new_status ? "Enable" : "Disable");
}
public function editLinkLongUrl(Request $request) {
/**
* If user is an admin, allow the user to edit the value of any link's long URL.
* Otherwise, only allow the user to edit their own links.
*/
$link_ending = $request->input('link_ending');
$link = LinkHelper::linkExists($link_ending);
$new_long_url = $request->input('new_long_url');
$this->validate($request, [
'new_long_url' => 'required|url',
]);
if (!$link) {
abort(404, 'Link not found.');
}
if ($link->creator !== session('username')) {
self::ensureAdmin();
}
$link->long_url = $new_long_url;
$link->save();
return "OK";
}
}
| |
php
|
<?php
namespace App\Http\Controllers;
use Mail;
use Hash;
use App\Models\User;
use Illuminate\Http\Request;
use App\Helpers\CryptoHelper;
use App\Helpers\UserHelper;
use App\Factories\UserFactory;
class UserController extends Controller {
/**
* Show pages related to the user control panel.
*
* @return Response
*/
public function displayLoginPage(Request $request) {
return view('login');
}
public function displaySignupPage(Request $request) {
return view('signup');
}
public function displayLostPasswordPage(Request $request) {
return view('lost_password');
}
public function performLogoutUser(Request $request) {
$request->session()->forget('username');
$request->session()->forget('role');
return redirect()->route('index');
}
public function performLogin(Request $request) {
$username = $request->input('username');
$password = $request->input('password');
$credentials_valid = UserHelper::checkCredentials($username, $password);
if ($credentials_valid != false) {
// log user in
$role = $credentials_valid['role'];
$request->session()->put('username', $username);
$request->session()->put('role', $role);
return redirect()->route('index');
}
else {
return redirect('login')->with('error', 'Invalid password or inactivated account. Try again.');
}
}
public function performSignup(Request $request) {
if (env('POLR_ALLOW_ACCT_CREATION') == false) {
return redirect(route('index'))->with('error', 'Sorry, but registration is disabled.');
}
if (env('POLR_ACCT_CREATION_RECAPTCHA')) {
// Verify reCAPTCHA if setting is enabled
$gRecaptchaResponse = $request->input('g-recaptcha-response');
$recaptcha = new \ReCaptcha\ReCaptcha(env('POLR_RECAPTCHA_SECRET_KEY'));
$recaptcha_resp = $recaptcha->verify($gRecaptchaResponse, $request->ip());
if (!$recaptcha_resp->isSuccess()) {
return redirect(route('signup'))->with('error', 'You must complete the reCAPTCHA to register.');
}
}
// Validate signup form data
$this->validate($request, [
'username' => 'required|alpha_dash',
'password' => 'required',
'email' => 'required|email'
]);
$username = $request->input('username');
$password = $request->input('password');
$email = $request->input('email');
if (env('SETTING_RESTRICT_EMAIL_DOMAIN')) {
$email_domain = explode('@', $email)[1];
$permitted_email_domains = explode(',', env('SETTING_ALLOWED_EMAIL_DOMAINS'));
if (!in_array($email_domain, $permitted_email_domains)) {
return redirect(route('signup'))->with('error', 'Sorry, your email\'s domain is not permitted to create new accounts.');
}
}
$ip = $request->ip();
$user_exists = UserHelper::userExists($username);
$email_exists = UserHelper::emailExists($email);
if ($user_exists || $email_exists) {
// if user or email email
return redirect(route('signup'))->with('error', 'Sorry, your email or username already exists. Try again.');
}
$acct_activation_needed = env('POLR_ACCT_ACTIVATION');
if ($acct_activation_needed == false) {
// if no activation is necessary
$active = 1;
$response = redirect(route('login'))->with('success', 'Thanks for signing up! You may now log in.');
}
else {
// email activation is necessary
$response = redirect(route('login'))->with('success', 'Thanks for signing up! Please confirm your email to continue.');
$active = 0;
}
$api_active = false;
$api_key = null;
if (env('SETTING_AUTO_API')) {
// if automatic API key assignment is on
$api_active = 1;
$api_key = CryptoHelper::generateRandomHex(env('_API_KEY_LENGTH'));
}
$user = UserFactory::createUser($username, $email, $password, $active, $ip, $api_key, $api_active);
if ($acct_activation_needed) {
Mail::send('emails.activation', [
'username' => $username, 'recovery_key' => $user->recovery_key, 'ip' => $ip
], function ($m) use ($user) {
$m->from(env('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME'));
$m->to($user->email, $user->username)->subject(env('APP_NAME') . ' account activation');
});
}
return $response;
}
public function performSendPasswordResetCode(Request $request) {
if (!env('SETTING_PASSWORD_RECOV')) {
return redirect(route('index'))->with('error', 'Password recovery is disabled.');
}
$email = $request->input('email');
$ip = $request->ip();
$user = UserHelper::getUserByEmail($email);
if (!$user) {
return redirect(route('lost_password'))->with('error', 'Email is not associated with a user.');
}
$recovery_key = UserHelper::resetRecoveryKey($user->username);
Mail::send('emails.lost_password', [
'username' => $user->username, 'recovery_key' => $recovery_key, 'ip' => $ip
], function ($m) use ($user) {
$m->from(env('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME'));
$m->to($user->email, $user->username)->subject(env('APP_NAME') . ' Password Reset');
});
return redirect(route('index'))->with('success', 'Password reset email sent. Check your inbox for details.');
}
public function performActivation(Request $request, $username, $recovery_key) {
$user = UserHelper::getUserByUsername($username, true);
if (UserHelper::userResetKeyCorrect($username, $recovery_key, true)) {
// Key is correct
// Activate account and reset recovery key
$user->active = 1;
$user->save();
UserHelper::resetRecoveryKey($username);
return redirect(route('login'))->with('success', 'Account activated. You may now login.');
}
else {
return redirect(route('index'))->with('error', 'Username or activation key incorrect.');
}
}
public function performPasswordReset(Request $request, $username, $recovery_key) {
$new_password = $request->input('new_password');
$user = UserHelper::getUserByUsername($username);
if (UserHelper::userResetKeyCorrect($username, $recovery_key)) {
if (!$new_password) {
return view('reset_password');
}
// Key is correct
// Reset password
$user->password = Hash::make($new_password);
$user->save();
UserHelper::resetRecoveryKey($username);
return redirect(route('login'))->with('success', 'Password reset. You may now login.');
}
else {
return redirect(route('index'))->with('error', 'Username or reset key incorrect.');
}
}
}
| |
php
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Helpers\CryptoHelper;
class IndexController extends Controller {
/**
* Show the index page.
*
* @return Response
*/
public function showIndexPage(Request $request) {
if (env('POLR_SETUP_RAN') != true) {
return redirect(route('setup'));
}
if (!env('SETTING_PUBLIC_INTERFACE') && !self::isLoggedIn()) {
if (env('SETTING_INDEX_REDIRECT')) {
return redirect()->to(env('SETTING_INDEX_REDIRECT'));
}
else {
return redirect()->to(route('login'));
}
}
return view('index', ['large' => true]);
}
}
| |
php
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Hash;
use App\Models\Link;
use App\Models\User;
use App\Helpers\UserHelper;
class AdminController extends Controller {
/**
* Show the admin panel, and process setting changes.
*
* @return Response
*/
public function displayAdminPage(Request $request) {
if (!$this->isLoggedIn()) {
return redirect(route('login'))->with('error', 'Please login to access your dashboard.');
}
$username = session('username');
$role = session('role');
$user = UserHelper::getUserByUsername($username);
if (!$user) {
return redirect(route('index'))->with('error', 'Invalid or disabled account.');
}
return view('admin', [
'role' => $role,
'admin_role' => UserHelper::$USER_ROLES['admin'],
'user_roles' => UserHelper::$USER_ROLES,
'api_key' => $user->api_key,
'api_active' => $user->api_active,
'api_quota' => $user->api_quota,
'user_id' => $user->id
]);
}
public function changePassword(Request $request) {
if (!$this->isLoggedIn()) {
return abort(404);
}
$username = session('username');
$old_password = $request->input('current_password');
$new_password = $request->input('new_password');
if (UserHelper::checkCredentials($username, $old_password) == false) {
// Invalid credentials
return redirect('admin')->with('error', 'Current password invalid. Try again.');
}
else {
// Credentials are correct
$user = UserHelper::getUserByUsername($username);
$user->password = Hash::make($new_password);
$user->save();
$request->session()->flash('success', "Password changed successfully.");
return redirect(route('admin'));
}
}
}
| |
php
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Redirect;
use App\Models\Link;
use App\Factories\LinkFactory;
use App\Helpers\CryptoHelper;
use App\Helpers\LinkHelper;
use App\Helpers\ClickHelper;
class LinkController extends Controller {
/**
* Show the admin panel, and process admin AJAX requests.
*
* @return Response
*/
private function renderError($message) {
return redirect(route('index'))->with('error', $message);
}
public function performShorten(Request $request) {
if (env('SETTING_SHORTEN_PERMISSION') && !self::isLoggedIn()) {
return redirect(route('index'))->with('error', 'You must be logged in to shorten links.');
}
// Validate URL form data
$this->validate($request, [
'link-url' => 'required|url',
'custom-ending' => 'alpha_dash'
]);
$long_url = $request->input('link-url');
$custom_ending = $request->input('custom-ending');
$is_secret = ($request->input('options') == "s" ? true : false);
$creator = session('username');
$link_ip = $request->ip();
try {
$short_url = LinkFactory::createLink($long_url, $is_secret, $custom_ending, $link_ip, $creator);
}
catch (\Exception $e) {
return self::renderError($e->getMessage());
}
return view('shorten_result', ['short_url' => $short_url]);
}
public function performRedirect(Request $request, $short_url, $secret_key=false) {
$link = Link::where('short_url', $short_url)
->first();
// Return 404 if link not found
if ($link == null) {
return abort(404);
}
// Return an error if the link has been disabled
// or return a 404 if SETTING_REDIRECT_404 is set to true
if ($link->is_disabled == 1) {
if (env('SETTING_REDIRECT_404')) {
return abort(404);
}
return view('error', [
'message' => 'Sorry, but this link has been disabled by an administrator.'
]);
}
// Return a 403 if the secret key is incorrect
$link_secret_key = $link->secret_key;
if ($link_secret_key) {
if (!$secret_key) {
// if we do not receieve a secret key
// when we are expecting one, return a 403
return abort(403);
}
else {
if ($link_secret_key != $secret_key) {
// a secret key is provided, but it is incorrect
return abort(403);
}
}
}
// Increment click count
$long_url = $link->long_url;
$clicks = intval($link->clicks);
if (is_int($clicks)) {
$clicks += 1;
}
$link->clicks = $clicks;
$link->save();
if (env('SETTING_ADV_ANALYTICS')) {
// Record advanced analytics if option is enabled
ClickHelper::recordClick($link, $request);
}
// Redirect to final destination
return redirect()->to($long_url, 301);
}
}
| |
php
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Yajra\Datatables\Facades\Datatables;
use App\Models\Link;
use App\Models\User;
use App\Helpers\UserHelper;
class AdminPaginationController extends Controller {
/**
* Process AJAX Datatables pagination queries from the admin panel.
*
* @return Response
*/
/* Cell rendering functions */
public function renderLongUrlCell($link) {
return '<a target="_blank" title="' . e($link->long_url) . '" href="'. e($link->long_url) .'">' . e(str_limit($link->long_url, 50)) . '</a>
<a class="btn btn-primary btn-xs edit-long-link-btn" ng-click="editLongLink(\'' . e($link->short_url) . '\', \'' . e($link->long_url) . '\')"><i class="fa fa-edit edit-link-icon"></i></a>';
}
public function renderClicksCell($link) {
if (env('SETTING_ADV_ANALYTICS')) {
return $link->clicks . ' <a target="_blank" class="stats-icon" href="/admin/stats/' . e($link->short_url) . '">
<i class="fa fa-area-chart" aria-hidden="true"></i>
</a>';
}
else {
return $link->clicks;
}
}
public function renderDeleteUserCell($user) {
// Add "Delete" action button
$btn_class = '';
if (session('username') === $user->username) {
$btn_class = 'disabled';
}
return '<a ng-click="deleteUser($event, \''. $user->id .'\')" class="btn btn-sm btn-danger ' . $btn_class . '">
Delete
</a>';
}
public function renderDeleteLinkCell($link) {
// Add "Delete" action button
return '<a ng-click="deleteLink($event, \'' . e($link->short_url) . '\')"
class="btn btn-sm btn-warning delete-link">
Delete
</a>';
}
public function renderAdminApiActionCell($user) {
// Add "API Info" action button
return '<a class="activate-api-modal btn btn-sm btn-info"
ng-click="openAPIModal($event, \'' . e($user->username) . '\', \'' . $user->api_key . '\', \'' . $user->api_active . '\', \'' . e($user->api_quota) . '\', \'' . $user->id . '\')">
API info
</a>';
}
public function renderToggleUserActiveCell($user) {
// Add user account active state toggle buttons
$btn_class = '';
if (session('username') === $user->username) {
$btn_class = ' disabled';
}
if ($user->active) {
$active_text = 'Active';
$btn_color_class = ' btn-success';
}
else {
$active_text = 'Inactive';
$btn_color_class = ' btn-danger';
}
return '<a class="btn btn-sm status-display' . $btn_color_class . $btn_class . '" ng-click="toggleUserActiveStatus($event, ' . $user->id . ')">' . $active_text . '</a>';
}
public function renderChangeUserRoleCell($user) {
// Add "change role" select box
// <select> field does not use Angular bindings
// because of an issue affecting fields with duplicate names.
$select_role = '<select ng-init="changeUserRole.u' . $user->id . ' = \'' . e($user->role) . '\'"
ng-model="changeUserRole.u' . $user->id . '" ng-change="changeUserRole(changeUserRole.u' . $user->id . ', '.$user->id.')"
class="form-control"';
if (session('username') === $user->username) {
// Do not allow user to change own role
$select_role .= ' disabled';
}
$select_role .= '>';
foreach (UserHelper::$USER_ROLES as $role_text => $role_val) {
// Iterate over each available role and output option
$select_role .= '<option value="' . e($role_val) . '"';
if ($user->role === $role_val) {
$select_role .= ' selected';
}
$select_role .= '>' . e($role_text) . '</option>';
}
$select_role .= '</select>';
return $select_role;
}
public function renderToggleLinkActiveCell($link) {
// Add "Disable/Enable" action buttons
$btn_class = 'btn-danger';
$btn_text = 'Disable';
if ($link->is_disabled) {
$btn_class = 'btn-success';
$btn_text = 'Enable';
}
return '<a ng-click="toggleLink($event, \'' . e($link->short_url) . '\')" class="btn btn-sm ' . $btn_class . '">
' . $btn_text . '
</a>';
}
/* DataTables bindings */
public function paginateAdminUsers(Request $request) {
self::ensureAdmin();
$admin_users = User::select(['username', 'email', 'created_at', 'active', 'api_key', 'api_active', 'api_quota', 'role', 'id']);
return Datatables::of($admin_users)
->addColumn('api_action', [$this, 'renderAdminApiActionCell'])
->addColumn('toggle_active', [$this, 'renderToggleUserActiveCell'])
->addColumn('change_role', [$this, 'renderChangeUserRoleCell'])
->addColumn('delete', [$this, 'renderDeleteUserCell'])
->escapeColumns(['username', 'email'])
->make(true);
}
public function paginateAdminLinks(Request $request) {
self::ensureAdmin();
$admin_links = Link::select(['short_url', 'long_url', 'clicks', 'created_at', 'creator', 'is_disabled']);
return Datatables::of($admin_links)
->addColumn('disable', [$this, 'renderToggleLinkActiveCell'])
->addColumn('delete', [$this, 'renderDeleteLinkCell'])
->editColumn('clicks', [$this, 'renderClicksCell'])
->editColumn('long_url', [$this, 'renderLongUrlCell'])
->escapeColumns(['short_url', 'creator'])
->make(true);
}
public function paginateUserLinks(Request $request) {
self::ensureLoggedIn();
$username = session('username');
$user_links = Link::where('creator', $username)
->select(['id', 'short_url', 'long_url', 'clicks', 'created_at']);
return Datatables::of($user_links)
->editColumn('clicks', [$this, 'renderClicksCell'])
->editColumn('long_url', [$this, 'renderLongUrlCell'])
->escapeColumns(['short_url'])
->make(true);
}
}
| |
php
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Redirect;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schema;
use App\Helpers\CryptoHelper;
use App\Models\User;
use App\Helpers\UserHelper;
use App\Factories\UserFactory;
use Cache;
class SetupController extends Controller {
protected static function parseExitCode($exitCode) {
if ($exitCode == 0) {
return true;
}
else {
return false;
}
}
private static function setupAlreadyRan() {
return view('error', [
'message' => 'Sorry, but you have already completed the setup process.'
]);
}
private function resetDatabase() {
$exitCode = Artisan::call('migrate:refresh', [
'--force' => true,
]);
return self::parseExitCode($exitCode);
}
private static function updateGeoIP() {
// Output GeoIP database for advanced
// analytics
$exitCode = Artisan::call('geoip:update', []);
return self::parseExitCode($exitCode);
}
private static function createDatabase() {
$exitCode = Artisan::call('migrate', [
'--force' => true,
]);
return self::parseExitCode($exitCode);
}
public static function displaySetupPage(Request $request) {
if (env('POLR_SETUP_RAN')) {
return self::setupAlreadyRan();
}
return view('setup');
}
public static function performSetup(Request $request) {
if (env('POLR_SETUP_RAN')) {
return self::setupAlreadyRan();
}
$app_key = CryptoHelper::generateRandomHex(16);
$setup_auth_key = CryptoHelper::generateRandomHex(16);
$app_name = $request->input('app:name');
$app_protocol = $request->input('app:protocol');
$app_address = $request->input('app:external_url');
$app_protocol = $request->input('app:protocol');
$app_stylesheet = $request->input('app:stylesheet');
date_default_timezone_set('UTC');
$date_today = date('F jS, Y');
$polr_setup_ran = 'true';
$db_host = $request->input('db:host');
$db_port = $request->input('db:port');
$db_name = $request->input('db:name');
$db_username = $request->input('db:username');
$db_password = $request->input('db:password');
$st_public_interface = $request->input('setting:public_interface');
$polr_registration_setting = $request->input('setting:registration_permission');
if ($polr_registration_setting == 'no-verification') {
$polr_acct_activation = false;
$polr_allow_acct_creation = true;
}
else if ($polr_registration_setting == 'none') {
$polr_acct_activation = false;
$polr_allow_acct_creation = false;
}
else if ($polr_registration_setting == 'email') {
$polr_acct_activation = true;
$polr_allow_acct_creation = true;
}
else {
return view('error', [
'message' => 'Invalid registration settings'
]);
}
$polr_acct_creation_recaptcha = $request->input('setting:acct_registration_recaptcha');
$polr_recaptcha_site_key = $request->input('setting:recaptcha_site_key');
$polr_recaptcha_secret_key = $request->input('setting:recaptcha_secret_key');
$maxmind_license_key = $request->input('maxmind:license_key');
$acct_username = $request->input('acct:username');
$acct_email = $request->input('acct:email');
$acct_password = $request->input('acct:password');
$acct_group = UserHelper::$USER_ROLES['admin'];
// if true, only logged in users can shorten
$st_shorten_permission = $request->input('setting:shorten_permission');
$st_index_redirect = $request->input('setting:index_redirect');
$st_redirect_404 = $request->input('setting:redirect_404');
$st_password_recov = $request->input('setting:password_recovery');
$st_restrict_email_domain = $request->input('setting:restrict_email_domain');
$st_allowed_email_domains = $request->input('setting:allowed_email_domains');
$st_base = $request->input('setting:base');
$st_auto_api_key = $request->input('setting:auto_api_key');
$st_anon_api = $request->input('setting:anon_api');
$st_anon_api_quota = $request->input('setting:anon_api_quota');
$st_pseudor_ending = $request->input('setting:pseudor_ending');
$st_adv_analytics = $request->input('setting:adv_analytics');
$mail_host = $request->input('app:smtp_server');
$mail_port = $request->input('app:smtp_port');
$mail_username = $request->input('app:smtp_username');
$mail_password = $request->input('app:smtp_password');
$mail_from = $request->input('app:smtp_from');
$mail_from_name = $request->input('app:smtp_from_name');
if ($mail_host) {
$mail_enabled = true;
}
else {
$mail_enabled = false;
}
$compiled_configuration = view('env', [
'APP_KEY' => $app_key,
'APP_NAME' => $app_name,
'APP_PROTOCOL' => $app_protocol,
'APP_ADDRESS' => $app_address,
'APP_STYLESHEET' => $app_stylesheet,
'POLR_GENERATED_AT' => $date_today,
'POLR_SETUP_RAN' => $polr_setup_ran,
'MAXMIND_LICENSE_KEY' => $maxmind_license_key,
'DB_HOST' => $db_host,
'DB_PORT' => $db_port,
'DB_USERNAME' => $db_username,
'DB_PASSWORD' => $db_password,
'DB_DATABASE' => $db_name,
'ST_PUBLIC_INTERFACE' => $st_public_interface,
'POLR_ALLOW_ACCT_CREATION' => $polr_allow_acct_creation,
'POLR_ACCT_ACTIVATION' => $polr_acct_activation,
'POLR_ACCT_CREATION_RECAPTCHA' => $polr_acct_creation_recaptcha,
'ST_SHORTEN_PERMISSION' => $st_shorten_permission,
'ST_INDEX_REDIRECT' => $st_index_redirect,
'ST_REDIRECT_404' => $st_redirect_404,
'ST_PASSWORD_RECOV' => $st_password_recov,
'ST_RESTRICT_EMAIL_DOMAIN' => $st_restrict_email_domain,
'ST_ALLOWED_EMAIL_DOMAINS' => $st_allowed_email_domains,
'POLR_RECAPTCHA_SITE_KEY' => $polr_recaptcha_site_key,
'POLR_RECAPTCHA_SECRET' => $polr_recaptcha_secret_key,
'MAIL_ENABLED' => $mail_enabled,
'MAIL_HOST' => $mail_host,
'MAIL_PORT' => $mail_port,
'MAIL_USERNAME' => $mail_username,
'MAIL_PASSWORD' => $mail_password,
'MAIL_FROM_ADDRESS' => $mail_from,
'MAIL_FROM_NAME' => $mail_from_name,
'ST_BASE' => $st_base,
'ST_AUTO_API' => $st_auto_api_key,
'ST_ANON_API' => $st_anon_api,
'ST_ANON_API_QUOTA' => $st_anon_api_quota,
'ST_PSEUDOR_ENDING' => $st_pseudor_ending,
'ST_ADV_ANALYTICS' => $st_adv_analytics,
'TMP_SETUP_AUTH_KEY' => $setup_auth_key
])->render();
$handle = fopen('../.env', 'w');
if (fwrite($handle, $compiled_configuration) === FALSE) {
$response = view('error', [
'message' => 'Could not write configuration to disk.'
]);
} else {
Cache::flush();
$setup_finish_arguments = json_encode([
'acct_username' => $acct_username,
'acct_email' => $acct_email,
'acct_password' => $acct_password,
'setup_auth_key' => $setup_auth_key
]);
$response = redirect(route('setup_finish'));
// set cookie with information needed for finishSetup, expire in 60 seconds
// we use PHP's setcookie rather than Laravel's cookie capabilities because
// our app key changes and Laravel encrypts cookies.
setcookie('setup_arguments', $setup_finish_arguments, time()+60);
}
fclose($handle);
return $response;
}
public static function finishSetup(Request $request) {
if (!isset($_COOKIE['setup_arguments'])) {
// Abort if setup arguments are missing.
abort(404);
}
$setup_finish_args_raw = $_COOKIE['setup_arguments'];
$setup_finish_args = json_decode($setup_finish_args_raw);
// unset cookie
setcookie('setup_arguments', '', time()-3600);
$transaction_authorised = env('TMP_SETUP_AUTH_KEY') === $setup_finish_args->setup_auth_key;
if ($transaction_authorised != true) {
abort(403, 'Transaction unauthorised.');
}
$usersTableExists = Schema::hasTable('users');
if ($usersTableExists) {
// If the users table exists, then the setup process may have already been completed before.
abort(403, 'Setup has been completed already.');
}
$database_created = self::createDatabase();
if (!$database_created) {
return redirect(route('setup'))->with('error', 'Could not create database. Perhaps your credentials were incorrect?');
}
if (env('SETTING_ADV_ANALYTICS')) {
$geoip_db_created = self::updateGeoIP();
if (!$geoip_db_created) {
return redirect(route('setup'))->with('error', 'Could not fetch GeoIP database for advanced analytics. Perhaps your server is not connected to the internet or your MAXMIND_LICENSE_KEY is incorrect?');
}
}
$user = UserFactory::createUser($setup_finish_args->acct_username, $setup_finish_args->acct_email, $setup_finish_args->acct_password, 1, $request->ip(), false, 0, UserHelper::$USER_ROLES['admin']);
return view('setup_thanks')->with('success', 'Set up completed! Thanks for using Polr!');
}
}
| |
php
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class StaticPageController extends Controller {
/**
* Show static pages such as the about page.
*
* @return Response
*/
public function displayAbout(Request $request) {
$user_role = session('role');
return view('about', ['role' => $user_role, 'no_div_padding' => true]);
}
}
| |
php
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Redirect;
use Carbon\Carbon;
use App\Models\Link;
use App\Models\Clicks;
use App\Helpers\StatsHelper;
use Illuminate\Support\Facades\DB;
class StatsController extends Controller {
const DAYS_TO_FETCH = 30;
public function displayStats(Request $request, $short_url) {
$validator = \Validator::make($request->all(), [
'left_bound' => 'date',
'right_bound' => 'date'
]);
if ($validator->fails() && !session('error')) {
// Do not flash error if there is already an error flashed
return redirect()->back()->with('error', 'Invalid date bounds.');
}
$user_left_bound = $request->input('left_bound');
$user_right_bound = $request->input('right_bound');
// Carbon bounds for StatHelper
$left_bound = $user_left_bound ?: Carbon::now()->subDays(self::DAYS_TO_FETCH);
$right_bound = $user_right_bound ?: Carbon::now();
if (Carbon::parse($right_bound)->gt(Carbon::now()) && !session('error')) {
// Right bound must not be greater than current time
// i.e cannot be in the future
return redirect()->back()->with('error', 'Right date bound cannot be in the future.');
}
if (!$this->isLoggedIn()) {
return redirect(route('login'))->with('error', 'Please login to view link stats.');
}
$link = Link::where('short_url', $short_url)
->first();
// Return 404 if link not found
if ($link == null) {
return redirect(route('admin'))->with('error', 'Cannot show stats for nonexistent link.');
}
if (!env('SETTING_ADV_ANALYTICS')) {
return redirect(route('login'))->with('error', 'Please enable advanced analytics to view this page.');
}
$link_id = $link->id;
if ( (session('username') != $link->creator) && !self::currIsAdmin() ) {
return redirect(route('admin'))->with('error', 'You do not have permission to view stats for this link.');
}
try {
// Initialize StatHelper
$stats = new StatsHelper($link_id, $left_bound, $right_bound);
}
catch (\Exception $e) {
if (!session('error')) {
// Do not flash error if there is already an error flashed
return redirect()->back()->with('error', 'Invalid date bounds.
The right date bound must be more recent than the left bound.');
}
}
$day_stats = $stats->getDayStats();
$country_stats = $stats->getCountryStats();
$referer_stats = $stats->getRefererStats();
return view('link_stats', [
'link' => $link,
'day_stats' => $day_stats,
'country_stats' => $country_stats,
'referer_stats' => $referer_stats,
'left_bound' => ($user_left_bound ?: $left_bound->toDateTimeString()),
'right_bound' => ($user_right_bound ?: $right_bound->toDateTimeString()),
'no_div_padding' => true
]);
}
}
| |
php
|
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Helpers\LinkHelper;
use App\Helpers\UserHelper;
use App\Helpers\StatsHelper;
use App\Exceptions\Api\ApiException;
class ApiAnalyticsController extends ApiController {
public function lookupLinkStats (Request $request, $stats_type=false) {
$user = $request->user;
$response_type = $request->input('response_type') ?: 'json';
if ($user->anonymous) {
throw new ApiException('AUTH_ERROR', 'Anonymous access of this API is not permitted.', 401, $response_type);
}
if ($response_type != 'json') {
throw new ApiException('JSON_ONLY', 'Only JSON-encoded data is available for this endpoint.', 401, $response_type);
}
$validator = \Validator::make($request->all(), [
'url_ending' => 'required|alpha_dash',
'stats_type' => 'alpha_num',
'left_bound' => 'date',
'right_bound' => 'date'
]);
if ($validator->fails()) {
throw new ApiException('MISSING_PARAMETERS', 'Invalid or missing parameters.', 400, $response_type);
}
$url_ending = $request->input('url_ending');
$stats_type = $request->input('stats_type');
$left_bound = $request->input('left_bound');
$right_bound = $request->input('right_bound');
$stats_type = $request->input('stats_type');
// ensure user can only read own analytics or user is admin
$link = LinkHelper::linkExists($url_ending);
if ($link === false) {
throw new ApiException('NOT_FOUND', 'Link not found.', 404, $response_type);
}
if (($link->creator != $user->username) &&
!(UserHelper::userIsAdmin($user->username))){
// If user does not own link and is not an admin
throw new ApiException('ACCESS_DENIED', 'Unauthorized.', 401, $response_type);
}
try {
$stats = new StatsHelper($link->id, $left_bound, $right_bound);
}
catch (\Exception $e) {
throw new ApiException('ANALYTICS_ERROR', $e->getMessage(), 400, $response_type);
}
if ($stats_type == 'day') {
$fetched_stats = $stats->getDayStats();
}
else if ($stats_type == 'country') {
$fetched_stats = $stats->getCountryStats();
}
else if ($stats_type == 'referer') {
$fetched_stats = $stats->getRefererStats();
}
else {
throw new ApiException('INVALID_ANALYTICS_TYPE', 'Invalid analytics type requested.', 400, $response_type);
}
return self::encodeResponse([
'url_ending' => $link->short_url,
'data' => $fetched_stats,
], 'data_link_' . $stats_type, $response_type, false);
}
}
| |
php
|
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
class ApiController extends Controller {
protected static function encodeResponse($result, $action, $response_type='json', $plain_text_response=false) {
$response = [
"action" => $action,
"result" => $result
];
if ($response_type == 'json') {
return response(json_encode($response))
->header('Content-Type', 'application/json')
->header('Access-Control-Allow-Origin', '*');
}
else {
if ($plain_text_response) {
// return alternative plain text response if provided
$result = $plain_text_response;
}
// assume plain text if json not requested
return response($result)
->header('Content-Type', 'text/plain')
->header('Access-Control-Allow-Origin', '*');
}
}
}
| |
php
|
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Factories\LinkFactory;
use App\Helpers\LinkHelper;
use App\Exceptions\Api\ApiException;
class ApiLinkController extends ApiController {
protected function getShortenedLink($long_url, $is_secret, $custom_ending, $link_ip, $username, $response_type) {
try {
$formatted_link = LinkFactory::createLink(
$long_url, $is_secret, $custom_ending, $link_ip, $username, false, true);
}
catch (\Exception $e) {
throw new ApiException('CREATION_ERROR', $e->getMessage(), 400, $response_type);
}
return $formatted_link;
}
public function shortenLink(Request $request) {
$response_type = $request->input('response_type');
$user = $request->user;
$validator = \Validator::make(array_merge([
'url' => str_replace(' ', '%20', $request->input('url'))
], $request->except('url')), [
'url' => 'required|url'
]);
if ($validator->fails()) {
throw new ApiException('MISSING_PARAMETERS', 'Invalid or missing parameters.', 400, $response_type);
}
$formatted_link = $this->getShortenedLink(
$request->input('url'),
($request->input('is_secret') == 'true' ? true : false),
$request->input('custom_ending'),
$request->ip(),
$user->username,
$response_type
);
return self::encodeResponse($formatted_link, 'shorten', $response_type);
}
public function shortenLinksBulk(Request $request) {
$response_type = $request->input('response_type', 'json');
$request_data = $request->input('data');
$user = $request->user;
$link_ip = $request->ip();
$username = $user->username;
if ($response_type != 'json') {
throw new ApiException('JSON_ONLY', 'Only JSON-encoded responses are available for this endpoint.', 401, $response_type);
}
$links_array_raw_json = json_decode($request_data, true);
if ($links_array_raw_json === null) {
throw new ApiException('INVALID_PARAMETERS', 'Invalid JSON.', 400, $response_type);
}
$links_array = $links_array_raw_json['links'];
foreach ($links_array as $link) {
$validator = \Validator::make($link, [
'url' => 'required|url'
]);
if ($validator->fails()) {
throw new ApiException('MISSING_PARAMETERS', 'Invalid or missing parameters.', 400, $response_type);
}
}
$formatted_links = [];
foreach ($links_array as $link) {
$formatted_link = $this->getShortenedLink(
$link['url'],
(array_get($link, 'is_secret') == 'true' ? true : false),
array_get($link, 'custom_ending'),
$link_ip,
$username,
$response_type
);
$formatted_links[] = [
'long_url' => $link['url'],
'short_url' => $formatted_link
];
}
return self::encodeResponse([
'shortened_links' => $formatted_links
], 'shorten_bulk', 'json');
}
public function lookupLink(Request $request) {
$user = $request->user;
$response_type = $request->input('response_type');
// Validate URL form data
$validator = \Validator::make($request->all(), [
'url_ending' => 'required|alpha_dash'
]);
if ($validator->fails()) {
throw new ApiException('MISSING_PARAMETERS', 'Invalid or missing parameters.', 400, $response_type);
}
$url_ending = $request->input('url_ending');
// "secret" key required for lookups on secret URLs
$url_key = $request->input('url_key');
$link = LinkHelper::linkExists($url_ending);
if ($link['secret_key']) {
if ($url_key != $link['secret_key']) {
throw new ApiException('ACCESS_DENIED', 'Invalid URL code for secret URL.', 401, $response_type);
}
}
if ($link) {
return self::encodeResponse([
'long_url' => $link['long_url'],
'created_at' => $link['created_at'],
'clicks' => $link['clicks'],
'updated_at' => $link['updated_at'],
'created_at' => $link['created_at']
], 'lookup', $response_type, $link['long_url']);
}
else {
throw new ApiException('NOT_FOUND', 'Link not found.', 404, $response_type);
}
}
}
| |
php
|
<?php
namespace App\Http\Middleware;
use Laravel\Lumen\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* Exclude API routes from CSRF protection.
*
* @var array
*/
public function handle($request, \Closure $next) {
if ($request->is('api/v*/action/*') || $request->is('api/v*/data/*')) {
// Exclude public API from CSRF protection
// but do not exclude private API endpoints
return $next($request);
}
return parent::handle($request, $next);
}
}
| |
php
|
<?php
namespace App\Http\Middleware;
use Closure;
class ExampleMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
}
| |
php
|
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use App\Models\User;
use App\Helpers\ApiHelper;
use App\Exceptions\Api\ApiException;
class ApiMiddleware {
protected static function getApiUserInfo(Request $request) {
$api_key = $request->input('key');
$response_type = $request->input('response_type');
if (!$api_key) {
// no API key provided; check whether anonymous API is enabled
if (env('SETTING_ANON_API')) {
$username = 'ANONIP-' . $request->ip();
}
else {
throw new ApiException('AUTH_ERROR', 'Authentication token required.', 401, $response_type);
}
$user = (object) [
'username' => $username,
'anonymous' => true
];
}
else {
$user = User::where('active', 1)
->where('api_key', $api_key)
->where('api_active', 1)
->first();
if (!$user) {
throw new ApiException('AUTH_ERROR', 'Authentication token invalid.', 401, $response_type);
}
$username = $user->username;
$user->anonymous = false;
}
$api_limit_reached = ApiHelper::checkUserApiQuota($username);
if ($api_limit_reached) {
throw new ApiException('QUOTA_EXCEEDED', 'Quota exceeded.', 429, $response_type);
}
return $user;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
$request->user = $this->getApiUserInfo($request);
return $next($request);
}
}
| |
php
|
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
abstract class Job implements SelfHandling, ShouldQueue
{
/*
|--------------------------------------------------------------------------
| Queueable Jobs
|--------------------------------------------------------------------------
|
| This job base class provides a central location to place any logic that
| is shared across all of your jobs. The trait included with the class
| provides access to the "queueOn" and "delay" queue helper methods.
|
*/
use InteractsWithQueue, Queueable, SerializesModels;
}
| |
php
|
<?php
namespace App\Helpers;
use App\Models\Click;
use App\Models\Link;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class StatsHelper {
function __construct($link_id, $left_bound, $right_bound) {
$this->link_id = $link_id;
$this->left_bound_parsed = Carbon::parse($left_bound);
$this->right_bound_parsed = Carbon::parse($right_bound);
if (!$this->left_bound_parsed->lte($this->right_bound_parsed)) {
// If left bound is not less than or equal to right bound
throw new \Exception('Invalid bounds.');
}
$days_diff = $this->left_bound_parsed->diffInDays($this->right_bound_parsed);
$max_days_diff = env('_ANALYTICS_MAX_DAYS_DIFF') ?: 365;
if ($days_diff > $max_days_diff) {
throw new \Exception('Bounds too broad.');
}
}
public function getBaseRows() {
/**
* Fetches base rows given left date bound, right date bound, and link id
*
* @param integer $link_id
* @param string $left_bound
* @param string $right_bound
*
* @return DB rows
*/
return DB::table('clicks')
->where('link_id', $this->link_id)
->where('created_at', '>=', $this->left_bound_parsed)
->where('created_at', '<=', $this->right_bound_parsed);
}
public function getDayStats() {
// Return stats by day from the last 30 days
// date => x
// clicks => y
$stats = $this->getBaseRows()
->select(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d') AS x, count(*) AS y"))
->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))
->orderBy('x', 'asc')
->get();
return $stats;
}
public function getCountryStats() {
$stats = $this->getBaseRows()
->select(DB::raw("country AS label, count(*) AS clicks"))
->groupBy('country')
->orderBy('clicks', 'desc')
->whereNotNull('country')
->get();
return $stats;
}
public function getRefererStats() {
$stats = $this->getBaseRows()
->select(DB::raw("COALESCE(referer_host, 'Direct') as label, count(*) as clicks"))
->groupBy('referer_host')
->orderBy('clicks', 'desc')
->get();
return $stats;
}
}
| |
php
|
<?php
namespace App\Helpers;
use App\Models\Link;
use App\Helpers\BaseHelper;
class LinkHelper {
static public function checkIfAlreadyShortened($long_link) {
/**
* Provided a long link (string),
* detect whether the link belongs to an URL shortener.
* @return boolean
*/
$shortener_domains = [
'polr.me',
'bit.ly',
'is.gd',
'tiny.cc',
'adf.ly',
'ur1.ca',
'goo.gl',
'ow.ly',
'j.mp',
't.co',
env('APP_ADDRESS')
];
foreach ($shortener_domains as $shortener_domain) {
$url_segment = ('://' . $shortener_domain);
if (strstr($long_link, $url_segment)) {
return true;
}
}
return false;
}
static public function linkExists($link_ending) {
/**
* Provided a link ending (string),
* return the link object, or false.
* @return Link model instance
*/
$link = Link::where('short_url', $link_ending)
->first();
if ($link != null) {
return $link;
}
else {
return false;
}
}
static public function longLinkExists($long_url, $username=false) {
/**
* Provided a long link (string),
* check whether the link is in the DB.
* If a username is provided, only search for links created by the
* user.
* @return boolean
*/
$link_base = Link::longUrl($long_url)
->where('is_custom', 0)
->where('secret_key', '');
if (is_null($username)) {
// Search for links without a creator only
$link = $link_base->where('creator', '')->first();
}
else if (($username !== false)) {
// Search for links created by $username only
$link = $link_base->where('creator', $username)->first();
}
else {
// Search for links created by any user
$link = $link_base->first();
}
if ($link == null) {
return false;
}
else {
return $link->short_url;
}
}
static public function validateEnding($link_ending) {
$is_valid_ending = preg_match('/^[a-zA-Z0-9-_]+$/', $link_ending);
return $is_valid_ending;
}
static public function findPseudoRandomEnding() {
/**
* Return an available pseudorandom string of length _PSEUDO_RANDOM_KEY_LENGTH,
* as defined in .env
* Edit _PSEUDO_RANDOM_KEY_LENGTH in .env if you wish to increase the length
* of the pseudorandom string generated.
* @return string
*/
$pr_str = '';
$in_use = true;
while ($in_use) {
// Generate a new string until the ending is not in use
$pr_str = str_random(env('_PSEUDO_RANDOM_KEY_LENGTH'));
$in_use = LinkHelper::linkExists($pr_str);
}
return $pr_str;
}
static public function findSuitableEnding() {
/**
* Provided an in-use link ending (string),
* find the next available base-32/62 ending.
* @return string
*/
$base = env('POLR_BASE');
$link = Link::where('is_custom', 0)
->orderBy('created_at', 'desc')
->first();
if ($link == null) {
$base10_val = 0;
$base_x_val = 0;
}
else {
$latest_link_ending = $link->short_url;
$base10_val = BaseHelper::toBase10($latest_link_ending, $base);
$base10_val++;
}
$base_x_val = null;
while (LinkHelper::linkExists($base_x_val) || $base_x_val == null) {
$base_x_val = BaseHelper::toBase($base10_val, $base);
$base10_val++;
}
return $base_x_val;
}
}
| |
php
|
<?php
namespace App\Helpers;
use App\Models\User;
use App\Helpers\CryptoHelper;
use Hash;
class UserHelper {
public static $USER_ROLES = [
'admin' => 'admin',
'default' => '',
];
public static function userExists($username) {
/* XXX: used primarily with test cases */
$user = self::getUserByUsername($username, $inactive=true);
return ($user ? true : false);
}
public static function emailExists($email) {
/* XXX: used primarily with test cases */
$user = self::getUserByEmail($email, $inactive=true);
return ($user ? true : false);
}
public static function validateUsername($username) {
return ctype_alnum($username);
}
public static function userIsAdmin($username) {
return (self::getUserByUsername($username)->role == self::$USER_ROLES['admin']);
}
public static function checkCredentials($username, $password) {
$user = User::where('active', 1)
->where('username', $username)
->first();
if ($user == null) {
return false;
}
$correct_password = Hash::check($password, $user->password);
if (!$correct_password) {
return false;
}
else {
return ['username' => $username, 'role' => $user->role];
}
}
public static function resetRecoveryKey($username) {
$recovery_key = CryptoHelper::generateRandomHex(50);
$user = self::getUserByUsername($username);
if (!$user) {
return false;
}
$user->recovery_key = $recovery_key;
$user->save();
return $recovery_key;
}
public static function userResetKeyCorrect($username, $recovery_key, $inactive=false) {
// Given a username and a recovery key, return true if they match.
$user = self::getUserByUsername($username, $inactive);
if ($user) {
if ($recovery_key != $user->recovery_key) {
return false;
}
}
else {
return false;
}
return true;
}
public static function getUserBy($attr, $value, $inactive=false) {
$user = User::where($attr, $value);
if (!$inactive) {
// if user must be active
$user = $user
->where('active', 1);
}
return $user->first();
}
public static function getUserById($user_id, $inactive=false) {
return self::getUserBy('id', $user_id, $inactive);
}
public static function getUserByUsername($username, $inactive=false) {
return self::getUserBy('username', $username, $inactive);
}
public static function getUserByEmail($email, $inactive=false) {
return self::getUserBy('email', $email, $inactive);
}
}
| |
php
|
<?php
namespace App\Helpers;
// http://stackoverflow.com/questions/4964197/converting-a-number-base-10-to-base-62-a-za-z0-9/4964352#4964352
class BaseHelper {
public static function toBase($num, $b=62) {
$base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$r = $num % $b;
$res = $base[$r];
$q = floor($num/$b);
while ($q) {
$r = $q % $b;
$q = floor($q/$b);
$res = $base[$r] . $res;
}
return $res;
}
public static function toBase10($num, $b=62) {
$base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$limit = strlen($num);
$res = strpos($base,$num[0]);
for ($i=1; $i<$limit; $i++) {
$res = $b * $res + strpos($base, $num[$i]);
}
return $res;
}
}
| |
php
|
<?php
namespace App\Helpers;
class CryptoHelper {
public static function generateRandomHex($rand_bytes_num) {
$rand_bytes = random_bytes($rand_bytes_num);
return bin2hex($rand_bytes);
}
}
| |
php
|
<?php
namespace App\Helpers;
class AdminHelper {
public static function pass() {
}
}
| |
php
|
<?php
namespace App\Helpers;
use App\Models\Link;
use App\Helpers\UserHelper;
class ApiHelper {
public static function checkUserApiQuota($username) {
/**
*
* @return boolean; whether API quota is met
*/
$last_minute_unix = time() - 60;
$last_minute = new \DateTime();
$last_minute->setTimestamp($last_minute_unix);
$user = UserHelper::getUserByUsername($username);
if ($user) {
$api_quota = $user->api_quota;
}
else {
$api_quota = env('SETTING_ANON_API_QUOTA') ?: 5;
}
if ($api_quota < 0) {
return false;
}
$links_last_minute = Link::where('is_api', 1)
->where('creator', $username)
->where('created_at', '>=', $last_minute)
->count();
return $links_last_minute >= $api_quota;
}
}
| |
php
|
<?php
namespace App\Helpers;
use App\Models\Click;
use App\Models\Link;
use Illuminate\Http\Request;
class ClickHelper {
static private function getCountry($ip) {
$country_iso = geoip()->getLocation($ip)->iso_code;
return $country_iso;
}
static private function getHost($url) {
// Return host given URL; NULL if host is
// not found.
return parse_url($url, PHP_URL_HOST);
}
static public function recordClick(Link $link, Request $request) {
/**
* Given a Link model instance and Request object, process post click operations.
* @param Link model instance $link
* @return boolean
*/
$ip = $request->ip();
$referer = $request->server('HTTP_REFERER');
$click = new Click;
$click->link_id = $link->id;
$click->ip = $ip;
$click->country = self::getCountry($ip);
$click->referer = $referer;
$click->referer_host = ClickHelper::getHost($referer);
$click->user_agent = $request->server('HTTP_USER_AGENT');
$click->save();
return true;
}
}
| |
php
|
<?php
namespace App\Listeners;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
abstract class Listener
{
//
}
| |
php
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Click extends Model {
protected $table = 'clicks';
}
| |
php
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Link extends Model {
protected $table = 'links';
public function setLongUrlAttribute($long_url) {
// Set crc32 hash and long_url
// whenever long_url is set on a Link instance
// Generate 32-bit unsigned integer crc32 value
// Use sprintf to prevent compatibility issues with 32-bit systems
// http://php.net/manual/en/function.crc32.php
$crc32_hash = sprintf('%u', crc32($long_url));
$this->attributes['long_url'] = $long_url;
$this->attributes['long_url_hash'] = $crc32_hash;
}
public function scopeLongUrl($query, $long_url) {
// Allow quick lookups with Link::longUrl that make use
// of the indexed crc32 hash to quickly fetch link
$crc32_hash = sprintf('%u', crc32($long_url));
return $query
->where('long_url_hash', $crc32_hash)
->where('long_url', $long_url);
}
}
| |
php
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
protected $table = 'users';
}
| |
php
|
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Laravel\Lumen\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
\Torann\GeoIP\Console\Update::class
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
//
}
}
| |
php
|
<?php
namespace App\Factories;
use Hash;
use App\Models\User;
use App\Helpers\CryptoHelper;
use App\Helpers\UserHelper;
class UserFactory {
public static function createUser($username, $email, $password, $active=0, $ip='127.0.0.1', $api_key=false, $api_active=0, $role=false) {
if (!$role) {
$role = UserHelper::$USER_ROLES['default'];
}
$hashed_password = Hash::make($password);
$recovery_key = CryptoHelper::generateRandomHex(50);
$user = new User;
$user->username = $username;
$user->password = $hashed_password;
$user->email = $email;
$user->recovery_key = $recovery_key;
$user->active = $active;
$user->ip = $ip;
$user->role = $role;
$user->api_key = $api_key;
$user->api_active = $api_active;
$user->save();
return $user;
}
}
| |
php
|
<?php
namespace App\Factories;
use App\Models\Link;
use App\Helpers\CryptoHelper;
use App\Helpers\LinkHelper;
class LinkFactory {
const MAXIMUM_LINK_LENGTH = 65535;
private static function formatLink($link_ending, $secret_ending=false) {
/**
* Given a link ending and a boolean indicating whether a secret ending is needed,
* return a link formatted with app protocol, app address, and link ending.
* @param string $link_ending
* @param boolean $secret_ending
* @return string
*/
$short_url = env('APP_PROTOCOL') . env('APP_ADDRESS') . '/' . $link_ending;
if ($secret_ending) {
$short_url .= '/' . $secret_ending;
}
return $short_url;
}
public static function createLink($long_url, $is_secret=false, $custom_ending=null, $link_ip='127.0.0.1', $creator=false, $return_object=false, $is_api=false) {
/**
* Given parameters needed to create a link, generate appropriate ending and
* return formatted link.
*
* @param string $custom_ending
* @param boolean (optional) $is_secret
* @param string (optional) $custom_ending
* @param string $link_ip
* @param string $creator
* @param bool $return_object
* @param bool $is_api
* @return string $formatted_link
*/
if (strlen($long_url) > self::MAXIMUM_LINK_LENGTH) {
// If $long_url is longer than the maximum length, then
// throw an Exception
throw new \Exception('Sorry, but your link is longer than the
maximum length allowed.');
}
$is_already_short = LinkHelper::checkIfAlreadyShortened($long_url);
if ($is_already_short) {
throw new \Exception('Sorry, but your link already
looks like a shortened URL.');
}
if (!$is_secret && (!isset($custom_ending) || $custom_ending === '') && (LinkHelper::longLinkExists($long_url, $creator) !== false)) {
// if link is not specified as secret, is non-custom, and
// already exists in Polr, lookup the value and return
$existing_link = LinkHelper::longLinkExists($long_url, $creator);
return self::formatLink($existing_link);
}
if (isset($custom_ending) && $custom_ending !== '') {
// has custom ending
$ending_conforms = LinkHelper::validateEnding($custom_ending);
if (!$ending_conforms) {
throw new \Exception('Custom endings
can only contain alphanumeric characters, hyphens, and underscores.');
}
$ending_in_use = LinkHelper::linkExists($custom_ending);
if ($ending_in_use) {
throw new \Exception('This URL ending is already in use.');
}
$link_ending = $custom_ending;
}
else {
if (env('SETTING_PSEUDORANDOM_ENDING')) {
// generate a pseudorandom ending
$link_ending = LinkHelper::findPseudoRandomEnding();
}
else {
// generate a counter-based ending or use existing ending if possible
$link_ending = LinkHelper::findSuitableEnding();
}
}
$link = new Link;
$link->short_url = $link_ending;
$link->long_url = $long_url;
$link->ip = $link_ip;
$link->is_custom = $custom_ending != null;
$link->is_api = $is_api;
if ($creator) {
$link->creator = $creator;
}
if ($is_secret) {
$rand_bytes_num = intval(env('POLR_SECRET_BYTES'));
$secret_key = CryptoHelper::generateRandomHex($rand_bytes_num);
$link->secret_key = $secret_key;
}
else {
$secret_key = false;
}
$link->save();
$formatted_link = self::formatLink($link_ending, $secret_key);
if ($return_object) {
return $link;
}
return $formatted_link;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.