4 use Civi\Core\Event\SystemInstallEvent
;
5 use Civi\Core\Lock\LockManager
;
6 use Doctrine\Common\Annotations\AnnotationReader
;
7 use Doctrine\Common\Annotations\AnnotationRegistry
;
8 use Doctrine\Common\Annotations\FileCacheReader
;
9 use Doctrine\Common\Cache\FilesystemCache
;
10 use Doctrine\ORM\EntityManager
;
11 use Doctrine\ORM\Mapping\Driver\AnnotationDriver
;
12 use Doctrine\ORM\Tools\Setup
;
13 use Symfony\Component\Config\ConfigCache
;
14 use Symfony\Component\DependencyInjection\ContainerBuilder
;
15 use Symfony\Component\DependencyInjection\ContainerInterface
;
16 use Symfony\Component\DependencyInjection\Definition
;
17 use Symfony\Component\DependencyInjection\Dumper\PhpDumper
;
18 use Symfony\Component\DependencyInjection\Reference
;
19 use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
;
20 use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass
;
22 // TODO use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
30 const SELF
= 'civi_container_factory';
34 * Whether to forcibly rebuild the entire container.
35 * @return \Symfony\Component\DependencyInjection\TaggedContainerInterface
37 public static function singleton($reset = FALSE) {
38 if ($reset ||
!isset(\Civi
::$statics[__CLASS__
]['container'])) {
41 return \Civi
::$statics[__CLASS__
]['container'];
45 * Find a cached container definition or construct a new one.
47 * There are many weird contexts in which Civi initializes (eg different
48 * variations of multitenancy and different permutations of CMS/CRM bootstrap),
49 * and hook_container may fire a bit differently in each context. To mitigate
50 * risk of leaks between environments, we compute a unique envID
51 * (md5(DB_NAME, HTTP_HOST, SCRIPT_FILENAME, etc)) and use separate caches for
52 * each (eg "templates_c/CachedCiviContainer.$ENVID.php").
55 * - CIVICRM_CONTAINER_CACHE -- 'always' [default], 'never', 'auto'
58 * - CIVICRM_TEMPLATE_COMPILEDIR
60 * @return ContainerInterface
62 public function loadContainer() {
63 // Note: The container's raison d'etre is to manage construction of other
64 // services. Consequently, we assume a minimal service available -- the classloader
65 // has been setup, and civicrm.settings.php is loaded, but nothing else works.
67 $cacheMode = defined('CIVICRM_CONTAINER_CACHE') ? CIVICRM_CONTAINER_CACHE
: 'always';
69 // In pre-installation environments, don't bother with caching.
70 if (!defined('CIVICRM_TEMPLATE_COMPILEDIR') ||
!defined('CIVICRM_DSN') ||
$cacheMode === 'never' || \CRM_Utils_System
::isInUpgradeMode()) {
71 return $this->createContainer();
74 $envId = \CRM_Core_Config_Runtime
::getId();
75 $file = CIVICRM_TEMPLATE_COMPILEDIR
. "/CachedCiviContainer.{$envId}.php";
76 $containerConfigCache = new ConfigCache($file, $cacheMode === 'auto');
77 if (!$containerConfigCache->isFresh()) {
78 $containerBuilder = $this->createContainer();
79 $containerBuilder->compile();
80 $dumper = new PhpDumper($containerBuilder);
81 $containerConfigCache->write(
82 $dumper->dump(array('class' => 'CachedCiviContainer')),
83 $containerBuilder->getResources()
88 $c = new \
CachedCiviContainer();
89 $c->set('service_container', $c);
94 * Construct a new container.
96 * @var ContainerBuilder
97 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
99 public function createContainer() {
100 $civicrm_base_path = dirname(dirname(__DIR__
));
101 $container = new ContainerBuilder();
102 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
103 $container->addObjectResource($this);
104 $container->setParameter('civicrm_base_path', $civicrm_base_path);
105 //$container->set(self::SELF, $this);
106 $container->setDefinition(self
::SELF
, new Definition(
107 'Civi\Core\Container',
111 // TODO Move configuration to an external file; define caching structure
112 // if (empty($configDirectories)) {
113 // throw new \Exception(__CLASS__ . ': Missing required properties (civicrmRoot, configDirectories)');
115 // $locator = new FileLocator($configDirectories);
116 // $loaderResolver = new LoaderResolver(array(
117 // new YamlFileLoader($container, $locator)
119 // $delegatingLoader = new DelegatingLoader($loaderResolver);
120 // foreach (array('services.yml') as $file) {
121 // $yamlUserFiles = $locator->locate($file, NULL, FALSE);
122 // foreach ($yamlUserFiles as $file) {
123 // $delegatingLoader->load($file);
127 $container->setDefinition('angular', new Definition(
128 'Civi\Angular\Manager',
131 ->setFactoryService(self
::SELF
)->setFactoryMethod('createAngularManager');
133 $container->setDefinition('dispatcher', new Definition(
134 'Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher',
135 array(new Reference('service_container'))
137 ->setFactoryService(self
::SELF
)->setFactoryMethod('createEventDispatcher');
139 $container->setDefinition('magic_function_provider', new Definition(
140 'Civi\API\Provider\MagicFunctionProvider',
144 $container->setDefinition('civi_api_kernel', new Definition(
146 array(new Reference('dispatcher'), new Reference('magic_function_provider'))
148 ->setFactoryService(self
::SELF
)->setFactoryMethod('createApiKernel');
150 $container->setDefinition('cxn_reg_client', new Definition(
151 'Civi\Cxn\Rpc\RegistrationClient',
154 ->setFactoryClass('CRM_Cxn_BAO_Cxn')->setFactoryMethod('createRegistrationClient');
156 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', array()));
158 foreach (array('js_strings', 'community_messages') as $cacheName) {
159 $container->setDefinition("cache.{$cacheName}", new Definition(
160 'CRM_Utils_Cache_Interface',
163 'name' => $cacheName,
164 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
167 ))->setFactoryClass('CRM_Utils_Cache')->setFactoryMethod('create');
170 $container->setDefinition('pear_mail', new Definition('Mail'))
171 ->setFactoryClass('CRM_Utils_Mail')->setFactoryMethod('createMailer');
173 if (empty(\Civi
::$statics[__CLASS__
]['boot'])) {
174 throw new \
RuntimeException("Cannot initialize container. Boot services are undefined.");
176 foreach (\Civi
::$statics[__CLASS__
]['boot'] as $bootService => $def) {
177 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE);
180 // Expose legacy singletons as services in the container.
182 'resources' => 'CRM_Core_Resources',
183 'httpClient' => 'CRM_Utils_HttpClient',
184 'cache.default' => 'CRM_Utils_Cache',
185 'i18n' => 'CRM_Core_I18n',
186 // Maybe? 'config' => 'CRM_Core_Config',
187 // Maybe? 'smarty' => 'CRM_Core_Smarty',
189 foreach ($singletons as $name => $class) {
190 $container->setDefinition($name, new Definition(
193 ->setFactoryClass($class)->setFactoryMethod('singleton');
196 $container->setDefinition('civi_token_compat', new Definition(
197 'Civi\Token\TokenCompatSubscriber',
199 ))->addTag('kernel.event_subscriber');
201 foreach (array('Activity', 'Contribute', 'Event', 'Member') as $comp) {
202 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
203 "CRM_{$comp}_Tokens",
205 ))->addTag('kernel.event_subscriber');
208 \CRM_Utils_Hook
::container($container);
214 * @return \Civi\Angular\Manager
216 public function createAngularManager() {
217 return new \Civi\Angular\
Manager(\CRM_Core_Resources
::singleton());
221 * @param ContainerInterface $container
222 * @return \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
224 public function createEventDispatcher($container) {
225 $dispatcher = new ContainerAwareEventDispatcher($container);
226 $dispatcher->addListener(SystemInstallEvent
::EVENT_NAME
, array('\Civi\Core\InstallationCanary', 'check'));
227 $dispatcher->addListener(SystemInstallEvent
::EVENT_NAME
, array('\Civi\Core\DatabaseInitializer', 'initialize'));
228 $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
229 $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
230 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
231 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
232 $dispatcher->addListener('DAO::post-insert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
233 $dispatcher->addListener('DAO::post-update', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
234 $dispatcher->addListener('DAO::post-delete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
235 $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
236 'CRM_Core_LegacyErrorHandler',
239 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Activity_ActionMapping', 'onRegisterActionMappings'));
240 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Contact_ActionMapping', 'onRegisterActionMappings'));
241 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings'));
242 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings'));
243 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Event_ActionMapping', 'onRegisterActionMappings'));
244 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Member_ActionMapping', 'onRegisterActionMappings'));
250 * @return LockManager
252 public static function createLockManager() {
253 // Ideally, downstream implementers could override any definitions in
254 // the container. For now, we'll make-do with some define()s.
255 $lm = new LockManager();
257 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK
: array('CRM_Core_Lock', 'createScopedLock'))
258 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK
: array('CRM_Core_Lock', 'createScopedLock'))
259 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: array('CRM_Core_Lock', 'createCivimailLock'))
260 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: array('CRM_Core_Lock', 'createScopedLock'));
262 // Registrations may use complex resolver expressions, but (as a micro-optimization)
263 // the default factory is specified as an array.
269 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
270 * @param $magicFunctionProvider
272 * @return \Civi\API\Kernel
274 public function createApiKernel($dispatcher, $magicFunctionProvider) {
275 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
ChainSubscriber());
276 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
TransactionSubscriber());
277 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
I18nSubscriber());
278 $dispatcher->addSubscriber($magicFunctionProvider);
279 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
PermissionCheck());
280 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
APIv3SchemaAdapter());
281 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
WrapperAdapter(array(
282 \CRM_Utils_API_HTMLInputCoder
::singleton(),
283 \CRM_Utils_API_NullOutputCoder
::singleton(),
284 \CRM_Utils_API_ReloadOption
::singleton(),
285 \CRM_Utils_API_MatchOption
::singleton(),
287 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
XDebugSubscriber());
288 $kernel = new \Civi\API\
Kernel($dispatcher);
290 $reflectionProvider = new \Civi\API\Provider\
ReflectionProvider($kernel);
291 $dispatcher->addSubscriber($reflectionProvider);
293 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
DynamicFKAuthorization(
296 array('create', 'get', 'delete'),
297 // Given a file ID, determine the entity+table it's attached to.
298 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
300 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
302 // Get a list of custom fields (field_name,table_name,extends)
303 'SELECT concat("custom_",fld.id) as field_name,
304 grp.table_name as table_name,
305 grp.extends as extends
306 FROM civicrm_custom_field fld
307 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
308 WHERE fld.data_type = "File"
310 array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
313 $kernel->setApiProviders(array(
315 $magicFunctionProvider,
322 * Get a list of boot services.
324 * These are services which must be setup *before* the container can operate.
326 * @param bool $loadFromDB
327 * @throws \CRM_Core_Exception
329 public static function boot($loadFromDB) {
330 // Array(string $serviceId => object $serviceInstance).
331 $bootServices = array();
332 \Civi
::$statics[__CLASS__
]['boot'] = &$bootServices;
334 $bootServices['runtime'] = $runtime = new \
CRM_Core_Config_Runtime();
335 $runtime->initialize($loadFromDB);
337 $bootServices['paths'] = new \Civi\Core\
Paths();
339 $class = $runtime->userFrameworkClass
;
340 $bootServices['userSystem'] = $userSystem = new $class();
341 $userSystem->initialize();
343 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework
;
344 $bootServices['userPermissionClass'] = new $userPermissionClass();
346 $bootServices['cache.settings'] = \CRM_Utils_Cache
::create(array(
347 'name' => 'settings',
348 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
351 $bootServices['settings_manager'] = new \Civi\Core\
SettingsManager($bootServices['cache.settings']);
353 $bootServices['lockManager'] = self
::createLockManager();
355 if ($loadFromDB && $runtime->dsn
) {
356 \CRM_Core_DAO
::init($runtime->dsn
);
357 \CRM_Utils_Hook
::singleton(TRUE);
358 \CRM_Extension_System
::singleton(TRUE);
359 \CRM_Extension_System
::singleton(TRUE)->getClassLoader()->register();
361 $runtime->includeCustomPath();
364 $container = $c->loadContainer();
365 foreach ($bootServices as $name => $obj) {
366 $container->set($name, $obj);
368 \Civi
::$statics[__CLASS__
]['container'] = $container;
372 public static function getBootService($name) {
373 return \Civi
::$statics[__CLASS__
]['boot'][$name];