CRM-20958 - Create activity and case triggers
[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();
40787e18
TO
92 return $c;
93 }
94
95 /**
96 * Construct a new container.
97 *
fa184193 98 * @var ContainerBuilder
77b97be7 99 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
fa184193
TO
100 */
101 public function createContainer() {
102 $civicrm_base_path = dirname(dirname(__DIR__));
103 $container = new ContainerBuilder();
40787e18
TO
104 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
105 $container->addObjectResource($this);
fa184193 106 $container->setParameter('civicrm_base_path', $civicrm_base_path);
40787e18 107 //$container->set(self::SELF, $this);
762dc04d
TO
108
109 $container->addResource(new \Symfony\Component\Config\Resource\FileResource(__FILE__));
110
40787e18
TO
111 $container->setDefinition(self::SELF, new Definition(
112 'Civi\Core\Container',
113 array()
114 ));
fa184193 115
505d8b83
TO
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)');
119 // }
120 // $locator = new FileLocator($configDirectories);
121 // $loaderResolver = new LoaderResolver(array(
122 // new YamlFileLoader($container, $locator)
123 // ));
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);
129 // }
130 // }
fa184193 131
16072ce1 132 $container->setDefinition('angular', new Definition(
40787e18 133 'Civi\Angular\Manager',
16072ce1
TO
134 array()
135 ))
d15f7e1c 136 ->setFactory(array(new Reference(self::SELF), 'createAngularManager'));
16072ce1 137
fa184193 138 $container->setDefinition('dispatcher', new Definition(
762dc04d 139 'Civi\Core\CiviEventDispatcher',
40787e18 140 array(new Reference('service_container'))
fa184193 141 ))
d15f7e1c 142 ->setFactory(array(new Reference(self::SELF), 'createEventDispatcher'));
fa184193 143
c65db512 144 $container->setDefinition('magic_function_provider', new Definition(
40787e18 145 'Civi\API\Provider\MagicFunctionProvider',
c65db512
TO
146 array()
147 ));
148
0f643fb2 149 $container->setDefinition('civi_api_kernel', new Definition(
40787e18 150 'Civi\API\Kernel',
c65db512 151 array(new Reference('dispatcher'), new Reference('magic_function_provider'))
0f643fb2 152 ))
d15f7e1c 153 ->setFactory(array(new Reference(self::SELF), 'createApiKernel'));
0f643fb2 154
7b4bbb34 155 $container->setDefinition('cxn_reg_client', new Definition(
40787e18 156 'Civi\Cxn\Rpc\RegistrationClient',
7b4bbb34
TO
157 array()
158 ))
5eda8e9b 159 ->setFactory('CRM_Cxn_BAO_Cxn::createRegistrationClient');
7b4bbb34 160
6e5ad5ee
TO
161 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', array()));
162
83617886 163 foreach (array('js_strings', 'community_messages') as $cacheName) {
a4704404
TO
164 $container->setDefinition("cache.{$cacheName}", new Definition(
165 'CRM_Utils_Cache_Interface',
166 array(
167 array(
168 'name' => $cacheName,
a944a143 169 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
a4704404
TO
170 ),
171 )
a892989e 172 ))->setFactory('CRM_Utils_Cache::create');
a4704404 173 }
3a84c0ab 174
4ed867e0
TO
175 $container->setDefinition('sql_triggers', new Definition(
176 'Civi\Core\SqlTriggers',
177 array()
178 ));
179
87e3fe24
TO
180 $container->setDefinition('asset_builder', new Definition(
181 'Civi\Core\AssetBuilder',
182 array()
183 ));
184
247eb841 185 $container->setDefinition('pear_mail', new Definition('Mail'))
a892989e 186 ->setFactory('CRM_Utils_Mail::createMailer');
247eb841 187
7f835399
TO
188 if (empty(\Civi::$statics[__CLASS__]['boot'])) {
189 throw new \RuntimeException("Cannot initialize container. Boot services are undefined.");
190 }
191 foreach (\Civi::$statics[__CLASS__]['boot'] as $bootService => $def) {
56eafc21 192 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE);
83617886
TO
193 }
194
c8074a93
TO
195 // Expose legacy singletons as services in the container.
196 $singletons = array(
197 'resources' => 'CRM_Core_Resources',
198 'httpClient' => 'CRM_Utils_HttpClient',
7b5937fe 199 'cache.default' => 'CRM_Utils_Cache',
a7c57397 200 'i18n' => 'CRM_Core_I18n',
c8074a93
TO
201 // Maybe? 'config' => 'CRM_Core_Config',
202 // Maybe? 'smarty' => 'CRM_Core_Smarty',
203 );
204 foreach ($singletons as $name => $class) {
205 $container->setDefinition($name, new Definition(
206 $class
207 ))
d15f7e1c 208 ->setFactory(array($class, 'singleton'));
c8074a93
TO
209 }
210
e0a667ad
TO
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'));
215
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'));
220
43ceab3f
TO
221 $container->setDefinition('civi_token_compat', new Definition(
222 'Civi\Token\TokenCompatSubscriber',
223 array()
224 ))->addTag('kernel.event_subscriber');
56df2d06
TO
225 $container->setDefinition("crm_mailing_action_tokens", new Definition(
226 "CRM_Mailing_ActionTokens",
227 array()
228 ))->addTag('kernel.event_subscriber');
43ceab3f 229
56df2d06 230 foreach (array('Activity', 'Contribute', 'Event', 'Mailing', 'Member') as $comp) {
46f5566c
TO
231 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
232 "CRM_{$comp}_Tokens",
233 array()
234 ))->addTag('kernel.event_subscriber');
235 }
50a23755 236
aa4343bc
TO
237 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_SERVICES')) {
238 \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_SERVICES, array($container));
239 }
240
40787e18
TO
241 \CRM_Utils_Hook::container($container);
242
fa184193
TO
243 return $container;
244 }
245
16072ce1
TO
246 /**
247 * @return \Civi\Angular\Manager
248 */
249 public function createAngularManager() {
250 return new \Civi\Angular\Manager(\CRM_Core_Resources::singleton());
251 }
252
fa184193 253 /**
40787e18 254 * @param ContainerInterface $container
43ceab3f 255 * @return \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
fa184193 256 */
40787e18 257 public function createEventDispatcher($container) {
762dc04d 258 $dispatcher = new CiviEventDispatcher($container);
0085db83 259 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\InstallationCanary', 'check'));
40d5632a 260 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\DatabaseInitializer', 'initialize'));
ece6501c 261 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\LocalizationInitializer', 'initialize'));
c73e3098
TO
262 $dispatcher->addListener('hook_civicrm_pre', array('\Civi\Core\Event\PreEvent', 'dispatchSubevent'), 100);
263 $dispatcher->addListener('hook_civicrm_post', array('\Civi\Core\Event\PostEvent', 'dispatchSubevent'), 100);
708d8fa2 264 $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
753657ed 265 $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
708d8fa2 266 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
b019b130 267 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
47e7c2f8 268 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\Core\CiviEventInspector', 'findBuiltInEvents'));
0d0031a0 269 // TODO We need a better code-convention for metadata about non-hook events.
47e7c2f8
TO
270 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\API\Events', 'hookEventDefs'));
271 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs'));
466e4b29 272 $dispatcher->addListener('hook_civicrm_buildAsset', array('\Civi\Angular\Page\Modules', 'buildAngularModules'));
94075464
TO
273 $dispatcher->addListener('civi.dao.postInsert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
274 $dispatcher->addListener('civi.dao.postUpdate', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
275 $dispatcher->addListener('civi.dao.postDelete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
46bcf597 276 $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
9ae2d27b
TO
277 'CRM_Core_LegacyErrorHandler',
278 'handleException',
c73e3098 279 ), -200);
46f5566c
TO
280 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Activity_ActionMapping', 'onRegisterActionMappings'));
281 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contact_ActionMapping', 'onRegisterActionMappings'));
2045389a 282 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings'));
b5302d4e 283 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings'));
46f5566c
TO
284 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Event_ActionMapping', 'onRegisterActionMappings'));
285 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Member_ActionMapping', 'onRegisterActionMappings'));
286
aa4343bc
TO
287 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_LISTENERS')) {
288 \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_LISTENERS, array($dispatcher));
289 }
290
fa184193
TO
291 return $dispatcher;
292 }
0f643fb2 293
10760fa1
TO
294 /**
295 * @return LockManager
296 */
83617886 297 public static function createLockManager() {
10760fa1
TO
298 // Ideally, downstream implementers could override any definitions in
299 // the container. For now, we'll make-do with some define()s.
300 $lm = new LockManager();
301 $lm
302 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
303 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
304 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createCivimailLock'))
305 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createScopedLock'));
306
307 // Registrations may use complex resolver expressions, but (as a micro-optimization)
308 // the default factory is specified as an array.
309
310 return $lm;
311 }
312
0f643fb2
TO
313 /**
314 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
2a6da8d7
EM
315 * @param $magicFunctionProvider
316 *
0f643fb2
TO
317 * @return \Civi\API\Kernel
318 */
c65db512 319 public function createApiKernel($dispatcher, $magicFunctionProvider) {
0a946de2 320 $dispatcher->addSubscriber(new \Civi\API\Subscriber\ChainSubscriber());
b55bc593 321 $dispatcher->addSubscriber(new \Civi\API\Subscriber\TransactionSubscriber());
bace5cd9 322 $dispatcher->addSubscriber(new \Civi\API\Subscriber\I18nSubscriber());
c65db512 323 $dispatcher->addSubscriber($magicFunctionProvider);
d0c9daa4 324 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
dcef11bd 325 $dispatcher->addSubscriber(new \Civi\API\Subscriber\APIv3SchemaAdapter());
6d3bdc98
TO
326 $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter(array(
327 \CRM_Utils_API_HTMLInputCoder::singleton(),
328 \CRM_Utils_API_NullOutputCoder::singleton(),
329 \CRM_Utils_API_ReloadOption::singleton(),
330 \CRM_Utils_API_MatchOption::singleton(),
331 )));
0661f62b 332 $dispatcher->addSubscriber(new \Civi\API\Subscriber\XDebugSubscriber());
82376c19
TO
333 $kernel = new \Civi\API\Kernel($dispatcher);
334
335 $reflectionProvider = new \Civi\API\Provider\ReflectionProvider($kernel);
336 $dispatcher->addSubscriber($reflectionProvider);
337
56154d36
TO
338 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DynamicFKAuthorization(
339 $kernel,
340 'Attachment',
341 array('create', 'get', 'delete'),
2e37a19f 342 // Given a file ID, determine the entity+table it's attached to.
56154d36
TO
343 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
344 FROM civicrm_file cf
345 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
346 WHERE cf.id = %1',
29468114
TO
347 // Get a list of custom fields (field_name,table_name,extends)
348 'SELECT concat("custom_",fld.id) as field_name,
349 grp.table_name as table_name,
350 grp.extends as extends
351 FROM civicrm_custom_field fld
352 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
353 WHERE fld.data_type = "File"
354 ',
e3e66815 355 array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
56154d36
TO
356 ));
357
82376c19
TO
358 $kernel->setApiProviders(array(
359 $reflectionProvider,
360 $magicFunctionProvider,
361 ));
362
0f643fb2
TO
363 return $kernel;
364 }
96025800 365
83617886
TO
366 /**
367 * Get a list of boot services.
368 *
369 * These are services which must be setup *before* the container can operate.
370 *
7f835399 371 * @param bool $loadFromDB
83617886
TO
372 * @throws \CRM_Core_Exception
373 */
7f835399 374 public static function boot($loadFromDB) {
56eafc21 375 // Array(string $serviceId => object $serviceInstance).
7f835399
TO
376 $bootServices = array();
377 \Civi::$statics[__CLASS__]['boot'] = &$bootServices;
d4330c62 378
56eafc21 379 $bootServices['runtime'] = $runtime = new \CRM_Core_Config_Runtime();
7f835399 380 $runtime->initialize($loadFromDB);
d4330c62 381
56eafc21 382 $bootServices['paths'] = new \Civi\Core\Paths();
d4330c62 383
7f835399 384 $class = $runtime->userFrameworkClass;
56eafc21 385 $bootServices['userSystem'] = $userSystem = new $class();
7f835399
TO
386 $userSystem->initialize();
387
388 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework;
56eafc21 389 $bootServices['userPermissionClass'] = new $userPermissionClass();
7f835399 390
56eafc21
TO
391 $bootServices['cache.settings'] = \CRM_Utils_Cache::create(array(
392 'name' => 'settings',
393 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
394 ));
7f835399 395
56eafc21 396 $bootServices['settings_manager'] = new \Civi\Core\SettingsManager($bootServices['cache.settings']);
7f835399 397
56eafc21 398 $bootServices['lockManager'] = self::createLockManager();
7f835399
TO
399
400 if ($loadFromDB && $runtime->dsn) {
3a036b15 401 \CRM_Core_DAO::init($runtime->dsn);
edbcbd96 402 \CRM_Utils_Hook::singleton(TRUE);
7f835399 403 \CRM_Extension_System::singleton(TRUE);
4025c773 404 \CRM_Extension_System::singleton(TRUE)->getClassLoader()->register();
7f835399 405
1b81ed50 406 $runtime->includeCustomPath();
407
7f835399 408 $c = new self();
56eafc21
TO
409 $container = $c->loadContainer();
410 foreach ($bootServices as $name => $obj) {
411 $container->set($name, $obj);
412 }
413 \Civi::$statics[__CLASS__]['container'] = $container;
83617886 414 }
83617886
TO
415 }
416
417 public static function getBootService($name) {
56eafc21 418 return \Civi::$statics[__CLASS__]['boot'][$name];
83617886
TO
419 }
420
4d8e83b6
TO
421 /**
422 * Determine whether the container services are available.
423 *
424 * @return bool
425 */
426 public static function isContainerBooted() {
427 return isset(\Civi::$statics[__CLASS__]['container']);
428 }
429
fa184193 430}