forked from FOSSBilling/FOSSBilling
-
Notifications
You must be signed in to change notification settings - Fork 0
/
di.php
875 lines (744 loc) · 23.9 KB
/
di.php
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
<?php
declare(strict_types=1);
/**
* Copyright 2022-2024 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
use FOSSBilling\Config;
use FOSSBilling\Environment;
use Lcharette\WebpackEncoreTwig\EntrypointsTwigExtension;
use Lcharette\WebpackEncoreTwig\JsonManifest;
use Lcharette\WebpackEncoreTwig\TagRenderer;
use Lcharette\WebpackEncoreTwig\VersionedAssetsTwigExtension;
use League\CommonMark\Extension\DefaultAttributes\DefaultAttributesExtension;
use RedBeanPHP\Facade;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\WebpackEncoreBundle\Asset\EntrypointLookup;
use Twig\Extension\CoreExtension;
use Twig\Extension\DebugExtension;
use Twig\Extension\StringLoaderExtension;
use Twig\Extra\Intl\IntlExtension;
$di = new Pimple\Container();
/*
* Returns the current FOSSBilling config.
*
* @param void
*
* @deprecated
*
* @return array
*/
$di['config'] = fn () => Config::getConfig();
/*
* Create a new logger instance and configures it based on the settings in the configuration file.
*
* @param void
*
* @return Box_Log A new logger instance
*/
$di['logger'] = function () use ($di) {
$log = new Box_Log();
$log->setDi($di);
$activity_service = $di['mod_service']('activity');
$dbWriter = new Box_LogDb($activity_service);
$log->addWriter($dbWriter);
if ($di['auth']->isAdminLoggedIn()) {
$admin = $di['loggedin_admin'];
$log->setEventItem('admin_id', $admin->id);
} elseif ($di['auth']->isClientLoggedIn()) {
$client = $di['loggedin_client'];
$log->setEventItem('client_id', $client->id);
}
$monolog = new FOSSBilling\Monolog();
$log->addWriter($monolog);
return $log;
};
/*
*
* @param void
*
* @return \Box_Crypt
*/
$di['crypt'] = function () use ($di) {
$crypt = new Box_Crypt();
$crypt->setDi($di);
return $crypt;
};
/*
* Creates a new PDO object for database connections
*
* @param void
*
* @return PDO The PDO object used for database connections
*/
$di['pdo'] = function () {
$config = Config::getProperty('db');
$pdo = new PDO(
$config['type'] . ':host=' . $config['host'] . ';port=' . $config['port'] . ';dbname=' . $config['name'],
$config['user'],
$config['password'],
[
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
if (isset($config['debug']) && $config['debug']) {
$pdo->setAttribute(PDO::ATTR_STATEMENT_CLASS, ['Box_DbLoggedPDOStatement']);
}
if ($config['type'] === 'mysql') {
$pdo->exec('SET NAMES "utf8"');
$pdo->exec('SET CHARACTER SET utf8');
$pdo->exec('SET CHARACTER_SET_CONNECTION = utf8');
$pdo->exec('SET character_set_results = utf8');
$pdo->exec('SET character_set_server = utf8');
$pdo->exec('SET SESSION interactive_timeout = 28800');
$pdo->exec('SET SESSION wait_timeout = 28800');
// Get the timezone offset in the PDO format
$datetime = new DateTime('now');
$offset = $datetime->format('P');
$pdo->exec("SET time_zone = '{$offset}'");
}
return $pdo;
};
/*
*
* @param void
*
* @return \Box_Database The new Box_Database object that was just created.
*/
$di['db'] = function () use ($di) {
RedBeanPHP\R::setup($di['pdo']);
RedBeanPHP\Util\DispenseHelper::setEnforceNamingPolicy(false);
$helper = new Box_BeanHelper();
$helper->setDi($di);
$mapper = new Facade();
$mapper->getRedBean()->setBeanHelper($helper);
$freeze = Config::getProperty('db.freeze', true);
$mapper->freeze($freeze);
$db = new Box_Database();
$db->setDi($di);
$db->setDataMapper($mapper);
return $db;
};
/*
*
* @param void
*
* @return Box_Pagination
*/
$di['pager'] = function () use ($di) {
$service = new Box_Pagination();
$service->setDi($di);
return $service;
};
/*
*
* @param void
*
* @return Box_Url
*/
$di['url'] = function () use ($di) {
$url = new Box_Url();
$url->setDi($di);
$url->setBaseUri(SYSTEM_URL);
return $url;
};
/*
* Returns a new Box_Mod object, created with the provided module name.
*
* @param string $name The name of the module to create the object with.
*
* @return \Box_Mod The new Box_Mod object that was just created.
*/
$di['mod'] = $di->protect(function ($name) use ($di) {
$mod = new Box_Mod($name);
$mod->setDi($di);
return $mod;
});
/*
*
* @param string $mod the name of the module to get
*
* @return mixed the service of the associated module
*/
$di['mod_service'] = $di->protect(fn ($mod, $sub = '') => $di['mod']($mod)->getService($sub));
/*
*
* @param string $name the name of the module to get the configuration of
*
* @return mixed the configuration of the associated module
*/
$di['mod_config'] = $di->protect(fn ($name) => $di['mod']($name)->getConfig());
/*
*
* @param void
*
* @return \Box_EventManager
*/
$di['events_manager'] = function () use ($di) {
$service = new Box_EventManager();
$service->setDi($di);
return $service;
};
/*
* Creates a new session, applying specified security rules depending on the config.php settings.
*
* @param void
*
* @return \FOSSBilling\Session
*/
$di['session'] = function () use ($di) {
$handler = new PdoSessionHandler($di['pdo']);
$session = new FOSSBilling\Session($handler);
$session->setDi($di);
$session->setupSession();
return $session;
};
/*
*
* @param void
*
* @return \FOSSBilling\Request
*/
$di['request'] = function () use ($di) {
$service = new FOSSBilling\Request();
$service->setDi($di);
return $service;
};
/*
* @param void
*
* @return \Symfony\Component\Cache\Adapter\FilesystemAdapter
*/
$di['cache'] = fn () =>
// Reference: https://symfony.com/doc/current/components/cache/adapters/filesystem_adapter.html
new FilesystemAdapter('sf_cache', 24 * 60 * 60, PATH_CACHE);
/*
*
* @param void
*
* @return \Box_Authorization
*/
$di['auth'] = fn () => new Box_Authorization($di);
/*
* Creates a new Twig environment that's configured for FOSSBilling.
*
* @param void
*
* @return \Twig\Environment The new Twig environment that was just created.
*
* @throws \Twig\Error\LoaderError If the Twig environment could not be created.
* @throws \Twig\Error\RuntimeError If an error occurs while rendering a template.
* @throws \Twig\Error\SyntaxError If a template is malformed.
*/
$di['twig'] = $di->factory(function () use ($di) {
$options = Config::getProperty('twig');
// Get internationalisation settings from config, or use sensible defaults for
// missing required settings.
$locale = FOSSBilling\i18n::getActiveLocale();
$timezone = Config::getProperty('i18n.timezone', 'UTC');
$date_format = strtoupper(Config::getProperty('i18n.date_format', 'MEDIUM'));
$time_format = strtoupper(Config::getProperty('i18n.time_format', 'SHORT'));
$datetime_pattern = Config::getProperty('i18n.datetime_pattern');
$loader = new Twig\Loader\ArrayLoader();
$twig = new Twig\Environment($loader, $options);
$box_extensions = new Box_TwigExtensions();
$box_extensions->setDi($di);
if ($di['encore_info']['is_encore_theme']) {
$entryPoints = new EntrypointLookup($di['encore_info']['entrypoints']);
$tagRenderer = new TagRenderer($entryPoints);
$encoreExtensions = new EntrypointsTwigExtension($entryPoints, $tagRenderer);
$twig->addExtension($encoreExtensions);
$twig->addExtension(new VersionedAssetsTwigExtension(new JsonManifest($di['encore_info']['manifest'])));
}
// $twig->addExtension(new OptimizerExtension());
$twig->addExtension(new StringLoaderExtension());
$twig->addExtension(new DebugExtension());
$twig->addExtension($box_extensions);
$twig->getExtension(CoreExtension::class)->setTimezone($timezone);
try {
$dateFormatter = new IntlDateFormatter($locale, constant("\IntlDateFormatter::$date_format"), constant("\IntlDateFormatter::$time_format"), $timezone, null, $datetime_pattern);
} catch (Symfony\Polyfill\Intl\Icu\Exception\MethodArgumentValueNotImplementedException) {
if (Config::getProperty('i18n.locale', 'en_US') == 'en_US') {
$dateFormatter = new IntlDateFormatter('en', constant("\IntlDateFormatter::$date_format"), constant("\IntlDateFormatter::$time_format"), $timezone, null, $datetime_pattern);
} else {
throw new FOSSBilling\InformationException('It appears you are trying to use FOSSBilling without the PHP intl extension enabled. FOSSBilling includes a polyfill for the intl extension, however it does not support :locale. Please enable the intl extension.', [':locale' => Config::getProperty('i18n.locale')]);
}
}
$twig->addExtension(new IntlExtension($dateFormatter));
// add globals
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
$_GET['ajax'] = true;
}
// CSRF token
if (session_status() !== PHP_SESSION_ACTIVE) {
$token = hash('md5', $_COOKIE['PHPSESSID'] ?? '');
} else {
$token = hash('md5', session_id());
}
if (!empty($_SESSION['redirect_uri'])) {
$twig->addGlobal('redirect_uri', $_SESSION['redirect_uri']);
}
$twig->addGlobal('CSRFToken', $token);
$twig->addGlobal('request', $_GET);
$twig->addGlobal('guest', $di['api_guest']);
$twig->addGlobal('FOSSBillingVersion', FOSSBilling\Version::VERSION);
return $twig;
});
/*
* Checks whether a client is logged in and throws an exception or redirects to the login page if not.
*
* @param void
*
* @return bool True if a client is logged in.
*
* @throws \Exception If a client is not logged in and the request is an API request.
*
* @throws \HttpException If a client is not logged in and the request is a browser request.
*/
$di['is_client_logged'] = function () use ($di) {
if (!$di['auth']->isClientLoggedIn()) {
$api_str = '/api/';
$url = $_GET['_url'] ?? ($_SERVER['PATH_INFO'] ?? '');
if (strncasecmp($url, $api_str, strlen($api_str)) === 0) {
// Throw Exception if api request
throw new Exception('Client is not logged in');
} else {
// Redirect to login page if browser request
$di['set_return_uri'];
$login_url = $di['url']->link('login');
header("Location: $login_url");
}
}
return true;
};
/*
* @param mixed $model The client DB model to check
* @return bool Returns true if the client's email address is valid or if email confirmation is disabled.
*/
$di['is_client_email_validated'] = $di->protect(function ($model) use ($di) {
$config = $di['mod_config']('client');
if (isset($config['require_email_confirmation']) && (bool) $config['require_email_confirmation']) {
return (bool) $model->email_approved;
}
return true;
});
/*
* Checks whether an admin is logged in and throws an exception or redirects to the login page if not.
*
* @param void
*
* @return bool True if an admin is logged in.
*
* @throws \Exception If an admin is not logged in and the request is an API request.
*
*/
$di['is_admin_logged'] = function () use ($di) {
if (!$di['auth']->isAdminLoggedIn()) {
$url = $_GET['_url'] ?? $_SERVER['PATH_INFO'] ?? '';
if (str_starts_with($url, '/api/')) {
throw new Exception('Admin is not logged in');
}
$di['set_return_uri'];
header(sprintf('Location: %s', $di['url']->adminLink('staff/login')));
exit;
}
return true;
};
/*
* Returns an existing logged-in client model object.
*
* @param void
*
* @return \Model_Client The existing logged-in client model object.
*/
$di['loggedin_client'] = function () use ($di) {
$di['is_client_logged'];
$client_id = $di['session']->get('client_id');
try {
return $di['db']->getExistingModelById('Client', $client_id);
} catch (Exception) {
// Either the account was deleted or the session is invalid. Either way, remove the ID from the session so the system doesn't consider someone logged in
$di['session']->delete('client_id');
// Then either give an appropriate API response or redirect to the login page.
$api_str = '/api/';
$url = $_GET['_url'] ?? ($_SERVER['PATH_INFO'] ?? '');
if (strncasecmp($url, $api_str, strlen($api_str)) === 0) {
// Throw Exception if api request
throw new Exception('Client is not logged in');
} else {
// Redirect to login page if browser request
$login_url = $di['url']->link('login');
header("Location: $login_url");
exit;
}
}
};
/*
* Returns an existing logged-in admin model object.
*
* @param void
*
* @return \Model_Admin|null The existing logged-in admin model object, or null if no admin is logged in.
*
* @throws \FOSSBilling\Exception If the script is running in CLI or CGI mode and there is no cron admin available.
*/
$di['loggedin_admin'] = function () use ($di) {
if (Environment::isCLI()) {
return $di['mod_service']('staff')->getCronAdmin();
}
$di['is_admin_logged'];
$admin = $di['session']->get('admin');
try {
return $di['db']->getExistingModelById('Admin', $admin['id']);
} catch (Exception) {
// Either the account was deleted or the session is invalid. Either way, remove the ID from the session so the system doesn't consider someone logged in
$di['session']->delete('admin');
// Then either give an appropriate API response or redirect to the login page.
$api_str = '/api/';
$url = $_GET['_url'] ?? ($_SERVER['PATH_INFO'] ?? '');
if (strncasecmp($url, $api_str, strlen($api_str)) === 0) {
// Throw Exception if api request
throw new Exception('Admin is not logged in');
} else {
// Redirect to login page if browser request
$login_url = $di['url']->adminLink('staff/login');
header("Location: $login_url");
exit;
}
}
};
$di['set_return_uri'] = function () use ($di): void {
$url = $_GET['_url'] ?? $_SERVER['PATH_INFO'] ?? '';
unset($_GET['_url']);
if (str_starts_with($url, ADMIN_PREFIX)) {
$url = substr($url, strlen(ADMIN_PREFIX));
}
if ($_GET) {
$url .= '?' . http_build_query($_GET);
}
$di['session']->set('redirect_uri', $url);
};
/*
* Creates a new API object based on the specified role and returns it.
*
* @param string $role The role to create the API object for. Can be 'guest', 'client', 'admin', or 'system'.
*
* @return \Api_Handler The new API object that was just created.
*
* @throws \Exception If the specified role is not recognized or if a client is trying to use the API while their email is not valid.
*/
$di['api'] = $di->protect(function ($role) use ($di) {
$identity = match ($role) {
'guest' => new Model_Guest(),
'client' => $di['loggedin_client'],
'admin' => $di['loggedin_admin'],
'system' => $di['mod_service']('staff')->getCronAdmin(),
default => throw new Exception('Unrecognized Handler type: ' . $role),
};
// Checks to enforce email validation for clients
if ($role === 'client' && !$di['is_client_email_validated']($identity)) {
$url = $_GET['_url'] ?? ($_SERVER['PATH_INFO'] ?? '');
// If it's an API request, only allow requests to the "client" and "profile" modules so they can change their email address or resend the confirmation email.
if (strncasecmp($url, '/api/', strlen('/api/')) === 0) {
if (strncasecmp($url, '/api/client/client/', strlen('/api/client/client/')) !== 0 && strncasecmp($url, '/api/client/profile/', strlen('/api/client/profile/')) !== 0) {
throw new Exception('Please check your mailbox and confirm your email address.');
}
} elseif (strncasecmp($url, '/client', strlen('/client')) !== 0) {
// If they aren't attempting to access their profile, redirect them to it.
$login_url = $di['url']->link('client/profile');
header("Location: $login_url");
exit;
}
}
$api = new Api_Handler($identity);
$api->setDi($di);
return $api;
});
/*
*
* @param void
*
* @return \Api_Handler
*/
$di['api_guest'] = fn () => $di['api']('guest');
/*
*
* @param void
*
* @return \Api_Handler
*/
$di['api_client'] = fn () => $di['api']('client');
/*
*
* @param void
*
* @return \Api_Handler
*/
$di['api_admin'] = fn () => $di['api']('admin');
/*
*
* @param void
*
* @return \Api_Handler
*/
$di['api_system'] = fn () => $di['api']('system');
$di['tools'] = function () use ($di) {
$service = new FOSSBilling\Tools();
$service->setDi($di);
return $service;
};
/*
*
* @param void
*
* @return \FOSSBilling\Validate
*/
$di['validator'] = function () use ($di) {
$validator = new FOSSBilling\Validate();
$validator->setDi($di);
return $validator;
};
/*
*
* @param void
*
* @return \FOSSBilling\CentralAlerts
*/
$di['central_alerts'] = function () use ($di) {
$centralalerts = new FOSSBilling\CentralAlerts();
$centralalerts->setDi($di);
return $centralalerts;
};
/*
*
* @param void
*
* @return \FOSSBilling\CentralAlerts
*/
$di['central_alerts'] = function () use ($di) {
$centralalerts = new FOSSBilling\CentralAlerts();
$centralalerts->setDi($di);
return $centralalerts;
};
/*
*
* @param void
*
* @return \FOSSBilling\ExtensionManager
*/
$di['extension_manager'] = function () use ($di) {
$extension = new FOSSBilling\ExtensionManager();
$extension->setDi($di);
return $extension;
};
/*
*
* @param void
*
* @return \FOSSBilling\Update
*/
$di['updater'] = function () use ($di) {
$updater = new FOSSBilling\Update();
$updater->setDi($di);
return $updater;
};
/*
* @param void
*
* @return Server_Package
*/
$di['server_package'] = fn () => new Server_Package();
/*
* @param void
*
* @return Server_Client
*/
$di['server_client'] = fn () => new Server_Client();
/*
* @param void
*
* @return Server_Account
*/
$di['server_account'] = fn () => new Server_Account();
/*
* Creates a new server manager object and returns it.
*
* @param string $manager The name of the server manager to create.
* @param array $config The configuration options for the server manager.
*
* @return \Server_Manager The new server manager object that was just created.
*/
$di['server_manager'] = $di->protect(function ($manager, $config) use ($di) {
$class = sprintf('Server_Manager_%s', ucfirst($manager));
$s = new $class($config);
$s->setLog($di['logger']);
return $s;
});
/*
* @param void
*
* @return \FOSSBilling\Requirements
*/
$di['requirements'] = function () {
$r = new FOSSBilling\Requirements();
return $r;
};
/*
* Creates a new Box_Period object using the provided period code and returns it.
*
* @param string $code The two character period code to create the period object with.
*
* @return \Box_Period The new period object that was just created.
*/
$di['period'] = $di->protect(fn ($code) => new Box_Period($code));
/*
* Gets the current client area theme.
*
* @param void
*
* @return \Box_Theme The current client area theme.
*/
$di['theme'] = function () use ($di) {
$service = $di['mod_service']('theme');
return $service->getCurrentClientAreaTheme();
};
/*
* Gets the information of Webpack Encore for the current route theme.
* @return string
*/
$di['encore_info'] = function () use ($di) {
$service = $di['mod_service']('theme');
return $service->getEncoreInfo();
};
/*
* Loads an existing cart session or creates a new one if there is no session.
*
* @param void
*
* @return mixed The either existing or new cart.
*/
$di['cart'] = function () use ($di) {
$service = $di['mod_service']('cart');
return $service->getSessionCart();
};
/*
* Creates a new table object and returns it.
*
* @param string $name The name of the table to create.
*
* @return \Box_Table The new table object that was just created.
*/
$di['table'] = $di->protect(function ($name) use ($di) {
$tools = new FOSSBilling\Tools();
$tools->setDi($di);
$table = $tools->getTable($name);
$table->setDi($di);
return $table;
});
/*
* @param void
*
* @return \Box\Mod\Servicelicense\Server
*/
$di['license_server'] = function () use ($di) {
$server = new Box\Mod\Servicelicense\Server($di['logger']);
$server->setDi($di);
return $server;
};
/*
* @param void
*
* @return \GeoIp2\Database\Reader
*/
$di['geoip'] = fn () => new GeoIp2\Database\Reader(PATH_LIBRARY . '/GeoLite2-Country.mmdb');
/*
* @param void
*
* @return \Box_Password
*/
$di['password'] = fn () => new FOSSBilling\PasswordManager();
/*
* Creates a new Box_Translate object and sets the specified text domain, locale, and other options.
*
* @param string $textDomain The text domain to create the translation object with.
*
* @return \Box_Translate The new translation object that was just created.
*/
$di['translate'] = $di->protect(function ($textDomain = '') use ($di) {
$tr = new Box_Translate();
if (!empty($textDomain)) {
$tr->setDomain($textDomain);
}
$locale = FOSSBilling\i18n::getActiveLocale();
$tr->setDi($di);
$tr->setLocale($locale);
$tr->setup();
return $tr;
});
/*
* Creates a CSV export of data from a specified table and sends it to the browser.
*
* @param string $table Name of the table to export data from
* @param string $outputName Name of the exported CSV file
* @param array $headers Optional array of column headers for the CSV file
* @param int $limit Optional limit of the number of rows to export from the table
* @return void
*/
$di['table_export_csv'] = $di->protect(function (string $table, string $outputName = 'export.csv', array $headers = [], int $limit = 0) use ($di): void {
if ($limit > 0) {
$beans = $di['db']->findAll($table, 'LIMIT :limit', [':limit' => $limit]);
} else {
$beans = $di['db']->findAll($table);
}
$rows = array_map(fn ($bean) => $bean->export(), $beans);
// If we've been provided a list of headers, use that. Otherwise, pull the keys from the rows and use that for the CSV header
if ($headers) {
$rows = array_map(fn ($row) => array_intersect_key($row, array_flip($headers)), $rows);
} else {
$headers = array_keys(reset($rows));
}
$csv = League\Csv\Writer::createFromFileObject(new SplTempFileObject());
$csv->addFormatter(new League\Csv\EscapeFormula());
$csv->insertOne($headers);
$csv->insertAll($rows);
$csv->output($outputName);
// Prevent further output from being added to the end of the CSV
exit;
});
/*
* Converts markdown into HTML and returns the result.
*
* @param string|null $content The content to convert
*
* @return string
*/
$di['parse_markdown'] = $di->protect(function (?string $content, bool $addAttributes = true) use ($di) {
$content ??= '';
$defaultAttributes = [];
// If we are defining the default attributes, build the list and add them to the config
if ($addAttributes) {
$attributes = $di['mod_service']('theme')->getDefaultMarkdownAttributes();
foreach ($attributes as $class => $attributes) {
$reflectionClass = new ReflectionClass($class);
$fqcn = $reflectionClass->getName();
$defaultAttributes[$fqcn] = $attributes;
}
}
$parser = new League\CommonMark\GithubFlavoredMarkdownConverter([
'html_input' => 'escape',
'allow_unsafe_links' => false,
'max_nesting_level' => 50,
'default_attributes' => $defaultAttributes,
]);
if ($addAttributes) {
$parser->getEnvironment()->addExtension(new DefaultAttributesExtension());
}
return $parser->convert($content);
});
return $di;