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