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 return $this->createContainer();
75 $envId = \CRM_Core_Config_Runtime
::getId();
76 $file = CIVICRM_TEMPLATE_COMPILEDIR
. "/CachedCiviContainer.{$envId}.php";
77 $containerConfigCache = new ConfigCache($file, $cacheMode === 'auto');
78 if (!$containerConfigCache->isFresh()) {
79 $containerBuilder = $this->createContainer();
80 $containerBuilder->compile();
81 $dumper = new PhpDumper($containerBuilder);
82 $containerConfigCache->write(
83 $dumper->dump(array('class' => 'CachedCiviContainer')),
84 $containerBuilder->getResources()
89 $c = new \
CachedCiviContainer();
90 $c->set('service_container', $c);
95 * Construct a new container.
97 * @var ContainerBuilder
98 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
100 public function createContainer() {
101 $civicrm_base_path = dirname(dirname(__DIR__
));
102 $container = new ContainerBuilder();
103 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
104 $container->addObjectResource($this);
105 $container->setParameter('civicrm_base_path', $civicrm_base_path);
106 //$container->set(self::SELF, $this);
107 $container->setDefinition(self
::SELF
, new Definition(
108 'Civi\Core\Container',
112 // TODO Move configuration to an external file; define caching structure
113 // if (empty($configDirectories)) {
114 // throw new \Exception(__CLASS__ . ': Missing required properties (civicrmRoot, configDirectories)');
116 // $locator = new FileLocator($configDirectories);
117 // $loaderResolver = new LoaderResolver(array(
118 // new YamlFileLoader($container, $locator)
120 // $delegatingLoader = new DelegatingLoader($loaderResolver);
121 // foreach (array('services.yml') as $file) {
122 // $yamlUserFiles = $locator->locate($file, NULL, FALSE);
123 // foreach ($yamlUserFiles as $file) {
124 // $delegatingLoader->load($file);
128 $container->setDefinition('angular', new Definition(
129 'Civi\Angular\Manager',
132 ->setFactoryService(self
::SELF
)->setFactoryMethod('createAngularManager');
134 $container->setDefinition('dispatcher', new Definition(
135 'Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher',
136 array(new Reference('service_container'))
138 ->setFactoryService(self
::SELF
)->setFactoryMethod('createEventDispatcher');
140 $container->setDefinition('magic_function_provider', new Definition(
141 'Civi\API\Provider\MagicFunctionProvider',
145 $container->setDefinition('civi_api_kernel', new Definition(
147 array(new Reference('dispatcher'), new Reference('magic_function_provider'))
149 ->setFactoryService(self
::SELF
)->setFactoryMethod('createApiKernel');
151 $container->setDefinition('cxn_reg_client', new Definition(
152 'Civi\Cxn\Rpc\RegistrationClient',
155 ->setFactoryClass('CRM_Cxn_BAO_Cxn')->setFactoryMethod('createRegistrationClient');
157 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', array()));
159 foreach (array('js_strings', 'community_messages') as $cacheName) {
160 $container->setDefinition("cache.{$cacheName}", new Definition(
161 'CRM_Utils_Cache_Interface',
164 'name' => $cacheName,
165 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
168 ))->setFactoryClass('CRM_Utils_Cache')->setFactoryMethod('create');
171 $container->setDefinition('sql_triggers', new Definition(
172 'Civi\Core\SqlTriggers',
176 $container->setDefinition('pear_mail', new Definition('Mail'))
177 ->setFactoryClass('CRM_Utils_Mail')->setFactoryMethod('createMailer');
179 if (empty(\Civi
::$statics[__CLASS__
]['boot'])) {
180 throw new \
RuntimeException("Cannot initialize container. Boot services are undefined.");
182 foreach (\Civi
::$statics[__CLASS__
]['boot'] as $bootService => $def) {
183 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE);
186 // Expose legacy singletons as services in the container.
188 'resources' => 'CRM_Core_Resources',
189 'httpClient' => 'CRM_Utils_HttpClient',
190 'cache.default' => 'CRM_Utils_Cache',
191 'i18n' => 'CRM_Core_I18n',
192 // Maybe? 'config' => 'CRM_Core_Config',
193 // Maybe? 'smarty' => 'CRM_Core_Smarty',
195 foreach ($singletons as $name => $class) {
196 $container->setDefinition($name, new Definition(
199 ->setFactoryClass($class)->setFactoryMethod('singleton');
202 $container->setDefinition('civi_token_compat', new Definition(
203 'Civi\Token\TokenCompatSubscriber',
205 ))->addTag('kernel.event_subscriber');
207 foreach (array('Activity', 'Contribute', 'Event', 'Member') as $comp) {
208 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
209 "CRM_{$comp}_Tokens",
211 ))->addTag('kernel.event_subscriber');
214 \CRM_Utils_Hook
::container($container);
220 * @return \Civi\Angular\Manager
222 public function createAngularManager() {
223 return new \Civi\Angular\
Manager(\CRM_Core_Resources
::singleton());
227 * @param ContainerInterface $container
228 * @return \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
230 public function createEventDispatcher($container) {
231 $dispatcher = new ContainerAwareEventDispatcher($container);
232 $dispatcher->addListener(SystemInstallEvent
::EVENT_NAME
, array('\Civi\Core\InstallationCanary', 'check'));
233 $dispatcher->addListener(SystemInstallEvent
::EVENT_NAME
, array('\Civi\Core\DatabaseInitializer', 'initialize'));
234 $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
235 $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
236 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
237 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
238 $dispatcher->addListener('DAO::post-insert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
239 $dispatcher->addListener('DAO::post-update', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
240 $dispatcher->addListener('DAO::post-delete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
241 $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
242 'CRM_Core_LegacyErrorHandler',
245 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Activity_ActionMapping', 'onRegisterActionMappings'));
246 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Contact_ActionMapping', 'onRegisterActionMappings'));
247 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings'));
248 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings'));
249 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Event_ActionMapping', 'onRegisterActionMappings'));
250 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Member_ActionMapping', 'onRegisterActionMappings'));
256 * @return LockManager
258 public static function createLockManager() {
259 // Ideally, downstream implementers could override any definitions in
260 // the container. For now, we'll make-do with some define()s.
261 $lm = new LockManager();
263 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK
: array('CRM_Core_Lock', 'createScopedLock'))
264 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK
: array('CRM_Core_Lock', 'createScopedLock'))
265 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: array('CRM_Core_Lock', 'createCivimailLock'))
266 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: array('CRM_Core_Lock', 'createScopedLock'));
268 // Registrations may use complex resolver expressions, but (as a micro-optimization)
269 // the default factory is specified as an array.
275 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
276 * @param $magicFunctionProvider
278 * @return \Civi\API\Kernel
280 public function createApiKernel($dispatcher, $magicFunctionProvider) {
281 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
ChainSubscriber());
282 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
TransactionSubscriber());
283 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
I18nSubscriber());
284 $dispatcher->addSubscriber($magicFunctionProvider);
285 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
PermissionCheck());
286 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
APIv3SchemaAdapter());
287 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
WrapperAdapter(array(
288 \CRM_Utils_API_HTMLInputCoder
::singleton(),
289 \CRM_Utils_API_NullOutputCoder
::singleton(),
290 \CRM_Utils_API_ReloadOption
::singleton(),
291 \CRM_Utils_API_MatchOption
::singleton(),
293 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
XDebugSubscriber());
294 $kernel = new \Civi\API\
Kernel($dispatcher);
296 $reflectionProvider = new \Civi\API\Provider\
ReflectionProvider($kernel);
297 $dispatcher->addSubscriber($reflectionProvider);
299 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
DynamicFKAuthorization(
302 array('create', 'get', 'delete'),
303 // Given a file ID, determine the entity+table it's attached to.
304 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
306 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
308 // Get a list of custom fields (field_name,table_name,extends)
309 'SELECT concat("custom_",fld.id) as field_name,
310 grp.table_name as table_name,
311 grp.extends as extends
312 FROM civicrm_custom_field fld
313 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
314 WHERE fld.data_type = "File"
316 array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
319 $kernel->setApiProviders(array(
321 $magicFunctionProvider,
328 * Get a list of boot services.
330 * These are services which must be setup *before* the container can operate.
332 * @param bool $loadFromDB
333 * @throws \CRM_Core_Exception
335 public static function boot($loadFromDB) {
336 // Array(string $serviceId => object $serviceInstance).
337 $bootServices = array();
338 \Civi
::$statics[__CLASS__
]['boot'] = &$bootServices;
340 $bootServices['runtime'] = $runtime = new \
CRM_Core_Config_Runtime();
341 $runtime->initialize($loadFromDB);
343 $bootServices['paths'] = new \Civi\Core\
Paths();
345 $class = $runtime->userFrameworkClass
;
346 $bootServices['userSystem'] = $userSystem = new $class();
347 $userSystem->initialize();
349 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework
;
350 $bootServices['userPermissionClass'] = new $userPermissionClass();
352 $bootServices['cache.settings'] = \CRM_Utils_Cache
::create(array(
353 'name' => 'settings',
354 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
357 $bootServices['settings_manager'] = new \Civi\Core\
SettingsManager($bootServices['cache.settings']);
359 $bootServices['lockManager'] = self
::createLockManager();
361 if ($loadFromDB && $runtime->dsn
) {
362 \CRM_Core_DAO
::init($runtime->dsn
);
363 \CRM_Utils_Hook
::singleton(TRUE);
364 \CRM_Extension_System
::singleton(TRUE);
365 \CRM_Extension_System
::singleton(TRUE)->getClassLoader()->register();
367 $runtime->includeCustomPath();
370 $container = $c->loadContainer();
371 foreach ($bootServices as $name => $obj) {
372 $container->set($name, $obj);
374 \Civi
::$statics[__CLASS__
]['container'] = $container;
378 public static function getBootService($name) {
379 return \Civi
::$statics[__CLASS__
]['boot'][$name];