-
Notifications
You must be signed in to change notification settings - Fork 248
Expand file tree
/
Copy pathProcessMakerServiceProvider.php
More file actions
612 lines (510 loc) · 20.9 KB
/
ProcessMakerServiceProvider.php
File metadata and controls
612 lines (510 loc) · 20.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
<?php
namespace ProcessMaker\Providers;
use Illuminate\Database\Console\Migrations\MigrateCommand;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Foundation\PackageManifest;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Notifications\Events\BroadcastNotificationCreated;
use Illuminate\Notifications\Events\NotificationSent;
use Illuminate\Queue\Events\JobAttempted;
use Illuminate\Queue\Events\JobProcessing;
use Illuminate\Queue\Events\JobRetryRequested;
use Illuminate\Support\Arr;
use Illuminate\Support\Env;
use Illuminate\Support\Facades;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\URL;
use Laravel\Dusk\DuskServiceProvider;
use Laravel\Horizon\Horizon;
use Lavary\Menu\Menu;
use ProcessMaker\Cache\Settings\SettingCacheManager;
use ProcessMaker\Console\Migration\ExtendedMigrateCommand;
use ProcessMaker\Events\ActivityAssigned;
use ProcessMaker\Events\ScreenBuilderStarting;
use ProcessMaker\Events\TenantResolved;
use ProcessMaker\Exception\MultitenancyAccessedLandlord;
use ProcessMaker\Exception\MultitenancyNoTenantFound;
use ProcessMaker\Helpers\PmHash;
use ProcessMaker\Http\Middleware\Etag\HandleEtag;
use ProcessMaker\ImportExport\Extension;
use ProcessMaker\ImportExport\SignalHelper;
use ProcessMaker\Jobs\SmartInbox;
use ProcessMaker\LicensedPackageManifest;
use ProcessMaker\Managers;
use ProcessMaker\Managers\MenuManager;
use ProcessMaker\Managers\ScreenCompiledManager;
use ProcessMaker\Models;
use ProcessMaker\Multitenancy\Tenant;
use ProcessMaker\Multitenancy\TenantBootstrapper;
use ProcessMaker\Observers;
use ProcessMaker\PolicyExtension;
use ProcessMaker\Repositories\SettingsConfigRepository;
use RuntimeException;
use Spatie\Multitenancy\Events\MadeTenantCurrentEvent;
use Spatie\Multitenancy\Events\TenantNotFoundForRequestEvent;
use Spatie\Multitenancy\TenantCollection;
/**
* Provide our ProcessMaker specific services.
*/
class ProcessMakerServiceProvider extends ServiceProvider
{
// Track the start time for service providers boot
private static $bootStart;
// Track the boot time for service providers
private static $bootTime;
// Track the boot time for each package
private static $packageBootTiming = [];
// Track the query time for each request
private static $queryTime = 0;
// Track the landlord values for multitenancy
private static $landlordValues = null;
// Cache tenant app containers to save memory
private static $tenantAppContainers = [];
public function boot(): void
{
// Track the start time for service providers boot
self::$bootStart = microtime(true);
// Set the current tenant
$this->setCurrentTenantForConsoleCommands();
$this->app->singleton(Menu::class, function ($app) {
return new MenuManager();
});
static::bootObservers();
static::extendValidators();
static::extendDrivers();
static::forceHttps();
$this->setupFactories();
parent::boot();
Route::pushMiddlewareToGroup('api', HandleEtag::class);
// Hook after service providers boot
self::$bootTime = (microtime(true) - self::$bootStart) * 1000; // Convert to milliseconds
}
public function register(): void
{
if (config('app.server_timing.enabled')) {
// Listen to query events and accumulate query execution time
DB::listen(function ($query) {
self::$queryTime += $query->time;
});
}
// Dusk, if env is appropriate
// TODO Remove Dusk references and remove from composer dependencies
if (!$this->app->environment('production')) {
$this->app->register(DuskServiceProvider::class);
}
$this->app->singleton(Managers\PackageManager::class, function () {
return new Managers\PackageManager();
});
$this->app->singleton(Managers\LoginManager::class, function () {
return new Managers\LoginManager();
});
/*
* Maps our Index Manager as a singleton. The Index Manager is used
* to manage customizations to the search indexer.
*/
$this->app->singleton(Managers\IndexManager::class, function () {
return new Managers\IndexManager();
});
$this->app->make(Managers\IndexManager::class)
->add('Requests', Models\ProcessRequest::class);
$this->app->make(Managers\IndexManager::class)
->add('Tasks', Models\ProcessRequestToken::class);
/*
* Maps our Modeler Manager as a singleton. The Modeler Manager is used
* to manage customizations to the Process Modeler.
*/
$this->app->singleton(Managers\ModelerManager::class, function ($app) {
return new Managers\ModelerManager();
});
/*
* Maps our Screen Builder Manager as a singleton. The Screen Builder Manager is used
* to manage customizations to the Screen Builder.
*/
$this->app->singleton(Managers\ScreenBuilderManager::class, function ($app) {
return new Managers\ScreenBuilderManager();
});
/*
* Maps our Script Builder Manager as a singleton. The Script builder Manager is used
* to manage customizations to the Process Script Builder.
*/
$this->app->singleton(Managers\ScriptBuilderManager::class, function ($app) {
return new Managers\ScriptBuilderManager();
});
$this->app->singleton(PmHash::class, function () {
return new PmHash();
});
$this->app->singleton(Models\RequestDevice::class, function () {
return new Models\RequestDevice();
});
/*
* Maps our Docker Manager as a singleton. The Docker Manager is used
* to manage docker execution over the application.
*/
$this->app->singleton(Managers\DockerManager::class, function ($app) {
return new Managers\DockerManager();
});
$this->app->singleton(Managers\GlobalScriptsManager::class, function ($app) {
return new Managers\GlobalScriptsManager();
});
$this->app->singleton(Models\AnonymousUser::class, function ($app) {
return Models\AnonymousUser::where('username', '=', Models\AnonymousUser::ANONYMOUS_USERNAME)
->firstOrFail();
});
$this->app->singleton(PolicyExtension::class, function ($app) {
return new PolicyExtension();
});
// Define the Import/Export Extension object as a singleton
$this->app->singleton(Extension::class);
// Define the SignalHelper object as a singleton
$this->app->singleton(SignalHelper::class);
// Register app-level events
static::registerEvents();
// Miscellaneous vendor customization
static::configureVendors();
$this->app->singleton(PackageManifest::class, fn () => new LicensedPackageManifest(
new Filesystem, $this->app->basePath(), $this->app->getCachedPackagesPath()
));
$this->app->extend(MigrateCommand::class, function () {
return new ExtendedMigrateCommand(
app('migrator'),
app('events')
);
});
// Register the compiled screen service
$this->app->singleton('compiledscreen', function ($app) {
return new ScreenCompiledManager();
});
$this->app->singleton('setting.cache', function ($app) {
if ($app['config']->get('cache.stores.cache_settings')) {
return new SettingCacheManager($app->make('cache'));
} else {
throw new RuntimeException('Cache configuration is missing.');
}
});
$this->app->extend('config', function ($originalConfig) {
return new SettingsConfigRepository($originalConfig->all());
});
$this->app->singleton('currentTenant', function () {
return null;
});
$this->app->instance('tenant-resolved', false);
}
/**
* In multitenancy, we need to bootstrap a new app with the tenant id set.
* This is because queue workers are long-running processes that are not
* tenant aware.
*/
private static function bootstrapTenantApp(JobProcessing|JobRetryRequested $event): void
{
Context::hydrate($event->job->payload()['illuminate:log:context'] ?? null);
$tenantId = Context::get(config('multitenancy.current_tenant_context_key'));
if ($tenantId) {
if (!method_exists($event->job, 'getRedisQueue')) {
// Not a redis job
return;
}
// Create a new tenant app instance
$_SERVER['TENANT'] = $tenantId;
if (!isset(self::$tenantAppContainers[$tenantId])) {
self::$tenantAppContainers[$tenantId] = require base_path('bootstrap/app.php');
}
self::$tenantAppContainers[$tenantId]->reactivateConsoleApp();
// Change the job's app service container to the tenant app
$event->job->getRedisQueue()->setContainer(self::$tenantAppContainers[$tenantId]);
}
}
/**
* Register app-level events.
*/
protected static function registerEvents(): void
{
Facades\Event::listen(JobProcessing::class, function (JobProcessing $event) {
self::bootstrapTenantApp($event);
});
Facades\Event::listen(JobRetryRequested::class, function (JobRetryRequested $event) {
self::bootstrapTenantApp($event);
});
// Listen to the events for our core screen
// types and add our javascript
Facades\Event::listen(ScreenBuilderStarting::class, function ($event) {
// Add any extensions to form builder
// and renderer from packages
$event->manager->addPackageScripts($event->type);
switch ($event->type) {
case 'FORM':
$event->manager->addScript(mix('js/processes/screen-builder/typeForm.js'));
break;
case 'DISPLAY':
$event->manager->addScript(mix('js/processes/screen-builder/typeDisplay.js'));
break;
}
});
// Log Notifications
Facades\Event::listen(NotificationSent::class, function ($event) {
$id = $event->notifiable->id;
$notifiable = get_class($event->notifiable);
$notification = get_class($event->notification);
Log::debug("Sent Notification to {$notifiable} #{$id}: {$notification}");
});
// Log Broadcasts (messages sent to laravel-echo-server and redis)
Facades\Event::listen(BroadcastNotificationCreated::class, function ($event) {
$channels = implode(', ', $event->broadcastOn());
Log::debug('Broadcasting Notification ' . $event->broadcastType() . 'on channel(s) ' . $channels);
});
// Fire job when task is assigned to a user
Facades\Event::listen(ActivityAssigned::class, function ($event) {
$task_id = $event->getProcessRequestToken()->id;
// Dispatch the SmartInbox job with the processRequestToken as parameter
SmartInbox::dispatch($task_id);
});
Facades\Event::listen(MadeTenantCurrentEvent::class, function ($event) {
event(new TenantResolved($event->tenant));
});
Facades\Event::listen(TenantNotFoundForRequestEvent::class, function ($event) {
if (config('app.multitenancy') === false || self::actuallyRunningInConsole()) {
// This is expected if multitenancy is disabled.
// We also need to check if we are running in a console command because
// sometimes we run them with APP_RUNNING_IN_CONSOLE=false which will
// trigger TenantNotFoundForRequestEvent and we don't want to
// stop execution because of that.
// Call the TenantResolved event with null to continue loading the app.
event(new TenantResolved(null));
} else {
// Multitenancy is enabled, but no tenant was found.
// Check if we are attempting to access the landlord directly (by comparing app.url)
// If so, show thelandlord landing page.
$requestHost = $event->request->getHost();
$appHost = parse_url(config('app.url'), PHP_URL_HOST);
if ($appHost === $requestHost) {
throw new MultitenancyAccessedLandlord();
}
// Otherwise, show a 404 page.
throw new MultitenancyNoTenantFound();
}
});
}
/**
* Bind and boot model observers.
*/
protected static function bootObservers(): void
{
Models\User::observe(Observers\UserObserver::class);
Models\Setting::observe(Observers\SettingObserver::class);
Models\Process::observe(Observers\ProcessObserver::class);
Models\ProcessRequest::observe(Observers\ProcessRequestObserver::class);
Models\ProcessRequestToken::observe(Observers\ProcessRequestTokenObserver::class);
Models\ProcessCollaboration::observe(Observers\ProcessCollaborationObserver::class);
}
/**
* Register and extend existing validators.
*/
protected static function extendValidators(): void
{
// Laravy Menu
Facades\Blade::directive('lavaryMenuJson', function ($menu) {
return "<?php echo htmlentities(lavaryMenuJson({$menu}), ENT_QUOTES); ?>";
});
// Custom validator for process, scripts, etc.
// names (just alphanumeric, space, apostrophe
// or dash characters)
Facades\Validator::extend('alpha_spaces', function ($attr, $val) {
return preg_match('/^[\pL\s\-\_\d\.\']+$/u', $val);
});
// Custom validator for variable names. Eg: correct var
// names _myvar, myvar, myvar1, _myvar1. Eg: incorrect
// variable names 1_myvar, 1myvar, myvar a
Facades\Validator::extend('valid_variable', function ($attr, $val) {
$key = explode('.', $attr)[1];
return preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $key);
});
}
/**
* Setup/configure various vendor services.
*/
protected static function configureVendors(): void
{
// Allow user to view horizon queue dashboard
Horizon::auth(function ($request) {
return Facades\Auth::user() instanceof Models\User;
});
}
private function setupFactories(): void
{
Factory::guessFactoryNamesUsing(function (string $modelName) {
$factoryFinder = [
[
'/ProcessMaker\\\\Plugins\\\\(.*?)\\\\Models\\\\(.*)/',
fn ($package, $baseName) => 'Database\\Factories\\ProcessMaker\\Plugins\\' . $package . '\\' . $baseName . 'Factory',
],
[
'/ProcessMaker\\\\Packages\\\\Connectors\\\\(.*?)\\\\Models\\\\(.*)/',
fn ($package, $baseName) => 'Database\\Factories\\ProcessMaker\\Plugins\\' . $package . '\\' . $baseName . 'Factory',
],
[
'/ProcessMaker\\\\Package\\\\(.*?)\\\\Models\\\\(.*)/',
fn ($package, $baseName) => 'Database\\Factories\\ProcessMaker\\Package\\' . $package . '\\' . $baseName . 'Factory',
],
[
'/ProcessMaker\\\\Models\\\\(.*)/',
fn ($baseName) => 'Database\\Factories\\ProcessMaker\\Models\\' . $baseName . 'Factory',
],
];
$factory = null;
foreach ($factoryFinder as $matcher) {
if (preg_match($matcher[0], $modelName, $match)) {
$factory = $matcher[1]($match[1], $match[2] ?? null);
break;
}
}
return $factory;
});
Factory::guessModelNamesUsing(function ($factory) {
$modelFinder = [
[
'/Database\\\\Factories\\\\ProcessMaker\\\\Plugins\\\\(.*?)\\\\(.*)Factory/',
function ($package, $baseName) {
$model = 'ProcessMaker\\Plugins\\' . $package . '\\Models\\' . $baseName;
if (class_exists($model)) {
return $model;
} else {
return 'ProcessMaker\\Packages\\Connectors\\' . $package . '\\Models\\' . $baseName;
}
},
],
[
'/Database\\\\Factories\\\\ProcessMaker\\\\Package\\\\(.*?)\\\\(.*)Factory/',
fn ($package, $baseName) => 'ProcessMaker\\Package\\' . $package . '\\Models\\' . $baseName,
],
[
'/Database\\\\Factories\\\\(.*)Factory/',
fn ($match) => $match,
],
];
$model = null;
foreach ($modelFinder as $matcher) {
if (preg_match($matcher[0], get_class($factory), $match)) {
$model = $matcher[1]($match[1], $match[2] ?? null);
break;
}
}
return $model;
});
}
protected static function extendDrivers(): void
{
Facades\Hash::extend('pm', function () {
return resolve(PmHash::class);
});
}
/**
* Force HTTPS schema if configured to do so.
*/
public static function forceHttps(): void
{
if (config('app.force_https')) {
URL::forceScheme('https');
}
}
/**
* Get the boot time for service providers.
*
* @return float|null
*/
public static function getBootTime(): ?float
{
return self::$bootTime;
}
/**
* Get the query time for the request.
*
* @return float
*/
public static function getQueryTime(): float
{
return self::$queryTime;
}
/**
* Set the boot time for service providers.
*
* @param string $package
* @param float $time
*/
public static function setPackageBootStart(string $package, float $time): void
{
if ($time < 0) {
Log::info("Server Timing: Invalid boot time for package: {$package}, time: {$time}");
$time = 0;
}
self::$packageBootTiming[$package] = [
'start' => $time,
'end' => null,
];
}
/**
* Set the boot time for service providers.
*
*
* @param float $time
*/
public static function setPackageBootedTime(string $package, $time): void
{
if (!isset(self::$packageBootTiming[$package]) || $time < 0) {
Log::info("Server Timing: Invalid booted time for package: {$package}, time: {$time}");
return;
}
self::$packageBootTiming[$package]['end'] = $time;
}
/**
* Get the boot time for service providers.
*
* @return array
*/
public static function getPackageBootTiming(): array
{
return self::$packageBootTiming;
}
/**
* Find the tenant based on the environment variable
*/
private function setCurrentTenantForConsoleCommands(): void
{
// See ProcessMaker\Multitenancy\TenantFinder::findForRequest() for disguised console commands (APP_RUNNING_IN_CONSOLE=false)
// We need to do this in 2 places because laravel-multitenancy skips the tenant finder when running in console
if (!app()->runningInConsole()) {
return;
}
if (config('app.multitenancy') === false) {
event(new TenantResolved(null));
return;
}
if ($tenant = Tenant::fromBootstrapper()) {
$tenant->makeCurrent();
return;
}
$tenantId = Env::get('TENANT');
if (!$tenantId) {
event(new TenantResolved(null));
return;
}
$tenant = Tenant::findOrFail($tenantId);
$tenant->makeCurrent();
}
/**
* Check if we are actually running in a console command.
*
* Sometimes we run console commands with APP_RUNNING_IN_CONSOLE=false
* so I took this form the framework to see if we are actually running
* in a console command. We can't NOT use APP_RUNNING_IN_CONSOLE=true
* because some routes are only registered when app()->runningInConsole()
* is false.
* @return bool
*/
private static function actuallyRunningInConsole(): bool
{
return PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
}
}