Merge pull request #14812 from eileenmcnaughton/ee
[civicrm-core.git] / Civi / Core / Container.php
CommitLineData
fa184193
TO
1<?php
2namespace Civi\Core;
46bcf597 3
0085db83 4use Civi\Core\Event\SystemInstallEvent;
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
49 * - CIVICRM_TEMPLATE_COMPILEDIR
50 *
34f3bbd9 51 * @return \Symfony\Component\DependencyInjection\ContainerInterface
40787e18
TO
52 */
53 public function loadContainer() {
54 // Note: The container's raison d'etre is to manage construction of other
55 // services. Consequently, we assume a minimal service available -- the classloader
56 // has been setup, and civicrm.settings.php is loaded, but nothing else works.
57
5497e016 58 $cacheMode = defined('CIVICRM_CONTAINER_CACHE') ? CIVICRM_CONTAINER_CACHE : 'auto';
40787e18
TO
59
60 // In pre-installation environments, don't bother with caching.
61 if (!defined('CIVICRM_TEMPLATE_COMPILEDIR') || !defined('CIVICRM_DSN') || $cacheMode === 'never' || \CRM_Utils_System::isInUpgradeMode()) {
12e01332
TO
62 $containerBuilder = $this->createContainer();
63 $containerBuilder->compile();
64 return $containerBuilder;
40787e18
TO
65 }
66
83617886 67 $envId = \CRM_Core_Config_Runtime::getId();
40787e18
TO
68 $file = CIVICRM_TEMPLATE_COMPILEDIR . "/CachedCiviContainer.{$envId}.php";
69 $containerConfigCache = new ConfigCache($file, $cacheMode === 'auto');
40787e18
TO
70 if (!$containerConfigCache->isFresh()) {
71 $containerBuilder = $this->createContainer();
72 $containerBuilder->compile();
73 $dumper = new PhpDumper($containerBuilder);
74 $containerConfigCache->write(
c64f69d9 75 $dumper->dump(['class' => 'CachedCiviContainer']),
40787e18
TO
76 $containerBuilder->getResources()
77 );
78 }
79
80 require_once $file;
81 $c = new \CachedCiviContainer();
40787e18
TO
82 return $c;
83 }
84
85 /**
86 * Construct a new container.
87 *
34f3bbd9 88 * @var \Symfony\Component\DependencyInjection\ContainerBuilder
77b97be7 89 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
fa184193
TO
90 */
91 public function createContainer() {
92 $civicrm_base_path = dirname(dirname(__DIR__));
93 $container = new ContainerBuilder();
40787e18
TO
94 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
95 $container->addObjectResource($this);
fa184193 96 $container->setParameter('civicrm_base_path', $civicrm_base_path);
40787e18 97 //$container->set(self::SELF, $this);
762dc04d
TO
98
99 $container->addResource(new \Symfony\Component\Config\Resource\FileResource(__FILE__));
100
40787e18
TO
101 $container->setDefinition(self::SELF, new Definition(
102 'Civi\Core\Container',
c64f69d9 103 []
40787e18 104 ));
fa184193 105
505d8b83
TO
106 // TODO Move configuration to an external file; define caching structure
107 // if (empty($configDirectories)) {
108 // throw new \Exception(__CLASS__ . ': Missing required properties (civicrmRoot, configDirectories)');
109 // }
110 // $locator = new FileLocator($configDirectories);
111 // $loaderResolver = new LoaderResolver(array(
112 // new YamlFileLoader($container, $locator)
113 // ));
114 // $delegatingLoader = new DelegatingLoader($loaderResolver);
115 // foreach (array('services.yml') as $file) {
116 // $yamlUserFiles = $locator->locate($file, NULL, FALSE);
117 // foreach ($yamlUserFiles as $file) {
118 // $delegatingLoader->load($file);
119 // }
120 // }
fa184193 121
16072ce1 122 $container->setDefinition('angular', new Definition(
40787e18 123 'Civi\Angular\Manager',
c64f69d9 124 []
16072ce1 125 ))
c64f69d9 126 ->setFactory([new Reference(self::SELF), 'createAngularManager']);
16072ce1 127
fa184193 128 $container->setDefinition('dispatcher', new Definition(
762dc04d 129 'Civi\Core\CiviEventDispatcher',
c64f69d9 130 [new Reference('service_container')]
fa184193 131 ))
c64f69d9 132 ->setFactory([new Reference(self::SELF), 'createEventDispatcher']);
fa184193 133
c65db512 134 $container->setDefinition('magic_function_provider', new Definition(
40787e18 135 'Civi\API\Provider\MagicFunctionProvider',
c64f69d9 136 []
c65db512
TO
137 ));
138
0f643fb2 139 $container->setDefinition('civi_api_kernel', new Definition(
40787e18 140 'Civi\API\Kernel',
c64f69d9 141 [new Reference('dispatcher'), new Reference('magic_function_provider')]
0f643fb2 142 ))
c64f69d9 143 ->setFactory([new Reference(self::SELF), 'createApiKernel']);
0f643fb2 144
7b4bbb34 145 $container->setDefinition('cxn_reg_client', new Definition(
40787e18 146 'Civi\Cxn\Rpc\RegistrationClient',
c64f69d9 147 []
7b4bbb34 148 ))
5eda8e9b 149 ->setFactory('CRM_Cxn_BAO_Cxn::createRegistrationClient');
7b4bbb34 150
c64f69d9 151 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', []));
6e5ad5ee 152
c64f69d9 153 $basicCaches = [
7a19d718
TO
154 'js_strings' => 'js_strings',
155 'community_messages' => 'community_messages',
b1fc1ab0 156 'checks' => 'checks',
19707a63 157 'session' => 'CiviCRM Session',
90cdaa0e 158 'long' => 'long',
0136044e 159 'groups' => 'contact groups',
c64f69d9 160 ];
7a19d718 161 foreach ($basicCaches as $cacheSvc => $cacheGrp) {
023bcf83
SL
162 $definitionParams = [
163 'name' => $cacheGrp,
164 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
165 ];
166 // For Caches that we don't really care about the ttl for and/or maybe accessed
167 // fairly often we use the fastArrayDecorator which improves reads and writes, these
168 // caches should also not have concurrency risk.
169 $fastArrayCaches = ['groups'];
170 if (in_array($cacheSvc, $fastArrayCaches)) {
171 $definitionParams['withArray'] = 'fast';
172 }
7a19d718 173 $container->setDefinition("cache.{$cacheSvc}", new Definition(
a4704404 174 'CRM_Utils_Cache_Interface',
023bcf83 175 [$definitionParams]
a892989e 176 ))->setFactory('CRM_Utils_Cache::create');
a4704404 177 }
3a84c0ab 178
da4effce
SL
179 // PrevNextCache cannot use memory or array cache at the moment because the
180 // Code in CRM_Core_BAO_PrevNextCache assumes that this cache is sql backed.
181 $container->setDefinition("cache.prevNextCache", new Definition(
182 'CRM_Utils_Cache_Interface',
183 [
184 [
185 'name' => 'CiviCRM Search PrevNextCache',
186 'type' => ['SqlGroup'],
187 ],
188 ]
189 ))->setFactory('CRM_Utils_Cache::create');
190
4ed867e0
TO
191 $container->setDefinition('sql_triggers', new Definition(
192 'Civi\Core\SqlTriggers',
c64f69d9 193 []
4ed867e0
TO
194 ));
195
87e3fe24
TO
196 $container->setDefinition('asset_builder', new Definition(
197 'Civi\Core\AssetBuilder',
c64f69d9 198 []
87e3fe24
TO
199 ));
200
d89d2545
TO
201 $container->setDefinition('themes', new Definition(
202 'Civi\Core\Themes',
203 []
204 ));
205
247eb841 206 $container->setDefinition('pear_mail', new Definition('Mail'))
a892989e 207 ->setFactory('CRM_Utils_Mail::createMailer');
247eb841 208
7f835399
TO
209 if (empty(\Civi::$statics[__CLASS__]['boot'])) {
210 throw new \RuntimeException("Cannot initialize container. Boot services are undefined.");
211 }
212 foreach (\Civi::$statics[__CLASS__]['boot'] as $bootService => $def) {
56eafc21 213 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE);
83617886
TO
214 }
215
c8074a93 216 // Expose legacy singletons as services in the container.
c64f69d9 217 $singletons = [
c8074a93 218 'httpClient' => 'CRM_Utils_HttpClient',
7b5937fe 219 'cache.default' => 'CRM_Utils_Cache',
a7c57397 220 'i18n' => 'CRM_Core_I18n',
c8074a93
TO
221 // Maybe? 'config' => 'CRM_Core_Config',
222 // Maybe? 'smarty' => 'CRM_Core_Smarty',
c64f69d9 223 ];
c8074a93
TO
224 foreach ($singletons as $name => $class) {
225 $container->setDefinition($name, new Definition(
226 $class
227 ))
c64f69d9 228 ->setFactory([$class, 'singleton']);
c8074a93 229 }
90cdaa0e 230 $container->setAlias('cache.short', 'cache.default');
c8074a93 231
223ba025
TO
232 $container->setDefinition('resources', new Definition(
233 'CRM_Core_Resources',
234 [new Reference('service_container')]
c64f69d9 235 ))->setFactory([new Reference(self::SELF), 'createResources']);
223ba025 236
780fd0e3 237 $container->setDefinition('prevnext', new Definition(
99098349
TO
238 'CRM_Core_PrevNextCache_Interface',
239 [new Reference('service_container')]
c64f69d9 240 ))->setFactory([new Reference(self::SELF), 'createPrevNextCache']);
99098349
TO
241
242 $container->setDefinition('prevnext.driver.sql', new Definition(
780fd0e3
TO
243 'CRM_Core_PrevNextCache_Sql',
244 []
245 ));
246
751f3d98
TO
247 $container->setDefinition('prevnext.driver.redis', new Definition(
248 'CRM_Core_PrevNextCache_Redis',
249 [new Reference('cache_config')]
250 ));
251
252 $container->setDefinition('cache_config', new Definition('ArrayObject'))
c64f69d9 253 ->setFactory([new Reference(self::SELF), 'createCacheConfig']);
751f3d98 254
e7a6eae8
SL
255 $container->setDefinition('civi.mailing.triggers', new Definition(
256 'Civi\Core\SqlTrigger\TimestampTriggers',
c64f69d9
CW
257 ['civicrm_mailing', 'Mailing']
258 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
e7a6eae8 259
e0a667ad
TO
260 $container->setDefinition('civi.activity.triggers', new Definition(
261 'Civi\Core\SqlTrigger\TimestampTriggers',
c64f69d9
CW
262 ['civicrm_activity', 'Activity']
263 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
e0a667ad
TO
264
265 $container->setDefinition('civi.case.triggers', new Definition(
266 'Civi\Core\SqlTrigger\TimestampTriggers',
c64f69d9
CW
267 ['civicrm_case', 'Case']
268 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
e0a667ad 269
b21ffed7
TO
270 $container->setDefinition('civi.case.staticTriggers', new Definition(
271 'Civi\Core\SqlTrigger\StaticTriggers',
c64f69d9
CW
272 [
273 [
274 [
275 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
b21ffed7
TO
276 'table' => 'civicrm_case_activity',
277 'when' => 'AFTER',
c64f69d9 278 'event' => ['INSERT'],
b21ffed7 279 'sql' => "\nUPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.case_id;\n",
c64f69d9
CW
280 ],
281 [
282 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
b21ffed7
TO
283 'table' => 'civicrm_activity',
284 'when' => 'BEFORE',
c64f69d9 285 'event' => ['UPDATE', 'DELETE'],
b21ffed7 286 '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
287 ],
288 ],
289 ]
b21ffed7 290 ))
c64f69d9 291 ->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
b21ffed7 292
43ceab3f
TO
293 $container->setDefinition('civi_token_compat', new Definition(
294 'Civi\Token\TokenCompatSubscriber',
c64f69d9 295 []
43ceab3f 296 ))->addTag('kernel.event_subscriber');
56df2d06
TO
297 $container->setDefinition("crm_mailing_action_tokens", new Definition(
298 "CRM_Mailing_ActionTokens",
c64f69d9 299 []
56df2d06 300 ))->addTag('kernel.event_subscriber');
43ceab3f 301
c64f69d9 302 foreach (['Activity', 'Contribute', 'Event', 'Mailing', 'Member'] as $comp) {
46f5566c
TO
303 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
304 "CRM_{$comp}_Tokens",
c64f69d9 305 []
46f5566c
TO
306 ))->addTag('kernel.event_subscriber');
307 }
50a23755 308
aa4343bc 309 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_SERVICES')) {
c64f69d9 310 \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_SERVICES, [$container]);
aa4343bc
TO
311 }
312
40787e18
TO
313 \CRM_Utils_Hook::container($container);
314
fa184193
TO
315 return $container;
316 }
317
16072ce1
TO
318 /**
319 * @return \Civi\Angular\Manager
320 */
321 public function createAngularManager() {
322 return new \Civi\Angular\Manager(\CRM_Core_Resources::singleton());
323 }
324
fa184193 325 /**
34f3bbd9 326 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
43ceab3f 327 * @return \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
fa184193 328 */
40787e18 329 public function createEventDispatcher($container) {
762dc04d 330 $dispatcher = new CiviEventDispatcher($container);
c64f69d9
CW
331 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, ['\Civi\Core\InstallationCanary', 'check']);
332 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, ['\Civi\Core\DatabaseInitializer', 'initialize']);
333 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, ['\Civi\Core\LocalizationInitializer', 'initialize']);
334 $dispatcher->addListener('hook_civicrm_pre', ['\Civi\Core\Event\PreEvent', 'dispatchSubevent'], 100);
335 $dispatcher->addListener('hook_civicrm_post', ['\Civi\Core\Event\PostEvent', 'dispatchSubevent'], 100);
336 $dispatcher->addListener('hook_civicrm_post::Activity', ['\Civi\CCase\Events', 'fireCaseChange']);
337 $dispatcher->addListener('hook_civicrm_post::Case', ['\Civi\CCase\Events', 'fireCaseChange']);
338 $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\Events', 'delegateToXmlListeners']);
339 $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\SequenceListener', 'onCaseChange_static']);
340 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\CiviEventInspector', 'findBuiltInEvents']);
0d0031a0 341 // TODO We need a better code-convention for metadata about non-hook events.
c64f69d9
CW
342 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\API\Events', 'hookEventDefs']);
343 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs']);
344 $dispatcher->addListener('hook_civicrm_buildAsset', ['\Civi\Angular\Page\Modules', 'buildAngularModules']);
345 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetJs']);
346 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetCss']);
f22fb451 347 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Core_Resources', 'renderMenubarStylesheet']);
303017a1 348 $dispatcher->addListener('hook_civicrm_coreResourceList', ['\CRM_Utils_System', 'appendCoreResources']);
62c20d1e 349 $dispatcher->addListener('hook_civicrm_getAssetUrl', ['\CRM_Utils_System', 'alterAssetUrl']);
c64f69d9
CW
350 $dispatcher->addListener('civi.dao.postInsert', ['\CRM_Core_BAO_RecurringEntity', 'triggerInsert']);
351 $dispatcher->addListener('civi.dao.postUpdate', ['\CRM_Core_BAO_RecurringEntity', 'triggerUpdate']);
352 $dispatcher->addListener('civi.dao.postDelete', ['\CRM_Core_BAO_RecurringEntity', 'triggerDelete']);
353 $dispatcher->addListener('hook_civicrm_unhandled_exception', [
9ae2d27b
TO
354 'CRM_Core_LegacyErrorHandler',
355 'handleException',
c64f69d9
CW
356 ], -200);
357 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Activity_ActionMapping', 'onRegisterActionMappings']);
358 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Contact_ActionMapping', 'onRegisterActionMappings']);
359 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings']);
360 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings']);
361 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Event_ActionMapping', 'onRegisterActionMappings']);
362 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Member_ActionMapping', 'onRegisterActionMappings']);
46f5566c 363
aa4343bc 364 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_LISTENERS')) {
c64f69d9 365 \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_LISTENERS, [$dispatcher]);
aa4343bc
TO
366 }
367
fa184193
TO
368 return $dispatcher;
369 }
0f643fb2 370
10760fa1 371 /**
34f3bbd9 372 * @return \Civi\Core\Lock\LockManager
10760fa1 373 */
83617886 374 public static function createLockManager() {
10760fa1
TO
375 // Ideally, downstream implementers could override any definitions in
376 // the container. For now, we'll make-do with some define()s.
377 $lm = new LockManager();
378 $lm
c64f69d9
CW
379 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : ['CRM_Core_Lock', 'createScopedLock'])
380 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : ['CRM_Core_Lock', 'createScopedLock'])
381 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : ['CRM_Core_Lock', 'createCivimailLock'])
382 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : ['CRM_Core_Lock', 'createScopedLock']);
10760fa1
TO
383
384 // Registrations may use complex resolver expressions, but (as a micro-optimization)
385 // the default factory is specified as an array.
386
387 return $lm;
388 }
389
0f643fb2
TO
390 /**
391 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
2a6da8d7
EM
392 * @param $magicFunctionProvider
393 *
0f643fb2
TO
394 * @return \Civi\API\Kernel
395 */
c65db512 396 public function createApiKernel($dispatcher, $magicFunctionProvider) {
0a946de2 397 $dispatcher->addSubscriber(new \Civi\API\Subscriber\ChainSubscriber());
b55bc593 398 $dispatcher->addSubscriber(new \Civi\API\Subscriber\TransactionSubscriber());
bace5cd9 399 $dispatcher->addSubscriber(new \Civi\API\Subscriber\I18nSubscriber());
c65db512 400 $dispatcher->addSubscriber($magicFunctionProvider);
d0c9daa4 401 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
dcef11bd 402 $dispatcher->addSubscriber(new \Civi\API\Subscriber\APIv3SchemaAdapter());
c64f69d9 403 $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter([
6d3bdc98
TO
404 \CRM_Utils_API_HTMLInputCoder::singleton(),
405 \CRM_Utils_API_NullOutputCoder::singleton(),
406 \CRM_Utils_API_ReloadOption::singleton(),
407 \CRM_Utils_API_MatchOption::singleton(),
c64f69d9 408 ]));
0661f62b 409 $dispatcher->addSubscriber(new \Civi\API\Subscriber\XDebugSubscriber());
82376c19
TO
410 $kernel = new \Civi\API\Kernel($dispatcher);
411
412 $reflectionProvider = new \Civi\API\Provider\ReflectionProvider($kernel);
413 $dispatcher->addSubscriber($reflectionProvider);
414
56154d36
TO
415 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DynamicFKAuthorization(
416 $kernel,
417 'Attachment',
c64f69d9 418 ['create', 'get', 'delete'],
2e37a19f 419 // Given a file ID, determine the entity+table it's attached to.
56154d36
TO
420 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
421 FROM civicrm_file cf
422 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
423 WHERE cf.id = %1',
29468114
TO
424 // Get a list of custom fields (field_name,table_name,extends)
425 'SELECT concat("custom_",fld.id) as field_name,
426 grp.table_name as table_name,
427 grp.extends as extends
428 FROM civicrm_custom_field fld
429 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
430 WHERE fld.data_type = "File"
431 ',
c64f69d9 432 ['civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant']
56154d36
TO
433 ));
434
c64f69d9 435 $kernel->setApiProviders([
82376c19
TO
436 $reflectionProvider,
437 $magicFunctionProvider,
c64f69d9 438 ]);
82376c19 439
0f643fb2
TO
440 return $kernel;
441 }
96025800 442
223ba025 443 /**
34f3bbd9 444 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
223ba025
TO
445 * @return \CRM_Core_Resources
446 */
447 public static function createResources($container) {
448 $sys = \CRM_Extension_System::singleton();
449 return new \CRM_Core_Resources(
450 $sys->getMapper(),
451 $container->get('cache.js_strings'),
452 \CRM_Core_Config::isUpgradeMode() ? NULL : 'resCacheCode'
453 );
454 }
455
99098349 456 /**
34f3bbd9 457 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
99098349
TO
458 * @return \CRM_Core_PrevNextCache_Interface
459 */
460 public static function createPrevNextCache($container) {
e28bf654
TO
461 $setting = \Civi::settings()->get('prevNextBackend');
462 if ($setting === 'default') {
f76de01c
TO
463 // For initial release (5.8.x), continue defaulting to SQL.
464 $isTransitional = version_compare(\CRM_Utils_System::version(), '5.9.alpha1', '<');
e28bf654
TO
465 $cacheDriver = \CRM_Utils_Cache::getCacheDriver();
466 $service = 'prevnext.driver.' . strtolower($cacheDriver);
f76de01c 467 return $container->has($service) && !$isTransitional
e28bf654
TO
468 ? $container->get($service)
469 : $container->get('prevnext.driver.sql');
470 }
471 else {
472 return $container->get('prevnext.driver.' . $setting);
473 }
99098349
TO
474 }
475
751f3d98
TO
476 public static function createCacheConfig() {
477 $driver = \CRM_Utils_Cache::getCacheDriver();
478 $settings = \CRM_Utils_Cache::getCacheSettings($driver);
479 $settings['driver'] = $driver;
480 return new \ArrayObject($settings);
481 }
482
83617886
TO
483 /**
484 * Get a list of boot services.
485 *
486 * These are services which must be setup *before* the container can operate.
487 *
7f835399 488 * @param bool $loadFromDB
83617886
TO
489 * @throws \CRM_Core_Exception
490 */
7f835399 491 public static function boot($loadFromDB) {
56eafc21 492 // Array(string $serviceId => object $serviceInstance).
c64f69d9 493 $bootServices = [];
7f835399 494 \Civi::$statics[__CLASS__]['boot'] = &$bootServices;
d4330c62 495
56eafc21 496 $bootServices['runtime'] = $runtime = new \CRM_Core_Config_Runtime();
7f835399 497 $runtime->initialize($loadFromDB);
d4330c62 498
56eafc21 499 $bootServices['paths'] = new \Civi\Core\Paths();
d4330c62 500
7f835399 501 $class = $runtime->userFrameworkClass;
56eafc21 502 $bootServices['userSystem'] = $userSystem = new $class();
7f835399
TO
503 $userSystem->initialize();
504
505 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework;
56eafc21 506 $bootServices['userPermissionClass'] = new $userPermissionClass();
7f835399 507
c64f69d9 508 $bootServices['cache.settings'] = \CRM_Utils_Cache::create([
56eafc21 509 'name' => 'settings',
c64f69d9
CW
510 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
511 ]);
7f835399 512
56eafc21 513 $bootServices['settings_manager'] = new \Civi\Core\SettingsManager($bootServices['cache.settings']);
7f835399 514
56eafc21 515 $bootServices['lockManager'] = self::createLockManager();
7f835399
TO
516
517 if ($loadFromDB && $runtime->dsn) {
3a036b15 518 \CRM_Core_DAO::init($runtime->dsn);
edbcbd96 519 \CRM_Utils_Hook::singleton(TRUE);
7f835399 520 \CRM_Extension_System::singleton(TRUE);
4025c773 521 \CRM_Extension_System::singleton(TRUE)->getClassLoader()->register();
7f835399 522
1b81ed50 523 $runtime->includeCustomPath();
524
7f835399 525 $c = new self();
56eafc21
TO
526 $container = $c->loadContainer();
527 foreach ($bootServices as $name => $obj) {
528 $container->set($name, $obj);
529 }
530 \Civi::$statics[__CLASS__]['container'] = $container;
83617886 531 }
83617886
TO
532 }
533
534 public static function getBootService($name) {
56eafc21 535 return \Civi::$statics[__CLASS__]['boot'][$name];
83617886
TO
536 }
537
4d8e83b6
TO
538 /**
539 * Determine whether the container services are available.
540 *
541 * @return bool
542 */
543 public static function isContainerBooted() {
544 return isset(\Civi::$statics[__CLASS__]['container']);
545 }
546
fa184193 547}