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