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';
32 * @var ContainerBuilder
34 private static $singleton;
38 * Whether to forcibly rebuild the entire container.
39 * @return \Symfony\Component\DependencyInjection\TaggedContainerInterface
41 public static function singleton($reset = FALSE) {
42 if ($reset || self
::$singleton === NULL) {
44 self
::$singleton = $c->loadContainer();
46 return self
::$singleton;
50 * Find a cached container definition or construct a new one.
52 * There are many weird contexts in which Civi initializes (eg different
53 * variations of multitenancy and different permutations of CMS/CRM bootstrap),
54 * and hook_container may fire a bit differently in each context. To mitigate
55 * risk of leaks between environments, we compute a unique envID
56 * (md5(DB_NAME, HTTP_HOST, SCRIPT_FILENAME, etc)) and use separate caches for
57 * each (eg "templates_c/CachedCiviContainer.$ENVID.php").
60 * - CIVICRM_CONTAINER_CACHE -- 'always' [default], 'never', 'auto'
63 * - CIVICRM_TEMPLATE_COMPILEDIR
65 * @return ContainerInterface
67 public function loadContainer() {
68 // Note: The container's raison d'etre is to manage construction of other
69 // services. Consequently, we assume a minimal service available -- the classloader
70 // has been setup, and civicrm.settings.php is loaded, but nothing else works.
72 $cacheMode = defined('CIVICRM_CONTAINER_CACHE') ? CIVICRM_CONTAINER_CACHE
: 'always';
74 // In pre-installation environments, don't bother with caching.
75 if (!defined('CIVICRM_TEMPLATE_COMPILEDIR') ||
!defined('CIVICRM_DSN') ||
$cacheMode === 'never' || \CRM_Utils_System
::isInUpgradeMode()) {
76 return $this->createContainer();
79 $envId = \CRM_Core_Config_Runtime
::getId();
80 $file = CIVICRM_TEMPLATE_COMPILEDIR
. "/CachedCiviContainer.{$envId}.php";
81 $containerConfigCache = new ConfigCache($file, $cacheMode === 'auto');
82 if (!$containerConfigCache->isFresh()) {
83 $containerBuilder = $this->createContainer();
84 $containerBuilder->compile();
85 $dumper = new PhpDumper($containerBuilder);
86 $containerConfigCache->write(
87 $dumper->dump(array('class' => 'CachedCiviContainer')),
88 $containerBuilder->getResources()
93 $c = new \
CachedCiviContainer();
94 $c->set('service_container', $c);
99 * Construct a new container.
101 * @var ContainerBuilder
102 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
104 public function createContainer() {
105 $civicrm_base_path = dirname(dirname(__DIR__
));
106 $container = new ContainerBuilder();
107 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
108 $container->addObjectResource($this);
109 $container->setParameter('civicrm_base_path', $civicrm_base_path);
110 //$container->set(self::SELF, $this);
111 $container->setDefinition(self
::SELF
, new Definition(
112 'Civi\Core\Container',
116 // TODO Move configuration to an external file; define caching structure
117 // if (empty($configDirectories)) {
118 // throw new \Exception(__CLASS__ . ': Missing required properties (civicrmRoot, configDirectories)');
120 // $locator = new FileLocator($configDirectories);
121 // $loaderResolver = new LoaderResolver(array(
122 // new YamlFileLoader($container, $locator)
124 // $delegatingLoader = new DelegatingLoader($loaderResolver);
125 // foreach (array('services.yml') as $file) {
126 // $yamlUserFiles = $locator->locate($file, NULL, FALSE);
127 // foreach ($yamlUserFiles as $file) {
128 // $delegatingLoader->load($file);
132 $container->setDefinition('angular', new Definition(
133 'Civi\Angular\Manager',
136 ->setFactoryService(self
::SELF
)->setFactoryMethod('createAngularManager');
138 $container->setDefinition('dispatcher', new Definition(
139 'Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher',
140 array(new Reference('service_container'))
142 ->setFactoryService(self
::SELF
)->setFactoryMethod('createEventDispatcher');
144 $container->setDefinition('magic_function_provider', new Definition(
145 'Civi\API\Provider\MagicFunctionProvider',
149 $container->setDefinition('civi_api_kernel', new Definition(
151 array(new Reference('dispatcher'), new Reference('magic_function_provider'))
153 ->setFactoryService(self
::SELF
)->setFactoryMethod('createApiKernel');
155 $container->setDefinition('cxn_reg_client', new Definition(
156 'Civi\Cxn\Rpc\RegistrationClient',
159 ->setFactoryClass('CRM_Cxn_BAO_Cxn')->setFactoryMethod('createRegistrationClient');
161 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', array()));
163 foreach (array('js_strings', 'community_messages') as $cacheName) {
164 $container->setDefinition("cache.{$cacheName}", new Definition(
165 'CRM_Utils_Cache_Interface',
168 'name' => $cacheName,
169 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
172 ))->setFactoryClass('CRM_Utils_Cache')->setFactoryMethod('create');
175 $container->setDefinition('pear_mail', new Definition('Mail'))
176 ->setFactoryClass('CRM_Utils_Mail')->setFactoryMethod('createMailer');
178 foreach (self
::getBootServices() as $bootService => $def) {
179 $container->setDefinition($bootService, new Definition($def['class'], array($bootService)))
180 ->setFactoryClass(__CLASS__
)
181 ->setFactoryMethod('getBootService');
184 // Expose legacy singletons as services in the container.
186 'resources' => 'CRM_Core_Resources',
187 'httpClient' => 'CRM_Utils_HttpClient',
188 'cache.default' => 'CRM_Utils_Cache',
189 // Maybe? 'config' => 'CRM_Core_Config',
190 // Maybe? 'smarty' => 'CRM_Core_Smarty',
192 foreach ($singletons as $name => $class) {
193 $container->setDefinition($name, new Definition(
196 ->setFactoryClass($class)->setFactoryMethod('singleton');
199 \CRM_Utils_Hook
::container($container);
205 * @return \Civi\Angular\Manager
207 public function createAngularManager() {
208 return new \Civi\Angular\
Manager(\CRM_Core_Resources
::singleton());
212 * @param ContainerInterface $container
213 * @return \Symfony\Component\EventDispatcher\EventDispatcher
215 public function createEventDispatcher($container) {
216 $dispatcher = new ContainerAwareEventDispatcher($container);
217 $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
218 $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
219 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
220 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
221 $dispatcher->addListener('DAO::post-insert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
222 $dispatcher->addListener('DAO::post-update', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
223 $dispatcher->addListener('DAO::post-delete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
224 $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
225 'CRM_Core_LegacyErrorHandler',
232 * @return LockManager
234 public static function createLockManager() {
235 // Ideally, downstream implementers could override any definitions in
236 // the container. For now, we'll make-do with some define()s.
237 $lm = new LockManager();
239 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK
: array('CRM_Core_Lock', 'createScopedLock'))
240 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK
: array('CRM_Core_Lock', 'createScopedLock'))
241 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: array('CRM_Core_Lock', 'createCivimailLock'))
242 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: array('CRM_Core_Lock', 'createScopedLock'));
244 // Registrations may use complex resolver expressions, but (as a micro-optimization)
245 // the default factory is specified as an array.
251 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
252 * @param $magicFunctionProvider
254 * @return \Civi\API\Kernel
256 public function createApiKernel($dispatcher, $magicFunctionProvider) {
257 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
ChainSubscriber());
258 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
TransactionSubscriber());
259 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
I18nSubscriber());
260 $dispatcher->addSubscriber($magicFunctionProvider);
261 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
PermissionCheck());
262 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
APIv3SchemaAdapter());
263 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
WrapperAdapter(array(
264 \CRM_Utils_API_HTMLInputCoder
::singleton(),
265 \CRM_Utils_API_NullOutputCoder
::singleton(),
266 \CRM_Utils_API_ReloadOption
::singleton(),
267 \CRM_Utils_API_MatchOption
::singleton(),
269 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
XDebugSubscriber());
270 $kernel = new \Civi\API\
Kernel($dispatcher);
272 $reflectionProvider = new \Civi\API\Provider\
ReflectionProvider($kernel);
273 $dispatcher->addSubscriber($reflectionProvider);
275 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
DynamicFKAuthorization(
278 array('create', 'get', 'delete'),
279 // Given a file ID, determine the entity+table it's attached to.
280 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
282 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
284 // Get a list of custom fields (field_name,table_name,extends)
285 'SELECT concat("custom_",fld.id) as field_name,
286 grp.table_name as table_name,
287 grp.extends as extends
288 FROM civicrm_custom_field fld
289 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
290 WHERE fld.data_type = "File"
292 array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
295 $kernel->setApiProviders(array(
297 $magicFunctionProvider,
304 * Get a list of boot services.
306 * These are services which must be setup *before* the container can operate.
309 * Ex: $result['serviceName'] = array('class' => $, 'obj' => $).
310 * @throws \CRM_Core_Exception
312 public static function getBootServices() {
313 if (!isset(\Civi
::$statics['*boot*'])) {
314 \Civi
::$statics['*boot*']['cache.settings'] = array(
315 'class' => 'CRM_Utils_Cache_Interface',
316 'obj' => \CRM_Utils_Cache
::create(array(
317 'name' => 'settings',
318 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
321 \Civi
::$statics['*boot*']['settings_manager'] = array(
322 'class' => 'Civi\Core\SettingsManager',
323 'obj' => new \Civi\Core\
SettingsManager(\Civi
::$statics['*boot*']['cache.settings']['obj']),
325 \Civi
::$statics['*boot*']['lockManager'] = array(
326 'class' => 'Civi\Core\Lock\LockManager',
327 'obj' => self
::createLockManager(),
330 return \Civi
::$statics['*boot*'];
333 public static function getBootService($name) {
334 return \Civi
::$statics['*boot*'][$name]['obj'];