Merge pull request #10759 from davejenx/CRM-20966
[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 : '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()) {
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 foreach (array('js_strings', 'community_messages') as $cacheName) {
164 $container->setDefinition("cache.{$cacheName}", new Definition(
165 'CRM_Utils_Cache_Interface',
166 array(
167 array(
168 'name' => $cacheName,
169 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
170 ),
171 )
172 ))->setFactory('CRM_Utils_Cache::create');
173 }
174
175 $container->setDefinition('sql_triggers', new Definition(
176 'Civi\Core\SqlTriggers',
177 array()
178 ));
179
180 $container->setDefinition('asset_builder', new Definition(
181 'Civi\Core\AssetBuilder',
182 array()
183 ));
184
185 $container->setDefinition('pear_mail', new Definition('Mail'))
186 ->setFactory('CRM_Utils_Mail::createMailer');
187
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) {
192 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE);
193 }
194
195 // Expose legacy singletons as services in the container.
196 $singletons = array(
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',
203 );
204 foreach ($singletons as $name => $class) {
205 $container->setDefinition($name, new Definition(
206 $class
207 ))
208 ->setFactory(array($class, 'singleton'));
209 }
210
211 $container->setDefinition('civi_token_compat', new Definition(
212 'Civi\Token\TokenCompatSubscriber',
213 array()
214 ))->addTag('kernel.event_subscriber');
215 $container->setDefinition("crm_mailing_action_tokens", new Definition(
216 "CRM_Mailing_ActionTokens",
217 array()
218 ))->addTag('kernel.event_subscriber');
219
220 foreach (array('Activity', 'Contribute', 'Event', 'Mailing', 'Member') as $comp) {
221 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
222 "CRM_{$comp}_Tokens",
223 array()
224 ))->addTag('kernel.event_subscriber');
225 }
226
227 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_SERVICES')) {
228 \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_SERVICES, array($container));
229 }
230
231 \CRM_Utils_Hook::container($container);
232
233 return $container;
234 }
235
236 /**
237 * @return \Civi\Angular\Manager
238 */
239 public function createAngularManager() {
240 return new \Civi\Angular\Manager(\CRM_Core_Resources::singleton());
241 }
242
243 /**
244 * @param ContainerInterface $container
245 * @return \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
246 */
247 public function createEventDispatcher($container) {
248 $dispatcher = new CiviEventDispatcher($container);
249 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\InstallationCanary', 'check'));
250 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\DatabaseInitializer', 'initialize'));
251 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\LocalizationInitializer', 'initialize'));
252 $dispatcher->addListener('hook_civicrm_pre', array('\Civi\Core\Event\PreEvent', 'dispatchSubevent'), 100);
253 $dispatcher->addListener('hook_civicrm_post', array('\Civi\Core\Event\PostEvent', 'dispatchSubevent'), 100);
254 $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
255 $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
256 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
257 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
258 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\Core\CiviEventInspector', 'findBuiltInEvents'));
259 // TODO We need a better code-convention for metadata about non-hook events.
260 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\API\Events', 'hookEventDefs'));
261 $dispatcher->addListener('hook_civicrm_eventDefs', array('\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs'));
262 $dispatcher->addListener('hook_civicrm_buildAsset', array('\Civi\Angular\Page\Modules', 'buildAngularModules'));
263 $dispatcher->addListener('civi.dao.postInsert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
264 $dispatcher->addListener('civi.dao.postUpdate', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
265 $dispatcher->addListener('civi.dao.postDelete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
266 $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
267 'CRM_Core_LegacyErrorHandler',
268 'handleException',
269 ), -200);
270 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Activity_ActionMapping', 'onRegisterActionMappings'));
271 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contact_ActionMapping', 'onRegisterActionMappings'));
272 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings'));
273 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings'));
274 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Event_ActionMapping', 'onRegisterActionMappings'));
275 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Member_ActionMapping', 'onRegisterActionMappings'));
276
277 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_LISTENERS')) {
278 \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_LISTENERS, array($dispatcher));
279 }
280
281 return $dispatcher;
282 }
283
284 /**
285 * @return LockManager
286 */
287 public static function createLockManager() {
288 // Ideally, downstream implementers could override any definitions in
289 // the container. For now, we'll make-do with some define()s.
290 $lm = new LockManager();
291 $lm
292 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
293 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
294 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createCivimailLock'))
295 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createScopedLock'));
296
297 // Registrations may use complex resolver expressions, but (as a micro-optimization)
298 // the default factory is specified as an array.
299
300 return $lm;
301 }
302
303 /**
304 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
305 * @param $magicFunctionProvider
306 *
307 * @return \Civi\API\Kernel
308 */
309 public function createApiKernel($dispatcher, $magicFunctionProvider) {
310 $dispatcher->addSubscriber(new \Civi\API\Subscriber\ChainSubscriber());
311 $dispatcher->addSubscriber(new \Civi\API\Subscriber\TransactionSubscriber());
312 $dispatcher->addSubscriber(new \Civi\API\Subscriber\I18nSubscriber());
313 $dispatcher->addSubscriber($magicFunctionProvider);
314 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
315 $dispatcher->addSubscriber(new \Civi\API\Subscriber\APIv3SchemaAdapter());
316 $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter(array(
317 \CRM_Utils_API_HTMLInputCoder::singleton(),
318 \CRM_Utils_API_NullOutputCoder::singleton(),
319 \CRM_Utils_API_ReloadOption::singleton(),
320 \CRM_Utils_API_MatchOption::singleton(),
321 )));
322 $dispatcher->addSubscriber(new \Civi\API\Subscriber\XDebugSubscriber());
323 $kernel = new \Civi\API\Kernel($dispatcher);
324
325 $reflectionProvider = new \Civi\API\Provider\ReflectionProvider($kernel);
326 $dispatcher->addSubscriber($reflectionProvider);
327
328 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DynamicFKAuthorization(
329 $kernel,
330 'Attachment',
331 array('create', 'get', 'delete'),
332 // Given a file ID, determine the entity+table it's attached to.
333 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
334 FROM civicrm_file cf
335 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
336 WHERE cf.id = %1',
337 // Get a list of custom fields (field_name,table_name,extends)
338 'SELECT concat("custom_",fld.id) as field_name,
339 grp.table_name as table_name,
340 grp.extends as extends
341 FROM civicrm_custom_field fld
342 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
343 WHERE fld.data_type = "File"
344 ',
345 array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
346 ));
347
348 $kernel->setApiProviders(array(
349 $reflectionProvider,
350 $magicFunctionProvider,
351 ));
352
353 return $kernel;
354 }
355
356 /**
357 * Get a list of boot services.
358 *
359 * These are services which must be setup *before* the container can operate.
360 *
361 * @param bool $loadFromDB
362 * @throws \CRM_Core_Exception
363 */
364 public static function boot($loadFromDB) {
365 // Array(string $serviceId => object $serviceInstance).
366 $bootServices = array();
367 \Civi::$statics[__CLASS__]['boot'] = &$bootServices;
368
369 $bootServices['runtime'] = $runtime = new \CRM_Core_Config_Runtime();
370 $runtime->initialize($loadFromDB);
371
372 $bootServices['paths'] = new \Civi\Core\Paths();
373
374 $class = $runtime->userFrameworkClass;
375 $bootServices['userSystem'] = $userSystem = new $class();
376 $userSystem->initialize();
377
378 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework;
379 $bootServices['userPermissionClass'] = new $userPermissionClass();
380
381 $bootServices['cache.settings'] = \CRM_Utils_Cache::create(array(
382 'name' => 'settings',
383 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
384 ));
385
386 $bootServices['settings_manager'] = new \Civi\Core\SettingsManager($bootServices['cache.settings']);
387
388 $bootServices['lockManager'] = self::createLockManager();
389
390 if ($loadFromDB && $runtime->dsn) {
391 \CRM_Core_DAO::init($runtime->dsn);
392 \CRM_Utils_Hook::singleton(TRUE);
393 \CRM_Extension_System::singleton(TRUE);
394 \CRM_Extension_System::singleton(TRUE)->getClassLoader()->register();
395
396 $runtime->includeCustomPath();
397
398 $c = new self();
399 $container = $c->loadContainer();
400 foreach ($bootServices as $name => $obj) {
401 $container->set($name, $obj);
402 }
403 \Civi::$statics[__CLASS__]['container'] = $container;
404 }
405 }
406
407 public static function getBootService($name) {
408 return \Civi::$statics[__CLASS__]['boot'][$name];
409 }
410
411 /**
412 * Determine whether the container services are available.
413 *
414 * @return bool
415 */
416 public static function isContainerBooted() {
417 return isset(\Civi::$statics[__CLASS__]['container']);
418 }
419
420 }