Merge pull request #6712 from jitendrapurohit/CRM-17146-tests
[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 // Maybe? 'config' => 'CRM_Core_Config',
187 // Maybe? 'smarty' => 'CRM_Core_Smarty',
188 );
189 foreach ($singletons as $name => $class) {
190 $container->setDefinition($name, new Definition(
191 $class
192 ))
193 ->setFactoryClass($class)->setFactoryMethod('singleton');
194 }
195
196 \CRM_Utils_Hook::container($container);
197
198 return $container;
199 }
200
201 /**
202 * @return \Civi\Angular\Manager
203 */
204 public function createAngularManager() {
205 return new \Civi\Angular\Manager(\CRM_Core_Resources::singleton());
206 }
207
208 /**
209 * @param ContainerInterface $container
210 * @return \Symfony\Component\EventDispatcher\EventDispatcher
211 */
212 public function createEventDispatcher($container) {
213 $dispatcher = new ContainerAwareEventDispatcher($container);
214 $dispatcher->addListener('hook_civicrm_post::Activity', array('\Civi\CCase\Events', 'fireCaseChange'));
215 $dispatcher->addListener('hook_civicrm_post::Case', array('\Civi\CCase\Events', 'fireCaseChange'));
216 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\Events', 'delegateToXmlListeners'));
217 $dispatcher->addListener('hook_civicrm_caseChange', array('\Civi\CCase\SequenceListener', 'onCaseChange_static'));
218 $dispatcher->addListener('DAO::post-insert', array('\CRM_Core_BAO_RecurringEntity', 'triggerInsert'));
219 $dispatcher->addListener('DAO::post-update', array('\CRM_Core_BAO_RecurringEntity', 'triggerUpdate'));
220 $dispatcher->addListener('DAO::post-delete', array('\CRM_Core_BAO_RecurringEntity', 'triggerDelete'));
221 $dispatcher->addListener('hook_civicrm_unhandled_exception', array(
222 'CRM_Core_LegacyErrorHandler',
223 'handleException',
224 ));
225 return $dispatcher;
226 }
227
228 /**
229 * @return LockManager
230 */
231 public static function createLockManager() {
232 // Ideally, downstream implementers could override any definitions in
233 // the container. For now, we'll make-do with some define()s.
234 $lm = new LockManager();
235 $lm
236 ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
237 ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : array('CRM_Core_Lock', 'createScopedLock'))
238 ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createCivimailLock'))
239 ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : array('CRM_Core_Lock', 'createScopedLock'));
240
241 // Registrations may use complex resolver expressions, but (as a micro-optimization)
242 // the default factory is specified as an array.
243
244 return $lm;
245 }
246
247 /**
248 * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
249 * @param $magicFunctionProvider
250 *
251 * @return \Civi\API\Kernel
252 */
253 public function createApiKernel($dispatcher, $magicFunctionProvider) {
254 $dispatcher->addSubscriber(new \Civi\API\Subscriber\ChainSubscriber());
255 $dispatcher->addSubscriber(new \Civi\API\Subscriber\TransactionSubscriber());
256 $dispatcher->addSubscriber(new \Civi\API\Subscriber\I18nSubscriber());
257 $dispatcher->addSubscriber($magicFunctionProvider);
258 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
259 $dispatcher->addSubscriber(new \Civi\API\Subscriber\APIv3SchemaAdapter());
260 $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter(array(
261 \CRM_Utils_API_HTMLInputCoder::singleton(),
262 \CRM_Utils_API_NullOutputCoder::singleton(),
263 \CRM_Utils_API_ReloadOption::singleton(),
264 \CRM_Utils_API_MatchOption::singleton(),
265 )));
266 $dispatcher->addSubscriber(new \Civi\API\Subscriber\XDebugSubscriber());
267 $kernel = new \Civi\API\Kernel($dispatcher);
268
269 $reflectionProvider = new \Civi\API\Provider\ReflectionProvider($kernel);
270 $dispatcher->addSubscriber($reflectionProvider);
271
272 $dispatcher->addSubscriber(new \Civi\API\Subscriber\DynamicFKAuthorization(
273 $kernel,
274 'Attachment',
275 array('create', 'get', 'delete'),
276 // Given a file ID, determine the entity+table it's attached to.
277 'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
278 FROM civicrm_file cf
279 LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
280 WHERE cf.id = %1',
281 // Get a list of custom fields (field_name,table_name,extends)
282 'SELECT concat("custom_",fld.id) as field_name,
283 grp.table_name as table_name,
284 grp.extends as extends
285 FROM civicrm_custom_field fld
286 INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
287 WHERE fld.data_type = "File"
288 ',
289 array('civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant')
290 ));
291
292 $kernel->setApiProviders(array(
293 $reflectionProvider,
294 $magicFunctionProvider,
295 ));
296
297 return $kernel;
298 }
299
300 /**
301 * Get a list of boot services.
302 *
303 * These are services which must be setup *before* the container can operate.
304 *
305 * @param bool $loadFromDB
306 * @throws \CRM_Core_Exception
307 */
308 public static function boot($loadFromDB) {
309 $bootServices = array();
310 \Civi::$statics[__CLASS__]['boot'] = &$bootServices;
311
312 $bootServices['runtime'] = array(
313 'class' => 'CRM_Core_Config_Runtime',
314 'obj' => ($runtime = new \CRM_Core_Config_Runtime()),
315 );
316 $runtime->initialize($loadFromDB);
317
318 if ($loadFromDB && $runtime->dsn) {
319 \CRM_Core_DAO::init($runtime->dsn);
320 }
321
322 $bootServices['paths'] = array(
323 'class' => 'Civi\Core\Paths',
324 'obj' => new \Civi\Core\Paths(),
325 );
326
327 $class = $runtime->userFrameworkClass;
328 $bootServices['userSystem'] = array(
329 'class' => 'CRM_Utils_Cache_Interface',
330 'obj' => ($userSystem = new $class()),
331 );
332 $userSystem->initialize();
333
334 $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework;
335 $bootServices['userPermissionClass'] = array(
336 // Ugh, silly name.
337 'class' => 'CRM_Core_Permission_Base',
338 'obj' => new $userPermissionClass(),
339 );
340
341 $bootServices['cache.settings'] = array(
342 'class' => 'CRM_Utils_Cache_Interface',
343 'obj' => \CRM_Utils_Cache::create(array(
344 'name' => 'settings',
345 'type' => array('*memory*', 'SqlGroup', 'ArrayCache'),
346 )),
347 );
348
349 $bootServices['settings_manager'] = array(
350 'class' => 'Civi\Core\SettingsManager',
351 'obj' => new \Civi\Core\SettingsManager($bootServices['cache.settings']['obj']),
352 );
353
354 $bootServices['lockManager'] = array(
355 'class' => 'Civi\Core\Lock\LockManager',
356 'obj' => self::createLockManager(),
357 );
358
359 if ($loadFromDB && $runtime->dsn) {
360 \CRM_Extension_System::singleton(TRUE);
361
362 $c = new self();
363 \Civi::$statics[__CLASS__]['container'] = $c->loadContainer();
364 }
365 }
366
367 public static function getBootService($name) {
368 return \Civi::$statics[__CLASS__]['boot'][$name]['obj'];
369 }
370
371 }