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 $containerBuilder = $this->createContainer();
73 $containerBuilder->compile();
74 return $containerBuilder;
77 $envId = \CRM_Core_Config_Runtime
::getId();
78 $file = CIVICRM_TEMPLATE_COMPILEDIR
. "/CachedCiviContainer.{$envId}.php";
79 $containerConfigCache = new ConfigCache($file, $cacheMode === 'auto');
80 if (!$containerConfigCache->isFresh()) {
81 $containerBuilder = $this->createContainer();
82 $containerBuilder->compile();
83 $dumper = new PhpDumper($containerBuilder);
84 $containerConfigCache->write(
85 $dumper->dump(array('class' => 'CachedCiviContainer')),
86 $containerBuilder->getResources()
91 $c = new \
CachedCiviContainer();
96 * Construct a new container.
98 * @var ContainerBuilder
99 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
101 public function createContainer() {
102 $civicrm_base_path = dirname(dirname(__DIR__
));
103 $container = new ContainerBuilder();
104 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
105 $container->addObjectResource($this);
106 $container->setParameter('civicrm_base_path', $civicrm_base_path);
107 //$container->set(self::SELF, $this);
109 $container->addResource(new \Symfony\Component\Config\
Resource\
FileResource(__FILE__
));
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 ->setFactory(array(new Reference(self
::SELF
), 'createAngularManager'));
138 $container->setDefinition('dispatcher', new Definition(
139 'Civi\Core\CiviEventDispatcher',
140 array(new Reference('service_container'))
142 ->setFactory(array(new Reference(self
::SELF
), '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 ->setFactory(array(new Reference(self
::SELF
), 'createApiKernel'));
155 $container->setDefinition('cxn_reg_client', new Definition(
156 'Civi\Cxn\Rpc\RegistrationClient',
159 ->setFactory('CRM_Cxn_BAO_Cxn::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 ))->setFactory('CRM_Utils_Cache::create');
175 $container->setDefinition('sql_triggers', new Definition(
176 'Civi\Core\SqlTriggers',
180 $container->setDefinition('asset_builder', new Definition(
181 'Civi\Core\AssetBuilder',
185 $container->setDefinition('pear_mail', new Definition('Mail'))
186 ->setFactory('CRM_Utils_Mail::createMailer');
188 if (empty(\Civi
::$statics[__CLASS__
]['boot'])) {
189 throw new \
RuntimeException("Cannot initialize container. Boot services are undefined.");
191 foreach (\Civi
::$statics[__CLASS__
]['boot'] as $bootService => $def) {
192 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE);
195 // Expose legacy singletons as services in the container.
197 'resources' => 'CRM_Core_Resources',
198 'httpClient' => 'CRM_Utils_HttpClient',
199 'cache.default' => 'CRM_Utils_Cache',
200 'i18n' => 'CRM_Core_I18n',
201 // Maybe? 'config' => 'CRM_Core_Config',
202 // Maybe? 'smarty' => 'CRM_Core_Smarty',
204 foreach ($singletons as $name => $class) {
205 $container->setDefinition($name, new Definition(
208 ->setFactory(array($class, 'singleton'));
211 $container->setDefinition('civi.activity.triggers', new Definition(
212 'Civi\Core\SqlTrigger\TimestampTriggers',
213 array('civicrm_activity', 'Activity')
214 ))->addTag('kernel.event_listener', array('event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'));
216 $container->setDefinition('civi.case.triggers', new Definition(
217 'Civi\Core\SqlTrigger\TimestampTriggers',
218 array('civicrm_case', 'Case')
219 ))->addTag('kernel.event_listener', array('event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'));
221 $container->setDefinition('civi.case.staticTriggers', new Definition(
222 'Civi\Core\SqlTrigger\StaticTriggers',
226 'upgrade_check' => array('table' => 'civicrm_case', 'column' => 'modified_date'),
227 'table' => 'civicrm_case_activity',
229 'event' => array('INSERT'),
230 'sql' => "\nUPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.case_id;\n",
233 'upgrade_check' => array('table' => 'civicrm_case', 'column' => 'modified_date'),
234 'table' => 'civicrm_activity',
236 'event' => array('UPDATE', 'DELETE'),
237 'sql' => "\nUPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id IN (SELECT ca.case_id FROM civicrm_case_activity ca WHERE ca.activity_id = OLD.id);\n",
242 ->addTag('kernel.event_listener', array('event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'));
244 $container->setDefinition('civi_token_compat', new Definition(
245 'Civi\Token\TokenCompatSubscriber',
247 ))->addTag('kernel.event_subscriber');
248 $container->setDefinition("crm_mailing_action_tokens", new Definition(
249 "CRM_Mailing_ActionTokens",
251 ))->addTag('kernel.event_subscriber');
253 foreach (array('Activity', 'Contribute', 'Event', 'Mailing', 'Member') as $comp) {
254 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
255 "CRM_{$comp}_Tokens",
257 ))->addTag('kernel.event_subscriber');
260 if (\CRM_Utils_Constant
::value('CIVICRM_FLEXMAILER_HACK_SERVICES')) {
261 \Civi\Core\Resolver
::singleton()->call(CIVICRM_FLEXMAILER_HACK_SERVICES
, array($container));
264 \CRM_Utils_Hook
::container($container);
270 * @return \Civi\Angular\Manager
272 public function createAngularManager() {
273 return new \Civi\Angular\
Manager(\CRM_Core_Resources
::singleton());
277 * @param ContainerInterface $container
278 * @return \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
280 public function createEventDispatcher($container) {
281 $dispatcher = new CiviEventDispatcher($container);
282 $dispatcher->addListener(SystemInstallEvent
::EVENT_NAME
, array('\Civi\Core\InstallationCanary', 'check'));
283 $dispatcher->addListener(SystemInstallEvent
::EVENT_NAME
, array('\Civi\Core\DatabaseInitializer', 'initialize'));
284 $dispatcher->addListener(SystemInstallEvent
::EVENT_NAME
, array('\Civi\Core\LocalizationInitializer', 'initialize'));
285 $dispatcher->addListener('hook_civicrm_pre', array('\Civi\Core\Event\PreEvent', 'dispatchSubevent'), 100);
286 $dispatcher->addListener('hook_civicrm_post', array('\Civi\Core\Event\PostEvent', 'dispatchSubevent'), 100);
287 $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
288 $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
289 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
290 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
291 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\Core\CiviEventInspector', 'findBuiltInEvents'));
292 // TODO We need a better code-convention for metadata about non-hook events.
293 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\API\Events', 'hookEventDefs'));
294 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs'));
295 $dispatcher->addListener('hook_civicrm_buildAsset', array('\Civi\Angular\Page\Modules', 'buildAngularModules'));
296 $dispatcher->addListener('civi.dao.postInsert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
297 $dispatcher->addListener('civi.dao.postUpdate', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
298 $dispatcher->addListener('civi.dao.postDelete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
299 $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
300 'CRM_Core_LegacyErrorHandler',
303 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Activity_ActionMapping', 'onRegisterActionMappings'));
304 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Contact_ActionMapping', 'onRegisterActionMappings'));
305 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings'));
306 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings'));
307 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Event_ActionMapping', 'onRegisterActionMappings'));
308 $dispatcher->addListener(\Civi\ActionSchedule\Events
::MAPPINGS
, array('CRM_Member_ActionMapping', 'onRegisterActionMappings'));
310 if (\CRM_Utils_Constant
::value('CIVICRM_FLEXMAILER_HACK_LISTENERS')) {
311 \Civi\Core\Resolver
::singleton()->call(CIVICRM_FLEXMAILER_HACK_LISTENERS
, array($dispatcher));
318 * @return LockManager
320 public static function createLockManager() {
321 // Ideally, downstream implementers could override any definitions in
322 // the container. For now, we'll make-do with some define()s.
323 $lm = new LockManager();
325 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK
: array('CRM_Core_Lock', 'createScopedLock'))
326 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK
: array('CRM_Core_Lock', 'createScopedLock'))
327 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: array('CRM_Core_Lock', 'createCivimailLock'))
328 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK
: array('CRM_Core_Lock', 'createScopedLock'));
330 // Registrations may use complex resolver expressions, but (as a micro-optimization)
331 // the default factory is specified as an array.
337 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
338 * @param $magicFunctionProvider
340 * @return \Civi\API\Kernel
342 public function createApiKernel($dispatcher, $magicFunctionProvider) {
343 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
ChainSubscriber());
344 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
TransactionSubscriber());
345 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
I18nSubscriber());
346 $dispatcher->addSubscriber($magicFunctionProvider);
347 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
PermissionCheck());
348 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
APIv3SchemaAdapter());
349 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
WrapperAdapter(array(
350 \CRM_Utils_API_HTMLInputCoder
::singleton(),
351 \CRM_Utils_API_NullOutputCoder
::singleton(),
352 \CRM_Utils_API_ReloadOption
::singleton(),
353 \CRM_Utils_API_MatchOption
::singleton(),
355 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
XDebugSubscriber());
356 $kernel = new \Civi\API\
Kernel($dispatcher);
358 $reflectionProvider = new \Civi\API\Provider\
ReflectionProvider($kernel);
359 $dispatcher->addSubscriber($reflectionProvider);
361 $dispatcher->addSubscriber(new \Civi\API\Subscriber\
DynamicFKAuthorization(
364 array('create', 'get', 'delete'),
365 // Given a file ID, determine the entity+table it's attached to.
366 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
368 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
370 // Get a list of custom fields (field_name,table_name,extends)
371 'SELECT concat("custom_",fld.id) as field_name,
372 grp.table_name as table_name,
373 grp.extends as extends
374 FROM civicrm_custom_field fld
375 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
376 WHERE fld.data_type = "File"
378 array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
381 $kernel->setApiProviders(array(
383 $magicFunctionProvider,
390 * Get a list of boot services.
392 * These are services which must be setup *before* the container can operate.
394 * @param bool $loadFromDB
395 * @throws \CRM_Core_Exception
397 public static function boot($loadFromDB) {
398 // Array(string $serviceId => object $serviceInstance).
399 $bootServices = array();
400 \Civi
::$statics[__CLASS__
]['boot'] = &$bootServices;
402 $bootServices['runtime'] = $runtime = new \
CRM_Core_Config_Runtime();
403 $runtime->initialize($loadFromDB);
405 $bootServices['paths'] = new \Civi\Core\
Paths();
407 $class = $runtime->userFrameworkClass
;
408 $bootServices['userSystem'] = $userSystem = new $class();
409 $userSystem->initialize();
411 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework
;
412 $bootServices['userPermissionClass'] = new $userPermissionClass();
414 $bootServices['cache.settings'] = \CRM_Utils_Cache
::create(array(
415 'name' => 'settings',
416 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
419 $bootServices['settings_manager'] = new \Civi\Core\
SettingsManager($bootServices['cache.settings']);
421 $bootServices['lockManager'] = self
::createLockManager();
423 if ($loadFromDB && $runtime->dsn
) {
424 \CRM_Core_DAO
::init($runtime->dsn
);
425 \CRM_Utils_Hook
::singleton(TRUE);
426 \CRM_Extension_System
::singleton(TRUE);
427 \CRM_Extension_System
::singleton(TRUE)->getClassLoader()->register();
429 $runtime->includeCustomPath();
432 $container = $c->loadContainer();
433 foreach ($bootServices as $name => $obj) {
434 $container->set($name, $obj);
436 \Civi
::$statics[__CLASS__
]['container'] = $container;
440 public static function getBootService($name) {
441 return \Civi
::$statics[__CLASS__
]['boot'][$name];
445 * Determine whether the container services are available.
449 public static function isContainerBooted() {
450 return isset(\Civi
::$statics[__CLASS__
]['container']);