/var/www/html_it/wp-content/plugins/loco-translate/src/gettext/Data.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
<?php

loco_require_lib
('compiled/gettext.php');

/**
 * Wrapper for array forms of parsed PO data
 */
class Loco_gettext_Data extends LocoPoIterator implements JsonSerializable {

    
/**
     * Normalize file extension to internal type.
     * @return string Normalized file extension "po", "pot", "mo", "json" or "php"
     * @throws Loco_error_Exception
     */
    
public static function extLoco_fs_File $file ):string {
        
$ext rtrimstrtolower$file->extension() ), '~' );
        if( 
'po' === $ext || 'pot' === $ext || 'mo' === $ext || 'json' === $ext ){
            return 
$ext;
        }
        
// only observing the full `.l10n.php` extension as a translation format.
        
if( 'php' === $ext && '.l10n.php' === substr($file->getPath(),-9) ){
            return 
'php';
        }
        
// translators: Error thrown when attempting to parse a file that is not a supported translation file format
        
throw new Loco_error_Exceptionsprintf__('%s is not a Gettext file','loco-translate'), $file->basename() ) );
    }


    public static function 
loadLoco_fs_File $file, ?string $type null ):self {
        if( 
is_null($type) ) {
            
$type self::ext($file);
        }
        
$type strtolower($type);
        
// catch parse errors, so we can inform user of which file is bad
        
try {
            if( 
'po' === $type || 'pot' === $type ){
                return 
self::fromSource$file->getContents() );
            }
            if( 
'mo' === $type ){
                return 
self::fromBinary$file->getContents() );
            }
            if( 
'json' === $type ){
                return 
self::fromJson$file->getContents() );
            }
            if( 
'php' === $type ){
                return 
self::fromPhp$file->getPath() );
            }
            throw new 
InvalidArgumentException('No parser for '.$type.' files');
        }
        catch( 
Loco_error_ParseException $e ){
            
$path $file->getRelativePathloco_constant('WP_CONTENT_DIR') );
            
Loco_error_AdminNotices::debugsprintf('Failed to parse %s as a %s file; %s',$path,strtoupper($type),$e->getMessage()) );
            throw new 
Loco_error_ParseExceptionsprintf('Invalid %s file: %s',$type,basename($path)) );
        }
    }


    
/**
     * Like load but just pulls header, saving a full parse
     * @throws InvalidArgumentException
     */
    
public static function headLoco_fs_File $file ):?LocoPoHeaders {
        
$p = new LocoPoParser$file->getContents() );
        
$p->parse(0);
        return 
$p->getHeader();
    }


    
/**
     * @param string $src PO source
     */
    
public static function fromSourcestring $src ):self {
        
$p = new LocoPoParser($src);
        return new 
Loco_gettext_Data$p->parse() );
    }


    
/**
     * @param string $bin MO bytes
     */
    
public static function fromBinarystring $bin ):self {
        
$p = new LocoMoParser($bin);
        return new 
Loco_gettext_Data$p->parse() );
    }


    
/**
     * @param string $json Jed source
     */
    
public static function fromJsonstring $json ):self {
        
$blob json_decode$jsontrue );
        
$p = new LocoJedParser$blob['locale_data'] );
        
// note that headers outside of locale_data are won't be parsed out. we don't currently need them.
        
return new Loco_gettext_Data$p->parse() );
    }


    
/**
     * @param string $path PHP file path
     */
    
public static function fromPhpstring $path ):self {
        
$blob = include $path;
        if( ! 
is_array($blob) || ! array_key_exists('messages',$blob) ){
            throw new 
Loco_error_ParseException('Invalid PHP translation file');
        }
        
// refactor PHP structure into JED format
        
$p = new LocoMoPhpParser($blob);
        return new 
Loco_gettext_Data$p->parse() );
    }


    
/**
     * Create a dummy/empty instance with minimum content to be a valid PO file.
     */
    
public static function dummy():self {
        return new 
Loco_gettext_Data( [ ['source'=>'','target'=>'Language:'] ] );
    }


    
/**
     * Ensure PO source is UTF-8. 
     * Required if we want PO code when we're not parsing it. e.g. source view
     */
    
public static function ensureUtf8string $src ):string {
        
$src loco_remove_bom($src,$cs);
        if( ! 
$cs ){
            
// read PO header, requiring partial parse
            
try {
                
$cs LocoPoHeaders::fromSource($src)->getCharset();
            }
            catch( 
Loco_error_ParseException $e ){
                
Loco_error_AdminNotices::debug$e->getMessage() );
            }
        }
        return 
loco_convert_utf8($src,$cs,false);
    }


    
/**
     * Compile messages to binary MO format
     * @return string MO file source
     * @throws Loco_error_Exception
     */
    
public function msgfmt():string {
        if( 
!== strlen("\xC2\xA3") ){
            throw new 
Loco_error_Exception('Refusing to compile MO file. Please disable mbstring.func_overload'); // @codeCoverageIgnore
        
}
        
$mo = new LocoMo$this$this->getHeaders() );
        
$opts Loco_data_Settings::get();
        if( 
$opts->gen_hash ){
            
$mo->enableHash();
        }
        if( 
$opts->use_fuzzy ){
            
$mo->useFuzzy();
        }
        
/*/ TODO optionally exclude .js strings
        if( $opts->purge_js ){
            $mo->filter....
        }*/
        
return $mo->compile();
    }


    
/**
     * Get final UTF-8 string for writing to file
     * @param bool $sort Whether to sort output, generally only for extracting strings
     */
    
public function msgcatbool $sort false ):string {
        
// set maximum line width, zero or >= 15
        
$this->wrapLoco_data_Settings::get()->po_width );
        
// concat with default text sorting if specified
        
$po $this->render$sort ? [ 'LocoPoIterator''compare' ] : null );
        
// Prepend byte order mark only if configured
        
if( Loco_data_Settings::get()->po_utf8_bom ){
            
$po "\xEF\xBB\xBF".$po;
        }
        return 
$po;
    }


    
/**
     * Compile JED flavour JSON
     * @param string $domain text domain for JED metadata
     * @param string $source reference to file that uses included strings
     * @return string JSON source, or empty if JED file has no entries
     */
    
public function msgjedstring $domain 'messages'string $source '' ):string {
        
// note that JED is sparse, like MO. We won't write empty files.
        
$data $this->exportJed();
        if( 
>= count($data) ){
            return 
'';
        }
        
$head $this->getHeaders();
        
$head['domain'] = $domain;
        
// Pretty formatting for debugging. Doing as per WordPress and always escaping Unicode.
        
$json_options 0;
        if( 
Loco_data_Settings::get()->jed_pretty ){
            
$json_options |= loco_constant('JSON_PRETTY_PRINT') | loco_constant('JSON_UNESCAPED_SLASHES'); // | loco_constant('JSON_UNESCAPED_UNICODE');
        
}
        
// PO should have a date if localised properly
        
return json_encode(  [
            
'translation-revision-date' => $head['PO-Revision-Date'],
            
'generator' => $head['X-Generator'],
            
'source' => $source,
            
'domain' => $domain,
            
'locale_data' =>  [
                
$domain => $data,
            ],
        ], 
$json_options );
    }


    
/**
     * @return array
     */
    
#[ReturnTypeWillChange]
    public function 
jsonSerialize(){
        
$po $this->getArrayCopy();
        
// exporting headers non-scalar so js doesn't have to parse them
        
try {
            
$headers $this->getHeaders();
            if( 
count($headers) && '' === $po[0]['source'] ){
                
$po[0]['target'] = $headers->getArrayCopy();
            }
        }
        
// suppress header errors when serializing
        // @codeCoverageIgnoreStart
        
catch( Exception $e ){ }
        
// @codeCoverageIgnoreEnd
        
return $po;
    }
    
    


    
/**
     * Create a signature for use in comparing source strings between documents
     */
    
public function getSourceDigest():string {
        
$data $this->getHashes();
        return 
md5implode("\1",$data) );
    }

    
    
/** 
     * @param string[] $custom custom headers
     */
    
public function localizeLoco_Locale $locale, array $custom = [] ):self {
        
$date gmdate('Y-m-d H:i').'+0000';
        
// headers that must always be set if absent
        
$defaults =  [
            
'Project-Id-Version' => '',
            
'Report-Msgid-Bugs-To' => '',
            
'POT-Creation-Date' => $date,
        ];
        
// headers that must always override when localizing
        
$required =  [
            
'PO-Revision-Date' => $date,
            
'Last-Translator' => '',
            
'Language-Team' => $locale->getName(),
            
'Language' => (string) $locale,
            
'Plural-Forms' => $locale->getPluralFormsHeader(),
            
'MIME-Version' => '1.0',
            
'Content-Type' => 'text/plain; charset=UTF-8',
            
'Content-Transfer-Encoding' => '8bit',
            
'X-Generator' => 'Loco https://localise.biz/',
            
'X-Loco-Version' => sprintf('%s; wp-%s; php-%s'loco_plugin_version(), $GLOBALS['wp_version'], PHP_VERSION ),
        ];
        
// Allow some existing headers to remain if PO was previously localized to the same language
        
$headers $this->getHeaders();
        
$previous Loco_Locale::parse$headers->trimmed('Language') );
        if( 
$previous->lang === $locale->lang ){
            
$header $headers->trimmed('Plural-Forms');
            if( 
preg_match('/^\\s*nplurals\\s*=\\s*\\d+\\s*;\\s*plural\\s*=/'$header) ) {
                
$required['Plural-Forms'] = $header;
            }
            if( 
$previous->region === $locale->region && $previous->variant === $locale->variant ){
                unset( 
$required['Language-Team'] );
            }
        }
        
// set user's preferred Last-Translator credit if configured
        
if( function_exists('get_current_user_id') && get_current_user_id() ){
            
$prefs Loco_data_Preferences::get();
            
$credit = (string) $prefs->credit;
            if( 
'' === $credit ){
                
$credit $prefs->default_credit();
            }
            
// filter credit with current username and email
            
$user wp_get_current_user();
            
$credit apply_filters'loco_current_translator'$credit$user->get('display_name'), $user->get('email') );
            if( 
'' !== $credit ){
                
$required['Last-Translator'] = $credit;
            }
        }
        
$headers $this->applyHeaders($required,$defaults,$custom);
        
// avoid non-empty POT placeholders that won't have been set from $defaults
        
if( 'PACKAGE VERSION' === $headers['Project-Id-Version'] ){
            
$headers['Project-Id-Version'] = '';
        }
        
// finally allow headers to be modified via filter
        
$replaced apply_filters'loco_po_headers'$headers );
        if( 
$replaced instanceof LocoPoHeaders && $replaced !== $headers ){
            
$this->setHeaders($replaced);
        }
        return 
$this->initPo();
    }


    public function 
templatizestring $domain '' ):self {
        
$date gmdate('Y-m-d H:i').'+0000'// <- forcing UCT
        
$defaults =  [
            
'Project-Id-Version' => 'PACKAGE VERSION',
            
'Report-Msgid-Bugs-To' => '',
        ];
        
$required =  [
            
'POT-Creation-Date' => $date,
            
'PO-Revision-Date' => 'YEAR-MO-DA HO:MI+ZONE',
            
'Last-Translator' => 'FULL NAME <EMAIL@ADDRESS>',
            
'Language-Team' => '',
            
'Language' => '',
            
'Plural-Forms' => 'nplurals=INTEGER; plural=EXPRESSION;',
            
'MIME-Version' => '1.0',
            
'Content-Type' => 'text/plain; charset=UTF-8',
            
'Content-Transfer-Encoding' => '8bit',
            
'X-Generator' => 'Loco https://localise.biz/',
            
'X-Loco-Version' => sprintf('%s; wp-%s; php-%s'loco_plugin_version(), $GLOBALS['wp_version'], PHP_VERSION ),

            
'X-Domain' => $domain,
        ];
        
$headers $this->applyHeaders($required,$defaults);
        
// finally allow headers to be modified via filter
        
$replaced apply_filters'loco_pot_headers'$headers );
        if( 
$replaced instanceof LocoPoHeaders && $replaced !== $headers ){
            
$this->setHeaders($replaced);
        }
        return 
$this->initPot();
    }


    private function 
applyHeaders( array $required = [], array $defaults = [], array $custom = [] ):LocoPoHeaders {
        
$headers $this->getHeaders();
        
// only set absent or empty headers from default list
        
foreach( $defaults as $key => $value ){
            if( ! 
$headers[$key] ){
                
$headers[$key] = $value;
            }
        }
        
// add required headers with custom ones overriding
        
if( $custom ){
            
$required array_merge$required$custom );
        }
        
// TODO fix ordering weirdness here. required headers seem to get appended wrongly
        
foreach( $required as $key => $value ){
            
$headers[$key] = $value;
        }
        return 
$headers;
    }


    
/**
     * Remap proprietary base path when PO file is moving to another location.
     * 
     * @param Loco_fs_File $origin the file that was originally extracted to (POT)
     * @param Loco_fs_File $target the file that must now target references relative to itself
     * @param string $vendor name used in header keys
     * @return bool whether base header was altered
     */
    
public function rebaseHeaderLoco_fs_File $originLoco_fs_File $targetstring $vendor ):bool {
        
$base $target->getParent();
        
$head $this->getHeaders();
        
$key $head->normalize('X-'.$vendor.'-Basepath');
        if( 
$key ){
            
$oldRelBase $head[$key];    
            
$oldAbsBase = new Loco_fs_Directory($oldRelBase);
            
$oldAbsBase->normalize$origin->getParent() );
            
$newRelBase $oldAbsBase->getRelativePath($base);
            
// new base path is relative to $target location 
            
$head[$key] = $newRelBase;
            return 
true;
        }
        return 
false;
    }


    
/**
     * Inherit meta values from header given, but leave standard headers intact.
     */
    
public function inheritHeaderLocoPoHeaders $source ):void {
        
$target $this->getHeaders();
        foreach( 
$source as $key => $value ){
            if( 
'X-' === substr($key,0,2) ) {
                
$target[$key] = $value;
            }
        }
    }


    
/**
     * @param string $podate Gettext data formatted "YEAR-MO-DA HO:MI+ZONE"
     */
    
public static function parseDatestring $podate ):int {
        if( 
method_exists('DateTime','createFromFormat') ){
            
$objdate DateTime::createFromFormat('Y-m-d H:iO'$podate);
            if( 
$objdate instanceof DateTime ){
                return 
$objdate->getTimestamp();
            }
        }
        return 
strtotime($podate);
    }