Merge pull request #23082 from agileware/CIVICRM-1958
[civicrm-core.git] / Civi / Core / Container.php
1 <?php
2 namespace Civi\Core;
3
4 use Civi\Core\Event\EventScanner;
5 use Civi\Core\Lock\LockManager;
6 use Symfony\Component\Config\ConfigCache;
7 use Symfony\Component\DependencyInjection\ContainerBuilder;
8 use Symfony\Component\DependencyInjection\Definition;
9 use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
10 use Symfony\Component\DependencyInjection\Reference;
11 use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass;
12
13 // TODO use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
14
15 /**
16 * Class Container
17 * @package Civi\Core
18 */
19 class Container {
20
21 const SELF = 'civi_container_factory';
22
23 /**
24 * @param bool $reset
25 * Whether to forcibly rebuild the entire container.
26 * @return \Symfony\Component\DependencyInjection\TaggedContainerInterface
27 */
28 public static function singleton($reset = FALSE) {
29 if ($reset || !isset(\Civi::$statics[__CLASS__]['container'])) {
30 self::boot(TRUE);
31 }
32 return \Civi::$statics[__CLASS__]['container'];
33 }
34
35 /**
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 *
50 * @return \Symfony\Component\DependencyInjection\ContainerInterface
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
57 $cacheMode = defined('CIVICRM_CONTAINER_CACHE') ? CIVICRM_CONTAINER_CACHE : 'auto';
58
59 // In pre-installation environments, don't bother with caching.
60 if (!defined('CIVICRM_DSN') || defined('CIVICRM_TEST') || CIVICRM_UF === 'UnitTests' || $cacheMode === 'never' || \CRM_Utils_System::isInUpgradeMode()) {
61 $containerBuilder = $this->createContainer();
62 $containerBuilder->compile();
63 return $containerBuilder;
64 }
65
66 $envId = \CRM_Core_Config_Runtime::getId();
67 $file = \Civi::paths()->getPath("[civicrm.compile]/CachedCiviContainer.{$envId}.php");
68 $containerConfigCache = new ConfigCache($file, $cacheMode === 'auto');
69 if (!$containerConfigCache->isFresh()) {
70 $containerBuilder = $this->createContainer();
71 $containerBuilder->compile();
72 $dumper = new PhpDumper($containerBuilder);
73 $containerConfigCache->write(
74 $dumper->dump(['class' => 'CachedCiviContainer']),
75 $containerBuilder->getResources()
76 );
77 }
78
79 require_once $file;
80 $c = new \CachedCiviContainer();
81 return $c;
82 }
83
84 /**
85 * Construct a new container.
86 *
87 * @var \Symfony\Component\DependencyInjection\ContainerBuilder
88 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
89 */
90 public function createContainer() {
91 $civicrm_base_path = dirname(dirname(__DIR__));
92 $container = new ContainerBuilder();
93 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
94 $container->addObjectResource($this);
95 $container->setParameter('civicrm_base_path', $civicrm_base_path);
96 //$container->set(self::SELF, $this);
97
98 $container->addResource(new \Symfony\Component\Config\Resource\FileResource(__FILE__));
99
100 $container->setDefinition(self::SELF, new Definition(
101 'Civi\Core\Container',
102 []
103 ));
104
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 // }
120
121 $container->setDefinition('angular', new Definition(
122 'Civi\Angular\Manager',
123 []
124 ))
125 ->setFactory([new Reference(self::SELF), 'createAngularManager'])->setPublic(TRUE);
126
127 $container->setDefinition('angularjs.loader', new Definition('Civi\Angular\AngularLoader', []))
128 ->setPublic(TRUE);
129
130 $container->setDefinition('dispatcher', new Definition(
131 'Civi\Core\CiviEventDispatcher',
132 []
133 ))
134 ->setFactory([new Reference(self::SELF), 'createEventDispatcher'])->setPublic(TRUE);
135
136 $container->setDefinition('magic_function_provider', new Definition(
137 'Civi\API\Provider\MagicFunctionProvider',
138 []
139 ))->setPublic(TRUE);
140
141 $container->setDefinition('civi_api_kernel', new Definition(
142 'Civi\API\Kernel',
143 [new Reference('dispatcher'), new Reference('magic_function_provider')]
144 ))
145 ->setFactory([new Reference(self::SELF), 'createApiKernel'])->setPublic(TRUE);
146
147 $container->setDefinition('cxn_reg_client', new Definition(
148 'Civi\Cxn\Rpc\RegistrationClient',
149 []
150 ))
151 ->setFactory('CRM_Cxn_BAO_Cxn::createRegistrationClient')->setPublic(TRUE);
152
153 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', []))->setPublic(TRUE);
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);
157
158 $basicCaches = [
159 'js_strings' => 'js_strings',
160 'community_messages' => 'community_messages',
161 'checks' => 'checks',
162 'session' => 'CiviCRM Session',
163 'long' => 'long',
164 'groups' => 'contact groups',
165 'navigation' => 'navigation',
166 'customData' => 'custom data',
167 'fields' => 'contact fields',
168 'contactTypes' => 'contactTypes',
169 'metadata' => 'metadata',
170 ];
171 $verSuffixCaches = ['metadata'];
172 $verSuffix = '_' . preg_replace(';[^0-9a-z_];', '_', \CRM_Utils_System::version());
173 foreach ($basicCaches as $cacheSvc => $cacheGrp) {
174 $definitionParams = [
175 'name' => $cacheGrp . (in_array($cacheGrp, $verSuffixCaches) ? $verSuffix : ''),
176 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
177 ];
178 // For Caches that we don't really care about the ttl for and/or maybe accessed
179 // fairly often we use the fastArrayDecorator which improves reads and writes, these
180 // caches should also not have concurrency risk.
181 $fastArrayCaches = ['groups', 'navigation', 'customData', 'fields', 'contactTypes', 'metadata'];
182 if (in_array($cacheSvc, $fastArrayCaches)) {
183 $definitionParams['withArray'] = 'fast';
184 }
185 $container->setDefinition("cache.{$cacheSvc}", new Definition(
186 'CRM_Utils_Cache_Interface',
187 [$definitionParams]
188 ))->setFactory('CRM_Utils_Cache::create')->setPublic(TRUE);
189 }
190
191 // PrevNextCache cannot use memory or array cache at the moment because the
192 // Code in CRM_Core_BAO_PrevNextCache assumes that this cache is sql backed.
193 $container->setDefinition("cache.prevNextCache", new Definition(
194 'CRM_Utils_Cache_Interface',
195 [
196 [
197 'name' => 'CiviCRM Search PrevNextCache',
198 'type' => ['SqlGroup'],
199 ],
200 ]
201 ))->setFactory('CRM_Utils_Cache::create')->setPublic(TRUE);
202
203 $container->setDefinition('sql_triggers', new Definition(
204 'Civi\Core\SqlTriggers',
205 []
206 ))->setPublic(TRUE);
207
208 $container->setDefinition('asset_builder', new Definition(
209 'Civi\Core\AssetBuilder',
210 []
211 ))->setPublic(TRUE);
212
213 $container->setDefinition('themes', new Definition(
214 'Civi\Core\Themes',
215 []
216 ))->setPublic(TRUE);
217
218 $container->setDefinition('format', new Definition(
219 '\Civi\Core\Format',
220 []
221 ))->setPublic(TRUE);
222
223 $container->setDefinition('bundle.bootstrap3', new Definition('CRM_Core_Resources_Bundle', ['bootstrap3']))
224 ->setFactory('CRM_Core_Resources_Common::createBootstrap3Bundle')->setPublic(TRUE);
225
226 $container->setDefinition('bundle.coreStyles', new Definition('CRM_Core_Resources_Bundle', ['coreStyles']))
227 ->setFactory('CRM_Core_Resources_Common::createStyleBundle')->setPublic(TRUE);
228
229 $container->setDefinition('bundle.coreResources', new Definition('CRM_Core_Resources_Bundle', ['coreResources']))
230 ->setFactory('CRM_Core_Resources_Common::createFullBundle')->setPublic(TRUE);
231
232 $container->setDefinition('pear_mail', new Definition('Mail'))
233 ->setFactory('CRM_Utils_Mail::createMailer')->setPublic(TRUE);
234
235 $container->setDefinition('crypto.registry', new Definition('Civi\Crypto\CryptoService'))
236 ->setFactory('Civi\Crypto\CryptoRegistry::createDefaultRegistry')->setPublic(TRUE);
237
238 $container->setDefinition('crypto.token', new Definition('Civi\Crypto\CryptoToken', []))
239 ->setPublic(TRUE);
240
241 $container->setDefinition('crypto.jwt', new Definition('Civi\Crypto\CryptoJwt', []))
242 ->setPublic(TRUE);
243
244 if (empty(\Civi::$statics[__CLASS__]['boot'])) {
245 throw new \RuntimeException('Cannot initialize container. Boot services are undefined.');
246 }
247 foreach (\Civi::$statics[__CLASS__]['boot'] as $bootService => $def) {
248 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE)->setPublic(TRUE);
249 }
250
251 // Expose legacy singletons as services in the container.
252 $singletons = [
253 'httpClient' => 'CRM_Utils_HttpClient',
254 'cache.default' => 'CRM_Utils_Cache',
255 'i18n' => 'CRM_Core_I18n',
256 // Maybe? 'config' => 'CRM_Core_Config',
257 // Maybe? 'smarty' => 'CRM_Core_Smarty',
258 ];
259 foreach ($singletons as $name => $class) {
260 $container->setDefinition($name, new Definition(
261 $class
262 ))
263 ->setFactory([$class, 'singleton'])->setPublic(TRUE);
264 }
265 $container->setAlias('cache.short', 'cache.default')->setPublic(TRUE);
266
267 $container->setDefinition('civi.pipe', new Definition(
268 'Civi\Pipe\PipeSession',
269 []
270 ))->setPublic(TRUE)->setShared(FALSE);
271
272 $container->setDefinition('resources', new Definition(
273 'CRM_Core_Resources',
274 [new Reference('service_container')]
275 ))->setFactory([new Reference(self::SELF), 'createResources'])->setPublic(TRUE);
276
277 $container->setDefinition('resources.js_strings', new Definition(
278 'CRM_Core_Resources_Strings',
279 [new Reference('cache.js_strings')]
280 ))->setPublic(TRUE);
281
282 $container->setDefinition('prevnext', new Definition(
283 'CRM_Core_PrevNextCache_Interface',
284 [new Reference('service_container')]
285 ))->setFactory([new Reference(self::SELF), 'createPrevNextCache'])->setPublic(TRUE);
286
287 $container->setDefinition('prevnext.driver.sql', new Definition(
288 'CRM_Core_PrevNextCache_Sql',
289 []
290 ))->setPublic(TRUE);
291
292 $container->setDefinition('prevnext.driver.redis', new Definition(
293 'CRM_Core_PrevNextCache_Redis',
294 [new Reference('cache_config')]
295 ))->setPublic(TRUE);
296
297 $container->setDefinition('cache_config', new Definition('ArrayObject'))
298 ->setFactory([new Reference(self::SELF), 'createCacheConfig'])->setPublic(TRUE);
299
300 $container->setDefinition('civi.activity.triggers', new Definition(
301 'Civi\Core\SqlTrigger\TimestampTriggers',
302 ['civicrm_activity', 'Activity']
303 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'])->setPublic(TRUE);
304
305 $container->setDefinition('civi.case.triggers', new Definition(
306 'Civi\Core\SqlTrigger\TimestampTriggers',
307 ['civicrm_case', 'Case']
308 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'])->setPublic(TRUE);
309
310 $container->setDefinition('civi.case.staticTriggers', new Definition(
311 'Civi\Core\SqlTrigger\StaticTriggers',
312 [
313 [
314 [
315 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
316 'table' => 'civicrm_case_activity',
317 'when' => 'AFTER',
318 'event' => ['INSERT'],
319 'sql' => "UPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.case_id;",
320 ],
321 [
322 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
323 'table' => 'civicrm_activity',
324 'when' => 'BEFORE',
325 'event' => ['UPDATE', 'DELETE'],
326 'sql' => "UPDATE 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);",
327 ],
328 ],
329 ]
330 ))
331 ->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'])->setPublic(TRUE);
332
333 $container->setDefinition('civi_token_compat', new Definition(
334 'Civi\Token\TokenCompatSubscriber',
335 []
336 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
337 $container->setDefinition("crm_mailing_action_tokens", new Definition(
338 'CRM_Mailing_ActionTokens',
339 []
340 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
341
342 foreach (['Activity', 'Contact', 'Contribute', 'Event', 'Mailing', 'Member', 'Case'] as $comp) {
343 $container->setDefinition('crm_' . strtolower($comp) . '_tokens', new Definition(
344 "CRM_{$comp}_Tokens",
345 []
346 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
347 }
348 $container->setDefinition('civi_token_impliedcontext', new Definition(
349 'Civi\Token\ImpliedContextSubscriber',
350 []
351 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
352 $container->setDefinition('crm_participant_tokens', new Definition(
353 'CRM_Event_ParticipantTokens',
354 []
355 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
356 $container->setDefinition('crm_contribution_recur_tokens', new Definition(
357 'CRM_Contribute_RecurTokens',
358 []
359 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
360 $container->setDefinition('crm_domain_tokens', new Definition(
361 'CRM_Core_DomainTokens',
362 []
363 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
364
365 $dispatcherDefn = $container->getDefinition('dispatcher');
366 foreach (\CRM_Core_DAO_AllCoreTables::getBaoClasses() as $baoEntity => $baoClass) {
367 $listenerMap = EventScanner::findListeners($baoClass, $baoEntity);
368 if ($listenerMap) {
369 $file = (new \ReflectionClass($baoClass))->getFileName();
370 $container->addResource(new \Symfony\Component\Config\Resource\FileResource($file));
371 $dispatcherDefn->addMethodCall('addListenerMap', [$baoClass, $listenerMap]);
372 }
373 }
374
375 \CRM_Api4_Services::hook_container($container);
376
377 \CRM_Utils_Hook::container($container);
378
379 return $container;
380 }
381
382 /**
383 * @return \Civi\Angular\Manager
384 */
385 public function createAngularManager() {
386 return new \Civi\Angular\Manager(\CRM_Core_Resources::singleton());
387 }
388
389 /**
390 * @return \Symfony\Component\EventDispatcher\EventDispatcher
391 */
392 public function createEventDispatcher() {
393 // Continue building on the original dispatcher created during bootstrap.
394 /** @var CiviEventDispatcher $dispatcher */
395 $dispatcher = static::getBootService('dispatcher.boot');
396
397 // Sometimes, you have a generic event ('hook_pre') and wish to fire more targeted aliases ('hook_pre::MyEntity') to allow shorter subscriber lists.
398 $aliasEvent = function($eventName, $fieldName) {
399 return function($e) use ($eventName, $fieldName) {
400 \Civi::dispatcher()->dispatch($eventName . "::" . $e->{$fieldName}, $e);
401 };
402 };
403 $aliasMethodEvent = function($eventName, $methodName) {
404 return function($e) use ($eventName, $methodName) {
405 \Civi::dispatcher()->dispatch($eventName . "::" . $e->{$methodName}(), $e);
406 };
407 };
408
409 $dispatcher->addListener('civi.api4.validate', $aliasMethodEvent('civi.api4.validate', 'getEntityName'), 100);
410 $dispatcher->addListener('civi.api4.authorizeRecord', $aliasMethodEvent('civi.api4.authorizeRecord', 'getEntityName'), 100);
411 $dispatcher->addListener('civi.api4.entityTypes', ['\Civi\Api4\Provider\CustomEntityProvider', 'addCustomEntities'], 100);
412
413 $dispatcher->addListener('civi.core.install', ['\Civi\Core\InstallationCanary', 'check']);
414 $dispatcher->addListener('civi.core.install', ['\Civi\Core\DatabaseInitializer', 'initialize']);
415 $dispatcher->addListener('civi.core.install', ['\Civi\Core\LocalizationInitializer', 'initialize']);
416 $dispatcher->addListener('hook_civicrm_post', ['\CRM_Core_Transaction', 'addPostCommit'], -1000);
417 $dispatcher->addListener('hook_civicrm_pre', $aliasEvent('hook_civicrm_pre', 'entity'), 100);
418 $dispatcher->addListener('civi.dao.preDelete', ['\CRM_Core_BAO_EntityTag', 'preDeleteOtherEntity']);
419 $dispatcher->addListener('hook_civicrm_post', $aliasEvent('hook_civicrm_post', 'entity'), 100);
420 $dispatcher->addListener('hook_civicrm_post::Activity', ['\Civi\CCase\Events', 'fireCaseChange']);
421 $dispatcher->addListener('hook_civicrm_post::Case', ['\Civi\CCase\Events', 'fireCaseChange']);
422 $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\Events', 'delegateToXmlListeners']);
423 $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\SequenceListener', 'onCaseChange_static']);
424 $dispatcher->addListener('hook_civicrm_cryptoRotateKey', ['\Civi\Crypto\RotateKeys', 'rotateSmtp']);
425 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\CiviEventInspector', 'findBuiltInEvents']);
426 // TODO We need a better code-convention for metadata about non-hook events.
427 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\API\Events', 'hookEventDefs']);
428 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs']);
429 $dispatcher->addListener('hook_civicrm_buildAsset', ['\Civi\Angular\Page\Modules', 'buildAngularModules']);
430 $dispatcher->addListenerService('civi.region.render', ['angularjs.loader', 'onRegionRender']);
431 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetJs']);
432 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetCss']);
433 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Core_Resources', 'renderMenubarStylesheet']);
434 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Core_Resources', 'renderL10nJs']);
435 $dispatcher->addListener('hook_civicrm_coreResourceList', ['\CRM_Utils_System', 'appendCoreResources']);
436 $dispatcher->addListener('hook_civicrm_getAssetUrl', ['\CRM_Utils_System', 'alterAssetUrl']);
437 $dispatcher->addListener('hook_civicrm_alterExternUrl', ['\CRM_Utils_System', 'migrateExternUrl'], 1000);
438 // Not a BAO class so it can't implement hookInterface
439 $dispatcher->addListener('hook_civicrm_post', ['CRM_Utils_Recent', 'on_hook_civicrm_post']);
440 $dispatcher->addListener('hook_civicrm_permissionList', ['CRM_Core_Permission_List', 'findConstPermissions'], 975);
441 $dispatcher->addListener('hook_civicrm_permissionList', ['CRM_Core_Permission_List', 'findCiviPermissions'], 950);
442 $dispatcher->addListener('hook_civicrm_permissionList', ['CRM_Core_Permission_List', 'findCmsPermissions'], 925);
443
444 $dispatcher->addListener('hook_civicrm_postSave_civicrm_domain', ['\CRM_Core_BAO_Domain', 'onPostSave']);
445 $dispatcher->addListener('hook_civicrm_unhandled_exception', [
446 'CRM_Core_LegacyErrorHandler',
447 'handleException',
448 ], -200);
449 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Activity_ActionMapping', 'onRegisterActionMappings']);
450 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Contact_ActionMapping', 'onRegisterActionMappings']);
451 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings']);
452 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings']);
453 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Event_ActionMapping', 'onRegisterActionMappings']);
454 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Member_ActionMapping', 'onRegisterActionMappings']);
455
456 return $dispatcher;
457 }
458
459 /**
460 * @return \Civi\Core\Lock\LockManager
461 */
462 public static function createLockManager() {
463 // Ideally, downstream implementers could override any definitions in
464 // the container. For now, we'll make-do with some define()s.
465 $lm = new LockManager();
466 $lm
467 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : ['CRM_Core_Lock', 'createScopedLock'])
468 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : ['CRM_Core_Lock', 'createScopedLock'])
469 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : ['CRM_Core_Lock', 'createCivimailLock'])
470 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : ['CRM_Core_Lock', 'createScopedLock']);
471
472 // Registrations may use complex resolver expressions, but (as a micro-optimization)
473 // the default factory is specified as an array.
474
475 return $lm;
476 }
477
478 /**
479 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
480 * @param $magicFunctionProvider
481 *
482 * @return \Civi\API\Kernel
483 */
484 public function createApiKernel($dispatcher, $magicFunctionProvider) {
485 $dispatcher->addSubscriber(new \Civi\API\Subscriber\ChainSubscriber());
486 $dispatcher->addSubscriber(new \Civi\API\Subscriber\TransactionSubscriber());
487 $dispatcher->addSubscriber(new \Civi\API\Subscriber\I18nSubscriber());
488 $dispatcher->addSubscriber($magicFunctionProvider);
489 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
490 $dispatcher->addSubscriber(new \Civi\API\Subscriber\APIv3SchemaAdapter());
491 $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter([
492 \CRM_Utils_API_HTMLInputCoder::singleton(),
493 \CRM_Utils_API_NullOutputCoder::singleton(),
494 \CRM_Utils_API_ReloadOption::singleton(),
495 \CRM_Utils_API_MatchOption::singleton(),
496 ]));
497 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DebugSubscriber());
498 $kernel = new \Civi\API\Kernel($dispatcher);
499
500 $reflectionProvider = new \Civi\API\Provider\ReflectionProvider($kernel);
501 $dispatcher->addSubscriber($reflectionProvider);
502
503 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DynamicFKAuthorization(
504 $kernel,
505 'Attachment',
506 ['create', 'get', 'delete'],
507 // Given a file ID, determine the entity+table it's attached to.
508 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
509 FROM civicrm_file cf
510 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
511 WHERE cf.id = %1',
512 // Get a list of custom fields (field_name,table_name,extends)
513 'SELECT concat("custom_",fld.id) as field_name,
514 grp.table_name as table_name,
515 grp.extends as extends
516 FROM civicrm_custom_field fld
517 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
518 WHERE fld.data_type = "File"
519 '
520 ));
521
522 $kernel->setApiProviders([
523 $reflectionProvider,
524 $magicFunctionProvider,
525 ]);
526
527 return $kernel;
528 }
529
530 /**
531 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
532 * @return \CRM_Core_Resources
533 */
534 public static function createResources($container) {
535 $sys = \CRM_Extension_System::singleton();
536 return new \CRM_Core_Resources(
537 $sys->getMapper(),
538 new \CRM_Core_Resources_Strings($container->get('cache.js_strings')),
539 \CRM_Core_Config::isUpgradeMode() ? NULL : 'resCacheCode'
540 );
541 }
542
543 /**
544 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
545 * @return \CRM_Core_PrevNextCache_Interface
546 */
547 public static function createPrevNextCache($container) {
548 $setting = \Civi::settings()->get('prevNextBackend');
549 if (!$setting || $setting === 'default') {
550 $cacheDriver = \CRM_Utils_Cache::getCacheDriver();
551 $service = 'prevnext.driver.' . strtolower($cacheDriver);
552 return $container->has($service)
553 ? $container->get($service)
554 : $container->get('prevnext.driver.sql');
555 }
556 return $container->get('prevnext.driver.' . $setting);
557 }
558
559 /**
560 * @return \ArrayObject
561 */
562 public static function createCacheConfig() {
563 $driver = \CRM_Utils_Cache::getCacheDriver();
564 $settings = \CRM_Utils_Cache::getCacheSettings($driver);
565 $settings['driver'] = $driver;
566 return new \ArrayObject($settings);
567 }
568
569 /**
570 * Get a list of boot services.
571 *
572 * These are services which must be setup *before* the container can operate.
573 *
574 * @param bool $loadFromDB
575 * @throws \CRM_Core_Exception
576 */
577 public static function boot($loadFromDB) {
578 // Array(string $serviceId => object $serviceInstance).
579 $bootServices = [];
580 \Civi::$statics[__CLASS__]['boot'] = &$bootServices;
581
582 $bootServices['runtime'] = $runtime = new \CRM_Core_Config_Runtime();
583 $runtime->initialize($loadFromDB);
584
585 $bootServices['paths'] = new \Civi\Core\Paths();
586
587 $bootServices['dispatcher.boot'] = new CiviEventDispatcher();
588
589 // Quality control: There should be no pre-boot hooks because they make it harder to understand/support/refactor.
590 // If a pre-boot hook sneaks in, we'll raise an error.
591 $bootDispatchPolicy = [
592 '/^hook_/' => 'not-ready',
593 '/^civi\./' => 'run',
594 ];
595 $mainDispatchPolicy = \CRM_Core_Config::isUpgradeMode() ? \CRM_Upgrade_DispatchPolicy::get('upgrade.main') : NULL;
596 $bootServices['dispatcher.boot']->setDispatchPolicy($bootDispatchPolicy);
597
598 $class = $runtime->userFrameworkClass;
599 $bootServices['userSystem'] = $userSystem = new $class();
600 $userSystem->initialize();
601
602 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework;
603 $bootServices['userPermissionClass'] = new $userPermissionClass();
604
605 $bootServices['cache.settings'] = \CRM_Utils_Cache::create([
606 'name' => 'settings',
607 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
608 ]);
609
610 $bootServices['settings_manager'] = new \Civi\Core\SettingsManager($bootServices['cache.settings']);
611
612 $bootServices['lockManager'] = self::createLockManager();
613
614 if ($loadFromDB && $runtime->dsn) {
615 \CRM_Core_DAO::init($runtime->dsn);
616 \CRM_Utils_Hook::singleton(TRUE);
617 \CRM_Extension_System::singleton(TRUE);
618 \CRM_Extension_System::singleton()->getClassLoader()->register();
619 \CRM_Extension_System::singleton()->getMixinLoader()->run();
620 $bootServices['dispatcher.boot']->setDispatchPolicy($mainDispatchPolicy);
621
622 $runtime->includeCustomPath();
623
624 $c = new self();
625 $container = $c->loadContainer();
626 foreach ($bootServices as $name => $obj) {
627 $container->set($name, $obj);
628 }
629 \Civi::$statics[__CLASS__]['container'] = $container;
630 // Ensure all container-based serivces have a chance to add their listeners.
631 // Without this, it's a matter of happenstance (dependent upon particular page-request/configuration/etc).
632 $container->get('dispatcher');
633
634 }
635 else {
636 $bootServices['dispatcher.boot']->setDispatchPolicy($mainDispatchPolicy);
637 }
638 }
639
640 /**
641 * @param string $name
642 *
643 * @return mixed
644 */
645 public static function getBootService($name) {
646 return \Civi::$statics[__CLASS__]['boot'][$name];
647 }
648
649 /**
650 * Determine whether the container services are available.
651 *
652 * @return bool
653 */
654 public static function isContainerBooted() {
655 return isset(\Civi::$statics[__CLASS__]['container']);
656 }
657
658 }