4 use Civi\Core\Lock\LockManager
;
5 use Doctrine\Common\Annotations\AnnotationReader
;
6 use Doctrine\Common\Annotations\AnnotationRegistry
;
7 use Doctrine\Common\Annotations\FileCacheReader
;
8 use Doctrine\Common\Cache\FilesystemCache
;
9 use Doctrine\ORM\EntityManager
;
10 use Doctrine\ORM\Mapping\Driver\AnnotationDriver
;
11 use Doctrine\ORM\Tools\Setup
;
12 use Symfony\Component\Config\ConfigCache
;
13 use Symfony\Component\DependencyInjection\ContainerBuilder
;
14 use Symfony\Component\DependencyInjection\ContainerInterface
;
15 use Symfony\Component\DependencyInjection\Definition
;
16 use Symfony\Component\DependencyInjection\Dumper\PhpDumper
;
17 use Symfony\Component\DependencyInjection\Reference
;
18 use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
;
19 use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass
;
21 // TODO use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
29 const SELF
= 'civi_container_factory';
33 * Whether to forcibly rebuild the entire container.
34 * @return \Symfony\Component\DependencyInjection\TaggedContainerInterface
36 public static function singleton($reset = FALSE) {
37 if ($reset ||
!isset(\Civi
::$statics[__CLASS__
]['container'])) {
40 return \Civi
::$statics[__CLASS__
]['container'];
44 * Find a cached container definition or construct a new one.
46 * There are many weird contexts in which Civi initializes (eg different
47 * variations of multitenancy and different permutations of CMS/CRM bootstrap),
48 * and hook_container may fire a bit differently in each context. To mitigate
49 * risk of leaks between environments, we compute a unique envID
50 * (md5(DB_NAME, HTTP_HOST, SCRIPT_FILENAME, etc)) and use separate caches for
51 * each (eg "templates_c/CachedCiviContainer.$ENVID.php").
54 * - CIVICRM_CONTAINER_CACHE -- 'always' [default], 'never', 'auto'
57 * - CIVICRM_TEMPLATE_COMPILEDIR
59 * @return ContainerInterface
61 public function loadContainer() {
62 // Note: The container's raison d'etre is to manage construction of other
63 // services. Consequently, we assume a minimal service available -- the classloader
64 // has been setup, and civicrm.settings.php is loaded, but nothing else works.
66 $cacheMode = defined('CIVICRM_CONTAINER_CACHE') ? CIVICRM_CONTAINER_CACHE
: 'always';
68 // In pre-installation environments, don't bother with caching.
69 if (!defined('CIVICRM_TEMPLATE_COMPILEDIR') ||
!defined('CIVICRM_DSN') ||
$cacheMode === 'never' || \CRM_Utils_System
::isInUpgradeMode()) {
70 return $this->createContainer();
73 $envId = \CRM_Core_Config_Runtime
::getId();
74 $file = CIVICRM_TEMPLATE_COMPILEDIR
. "/CachedCiviContainer.{$envId}.php";
75 $containerConfigCache = new ConfigCache($file, $cacheMode === 'auto');
76 if (!$containerConfigCache->isFresh()) {
77 $containerBuilder = $this->createContainer();
78 $containerBuilder->compile();
79 $dumper = new PhpDumper($containerBuilder);
80 $containerConfigCache->write(
81 $dumper->dump(array('class' => 'CachedCiviContainer')),
82 $containerBuilder->getResources()
87 $c = new \
CachedCiviContainer();
88 $c->set('service_container', $c);
93 * Construct a new container.
95 * @var ContainerBuilder
96 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
98 public function createContainer() {
99 $civicrm_base_path = dirname(dirname(__DIR__
));
100 $container = new ContainerBuilder();
101 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
102 $container->addObjectResource($this);
103 $container->setParameter('civicrm_base_path', $civicrm_base_path);
104 //$container->set(self::SELF, $this);
105 $container->setDefinition(self
::SELF
, new Definition(
106 'Civi\Core\Container',
110 // TODO Move configuration to an external file; define caching structure
111 // if (empty($configDirectories)) {
112 // throw new \Exception(__CLASS__ . ': Missing required properties (civicrmRoot, configDirectories)');
114 // $locator = new FileLocator($configDirectories);
115 // $loaderResolver = new LoaderResolver(array(
116 // new YamlFileLoader($container, $locator)
118 // $delegatingLoader = new DelegatingLoader($loaderResolver);
119 // foreach (array('services.yml') as $file) {
120 // $yamlUserFiles = $locator->locate($file, NULL, FALSE);
121 // foreach ($yamlUserFiles as $file) {
122 // $delegatingLoader->load($file);
126 $container->setDefinition('angular', new Definition(
127 'Civi\Angular\Manager',
130 ->setFactoryService(self
::SELF
)->setFactoryMethod('createAngularManager');
132 $container->setDefinition('dispatcher', new Definition(
133 'Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher',
134 array(new Reference('service_container'))
136 ->setFactoryService(self
::SELF
)->setFactoryMethod('createEventDispatcher');
138 $container->setDefinition('magic_function_provider', new Definition(
139 'Civi\API\Provider\MagicFunctionProvider',
143 $container->setDefinition('civi_api_kernel', new Definition(
145 array(new Reference('dispatcher'), new Reference('magic_function_provider'))
147 ->setFactoryService(self
::SELF
)->setFactoryMethod('createApiKernel');
149 $container->setDefinition('cxn_reg_client', new Definition(
150 'Civi\Cxn\Rpc\RegistrationClient',
153 ->setFactoryClass('CRM_Cxn_BAO_Cxn')->setFactoryMethod('createRegistrationClient');
155 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', array()));
157 foreach (array('js_strings', 'community_messages') as $cacheName) {
158 $container->setDefinition("cache.{$cacheName}", new Definition(
159 'CRM_Utils_Cache_Interface',
162 'name' => $cacheName,
163 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
166 ))->setFactoryClass('CRM_Utils_Cache')->setFactoryMethod('create');
169 $container->setDefinition('pear_mail', new Definition('Mail'))
170 ->setFactoryClass('CRM_Utils_Mail')->setFactoryMethod('createMailer');
172 if (empty(\Civi
::$statics[__CLASS__
]['boot'])) {
173 throw new \
RuntimeException("Cannot initialize container. Boot services are undefined.");
175 foreach (\Civi
::$statics[__CLASS__
]['boot'] as $bootService => $def) {
176 $container->setDefinition($bootService, new Definition($def['class'], array($bootService)))
177 ->setFactoryClass(__CLASS__
)
178 ->setFactoryMethod('getBootService');
181 // Expose legacy singletons as services in the container.
183 'resources' => 'CRM_Core_Resources',
184 'httpClient' => 'CRM_Utils_HttpClient',
185 'cache.default' => 'CRM_Utils_Cache',
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 \CRM_Utils_Hook
::container($container);
202 * @return \Civi\Angular\Manager
204 public function createAngularManager() {
205 return new \Civi\Angular\
Manager(\CRM_Core_Resources
::singleton());
209 * @param ContainerInterface $container
210 * @return \Symfony\Component\EventDispatcher\EventDispatcher
212 public function createEventDispatcher($container) {
213 $dispatcher = new ContainerAwareEventDispatcher($container);
214 $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
215 $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
216 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
217 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
218 $dispatcher->addListener('DAO::post-insert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
219 $dispatcher->addListener('DAO::post-update', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
220 $dispatcher->addListener('DAO::post-delete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
221 $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
222 'CRM_Core_LegacyErrorHandler',
229 * @return LockManager
231 public static function createLockManager() {
232 // Ideally, downstream implementers could override any definitions in
233 // the container. For now, we'll make-do with some define()s.
234 $lm = new LockManager();
236 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK
: array('CRM_Core_Lock', 'createScopedLock'))
237 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK
: array('CRM_Core_Lock', 'createScopedLock'))
238 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: array('CRM_Core_Lock', 'createCivimailLock'))
239 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: array('CRM_Core_Lock', 'createScopedLock'));
241 // Registrations may use complex resolver expressions, but (as a micro-optimization)
242 // the default factory is specified as an array.
248 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
249 * @param $magicFunctionProvider
251 * @return \Civi\API\Kernel
253 public function createApiKernel($dispatcher, $magicFunctionProvider) {
254 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
ChainSubscriber());
255 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
TransactionSubscriber());
256 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
I18nSubscriber());
257 $dispatcher->addSubscriber($magicFunctionProvider);
258 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
PermissionCheck());
259 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
APIv3SchemaAdapter());
260 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
WrapperAdapter(array(
261 \CRM_Utils_API_HTMLInputCoder
::singleton(),
262 \CRM_Utils_API_NullOutputCoder
::singleton(),
263 \CRM_Utils_API_ReloadOption
::singleton(),
264 \CRM_Utils_API_MatchOption
::singleton(),
266 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
XDebugSubscriber());
267 $kernel = new \Civi\API\
Kernel($dispatcher);
269 $reflectionProvider = new \Civi\API\Provider\
ReflectionProvider($kernel);
270 $dispatcher->addSubscriber($reflectionProvider);
272 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
DynamicFKAuthorization(
275 array('create', 'get', 'delete'),
276 // Given a file ID, determine the entity+table it's attached to.
277 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
279 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
281 // Get a list of custom fields (field_name,table_name,extends)
282 'SELECT concat("custom_",fld.id) as field_name,
283 grp.table_name as table_name,
284 grp.extends as extends
285 FROM civicrm_custom_field fld
286 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
287 WHERE fld.data_type = "File"
289 array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
292 $kernel->setApiProviders(array(
294 $magicFunctionProvider,
301 * Get a list of boot services.
303 * These are services which must be setup *before* the container can operate.
305 * @param bool $loadFromDB
306 * @throws \CRM_Core_Exception
308 public static function boot($loadFromDB) {
309 $bootServices = array();
310 \Civi
::$statics[__CLASS__
]['boot'] = &$bootServices;
312 $bootServices['runtime'] = array(
313 'class' => 'CRM_Core_Config_Runtime',
314 'obj' => ($runtime = new \
CRM_Core_Config_Runtime()),
316 $runtime->initialize($loadFromDB);
318 if ($loadFromDB && $runtime->dsn
) {
319 \CRM_Core_DAO
::init($runtime->dsn
);
322 $bootServices['paths'] = array(
323 'class' => 'Civi\Core\Paths',
324 'obj' => new \Civi\Core\
Paths(),
327 $class = $runtime->userFrameworkClass
;
328 $bootServices['userSystem'] = array(
329 'class' => 'CRM_Utils_Cache_Interface',
330 'obj' => ($userSystem = new $class()),
332 $userSystem->initialize();
334 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework
;
335 $bootServices['userPermissionClass'] = array(
337 'class' => 'CRM_Core_Permission_Base',
338 'obj' => new $userPermissionClass(),
341 $bootServices['cache.settings'] = array(
342 'class' => 'CRM_Utils_Cache_Interface',
343 'obj' => \CRM_Utils_Cache
::create(array(
344 'name' => 'settings',
345 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
349 $bootServices['settings_manager'] = array(
350 'class' => 'Civi\Core\SettingsManager',
351 'obj' => new \Civi\Core\
SettingsManager($bootServices['cache.settings']['obj']),
354 $bootServices['lockManager'] = array(
355 'class' => 'Civi\Core\Lock\LockManager',
356 'obj' => self
::createLockManager(),
359 if ($loadFromDB && $runtime->dsn
) {
360 \CRM_Extension_System
::singleton(TRUE);
363 \Civi
::$statics[__CLASS__
]['container'] = $c->loadContainer();
367 public static function getBootService($name) {
368 return \Civi
::$statics[__CLASS__
]['boot'][$name]['obj'];