PopulatorData
2 months ago
AccessControl.php
2 years ago
Activator.php
2 months ago
AssetsLoader.php
2 weeks ago
Capabilities.php
2 months ago
Changelog.php
2 months ago
DeactivationPoll.php
3 years ago
DeferredAdminNotices.php
2 months ago
Env.php
6 months ago
Hooks.php
4 weeks ago
HooksWooCommerce.php
1 month ago
Initializer.php
4 weeks ago
Installer.php
10 months ago
Localizer.php
3 years ago
Menu.php
1 month ago
PersonalDataErasers.php
1 month ago
PersonalDataExporters.php
1 month ago
PluginActivatedHook.php
3 years ago
Populator.php
2 weeks ago
PrivacyPolicy.php
1 month ago
Renderer.php
1 year ago
RendererFactory.php
3 years ago
RequirementsChecker.php
2 months ago
Router.php
2 months ago
ServicesChecker.php
3 years ago
Shortcodes.php
1 month ago
SilentUpgraderSkin.php
3 years ago
SubscriberChangesNotifier.php
2 months ago
TranslationUpdater.php
3 months ago
TwigEnvironment.php
1 year ago
TwigFileSystemCache.php
3 years ago
Updater.php
4 days ago
index.php
3 years ago
TranslationUpdater.php
215 lines
| 1 | <?php declare(strict_types = 1); |
| 2 | |
| 3 | namespace MailPoet\Config; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\WP\Functions as WPFunctions; |
| 9 | use MailPoetVendor\Carbon\CarbonImmutable; |
| 10 | use Tracy\Debugger; |
| 11 | use Tracy\ILogger; |
| 12 | use WP_Error; |
| 13 | |
| 14 | class TranslationUpdater { |
| 15 | const API_UPDATES_BASE_URI = 'https://translate.wordpress.com/api/translations-updates/mailpoet/'; |
| 16 | const MAILPOET_FREE_DOT_COM_PROJECT_ID = 'MailPoet - MailPoet'; |
| 17 | const TRANSIENT_KEY_PREFIX = 'mailpoet_translation_updates_'; |
| 18 | const TRANSIENT_EXPIRATION = 300; // 5 minutes |
| 19 | |
| 20 | /** @var WPFunctions */ |
| 21 | private $wpFunctions; |
| 22 | |
| 23 | /** @var string */ |
| 24 | private $freeSlug; |
| 25 | |
| 26 | /** @var string */ |
| 27 | private $freeVersion; |
| 28 | |
| 29 | /** @var string */ |
| 30 | private $premiumSlug; |
| 31 | |
| 32 | /** @var string|null */ |
| 33 | private $premiumVersion; |
| 34 | |
| 35 | public function __construct( |
| 36 | WPFunctions $wpFunctions, |
| 37 | string $freeSlug, |
| 38 | string $freeVersion, |
| 39 | string $premiumSlug, |
| 40 | ?string $premiumVersion |
| 41 | ) { |
| 42 | $this->wpFunctions = $wpFunctions; |
| 43 | $this->freeSlug = $freeSlug; |
| 44 | $this->freeVersion = $freeVersion; |
| 45 | $this->premiumSlug = $premiumSlug; |
| 46 | $this->premiumVersion = $premiumVersion; |
| 47 | } |
| 48 | |
| 49 | public function init(): void { |
| 50 | $this->wpFunctions->addFilter('pre_set_site_transient_update_plugins', [$this, 'checkForTranslations'], 21); |
| 51 | } |
| 52 | |
| 53 | public function checkForTranslations($transient) { |
| 54 | if (!$transient instanceof \stdClass) { |
| 55 | $transient = new \stdClass; |
| 56 | } |
| 57 | |
| 58 | $locales = $this->getLocales(); |
| 59 | if (empty($locales)) { |
| 60 | return $transient; |
| 61 | } |
| 62 | |
| 63 | $languagePacksData = $this->getAvailableTranslations($locales); |
| 64 | $translations = $this->selectUpdatesToInstall($languagePacksData); |
| 65 | // We want to ignore translations from .org in case a translation pack for the same locale is available from .com |
| 66 | $dotOrgTranslations = $this->removeDuplicateTranslationsFromOrg($transient->translations ?? [], $languagePacksData[$this->freeSlug] ?? []); |
| 67 | $transient->translations = array_merge($dotOrgTranslations ?? [], $translations); |
| 68 | return $transient; |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * Find available languages |
| 73 | * @return array |
| 74 | */ |
| 75 | private function getLocales(): array { |
| 76 | $locales = array_values($this->wpFunctions->getAvailableLanguages()); |
| 77 | $locales = apply_filters('plugins_update_check_locales', $locales); |
| 78 | return array_unique($locales); |
| 79 | } |
| 80 | |
| 81 | private function getAvailableTranslations(array $locales): array { |
| 82 | $requestBody = [ |
| 83 | 'locales' => $locales, |
| 84 | 'plugins' => [ |
| 85 | $this->freeSlug => ['version' => $this->freeVersion], |
| 86 | ], |
| 87 | ]; |
| 88 | if ($this->premiumVersion) { |
| 89 | $requestBody['plugins'][$this->premiumSlug] = ['version' => $this->premiumVersion]; |
| 90 | } |
| 91 | |
| 92 | $cacheKey = self::TRANSIENT_KEY_PREFIX . md5(serialize($requestBody)); |
| 93 | $rawResponse = $this->wpFunctions->getTransient($cacheKey); |
| 94 | if (!$rawResponse) { |
| 95 | $rawResponse = $this->fetchApiResponse($requestBody); |
| 96 | if ($rawResponse instanceof WP_Error) { |
| 97 | // Don't continue if there was an error. |
| 98 | $this->logError("MailPoet: Failed to fetch translations from WordPress.com API with error: " . $rawResponse->get_error_message()); |
| 99 | return []; |
| 100 | } |
| 101 | |
| 102 | $responseCode = $this->wpFunctions->wpRemoteRetrieveResponseCode($rawResponse); |
| 103 | // Wait a couple of seconds and retry when 429 is returned. |
| 104 | if ($responseCode === 429) { |
| 105 | sleep(2); |
| 106 | $rawResponse = $this->fetchApiResponse($requestBody); |
| 107 | if ($rawResponse instanceof WP_Error) { |
| 108 | // Don't continue if there was an error. |
| 109 | $this->logError("MailPoet: Failed retrying to fetch translations from WordPress.com API with error: " . $rawResponse->get_error_message()); |
| 110 | return []; |
| 111 | } |
| 112 | $responseCode = $this->wpFunctions->wpRemoteRetrieveResponseCode($rawResponse); |
| 113 | } |
| 114 | // Don't continue when API request failed. |
| 115 | if ($responseCode !== 200) { |
| 116 | $this->logError("MailPoet: Failed to fetch translations from WordPress.com API with $responseCode and response message: " . $this->wpFunctions->wpRemoteRetrieveResponseMessage($rawResponse)); |
| 117 | return []; |
| 118 | } |
| 119 | $this->wpFunctions->setTransient($cacheKey, $rawResponse, self::TRANSIENT_EXPIRATION); |
| 120 | } |
| 121 | $response = json_decode($this->wpFunctions->wpRemoteRetrieveBody($rawResponse), true); |
| 122 | if ( |
| 123 | !is_array($response) |
| 124 | || (array_key_exists('success', $response) && $response['success'] === false) |
| 125 | || !array_key_exists('data', $response) |
| 126 | || !is_array($response['data']) |
| 127 | ) { |
| 128 | $this->logError("MailPoet: Failed to fetch translations from WordPress.com API with code 200 and response: " . json_encode($response)); |
| 129 | return []; |
| 130 | } |
| 131 | return $response['data']; |
| 132 | } |
| 133 | |
| 134 | private function selectUpdatesToInstall(array $responseData) { |
| 135 | $installedTranslations = $this->wpFunctions->wpGetInstalledTranslations('plugins'); |
| 136 | $translationsToInstall = []; |
| 137 | foreach ($responseData as $pluginName => $languagePacks) { |
| 138 | foreach ($languagePacks as $languagePack) { |
| 139 | // Check revision date if translation is already installed. |
| 140 | if (array_key_exists($pluginName, $installedTranslations) && array_key_exists($languagePack['wp_locale'], $installedTranslations[$pluginName])) { |
| 141 | $installedFromWpOrg = ($pluginName === $this->freeSlug) && ($installedTranslations[$pluginName][$languagePack['wp_locale']]['Project-Id-Version'] !== self::MAILPOET_FREE_DOT_COM_PROJECT_ID); |
| 142 | $installedTranslationRevisionTime = new CarbonImmutable($installedTranslations[$pluginName][$languagePack['wp_locale']]['PO-Revision-Date']); |
| 143 | $newTranslationRevisionTime = new CarbonImmutable($languagePack['last_modified']); |
| 144 | |
| 145 | // In case installed translation pack comes from WP.org make sure that the one coming from WP.com has newer date |
| 146 | if ($installedFromWpOrg && $newTranslationRevisionTime <= $installedTranslationRevisionTime) { |
| 147 | $languagePack['last_modified'] = $installedTranslationRevisionTime->addSecond()->toDateTimeString(); |
| 148 | $newTranslationRevisionTime = new CarbonImmutable($languagePack['last_modified']); |
| 149 | } |
| 150 | |
| 151 | // Skip if translation language pack is not newer than what is installed already. |
| 152 | if ($newTranslationRevisionTime <= $installedTranslationRevisionTime) { |
| 153 | continue; |
| 154 | } |
| 155 | } |
| 156 | $translationsToInstall[] = [ |
| 157 | 'type' => 'plugin', |
| 158 | 'slug' => $pluginName, |
| 159 | 'language' => $languagePack['wp_locale'], |
| 160 | 'version' => $languagePack['version'], |
| 161 | 'updated' => $languagePack['last_modified'], |
| 162 | 'package' => $languagePack['package'], |
| 163 | 'autoupdate' => true, |
| 164 | ]; |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | return $translationsToInstall; |
| 169 | } |
| 170 | |
| 171 | private function removeDuplicateTranslationsFromOrg(array $translationsDotOrg, array $translationsDotComData) { |
| 172 | $localesAvailableFromDotCom = array_unique(array_column($translationsDotComData, 'wp_locale')); |
| 173 | return array_filter($translationsDotOrg, function ($translation) use($localesAvailableFromDotCom) { |
| 174 | if ( |
| 175 | $translation['slug'] !== $this->freeSlug |
| 176 | || !in_array($translation['language'], $localesAvailableFromDotCom, true) |
| 177 | ) { |
| 178 | return true; |
| 179 | } |
| 180 | return false; |
| 181 | }); |
| 182 | } |
| 183 | |
| 184 | protected function logError(string $message): void { |
| 185 | if (class_exists(Debugger::class) && Debugger::$logDirectory) { |
| 186 | Debugger::log($message, ILogger::ERROR); |
| 187 | } |
| 188 | if (function_exists('error_log')) { |
| 189 | // phpcs:disable QITStandard.PHP.DebugCode.DebugFunctionFound |
| 190 | error_log($message); // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged |
| 191 | // phpcs:enable QITStandard.PHP.DebugCode.DebugFunctionFound |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | /** |
| 196 | * @return array|\WP_Error |
| 197 | */ |
| 198 | private function fetchApiResponse(array $requestBody) { |
| 199 | // Ten seconds, plus one extra second for every 10 locales. |
| 200 | $timeout = 10 + (int)(count($requestBody['locales']) / 10); |
| 201 | |
| 202 | $body = wp_json_encode($requestBody); |
| 203 | if ($body === false) { |
| 204 | return new WP_Error('wp_json_encode_error', 'Failed to encode request body to retrieve translations'); |
| 205 | } |
| 206 | |
| 207 | $response = $this->wpFunctions->wpRemotePost(self::API_UPDATES_BASE_URI, [ |
| 208 | 'body' => $body, |
| 209 | 'headers' => ['Content-Type: application/json'], |
| 210 | 'timeout' => $timeout, |
| 211 | ]); |
| 212 | return $response; |
| 213 | } |
| 214 | } |
| 215 |