Merge pull request #12949 from eileenmcnaughton/activity_extract
[civicrm-core.git] / Civi / Core / Container.php
1 <?php
2 namespace Civi\Core;
3
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;
22
23 // TODO use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
24
25 /**
26 * Class Container
27 * @package Civi\Core
28 */
29 class Container {
30
31 const SELF = 'civi_container_factory';
32
33 /**
34 * @param bool $reset
35 * Whether to forcibly rebuild the entire container.
36 * @return \Symfony\Component\DependencyInjection\TaggedContainerInterface
37 */
38 public static function singleton($reset = FALSE) {
39 if ($reset || !isset(\Civi::$statics[__CLASS__]['container'])) {
40 self::boot(TRUE);
41 }
42 return \Civi::$statics[__CLASS__]['container'];
43 }
44
45 /**
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 : 'auto';
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()) {
72 $containerBuilder = $this->createContainer();
73 $containerBuilder->compile();
74 return $containerBuilder;
75 }
76
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()
87 );
88 }
89
90 require_once $file;
91 $c = new \CachedCiviContainer();
92 return $c;
93 }
94
95 /**
96 * Construct a new container.
97 *
98 * @var ContainerBuilder
99 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
100 */
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);
108
109 $container->addResource(new \Symfony\Component\Config\Resource\FileResource(__FILE__));
110
111 $container->setDefinition(self::SELF, new Definition(
112 'Civi\Core\Container',
113 array()
114 ));
115
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 // }
131
132 $container->setDefinition('angular', new Definition(
133 'Civi\Angular\Manager',
134 array()
135 ))
136 ->setFactory(array(new Reference(self::SELF), 'createAngularManager'));
137
138 $container->setDefinition('dispatcher', new Definition(
139 'Civi\Core\CiviEventDispatcher',
140 array(new Reference('service_container'))
141 ))
142 ->setFactory(array(new Reference(self::SELF), 'createEventDispatcher'));
143
144 $container->setDefinition('magic_function_provider', new Definition(
145 'Civi\API\Provider\MagicFunctionProvider',
146 array()
147 ));
148
149 $container->setDefinition('civi_api_kernel', new Definition(
150 'Civi\API\Kernel',
151 array(new Reference('dispatcher'), new Reference('magic_function_provider'))
152 ))
153 ->setFactory(array(new Reference(self::SELF), 'createApiKernel'));
154
155 $container->setDefinition('cxn_reg_client', new Definition(
156 'Civi\Cxn\Rpc\RegistrationClient',
157 array()
158 ))
159 ->setFactory('CRM_Cxn_BAO_Cxn::createRegistrationClient');
160
161 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', array()));
162
163 $basicCaches = array(
164 'js_strings' => 'js_strings',
165 'community_messages' => 'community_messages',
166 'checks' => 'checks',
167 'session' => 'CiviCRM Session',
168 'long' => 'long',
169 );
170 foreach ($basicCaches as $cacheSvc => $cacheGrp) {
171 $container->setDefinition("cache.{$cacheSvc}", new Definition(
172 'CRM_Utils_Cache_Interface',
173 array(
174 array(
175 'name' => $cacheGrp,
176 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
177 ),
178 )
179 ))->setFactory('CRM_Utils_Cache::create');
180 }
181
182 $container->setDefinition('sql_triggers', new Definition(
183 'Civi\Core\SqlTriggers',
184 array()
185 ));
186
187 $container->setDefinition('asset_builder', new Definition(
188 'Civi\Core\AssetBuilder',
189 array()
190 ));
191
192 $container->setDefinition('pear_mail', new Definition('Mail'))
193 ->setFactory('CRM_Utils_Mail::createMailer');
194
195 if (empty(\Civi::$statics[__CLASS__]['boot'])) {
196 throw new \RuntimeException("Cannot initialize container. Boot services are undefined.");
197 }
198 foreach (\Civi::$statics[__CLASS__]['boot'] as $bootService => $def) {
199 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE);
200 }
201
202 // Expose legacy singletons as services in the container.
203 $singletons = array(
204 'httpClient' => 'CRM_Utils_HttpClient',
205 'cache.default' => 'CRM_Utils_Cache',
206 'i18n' => 'CRM_Core_I18n',
207 // Maybe? 'config' => 'CRM_Core_Config',
208 // Maybe? 'smarty' => 'CRM_Core_Smarty',
209 );
210 foreach ($singletons as $name => $class) {
211 $container->setDefinition($name, new Definition(
212 $class
213 ))
214 ->setFactory(array($class, 'singleton'));
215 }
216 $container->setAlias('cache.short', 'cache.default');
217
218 $container->setDefinition('resources', new Definition(
219 'CRM_Core_Resources',
220 [new Reference('service_container')]
221 ))->setFactory(array(new Reference(self::SELF), 'createResources'));
222
223 $container->setDefinition('prevnext', new Definition(
224 'CRM_Core_PrevNextCache_Interface',
225 [new Reference('service_container')]
226 ))->setFactory(array(new Reference(self::SELF), 'createPrevNextCache'));
227
228 $container->setDefinition('prevnext.driver.sql', new Definition(
229 'CRM_Core_PrevNextCache_Sql',
230 []
231 ));
232
233 $container->setDefinition('civi.mailing.triggers', new Definition(
234 'Civi\Core\SqlTrigger\TimestampTriggers',
235 array('civicrm_mailing', 'Mailing')
236 ))->addTag('kernel.event_listener', array('event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'));
237
238 $container->setDefinition('civi.activity.triggers', new Definition(
239 'Civi\Core\SqlTrigger\TimestampTriggers',
240 array('civicrm_activity', 'Activity')
241 ))->addTag('kernel.event_listener', array('event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'));
242
243 $container->setDefinition('civi.case.triggers', new Definition(
244 'Civi\Core\SqlTrigger\TimestampTriggers',
245 array('civicrm_case', 'Case')
246 ))->addTag('kernel.event_listener', array('event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'));
247
248 $container->setDefinition('civi.case.staticTriggers', new Definition(
249 'Civi\Core\SqlTrigger\StaticTriggers',
250 array(
251 array(
252 array(
253 'upgrade_check' => array('table' => 'civicrm_case', 'column' => 'modified_date'),
254 'table' => 'civicrm_case_activity',
255 'when' => 'AFTER',
256 'event' => array('INSERT'),
257 'sql' => "\nUPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.case_id;\n",
258 ),
259 array(
260 'upgrade_check' => array('table' => 'civicrm_case', 'column' => 'modified_date'),
261 'table' => 'civicrm_activity',
262 'when' => 'BEFORE',
263 'event' => array('UPDATE', 'DELETE'),
264 '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",
265 ),
266 ),
267 )
268 ))
269 ->addTag('kernel.event_listener', array('event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo'));
270
271 $container->setDefinition('civi_token_compat', new Definition(
272 'Civi\Token\TokenCompatSubscriber',
273 array()
274 ))->addTag('kernel.event_subscriber');
275 $container->setDefinition("crm_mailing_action_tokens", new Definition(
276 "CRM_Mailing_ActionTokens",
277 array()
278 ))->addTag('kernel.event_subscriber');
279
280 foreach (array('Activity', 'Contribute', 'Event', 'Mailing', 'Member') as $comp) {
281 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
282 "CRM_{$comp}_Tokens",
283 array()
284 ))->addTag('kernel.event_subscriber');
285 }
286
287 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_SERVICES')) {
288 \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_SERVICES, array($container));
289 }
290
291 \CRM_Utils_Hook::container($container);
292
293 return $container;
294 }
295
296 /**
297 * @return \Civi\Angular\Manager
298 */
299 public function createAngularManager() {
300 return new \Civi\Angular\Manager(\CRM_Core_Resources::singleton());
301 }
302
303 /**
304 * @param ContainerInterface $container
305 * @return \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
306 */
307 public function createEventDispatcher($container) {
308 $dispatcher = new CiviEventDispatcher($container);
309 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\InstallationCanary', 'check'));
310 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\DatabaseInitializer', 'initialize'));
311 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\LocalizationInitializer', 'initialize'));
312 $dispatcher->addListener('hook_civicrm_pre', array('\Civi\Core\Event\PreEvent', 'dispatchSubevent'), 100);
313 $dispatcher->addListener('hook_civicrm_post', array('\Civi\Core\Event\PostEvent', 'dispatchSubevent'), 100);
314 $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
315 $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
316 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
317 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
318 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\Core\CiviEventInspector', 'findBuiltInEvents'));
319 // TODO We need a better code-convention for metadata about non-hook events.
320 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\API\Events', 'hookEventDefs'));
321 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs'));
322 $dispatcher->addListener('hook_civicrm_buildAsset', array('\Civi\Angular\Page\Modules', 'buildAngularModules'));
323 $dispatcher->addListener('hook_civicrm_buildAsset', array('\CRM_Utils_VisualBundle', 'buildAssetJs'));
324 $dispatcher->addListener('hook_civicrm_buildAsset', array('\CRM_Utils_VisualBundle', 'buildAssetCss'));
325 $dispatcher->addListener('civi.dao.postInsert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
326 $dispatcher->addListener('civi.dao.postUpdate', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
327 $dispatcher->addListener('civi.dao.postDelete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
328 $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
329 'CRM_Core_LegacyErrorHandler',
330 'handleException',
331 ), -200);
332 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Activity_ActionMapping', 'onRegisterActionMappings'));
333 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contact_ActionMapping', 'onRegisterActionMappings'));
334 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings'));
335 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings'));
336 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Event_ActionMapping', 'onRegisterActionMappings'));
337 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Member_ActionMapping', 'onRegisterActionMappings'));
338
339 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_LISTENERS')) {
340 \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_LISTENERS, array($dispatcher));
341 }
342
343 return $dispatcher;
344 }
345
346 /**
347 * @return LockManager
348 */
349 public static function createLockManager() {
350 // Ideally, downstream implementers could override any definitions in
351 // the container. For now, we'll make-do with some define()s.
352 $lm = new LockManager();
353 $lm
354 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
355 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
356 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createCivimailLock'))
357 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createScopedLock'));
358
359 // Registrations may use complex resolver expressions, but (as a micro-optimization)
360 // the default factory is specified as an array.
361
362 return $lm;
363 }
364
365 /**
366 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
367 * @param $magicFunctionProvider
368 *
369 * @return \Civi\API\Kernel
370 */
371 public function createApiKernel($dispatcher, $magicFunctionProvider) {
372 $dispatcher->addSubscriber(new \Civi\API\Subscriber\ChainSubscriber());
373 $dispatcher->addSubscriber(new \Civi\API\Subscriber\TransactionSubscriber());
374 $dispatcher->addSubscriber(new \Civi\API\Subscriber\I18nSubscriber());
375 $dispatcher->addSubscriber($magicFunctionProvider);
376 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
377 $dispatcher->addSubscriber(new \Civi\API\Subscriber\APIv3SchemaAdapter());
378 $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter(array(
379 \CRM_Utils_API_HTMLInputCoder::singleton(),
380 \CRM_Utils_API_NullOutputCoder::singleton(),
381 \CRM_Utils_API_ReloadOption::singleton(),
382 \CRM_Utils_API_MatchOption::singleton(),
383 )));
384 $dispatcher->addSubscriber(new \Civi\API\Subscriber\XDebugSubscriber());
385 $kernel = new \Civi\API\Kernel($dispatcher);
386
387 $reflectionProvider = new \Civi\API\Provider\ReflectionProvider($kernel);
388 $dispatcher->addSubscriber($reflectionProvider);
389
390 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DynamicFKAuthorization(
391 $kernel,
392 'Attachment',
393 array('create', 'get', 'delete'),
394 // Given a file ID, determine the entity+table it's attached to.
395 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
396 FROM civicrm_file cf
397 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
398 WHERE cf.id = %1',
399 // Get a list of custom fields (field_name,table_name,extends)
400 'SELECT concat("custom_",fld.id) as field_name,
401 grp.table_name as table_name,
402 grp.extends as extends
403 FROM civicrm_custom_field fld
404 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
405 WHERE fld.data_type = "File"
406 ',
407 array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
408 ));
409
410 $kernel->setApiProviders(array(
411 $reflectionProvider,
412 $magicFunctionProvider,
413 ));
414
415 return $kernel;
416 }
417
418 /**
419 * @param ContainerInterface $container
420 * @return \CRM_Core_Resources
421 */
422 public static function createResources($container) {
423 $sys = \CRM_Extension_System::singleton();
424 return new \CRM_Core_Resources(
425 $sys->getMapper(),
426 $container->get('cache.js_strings'),
427 \CRM_Core_Config::isUpgradeMode() ? NULL : 'resCacheCode'
428 );
429 }
430
431 /**
432 * @param ContainerInterface $container
433 * @return \CRM_Core_PrevNextCache_Interface
434 */
435 public static function createPrevNextCache($container) {
436 $cacheDriver = \CRM_Utils_Cache::getCacheDriver();
437 $service = 'prevnext.driver.' . strtolower($cacheDriver);
438 return $container->has($service)
439 ? $container->get($service)
440 : $container->get('prevnext.driver.sql');
441 }
442
443 /**
444 * Get a list of boot services.
445 *
446 * These are services which must be setup *before* the container can operate.
447 *
448 * @param bool $loadFromDB
449 * @throws \CRM_Core_Exception
450 */
451 public static function boot($loadFromDB) {
452 // Array(string $serviceId => object $serviceInstance).
453 $bootServices = array();
454 \Civi::$statics[__CLASS__]['boot'] = &$bootServices;
455
456 $bootServices['runtime'] = $runtime = new \CRM_Core_Config_Runtime();
457 $runtime->initialize($loadFromDB);
458
459 $bootServices['paths'] = new \Civi\Core\Paths();
460
461 $class = $runtime->userFrameworkClass;
462 $bootServices['userSystem'] = $userSystem = new $class();
463 $userSystem->initialize();
464
465 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework;
466 $bootServices['userPermissionClass'] = new $userPermissionClass();
467
468 $bootServices['cache.settings'] = \CRM_Utils_Cache::create(array(
469 'name' => 'settings',
470 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
471 ));
472
473 $bootServices['settings_manager'] = new \Civi\Core\SettingsManager($bootServices['cache.settings']);
474
475 $bootServices['lockManager'] = self::createLockManager();
476
477 if ($loadFromDB && $runtime->dsn) {
478 \CRM_Core_DAO::init($runtime->dsn);
479 \CRM_Utils_Hook::singleton(TRUE);
480 \CRM_Extension_System::singleton(TRUE);
481 \CRM_Extension_System::singleton(TRUE)->getClassLoader()->register();
482
483 $runtime->includeCustomPath();
484
485 $c = new self();
486 $container = $c->loadContainer();
487 foreach ($bootServices as $name => $obj) {
488 $container->set($name, $obj);
489 }
490 \Civi::$statics[__CLASS__]['container'] = $container;
491 }
492 }
493
494 public static function getBootService($name) {
495 return \Civi::$statics[__CLASS__]['boot'][$name];
496 }
497
498 /**
499 * Determine whether the container services are available.
500 *
501 * @return bool
502 */
503 public static function isContainerBooted() {
504 return isset(\Civi::$statics[__CLASS__]['container']);
505 }
506
507 }