Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Scheduled Reminders - Pass locale through to TokenProcessor #21085

Merged
merged 5 commits into from
Aug 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 18 additions & 12 deletions CRM/Core/BAO/ActionSchedule.php
Original file line number Diff line number Diff line change
Expand Up @@ -268,19 +268,23 @@ public static function sendMailings($mappingID, $now) {

$multilingual = CRM_Core_I18n::isMultilingual();
while ($dao->fetch()) {
// switch language if necessary
if ($multilingual) {
$preferred_language = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $dao->contactID, 'preferred_language');
CRM_Core_BAO_ActionSchedule::setCommunicationLanguage($actionSchedule->communication_language, $preferred_language);
}

$errors = [];
try {
$tokenProcessor = self::createTokenProcessor($actionSchedule, $mapping);
$tokenProcessor->addRow()
$row = $tokenProcessor->addRow()
->context('contactId', $dao->contactID)
->context('actionSearchResult', (object) $dao->toArray());

// switch language if necessary
if ($multilingual) {
$preferred_language = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $dao->contactID, 'preferred_language');
$row->context('locale', CRM_Core_BAO_ActionSchedule::pickLocale($actionSchedule->communication_language, $preferred_language));
}

foreach ($tokenProcessor->evaluate()->getRows() as $tokenRow) {
// It's possible, eg, that sendReminderEmail fires Hook::alterMailParams() and that some listener use ts().
$swapLocale = empty($row->context['locale']) ? NULL : \CRM_Utils_AutoClean::swapLocale($row->context['locale']);

if ($actionSchedule->mode === 'SMS' || $actionSchedule->mode === 'User_Preference') {
CRM_Utils_Array::extend($errors, self::sendReminderSms($tokenRow, $actionSchedule, $dao->contactID));
}
Expand All @@ -293,6 +297,8 @@ public static function sendMailings($mappingID, $now) {
$caseID = empty($dao->case_id) ? NULL : $dao->case_id;
CRM_Core_BAO_ActionSchedule::createMailingActivity($tokenRow, $mapping, $dao->contactID, $dao->entityID, $caseID);
}

unset($swapLocale);
}
}
catch (\Civi\Token\TokenException $e) {
Expand Down Expand Up @@ -401,10 +407,11 @@ public static function getRecipientListing($mappingID, $recipientType) {
}

/**
* @param $communication_language
* @param $preferred_language
* @param string|null $communication_language
* @param string|null $preferred_language
* @return string
*/
public static function setCommunicationLanguage($communication_language, $preferred_language) {
public static function pickLocale($communication_language, $preferred_language) {
$currentLocale = CRM_Core_I18n::getLocale();
$language = $currentLocale;

Expand All @@ -425,8 +432,7 @@ public static function setCommunicationLanguage($communication_language, $prefer
}

// change the language
$i18n = CRM_Core_I18n::singleton();
$i18n->setLocale($language);
return $language;
}

/**
Expand Down
20 changes: 20 additions & 0 deletions CRM/Utils/AutoClean.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,26 @@ public static function with($callback) {
return $ac;
}

/**
* Temporarily set the active locale. Cleanup locale when the autoclean handle disappears.
*
* @param string|null $newLocale
* Ex: 'fr_CA'
* @return \CRM_Utils_AutoClean|null
*/
public static function swapLocale(?string $newLocale) {
$oldLocale = $GLOBALS['tsLocale'] ?? NULL;
if ($oldLocale === $newLocale) {
return NULL;
}

$i18n = \CRM_Core_I18n::singleton();
$i18n->setLocale($newLocale);
return static::with(function() use ($i18n, $oldLocale) {
$i18n->setLocale($oldLocale);
});
}

/**
* Temporarily swap values using callback functions, and cleanup
* when the current context shuts down.
Expand Down
4 changes: 4 additions & 0 deletions Civi/Token/TokenCompatSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ public function onEvaluate(TokenValueEvent $e) {
if (empty($row->context['contactId'])) {
continue;
}

unset($swapLocale);
$swapLocale = empty($row->context['locale']) ? NULL : \CRM_Utils_AutoClean::swapLocale($row->context['locale']);

/** @var int $contactId */
$contactId = $row->context['contactId'];
if (empty($row->context['contact'])) {
Expand Down
3 changes: 3 additions & 0 deletions Civi/Token/TokenProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ class TokenProcessor {
* automatically from contactId.)
* - actionSchedule: DAO, the rule which triggered the mailing
* [for CRM_Core_BAO_ActionScheduler].
* - locale: string, the name of a locale (eg 'fr_CA') to use for {ts} strings in the view.
* - schema: array, a list of fields that will be provided for each row.
* This is automatically populated with any general context
* keys, but you may need to add extra keys for token-row data.
Expand Down Expand Up @@ -351,6 +352,8 @@ public function render($name, $row) {
$row = $this->getRow($row);
}

$swapLocale = empty($row->context['locale']) ? NULL : \CRM_Utils_AutoClean::swapLocale($row->context['locale']);

$message = $this->getMessage($name);
$row->fill($message['format']);
$useSmarty = !empty($row->context['smarty']);
Expand Down
69 changes: 69 additions & 0 deletions tests/phpunit/Civi/Token/TokenProcessorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,75 @@ public function testRowTokens() {
}
}

public function testRenderLocalizedSmarty() {
$this->dispatcher->addSubscriber(new TokenCompatSubscriber());
$p = new TokenProcessor($this->dispatcher, [
'controller' => __CLASS__,
'smarty' => TRUE,
]);
$p->addMessage('text', '{ts}Yes{/ts} {ts}No{/ts}', 'text/plain');
$p->addRow([]);
$p->addRow(['locale' => 'fr_FR']);
$p->addRow(['locale' => 'es_MX']);

$expectText = [
'Yes No',
'Oui Non',
'Sí No',
];

$rowCount = 0;
foreach ($p->evaluate()->getRows() as $key => $row) {
/** @var TokenRow */
$this->assertTrue($row instanceof TokenRow);
$this->assertEquals($expectText[$key], $row->render('text'));
$rowCount++;
}
$this->assertEquals(3, $rowCount);
}

public function testRenderLocalizedHookToken() {
$cid = $this->individualCreate();

$this->dispatcher->addSubscriber(new TokenCompatSubscriber());
\Civi::dispatcher()->addListener('hook_civicrm_tokens', function($e) {
$e->tokens['trans'] = [
'trans.affirm' => ts('Translated affirmation'),
];
});
\Civi::dispatcher()->addListener('hook_civicrm_tokenValues', function($e) {
if (in_array('affirm', $e->tokens['trans'])) {
foreach ($e->contactIDs as $cid) {
$e->details[$cid]['trans.affirm'] = ts('Yes');
}
}
});

$p = new TokenProcessor($this->dispatcher, [
'controller' => __CLASS__,
'smarty' => FALSE,
]);
$p->addMessage('text', '!!{trans.affirm}!!', 'text/plain');
$p->addRow(['contactId' => $cid]);
$p->addRow(['contactId' => $cid, 'locale' => 'fr_FR']);
$p->addRow(['contactId' => $cid, 'locale' => 'es_MX']);

$expectText = [
'!!Yes!!',
'!!Oui!!',
'!!Sí!!',
];

$rowCount = 0;
foreach ($p->evaluate()->getRows() as $key => $row) {
/** @var TokenRow */
$this->assertTrue($row instanceof TokenRow);
$this->assertEquals($expectText[$key], $row->render('text'));
$rowCount++;
}
$this->assertEquals(3, $rowCount);
}

public function testGetMessageTokens() {
$p = new TokenProcessor($this->dispatcher, [
'controller' => __CLASS__,
Expand Down