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