CRM_Utils_String - Add URL-style base64 codec
[civicrm-core.git] / Civi / Core / Container.php
1 <?php
2 namespace Civi\Core;
3
4 use Civi\Core\Lock\LockManager;
5 use Symfony\Component\Config\ConfigCache;
6 use Symfony\Component\DependencyInjection\ContainerBuilder;
7 use Symfony\Component\DependencyInjection\Definition;
8 use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
9 use Symfony\Component\DependencyInjection\Reference;
10 use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass;
11
12 // TODO use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
13
14 /**
15 * Class Container
16 * @package Civi\Core
17 */
18 class Container {
19
20 const SELF = 'civi_container_factory';
21
22 /**
23 * @param bool $reset
24 * Whether to forcibly rebuild the entire container.
25 * @return \Symfony\Component\DependencyInjection\TaggedContainerInterface
26 */
27 public static function singleton($reset = FALSE) {
28 if ($reset || !isset(\Civi::$statics[__CLASS__]['container'])) {
29 self::boot(TRUE);
30 }
31 return \Civi::$statics[__CLASS__]['container'];
32 }
33
34 /**
35 * Find a cached container definition or construct a new one.
36 *
37 * There are many weird contexts in which Civi initializes (eg different
38 * variations of multitenancy and different permutations of CMS/CRM bootstrap),
39 * and hook_container may fire a bit differently in each context. To mitigate
40 * risk of leaks between environments, we compute a unique envID
41 * (md5(DB_NAME, HTTP_HOST, SCRIPT_FILENAME, etc)) and use separate caches for
42 * each (eg "templates_c/CachedCiviContainer.$ENVID.php").
43 *
44 * Constants:
45 * - CIVICRM_CONTAINER_CACHE -- 'always' [default], 'never', 'auto'
46 * - CIVICRM_DSN
47 * - CIVICRM_DOMAIN_ID
48 *
49 * @return \Symfony\Component\DependencyInjection\ContainerInterface
50 */
51 public function loadContainer() {
52 // Note: The container's raison d'etre is to manage construction of other
53 // services. Consequently, we assume a minimal service available -- the classloader
54 // has been setup, and civicrm.settings.php is loaded, but nothing else works.
55
56 $cacheMode = defined('CIVICRM_CONTAINER_CACHE') ? CIVICRM_CONTAINER_CACHE : 'auto';
57
58 // In pre-installation environments, don't bother with caching.
59 if (!defined('CIVICRM_DSN') || defined('CIVICRM_TEST') || CIVICRM_UF === 'UnitTests' || $cacheMode === 'never' || \CRM_Utils_System::isInUpgradeMode()) {
60 $containerBuilder = $this->createContainer();
61 $containerBuilder->compile();
62 return $containerBuilder;
63 }
64
65 $envId = \CRM_Core_Config_Runtime::getId();
66 $file = \Civi::paths()->getPath("[civicrm.compile]/CachedCiviContainer.{$envId}.php");
67 $containerConfigCache = new ConfigCache($file, $cacheMode === 'auto');
68 if (!$containerConfigCache->isFresh()) {
69 $containerBuilder = $this->createContainer();
70 $containerBuilder->compile();
71 $dumper = new PhpDumper($containerBuilder);
72 $containerConfigCache->write(
73 $dumper->dump(['class' => 'CachedCiviContainer']),
74 $containerBuilder->getResources()
75 );
76 }
77
78 require_once $file;
79 $c = new \CachedCiviContainer();
80 return $c;
81 }
82
83 /**
84 * Construct a new container.
85 *
86 * @var \Symfony\Component\DependencyInjection\ContainerBuilder
87 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
88 */
89 public function createContainer() {
90 $civicrm_base_path = dirname(dirname(__DIR__));
91 $container = new ContainerBuilder();
92 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
93 $container->addObjectResource($this);
94 $container->setParameter('civicrm_base_path', $civicrm_base_path);
95 //$container->set(self::SELF, $this);
96
97 $container->addResource(new \Symfony\Component\Config\Resource\FileResource(__FILE__));
98
99 $container->setDefinition(self::SELF, new Definition(
100 'Civi\Core\Container',
101 []
102 ));
103
104 // TODO Move configuration to an external file; define caching structure
105 // if (empty($configDirectories)) {
106 // throw new \Exception(__CLASS__ . ': Missing required properties (civicrmRoot, configDirectories)');
107 // }
108 // $locator = new FileLocator($configDirectories);
109 // $loaderResolver = new LoaderResolver(array(
110 // new YamlFileLoader($container, $locator)
111 // ));
112 // $delegatingLoader = new DelegatingLoader($loaderResolver);
113 // foreach (array('services.yml') as $file) {
114 // $yamlUserFiles = $locator->locate($file, NULL, FALSE);
115 // foreach ($yamlUserFiles as $file) {
116 // $delegatingLoader->load($file);
117 // }
118 // }
119
120 $container->setDefinition('angular', new Definition(
121 'Civi\Angular\Manager',
122 []
123 ))
124 ->setFactory([new Reference(self::SELF), 'createAngularManager'])->setPublic(TRUE);
125
126 $container->setDefinition('dispatcher', new Definition(
127 'Civi\Core\CiviEventDispatcher',
128 []
129 ))
130 ->setFactory([new Reference(self::SELF), 'createEventDispatcher'])->setPublic(TRUE);
131
132 $container->setDefinition('magic_function_provider', new Definition(
133 'Civi\API\Provider\MagicFunctionProvider',
134 []
135 ))->setPublic(TRUE);
136
137 $container->setDefinition('civi_api_kernel', new Definition(
138 'Civi\API\Kernel',
139 [new Reference('dispatcher'), new Reference('magic_function_provider')]
140 ))
141 ->setFactory([new Reference(self::SELF), 'createApiKernel'])->setPublic(TRUE);
142
143 $container->setDefinition('cxn_reg_client', new Definition(
144 'Civi\Cxn\Rpc\RegistrationClient',
145 []
146 ))
147 ->setFactory('CRM_Cxn_BAO_Cxn::createRegistrationClient')->setPublic(TRUE);
148
149 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', []))->setPublic(TRUE);
150
151 $basicCaches = [
152 'js_strings' => 'js_strings',
153 'community_messages' => 'community_messages',
154 'checks' => 'checks',
155 'session' => 'CiviCRM Session',
156 'long' => 'long',
157 'groups' => 'contact groups',
158 'navigation' => 'navigation',
159 'customData' => 'custom data',
160 'fields' => 'contact fields',
161 'contactTypes' => 'contactTypes',
162 'metadata' => 'metadata',
163 ];
164 foreach ($basicCaches as $cacheSvc => $cacheGrp) {
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.
172 $fastArrayCaches = ['groups', 'navigation', 'customData', 'fields', 'contactTypes', 'metadata'];
173 if (in_array($cacheSvc, $fastArrayCaches)) {
174 $definitionParams['withArray'] = 'fast';
175 }
176 $container->setDefinition("cache.{$cacheSvc}", new Definition(
177 'CRM_Utils_Cache_Interface',
178 [$definitionParams]
179 ))->setFactory('CRM_Utils_Cache::create')->setPublic(TRUE);
180 }
181
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')->setPublic(TRUE);
193
194 $container->setDefinition('sql_triggers', new Definition(
195 'Civi\Core\SqlTriggers',
196 []
197 ))->setPublic(TRUE);
198
199 $container->setDefinition('asset_builder', new Definition(
200 'Civi\Core\AssetBuilder',
201 []
202 ))->setPublic(TRUE);
203
204 $container->setDefinition('themes', new Definition(
205 'Civi\Core\Themes',
206 []
207 ))->setPublic(TRUE);
208
209 $container->setDefinition('bundle.bootstrap3', new Definition('CRM_Core_Resources_Bundle', ['bootstrap3']))
210 ->setFactory('CRM_Core_Resources_Common::createBootstrap3Bundle')->setPublic(TRUE);
211
212 $container->setDefinition('bundle.coreStyles', new Definition('CRM_Core_Resources_Bundle', ['coreStyles']))
213 ->setFactory('CRM_Core_Resources_Common::createStyleBundle')->setPublic(TRUE);
214
215 $container->setDefinition('bundle.coreResources', new Definition('CRM_Core_Resources_Bundle', ['coreResources']))
216 ->setFactory('CRM_Core_Resources_Common::createFullBundle')->setPublic(TRUE);
217
218 $container->setDefinition('pear_mail', new Definition('Mail'))
219 ->setFactory('CRM_Utils_Mail::createMailer')->setPublic(TRUE);
220
221 if (empty(\Civi::$statics[__CLASS__]['boot'])) {
222 throw new \RuntimeException('Cannot initialize container. Boot services are undefined.');
223 }
224 foreach (\Civi::$statics[__CLASS__]['boot'] as $bootService => $def) {
225 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE)->setPublic(TRUE);
226 }
227
228 // Expose legacy singletons as services in the container.
229 $singletons = [
230 'httpClient' => 'CRM_Utils_HttpClient',
231 'cache.default' => 'CRM_Utils_Cache',
232 'i18n' => 'CRM_Core_I18n',
233 // Maybe? 'config' => 'CRM_Core_Config',
234 // Maybe? 'smarty' => 'CRM_Core_Smarty',
235 ];
236 foreach ($singletons as $name => $class) {
237 $container->setDefinition($name, new Definition(
238 $class
239 ))
240 ->setFactory([$class, 'singleton'])->setPublic(TRUE);
241 }
242 $container->setAlias('cache.short', 'cache.default')->setPublic(TRUE);
243
244 $container->setDefinition('resources', new Definition(
245 'CRM_Core_Resources',
246 [new Reference('service_container')]
247 ))->setFactory([new Reference(self::SELF), 'createResources'])->setPublic(TRUE);
248
249 $container->setDefinition('resources.js_strings', new Definition(
250 'CRM_Core_Resources_Strings',
251 [new Reference('cache.js_strings')]
252 ))->setPublic(TRUE);
253
254 $container->setDefinition('prevnext', new Definition(
255 'CRM_Core_PrevNextCache_Interface',
256 [new Reference('service_container')]
257 ))->setFactory([new Reference(self::SELF), 'createPrevNextCache'])->setPublic(TRUE);
258
259 $container->setDefinition('prevnext.driver.sql', new Definition(
260 'CRM_Core_PrevNextCache_Sql',
261 []
262 ))->setPublic(TRUE);
263
264 $container->setDefinition('prevnext.driver.redis', new Definition(
265 'CRM_Core_PrevNextCache_Redis',
266 [new Reference('cache_config')]
267 ))->setPublic(TRUE);
268
269 $container->setDefinition('cache_config', new Definition('ArrayObject'))
270 ->setFactory([new Reference(self::SELF), 'createCacheConfig'])->setPublic(TRUE);
271
272 $container->setDefinition('civi.mailing.triggers', new Definition(
273 'Civi\Core\SqlTrigger\TimestampTriggers',
274 ['civicrm_mailing', 'Mailing']
275 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'])->setPublic(TRUE);
276
277 $container->setDefinition('civi.activity.triggers', new Definition(
278 'Civi\Core\SqlTrigger\TimestampTriggers',
279 ['civicrm_activity', 'Activity']
280 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'])->setPublic(TRUE);
281
282 $container->setDefinition('civi.case.triggers', new Definition(
283 'Civi\Core\SqlTrigger\TimestampTriggers',
284 ['civicrm_case', 'Case']
285 ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'])->setPublic(TRUE);
286
287 $container->setDefinition('civi.case.staticTriggers', new Definition(
288 'Civi\Core\SqlTrigger\StaticTriggers',
289 [
290 [
291 [
292 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
293 'table' => 'civicrm_case_activity',
294 'when' => 'AFTER',
295 'event' => ['INSERT'],
296 'sql' => "\nUPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.case_id;\n",
297 ],
298 [
299 'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
300 'table' => 'civicrm_activity',
301 'when' => 'BEFORE',
302 'event' => ['UPDATE', 'DELETE'],
303 '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",
304 ],
305 ],
306 ]
307 ))
308 ->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'])->setPublic(TRUE);
309
310 $container->setDefinition('civi_token_compat', new Definition(
311 'Civi\Token\TokenCompatSubscriber',
312 []
313 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
314 $container->setDefinition("crm_mailing_action_tokens", new Definition(
315 "CRM_Mailing_ActionTokens",
316 []
317 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
318
319 foreach (['Activity', 'Contribute', 'Event', 'Mailing', 'Member'] as $comp) {
320 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
321 "CRM_{$comp}_Tokens",
322 []
323 ))->addTag('kernel.event_subscriber')->setPublic(TRUE);
324 }
325
326 \CRM_Api4_Services::hook_container($container);
327
328 \CRM_Utils_Hook::container($container);
329
330 return $container;
331 }
332
333 /**
334 * @return \Civi\Angular\Manager
335 */
336 public function createAngularManager() {
337 return new \Civi\Angular\Manager(\CRM_Core_Resources::singleton());
338 }
339
340 /**
341 * @return \Symfony\Component\EventDispatcher\EventDispatcher
342 */
343 public function createEventDispatcher() {
344 // Continue building on the original dispatcher created during bootstrap.
345 $dispatcher = static::getBootService('dispatcher.boot');
346
347 $dispatcher->addListener('civi.core.install', ['\Civi\Core\InstallationCanary', 'check']);
348 $dispatcher->addListener('civi.core.install', ['\Civi\Core\DatabaseInitializer', 'initialize']);
349 $dispatcher->addListener('civi.core.install', ['\Civi\Core\LocalizationInitializer', 'initialize']);
350 $dispatcher->addListener('hook_civicrm_post', ['\CRM_Core_Transaction', 'addPostCommit'], -1000);
351 $dispatcher->addListener('hook_civicrm_pre', ['\Civi\Core\Event\PreEvent', 'dispatchSubevent'], 100);
352 $dispatcher->addListener('civi.dao.preDelete', ['\CRM_Core_BAO_EntityTag', 'preDeleteOtherEntity']);
353 $dispatcher->addListener('hook_civicrm_post', ['\Civi\Core\Event\PostEvent', 'dispatchSubevent'], 100);
354 $dispatcher->addListener('hook_civicrm_post::Activity', ['\Civi\CCase\Events', 'fireCaseChange']);
355 $dispatcher->addListener('hook_civicrm_post::Case', ['\Civi\CCase\Events', 'fireCaseChange']);
356 $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\Events', 'delegateToXmlListeners']);
357 $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\SequenceListener', 'onCaseChange_static']);
358 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\CiviEventInspector', 'findBuiltInEvents']);
359 // TODO We need a better code-convention for metadata about non-hook events.
360 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\API\Events', 'hookEventDefs']);
361 $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs']);
362 $dispatcher->addListener('hook_civicrm_buildAsset', ['\Civi\Angular\Page\Modules', 'buildAngularModules']);
363 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetJs']);
364 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetCss']);
365 $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Core_Resources', 'renderMenubarStylesheet']);
366 $dispatcher->addListener('hook_civicrm_coreResourceList', ['\CRM_Utils_System', 'appendCoreResources']);
367 $dispatcher->addListener('hook_civicrm_getAssetUrl', ['\CRM_Utils_System', 'alterAssetUrl']);
368 $dispatcher->addListener('hook_civicrm_alterExternUrl', ['\CRM_Utils_System', 'migrateExternUrl'], 1000);
369 $dispatcher->addListener('hook_civicrm_permissionList', ['CRM_Core_Permission_List', 'findConstPermissions'], 975);
370 $dispatcher->addListener('hook_civicrm_permissionList', ['CRM_Core_Permission_List', 'findCiviPermissions'], 950);
371 $dispatcher->addListener('hook_civicrm_permissionList', ['CRM_Core_Permission_List', 'findCmsPermissions'], 925);
372
373 $dispatcher->addListener('hook_civicrm_triggerInfo', ['\CRM_Contact_BAO_RelationshipCache', 'onHookTriggerInfo']);
374 $dispatcher->addListener('civi.dao.postInsert', ['\CRM_Core_BAO_RecurringEntity', 'triggerInsert']);
375 $dispatcher->addListener('civi.dao.postUpdate', ['\CRM_Core_BAO_RecurringEntity', 'triggerUpdate']);
376 $dispatcher->addListener('civi.dao.postDelete', ['\CRM_Core_BAO_RecurringEntity', 'triggerDelete']);
377 $dispatcher->addListener('hook_civicrm_postSave_civicrm_domain', ['\CRM_Core_BAO_Domain', 'onPostSave']);
378 $dispatcher->addListener('hook_civicrm_unhandled_exception', [
379 'CRM_Core_LegacyErrorHandler',
380 'handleException',
381 ], -200);
382 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Activity_ActionMapping', 'onRegisterActionMappings']);
383 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Contact_ActionMapping', 'onRegisterActionMappings']);
384 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings']);
385 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings']);
386 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Event_ActionMapping', 'onRegisterActionMappings']);
387 $dispatcher->addListener('civi.actionSchedule.getMappings', ['CRM_Member_ActionMapping', 'onRegisterActionMappings']);
388
389 return $dispatcher;
390 }
391
392 /**
393 * @return \Civi\Core\Lock\LockManager
394 */
395 public static function createLockManager() {
396 // Ideally, downstream implementers could override any definitions in
397 // the container. For now, we'll make-do with some define()s.
398 $lm = new LockManager();
399 $lm
400 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : ['CRM_Core_Lock', 'createScopedLock'])
401 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : ['CRM_Core_Lock', 'createScopedLock'])
402 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : ['CRM_Core_Lock', 'createCivimailLock'])
403 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : ['CRM_Core_Lock', 'createScopedLock']);
404
405 // Registrations may use complex resolver expressions, but (as a micro-optimization)
406 // the default factory is specified as an array.
407
408 return $lm;
409 }
410
411 /**
412 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
413 * @param $magicFunctionProvider
414 *
415 * @return \Civi\API\Kernel
416 */
417 public function createApiKernel($dispatcher, $magicFunctionProvider) {
418 $dispatcher->addSubscriber(new \Civi\API\Subscriber\ChainSubscriber());
419 $dispatcher->addSubscriber(new \Civi\API\Subscriber\TransactionSubscriber());
420 $dispatcher->addSubscriber(new \Civi\API\Subscriber\I18nSubscriber());
421 $dispatcher->addSubscriber($magicFunctionProvider);
422 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
423 $dispatcher->addSubscriber(new \Civi\API\Subscriber\APIv3SchemaAdapter());
424 $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter([
425 \CRM_Utils_API_HTMLInputCoder::singleton(),
426 \CRM_Utils_API_NullOutputCoder::singleton(),
427 \CRM_Utils_API_ReloadOption::singleton(),
428 \CRM_Utils_API_MatchOption::singleton(),
429 ]));
430 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DebugSubscriber());
431 $kernel = new \Civi\API\Kernel($dispatcher);
432
433 $reflectionProvider = new \Civi\API\Provider\ReflectionProvider($kernel);
434 $dispatcher->addSubscriber($reflectionProvider);
435
436 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DynamicFKAuthorization(
437 $kernel,
438 'Attachment',
439 ['create', 'get', 'delete'],
440 // Given a file ID, determine the entity+table it's attached to.
441 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
442 FROM civicrm_file cf
443 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
444 WHERE cf.id = %1',
445 // Get a list of custom fields (field_name,table_name,extends)
446 'SELECT concat("custom_",fld.id) as field_name,
447 grp.table_name as table_name,
448 grp.extends as extends
449 FROM civicrm_custom_field fld
450 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
451 WHERE fld.data_type = "File"
452 '
453 ));
454
455 $kernel->setApiProviders([
456 $reflectionProvider,
457 $magicFunctionProvider,
458 ]);
459
460 return $kernel;
461 }
462
463 /**
464 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
465 * @return \CRM_Core_Resources
466 */
467 public static function createResources($container) {
468 $sys = \CRM_Extension_System::singleton();
469 return new \CRM_Core_Resources(
470 $sys->getMapper(),
471 new \CRM_Core_Resources_Strings($container->get('cache.js_strings')),
472 \CRM_Core_Config::isUpgradeMode() ? NULL : 'resCacheCode'
473 );
474 }
475
476 /**
477 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
478 * @return \CRM_Core_PrevNextCache_Interface
479 */
480 public static function createPrevNextCache($container) {
481 $setting = \Civi::settings()->get('prevNextBackend');
482 if (!$setting || $setting === 'default') {
483 $cacheDriver = \CRM_Utils_Cache::getCacheDriver();
484 $service = 'prevnext.driver.' . strtolower($cacheDriver);
485 return $container->has($service)
486 ? $container->get($service)
487 : $container->get('prevnext.driver.sql');
488 }
489 return $container->get('prevnext.driver.' . $setting);
490 }
491
492 /**
493 * @return \ArrayObject
494 */
495 public static function createCacheConfig() {
496 $driver = \CRM_Utils_Cache::getCacheDriver();
497 $settings = \CRM_Utils_Cache::getCacheSettings($driver);
498 $settings['driver'] = $driver;
499 return new \ArrayObject($settings);
500 }
501
502 /**
503 * Get a list of boot services.
504 *
505 * These are services which must be setup *before* the container can operate.
506 *
507 * @param bool $loadFromDB
508 * @throws \CRM_Core_Exception
509 */
510 public static function boot($loadFromDB) {
511 // Array(string $serviceId => object $serviceInstance).
512 $bootServices = [];
513 \Civi::$statics[__CLASS__]['boot'] = &$bootServices;
514
515 $bootServices['runtime'] = $runtime = new \CRM_Core_Config_Runtime();
516 $runtime->initialize($loadFromDB);
517
518 $bootServices['paths'] = new \Civi\Core\Paths();
519
520 $bootServices['dispatcher.boot'] = new CiviEventDispatcher();
521
522 // Quality control: There should be no pre-boot hooks because they make it harder to understand/support/refactor.
523 // If a pre-boot hook sneaks in, we'll raise an error.
524 $bootDispatchPolicy = [
525 '/^hook_/' => 'not-ready',
526 '/^civi\./' => 'run',
527 ];
528 $mainDispatchPolicy = \CRM_Core_Config::isUpgradeMode() ? \CRM_Upgrade_DispatchPolicy::get('upgrade.main') : NULL;
529 $bootServices['dispatcher.boot']->setDispatchPolicy($bootDispatchPolicy);
530
531 $class = $runtime->userFrameworkClass;
532 $bootServices['userSystem'] = $userSystem = new $class();
533 $userSystem->initialize();
534
535 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework;
536 $bootServices['userPermissionClass'] = new $userPermissionClass();
537
538 $bootServices['cache.settings'] = \CRM_Utils_Cache::create([
539 'name' => 'settings',
540 'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
541 ]);
542
543 $bootServices['settings_manager'] = new \Civi\Core\SettingsManager($bootServices['cache.settings']);
544
545 $bootServices['lockManager'] = self::createLockManager();
546
547 if ($loadFromDB && $runtime->dsn) {
548 \CRM_Core_DAO::init($runtime->dsn);
549 \CRM_Utils_Hook::singleton(TRUE);
550 \CRM_Extension_System::singleton(TRUE);
551 \CRM_Extension_System::singleton(TRUE)->getClassLoader()->register();
552 $bootServices['dispatcher.boot']->setDispatchPolicy($mainDispatchPolicy);
553
554 $runtime->includeCustomPath();
555
556 $c = new self();
557 $container = $c->loadContainer();
558 foreach ($bootServices as $name => $obj) {
559 $container->set($name, $obj);
560 }
561 \Civi::$statics[__CLASS__]['container'] = $container;
562 }
563 else {
564 $bootServices['dispatcher.boot']->setDispatchPolicy($mainDispatchPolicy);
565 }
566 }
567
568 /**
569 * @param string $name
570 *
571 * @return mixed
572 */
573 public static function getBootService($name) {
574 return \Civi::$statics[__CLASS__]['boot'][$name];
575 }
576
577 /**
578 * Determine whether the container services are available.
579 *
580 * @return bool
581 */
582 public static function isContainerBooted() {
583 return isset(\Civi::$statics[__CLASS__]['container']);
584 }
585
586 }