/var/www/html_us/wp-content/plugins/woocommerce/src/Internal/Admin/Translations.php


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
<?php
/**
 * Register the scripts, and handles items needed for managing translations within WooCommerce Admin.
 */

namespace Automattic\WooCommerce\Internal\Admin;

use 
Automattic\WooCommerce\Admin\PageController;
use 
Automattic\WooCommerce\Internal\Admin\Loader;

/**
 * Translations Class.
 */
class Translations {

    
/**
     * Class instance.
     *
     * @var Translations instance
     */
    
protected static $instance null;

    
/**
     * Plugin domain.
     *
     * @var string
     */
    
private static $plugin_domain 'woocommerce';

    
/**
     * Get class instance.
     */
    
public static function get_instance() {
        if ( ! 
self::$instance ) {
            
self::$instance = new self();
        }
        return 
self::$instance;
    }

    
/**
     * Constructor.
     * Hooks added here should be removed in `wc_admin_initialize` via the feature plugin.
     */
    
public function __construct() {
        
add_action'admin_enqueue_scripts', array( $this'potentially_load_translation_script_file' ), 15 );

        
// Combine JSON translation files (from chunks) when language packs are updated.
        
add_action'upgrader_process_complete', array( $this'combine_translation_chunk_files' ), 10);

        
// Handler for WooCommerce and WooCommerce Admin plugin activation.
        
add_action'woocommerce_activated_plugin', array( $this'potentially_generate_translation_strings' ) );
        
add_action'activated_plugin', array( $this'potentially_generate_translation_strings' ) );
    }

    
/**
     * Generate a filename to cache translations from JS chunks.
     *
     * @param string $domain Text domain.
     * @param string $locale Locale being retrieved.
     * @return string Filename.
     */
    
private function get_combined_translation_filename$domain$locale ) {
        
$filename implode'-', array( $domain$localeWC_ADMIN_APP ) ) . '.json';

        return 
$filename;
    }

    
/**
     * Combines data from translation chunk files based on officially downloaded file format.
     *
     * @param array $json_i18n_filenames List of JSON chunk files.
     * @return array Combined translation chunk data.
     */
    
private function combine_official_translation_chunks$json_i18n_filenames ) {
        
// the filesystem object should be hooked up.
        
global $wp_filesystem;
        
$combined_translation_data = array();

        foreach ( 
$json_i18n_filenames as $json_filename ) {
            if ( ! 
$wp_filesystem->is_readable$json_filename ) ) {
                continue;
            }

            
$file_contents $wp_filesystem->get_contents$json_filename );
            
$chunk_data    \json_decode$file_contentstrue );

            if ( empty( 
$chunk_data ) ) {
                continue;
            }

            if ( ! isset( 
$chunk_data['comment']['reference'] ) ) {
                continue;
            }

            
$reference_file $chunk_data['comment']['reference'];

            
// Only combine "app" files (not scripts registered with WP).
            
if (
                
false === strpos$reference_fileWC_ADMIN_DIST_JS_FOLDER 'app/index.js' ) &&
                
false === strpos$reference_fileWC_ADMIN_DIST_JS_FOLDER 'chunks/' )
            ) {
                continue;
            }

            if ( empty( 
$combined_translation_data ) ) {
                
// Use the first translation file as the base structure.
                
$combined_translation_data $chunk_data;
            } else {
                
// Combine all messages from all chunk files.
                
$combined_translation_data['locale_data']['messages'] = array_merge(
                    
$combined_translation_data['locale_data']['messages'],
                    
$chunk_data['locale_data']['messages']
                );
            }
        }

        
// Remove inaccurate reference comment.
        
unset( $combined_translation_data['comment'] );
        return 
$combined_translation_data;
    }

    
/**
     * Combines data from translation chunk files based on user-generated file formats,
     * such as wp-cli tool or Loco Translate plugin.
     *
     * @param array $json_i18n_filenames List of JSON chunk files.
     * @return array Combined translation chunk data.
     */
    
private function combine_user_translation_chunks$json_i18n_filenames ) {
        
// the filesystem object should be hooked up.
        
global $wp_filesystem;
        
$combined_translation_data = array();

        foreach ( 
$json_i18n_filenames as $json_filename ) {
            if ( ! 
$wp_filesystem->is_readable$json_filename ) ) {
                continue;
            }

            
$file_contents $wp_filesystem->get_contents$json_filename );
            
$chunk_data    \json_decode$file_contentstrue );

            if ( empty( 
$chunk_data ) ) {
                continue;
            }

            
$reference_file $chunk_data['source'];

            
// Only combine "app" files (not scripts registered with WP).
            
if (
                
false === strpos$reference_fileWC_ADMIN_DIST_JS_FOLDER 'app/index.js' ) &&
                
false === strpos$reference_fileWC_ADMIN_DIST_JS_FOLDER 'chunks/' )
            ) {
                continue;
            }

            if ( empty( 
$combined_translation_data ) ) {
                
// Use the first translation file as the base structure.
                
$combined_translation_data $chunk_data;
            } else {
                
// Combine all messages from all chunk files.
                
$combined_translation_data['locale_data']['woocommerce'] = array_merge(
                    
$combined_translation_data['locale_data']['woocommerce'],
                    
$chunk_data['locale_data']['woocommerce']
                );
            }
        }

        
// Remove inaccurate reference comment.
        
unset( $combined_translation_data['source'] );
        return 
$combined_translation_data;
    }

    
/**
     * Find and combine translation chunk files.
     *
     * Only targets files that aren't represented by a registered script (e.g. not passed to wp_register_script()).
     *
     * @param string $lang_dir Path to language files.
     * @param string $domain Text domain.
     * @param string $locale Locale being retrieved.
     * @return array Combined translation chunk data.
     */
    
private function get_translation_chunk_data$lang_dir$domain$locale ) {
        
// So long as this function is called during the 'upgrader_process_complete' action,
        // the filesystem object should be hooked up.
        
global $wp_filesystem;

        
// Grab all JSON files in the current language pack.
        
$json_i18n_filenames       glob$lang_dir $domain '-' $locale '-*.json' );
        
$combined_translation_data = array();

        if ( 
false === $json_i18n_filenames ) {
            return 
$combined_translation_data;
        }

        
// Use first JSON file to determine file format. This check is required due to
        // file format difference between official language files and user translated files.
        
$format_determine_file reset$json_i18n_filenames );

        if ( ! 
$wp_filesystem->is_readable$format_determine_file ) ) {
            return 
$combined_translation_data;
        }

        
$file_contents         $wp_filesystem->get_contents$format_determine_file );
        
$format_determine_data \json_decode$file_contentstrue );

        if ( empty( 
$format_determine_data ) ) {
            return 
$combined_translation_data;
        }

        if ( isset( 
$format_determine_data['comment'] ) ) {
            return 
$this->combine_official_translation_chunks$json_i18n_filenames );
        } elseif ( isset( 
$format_determine_data['source'] ) ) {
            return 
$this->combine_user_translation_chunks$json_i18n_filenames );
        } else {
            return 
$combined_translation_data;
        }
    }

    
/**
     * Combine and save translations for a specific locale.
     *
     * Note that this assumes \WP_Filesystem is already initialized with write access.
     *
     * @param string $language_dir Path to language files.
     * @param string $plugin_domain Text domain.
     * @param string $locale Locale being retrieved.
     */
    
private function build_and_save_translations$language_dir$plugin_domain$locale ) {
        global 
$wp_filesystem;
        
$translations_from_chunks $this->get_translation_chunk_data$language_dir$plugin_domain$locale );

        if ( empty( 
$translations_from_chunks ) ) {
            return;
        }

        
$cache_filename          $this->get_combined_translation_filename$plugin_domain$locale );
        
$chunk_translations_json wp_json_encode$translations_from_chunks );

        
// Cache combined translations strings to a file.
        
$wp_filesystem->put_contents$language_dir $cache_filename$chunk_translations_json );
    }

    
/**
     * Combine translation chunks when plugin is activated.
     *
     * This function combines JSON translation data auto-extracted by GlotPress
     * from Webpack-generated JS chunks into a single file. This is necessary
     * since the JS chunks are not known to WordPress via wp_register_script()
     * and wp_set_script_translations().
     */
    
private function generate_translation_strings() {
        
$locale   determine_locale();
        
$lang_dir WP_LANG_DIR '/plugins/';

        
// Bail early if not localized.
        
if ( 'en_US' === $locale ) {
            return;
        }

        if ( ! 
function_exists'get_filesystem_method' ) ) {
            require_once 
ABSPATH 'wp-admin/includes/file.php';
        }

        
$access_type get_filesystem_method();
        if ( 
'direct' === $access_type ) {
            
\WP_Filesystem();
            
$this->build_and_save_translations$lang_dirself::$plugin_domain$locale );
        } else {
            
// I'm reluctant to add support for other filesystems here as it would require
            // user's input on activating plugin - which I don't think is common.
            
return;
        }
    }

    
/**
     * Loads the required translation scripts on the correct pages.
     */
    
public function potentially_load_translation_script_file() {
        if ( ! 
PageController::is_admin_or_embed_page() ) {
            return;
        }

        
// Grab translation strings from Webpack-generated chunks.
        
add_filter'load_script_translation_file', array( $this'load_script_translation_file' ), 10);
    }

    
/**
     * Load translation strings from language packs for dynamic imports.
     *
     * @param string $file File location for the script being translated.
     * @param string $handle Script handle.
     * @param string $domain Text domain.
     *
     * @return string New file location for the script being translated.
     */
    
public function load_script_translation_file$file$handle$domain ) {
        
// Make sure the main app script is being loaded.
        
if ( WC_ADMIN_APP !== $handle ) {
            return 
$file;
        }

        
// Make sure we're handing the correct domain.
        
if ( self::$plugin_domain !== $domain ) {
            return 
$file;
        }

        
$locale         determine_locale();
        
$cache_filename $this->get_combined_translation_filename$domain$locale );

        return 
WP_LANG_DIR '/plugins/' $cache_filename;
    }

    
/**
     * Run when plugin is activated (can be WooCommerce or WooCommerce Admin).
     *
     * @param string $filename Activated plugin filename.
     */
    
public function potentially_generate_translation_strings$filename ) {
        
$activated_plugin_domain explode'/'$filename )[0];

        
// Ensure we're only running only on activation hook that originates from our plugin.
        
if ( self::$plugin_domain === $activated_plugin_domain ) {
            
$this->generate_translation_strings();
        }
    }

    
/**
     * Combine translation chunks when files are updated.
     *
     * This function combines JSON translation data auto-extracted by GlotPress
     * from Webpack-generated JS chunks into a single file that can be used in
     * subsequent requests. This is necessary since the JS chunks are not known
     * to WordPress via wp_register_script() and wp_set_script_translations().
     *
     * @param Language_Pack_Upgrader $instance Upgrader instance.
     * @param array                  $hook_extra Info about the upgraded language packs.
     */
    
public function combine_translation_chunk_files$instance$hook_extra ) {
        if (
            ! 
is_a$instance'Language_Pack_Upgrader' ) ||
            ! isset( 
$hook_extra['translations'] ) ||
            ! 
is_array$hook_extra['translations'] )
        ) {
            return;
        }

        
$locales      = array();
        
$language_dir WP_LANG_DIR '/plugins/';

        
// Gather the locales that were updated in this operation.
        
foreach ( $hook_extra['translations'] as $translation ) {
            if (
                
'plugin' === $translation['type'] &&
                
self::$plugin_domain === $translation['slug']
            ) {
                
$locales[] = $translation['language'];
            }
        }

        
// Build combined translation files for all updated locales.
        
foreach ( $locales as $locale ) {
            
// So long as this function is hooked to the 'upgrader_process_complete' action,
            // WP_Filesystem should be hooked up to be able to call build_and_save_translations.
            
$this->build_and_save_translations$language_dirself::$plugin_domain$locale );
        }
    }
}