composer.lock - Require firebase/php-jwt
[civicrm-core.git] / Civi / Core / Container.php
CommitLineData
fa184193
TO
1<?php
2namespace Civi\Core;
46bcf597 3
10760fa1 4use Civi\Core\Lock\LockManager;
40787e18 5use Symfony\Component\Config\ConfigCache;
fa184193
TO
6use Symfony\Component\DependencyInjection\ContainerBuilder;
7use Symfony\Component\DependencyInjection\Definition;
40787e18 8use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
fa184193 9use Symfony\Component\DependencyInjection\Reference;
40787e18 10use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass;
fa184193
TO
11
12// TODO use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
13
6550386a
EM
14/**
15 * Class Container
16 * @package Civi\Core
17 */
fa184193
TO
18class Container {
19
20 const SELF = 'civi_container_factory';
21
fa184193 22 /**
04855556
TO
23 * @param bool $reset
24 * Whether to forcibly rebuild the entire container.
fa184193
TO
25 * @return \Symfony\Component\DependencyInjection\TaggedContainerInterface
26 */
378e2654 27 public static function singleton($reset = FALSE) {
7f835399
TO
28 if ($reset || !isset(\Civi::$statics[__CLASS__]['container'])) {
29 self::boot(TRUE);
fa184193 30 }
7f835399 31 return \Civi::$statics[__CLASS__]['container'];
fa184193
TO
32 }
33
34 /**
40787e18
TO
35 * Find a cached container definition or construct a new one.
36 *
37 * There are many weird contexts in which Civi initializes (eg different
38 * variations of multitenancy and different permutations of CMS/CRM bootstrap),
39 * and hook_container may fire a bit differently in each context. To mitigate
40 * risk of leaks between environments, we compute a unique envID
41 * (md5(DB_NAME, HTTP_HOST, SCRIPT_FILENAME, etc)) and use separate caches for
42 * each (eg "templates_c/CachedCiviContainer.$ENVID.php").
43 *
44 * Constants:
45 * - CIVICRM_CONTAINER_CACHE -- 'always' [default], 'never', 'auto'
46 * - CIVICRM_DSN
47 * - CIVICRM_DOMAIN_ID
40787e18 48 *
34f3bbd9 49 * @return \Symfony\Component\DependencyInjection\ContainerInterface
40787e18
TO
50 */
51 public function loadContainer() {
52 // Note: The container's raison d'etre is to manage construction of other
53 // services. Consequently, we assume a minimal service available -- the classloader
54 // has been setup, and civicrm.settings.php is loaded, but nothing else works.
55
5497e016 56 $cacheMode = defined('CIVICRM_CONTAINER_CACHE') ? CIVICRM_CONTAINER_CACHE : 'auto';
40787e18
TO
57
58 // In pre-installation environments, don't bother with caching.
43a2114e 59 if (!defined('CIVICRM_DSN') || defined('CIVICRM_TEST') || CIVICRM_UF === 'UnitTests' || $cacheMode === 'never' || \CRM_Utils_System::isInUpgradeMode()) {
12e01332
TO
60 $containerBuilder = $this->createContainer();
61 $containerBuilder->compile();
62 return $containerBuilder;
40787e18
TO
63 }
64
83617886 65 $envId = \CRM_Core_Config_Runtime::getId();
6f50d29c 66 $file = \Civi::paths()->getPath("[civicrm.compile]/CachedCiviContainer.{$envId}.php");
40787e18 67 $containerConfigCache = new ConfigCache($file, $cacheMode === 'auto');
40787e18
TO
68 if (!$containerConfigCache->isFresh()) {
69 $containerBuilder = $this->createContainer();
70 $containerBuilder->compile();
71 $dumper = new PhpDumper($containerBuilder);
72 $containerConfigCache->write(
c64f69d9 73 $dumper->dump(['class' => 'CachedCiviContainer']),
40787e18
TO
74 $containerBuilder->getResources()
75 );
76 }
77
78 require_once $file;
79 $c = new \CachedCiviContainer();
40787e18
TO
80 return $c;
81 }
82
83 /**
84 * Construct a new container.
85 *
34f3bbd9 86 * @var \Symfony\Component\DependencyInjection\ContainerBuilder
77b97be7 87 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
fa184193
TO
88 */
89 public function createContainer() {
90 $civicrm_base_path = dirname(dirname(__DIR__));
91 $container = new ContainerBuilder();
40787e18
TO
92 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
93 $container->addObjectResource($this);
fa184193 94 $container->setParameter('civicrm_base_path', $civicrm_base_path);
40787e18 95 //$container->set(self::SELF, $this);
762dc04d
TO
96
97 $container->addResource(new \Symfony\Component\Config\Resource\FileResource(__FILE__));
98
40787e18
TO
99 $container->setDefinition(self::SELF, new Definition(
100 'Civi\Core\Container',
c64f69d9 101 []
40787e18 102 ));
fa184193 103
505d8b83
TO
104 // TODO Move configuration to an external file; define caching structure
105 // if (empty($configDirectories)) {
106 // throw new \Exception(__CLASS__ . ': Missing required properties (civicrmRoot, configDirectories)');
107 // }
108 // $locator = new FileLocator($configDirectories);
109 // $loaderResolver = new LoaderResolver(array(
110 // new YamlFileLoader($container, $locator)
111 // ));
112 // $delegatingLoader = new DelegatingLoader($loaderResolver);
113 // foreach (array('services.yml') as $file) {
114 // $yamlUserFiles = $locator->locate($file, NULL, FALSE);
115 // foreach ($yamlUserFiles as $file) {
116 // $delegatingLoader->load($file);
117 // }
118 // }
fa184193 119
16072ce1 120 $container->setDefinition('angular', new Definition(
40787e18 121 'Civi\Angular\Manager',
c64f69d9 122 []
16072ce1 123 ))
3c006cb8 124 ->setFactory([new Reference(self::SELF), 'createAngularManager'])->setPublic(TRUE);
16072ce1 125
fa184193 126 $container->setDefinition('dispatcher', new Definition(
762dc04d 127 'Civi\Core\CiviEventDispatcher',
42ccedc7 128 []
fa184193 129 ))
3c006cb8 130 ->setFactory([new Reference(self::SELF), 'createEventDispatcher'])->setPublic(TRUE);
fa184193 131
c65db512 132 $container->setDefinition('magic_function_provider', new Definition(
40787e18 133 'Civi\API\Provider\MagicFunctionProvider',
c64f69d9 134 []
3c006cb8 135 ))->setPublic(TRUE);
c65db512 136
0f643fb2 137 $container->setDefinition('civi_api_kernel', new Definition(
40787e18 138 'Civi\API\Kernel',
c64f69d9 139 [new Reference('dispatcher'), new Reference('magic_function_provider')]
0f643fb2 140 ))
3c006cb8 141 ->setFactory([new Reference(self::SELF), 'createApiKernel'])->setPublic(TRUE);
0f643fb2 142
7b4bbb34 143 $container->setDefinition('cxn_reg_client', new Definition(
40787e18 144 'Civi\Cxn\Rpc\RegistrationClient',
c64f69d9 145 []
7b4bbb34 146 ))
3c006cb8 147 ->setFactory('CRM_Cxn_BAO_Cxn::createRegistrationClient')->setPublic(TRUE);
7b4bbb34 148
3c006cb8 149 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', []))->setPublic(TRUE);
6e5ad5ee 150
c64f69d9 151 $basicCaches = [
7a19d718
TO
152 'js_strings' => 'js_strings',
153 'community_messages' => 'community_messages',
b1fc1ab0 154 'checks' => 'checks',
19707a63 155 'session' => 'CiviCRM Session',
90cdaa0e 156 'long' => 'long',
0136044e 157 'groups' => 'contact groups',
96689db3 158 'navigation' => 'navigation',
792fce0b 159 'customData' => 'custom data',
9cdf85c1 160 'fields' => 'contact fields',
81c4c148 161 'contactTypes' => 'contactTypes',
eb151aab 162 'metadata' => 'metadata',
c64f69d9 163 ];
7a19d718 164 foreach ($basicCaches as $cacheSvc => $cacheGrp) {
023bcf83
SL
165 $definitionParams = [
166 'name' => $cacheGrp,
167 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
168 ];
169 // For Caches that we don't really care about the ttl for and/or maybe accessed
170 // fairly often we use the fastArrayDecorator which improves reads and writes, these
171 // caches should also not have concurrency risk.
eb151aab 172 $fastArrayCaches = ['groups', 'navigation', 'customData', 'fields', 'contactTypes', 'metadata'];
023bcf83
SL
173 if (in_array($cacheSvc, $fastArrayCaches)) {
174 $definitionParams['withArray'] = 'fast';
175 }
7a19d718 176 $container->setDefinition("cache.{$cacheSvc}", new Definition(
a4704404 177 'CRM_Utils_Cache_Interface',
023bcf83 178 [$definitionParams]
3c006cb8 179 ))->setFactory('CRM_Utils_Cache::create')->setPublic(TRUE);
a4704404 180 }
3a84c0ab 181
da4effce
SL
182 // PrevNextCache cannot use memory or array cache at the moment because the
183 // Code in CRM_Core_BAO_PrevNextCache assumes that this cache is sql backed.
184 $container->setDefinition("cache.prevNextCache", new Definition(
185 'CRM_Utils_Cache_Interface',
186 [
187 [
188 'name' => 'CiviCRM Search PrevNextCache',
189 'type' => ['SqlGroup'],
190 ],
191 ]
3c006cb8 192 ))->setFactory('CRM_Utils_Cache::create')->setPublic(TRUE);
da4effce 193
4ed867e0
TO
194 $container->setDefinition('sql_triggers', new Definition(
195 'Civi\Core\SqlTriggers',
c64f69d9 196 []
3c006cb8 197 ))->setPublic(TRUE);
4ed867e0 198
87e3fe24
TO
199 $container->setDefinition('asset_builder', new Definition(
200 'Civi\Core\AssetBuilder',
c64f69d9 201 []
3c006cb8 202 ))->setPublic(TRUE);
87e3fe24 203
d89d2545
TO
204 $container->setDefinition('themes', new Definition(
205 'Civi\Core\Themes',
206 []
3c006cb8 207 ))->setPublic(TRUE);
d89d2545 208
6e7adedc 209 $container->setDefinition('bundle.bootstrap3', new Definition('CRM_Core_Resources_Bundle', ['bootstrap3']))
3c86501c 210 ->setFactory('CRM_Core_Resources_Common::createBootstrap3Bundle')->setPublic(TRUE);
6e7adedc 211
b2d8361e 212 $container->setDefinition('bundle.coreStyles', new Definition('CRM_Core_Resources_Bundle', ['coreStyles']))
3c86501c 213 ->setFactory('CRM_Core_Resources_Common::createStyleBundle')->setPublic(TRUE);
b2d8361e
TO
214
215 $container->setDefinition('bundle.coreResources', new Definition('CRM_Core_Resources_Bundle', ['coreResources']))
3c86501c 216 ->setFactory('CRM_Core_Resources_Common::createFullBundle')->setPublic(TRUE);
b2d8361e 217
247eb841 218 $container->setDefinition('pear_mail', new Definition('Mail'))
3c86501c 219 ->setFactory('CRM_Utils_Mail::createMailer')->setPublic(TRUE);
247eb841 220
281eacd8 221 $container->setDefinition('crypto.registry', new Definition('Civi\Crypto\CryptoService'))
23fa0118 222 ->setFactory('Civi\Crypto\CryptoRegistry::createDefaultRegistry')->setPublic(TRUE);
281eacd8 223
7c5110c3
TO
224 $container->setDefinition('crypto.token', new Definition('Civi\Crypto\CryptoToken', []))
225 ->setPublic(TRUE);
8d3452c4 226
7f835399 227 if (empty(\Civi::$statics[__CLASS__]['boot'])) {
272dfdc3 228 throw new \RuntimeException('Cannot initialize container. Boot services are undefined.');
7f835399
TO
229 }
230 foreach (\Civi::$statics[__CLASS__]['boot'] as $bootService => $def) {
765daeac 231 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE)->setPublic(TRUE);
83617886
TO
232 }
233
c8074a93 234 // Expose legacy singletons as services in the container.
c64f69d9 235 $singletons = [
c8074a93 236 'httpClient' => 'CRM_Utils_HttpClient',
7b5937fe 237 'cache.default' => 'CRM_Utils_Cache',
a7c57397 238 'i18n' => 'CRM_Core_I18n',
c8074a93
TO
239 // Maybe? 'config' => 'CRM_Core_Config',
240 // Maybe? 'smarty' => 'CRM_Core_Smarty',
c64f69d9 241 ];
c8074a93
TO
242 foreach ($singletons as $name => $class) {
243 $container->setDefinition($name, new Definition(
244 $class
245 ))
3c006cb8 246 ->setFactory([$class, 'singleton'])->setPublic(TRUE);
c8074a93 247 }
e5c6b3cd 248 $container->setAlias('cache.short', 'cache.default')->setPublic(TRUE);
c8074a93 249
223ba025
TO
250 $container->setDefinition('resources', new Definition(
251 'CRM_Core_Resources',
252 [new Reference('service_container')]
3c006cb8 253 ))->setFactory([new Reference(self::SELF), 'createResources'])->setPublic(TRUE);
223ba025 254
bbcf0f46
TO
255 $container->setDefinition('resources.js_strings', new Definition(
256 'CRM_Core_Resources_Strings',
257 [new Reference('cache.js_strings')]
258 ))->setPublic(TRUE);
259
780fd0e3 260 $container->setDefinition('prevnext', new Definition(
99098349
TO
261 'CRM_Core_PrevNextCache_Interface',
262 [new Reference('service_container')]
3c006cb8 263 ))->setFactory([new Reference(self::SELF), 'createPrevNextCache'])->setPublic(TRUE);
99098349
TO
264
265 $container->setDefinition('prevnext.driver.sql', new Definition(
780fd0e3
TO
266 'CRM_Core_PrevNextCache_Sql',
267 []
3c006cb8 268 ))->setPublic(TRUE);
780fd0e3 269
751f3d98
TO
270 $container->setDefinition('prevnext.driver.redis', new Definition(
271 'CRM_Core_PrevNextCache_Redis',
272 [new Reference('cache_config')]
3c006cb8 273 ))->setPublic(TRUE);
751f3d98
TO
274
275 $container->setDefinition('cache_config', new Definition('ArrayObject'))
3c006cb8 276 ->setFactory([new Reference(self::SELF), 'createCacheConfig'])->setPublic(TRUE);
751f3d98 277
e7a6eae8
SL
278 $container->setDefinition('civi.mailing.triggers', new Definition(
279 'Civi\Core\SqlTrigger\TimestampTriggers',
c64f69d9 280 ['civicrm_mailing', 'Mailing']
3c006cb8 281 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'])->setPublic(TRUE);
e7a6eae8 282
e0a667ad
TO
283 $container->setDefinition('civi.activity.triggers', new Definition(
284 'Civi\Core\SqlTrigger\TimestampTriggers',
c64f69d9 285 ['civicrm_activity', 'Activity']
3c006cb8 286 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'])->setPublic(TRUE);
e0a667ad
TO
287
288 $container->setDefinition('civi.case.triggers', new Definition(
289 'Civi\Core\SqlTrigger\TimestampTriggers',
c64f69d9 290 ['civicrm_case', 'Case']
3c006cb8 291 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'])->setPublic(TRUE);
e0a667ad 292
b21ffed7
TO
293 $container->setDefinition('civi.case.staticTriggers', new Definition(
294 'Civi\Core\SqlTrigger\StaticTriggers',
c64f69d9
CW
295 [
296 [
297 [
298 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
b21ffed7
TO
299 'table' => 'civicrm_case_activity',
300 'when' => 'AFTER',
c64f69d9 301 'event' => ['INSERT'],
b21ffed7 302 'sql' => "\nUPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.case_id;\n",
c64f69d9
CW
303 ],
304 [
305 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
b21ffed7
TO
306 'table' => 'civicrm_activity',
307 'when' => 'BEFORE',
c64f69d9 308 'event' => ['UPDATE', 'DELETE'],
b21ffed7 309 'sql' => "\nUPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id IN (SELECT ca.case_id FROM civicrm_case_activity ca WHERE ca.activity_id = OLD.id);\n",
c64f69d9
CW
310 ],
311 ],
312 ]
b21ffed7 313 ))
3c006cb8 314 ->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'])->setPublic(TRUE);
b21ffed7 315
43ceab3f
TO
316 $container->setDefinition('civi_token_compat', new Definition(
317 'Civi\Token\TokenCompatSubscriber',
c64f69d9 318 []
3c006cb8 319 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
56df2d06
TO
320 $container->setDefinition("crm_mailing_action_tokens", new Definition(
321 "CRM_Mailing_ActionTokens",
c64f69d9 322 []
3c006cb8 323 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
43ceab3f 324
c64f69d9 325 foreach (['Activity', 'Contribute', 'Event', 'Mailing', 'Member'] as $comp) {
46f5566c
TO
326 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
327 "CRM_{$comp}_Tokens",
c64f69d9 328 []
3c006cb8 329 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
46f5566c 330 }
50a23755 331
caaeea39 332 \CRM_Api4_Services::hook_container($container);
aa4343bc 333
40787e18
TO
334 \CRM_Utils_Hook::container($container);
335
fa184193
TO
336 return $container;
337 }
338
16072ce1
TO
339 /**
340 * @return \Civi\Angular\Manager
341 */
342 public function createAngularManager() {
343 return new \Civi\Angular\Manager(\CRM_Core_Resources::singleton());
344 }
345
fa184193 346 /**
3c006cb8 347 * @return \Symfony\Component\EventDispatcher\EventDispatcher
fa184193 348 */
42ccedc7
TO
349 public function createEventDispatcher() {
350 // Continue building on the original dispatcher created during bootstrap.
351 $dispatcher = static::getBootService('dispatcher.boot');
ecb0ae5d 352
1d440215
TO
353 $dispatcher->addListener('civi.core.install', ['\Civi\Core\InstallationCanary', 'check']);
354 $dispatcher->addListener('civi.core.install', ['\Civi\Core\DatabaseInitializer', 'initialize']);
355 $dispatcher->addListener('civi.core.install', ['\Civi\Core\LocalizationInitializer', 'initialize']);
74effac4 356 $dispatcher->addListener('hook_civicrm_post', ['\CRM_Core_Transaction', 'addPostCommit'], -1000);
c64f69d9 357 $dispatcher->addListener('hook_civicrm_pre', ['\Civi\Core\Event\PreEvent', 'dispatchSubevent'], 100);
9d4c4ffd 358 $dispatcher->addListener('civi.dao.preDelete', ['\CRM_Core_BAO_EntityTag', 'preDeleteOtherEntity']);
c64f69d9
CW
359 $dispatcher->addListener('hook_civicrm_post', ['\Civi\Core\Event\PostEvent', 'dispatchSubevent'], 100);
360 $dispatcher->addListener('hook_civicrm_post::Activity', ['\Civi\CCase\Events', 'fireCaseChange']);
361 $dispatcher->addListener('hook_civicrm_post::Case', ['\Civi\CCase\Events', 'fireCaseChange']);
362 $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\Events', 'delegateToXmlListeners']);
363 $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\SequenceListener', 'onCaseChange_static']);
f1aeb0ba 364 $dispatcher->addListener('hook_civicrm_cryptoRotateKey', ['\Civi\Crypto\RotateKeys', 'rotateSmtp']);
c64f69d9 365 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\CiviEventInspector', 'findBuiltInEvents']);
0d0031a0 366 // TODO We need a better code-convention for metadata about non-hook events.
c64f69d9
CW
367 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\API\Events', 'hookEventDefs']);
368 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs']);
369 $dispatcher->addListener('hook_civicrm_buildAsset', ['\Civi\Angular\Page\Modules', 'buildAngularModules']);
370 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetJs']);
371 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetCss']);
f22fb451 372 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Core_Resources', 'renderMenubarStylesheet']);
303017a1 373 $dispatcher->addListener('hook_civicrm_coreResourceList', ['\CRM_Utils_System', 'appendCoreResources']);
62c20d1e 374 $dispatcher->addListener('hook_civicrm_getAssetUrl', ['\CRM_Utils_System', 'alterAssetUrl']);
28e28c36 375 $dispatcher->addListener('hook_civicrm_alterExternUrl', ['\CRM_Utils_System', 'migrateExternUrl'], 1000);
29541977
TO
376 $dispatcher->addListener('hook_civicrm_permissionList', ['CRM_Core_Permission_List', 'findConstPermissions'], 975);
377 $dispatcher->addListener('hook_civicrm_permissionList', ['CRM_Core_Permission_List', 'findCiviPermissions'], 950);
378 $dispatcher->addListener('hook_civicrm_permissionList', ['CRM_Core_Permission_List', 'findCmsPermissions'], 925);
379
bcf70e08 380 $dispatcher->addListener('hook_civicrm_triggerInfo', ['\CRM_Contact_BAO_RelationshipCache', 'onHookTriggerInfo']);
c64f69d9
CW
381 $dispatcher->addListener('civi.dao.postInsert', ['\CRM_Core_BAO_RecurringEntity', 'triggerInsert']);
382 $dispatcher->addListener('civi.dao.postUpdate', ['\CRM_Core_BAO_RecurringEntity', 'triggerUpdate']);
383 $dispatcher->addListener('civi.dao.postDelete', ['\CRM_Core_BAO_RecurringEntity', 'triggerDelete']);
d357f225 384 $dispatcher->addListener('hook_civicrm_postSave_civicrm_domain', ['\CRM_Core_BAO_Domain', 'onPostSave']);
c64f69d9 385 $dispatcher->addListener('hook_civicrm_unhandled_exception', [
9ae2d27b
TO
386 'CRM_Core_LegacyErrorHandler',
387 'handleException',
c64f69d9 388 ], -200);
bc2feeb1
TO
389 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Activity_ActionMapping', 'onRegisterActionMappings']);
390 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Contact_ActionMapping', 'onRegisterActionMappings']);
391 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings']);
392 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings']);
393 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Event_ActionMapping', 'onRegisterActionMappings']);
394 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Member_ActionMapping', 'onRegisterActionMappings']);
46f5566c 395
fa184193
TO
396 return $dispatcher;
397 }
0f643fb2 398
10760fa1 399 /**
34f3bbd9 400 * @return \Civi\Core\Lock\LockManager
10760fa1 401 */
83617886 402 public static function createLockManager() {
10760fa1
TO
403 // Ideally, downstream implementers could override any definitions in
404 // the container. For now, we'll make-do with some define()s.
405 $lm = new LockManager();
406 $lm
c64f69d9
CW
407 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : ['CRM_Core_Lock', 'createScopedLock'])
408 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : ['CRM_Core_Lock', 'createScopedLock'])
409 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : ['CRM_Core_Lock', 'createCivimailLock'])
410 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : ['CRM_Core_Lock', 'createScopedLock']);
10760fa1
TO
411
412 // Registrations may use complex resolver expressions, but (as a micro-optimization)
413 // the default factory is specified as an array.
414
415 return $lm;
416 }
417
0f643fb2
TO
418 /**
419 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
2a6da8d7
EM
420 * @param $magicFunctionProvider
421 *
0f643fb2
TO
422 * @return \Civi\API\Kernel
423 */
c65db512 424 public function createApiKernel($dispatcher, $magicFunctionProvider) {
0a946de2 425 $dispatcher->addSubscriber(new \Civi\API\Subscriber\ChainSubscriber());
b55bc593 426 $dispatcher->addSubscriber(new \Civi\API\Subscriber\TransactionSubscriber());
bace5cd9 427 $dispatcher->addSubscriber(new \Civi\API\Subscriber\I18nSubscriber());
c65db512 428 $dispatcher->addSubscriber($magicFunctionProvider);
d0c9daa4 429 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
dcef11bd 430 $dispatcher->addSubscriber(new \Civi\API\Subscriber\APIv3SchemaAdapter());
c64f69d9 431 $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter([
6d3bdc98
TO
432 \CRM_Utils_API_HTMLInputCoder::singleton(),
433 \CRM_Utils_API_NullOutputCoder::singleton(),
434 \CRM_Utils_API_ReloadOption::singleton(),
435 \CRM_Utils_API_MatchOption::singleton(),
c64f69d9 436 ]));
2aafb0fc 437 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DebugSubscriber());
82376c19
TO
438 $kernel = new \Civi\API\Kernel($dispatcher);
439
440 $reflectionProvider = new \Civi\API\Provider\ReflectionProvider($kernel);
441 $dispatcher->addSubscriber($reflectionProvider);
442
56154d36
TO
443 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DynamicFKAuthorization(
444 $kernel,
445 'Attachment',
c64f69d9 446 ['create', 'get', 'delete'],
2e37a19f 447 // Given a file ID, determine the entity+table it's attached to.
56154d36
TO
448 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
449 FROM civicrm_file cf
450 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
451 WHERE cf.id = %1',
29468114
TO
452 // Get a list of custom fields (field_name,table_name,extends)
453 'SELECT concat("custom_",fld.id) as field_name,
454 grp.table_name as table_name,
455 grp.extends as extends
456 FROM civicrm_custom_field fld
457 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
458 WHERE fld.data_type = "File"
09871447 459 '
56154d36
TO
460 ));
461
c64f69d9 462 $kernel->setApiProviders([
82376c19
TO
463 $reflectionProvider,
464 $magicFunctionProvider,
c64f69d9 465 ]);
82376c19 466
0f643fb2
TO
467 return $kernel;
468 }
96025800 469
223ba025 470 /**
34f3bbd9 471 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
223ba025
TO
472 * @return \CRM_Core_Resources
473 */
474 public static function createResources($container) {
475 $sys = \CRM_Extension_System::singleton();
476 return new \CRM_Core_Resources(
477 $sys->getMapper(),
bbcf0f46 478 new \CRM_Core_Resources_Strings($container->get('cache.js_strings')),
223ba025
TO
479 \CRM_Core_Config::isUpgradeMode() ? NULL : 'resCacheCode'
480 );
481 }
482
99098349 483 /**
34f3bbd9 484 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
99098349
TO
485 * @return \CRM_Core_PrevNextCache_Interface
486 */
487 public static function createPrevNextCache($container) {
e28bf654 488 $setting = \Civi::settings()->get('prevNextBackend');
272dfdc3 489 if (!$setting || $setting === 'default') {
e28bf654
TO
490 $cacheDriver = \CRM_Utils_Cache::getCacheDriver();
491 $service = 'prevnext.driver.' . strtolower($cacheDriver);
272dfdc3 492 return $container->has($service)
e28bf654
TO
493 ? $container->get($service)
494 : $container->get('prevnext.driver.sql');
495 }
272dfdc3 496 return $container->get('prevnext.driver.' . $setting);
99098349
TO
497 }
498
272dfdc3 499 /**
500 * @return \ArrayObject
501 */
751f3d98
TO
502 public static function createCacheConfig() {
503 $driver = \CRM_Utils_Cache::getCacheDriver();
504 $settings = \CRM_Utils_Cache::getCacheSettings($driver);
505 $settings['driver'] = $driver;
506 return new \ArrayObject($settings);
507 }
508
83617886
TO
509 /**
510 * Get a list of boot services.
511 *
512 * These are services which must be setup *before* the container can operate.
513 *
7f835399 514 * @param bool $loadFromDB
83617886
TO
515 * @throws \CRM_Core_Exception
516 */
7f835399 517 public static function boot($loadFromDB) {
56eafc21 518 // Array(string $serviceId => object $serviceInstance).
c64f69d9 519 $bootServices = [];
7f835399 520 \Civi::$statics[__CLASS__]['boot'] = &$bootServices;
d4330c62 521
56eafc21 522 $bootServices['runtime'] = $runtime = new \CRM_Core_Config_Runtime();
7f835399 523 $runtime->initialize($loadFromDB);
d4330c62 524
b1db062e
H
525 $bootServices['paths'] = new \Civi\Core\Paths();
526
42ccedc7 527 $bootServices['dispatcher.boot'] = new CiviEventDispatcher();
27e05c5c
TO
528
529 // Quality control: There should be no pre-boot hooks because they make it harder to understand/support/refactor.
530 // If a pre-boot hook sneaks in, we'll raise an error.
531 $bootDispatchPolicy = [
532 '/^hook_/' => 'not-ready',
533 '/^civi\./' => 'run',
534 ];
535 $mainDispatchPolicy = \CRM_Core_Config::isUpgradeMode() ? \CRM_Upgrade_DispatchPolicy::get('upgrade.main') : NULL;
536 $bootServices['dispatcher.boot']->setDispatchPolicy($bootDispatchPolicy);
42ccedc7 537
7f835399 538 $class = $runtime->userFrameworkClass;
56eafc21 539 $bootServices['userSystem'] = $userSystem = new $class();
7f835399
TO
540 $userSystem->initialize();
541
542 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework;
56eafc21 543 $bootServices['userPermissionClass'] = new $userPermissionClass();
7f835399 544
c64f69d9 545 $bootServices['cache.settings'] = \CRM_Utils_Cache::create([
56eafc21 546 'name' => 'settings',
c64f69d9
CW
547 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
548 ]);
7f835399 549
56eafc21 550 $bootServices['settings_manager'] = new \Civi\Core\SettingsManager($bootServices['cache.settings']);
7f835399 551
56eafc21 552 $bootServices['lockManager'] = self::createLockManager();
7f835399
TO
553
554 if ($loadFromDB && $runtime->dsn) {
3a036b15 555 \CRM_Core_DAO::init($runtime->dsn);
edbcbd96 556 \CRM_Utils_Hook::singleton(TRUE);
7f835399 557 \CRM_Extension_System::singleton(TRUE);
4025c773 558 \CRM_Extension_System::singleton(TRUE)->getClassLoader()->register();
27e05c5c 559 $bootServices['dispatcher.boot']->setDispatchPolicy($mainDispatchPolicy);
7f835399 560
1b81ed50 561 $runtime->includeCustomPath();
562
7f835399 563 $c = new self();
56eafc21
TO
564 $container = $c->loadContainer();
565 foreach ($bootServices as $name => $obj) {
566 $container->set($name, $obj);
567 }
568 \Civi::$statics[__CLASS__]['container'] = $container;
83617886 569 }
27e05c5c
TO
570 else {
571 $bootServices['dispatcher.boot']->setDispatchPolicy($mainDispatchPolicy);
572 }
83617886
TO
573 }
574
272dfdc3 575 /**
576 * @param string $name
577 *
578 * @return mixed
579 */
83617886 580 public static function getBootService($name) {
56eafc21 581 return \Civi::$statics[__CLASS__]['boot'][$name];
83617886
TO
582 }
583
4d8e83b6
TO
584 /**
585 * Determine whether the container services are available.
586 *
587 * @return bool
588 */
589 public static function isContainerBooted() {
590 return isset(\Civi::$statics[__CLASS__]['container']);
591 }
592
fa184193 593}