4 use Civi\Core\Event\SystemInstallEvent
;
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
;
13 // TODO use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
21 const SELF
= 'civi_container_factory';
25 * Whether to forcibly rebuild the entire container.
26 * @return \Symfony\Component\DependencyInjection\TaggedContainerInterface
28 public static function singleton($reset = FALSE) {
29 if ($reset ||
!isset(\Civi
::$statics[__CLASS__
]['container'])) {
32 return \Civi
::$statics[__CLASS__
]['container'];
36 * Find a cached container definition or construct a new one.
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").
46 * - CIVICRM_CONTAINER_CACHE -- 'always' [default], 'never', 'auto'
50 * @return \Symfony\Component\DependencyInjection\ContainerInterface
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.
57 $cacheMode = defined('CIVICRM_CONTAINER_CACHE') ? CIVICRM_CONTAINER_CACHE
: 'auto';
59 // In pre-installation environments, don't bother with caching.
60 if (!defined('CIVICRM_DSN') ||
$cacheMode === 'never' || \CRM_Utils_System
::isInUpgradeMode()) {
61 $containerBuilder = $this->createContainer();
62 $containerBuilder->compile();
63 return $containerBuilder;
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()
80 $c = new \
CachedCiviContainer();
85 * Construct a new container.
87 * @var \Symfony\Component\DependencyInjection\ContainerBuilder
88 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
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);
98 $container->addResource(new \Symfony\Component\Config\
Resource\
FileResource(__FILE__
));
100 $container->setDefinition(self
::SELF
, new Definition(
101 'Civi\Core\Container',
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)');
109 // $locator = new FileLocator($configDirectories);
110 // $loaderResolver = new LoaderResolver(array(
111 // new YamlFileLoader($container, $locator)
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);
121 $container->setDefinition('angular', new Definition(
122 'Civi\Angular\Manager',
125 ->setFactory([new Reference(self
::SELF
), 'createAngularManager']);
127 $container->setDefinition('dispatcher', new Definition(
128 'Civi\Core\CiviEventDispatcher',
129 [new Reference('service_container')]
131 ->setFactory([new Reference(self
::SELF
), 'createEventDispatcher']);
133 $container->setDefinition('magic_function_provider', new Definition(
134 'Civi\API\Provider\MagicFunctionProvider',
138 $container->setDefinition('civi_api_kernel', new Definition(
140 [new Reference('dispatcher'), new Reference('magic_function_provider')]
142 ->setFactory([new Reference(self
::SELF
), 'createApiKernel']);
144 $container->setDefinition('cxn_reg_client', new Definition(
145 'Civi\Cxn\Rpc\RegistrationClient',
148 ->setFactory('CRM_Cxn_BAO_Cxn::createRegistrationClient');
150 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', []));
153 'js_strings' => 'js_strings',
154 'community_messages' => 'community_messages',
155 'checks' => 'checks',
156 'session' => 'CiviCRM Session',
158 'groups' => 'contact groups',
159 'navigation' => 'navigation',
160 'customData' => 'custom data',
161 'fields' => 'contact fields',
162 'contactTypes' => 'contactTypes',
163 'metadata' => 'metadata',
165 foreach ($basicCaches as $cacheSvc => $cacheGrp) {
166 $definitionParams = [
168 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
170 // For Caches that we don't really care about the ttl for and/or maybe accessed
171 // fairly often we use the fastArrayDecorator which improves reads and writes, these
172 // caches should also not have concurrency risk.
173 $fastArrayCaches = ['groups', 'navigation', 'customData', 'fields', 'contactTypes', 'metadata'];
174 if (in_array($cacheSvc, $fastArrayCaches)) {
175 $definitionParams['withArray'] = 'fast';
177 $container->setDefinition("cache.{$cacheSvc}", new Definition(
178 'CRM_Utils_Cache_Interface',
180 ))->setFactory('CRM_Utils_Cache::create');
183 // PrevNextCache cannot use memory or array cache at the moment because the
184 // Code in CRM_Core_BAO_PrevNextCache assumes that this cache is sql backed.
185 $container->setDefinition("cache.prevNextCache", new Definition(
186 'CRM_Utils_Cache_Interface',
189 'name' => 'CiviCRM Search PrevNextCache',
190 'type' => ['SqlGroup'],
193 ))->setFactory('CRM_Utils_Cache::create');
195 $container->setDefinition('sql_triggers', new Definition(
196 'Civi\Core\SqlTriggers',
200 $container->setDefinition('asset_builder', new Definition(
201 'Civi\Core\AssetBuilder',
205 $container->setDefinition('themes', new Definition(
210 $container->setDefinition('pear_mail', new Definition('Mail'))
211 ->setFactory('CRM_Utils_Mail::createMailer');
213 if (empty(\Civi
::$statics[__CLASS__
]['boot'])) {
214 throw new \
RuntimeException("Cannot initialize container. Boot services are undefined.");
216 foreach (\Civi
::$statics[__CLASS__
]['boot'] as $bootService => $def) {
217 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE);
220 // Expose legacy singletons as services in the container.
222 'httpClient' => 'CRM_Utils_HttpClient',
223 'cache.default' => 'CRM_Utils_Cache',
224 'i18n' => 'CRM_Core_I18n',
225 // Maybe? 'config' => 'CRM_Core_Config',
226 // Maybe? 'smarty' => 'CRM_Core_Smarty',
228 foreach ($singletons as $name => $class) {
229 $container->setDefinition($name, new Definition(
232 ->setFactory([$class, 'singleton']);
234 $container->setAlias('cache.short', 'cache.default');
236 $container->setDefinition('resources', new Definition(
237 'CRM_Core_Resources',
238 [new Reference('service_container')]
239 ))->setFactory([new Reference(self
::SELF
), 'createResources']);
241 $container->setDefinition('prevnext', new Definition(
242 'CRM_Core_PrevNextCache_Interface',
243 [new Reference('service_container')]
244 ))->setFactory([new Reference(self
::SELF
), 'createPrevNextCache']);
246 $container->setDefinition('prevnext.driver.sql', new Definition(
247 'CRM_Core_PrevNextCache_Sql',
251 $container->setDefinition('prevnext.driver.redis', new Definition(
252 'CRM_Core_PrevNextCache_Redis',
253 [new Reference('cache_config')]
256 $container->setDefinition('cache_config', new Definition('ArrayObject'))
257 ->setFactory([new Reference(self
::SELF
), 'createCacheConfig']);
259 $container->setDefinition('civi.mailing.triggers', new Definition(
260 'Civi\Core\SqlTrigger\TimestampTriggers',
261 ['civicrm_mailing', 'Mailing']
262 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
264 $container->setDefinition('civi.activity.triggers', new Definition(
265 'Civi\Core\SqlTrigger\TimestampTriggers',
266 ['civicrm_activity', 'Activity']
267 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
269 $container->setDefinition('civi.case.triggers', new Definition(
270 'Civi\Core\SqlTrigger\TimestampTriggers',
271 ['civicrm_case', 'Case']
272 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
274 $container->setDefinition('civi.case.staticTriggers', new Definition(
275 'Civi\Core\SqlTrigger\StaticTriggers',
279 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
280 'table' => 'civicrm_case_activity',
282 'event' => ['INSERT'],
283 'sql' => "\nUPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.case_id;\n",
286 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
287 'table' => 'civicrm_activity',
289 'event' => ['UPDATE', 'DELETE'],
290 '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",
295 ->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
297 $container->setDefinition('civi_token_compat', new Definition(
298 'Civi\Token\TokenCompatSubscriber',
300 ))->addTag('kernel.event_subscriber');
301 $container->setDefinition("crm_mailing_action_tokens", new Definition(
302 "CRM_Mailing_ActionTokens",
304 ))->addTag('kernel.event_subscriber');
306 foreach (['Activity', 'Contribute', 'Event', 'Mailing', 'Member'] as $comp) {
307 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
308 "CRM_{$comp}_Tokens",
310 ))->addTag('kernel.event_subscriber');
313 if (\CRM_Utils_Constant
::value('CIVICRM_FLEXMAILER_HACK_SERVICES')) {
314 \Civi\Core\Resolver
::singleton()->call(CIVICRM_FLEXMAILER_HACK_SERVICES
, [$container]);
317 \CRM_Utils_Hook
::container($container);
323 * @return \Civi\Angular\Manager
325 public function createAngularManager() {
326 return new \Civi\Angular\
Manager(\CRM_Core_Resources
::singleton());
330 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
331 * @return \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
333 public function createEventDispatcher($container) {
334 $dispatcher = new CiviEventDispatcher($container);
335 $dispatcher->addListener(SystemInstallEvent
::EVENT_NAME
, ['\Civi\Core\InstallationCanary', 'check']);
336 $dispatcher->addListener(SystemInstallEvent
::EVENT_NAME
, ['\Civi\Core\DatabaseInitializer', 'initialize']);
337 $dispatcher->addListener(SystemInstallEvent
::EVENT_NAME
, ['\Civi\Core\LocalizationInitializer', 'initialize']);
338 $dispatcher->addListener('hook_civicrm_pre', ['\Civi\Core\Event\PreEvent', 'dispatchSubevent'], 100);
339 $dispatcher->addListener('hook_civicrm_post', ['\Civi\Core\Event\PostEvent', 'dispatchSubevent'], 100);
340 $dispatcher->addListener('hook_civicrm_post::Activity', ['\Civi\CCase\Events', 'fireCaseChange']);
341 $dispatcher->addListener('hook_civicrm_post::Case', ['\Civi\CCase\Events', 'fireCaseChange']);
342 $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\Events', 'delegateToXmlListeners']);
343 $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\SequenceListener', 'onCaseChange_static']);
344 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\CiviEventInspector', 'findBuiltInEvents']);
345 // TODO We need a better code-convention for metadata about non-hook events.
346 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\API\Events', 'hookEventDefs']);
347 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs']);
348 $dispatcher->addListener('hook_civicrm_buildAsset', ['\Civi\Angular\Page\Modules', 'buildAngularModules']);
349 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetJs']);
350 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetCss']);
351 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Core_Resources', 'renderMenubarStylesheet']);
352 $dispatcher->addListener('hook_civicrm_coreResourceList', ['\CRM_Utils_System', 'appendCoreResources']);
353 $dispatcher->addListener('hook_civicrm_getAssetUrl', ['\CRM_Utils_System', 'alterAssetUrl']);
354 $dispatcher->addListener('civi.dao.postInsert', ['\CRM_Core_BAO_RecurringEntity', 'triggerInsert']);
355 $dispatcher->addListener('civi.dao.postUpdate', ['\CRM_Core_BAO_RecurringEntity', 'triggerUpdate']);
356 $dispatcher->addListener('civi.dao.postDelete', ['\CRM_Core_BAO_RecurringEntity', 'triggerDelete']);
357 $dispatcher->addListener('hook_civicrm_unhandled_exception', [
358 'CRM_Core_LegacyErrorHandler',
361 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, ['CRM_Activity_ActionMapping', 'onRegisterActionMappings']);
362 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, ['CRM_Contact_ActionMapping', 'onRegisterActionMappings']);
363 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, ['CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings']);
364 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, ['CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings']);
365 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, ['CRM_Event_ActionMapping', 'onRegisterActionMappings']);
366 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, ['CRM_Member_ActionMapping', 'onRegisterActionMappings']);
368 if (\CRM_Utils_Constant
::value('CIVICRM_FLEXMAILER_HACK_LISTENERS')) {
369 \Civi\Core\Resolver
::singleton()->call(CIVICRM_FLEXMAILER_HACK_LISTENERS
, [$dispatcher]);
376 * @return \Civi\Core\Lock\LockManager
378 public static function createLockManager() {
379 // Ideally, downstream implementers could override any definitions in
380 // the container. For now, we'll make-do with some define()s.
381 $lm = new LockManager();
383 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK
: ['CRM_Core_Lock', 'createScopedLock'])
384 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK
: ['CRM_Core_Lock', 'createScopedLock'])
385 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: ['CRM_Core_Lock', 'createCivimailLock'])
386 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: ['CRM_Core_Lock', 'createScopedLock']);
388 // Registrations may use complex resolver expressions, but (as a micro-optimization)
389 // the default factory is specified as an array.
395 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
396 * @param $magicFunctionProvider
398 * @return \Civi\API\Kernel
400 public function createApiKernel($dispatcher, $magicFunctionProvider) {
401 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
ChainSubscriber());
402 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
TransactionSubscriber());
403 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
I18nSubscriber());
404 $dispatcher->addSubscriber($magicFunctionProvider);
405 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
PermissionCheck());
406 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
APIv3SchemaAdapter());
407 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
WrapperAdapter([
408 \CRM_Utils_API_HTMLInputCoder
::singleton(),
409 \CRM_Utils_API_NullOutputCoder
::singleton(),
410 \CRM_Utils_API_ReloadOption
::singleton(),
411 \CRM_Utils_API_MatchOption
::singleton(),
413 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
XDebugSubscriber());
414 $kernel = new \Civi\API\
Kernel($dispatcher);
416 $reflectionProvider = new \Civi\API\Provider\
ReflectionProvider($kernel);
417 $dispatcher->addSubscriber($reflectionProvider);
419 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
DynamicFKAuthorization(
422 ['create', 'get', 'delete'],
423 // Given a file ID, determine the entity+table it's attached to.
424 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
426 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
428 // Get a list of custom fields (field_name,table_name,extends)
429 'SELECT concat("custom_",fld.id) as field_name,
430 grp.table_name as table_name,
431 grp.extends as extends
432 FROM civicrm_custom_field fld
433 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
434 WHERE fld.data_type = "File"
436 ['civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant']
439 $kernel->setApiProviders([
441 $magicFunctionProvider,
448 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
449 * @return \CRM_Core_Resources
451 public static function createResources($container) {
452 $sys = \CRM_Extension_System
::singleton();
453 return new \
CRM_Core_Resources(
455 $container->get('cache.js_strings'),
456 \CRM_Core_Config
::isUpgradeMode() ?
NULL : 'resCacheCode'
461 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
462 * @return \CRM_Core_PrevNextCache_Interface
464 public static function createPrevNextCache($container) {
465 $setting = \Civi
::settings()->get('prevNextBackend');
466 if ($setting === 'default') {
467 // For initial release (5.8.x), continue defaulting to SQL.
468 $isTransitional = version_compare(\CRM_Utils_System
::version(), '5.9.alpha1', '<');
469 $cacheDriver = \CRM_Utils_Cache
::getCacheDriver();
470 $service = 'prevnext.driver.' . strtolower($cacheDriver);
471 return $container->has($service) && !$isTransitional
472 ?
$container->get($service)
473 : $container->get('prevnext.driver.sql');
476 return $container->get('prevnext.driver.' . $setting);
480 public static function createCacheConfig() {
481 $driver = \CRM_Utils_Cache
::getCacheDriver();
482 $settings = \CRM_Utils_Cache
::getCacheSettings($driver);
483 $settings['driver'] = $driver;
484 return new \
ArrayObject($settings);
488 * Get a list of boot services.
490 * These are services which must be setup *before* the container can operate.
492 * @param bool $loadFromDB
493 * @throws \CRM_Core_Exception
495 public static function boot($loadFromDB) {
496 // Array(string $serviceId => object $serviceInstance).
498 \Civi
::$statics[__CLASS__
]['boot'] = &$bootServices;
500 $bootServices['runtime'] = $runtime = new \
CRM_Core_Config_Runtime();
501 $runtime->initialize($loadFromDB);
503 $bootServices['paths'] = new \Civi\Core\
Paths();
505 $class = $runtime->userFrameworkClass
;
506 $bootServices['userSystem'] = $userSystem = new $class();
507 $userSystem->initialize();
509 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework
;
510 $bootServices['userPermissionClass'] = new $userPermissionClass();
512 $bootServices['cache.settings'] = \CRM_Utils_Cache
::create([
513 'name' => 'settings',
514 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
517 $bootServices['settings_manager'] = new \Civi\Core\
SettingsManager($bootServices['cache.settings']);
519 $bootServices['lockManager'] = self
::createLockManager();
521 if ($loadFromDB && $runtime->dsn
) {
522 \CRM_Core_DAO
::init($runtime->dsn
);
523 \CRM_Utils_Hook
::singleton(TRUE);
524 \CRM_Extension_System
::singleton(TRUE);
525 \CRM_Extension_System
::singleton(TRUE)->getClassLoader()->register();
527 $runtime->includeCustomPath();
530 $container = $c->loadContainer();
531 foreach ($bootServices as $name => $obj) {
532 $container->set($name, $obj);
534 \Civi
::$statics[__CLASS__
]['container'] = $container;
538 public static function getBootService($name) {
539 return \Civi
::$statics[__CLASS__
]['boot'][$name];
543 * Determine whether the container services are available.
547 public static function isContainerBooted() {
548 return isset(\Civi
::$statics[__CLASS__
]['container']);