Merge pull request #8177 from herbdool/backdrop-install
[civicrm-core.git] / Civi / Core / Container.php
1 <?php
2 namespace Civi\Core;
3
4 use Civi\Core\Event\SystemInstallEvent;
5 use Civi\Core\Lock\LockManager;
6 use Doctrine\Common\Annotations\AnnotationReader;
7 use Doctrine\Common\Annotations\AnnotationRegistry;
8 use Doctrine\Common\Annotations\FileCacheReader;
9 use Doctrine\Common\Cache\FilesystemCache;
10 use Doctrine\ORM\EntityManager;
11 use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
12 use Doctrine\ORM\Tools\Setup;
13 use Symfony\Component\Config\ConfigCache;
14 use Symfony\Component\DependencyInjection\ContainerBuilder;
15 use Symfony\Component\DependencyInjection\ContainerInterface;
16 use Symfony\Component\DependencyInjection\Definition;
17 use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
18 use Symfony\Component\DependencyInjection\Reference;
19 use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher;
20 use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass;
21
22 // TODO use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
23
24 /**
25 * Class Container
26 * @package Civi\Core
27 */
28 class Container {
29
30 const SELF = 'civi_container_factory';
31
32 /**
33 * @param bool $reset
34 * Whether to forcibly rebuild the entire container.
35 * @return \Symfony\Component\DependencyInjection\TaggedContainerInterface
36 */
37 public static function singleton($reset = FALSE) {
38 if ($reset || !isset(\Civi::$statics[__CLASS__]['container'])) {
39 self::boot(TRUE);
40 }
41 return \Civi::$statics[__CLASS__]['container'];
42 }
43
44 /**
45 * Find a cached container definition or construct a new one.
46 *
47 * There are many weird contexts in which Civi initializes (eg different
48 * variations of multitenancy and different permutations of CMS/CRM bootstrap),
49 * and hook_container may fire a bit differently in each context. To mitigate
50 * risk of leaks between environments, we compute a unique envID
51 * (md5(DB_NAME, HTTP_HOST, SCRIPT_FILENAME, etc)) and use separate caches for
52 * each (eg "templates_c/CachedCiviContainer.$ENVID.php").
53 *
54 * Constants:
55 * - CIVICRM_CONTAINER_CACHE -- 'always' [default], 'never', 'auto'
56 * - CIVICRM_DSN
57 * - CIVICRM_DOMAIN_ID
58 * - CIVICRM_TEMPLATE_COMPILEDIR
59 *
60 * @return ContainerInterface
61 */
62 public function loadContainer() {
63 // Note: The container's raison d'etre is to manage construction of other
64 // services. Consequently, we assume a minimal service available -- the classloader
65 // has been setup, and civicrm.settings.php is loaded, but nothing else works.
66
67 $cacheMode = defined('CIVICRM_CONTAINER_CACHE') ? CIVICRM_CONTAINER_CACHE : 'always';
68
69 // In pre-installation environments, don't bother with caching.
70 if (!defined('CIVICRM_TEMPLATE_COMPILEDIR') || !defined('CIVICRM_DSN') || $cacheMode === 'never' || \CRM_Utils_System::isInUpgradeMode()) {
71 return $this->createContainer();
72 }
73
74 $envId = \CRM_Core_Config_Runtime::getId();
75 $file = CIVICRM_TEMPLATE_COMPILEDIR . "/CachedCiviContainer.{$envId}.php";
76 $containerConfigCache = new ConfigCache($file, $cacheMode === 'auto');
77 if (!$containerConfigCache->isFresh()) {
78 $containerBuilder = $this->createContainer();
79 $containerBuilder->compile();
80 $dumper = new PhpDumper($containerBuilder);
81 $containerConfigCache->write(
82 $dumper->dump(array('class' => 'CachedCiviContainer')),
83 $containerBuilder->getResources()
84 );
85 }
86
87 require_once $file;
88 $c = new \CachedCiviContainer();
89 $c->set('service_container', $c);
90 return $c;
91 }
92
93 /**
94 * Construct a new container.
95 *
96 * @var ContainerBuilder
97 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
98 */
99 public function createContainer() {
100 $civicrm_base_path = dirname(dirname(__DIR__));
101 $container = new ContainerBuilder();
102 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
103 $container->addObjectResource($this);
104 $container->setParameter('civicrm_base_path', $civicrm_base_path);
105 //$container->set(self::SELF, $this);
106 $container->setDefinition(self::SELF, new Definition(
107 'Civi\Core\Container',
108 array()
109 ));
110
111 // TODO Move configuration to an external file; define caching structure
112 // if (empty($configDirectories)) {
113 // throw new \Exception(__CLASS__ . ': Missing required properties (civicrmRoot, configDirectories)');
114 // }
115 // $locator = new FileLocator($configDirectories);
116 // $loaderResolver = new LoaderResolver(array(
117 // new YamlFileLoader($container, $locator)
118 // ));
119 // $delegatingLoader = new DelegatingLoader($loaderResolver);
120 // foreach (array('services.yml') as $file) {
121 // $yamlUserFiles = $locator->locate($file, NULL, FALSE);
122 // foreach ($yamlUserFiles as $file) {
123 // $delegatingLoader->load($file);
124 // }
125 // }
126
127 $container->setDefinition('angular', new Definition(
128 'Civi\Angular\Manager',
129 array()
130 ))
131 ->setFactoryService(self::SELF)->setFactoryMethod('createAngularManager');
132
133 $container->setDefinition('dispatcher', new Definition(
134 'Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher',
135 array(new Reference('service_container'))
136 ))
137 ->setFactoryService(self::SELF)->setFactoryMethod('createEventDispatcher');
138
139 $container->setDefinition('magic_function_provider', new Definition(
140 'Civi\API\Provider\MagicFunctionProvider',
141 array()
142 ));
143
144 $container->setDefinition('civi_api_kernel', new Definition(
145 'Civi\API\Kernel',
146 array(new Reference('dispatcher'), new Reference('magic_function_provider'))
147 ))
148 ->setFactoryService(self::SELF)->setFactoryMethod('createApiKernel');
149
150 $container->setDefinition('cxn_reg_client', new Definition(
151 'Civi\Cxn\Rpc\RegistrationClient',
152 array()
153 ))
154 ->setFactoryClass('CRM_Cxn_BAO_Cxn')->setFactoryMethod('createRegistrationClient');
155
156 $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', array()));
157
158 foreach (array('js_strings', 'community_messages') as $cacheName) {
159 $container->setDefinition("cache.{$cacheName}", new Definition(
160 'CRM_Utils_Cache_Interface',
161 array(
162 array(
163 'name' => $cacheName,
164 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
165 ),
166 )
167 ))->setFactoryClass('CRM_Utils_Cache')->setFactoryMethod('create');
168 }
169
170 $container->setDefinition('sql_triggers', new Definition(
171 'Civi\Core\SqlTriggers',
172 array()
173 ));
174
175 $container->setDefinition('pear_mail', new Definition('Mail'))
176 ->setFactoryClass('CRM_Utils_Mail')->setFactoryMethod('createMailer');
177
178 if (empty(\Civi::$statics[__CLASS__]['boot'])) {
179 throw new \RuntimeException("Cannot initialize container. Boot services are undefined.");
180 }
181 foreach (\Civi::$statics[__CLASS__]['boot'] as $bootService => $def) {
182 $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE);
183 }
184
185 // Expose legacy singletons as services in the container.
186 $singletons = array(
187 'resources' => 'CRM_Core_Resources',
188 'httpClient' => 'CRM_Utils_HttpClient',
189 'cache.default' => 'CRM_Utils_Cache',
190 'i18n' => 'CRM_Core_I18n',
191 // Maybe? 'config' => 'CRM_Core_Config',
192 // Maybe? 'smarty' => 'CRM_Core_Smarty',
193 );
194 foreach ($singletons as $name => $class) {
195 $container->setDefinition($name, new Definition(
196 $class
197 ))
198 ->setFactoryClass($class)->setFactoryMethod('singleton');
199 }
200
201 $container->setDefinition('civi_token_compat', new Definition(
202 'Civi\Token\TokenCompatSubscriber',
203 array()
204 ))->addTag('kernel.event_subscriber');
205
206 foreach (array('Activity', 'Contribute', 'Event', 'Member') as $comp) {
207 $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
208 "CRM_{$comp}_Tokens",
209 array()
210 ))->addTag('kernel.event_subscriber');
211 }
212
213 \CRM_Utils_Hook::container($container);
214
215 return $container;
216 }
217
218 /**
219 * @return \Civi\Angular\Manager
220 */
221 public function createAngularManager() {
222 return new \Civi\Angular\Manager(\CRM_Core_Resources::singleton());
223 }
224
225 /**
226 * @param ContainerInterface $container
227 * @return \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
228 */
229 public function createEventDispatcher($container) {
230 $dispatcher = new ContainerAwareEventDispatcher($container);
231 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\InstallationCanary', 'check'));
232 $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, array('\Civi\Core\DatabaseInitializer', 'initialize'));
233 $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
234 $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
235 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
236 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
237 $dispatcher->addListener('DAO::post-insert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
238 $dispatcher->addListener('DAO::post-update', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
239 $dispatcher->addListener('DAO::post-delete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
240 $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
241 'CRM_Core_LegacyErrorHandler',
242 'handleException',
243 ));
244 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Activity_ActionMapping', 'onRegisterActionMappings'));
245 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contact_ActionMapping', 'onRegisterActionMappings'));
246 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings'));
247 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings'));
248 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Event_ActionMapping', 'onRegisterActionMappings'));
249 $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, array('CRM_Member_ActionMapping', 'onRegisterActionMappings'));
250
251 return $dispatcher;
252 }
253
254 /**
255 * @return LockManager
256 */
257 public static function createLockManager() {
258 // Ideally, downstream implementers could override any definitions in
259 // the container. For now, we'll make-do with some define()s.
260 $lm = new LockManager();
261 $lm
262 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
263 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
264 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createCivimailLock'))
265 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createScopedLock'));
266
267 // Registrations may use complex resolver expressions, but (as a micro-optimization)
268 // the default factory is specified as an array.
269
270 return $lm;
271 }
272
273 /**
274 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
275 * @param $magicFunctionProvider
276 *
277 * @return \Civi\API\Kernel
278 */
279 public function createApiKernel($dispatcher, $magicFunctionProvider) {
280 $dispatcher->addSubscriber(new \Civi\API\Subscriber\ChainSubscriber());
281 $dispatcher->addSubscriber(new \Civi\API\Subscriber\TransactionSubscriber());
282 $dispatcher->addSubscriber(new \Civi\API\Subscriber\I18nSubscriber());
283 $dispatcher->addSubscriber($magicFunctionProvider);
284 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
285 $dispatcher->addSubscriber(new \Civi\API\Subscriber\APIv3SchemaAdapter());
286 $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter(array(
287 \CRM_Utils_API_HTMLInputCoder::singleton(),
288 \CRM_Utils_API_NullOutputCoder::singleton(),
289 \CRM_Utils_API_ReloadOption::singleton(),
290 \CRM_Utils_API_MatchOption::singleton(),
291 )));
292 $dispatcher->addSubscriber(new \Civi\API\Subscriber\XDebugSubscriber());
293 $kernel = new \Civi\API\Kernel($dispatcher);
294
295 $reflectionProvider = new \Civi\API\Provider\ReflectionProvider($kernel);
296 $dispatcher->addSubscriber($reflectionProvider);
297
298 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DynamicFKAuthorization(
299 $kernel,
300 'Attachment',
301 array('create', 'get', 'delete'),
302 // Given a file ID, determine the entity+table it's attached to.
303 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
304 FROM civicrm_file cf
305 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
306 WHERE cf.id = %1',
307 // Get a list of custom fields (field_name,table_name,extends)
308 'SELECT concat("custom_",fld.id) as field_name,
309 grp.table_name as table_name,
310 grp.extends as extends
311 FROM civicrm_custom_field fld
312 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
313 WHERE fld.data_type = "File"
314 ',
315 array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
316 ));
317
318 $kernel->setApiProviders(array(
319 $reflectionProvider,
320 $magicFunctionProvider,
321 ));
322
323 return $kernel;
324 }
325
326 /**
327 * Get a list of boot services.
328 *
329 * These are services which must be setup *before* the container can operate.
330 *
331 * @param bool $loadFromDB
332 * @throws \CRM_Core_Exception
333 */
334 public static function boot($loadFromDB) {
335 // Array(string $serviceId => object $serviceInstance).
336 $bootServices = array();
337 \Civi::$statics[__CLASS__]['boot'] = &$bootServices;
338
339 $bootServices['runtime'] = $runtime = new \CRM_Core_Config_Runtime();
340 $runtime->initialize($loadFromDB);
341
342 $bootServices['paths'] = new \Civi\Core\Paths();
343
344 $class = $runtime->userFrameworkClass;
345 $bootServices['userSystem'] = $userSystem = new $class();
346 $userSystem->initialize();
347
348 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework;
349 $bootServices['userPermissionClass'] = new $userPermissionClass();
350
351 $bootServices['cache.settings'] = \CRM_Utils_Cache::create(array(
352 'name' => 'settings',
353 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
354 ));
355
356 $bootServices['settings_manager'] = new \Civi\Core\SettingsManager($bootServices['cache.settings']);
357
358 $bootServices['lockManager'] = self::createLockManager();
359
360 if ($loadFromDB && $runtime->dsn) {
361 \CRM_Core_DAO::init($runtime->dsn);
362 \CRM_Utils_Hook::singleton(TRUE);
363 \CRM_Extension_System::singleton(TRUE);
364 \CRM_Extension_System::singleton(TRUE)->getClassLoader()->register();
365
366 $runtime->includeCustomPath();
367
368 $c = new self();
369 $container = $c->loadContainer();
370 foreach ($bootServices as $name => $obj) {
371 $container->set($name, $obj);
372 }
373 \Civi::$statics[__CLASS__]['container'] = $container;
374 }
375 }
376
377 public static function getBootService($name) {
378 return \Civi::$statics[__CLASS__]['boot'][$name];
379 }
380
381 }