Rename hook_civicrm_hooks to hook_civicrm_eventDefs
[civicrm-core.git] / Civi / Core / Container.php
CommitLineData
fa184193
TO
1<?php
2namespace Civi\Core;
46bcf597 3
8bcc0d86 4use Civi\API\Provider\ActionObjectProvider;
0085db83 5use Civi\Core\Event\SystemInstallEvent;
10760fa1 6use Civi\Core\Lock\LockManager;
fa184193
TO
7use Doctrine\Common\Annotations\AnnotationReader;
8use Doctrine\Common\Annotations\AnnotationRegistry;
9use Doctrine\Common\Annotations\FileCacheReader;
10use Doctrine\Common\Cache\FilesystemCache;
11use Doctrine\ORM\EntityManager;
12use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
13use Doctrine\ORM\Tools\Setup;
40787e18 14use Symfony\Component\Config\ConfigCache;
fa184193 15use Symfony\Component\DependencyInjection\ContainerBuilder;
c8074a93 16use Symfony\Component\DependencyInjection\ContainerInterface;
fa184193 17use Symfony\Component\DependencyInjection\Definition;
40787e18 18use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
fa184193 19use Symfony\Component\DependencyInjection\Reference;
40787e18
TO
20use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher;
21use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass;
fa184193
TO
22
23// TODO use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
24
6550386a
EM
25/**
26 * Class Container
27 * @package Civi\Core
28 */
fa184193
TO
29class Container {
30
31 const SELF = 'civi_container_factory';
32
fa184193 33 /**
04855556
TO
34 * @param bool $reset
35 * Whether to forcibly rebuild the entire container.
fa184193
TO
36 * @return \Symfony\Component\DependencyInjection\TaggedContainerInterface
37 */
378e2654 38 public static function singleton($reset = FALSE) {
7f835399
TO
39 if ($reset || !isset(\Civi::$statics[__CLASS__]['container'])) {
40 self::boot(TRUE);
fa184193 41 }
7f835399 42 return \Civi::$statics[__CLASS__]['container'];
fa184193
TO
43 }
44
45 /**
40787e18
TO
46 * Find a cached container definition or construct a new one.
47 *
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").
54 *
55 * Constants:
56 * - CIVICRM_CONTAINER_CACHE -- 'always' [default], 'never', 'auto'
57 * - CIVICRM_DSN
58 * - CIVICRM_DOMAIN_ID
59 * - CIVICRM_TEMPLATE_COMPILEDIR
60 *
61 * @return ContainerInterface
62 */
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.
67
68 $cacheMode = defined('CIVICRM_CONTAINER_CACHE') ? CIVICRM_CONTAINER_CACHE : 'always';
69
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()) {
12e01332
TO
72 $containerBuilder = $this->createContainer();
73 $containerBuilder->compile();
74 return $containerBuilder;
40787e18
TO
75 }
76
83617886 77 $envId = \CRM_Core_Config_Runtime::getId();
40787e18
TO
78 $file = CIVICRM_TEMPLATE_COMPILEDIR . "/CachedCiviContainer.{$envId}.php";
79 $containerConfigCache = new ConfigCache($file, $cacheMode === 'auto');
40787e18
TO
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()
87 );
88 }
89
90 require_once $file;
91 $c = new \CachedCiviContainer();
92 $c->set('service_container', $c);
93 return $c;
94 }
95
96 /**
97 * Construct a new container.
98 *
fa184193 99 * @var ContainerBuilder
77b97be7 100 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
fa184193
TO
101 */
102 public function createContainer() {
103 $civicrm_base_path = dirname(dirname(__DIR__));
104 $container = new ContainerBuilder();
40787e18
TO
105 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
106 $container->addObjectResource($this);
fa184193 107 $container->setParameter('civicrm_base_path', $civicrm_base_path);
40787e18 108 //$container->set(self::SELF, $this);
762dc04d
TO
109
110 $container->addResource(new \Symfony\Component\Config\Resource\FileResource(__FILE__));
111
40787e18
TO
112 $container->setDefinition(self::SELF, new Definition(
113 'Civi\Core\Container',
114 array()
115 ));
fa184193 116
505d8b83
TO
117 // TODO Move configuration to an external file; define caching structure
118 // if (empty($configDirectories)) {
119 // throw new \Exception(__CLASS__ . ': Missing required properties (civicrmRoot, configDirectories)');
120 // }
121 // $locator = new FileLocator($configDirectories);
122 // $loaderResolver = new LoaderResolver(array(
123 // new YamlFileLoader($container, $locator)
124 // ));
125 // $delegatingLoader = new DelegatingLoader($loaderResolver);
126 // foreach (array('services.yml') as $file) {
127 // $yamlUserFiles = $locator->locate($file, NULL, FALSE);
128 // foreach ($yamlUserFiles as $file) {
129 // $delegatingLoader->load($file);
130 // }
131 // }
fa184193 132
16072ce1 133 $container->setDefinition('angular', new Definition(
40787e18 134 'Civi\Angular\Manager',
16072ce1
TO
135 array()
136 ))
137 ->setFactoryService(self::SELF)->setFactoryMethod('createAngularManager');
138
fa184193 139 $container->setDefinition('dispatcher', new Definition(
762dc04d 140 'Civi\Core\CiviEventDispatcher',
40787e18 141 array(new Reference('service_container'))
fa184193
TO
142 ))
143 ->setFactoryService(self::SELF)->setFactoryMethod('createEventDispatcher');
144
c65db512 145 $container->setDefinition('magic_function_provider', new Definition(
40787e18 146 'Civi\API\Provider\MagicFunctionProvider',
c65db512
TO
147 array()
148 ));
149
0f643fb2 150 $container->setDefinition('civi_api_kernel', new Definition(
40787e18 151 'Civi\API\Kernel',
c65db512 152 array(new Reference('dispatcher'), new Reference('magic_function_provider'))
0f643fb2
TO
153 ))
154 ->setFactoryService(self::SELF)->setFactoryMethod('createApiKernel');
155
7b4bbb34 156 $container->setDefinition('cxn_reg_client', new Definition(
40787e18 157 'Civi\Cxn\Rpc\RegistrationClient',
7b4bbb34
TO
158 array()
159 ))
9ae2d27b 160 ->setFactoryClass('CRM_Cxn_BAO_Cxn')->setFactoryMethod('createRegistrationClient');
7b4bbb34 161
6e5ad5ee
TO
162 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', array()));
163
83617886 164 foreach (array('js_strings', 'community_messages') as $cacheName) {
a4704404
TO
165 $container->setDefinition("cache.{$cacheName}", new Definition(
166 'CRM_Utils_Cache_Interface',
167 array(
168 array(
169 'name' => $cacheName,
a944a143 170 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
a4704404
TO
171 ),
172 )
173 ))->setFactoryClass('CRM_Utils_Cache')->setFactoryMethod('create');
174 }
3a84c0ab 175
4ed867e0
TO
176 $container->setDefinition('sql_triggers', new Definition(
177 'Civi\Core\SqlTriggers',
178 array()
179 ));
180
247eb841
TO
181 $container->setDefinition('pear_mail', new Definition('Mail'))
182 ->setFactoryClass('CRM_Utils_Mail')->setFactoryMethod('createMailer');
183
7f835399
TO
184 if (empty(\Civi::$statics[__CLASS__]['boot'])) {
185 throw new \RuntimeException("Cannot initialize container. Boot services are undefined.");
186 }
187 foreach (\Civi::$statics[__CLASS__]['boot'] as $bootService => $def) {
56eafc21 188 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE);
83617886
TO
189 }
190
c8074a93
TO
191 // Expose legacy singletons as services in the container.
192 $singletons = array(
193 'resources' => 'CRM_Core_Resources',
194 'httpClient' => 'CRM_Utils_HttpClient',
7b5937fe 195 'cache.default' => 'CRM_Utils_Cache',
a7c57397 196 'i18n' => 'CRM_Core_I18n',
c8074a93
TO
197 // Maybe? 'config' => 'CRM_Core_Config',
198 // Maybe? 'smarty' => 'CRM_Core_Smarty',
199 );
200 foreach ($singletons as $name => $class) {
201 $container->setDefinition($name, new Definition(
202 $class
203 ))
204 ->setFactoryClass($class)->setFactoryMethod('singleton');
205 }
206
43ceab3f
TO
207 $container->setDefinition('civi_token_compat', new Definition(
208 'Civi\Token\TokenCompatSubscriber',
209 array()
210 ))->addTag('kernel.event_subscriber');
56df2d06
TO
211 $container->setDefinition("crm_mailing_action_tokens", new Definition(
212 "CRM_Mailing_ActionTokens",
213 array()
214 ))->addTag('kernel.event_subscriber');
43ceab3f 215
56df2d06 216 foreach (array('Activity', 'Contribute', 'Event', 'Mailing', 'Member') as $comp) {
46f5566c
TO
217 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
218 "CRM_{$comp}_Tokens",
219 array()
220 ))->addTag('kernel.event_subscriber');
221 }
50a23755 222
aa4343bc
TO
223 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_SERVICES')) {
224 \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_SERVICES, array($container));
225 }
226
40787e18
TO
227 \CRM_Utils_Hook::container($container);
228
fa184193
TO
229 return $container;
230 }
231
16072ce1
TO
232 /**
233 * @return \Civi\Angular\Manager
234 */
235 public function createAngularManager() {
236 return new \Civi\Angular\Manager(\CRM_Core_Resources::singleton());
237 }
238
fa184193 239 /**
40787e18 240 * @param ContainerInterface $container
43ceab3f 241 * @return \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
fa184193 242 */
40787e18 243 public function createEventDispatcher($container) {
762dc04d 244 $dispatcher = new CiviEventDispatcher($container);
0085db83 245 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\InstallationCanary', 'check'));
40d5632a 246 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\DatabaseInitializer', 'initialize'));
c73e3098
TO
247 $dispatcher->addListener('hook_civicrm_pre', array('\Civi\Core\Event\PreEvent', 'dispatchSubevent'), 100);
248 $dispatcher->addListener('hook_civicrm_post', array('\Civi\Core\Event\PostEvent', 'dispatchSubevent'), 100);
708d8fa2 249 $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
753657ed 250 $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
708d8fa2 251 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
b019b130 252 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
47e7c2f8 253 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\Core\CiviEventInspector', 'findBuiltInEvents'));
0d0031a0 254 // TODO We need a better code-convention for metadata about non-hook events.
47e7c2f8
TO
255 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\API\Events', 'hookEventDefs'));
256 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs'));
94075464
TO
257 $dispatcher->addListener('civi.dao.postInsert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
258 $dispatcher->addListener('civi.dao.postUpdate', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
259 $dispatcher->addListener('civi.dao.postDelete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
46bcf597 260 $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
9ae2d27b
TO
261 'CRM_Core_LegacyErrorHandler',
262 'handleException',
c73e3098 263 ), -200);
46f5566c
TO
264 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Activity_ActionMapping', 'onRegisterActionMappings'));
265 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contact_ActionMapping', 'onRegisterActionMappings'));
2045389a 266 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings'));
b5302d4e 267 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings'));
46f5566c
TO
268 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Event_ActionMapping', 'onRegisterActionMappings'));
269 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Member_ActionMapping', 'onRegisterActionMappings'));
270
aa4343bc
TO
271 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_LISTENERS')) {
272 \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_LISTENERS, array($dispatcher));
273 }
274
fa184193
TO
275 return $dispatcher;
276 }
0f643fb2 277
10760fa1
TO
278 /**
279 * @return LockManager
280 */
83617886 281 public static function createLockManager() {
10760fa1
TO
282 // Ideally, downstream implementers could override any definitions in
283 // the container. For now, we'll make-do with some define()s.
284 $lm = new LockManager();
285 $lm
286 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
287 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
288 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createCivimailLock'))
289 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createScopedLock'));
290
291 // Registrations may use complex resolver expressions, but (as a micro-optimization)
292 // the default factory is specified as an array.
293
294 return $lm;
295 }
296
0f643fb2
TO
297 /**
298 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
2a6da8d7
EM
299 * @param $magicFunctionProvider
300 *
0f643fb2
TO
301 * @return \Civi\API\Kernel
302 */
c65db512 303 public function createApiKernel($dispatcher, $magicFunctionProvider) {
0a946de2 304 $dispatcher->addSubscriber(new \Civi\API\Subscriber\ChainSubscriber());
b55bc593 305 $dispatcher->addSubscriber(new \Civi\API\Subscriber\TransactionSubscriber());
bace5cd9 306 $dispatcher->addSubscriber(new \Civi\API\Subscriber\I18nSubscriber());
c65db512 307 $dispatcher->addSubscriber($magicFunctionProvider);
d0c9daa4 308 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
dcef11bd 309 $dispatcher->addSubscriber(new \Civi\API\Subscriber\APIv3SchemaAdapter());
6d3bdc98
TO
310 $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter(array(
311 \CRM_Utils_API_HTMLInputCoder::singleton(),
312 \CRM_Utils_API_NullOutputCoder::singleton(),
313 \CRM_Utils_API_ReloadOption::singleton(),
314 \CRM_Utils_API_MatchOption::singleton(),
315 )));
0661f62b 316 $dispatcher->addSubscriber(new \Civi\API\Subscriber\XDebugSubscriber());
82376c19
TO
317 $kernel = new \Civi\API\Kernel($dispatcher);
318
319 $reflectionProvider = new \Civi\API\Provider\ReflectionProvider($kernel);
320 $dispatcher->addSubscriber($reflectionProvider);
321
56154d36
TO
322 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DynamicFKAuthorization(
323 $kernel,
324 'Attachment',
325 array('create', 'get', 'delete'),
2e37a19f 326 // Given a file ID, determine the entity+table it's attached to.
56154d36
TO
327 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
328 FROM civicrm_file cf
329 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
330 WHERE cf.id = %1',
29468114
TO
331 // Get a list of custom fields (field_name,table_name,extends)
332 'SELECT concat("custom_",fld.id) as field_name,
333 grp.table_name as table_name,
334 grp.extends as extends
335 FROM civicrm_custom_field fld
336 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
337 WHERE fld.data_type = "File"
338 ',
e3e66815 339 array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
56154d36
TO
340 ));
341
82376c19
TO
342 $kernel->setApiProviders(array(
343 $reflectionProvider,
344 $magicFunctionProvider,
345 ));
346
0f643fb2
TO
347 return $kernel;
348 }
96025800 349
83617886
TO
350 /**
351 * Get a list of boot services.
352 *
353 * These are services which must be setup *before* the container can operate.
354 *
7f835399 355 * @param bool $loadFromDB
83617886
TO
356 * @throws \CRM_Core_Exception
357 */
7f835399 358 public static function boot($loadFromDB) {
56eafc21 359 // Array(string $serviceId => object $serviceInstance).
7f835399
TO
360 $bootServices = array();
361 \Civi::$statics[__CLASS__]['boot'] = &$bootServices;
d4330c62 362
56eafc21 363 $bootServices['runtime'] = $runtime = new \CRM_Core_Config_Runtime();
7f835399 364 $runtime->initialize($loadFromDB);
d4330c62 365
56eafc21 366 $bootServices['paths'] = new \Civi\Core\Paths();
d4330c62 367
7f835399 368 $class = $runtime->userFrameworkClass;
56eafc21 369 $bootServices['userSystem'] = $userSystem = new $class();
7f835399
TO
370 $userSystem->initialize();
371
372 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework;
56eafc21 373 $bootServices['userPermissionClass'] = new $userPermissionClass();
7f835399 374
56eafc21
TO
375 $bootServices['cache.settings'] = \CRM_Utils_Cache::create(array(
376 'name' => 'settings',
377 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
378 ));
7f835399 379
56eafc21 380 $bootServices['settings_manager'] = new \Civi\Core\SettingsManager($bootServices['cache.settings']);
7f835399 381
56eafc21 382 $bootServices['lockManager'] = self::createLockManager();
7f835399
TO
383
384 if ($loadFromDB && $runtime->dsn) {
3a036b15 385 \CRM_Core_DAO::init($runtime->dsn);
edbcbd96 386 \CRM_Utils_Hook::singleton(TRUE);
7f835399 387 \CRM_Extension_System::singleton(TRUE);
4025c773 388 \CRM_Extension_System::singleton(TRUE)->getClassLoader()->register();
7f835399 389
1b81ed50 390 $runtime->includeCustomPath();
391
7f835399 392 $c = new self();
56eafc21
TO
393 $container = $c->loadContainer();
394 foreach ($bootServices as $name => $obj) {
395 $container->set($name, $obj);
396 }
397 \Civi::$statics[__CLASS__]['container'] = $container;
83617886 398 }
83617886
TO
399 }
400
401 public static function getBootService($name) {
56eafc21 402 return \Civi::$statics[__CLASS__]['boot'][$name];
83617886
TO
403 }
404
4d8e83b6
TO
405 /**
406 * Determine whether the container services are available.
407 *
408 * @return bool
409 */
410 public static function isContainerBooted() {
411 return isset(\Civi::$statics[__CLASS__]['container']);
412 }
413
fa184193 414}