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