3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 namespace Civi\API\Subscriber
;
15 use Symfony\Component\EventDispatcher\EventSubscriberInterface
;
18 * Class I18nSubscriber
19 * @package Civi\API\Subscriber
21 class I18nSubscriber
implements EventSubscriberInterface
{
24 * Used for rolling back language to its original setting after the api call.
28 public $originalLang = [];
33 public static function getSubscribedEvents() {
35 Events
::PREPARE
=> ['onApiPrepare', Events
::W_MIDDLE
],
36 Events
::RESPOND
=> ['onApiRespond', Events
::W_LATE
],
41 * Support multi-lingual requests
43 * @param \Civi\API\Event\Event $event
44 * API preparation event.
46 * @throws \API_Exception
48 public function onApiPrepare(\Civi\API\Event\Event
$event) {
49 $apiRequest = $event->getApiRequest();
51 $params = $apiRequest['params'];
52 if ($apiRequest['version'] < 4) {
53 $language = !empty($params['options']['language']) ?
$params['options']['language'] : \CRM_Utils_Array
::value('option.language', $params);
56 $language = \CRM_Utils_Array
::value('language', $params);
59 $this->setLocale($language, $apiRequest['id']);
64 * Reset language to the default.
66 * @param \Civi\API\Event\Event $event
68 * @throws \API_Exception
70 public function onApiRespond(\Civi\API\Event\Event
$event) {
71 $apiRequest = $event->getApiRequest();
73 if (!empty($this->originalLang
[$apiRequest['id']])) {
76 $tsLocale = $this->originalLang
[$apiRequest['id']]['tsLocale'];
77 $dbLocale = $this->originalLang
[$apiRequest['id']]['dbLocale'];
82 * Sets the tsLocale and dbLocale for multi-lingual sites.
83 * Some code duplication from CRM/Core/BAO/ConfigSetting.php retrieve()
84 * to avoid regressions from refactoring.
85 * @param string $lcMessages
86 * @param int $requestId
87 * @throws \API_Exception
89 public function setLocale($lcMessages, $requestId) {
90 $domain = new \
CRM_Core_DAO_Domain();
91 $domain->id
= \CRM_Core_Config
::domainID();
94 // Check if the site is multi-lingual
95 if ($domain->locales
&& $lcMessages) {
96 // Validate language, otherwise a bad dbLocale could probably lead to sql-injection.
97 if (!array_key_exists($lcMessages, \Civi
::settings()->get('languageLimit'))) {
98 throw new \
API_Exception(ts('Language not enabled: %1', [1 => $lcMessages]));
104 // Store original value to be restored in $this->onApiRespond
105 $this->originalLang
[$requestId] = [
106 'tsLocale' => $tsLocale,
107 'dbLocale' => $dbLocale,
110 // Set suffix for table names - use views if more than one language
111 $dbLocale = "_{$lcMessages}";
113 // Also set tsLocale - CRM-4041
114 $tsLocale = $lcMessages;