CRM-16373 - Bootstrap subsystems in more predictable order
[civicrm-core.git] / Civi / Core / Container.php
1 <?php
2 namespace Civi\Core;
3
4 use Civi\Core\Lock\LockManager;
5 use Doctrine\Common\Annotations\AnnotationReader;
6 use Doctrine\Common\Annotations\AnnotationRegistry;
7 use Doctrine\Common\Annotations\FileCacheReader;
8 use Doctrine\Common\Cache\FilesystemCache;
9 use Doctrine\ORM\EntityManager;
10 use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
11 use Doctrine\ORM\Tools\Setup;
12 use Symfony\Component\Config\ConfigCache;
13 use Symfony\Component\DependencyInjection\ContainerBuilder;
14 use Symfony\Component\DependencyInjection\ContainerInterface;
15 use Symfony\Component\DependencyInjection\Definition;
16 use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
17 use Symfony\Component\DependencyInjection\Reference;
18 use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher;
19 use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass;
20
21 // TODO use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
22
23 /**
24 * Class Container
25 * @package Civi\Core
26 */
27 class Container {
28
29 const SELF = 'civi_container_factory';
30
31 /**
32 * @var ContainerBuilder
33 */
34 private static $singleton;
35
36 /**
37 * @param bool $reset
38 * Whether to forcibly rebuild the entire container.
39 * @return \Symfony\Component\DependencyInjection\TaggedContainerInterface
40 */
41 public static function singleton($reset = FALSE) {
42 if ($reset || self::$singleton === NULL) {
43 $c = new self();
44 self::$singleton = $c->loadContainer();
45 }
46 return self::$singleton;
47 }
48
49 /**
50 * Find a cached container definition or construct a new one.
51 *
52 * There are many weird contexts in which Civi initializes (eg different
53 * variations of multitenancy and different permutations of CMS/CRM bootstrap),
54 * and hook_container may fire a bit differently in each context. To mitigate
55 * risk of leaks between environments, we compute a unique envID
56 * (md5(DB_NAME, HTTP_HOST, SCRIPT_FILENAME, etc)) and use separate caches for
57 * each (eg "templates_c/CachedCiviContainer.$ENVID.php").
58 *
59 * Constants:
60 * - CIVICRM_CONTAINER_CACHE -- 'always' [default], 'never', 'auto'
61 * - CIVICRM_DSN
62 * - CIVICRM_DOMAIN_ID
63 * - CIVICRM_TEMPLATE_COMPILEDIR
64 *
65 * @return ContainerInterface
66 */
67 public function loadContainer() {
68 // Note: The container's raison d'etre is to manage construction of other
69 // services. Consequently, we assume a minimal service available -- the classloader
70 // has been setup, and civicrm.settings.php is loaded, but nothing else works.
71
72 $cacheMode = defined('CIVICRM_CONTAINER_CACHE') ? CIVICRM_CONTAINER_CACHE : 'always';
73
74 // In pre-installation environments, don't bother with caching.
75 if (!defined('CIVICRM_TEMPLATE_COMPILEDIR') || !defined('CIVICRM_DSN') || $cacheMode === 'never' || \CRM_Utils_System::isInUpgradeMode()) {
76 return $this->createContainer();
77 }
78
79 $envId = \CRM_Core_Config_Runtime::getId();
80 $file = CIVICRM_TEMPLATE_COMPILEDIR . "/CachedCiviContainer.{$envId}.php";
81 $containerConfigCache = new ConfigCache($file, $cacheMode === 'auto');
82 if (!$containerConfigCache->isFresh()) {
83 $containerBuilder = $this->createContainer();
84 $containerBuilder->compile();
85 $dumper = new PhpDumper($containerBuilder);
86 $containerConfigCache->write(
87 $dumper->dump(array('class' => 'CachedCiviContainer')),
88 $containerBuilder->getResources()
89 );
90 }
91
92 require_once $file;
93 $c = new \CachedCiviContainer();
94 $c->set('service_container', $c);
95 return $c;
96 }
97
98 /**
99 * Construct a new container.
100 *
101 * @var ContainerBuilder
102 * @return \Symfony\Component\DependencyInjection\ContainerBuilder
103 */
104 public function createContainer() {
105 $civicrm_base_path = dirname(dirname(__DIR__));
106 $container = new ContainerBuilder();
107 $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
108 $container->addObjectResource($this);
109 $container->setParameter('civicrm_base_path', $civicrm_base_path);
110 //$container->set(self::SELF, $this);
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 ->setFactoryService(self::SELF)->setFactoryMethod('createAngularManager');
137
138 $container->setDefinition('dispatcher', new Definition(
139 'Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher',
140 array(new Reference('service_container'))
141 ))
142 ->setFactoryService(self::SELF)->setFactoryMethod('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 ->setFactoryService(self::SELF)->setFactoryMethod('createApiKernel');
154
155 $container->setDefinition('cxn_reg_client', new Definition(
156 'Civi\Cxn\Rpc\RegistrationClient',
157 array()
158 ))
159 ->setFactoryClass('CRM_Cxn_BAO_Cxn')->setFactoryMethod('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 ))->setFactoryClass('CRM_Utils_Cache')->setFactoryMethod('create');
173 }
174
175 $container->setDefinition('pear_mail', new Definition('Mail'))
176 ->setFactoryClass('CRM_Utils_Mail')->setFactoryMethod('createMailer');
177
178 foreach (self::getBootServices() as $bootService => $def) {
179 $container->setDefinition($bootService, new Definition($def['class'], array($bootService)))
180 ->setFactoryClass(__CLASS__)
181 ->setFactoryMethod('getBootService');
182 }
183
184 // Expose legacy singletons as services in the container.
185 $singletons = array(
186 'resources' => 'CRM_Core_Resources',
187 'httpClient' => 'CRM_Utils_HttpClient',
188 'cache.default' => 'CRM_Utils_Cache',
189 // Maybe? 'config' => 'CRM_Core_Config',
190 // Maybe? 'smarty' => 'CRM_Core_Smarty',
191 );
192 foreach ($singletons as $name => $class) {
193 $container->setDefinition($name, new Definition(
194 $class
195 ))
196 ->setFactoryClass($class)->setFactoryMethod('singleton');
197 }
198
199 \CRM_Utils_Hook::container($container);
200
201 return $container;
202 }
203
204 /**
205 * @return \Civi\Angular\Manager
206 */
207 public function createAngularManager() {
208 return new \Civi\Angular\Manager(\CRM_Core_Resources::singleton());
209 }
210
211 /**
212 * @param ContainerInterface $container
213 * @return \Symfony\Component\EventDispatcher\EventDispatcher
214 */
215 public function createEventDispatcher($container) {
216 $dispatcher = new ContainerAwareEventDispatcher($container);
217 $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
218 $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
219 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
220 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
221 $dispatcher->addListener('DAO::post-insert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
222 $dispatcher->addListener('DAO::post-update', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
223 $dispatcher->addListener('DAO::post-delete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
224 $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
225 'CRM_Core_LegacyErrorHandler',
226 'handleException',
227 ));
228 return $dispatcher;
229 }
230
231 /**
232 * @return LockManager
233 */
234 public static function createLockManager() {
235 // Ideally, downstream implementers could override any definitions in
236 // the container. For now, we'll make-do with some define()s.
237 $lm = new LockManager();
238 $lm
239 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
240 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
241 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createCivimailLock'))
242 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createScopedLock'));
243
244 // Registrations may use complex resolver expressions, but (as a micro-optimization)
245 // the default factory is specified as an array.
246
247 return $lm;
248 }
249
250 /**
251 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
252 * @param $magicFunctionProvider
253 *
254 * @return \Civi\API\Kernel
255 */
256 public function createApiKernel($dispatcher, $magicFunctionProvider) {
257 $dispatcher->addSubscriber(new \Civi\API\Subscriber\ChainSubscriber());
258 $dispatcher->addSubscriber(new \Civi\API\Subscriber\TransactionSubscriber());
259 $dispatcher->addSubscriber(new \Civi\API\Subscriber\I18nSubscriber());
260 $dispatcher->addSubscriber($magicFunctionProvider);
261 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
262 $dispatcher->addSubscriber(new \Civi\API\Subscriber\APIv3SchemaAdapter());
263 $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter(array(
264 \CRM_Utils_API_HTMLInputCoder::singleton(),
265 \CRM_Utils_API_NullOutputCoder::singleton(),
266 \CRM_Utils_API_ReloadOption::singleton(),
267 \CRM_Utils_API_MatchOption::singleton(),
268 )));
269 $dispatcher->addSubscriber(new \Civi\API\Subscriber\XDebugSubscriber());
270 $kernel = new \Civi\API\Kernel($dispatcher);
271
272 $reflectionProvider = new \Civi\API\Provider\ReflectionProvider($kernel);
273 $dispatcher->addSubscriber($reflectionProvider);
274
275 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DynamicFKAuthorization(
276 $kernel,
277 'Attachment',
278 array('create', 'get', 'delete'),
279 // Given a file ID, determine the entity+table it's attached to.
280 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
281 FROM civicrm_file cf
282 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
283 WHERE cf.id = %1',
284 // Get a list of custom fields (field_name,table_name,extends)
285 'SELECT concat("custom_",fld.id) as field_name,
286 grp.table_name as table_name,
287 grp.extends as extends
288 FROM civicrm_custom_field fld
289 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
290 WHERE fld.data_type = "File"
291 ',
292 array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
293 ));
294
295 $kernel->setApiProviders(array(
296 $reflectionProvider,
297 $magicFunctionProvider,
298 ));
299
300 return $kernel;
301 }
302
303 /**
304 * Get a list of boot services.
305 *
306 * These are services which must be setup *before* the container can operate.
307 *
308 * @return array
309 * Ex: $result['serviceName'] = array('class' => $, 'obj' => $).
310 * @throws \CRM_Core_Exception
311 */
312 public static function getBootServices() {
313 if (!isset(\Civi::$statics['*boot*'])) {
314 \Civi::$statics['*boot*']['cache.settings'] = array(
315 'class' => 'CRM_Utils_Cache_Interface',
316 'obj' => \CRM_Utils_Cache::create(array(
317 'name' => 'settings',
318 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
319 )),
320 );
321 \Civi::$statics['*boot*']['settings_manager'] = array(
322 'class' => 'Civi\Core\SettingsManager',
323 'obj' => new \Civi\Core\SettingsManager(\Civi::$statics['*boot*']['cache.settings']['obj']),
324 );
325 \Civi::$statics['*boot*']['lockManager'] = array(
326 'class' => 'Civi\Core\Lock\LockManager',
327 'obj' => self::createLockManager(),
328 );
329 }
330 return \Civi::$statics['*boot*'];
331 }
332
333 public static function getBootService($name) {
334 return \Civi::$statics['*boot*'][$name]['obj'];
335 }
336
337 }