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