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