-
Notifications
You must be signed in to change notification settings - Fork 642
/
Copy pathApplicationTrait.php
1698 lines (1541 loc) · 54.4 KB
/
ApplicationTrait.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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\base;
use Craft;
use craft\console\Application as ConsoleApplication;
use craft\console\Request as ConsoleRequest;
use craft\db\Connection;
use craft\db\MigrationManager;
use craft\db\mysql\Schema;
use craft\db\Query;
use craft\db\Table;
use craft\elements\Address;
use craft\elements\Asset;
use craft\elements\Category;
use craft\elements\Entry;
use craft\elements\Tag;
use craft\elements\User;
use craft\errors\DbConnectException;
use craft\errors\SiteNotFoundException;
use craft\errors\WrongEditionException;
use craft\events\DefineFieldLayoutFieldsEvent;
use craft\events\DeleteSiteEvent;
use craft\events\EditionChangeEvent;
use craft\fieldlayoutelements\addresses\AddressField;
use craft\fieldlayoutelements\addresses\CountryCodeField;
use craft\fieldlayoutelements\addresses\LabelField;
use craft\fieldlayoutelements\addresses\LatLongField;
use craft\fieldlayoutelements\addresses\OrganizationField;
use craft\fieldlayoutelements\addresses\OrganizationTaxIdField;
use craft\fieldlayoutelements\assets\AltField;
use craft\fieldlayoutelements\assets\AssetTitleField;
use craft\fieldlayoutelements\entries\EntryTitleField;
use craft\fieldlayoutelements\FullNameField;
use craft\fieldlayoutelements\TitleField;
use craft\fieldlayoutelements\users\AddressesField;
use craft\helpers\App;
use craft\helpers\Db;
use craft\helpers\Session;
use craft\i18n\Formatter;
use craft\i18n\I18N;
use craft\i18n\Locale;
use craft\mail\Mailer;
use craft\models\FieldLayout;
use craft\models\Info;
use craft\queue\QueueInterface;
use craft\services\Addresses;
use craft\services\Announcements;
use craft\services\Api;
use craft\services\AssetIndexer;
use craft\services\Assets;
use craft\services\Categories;
use craft\services\Composer;
use craft\services\Conditions;
use craft\services\Config;
use craft\services\Content;
use craft\services\Dashboard;
use craft\services\Deprecator;
use craft\services\Drafts;
use craft\services\Elements;
use craft\services\ElementSources;
use craft\services\Entries;
use craft\services\Fields;
use craft\services\Fs;
use craft\services\Gc;
use craft\services\Globals;
use craft\services\Gql;
use craft\services\Images;
use craft\services\ImageTransforms;
use craft\services\Matrix;
use craft\services\Path;
use craft\services\Plugins;
use craft\services\PluginStore;
use craft\services\ProjectConfig;
use craft\services\Relations;
use craft\services\Revisions;
use craft\services\Routes;
use craft\services\Search;
use craft\services\Sections;
use craft\services\Security;
use craft\services\Sites;
use craft\services\Structures;
use craft\services\SystemMessages;
use craft\services\Tags;
use craft\services\TemplateCaches;
use craft\services\Tokens;
use craft\services\Updates;
use craft\services\UserGroups;
use craft\services\UserPermissions;
use craft\services\Users;
use craft\services\Utilities;
use craft\services\Volumes;
use craft\services\Webpack;
use craft\web\Application as WebApplication;
use craft\web\AssetManager;
use craft\web\Request as WebRequest;
use craft\web\View;
use Illuminate\Support\Collection;
use Yii;
use yii\base\Application;
use yii\base\ErrorHandler;
use yii\base\Event;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\caching\Cache;
use yii\db\ColumnSchemaBuilder;
use yii\db\Exception as DbException;
use yii\db\Expression;
use yii\mutex\Mutex;
use yii\queue\Queue;
use yii\web\ServerErrorHttpException;
/**
* ApplicationTrait
*
* @property bool $isInstalled Whether Craft is installed
* @property int $edition The active Craft edition
* @property-read Addresses $addresses The addresses service
* @property-read Announcements $announcements The announcements service
* @property-read Api $api The API service
* @property-read AssetIndexer $assetIndexer The asset indexer service
* @property-read AssetManager $assetManager The asset manager component
* @property-read Assets $assets The assets service
* @property-read Categories $categories The categories service
* @property-read Composer $composer The Composer service
* @property-read Conditions $conditions The conditions service
* @property-read Config $config The config service
* @property-read Connection $db The database connection component
* @property-read Content $content The content service
* @property-read Dashboard $dashboard The dashboard service
* @property-read Deprecator $deprecator The deprecator service
* @property-read Drafts $drafts The drafts service
* @property-read ElementSources $elementSources The element sources service
* @property-read Elements $elements The elements service
* @property-read Entries $entries The entries service
* @property-read Fields $fields The fields service
* @property-read Formatter $formatter The formatter component
* @property-read Fs $fs The filesystems service
* @property-read Gc $gc The garbage collection service
* @property-read Globals $globals The globals service
* @property-read Gql $gql The GraphQl service
* @property-read I18N $i18n The internationalization (i18n) component
* @property-read Images $images The images service
* @property-read ImageTransforms $imageTransforms The image transforms service
* @property-read Locale $formattingLocale The Locale object that should be used to define the formatter
* @property-read Locale $locale The Locale object for the target language
* @property-read Mailer $mailer The mailer component
* @property-read Matrix $matrix The matrix service
* @property-read MigrationManager $contentMigrator The content migration manager
* @property-read MigrationManager $migrator The application’s migration manager
* @property-read Mutex $mutex The application’s mutex service
* @property-read Path $path The path service
* @property-read PluginStore $pluginStore The plugin store service
* @property-read Plugins $plugins The plugins service
* @property-read ProjectConfig $projectConfig The project config service
* @property-read Queue|QueueInterface $queue The job queue
* @property-read Relations $relations The relations service
* @property-read Revisions $revisions The revisions service
* @property-read Routes $routes The routes service
* @property-read Search $search The search service
* @property-read Sections $sections The sections service
* @property-read Security $security The security component
* @property-read Sites $sites The sites service
* @property-read Structures $structures The structures service
* @property-read SystemMessages $systemMessages The system email messages service
* @property-read Tags $tags The tags service
* @property-read TemplateCaches $templateCaches The template caches service
* @property-read Tokens $tokens The tokens service
* @property-read Updates $updates The updates service
* @property-read UserGroups $userGroups The user groups service
* @property-read UserPermissions $userPermissions The user permissions service
* @property-read Users $users The users service
* @property-read Utilities $utilities The utilities service
* @property-read View $view The view component
* @property-read Volumes $volumes The volumes service
* @property-read Webpack $webpack The webpack service
* @property-read bool $canTestEditions Whether Craft is running on a domain that is eligible to test out the editions
* @property-read bool $canUpgradeEdition Whether Craft is eligible to be upgraded to a different edition
* @property-read bool $hasWrongEdition Whether Craft is running with the wrong edition
* @property-read bool $isInMaintenanceMode Whether someone is currently performing a system update
* @property-read bool $isInitialized Whether Craft is fully initialized
* @property-read bool $isMultiSite Whether this site has multiple sites
* @property-read bool $isSystemLive Whether the system is live
* @property-read string $installedSchemaVersion The installed schema version
* @method AssetManager getAssetManager() Returns the asset manager component.
* @method Connection getDb() Returns the database connection component.
* @method Formatter getFormatter() Returns the formatter component.
* @method I18N getI18n() Returns the internationalization (i18n) component.
* @method Security getSecurity() Returns the security component.
* @method View getView() Returns the view component.
* @mixin WebApplication
* @mixin ConsoleApplication
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 3.0.0
*/
trait ApplicationTrait
{
/**
* @var string Craft’s schema version number.
*/
public string $schemaVersion;
/**
* @var string The minimum Craft build number required to update to this build.
*/
public string $minVersionRequired;
/**
* @var string|null The environment ID Craft is currently running in.
*/
public ?string $env = null;
/**
* @var string The base Craftnet API URL to use.
* @since 3.3.16
* @internal
*/
public string $baseApiUrl = 'https://api.craftcms.com/v1/';
/**
* @var string[]|null Query params that should be appended to Craftnet API requests.
* @since 3.3.16
* @internal
*/
public ?array $apiParams = null;
/**
* @var bool|null
*/
private ?bool $_isInstalled = null;
/**
* @var bool Whether the application is fully initialized yet
* @see getIsInitialized()
*/
private bool $_isInitialized = false;
/**
* @var bool
* @see getIsMultiSite()
*/
private bool $_isMultiSite;
/**
* @var bool
* @see getIsMultiSite()
*/
private bool $_isMultiSiteWithTrashed;
/**
* @var int The Craft edition
* @see getEdition()
*/
private int $_edition;
/**
* @var Info|null
*/
private ?Info $_info = null;
/**
* @var bool
*/
private bool $_gettingLanguage = false;
/**
* @var bool Whether we’re listening for the request end, to update the application info
* @see saveInfoAfterRequest()
*/
private bool $_waitingToSaveInfo = false;
/**
* Sets the target application language.
*
* @param bool|null $useUserLanguage Whether the user’s preferred language should be used.
* If null, the user’s preferred language will be used if this is a control panel request or a console request.
*/
public function updateTargetLanguage(?bool $useUserLanguage = null): void
{
// Defend against an infinite updateTargetLanguage() loop
if ($this->_gettingLanguage === true) {
// We tried to get the language, but something went wrong. Use fallback to prevent infinite loop.
$fallbackLanguage = $this->_getFallbackLanguage();
$this->_gettingLanguage = false;
$this->language = $fallbackLanguage;
return;
}
$this->_gettingLanguage = true;
if ($useUserLanguage === null) {
$useUserLanguage = $this->getRequest()->getIsCpRequest();
}
$this->language = $this->getTargetLanguage($useUserLanguage);
$this->_gettingLanguage = false;
}
/**
* Returns the target app language.
*
* @param bool $useUserLanguage Whether the user’s preferred language should be used.
* @return string
*/
public function getTargetLanguage(bool $useUserLanguage = true): string
{
// Use the fallback language for console requests, or if Craft isn't installed or is updating
if (
$this instanceof ConsoleApplication ||
!$this->getIsInstalled() ||
$this->getUpdates()->getIsCraftUpdatePending()
) {
return $this->_getFallbackLanguage();
}
if ($useUserLanguage) {
// If the user is logged in *and* has a primary language set, use that
// (don't actually try to fetch the user, as plugins haven't been loaded yet)
$id = Session::get($this->getUser()->idParam);
if (
$id &&
($language = $this->getUsers()->getUserPreference($id, 'language')) !== null &&
Craft::$app->getI18n()->validateAppLocaleId($language)
) {
return $language;
}
// Fall back on the default control panel language, if there is one, otherwise the browser language
return Craft::$app->getConfig()->getGeneral()->defaultCpLanguage ?? $this->_getFallbackLanguage();
}
/** @noinspection PhpUnhandledExceptionInspection */
return $this->getSites()->getCurrentSite()->language;
}
/**
* Returns whether Craft is installed.
*
* @param bool $strict Whether to ignore the cached value and explicitly check from the default schema.
* @return bool
*/
public function getIsInstalled(bool $strict = false): bool
{
if ($strict) {
$this->_isInstalled = null;
$this->_info = null;
} elseif (isset($this->_isInstalled)) {
return $this->_isInstalled;
}
if (!$this->getIsDbConnectionValid()) {
return $this->_isInstalled = false;
}
try {
if ($strict) {
$db = Craft::$app->getDb();
if ($db->getIsPgsql()) {
// Look for the `info` row, explicitly in the default schema.
return $this->_isInstalled = (new Query())
->from([sprintf('%s.%s', $db->getSchema()->defaultSchema, Table::INFO)])
->where(['id' => 1])
->exists();
}
}
$info = $this->getInfo(true);
return $this->_isInstalled = !empty($info->id);
} catch (DbException|ServerErrorHttpException $e) {
// yii2-redis awkwardly throws yii\db\Exception's rather than their own exception class.
if ($e instanceof DbException && str_contains($e->getMessage(), 'Redis')) {
throw $e;
}
// Allow console requests to bypass error
if ($this instanceof WebApplication) {
Craft::error('There was a problem fetching the info row: ' . $e->getMessage(), __METHOD__);
/** @var ErrorHandler $errorHandler */
$errorHandler = $this->getErrorHandler();
$errorHandler->logException($e);
}
return $this->_isInstalled = false;
}
}
/**
* Sets Craft's record of whether it's installed
*
* @param bool|null $value
*/
public function setIsInstalled(?bool $value = true): void
{
$this->_isInstalled = $value;
}
/**
* Returns the installed schema version.
*
* @return string
* @since 3.2.0
* @deprecated in 4.0.0
*/
public function getInstalledSchemaVersion(): string
{
return $this->getInfo()->schemaVersion ?: $this->schemaVersion;
}
/**
* Returns whether Craft has been fully initialized.
*
* @return bool
* @since 3.0.13
*/
public function getIsInitialized(): bool
{
return $this->_isInitialized;
}
/**
* Invokes a callback method when Craft is fully initialized.
*
* @param callable $callback
* @since 4.3.5
*/
public function onInit(callable $callback): void
{
if ($this->_isInitialized) {
$callback();
} else {
$this->on(WebApplication::EVENT_INIT, function() use ($callback) {
$callback();
});
}
}
/**
* Returns whether this Craft install has multiple sites.
*
* @param bool $refresh Whether to ignore the cached result and check again
* @param bool $withTrashed Whether to factor in soft-deleted sites
* @return bool
*/
public function getIsMultiSite(bool $refresh = false, bool $withTrashed = false): bool
{
if ($withTrashed) {
if (!$refresh && isset($this->_isMultiSiteWithTrashed)) {
return $this->_isMultiSiteWithTrashed;
}
// This is a ridiculous microoptimization for the `sites` table, but all we need to know is whether there is
// 1 or "more than 1" rows, and this is the fastest way to do it.
// (https://stackoverflow.com/a/14916838/1688568)
return $this->_isMultiSiteWithTrashed = (new Query())
->from([
'x' => (new Query())
->select([new Expression('1')])
->from([Table::SITES])
->limit(2),
])
->count() != 1;
}
if (!$refresh && isset($this->_isMultiSite)) {
return $this->_isMultiSite;
}
return $this->_isMultiSite = count($this->getSites()->getAllSites(true)) > 1;
}
/**
* Returns the Craft edition.
*
* @return int
*/
public function getEdition(): int
{
if (!isset($this->_edition)) {
$handle = $this->getProjectConfig()->get('system.edition') ?? 'solo';
$this->_edition = App::editionIdByHandle($handle);
}
return $this->_edition;
}
/**
* Returns the name of the Craft edition.
*
* @return string
*/
public function getEditionName(): string
{
return App::editionName($this->getEdition());
}
/**
* Returns the edition Craft is actually licensed to run in.
*
* @return int|null
*/
public function getLicensedEdition(): ?int
{
$licensedEdition = $this->getCache()->get('licensedEdition');
if ($licensedEdition !== false) {
return (int)$licensedEdition;
}
return null;
}
/**
* Returns the name of the edition Craft is actually licensed to run in.
*
* @return string|null
*/
public function getLicensedEditionName(): ?string
{
$licensedEdition = $this->getLicensedEdition();
if ($licensedEdition !== null) {
return App::editionName($licensedEdition);
}
return null;
}
/**
* Returns whether Craft is running with the wrong edition.
*
* @return bool
*/
public function getHasWrongEdition(): bool
{
$licensedEdition = $this->getLicensedEdition();
return ($licensedEdition !== null && $licensedEdition !== $this->getEdition() && !$this->getCanTestEditions());
}
/**
* Sets the Craft edition.
*
* @param int $edition The edition to set.
* @return bool
*/
public function setEdition(int $edition): bool
{
$oldEdition = $this->getEdition();
$this->getProjectConfig()->set('system.edition', App::editionHandle($edition), "Craft CMS edition change");
$this->_edition = $edition;
// Fire an 'afterEditionChange' event
/** @var WebRequest|ConsoleRequest $request */
$request = $this->getRequest();
if (!$request->getIsConsoleRequest() && $this->hasEventHandlers(WebApplication::EVENT_AFTER_EDITION_CHANGE)) {
$this->trigger(WebApplication::EVENT_AFTER_EDITION_CHANGE, new EditionChangeEvent([
'oldEdition' => $oldEdition,
'newEdition' => $edition,
]));
}
return true;
}
/**
* Requires that Craft is running an equal or better edition than what's passed in
*
* @param int $edition The Craft edition to require.
* @param bool $orBetter If true, makes $edition the minimum edition required.
* @throws WrongEditionException if attempting to do something not allowed by the current Craft edition
*/
public function requireEdition(int $edition, bool $orBetter = true): void
{
if ($this->getIsInstalled() && !$this->getProjectConfig()->getIsApplyingExternalChanges()) {
$installedEdition = $this->getEdition();
if (($orBetter && $installedEdition < $edition) || (!$orBetter && $installedEdition !== $edition)) {
$editionName = App::editionName($edition);
throw new WrongEditionException("Craft $editionName is required for this");
}
}
}
/**
* Returns whether Craft is eligible to be upgraded to a different edition.
*
* @return bool
*/
public function getCanUpgradeEdition(): bool
{
// Only admin accounts can upgrade Craft
if (
$this->getUser()->getIsAdmin() &&
Craft::$app->getConfig()->getGeneral()->allowAdminChanges
) {
// Are they either *using* or *licensed to use* something < Craft Pro?
$activeEdition = $this->getEdition();
$licensedEdition = $this->getLicensedEdition();
return (
($activeEdition < Craft::Pro) ||
($licensedEdition !== null && $licensedEdition < Craft::Pro)
);
}
return false;
}
/**
* Returns whether Craft is running on a domain that is eligible to test out the editions.
*
* @return bool
*/
public function getCanTestEditions(): bool
{
if (!$this instanceof WebApplication) {
return false;
}
/** @var Cache $cache */
$cache = $this->getCache();
return $cache->get(sprintf('editionTestableDomain@%s', $this->getRequest()->getHostName()));
}
/**
* Returns the system's UID.
*
* @return string|null
*/
public function getSystemUid(): ?string
{
return $this->getInfo()->uid;
}
/**
* Returns whether the system is currently live.
*
* @return bool
* @since 3.1.0
*/
public function getIsLive(): bool
{
if (is_bool($live = $this->getConfig()->getGeneral()->isSystemLive)) {
return $live;
}
return App::parseBooleanEnv($this->getProjectConfig()->get('system.live')) ?? false;
}
/**
* Returns whether someone is currently performing a system update.
*
* @return bool
* @see enableMaintenanceMode()
* @see disableMaintenanceMode()
*/
public function getIsInMaintenanceMode(): bool
{
return $this->getInfo()->maintenance;
}
/**
* Enables Maintenance Mode.
*
* @return bool
* @see getIsInMaintenanceMode()
* @see disableMaintenanceMode()
*/
public function enableMaintenanceMode(): bool
{
return $this->_setMaintenanceMode(true);
}
/**
* Disables Maintenance Mode.
*
* @return bool
* @see getIsInMaintenanceMode()
* @see disableMaintenanceMode()
*/
public function disableMaintenanceMode(): bool
{
return $this->_setMaintenanceMode(false);
}
/**
* Returns the info model, or just a particular attribute.
*
* @param bool $throwException Whether an exception should be thrown if the `info` table doesn't exist
* @return Info
* @throws DbException if the `info` table doesn’t exist yet and `$throwException` is `true`
* @throws ServerErrorHttpException if the info table is missing its row
*/
public function getInfo(bool $throwException = false): Info
{
if (isset($this->_info)) {
return $this->_info;
}
try {
$row = (new Query())
->from([Table::INFO])
->where(['id' => 1])
->one();
} catch (DbException|DbConnectException $e) {
if ($throwException) {
throw $e;
}
return $this->_info = new Info();
}
if (!$row) {
$tableName = $this->getDb()->getSchema()->getRawTableName(Table::INFO);
throw new ServerErrorHttpException("The $tableName table is missing its row");
}
return $this->_info = new Info($row);
}
/**
* Updates the info row at the end of the request.
*
* @since 3.1.33
*/
public function saveInfoAfterRequest(): void
{
if (!$this->_waitingToSaveInfo) {
$this->_waitingToSaveInfo = true;
// If the request is already over, trigger this immediately
if (in_array($this->state, [
Application::STATE_AFTER_REQUEST,
Application::STATE_SENDING_RESPONSE,
Application::STATE_END,
], true)) {
$this->saveInfoAfterRequestHandler();
} else {
Craft::$app->on(WebApplication::EVENT_AFTER_REQUEST, [$this, 'saveInfoAfterRequestHandler']);
}
}
}
/**
* @throws Exception
* @throws ServerErrorHttpException
* @since 3.1.33
* @internal
*/
public function saveInfoAfterRequestHandler(): void
{
$info = $this->getInfo();
if (!$this->saveInfo($info)) {
throw new Exception("Unable to save new application info: " . implode(', ', $info->getErrorSummary(true)));
}
$this->_waitingToSaveInfo = false;
}
/**
* Updates the info row.
*
* @param Info $info
* @param string[]|null $attributeNames The attributes to save
* @return bool
*/
public function saveInfo(Info $info, ?array $attributeNames = null): bool
{
if ($attributeNames === null) {
$attributeNames = ['version', 'schemaVersion', 'maintenance', 'configVersion', 'fieldVersion'];
}
if (!$info->validate($attributeNames)) {
return false;
}
$attributes = $info->getAttributes($attributeNames);
$infoRowExists = (new Query())
->from([Table::INFO])
->where(['id' => 1])
->exists();
if ($infoRowExists) {
Db::update(Table::INFO, $attributes, [
'id' => 1,
]);
} else {
Db::insert(Table::INFO, $attributes + [
'id' => 1,
]);
}
$this->setIsInstalled();
// Use this as the new cached Info
$this->_info = $info;
return true;
}
/**
* Returns the system name.
*
* @return string
* @since 3.1.4
*/
public function getSystemName(): string
{
if (($name = Craft::$app->getProjectConfig()->get('system.name')) !== null) {
return App::parseEnv($name);
}
try {
$name = $this->getSites()->getPrimarySite()->getName();
} catch (SiteNotFoundException) {
$name = null;
}
return $name ?: 'Craft';
}
/**
* Returns the Yii framework version.
*
* @return string
*/
public function getYiiVersion(): string
{
return Yii::getVersion();
}
/**
* Returns whether the DB connection settings are valid.
*
* @return bool
* @internal Don't even think of moving this check into Connection->init().
*/
public function getIsDbConnectionValid(): bool
{
try {
$this->getDb()->open();
} catch (DbConnectException|InvalidConfigException $e) {
Craft::error('There was a problem connecting to the database: ' . $e->getMessage(), __METHOD__);
/** @var ErrorHandler $errorHandler */
$errorHandler = $this->getErrorHandler();
$errorHandler->logException($e);
return false;
}
return true;
}
// Service Getters
// -------------------------------------------------------------------------
/**
* Returns the addresses service.
*
* @return Addresses The addresses service
* @since 4.0.0
*/
public function getAddresses(): Addresses
{
/** @noinspection PhpIncompatibleReturnTypeInspection */
return $this->get('addresses');
}
/**
* Returns the announcements service.
*
* @return Announcements The announcements service
* @since 3.7.0
*/
public function getAnnouncements(): Announcements
{
/** @noinspection PhpIncompatibleReturnTypeInspection */
return $this->get('announcements');
}
/**
* Returns the API service.
*
* @return Api The API service
*/
public function getApi(): Api
{
/** @noinspection PhpIncompatibleReturnTypeInspection */
return $this->get('api');
}
/**
* Returns the assets service.
*
* @return Assets The assets service
*/
public function getAssets(): Assets
{
/** @noinspection PhpIncompatibleReturnTypeInspection */
return $this->get('assets');
}
/**
* Returns the asset indexing service.
*
* @return AssetIndexer The asset indexing service
*/
public function getAssetIndexer(): AssetIndexer
{
/** @noinspection PhpIncompatibleReturnTypeInspection */
return $this->get('assetIndexer');
}
/**
* Returns the image transforms service.
*
* @return ImageTransforms The asset transforms service
*/
public function getImageTransforms(): ImageTransforms
{
/** @noinspection PhpIncompatibleReturnTypeInspection */
return $this->get('imageTransforms');
}
/**
* Returns the categories service.
*
* @return Categories The categories service
*/
public function getCategories(): Categories
{
/** @noinspection PhpIncompatibleReturnTypeInspection */
return $this->get('categories');
}
/**
* Returns the Composer service.
*
* @return Composer The Composer service
*/
public function getComposer(): Composer
{
/** @noinspection PhpIncompatibleReturnTypeInspection */
return $this->get('composer');
}
/**
* Returns the conditions service.
*
* @return Conditions The conditions service
* @since 4.0.0
*/
public function getConditions(): Conditions
{
/** @noinspection PhpIncompatibleReturnTypeInspection */
return $this->get('conditions');
}
/**
* Returns the config service.
*
* @return Config The config service
*/
public function getConfig(): Config
{
/** @noinspection PhpIncompatibleReturnTypeInspection */
return $this->get('config');
}
/**
* Returns the content service.
*
* @return Content The content service
*/
public function getContent(): Content
{
/** @noinspection PhpIncompatibleReturnTypeInspection */
return $this->get('content');
}
/**
* Returns the content migration manager.
*
* @return MigrationManager The content migration manager
*/
public function getContentMigrator(): MigrationManager
{
/** @noinspection PhpIncompatibleReturnTypeInspection */
return $this->get('contentMigrator');
}
/**
* Returns the dashboard service.
*
* @return Dashboard The dashboard service
*/
public function getDashboard(): Dashboard
{
/** @noinspection PhpIncompatibleReturnTypeInspection */
return $this->get('dashboard');
}