Convert the contact fields cache group to standard cache backend
[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',
96689db3 160 'navigation' => 'navigation',
792fce0b 161 'customData' => 'custom data',
9cdf85c1 162 'fields' => 'contact fields',
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.
5d27adeb 172 $fastArrayCaches = ['groups', 'navigation', 'customData'];
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]
a892989e 179 ))->setFactory('CRM_Utils_Cache::create');
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 ]
192 ))->setFactory('CRM_Utils_Cache::create');
193
4ed867e0
TO
194 $container->setDefinition('sql_triggers', new Definition(
195 'Civi\Core\SqlTriggers',
c64f69d9 196 []
4ed867e0
TO
197 ));
198
87e3fe24
TO
199 $container->setDefinition('asset_builder', new Definition(
200 'Civi\Core\AssetBuilder',
c64f69d9 201 []
87e3fe24
TO
202 ));
203
d89d2545
TO
204 $container->setDefinition('themes', new Definition(
205 'Civi\Core\Themes',
206 []
207 ));
208
247eb841 209 $container->setDefinition('pear_mail', new Definition('Mail'))
a892989e 210 ->setFactory('CRM_Utils_Mail::createMailer');
247eb841 211
7f835399
TO
212 if (empty(\Civi::$statics[__CLASS__]['boot'])) {
213 throw new \RuntimeException("Cannot initialize container. Boot services are undefined.");
214 }
215 foreach (\Civi::$statics[__CLASS__]['boot'] as $bootService => $def) {
56eafc21 216 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE);
83617886
TO
217 }
218
c8074a93 219 // Expose legacy singletons as services in the container.
c64f69d9 220 $singletons = [
c8074a93 221 'httpClient' => 'CRM_Utils_HttpClient',
7b5937fe 222 'cache.default' => 'CRM_Utils_Cache',
a7c57397 223 'i18n' => 'CRM_Core_I18n',
c8074a93
TO
224 // Maybe? 'config' => 'CRM_Core_Config',
225 // Maybe? 'smarty' => 'CRM_Core_Smarty',
c64f69d9 226 ];
c8074a93
TO
227 foreach ($singletons as $name => $class) {
228 $container->setDefinition($name, new Definition(
229 $class
230 ))
c64f69d9 231 ->setFactory([$class, 'singleton']);
c8074a93 232 }
90cdaa0e 233 $container->setAlias('cache.short', 'cache.default');
c8074a93 234
223ba025
TO
235 $container->setDefinition('resources', new Definition(
236 'CRM_Core_Resources',
237 [new Reference('service_container')]
c64f69d9 238 ))->setFactory([new Reference(self::SELF), 'createResources']);
223ba025 239
780fd0e3 240 $container->setDefinition('prevnext', new Definition(
99098349
TO
241 'CRM_Core_PrevNextCache_Interface',
242 [new Reference('service_container')]
c64f69d9 243 ))->setFactory([new Reference(self::SELF), 'createPrevNextCache']);
99098349
TO
244
245 $container->setDefinition('prevnext.driver.sql', new Definition(
780fd0e3
TO
246 'CRM_Core_PrevNextCache_Sql',
247 []
248 ));
249
751f3d98
TO
250 $container->setDefinition('prevnext.driver.redis', new Definition(
251 'CRM_Core_PrevNextCache_Redis',
252 [new Reference('cache_config')]
253 ));
254
255 $container->setDefinition('cache_config', new Definition('ArrayObject'))
c64f69d9 256 ->setFactory([new Reference(self::SELF), 'createCacheConfig']);
751f3d98 257
e7a6eae8
SL
258 $container->setDefinition('civi.mailing.triggers', new Definition(
259 'Civi\Core\SqlTrigger\TimestampTriggers',
c64f69d9
CW
260 ['civicrm_mailing', 'Mailing']
261 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
e7a6eae8 262
e0a667ad
TO
263 $container->setDefinition('civi.activity.triggers', new Definition(
264 'Civi\Core\SqlTrigger\TimestampTriggers',
c64f69d9
CW
265 ['civicrm_activity', 'Activity']
266 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
e0a667ad
TO
267
268 $container->setDefinition('civi.case.triggers', new Definition(
269 'Civi\Core\SqlTrigger\TimestampTriggers',
c64f69d9
CW
270 ['civicrm_case', 'Case']
271 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
e0a667ad 272
b21ffed7
TO
273 $container->setDefinition('civi.case.staticTriggers', new Definition(
274 'Civi\Core\SqlTrigger\StaticTriggers',
c64f69d9
CW
275 [
276 [
277 [
278 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
b21ffed7
TO
279 'table' => 'civicrm_case_activity',
280 'when' => 'AFTER',
c64f69d9 281 'event' => ['INSERT'],
b21ffed7 282 'sql' => "\nUPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.case_id;\n",
c64f69d9
CW
283 ],
284 [
285 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
b21ffed7
TO
286 'table' => 'civicrm_activity',
287 'when' => 'BEFORE',
c64f69d9 288 'event' => ['UPDATE', 'DELETE'],
b21ffed7 289 '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
290 ],
291 ],
292 ]
b21ffed7 293 ))
c64f69d9 294 ->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
b21ffed7 295
43ceab3f
TO
296 $container->setDefinition('civi_token_compat', new Definition(
297 'Civi\Token\TokenCompatSubscriber',
c64f69d9 298 []
43ceab3f 299 ))->addTag('kernel.event_subscriber');
56df2d06
TO
300 $container->setDefinition("crm_mailing_action_tokens", new Definition(
301 "CRM_Mailing_ActionTokens",
c64f69d9 302 []
56df2d06 303 ))->addTag('kernel.event_subscriber');
43ceab3f 304
c64f69d9 305 foreach (['Activity', 'Contribute', 'Event', 'Mailing', 'Member'] as $comp) {
46f5566c
TO
306 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
307 "CRM_{$comp}_Tokens",
c64f69d9 308 []
46f5566c
TO
309 ))->addTag('kernel.event_subscriber');
310 }
50a23755 311
aa4343bc 312 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_SERVICES')) {
c64f69d9 313 \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_SERVICES, [$container]);
aa4343bc
TO
314 }
315
40787e18
TO
316 \CRM_Utils_Hook::container($container);
317
fa184193
TO
318 return $container;
319 }
320
16072ce1
TO
321 /**
322 * @return \Civi\Angular\Manager
323 */
324 public function createAngularManager() {
325 return new \Civi\Angular\Manager(\CRM_Core_Resources::singleton());
326 }
327
fa184193 328 /**
34f3bbd9 329 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
43ceab3f 330 * @return \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
fa184193 331 */
40787e18 332 public function createEventDispatcher($container) {
762dc04d 333 $dispatcher = new CiviEventDispatcher($container);
c64f69d9
CW
334 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, ['\Civi\Core\InstallationCanary', 'check']);
335 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, ['\Civi\Core\DatabaseInitializer', 'initialize']);
336 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, ['\Civi\Core\LocalizationInitializer', 'initialize']);
337 $dispatcher->addListener('hook_civicrm_pre', ['\Civi\Core\Event\PreEvent', 'dispatchSubevent'], 100);
338 $dispatcher->addListener('hook_civicrm_post', ['\Civi\Core\Event\PostEvent', 'dispatchSubevent'], 100);
339 $dispatcher->addListener('hook_civicrm_post::Activity', ['\Civi\CCase\Events', 'fireCaseChange']);
340 $dispatcher->addListener('hook_civicrm_post::Case', ['\Civi\CCase\Events', 'fireCaseChange']);
341 $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\Events', 'delegateToXmlListeners']);
342 $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\SequenceListener', 'onCaseChange_static']);
343 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\CiviEventInspector', 'findBuiltInEvents']);
0d0031a0 344 // TODO We need a better code-convention for metadata about non-hook events.
c64f69d9
CW
345 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\API\Events', 'hookEventDefs']);
346 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs']);
347 $dispatcher->addListener('hook_civicrm_buildAsset', ['\Civi\Angular\Page\Modules', 'buildAngularModules']);
348 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetJs']);
349 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetCss']);
f22fb451 350 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Core_Resources', 'renderMenubarStylesheet']);
303017a1 351 $dispatcher->addListener('hook_civicrm_coreResourceList', ['\CRM_Utils_System', 'appendCoreResources']);
62c20d1e 352 $dispatcher->addListener('hook_civicrm_getAssetUrl', ['\CRM_Utils_System', 'alterAssetUrl']);
c64f69d9
CW
353 $dispatcher->addListener('civi.dao.postInsert', ['\CRM_Core_BAO_RecurringEntity', 'triggerInsert']);
354 $dispatcher->addListener('civi.dao.postUpdate', ['\CRM_Core_BAO_RecurringEntity', 'triggerUpdate']);
355 $dispatcher->addListener('civi.dao.postDelete', ['\CRM_Core_BAO_RecurringEntity', 'triggerDelete']);
356 $dispatcher->addListener('hook_civicrm_unhandled_exception', [
9ae2d27b
TO
357 'CRM_Core_LegacyErrorHandler',
358 'handleException',
c64f69d9
CW
359 ], -200);
360 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Activity_ActionMapping', 'onRegisterActionMappings']);
361 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Contact_ActionMapping', 'onRegisterActionMappings']);
362 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings']);
363 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings']);
364 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Event_ActionMapping', 'onRegisterActionMappings']);
365 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Member_ActionMapping', 'onRegisterActionMappings']);
46f5566c 366
aa4343bc 367 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_LISTENERS')) {
c64f69d9 368 \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_LISTENERS, [$dispatcher]);
aa4343bc
TO
369 }
370
fa184193
TO
371 return $dispatcher;
372 }
0f643fb2 373
10760fa1 374 /**
34f3bbd9 375 * @return \Civi\Core\Lock\LockManager
10760fa1 376 */
83617886 377 public static function createLockManager() {
10760fa1
TO
378 // Ideally, downstream implementers could override any definitions in
379 // the container. For now, we'll make-do with some define()s.
380 $lm = new LockManager();
381 $lm
c64f69d9
CW
382 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : ['CRM_Core_Lock', 'createScopedLock'])
383 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : ['CRM_Core_Lock', 'createScopedLock'])
384 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : ['CRM_Core_Lock', 'createCivimailLock'])
385 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : ['CRM_Core_Lock', 'createScopedLock']);
10760fa1
TO
386
387 // Registrations may use complex resolver expressions, but (as a micro-optimization)
388 // the default factory is specified as an array.
389
390 return $lm;
391 }
392
0f643fb2
TO
393 /**
394 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
2a6da8d7
EM
395 * @param $magicFunctionProvider
396 *
0f643fb2
TO
397 * @return \Civi\API\Kernel
398 */
c65db512 399 public function createApiKernel($dispatcher, $magicFunctionProvider) {
0a946de2 400 $dispatcher->addSubscriber(new \Civi\API\Subscriber\ChainSubscriber());
b55bc593 401 $dispatcher->addSubscriber(new \Civi\API\Subscriber\TransactionSubscriber());
bace5cd9 402 $dispatcher->addSubscriber(new \Civi\API\Subscriber\I18nSubscriber());
c65db512 403 $dispatcher->addSubscriber($magicFunctionProvider);
d0c9daa4 404 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
dcef11bd 405 $dispatcher->addSubscriber(new \Civi\API\Subscriber\APIv3SchemaAdapter());
c64f69d9 406 $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter([
6d3bdc98
TO
407 \CRM_Utils_API_HTMLInputCoder::singleton(),
408 \CRM_Utils_API_NullOutputCoder::singleton(),
409 \CRM_Utils_API_ReloadOption::singleton(),
410 \CRM_Utils_API_MatchOption::singleton(),
c64f69d9 411 ]));
0661f62b 412 $dispatcher->addSubscriber(new \Civi\API\Subscriber\XDebugSubscriber());
82376c19
TO
413 $kernel = new \Civi\API\Kernel($dispatcher);
414
415 $reflectionProvider = new \Civi\API\Provider\ReflectionProvider($kernel);
416 $dispatcher->addSubscriber($reflectionProvider);
417
56154d36
TO
418 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DynamicFKAuthorization(
419 $kernel,
420 'Attachment',
c64f69d9 421 ['create', 'get', 'delete'],
2e37a19f 422 // Given a file ID, determine the entity+table it's attached to.
56154d36
TO
423 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
424 FROM civicrm_file cf
425 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
426 WHERE cf.id = %1',
29468114
TO
427 // Get a list of custom fields (field_name,table_name,extends)
428 'SELECT concat("custom_",fld.id) as field_name,
429 grp.table_name as table_name,
430 grp.extends as extends
431 FROM civicrm_custom_field fld
432 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
433 WHERE fld.data_type = "File"
434 ',
c64f69d9 435 ['civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant']
56154d36
TO
436 ));
437
c64f69d9 438 $kernel->setApiProviders([
82376c19
TO
439 $reflectionProvider,
440 $magicFunctionProvider,
c64f69d9 441 ]);
82376c19 442
0f643fb2
TO
443 return $kernel;
444 }
96025800 445
223ba025 446 /**
34f3bbd9 447 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
223ba025
TO
448 * @return \CRM_Core_Resources
449 */
450 public static function createResources($container) {
451 $sys = \CRM_Extension_System::singleton();
452 return new \CRM_Core_Resources(
453 $sys->getMapper(),
454 $container->get('cache.js_strings'),
455 \CRM_Core_Config::isUpgradeMode() ? NULL : 'resCacheCode'
456 );
457 }
458
99098349 459 /**
34f3bbd9 460 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
99098349
TO
461 * @return \CRM_Core_PrevNextCache_Interface
462 */
463 public static function createPrevNextCache($container) {
e28bf654
TO
464 $setting = \Civi::settings()->get('prevNextBackend');
465 if ($setting === 'default') {
f76de01c
TO
466 // For initial release (5.8.x), continue defaulting to SQL.
467 $isTransitional = version_compare(\CRM_Utils_System::version(), '5.9.alpha1', '<');
e28bf654
TO
468 $cacheDriver = \CRM_Utils_Cache::getCacheDriver();
469 $service = 'prevnext.driver.' . strtolower($cacheDriver);
f76de01c 470 return $container->has($service) && !$isTransitional
e28bf654
TO
471 ? $container->get($service)
472 : $container->get('prevnext.driver.sql');
473 }
474 else {
475 return $container->get('prevnext.driver.' . $setting);
476 }
99098349
TO
477 }
478
751f3d98
TO
479 public static function createCacheConfig() {
480 $driver = \CRM_Utils_Cache::getCacheDriver();
481 $settings = \CRM_Utils_Cache::getCacheSettings($driver);
482 $settings['driver'] = $driver;
483 return new \ArrayObject($settings);
484 }
485
83617886
TO
486 /**
487 * Get a list of boot services.
488 *
489 * These are services which must be setup *before* the container can operate.
490 *
7f835399 491 * @param bool $loadFromDB
83617886
TO
492 * @throws \CRM_Core_Exception
493 */
7f835399 494 public static function boot($loadFromDB) {
56eafc21 495 // Array(string $serviceId => object $serviceInstance).
c64f69d9 496 $bootServices = [];
7f835399 497 \Civi::$statics[__CLASS__]['boot'] = &$bootServices;
d4330c62 498
56eafc21 499 $bootServices['runtime'] = $runtime = new \CRM_Core_Config_Runtime();
7f835399 500 $runtime->initialize($loadFromDB);
d4330c62 501
56eafc21 502 $bootServices['paths'] = new \Civi\Core\Paths();
d4330c62 503
7f835399 504 $class = $runtime->userFrameworkClass;
56eafc21 505 $bootServices['userSystem'] = $userSystem = new $class();
7f835399
TO
506 $userSystem->initialize();
507
508 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework;
56eafc21 509 $bootServices['userPermissionClass'] = new $userPermissionClass();
7f835399 510
c64f69d9 511 $bootServices['cache.settings'] = \CRM_Utils_Cache::create([
56eafc21 512 'name' => 'settings',
c64f69d9
CW
513 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
514 ]);
7f835399 515
56eafc21 516 $bootServices['settings_manager'] = new \Civi\Core\SettingsManager($bootServices['cache.settings']);
7f835399 517
56eafc21 518 $bootServices['lockManager'] = self::createLockManager();
7f835399
TO
519
520 if ($loadFromDB && $runtime->dsn) {
3a036b15 521 \CRM_Core_DAO::init($runtime->dsn);
edbcbd96 522 \CRM_Utils_Hook::singleton(TRUE);
7f835399 523 \CRM_Extension_System::singleton(TRUE);
4025c773 524 \CRM_Extension_System::singleton(TRUE)->getClassLoader()->register();
7f835399 525
1b81ed50 526 $runtime->includeCustomPath();
527
7f835399 528 $c = new self();
56eafc21
TO
529 $container = $c->loadContainer();
530 foreach ($bootServices as $name => $obj) {
531 $container->set($name, $obj);
532 }
533 \Civi::$statics[__CLASS__]['container'] = $container;
83617886 534 }
83617886
TO
535 }
536
537 public static function getBootService($name) {
56eafc21 538 return \Civi::$statics[__CLASS__]['boot'][$name];
83617886
TO
539 }
540
4d8e83b6
TO
541 /**
542 * Determine whether the container services are available.
543 *
544 * @return bool
545 */
546 public static function isContainerBooted() {
547 return isset(\Civi::$statics[__CLASS__]['container']);
548 }
549
fa184193 550}