4 use Civi\API\Provider\ActionObjectProvider
;
5 use Civi\Core\Event\SystemInstallEvent
;
6 use Civi\Core\Lock\LockManager
;
7 use Doctrine\Common\Annotations\AnnotationReader
;
8 use Doctrine\Common\Annotations\AnnotationRegistry
;
9 use Doctrine\Common\Annotations\FileCacheReader
;
10 use Doctrine\Common\Cache\FilesystemCache
;
11 use Doctrine\ORM\EntityManager
;
12 use Doctrine\ORM\Mapping\Driver\AnnotationDriver
;
13 use Doctrine\ORM\Tools\Setup
;
14 use Symfony\Component\Config\ConfigCache
;
15 use Symfony\Component\DependencyInjection\ContainerBuilder
;
16 use Symfony\Component\DependencyInjection\ContainerInterface
;
17 use Symfony\Component\DependencyInjection\Definition
;
18 use Symfony\Component\DependencyInjection\Dumper\PhpDumper
;
19 use Symfony\Component\DependencyInjection\Reference
;
20 use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
;
21 use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass
;
23 // TODO use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
31 const SELF
= 'civi_container_factory';
35 * Whether to forcibly rebuild the entire container.
36 * @return \Symfony\Component\DependencyInjection\TaggedContainerInterface
38 public static function singleton($reset = FALSE) {
39 if ($reset ||
!isset(\Civi
::$statics[__CLASS__
]['container'])) {
42 return \Civi
::$statics[__CLASS__
]['container'];
46 * Find a cached container definition or construct a new one.
48 * There are many weird contexts in which Civi initializes (eg different
49 * variations of multitenancy and different permutations of CMS/CRM bootstrap),
50 * and hook_container may fire a bit differently in each context. To mitigate
51 * risk of leaks between environments, we compute a unique envID
52 * (md5(DB_NAME, HTTP_HOST, SCRIPT_FILENAME, etc)) and use separate caches for
53 * each (eg "templates_c/CachedCiviContainer.$ENVID.php").
56 * - CIVICRM_CONTAINER_CACHE -- 'always' [default], 'never', 'auto'
59 * - CIVICRM_TEMPLATE_COMPILEDIR
61 * @return ContainerInterface
63 public function loadContainer() {
64 // Note: The container's raison d'etre is to manage construction of other
65 // services. Consequently, we assume a minimal service available -- the classloader
66 // has been setup, and civicrm.settings.php is loaded, but nothing else works.
68 $cacheMode = defined('CIVICRM_CONTAINER_CACHE') ? CIVICRM_CONTAINER_CACHE
: 'always';
70 // In pre-installation environments, don't bother with caching.
71 if (!defined('CIVICRM_TEMPLATE_COMPILEDIR') ||
!defined('CIVICRM_DSN') ||
$cacheMode === 'never' || \CRM_Utils_System
::isInUpgradeMode()) {
72 $containerBuilder = $this->createContainer();
73 $containerBuilder->compile();
74 return $containerBuilder;
77 $envId = \CRM_Core_Config_Runtime
::getId();
78 $file = CIVICRM_TEMPLATE_COMPILEDIR
. "/CachedCiviContainer.{$envId}.php";
79 $containerConfigCache = new ConfigCache($file, $cacheMode === 'auto');
80 if (!$containerConfigCache->isFresh()) {
81 $containerBuilder = $this->createContainer();
82 $containerBuilder->compile();
83 $dumper = new PhpDumper($containerBuilder);
84 $containerConfigCache->write(
85 $dumper->dump(array('class' => 'CachedCiviContainer')),
86 $containerBuilder->getResources()
91 $c = new \
CachedCiviContainer();
92 $c->set('service_container', $c);
97 * Construct a new container.
99 * @var ContainerBuilder
100 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
102 public function createContainer() {
103 $civicrm_base_path = dirname(dirname(__DIR__
));
104 $container = new ContainerBuilder();
105 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
106 $container->addObjectResource($this);
107 $container->setParameter('civicrm_base_path', $civicrm_base_path);
108 //$container->set(self::SELF, $this);
110 $container->addResource(new \Symfony\Component\Config\
Resource\
FileResource(__FILE__
));
112 $container->setDefinition(self
::SELF
, new Definition(
113 'Civi\Core\Container',
117 // TODO Move configuration to an external file; define caching structure
118 // if (empty($configDirectories)) {
119 // throw new \Exception(__CLASS__ . ': Missing required properties (civicrmRoot, configDirectories)');
121 // $locator = new FileLocator($configDirectories);
122 // $loaderResolver = new LoaderResolver(array(
123 // new YamlFileLoader($container, $locator)
125 // $delegatingLoader = new DelegatingLoader($loaderResolver);
126 // foreach (array('services.yml') as $file) {
127 // $yamlUserFiles = $locator->locate($file, NULL, FALSE);
128 // foreach ($yamlUserFiles as $file) {
129 // $delegatingLoader->load($file);
133 $container->setDefinition('angular', new Definition(
134 'Civi\Angular\Manager',
137 ->setFactoryService(self
::SELF
)->setFactoryMethod('createAngularManager');
139 $container->setDefinition('dispatcher', new Definition(
140 'Civi\Core\CiviEventDispatcher',
141 array(new Reference('service_container'))
143 ->setFactoryService(self
::SELF
)->setFactoryMethod('createEventDispatcher');
145 $container->setDefinition('magic_function_provider', new Definition(
146 'Civi\API\Provider\MagicFunctionProvider',
150 $container->setDefinition('civi_api_kernel', new Definition(
152 array(new Reference('dispatcher'), new Reference('magic_function_provider'))
154 ->setFactoryService(self
::SELF
)->setFactoryMethod('createApiKernel');
156 $container->setDefinition('cxn_reg_client', new Definition(
157 'Civi\Cxn\Rpc\RegistrationClient',
160 ->setFactoryClass('CRM_Cxn_BAO_Cxn')->setFactoryMethod('createRegistrationClient');
162 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', array()));
164 foreach (array('js_strings', 'community_messages') as $cacheName) {
165 $container->setDefinition("cache.{$cacheName}", new Definition(
166 'CRM_Utils_Cache_Interface',
169 'name' => $cacheName,
170 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
173 ))->setFactoryClass('CRM_Utils_Cache')->setFactoryMethod('create');
176 $container->setDefinition('sql_triggers', new Definition(
177 'Civi\Core\SqlTriggers',
181 $container->setDefinition('asset_builder', new Definition(
182 'Civi\Core\AssetBuilder',
186 $container->setDefinition('pear_mail', new Definition('Mail'))
187 ->setFactoryClass('CRM_Utils_Mail')->setFactoryMethod('createMailer');
189 if (empty(\Civi
::$statics[__CLASS__
]['boot'])) {
190 throw new \
RuntimeException("Cannot initialize container. Boot services are undefined.");
192 foreach (\Civi
::$statics[__CLASS__
]['boot'] as $bootService => $def) {
193 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE);
196 // Expose legacy singletons as services in the container.
198 'resources' => 'CRM_Core_Resources',
199 'httpClient' => 'CRM_Utils_HttpClient',
200 'cache.default' => 'CRM_Utils_Cache',
201 'i18n' => 'CRM_Core_I18n',
202 // Maybe? 'config' => 'CRM_Core_Config',
203 // Maybe? 'smarty' => 'CRM_Core_Smarty',
205 foreach ($singletons as $name => $class) {
206 $container->setDefinition($name, new Definition(
209 ->setFactoryClass($class)->setFactoryMethod('singleton');
212 $container->setDefinition('civi_token_compat', new Definition(
213 'Civi\Token\TokenCompatSubscriber',
215 ))->addTag('kernel.event_subscriber');
216 $container->setDefinition("crm_mailing_action_tokens", new Definition(
217 "CRM_Mailing_ActionTokens",
219 ))->addTag('kernel.event_subscriber');
221 foreach (array('Activity', 'Contribute', 'Event', 'Mailing', 'Member') as $comp) {
222 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
223 "CRM_{$comp}_Tokens",
225 ))->addTag('kernel.event_subscriber');
228 if (\CRM_Utils_Constant
::value('CIVICRM_FLEXMAILER_HACK_SERVICES')) {
229 \Civi\Core\Resolver
::singleton()->call(CIVICRM_FLEXMAILER_HACK_SERVICES
, array($container));
232 \CRM_Utils_Hook
::container($container);
238 * @return \Civi\Angular\Manager
240 public function createAngularManager() {
241 return new \Civi\Angular\
Manager(\CRM_Core_Resources
::singleton());
245 * @param ContainerInterface $container
246 * @return \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
248 public function createEventDispatcher($container) {
249 $dispatcher = new CiviEventDispatcher($container);
250 $dispatcher->addListener(SystemInstallEvent
::EVENT_NAME
, array('\Civi\Core\InstallationCanary', 'check'));
251 $dispatcher->addListener(SystemInstallEvent
::EVENT_NAME
, array('\Civi\Core\DatabaseInitializer', 'initialize'));
252 $dispatcher->addListener(SystemInstallEvent
::EVENT_NAME
, array('\Civi\Core\LocalizationInitializer', 'initialize'));
253 $dispatcher->addListener('hook_civicrm_pre', array('\Civi\Core\Event\PreEvent', 'dispatchSubevent'), 100);
254 $dispatcher->addListener('hook_civicrm_post', array('\Civi\Core\Event\PostEvent', 'dispatchSubevent'), 100);
255 $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
256 $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
257 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
258 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
259 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\Core\CiviEventInspector', 'findBuiltInEvents'));
260 // TODO We need a better code-convention for metadata about non-hook events.
261 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\API\Events', 'hookEventDefs'));
262 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs'));
263 $dispatcher->addListener('hook_civicrm_buildAsset', array('\Civi\Angular\Page\Modules', 'buildAngularModules'));
264 $dispatcher->addListener('civi.dao.postInsert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
265 $dispatcher->addListener('civi.dao.postUpdate', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
266 $dispatcher->addListener('civi.dao.postDelete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
267 $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
268 'CRM_Core_LegacyErrorHandler',
271 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Activity_ActionMapping', 'onRegisterActionMappings'));
272 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Contact_ActionMapping', 'onRegisterActionMappings'));
273 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings'));
274 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings'));
275 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Event_ActionMapping', 'onRegisterActionMappings'));
276 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Member_ActionMapping', 'onRegisterActionMappings'));
278 if (\CRM_Utils_Constant
::value('CIVICRM_FLEXMAILER_HACK_LISTENERS')) {
279 \Civi\Core\Resolver
::singleton()->call(CIVICRM_FLEXMAILER_HACK_LISTENERS
, array($dispatcher));
286 * @return LockManager
288 public static function createLockManager() {
289 // Ideally, downstream implementers could override any definitions in
290 // the container. For now, we'll make-do with some define()s.
291 $lm = new LockManager();
293 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK
: array('CRM_Core_Lock', 'createScopedLock'))
294 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK
: array('CRM_Core_Lock', 'createScopedLock'))
295 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: array('CRM_Core_Lock', 'createCivimailLock'))
296 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: array('CRM_Core_Lock', 'createScopedLock'));
298 // Registrations may use complex resolver expressions, but (as a micro-optimization)
299 // the default factory is specified as an array.
305 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
306 * @param $magicFunctionProvider
308 * @return \Civi\API\Kernel
310 public function createApiKernel($dispatcher, $magicFunctionProvider) {
311 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
ChainSubscriber());
312 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
TransactionSubscriber());
313 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
I18nSubscriber());
314 $dispatcher->addSubscriber($magicFunctionProvider);
315 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
PermissionCheck());
316 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
APIv3SchemaAdapter());
317 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
WrapperAdapter(array(
318 \CRM_Utils_API_HTMLInputCoder
::singleton(),
319 \CRM_Utils_API_NullOutputCoder
::singleton(),
320 \CRM_Utils_API_ReloadOption
::singleton(),
321 \CRM_Utils_API_MatchOption
::singleton(),
323 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
XDebugSubscriber());
324 $kernel = new \Civi\API\
Kernel($dispatcher);
326 $reflectionProvider = new \Civi\API\Provider\
ReflectionProvider($kernel);
327 $dispatcher->addSubscriber($reflectionProvider);
329 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
DynamicFKAuthorization(
332 array('create', 'get', 'delete'),
333 // Given a file ID, determine the entity+table it's attached to.
334 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
336 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
338 // Get a list of custom fields (field_name,table_name,extends)
339 'SELECT concat("custom_",fld.id) as field_name,
340 grp.table_name as table_name,
341 grp.extends as extends
342 FROM civicrm_custom_field fld
343 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
344 WHERE fld.data_type = "File"
346 array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
349 $kernel->setApiProviders(array(
351 $magicFunctionProvider,
358 * Get a list of boot services.
360 * These are services which must be setup *before* the container can operate.
362 * @param bool $loadFromDB
363 * @throws \CRM_Core_Exception
365 public static function boot($loadFromDB) {
366 // Array(string $serviceId => object $serviceInstance).
367 $bootServices = array();
368 \Civi
::$statics[__CLASS__
]['boot'] = &$bootServices;
370 $bootServices['runtime'] = $runtime = new \
CRM_Core_Config_Runtime();
371 $runtime->initialize($loadFromDB);
373 $bootServices['paths'] = new \Civi\Core\
Paths();
375 $class = $runtime->userFrameworkClass
;
376 $bootServices['userSystem'] = $userSystem = new $class();
377 $userSystem->initialize();
379 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework
;
380 $bootServices['userPermissionClass'] = new $userPermissionClass();
382 $bootServices['cache.settings'] = \CRM_Utils_Cache
::create(array(
383 'name' => 'settings',
384 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
387 $bootServices['settings_manager'] = new \Civi\Core\
SettingsManager($bootServices['cache.settings']);
389 $bootServices['lockManager'] = self
::createLockManager();
391 if ($loadFromDB && $runtime->dsn
) {
392 \CRM_Core_DAO
::init($runtime->dsn
);
393 \CRM_Utils_Hook
::singleton(TRUE);
394 \CRM_Extension_System
::singleton(TRUE);
395 \CRM_Extension_System
::singleton(TRUE)->getClassLoader()->register();
397 $runtime->includeCustomPath();
400 $container = $c->loadContainer();
401 foreach ($bootServices as $name => $obj) {
402 $container->set($name, $obj);
404 \Civi
::$statics[__CLASS__
]['container'] = $container;
408 public static function getBootService($name) {
409 return \Civi
::$statics[__CLASS__
]['boot'][$name];
413 * Determine whether the container services are available.
417 public static function isContainerBooted() {
418 return isset(\Civi
::$statics[__CLASS__
]['container']);