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('sql_triggers', new Definition(
171 'Civi\Core\SqlTriggers',
175 $container->setDefinition('pear_mail', new Definition('Mail'))
176 ->setFactoryClass('CRM_Utils_Mail')->setFactoryMethod('createMailer');
178 if (empty(\Civi
::$statics[__CLASS__
]['boot'])) {
179 throw new \
RuntimeException("Cannot initialize container. Boot services are undefined.");
181 foreach (\Civi
::$statics[__CLASS__
]['boot'] as $bootService => $def) {
182 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE);
185 // Expose legacy singletons as services in the container.
187 'resources' => 'CRM_Core_Resources',
188 'httpClient' => 'CRM_Utils_HttpClient',
189 'cache.default' => 'CRM_Utils_Cache',
190 'i18n' => 'CRM_Core_I18n',
191 // Maybe? 'config' => 'CRM_Core_Config',
192 // Maybe? 'smarty' => 'CRM_Core_Smarty',
194 foreach ($singletons as $name => $class) {
195 $container->setDefinition($name, new Definition(
198 ->setFactoryClass($class)->setFactoryMethod('singleton');
201 $container->setDefinition('civi_token_compat', new Definition(
202 'Civi\Token\TokenCompatSubscriber',
204 ))->addTag('kernel.event_subscriber');
206 foreach (array('Activity', 'Contribute', 'Event', 'Member') as $comp) {
207 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
208 "CRM_{$comp}_Tokens",
210 ))->addTag('kernel.event_subscriber');
213 \CRM_Utils_Hook
::container($container);
219 * @return \Civi\Angular\Manager
221 public function createAngularManager() {
222 return new \Civi\Angular\
Manager(\CRM_Core_Resources
::singleton());
226 * @param ContainerInterface $container
227 * @return \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
229 public function createEventDispatcher($container) {
230 $dispatcher = new ContainerAwareEventDispatcher($container);
231 $dispatcher->addListener(SystemInstallEvent
::EVENT_NAME
, array('\Civi\Core\InstallationCanary', 'check'));
232 $dispatcher->addListener(SystemInstallEvent
::EVENT_NAME
, array('\Civi\Core\DatabaseInitializer', 'initialize'));
233 $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
234 $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
235 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
236 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
237 $dispatcher->addListener('DAO::post-insert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
238 $dispatcher->addListener('DAO::post-update', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
239 $dispatcher->addListener('DAO::post-delete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
240 $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
241 'CRM_Core_LegacyErrorHandler',
244 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Activity_ActionMapping', 'onRegisterActionMappings'));
245 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Contact_ActionMapping', 'onRegisterActionMappings'));
246 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings'));
247 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings'));
248 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Event_ActionMapping', 'onRegisterActionMappings'));
249 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Member_ActionMapping', 'onRegisterActionMappings'));
255 * @return LockManager
257 public static function createLockManager() {
258 // Ideally, downstream implementers could override any definitions in
259 // the container. For now, we'll make-do with some define()s.
260 $lm = new LockManager();
262 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK
: array('CRM_Core_Lock', 'createScopedLock'))
263 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK
: array('CRM_Core_Lock', 'createScopedLock'))
264 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: array('CRM_Core_Lock', 'createCivimailLock'))
265 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: array('CRM_Core_Lock', 'createScopedLock'));
267 // Registrations may use complex resolver expressions, but (as a micro-optimization)
268 // the default factory is specified as an array.
274 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
275 * @param $magicFunctionProvider
277 * @return \Civi\API\Kernel
279 public function createApiKernel($dispatcher, $magicFunctionProvider) {
280 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
ChainSubscriber());
281 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
TransactionSubscriber());
282 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
I18nSubscriber());
283 $dispatcher->addSubscriber($magicFunctionProvider);
284 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
PermissionCheck());
285 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
APIv3SchemaAdapter());
286 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
WrapperAdapter(array(
287 \CRM_Utils_API_HTMLInputCoder
::singleton(),
288 \CRM_Utils_API_NullOutputCoder
::singleton(),
289 \CRM_Utils_API_ReloadOption
::singleton(),
290 \CRM_Utils_API_MatchOption
::singleton(),
292 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
XDebugSubscriber());
293 $kernel = new \Civi\API\
Kernel($dispatcher);
295 $reflectionProvider = new \Civi\API\Provider\
ReflectionProvider($kernel);
296 $dispatcher->addSubscriber($reflectionProvider);
298 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
DynamicFKAuthorization(
301 array('create', 'get', 'delete'),
302 // Given a file ID, determine the entity+table it's attached to.
303 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
305 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
307 // Get a list of custom fields (field_name,table_name,extends)
308 'SELECT concat("custom_",fld.id) as field_name,
309 grp.table_name as table_name,
310 grp.extends as extends
311 FROM civicrm_custom_field fld
312 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
313 WHERE fld.data_type = "File"
315 array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
318 $kernel->setApiProviders(array(
320 $magicFunctionProvider,
327 * Get a list of boot services.
329 * These are services which must be setup *before* the container can operate.
331 * @param bool $loadFromDB
332 * @throws \CRM_Core_Exception
334 public static function boot($loadFromDB) {
335 // Array(string $serviceId => object $serviceInstance).
336 $bootServices = array();
337 \Civi
::$statics[__CLASS__
]['boot'] = &$bootServices;
339 $bootServices['runtime'] = $runtime = new \
CRM_Core_Config_Runtime();
340 $runtime->initialize($loadFromDB);
342 $bootServices['paths'] = new \Civi\Core\
Paths();
344 $class = $runtime->userFrameworkClass
;
345 $bootServices['userSystem'] = $userSystem = new $class();
346 $userSystem->initialize();
348 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework
;
349 $bootServices['userPermissionClass'] = new $userPermissionClass();
351 $bootServices['cache.settings'] = \CRM_Utils_Cache
::create(array(
352 'name' => 'settings',
353 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
356 $bootServices['settings_manager'] = new \Civi\Core\
SettingsManager($bootServices['cache.settings']);
358 $bootServices['lockManager'] = self
::createLockManager();
360 if ($loadFromDB && $runtime->dsn
) {
361 \CRM_Core_DAO
::init($runtime->dsn
);
362 \CRM_Utils_Hook
::singleton(TRUE);
363 \CRM_Extension_System
::singleton(TRUE);
364 \CRM_Extension_System
::singleton(TRUE)->getClassLoader()->register();
366 $runtime->includeCustomPath();
369 $container = $c->loadContainer();
370 foreach ($bootServices as $name => $obj) {
371 $container->set($name, $obj);
373 \Civi
::$statics[__CLASS__
]['container'] = $container;
377 public static function getBootService($name) {
378 return \Civi
::$statics[__CLASS__
]['boot'][$name];