Merge pull request #9907 from eileenmcnaughton/dedupe_code
[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 $c->set('service_container', $c);
93 return $c;
94 }
95
96 /**
97 * Construct a new container.
98 *
99 * @var ContainerBuilder
100 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
101 */
102 public function createContainer() {
103 $civicrm_base_path = dirname(dirname(__DIR__));
104 $container = new ContainerBuilder();
105 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
106 $container->addObjectResource($this);
107 $container->setParameter('civicrm_base_path', $civicrm_base_path);
108 //$container->set(self::SELF, $this);
109 $container->setDefinition(self::SELF, new Definition(
110 'Civi\Core\Container',
111 array()
112 ));
113
114 // TODO Move configuration to an external file; define caching structure
115 // if (empty($configDirectories)) {
116 // throw new \Exception(__CLASS__ . ': Missing required properties (civicrmRoot, configDirectories)');
117 // }
118 // $locator = new FileLocator($configDirectories);
119 // $loaderResolver = new LoaderResolver(array(
120 // new YamlFileLoader($container, $locator)
121 // ));
122 // $delegatingLoader = new DelegatingLoader($loaderResolver);
123 // foreach (array('services.yml') as $file) {
124 // $yamlUserFiles = $locator->locate($file, NULL, FALSE);
125 // foreach ($yamlUserFiles as $file) {
126 // $delegatingLoader->load($file);
127 // }
128 // }
129
130 $container->setDefinition('angular', new Definition(
131 'Civi\Angular\Manager',
132 array()
133 ))
134 ->setFactoryService(self::SELF)->setFactoryMethod('createAngularManager');
135
136 $container->setDefinition('dispatcher', new Definition(
137 'Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher',
138 array(new Reference('service_container'))
139 ))
140 ->setFactoryService(self::SELF)->setFactoryMethod('createEventDispatcher');
141
142 $container->setDefinition('magic_function_provider', new Definition(
143 'Civi\API\Provider\MagicFunctionProvider',
144 array()
145 ));
146
147 $container->setDefinition('civi_api_kernel', new Definition(
148 'Civi\API\Kernel',
149 array(new Reference('dispatcher'), new Reference('magic_function_provider'))
150 ))
151 ->setFactoryService(self::SELF)->setFactoryMethod('createApiKernel');
152
153 $container->setDefinition('cxn_reg_client', new Definition(
154 'Civi\Cxn\Rpc\RegistrationClient',
155 array()
156 ))
157 ->setFactoryClass('CRM_Cxn_BAO_Cxn')->setFactoryMethod('createRegistrationClient');
158
159 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', array()));
160
161 foreach (array('js_strings', 'community_messages') as $cacheName) {
162 $container->setDefinition("cache.{$cacheName}", new Definition(
163 'CRM_Utils_Cache_Interface',
164 array(
165 array(
166 'name' => $cacheName,
167 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
168 ),
169 )
170 ))->setFactoryClass('CRM_Utils_Cache')->setFactoryMethod('create');
171 }
172
173 $container->setDefinition('sql_triggers', new Definition(
174 'Civi\Core\SqlTriggers',
175 array()
176 ));
177
178 $container->setDefinition('pear_mail', new Definition('Mail'))
179 ->setFactoryClass('CRM_Utils_Mail')->setFactoryMethod('createMailer');
180
181 if (empty(\Civi::$statics[__CLASS__]['boot'])) {
182 throw new \RuntimeException("Cannot initialize container. Boot services are undefined.");
183 }
184 foreach (\Civi::$statics[__CLASS__]['boot'] as $bootService => $def) {
185 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE);
186 }
187
188 // Expose legacy singletons as services in the container.
189 $singletons = array(
190 'resources' => 'CRM_Core_Resources',
191 'httpClient' => 'CRM_Utils_HttpClient',
192 'cache.default' => 'CRM_Utils_Cache',
193 'i18n' => 'CRM_Core_I18n',
194 // Maybe? 'config' => 'CRM_Core_Config',
195 // Maybe? 'smarty' => 'CRM_Core_Smarty',
196 );
197 foreach ($singletons as $name => $class) {
198 $container->setDefinition($name, new Definition(
199 $class
200 ))
201 ->setFactoryClass($class)->setFactoryMethod('singleton');
202 }
203
204 $container->setDefinition('civi_token_compat', new Definition(
205 'Civi\Token\TokenCompatSubscriber',
206 array()
207 ))->addTag('kernel.event_subscriber');
208 $container->setDefinition("crm_mailing_action_tokens", new Definition(
209 "CRM_Mailing_ActionTokens",
210 array()
211 ))->addTag('kernel.event_subscriber');
212
213 foreach (array('Activity', 'Contribute', 'Event', 'Mailing', 'Member') as $comp) {
214 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
215 "CRM_{$comp}_Tokens",
216 array()
217 ))->addTag('kernel.event_subscriber');
218 }
219
220 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_SERVICES')) {
221 \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_SERVICES, array($container));
222 }
223
224 \CRM_Utils_Hook::container($container);
225
226 return $container;
227 }
228
229 /**
230 * @return \Civi\Angular\Manager
231 */
232 public function createAngularManager() {
233 return new \Civi\Angular\Manager(\CRM_Core_Resources::singleton());
234 }
235
236 /**
237 * @param ContainerInterface $container
238 * @return \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
239 */
240 public function createEventDispatcher($container) {
241 $dispatcher = new ContainerAwareEventDispatcher($container);
242 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\InstallationCanary', 'check'));
243 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\DatabaseInitializer', 'initialize'));
244 $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
245 $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
246 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
247 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
248 $dispatcher->addListener('civi.dao.postInsert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
249 $dispatcher->addListener('civi.dao.postUpdate', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
250 $dispatcher->addListener('civi.dao.postDelete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
251 $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
252 'CRM_Core_LegacyErrorHandler',
253 'handleException',
254 ));
255 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Activity_ActionMapping', 'onRegisterActionMappings'));
256 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contact_ActionMapping', 'onRegisterActionMappings'));
257 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings'));
258 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings'));
259 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Event_ActionMapping', 'onRegisterActionMappings'));
260 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Member_ActionMapping', 'onRegisterActionMappings'));
261
262 if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_LISTENERS')) {
263 \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_LISTENERS, array($dispatcher));
264 }
265
266 return $dispatcher;
267 }
268
269 /**
270 * @return LockManager
271 */
272 public static function createLockManager() {
273 // Ideally, downstream implementers could override any definitions in
274 // the container. For now, we'll make-do with some define()s.
275 $lm = new LockManager();
276 $lm
277 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
278 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
279 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createCivimailLock'))
280 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createScopedLock'));
281
282 // Registrations may use complex resolver expressions, but (as a micro-optimization)
283 // the default factory is specified as an array.
284
285 return $lm;
286 }
287
288 /**
289 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
290 * @param $magicFunctionProvider
291 *
292 * @return \Civi\API\Kernel
293 */
294 public function createApiKernel($dispatcher, $magicFunctionProvider) {
295 $dispatcher->addSubscriber(new \Civi\API\Subscriber\ChainSubscriber());
296 $dispatcher->addSubscriber(new \Civi\API\Subscriber\TransactionSubscriber());
297 $dispatcher->addSubscriber(new \Civi\API\Subscriber\I18nSubscriber());
298 $dispatcher->addSubscriber($magicFunctionProvider);
299 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
300 $dispatcher->addSubscriber(new \Civi\API\Subscriber\APIv3SchemaAdapter());
301 $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter(array(
302 \CRM_Utils_API_HTMLInputCoder::singleton(),
303 \CRM_Utils_API_NullOutputCoder::singleton(),
304 \CRM_Utils_API_ReloadOption::singleton(),
305 \CRM_Utils_API_MatchOption::singleton(),
306 )));
307 $dispatcher->addSubscriber(new \Civi\API\Subscriber\XDebugSubscriber());
308 $kernel = new \Civi\API\Kernel($dispatcher);
309
310 $reflectionProvider = new \Civi\API\Provider\ReflectionProvider($kernel);
311 $dispatcher->addSubscriber($reflectionProvider);
312
313 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DynamicFKAuthorization(
314 $kernel,
315 'Attachment',
316 array('create', 'get', 'delete'),
317 // Given a file ID, determine the entity+table it's attached to.
318 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
319 FROM civicrm_file cf
320 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
321 WHERE cf.id = %1',
322 // Get a list of custom fields (field_name,table_name,extends)
323 'SELECT concat("custom_",fld.id) as field_name,
324 grp.table_name as table_name,
325 grp.extends as extends
326 FROM civicrm_custom_field fld
327 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
328 WHERE fld.data_type = "File"
329 ',
330 array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
331 ));
332
333 $kernel->setApiProviders(array(
334 $reflectionProvider,
335 $magicFunctionProvider,
336 ));
337
338 return $kernel;
339 }
340
341 /**
342 * Get a list of boot services.
343 *
344 * These are services which must be setup *before* the container can operate.
345 *
346 * @param bool $loadFromDB
347 * @throws \CRM_Core_Exception
348 */
349 public static function boot($loadFromDB) {
350 // Array(string $serviceId => object $serviceInstance).
351 $bootServices = array();
352 \Civi::$statics[__CLASS__]['boot'] = &$bootServices;
353
354 $bootServices['runtime'] = $runtime = new \CRM_Core_Config_Runtime();
355 $runtime->initialize($loadFromDB);
356
357 $bootServices['paths'] = new \Civi\Core\Paths();
358
359 $class = $runtime->userFrameworkClass;
360 $bootServices['userSystem'] = $userSystem = new $class();
361 $userSystem->initialize();
362
363 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework;
364 $bootServices['userPermissionClass'] = new $userPermissionClass();
365
366 $bootServices['cache.settings'] = \CRM_Utils_Cache::create(array(
367 'name' => 'settings',
368 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
369 ));
370
371 $bootServices['settings_manager'] = new \Civi\Core\SettingsManager($bootServices['cache.settings']);
372
373 $bootServices['lockManager'] = self::createLockManager();
374
375 if ($loadFromDB && $runtime->dsn) {
376 \CRM_Core_DAO::init($runtime->dsn);
377 \CRM_Utils_Hook::singleton(TRUE);
378 \CRM_Extension_System::singleton(TRUE);
379 \CRM_Extension_System::singleton(TRUE)->getClassLoader()->register();
380
381 $runtime->includeCustomPath();
382
383 $c = new self();
384 $container = $c->loadContainer();
385 foreach ($bootServices as $name => $obj) {
386 $container->set($name, $obj);
387 }
388 \Civi::$statics[__CLASS__]['container'] = $container;
389 }
390 }
391
392 public static function getBootService($name) {
393 return \Civi::$statics[__CLASS__]['boot'][$name];
394 }
395
396 }