JFIF    $         d d  7    * Z qn )ZP 0   !1 A "#a$2Qr   D8 a Ri [f  \m I ykI w0 c u F c Rı?lO7 к _f˓ [C $殷WF< _W ԣ s Kc ëI zyQy /_LK ℂ ;C",p F A : /] =H  ~ , l s / 9  ć: [=/#f ; ) x { ٛE Q )~     = 𘙲r*2~  a _V = '  ku m F  D } KYYC )( { * g& f `툪 r y ` = ^ c J. I ]( * `wq  1dđ #̩ ͑ 0  ; H ] u 搂 @:~ ו K L  N s h } O I R* 8 :2 ! lD JV o (  3 = M ( z Ȱ+i *N A  r6K n S l ) ! J J Ӂ* %  ݉?|D } d5: eP0 R; {$X' x F @ .ÊB {,WJ uQ ɲRI ;9 Q E琯 6 2fT .DU J ;*c  P A\IL Nj! J ۱+ O\ ͔ ] ޒ S߼ J ȧ c%A N ol  ՎprU L Zԛe r E2= X D Xg VQeӓ k y P7 U* o m Q I s ,K `) 6\G3t?pgjr m ۛجw luGt f  h 9uyP 0D;Uڽ"OXl i f $ ) &|ML 0 Z rm1 [ H XP l P R0  'G=i 2N +0 e 2 ]] 9 VT P  O׮ 7 h(F * 癈 ' = Q VZD F,d ߬ ~ T X G[ `le 69C R(!S2! P  < 0 x <     !1AQ "Raq 02Br #S CTb  ? Ζ "]mH5WR 7 k.ۛ ! } Q~ + yԏ z |@ T20 S~ K e k *zF f^2X *( @ 8 r ? C I uI|֓>^Ex LgNU Y+{.R Ѫ τV׸ YT D I 6 2 '8Y2  7'\T P.6 d &˦ @V q i  |8 -O Ε  ] ʔ U=   T L 8= ;6c |  !qfF3 a ů& ~$ l} 'NW U s$U k^S V : U# 6w +  +s &r+n ڐ   { @ 29 gL u " T Ù  M=6  (^ "7 r}=6Yݾ lC u hquymp Ǧ G jhs ǜNl ɻ} o 7 #S6 a w 4 !  OS  r D  5 7 % | ?x> L |  / nD 6?/8 w # [ ) L 7 +6〼T A T g   !  %5  Mm Z /c  -{1_Je "| ^$ 'O  & ޱմ < H vNqϡQ$ < 6 &Nݛ ֨tǻN (9 n ru~'όN sMG& ,uH Kw *Ī 5@  u6  BԒ  i YN * f 0 _ GhKW u  lT <nj- 0{  M L~ | /a v\ E = ?1 \ɟuq Ђ Y O a K ޡP q  $ H8o Q˼EV ~ k 0 h' L  Pp M -M"  m^ !6l nմ 쮝C U T . ! :vMǨb h ډ Vc r @񄞅~p   #   !1QAa q  ? AL0L  x LU 4 d ; x   " 16ad0 7.\ߋ 0  = P l v/ " c A Ay A|2pO8"d MV #1] = \ " ˡ ] k v I9 d ۓ & q ) ǐq E ꞅ v "P )q X  &Q  З non]я u ג./ ; gZ$ M QР 2M ]h ni 0  P $ێ 3CɏGjώy : m c # S_ l@ '_ \m|C 2`K _  1 cIvGc $? PCQ S+D ? K aײ k Fr b 8 ύ NEدg ĝ U 3  6 #Ik+ v  {ƒ v i ( ވ  ? a e)  X xy/*@Q Ǽ Ծ ) $ IWO l c G;  !i  k{ gOŀ L ('x  T rb $ w) R $ & N1E td U3Uȉ1p M"N* (DNy d96.(jQ)  X 5 c QɎMy W ?  Q *!R > 6=7)Xj 5`J ] e  8%t ! + ' ! 1Q 5   !1 AQaq ё #2 "0BRb ? G t^ ## .l lQ T $  v , ,m   㵜5u bV  =sY+ @d { N ! dn O < .- B;  _w J t 6;Q  Jd. Q c%p{ 1 ,sND dF H I0 Гo X ш  e黅X ۢ F :)[ F G X ƹ / w _c MeD   ,ʡc c .  W D  tA $ j@ : ) - # u c1< @ۗ9F ) KJ- hpP] _ x [ q B lb p ʖ w q " LFGd ƶ * s +ډ_Zc " ? % t[I P  6 J ]# =ɺ V v v CGs Gh1 > )6 |e y ? L ӣ m,4 G W Ui ` ] uJVo VDG< SB 6ϏQ @ TiU l y O U 0 kfV ~ ~}S Z @ *WU Ui ## ; s /[ = ! 7}" W N ] ' (L !  ~ y5 g9T̅J kbM' +s :S +B) v @ M  j e C f j E 0  Y\Qn z G 1 д~ W o{T 9?`  Rm yhsy3 !HAD ] m  c1 ~ 2 L  S u7x T ;j$ `} 4-> L#  vzŏ I L S  ֭  T { r  jGK C ; b  pU= - ` Bs K. S F w4  M q] Z dH S 0 ) tLg Tiny File Manager | Compiler.php
  • File: Compiler.php
  • Full Path: /home/mata8712/public_html/on-me-trouve/wp-content/plugins/loco-translate/src/gettext/Compiler.php
  • File size: 12.45 KB
  • MIME-type: text/x-php
  • Charset: utf-8
<?php
/**
 * Utility for compiling PO data to MO AND JSON files
 */
class Loco_gettext_Compiler {

    /**
     * @var Loco_api_WordPressFileSystem|null
     */
    private $fs;

    /**
     * Target file group, where we're compiling to
     * @var Loco_fs_Siblings
     */
    private $files;

    /**
     * Result when files written
     * @var Loco_fs_FileList
     */
    private $done;
    
    /**
     * @var Loco_mvc_ViewParams
     */
    private $progress;
    

    /**
     * Construct with primary file (PO) being saved
     * @param Loco_fs_File $pofile Localised PO file which may or may not exist yet
     */
    public function __construct( Loco_fs_File $pofile ){
        $this->files = new Loco_fs_Siblings($pofile);
        $this->progress = new Loco_mvc_ViewParams( [
            'pobytes' => 0,
            'mobytes' => 0,
            'numjson' => 0,
            'phbytes' => 0,
        ] );
        // Connect compiler to the file system, if writing to disk for real
        if( ! $pofile instanceof Loco_fs_DummyFile ) {
            $this->fs = new Loco_api_WordPressFileSystem;
        }
        $this->done = new Loco_fs_FileList;
    }


    /**
     * Write PO, MO and JSON siblings
     */
    public function writeAll( Loco_gettext_Data $po, ?Loco_package_Project $project = null ):Loco_fs_FileList {
        $this->writePo($po);
        $this->writeMo($po);
        if( $project ){
            $this->writeJson($project,$po);
        }
        return $this->done;
    }


    /**
     * @return int bytes written to PO file
     * @throws Loco_error_WriteException
     */
    public function writePo( Loco_gettext_Data $po ):int {
        $file = $this->files->getSource();
        // Perform PO file backup before overwriting an existing PO
        if( $file->exists() && $this->fs ){
            $backups = new Loco_fs_Revisions($file);
            $backup = $backups->rotate($this->fs);
            // debug backup creation only under cli. too noisy otherwise
            if( $backup && 'cli' === PHP_SAPI && $backup->exists() ){
                Loco_error_AdminNotices::debug( sprintf('Wrote backup: %s -> %s',$file->basename(),$backup->basename() ) );
            }
        }
        $bytes = $this->writeFile( $file, $po->msgcat() );
        $this->progress['pobytes'] = $bytes;
        return $bytes;
    }


    /**
     * @return int bytes written to MO file
     */
    public function writeMo( Loco_gettext_Data $po ):int {
        try {
            $mofile = $this->files->getBinary();
            $bytes = $this->writeFile( $mofile, $po->msgfmt() );
        }
        catch( Exception $e ){
            Loco_error_AdminNotices::debug( $e->getMessage() );
            Loco_error_AdminNotices::warn( __('PO file saved, but MO file compilation failed','loco-translate') );
            $bytes = 0;
        }
        $this->progress['mobytes'] = $bytes;
        // write PHP cache, if WordPress >= 6.5
        if( 0 !== $bytes ){
            try {
                $this->progress['phbytes'] = $this->writePhp($po);
            }
            catch( Exception $e ){
                Loco_error_AdminNotices::debug( $e->getMessage() );
            }
        }
        return $bytes;
    }


    /**
     * @return int bytes written to .l10n.php file
     */
    private function writePhp( Loco_gettext_Data $po ):int {
        $phfile = $this->files->getCache();
        if( $phfile && class_exists('WP_Translation_File_PHP',false) ){
            return $this->writeFile( $phfile, Loco_gettext_PhpCache::render($po) );
        }
        return 0;
    }


    /**
     * @param Loco_package_Project $project Translation set, required to resolve script paths
     * @param Loco_gettext_Data $po PO data to export
     */
    public function writeJson( Loco_package_Project $project, Loco_gettext_Data $po ):Loco_fs_FileList {
        $domain = $project->getDomain()->getName();
        $pofile = $this->files->getSource();
        $jsons = new Loco_fs_FileList;
        // Allow plugins to dictate a single JSON file to hold all script translations for a text domain
        // authors will additionally have to filter at runtime on load_script_translation_file
        $path = apply_filters('loco_compile_single_json', '', $pofile->getPath(), $domain );
        if( is_string($path) && '' !== $path ){
            $refs = $po->splitRefs( $this->getJsExtMap() );
            if( array_key_exists('js',$refs) && $refs['js'] instanceof Loco_gettext_Data ){
                $jsonfile = new Loco_fs_File($path);
                $json = $refs['js']->msgjed($domain,'*.js');
                try {
                    if( '' !== $json ){
                        $this->writeFile($jsonfile,$json);
                        $jsons->add($jsonfile);
                    }
                }
                catch( Loco_error_WriteException $e ){
                    Loco_error_AdminNotices::debug( $e->getMessage() );
                    // translators: %s refers to a JSON file which could not be compiled due to an error
                    Loco_error_AdminNotices::warn( sprintf(__('JSON compilation failed for %s','loco-translate'),$jsonfile->basename()) );
                }
            }
        }
        // continue as per default, generating multiple per-script JSON
        else {
            $buffer = [];
            $base_dir = $project->getBundle()->getDirectoryPath();
            $extensions = array_keys( $this->getJsExtMap() );
            $refsGrep = '\\.(?:'.implode('|',$extensions).')';
            /* @var Loco_gettext_Data $fragment */
            foreach( $po->exportRefs($refsGrep) as $ref => $fragment ){
                $use = null;
                // Reference could be a js source file, or a minified version. We'll try .min.js first, then .js
                // Build systems may differ, but WordPress only supports these suffixes. See WP-CLI MakeJsonCommand.
                if( substr($ref,-7) === '.min.js' ) {
                    $paths = [ $ref, substr($ref,-7).'.js' ];
                }
                else {
                    $paths = [ substr($ref,0,-3).'.min.js', $ref ];
                }
                // Try .js and .min.js paths to check whether deployed script actually exists
                foreach( $paths as $path ){
                    // Hook into load_script_textdomain_relative_path like load_script_textdomain() does.
                    $url = $project->getBundle()->getDirectoryUrl().$path;
                    $path = apply_filters( 'load_script_textdomain_relative_path', $path, $url );
                    if( ! is_string($path) || '' === $path ){
                        continue;
                    }
                    // by default ignore js file that is not in deployed code
                    $file = new Loco_fs_File($path);
                    $file->normalize($base_dir);
                    if( apply_filters('loco_compile_script_reference',$file->exists(),$path,$domain) ){
                        $use = $path;
                        break;
                    }
                }
                // if neither exists in the bundle, this is a source path that will never be resolved at runtime
                if( is_null($use) ){
                    Loco_error_AdminNotices::debug( sprintf('Skipping JSON for %s; script not found in bundle',$ref) );
                }
                // add .js strings to buffer for this json and merge if already present
                else if( array_key_exists($use,$buffer) ){
                    $buffer[$use]->concat($fragment);
                }
                else {
                    $buffer[$use] = $fragment;
                }
            }
            if( $buffer ){
                // write all buffered fragments to their computed JSON paths
                foreach( $buffer as $ref => $fragment ) {
                    $json = $fragment->msgjed($domain,$ref);
                    if( '' === $json ){
                        Loco_error_AdminNotices::debug( sprintf('Skipping JSON for %s; no translations',$ref) );
                        continue;
                    }
                    try {
                        $jsonfile = self::cloneJson($pofile,$ref,$domain);
                        $this->writeFile( $jsonfile, $json );
                        $jsons->add($jsonfile);
                    }
                    catch( Loco_error_WriteException $e ){
                        Loco_error_AdminNotices::debug( $e->getMessage() );
                        // phpcs:ignore -- comment already applied to this string elsewhere
                        Loco_error_AdminNotices::warn( sprintf(__('JSON compilation failed for %s','loco-translate'),$ref));
                    }
                }
                $buffer = null;
            }
        }
        // clean up redundant JSONs including if no JSONs were compiled
        if( Loco_data_Settings::get()->jed_clean ){
            foreach( $this->files->getJsons($domain) as $path ){
                $jsonfile = new Loco_fs_File($path);
                if( ! $jsons->has($jsonfile) ){
                    try {
                        $jsonfile->unlink();
                    }
                    catch( Loco_error_WriteException $e ){
                        Loco_error_AdminNotices::debug('Unable to remove redundant JSON: '.$e->getMessage() );
                    }
                }
            }
        }
        $this->progress['numjson'] = $jsons->count();
        return $jsons;
    }


    /**
     * Clone localised file as a WordPress script translation file
     */
    private static function cloneJson( Loco_fs_File $pofile, string $ref, string $domain ):Loco_fs_File {
        $name = $pofile->filename();
        // Theme author PO files have no text domain, but JSON files must always be prefixed
        if( $domain && 'default' !== $domain && preg_match('/^[a-z]{2,3}(?:_[a-z\\d_]+)?$/i',$name) ){
            $name = $domain.'-'.$name;
        }
        // Hashable reference is always finally unminified, as per load_script_textdomain()
        if( '' !== $ref ){
            $name .= '-'.self::hashRef($ref);
        }
        return $pofile->cloneBasename( $name.'.json' );
    }


    /**
     * Hashable reference is always finally unminified, as per load_script_textdomain()
     * @param string $ref script path relative to plugin base
     */
    private static function hashRef( string $ref ):string {
        if( substr($ref,-7) === '.min.js' ) {
            $ref = substr($ref,0,-7).'.js';
        }
        return md5($ref);
    }


    /**
     * Fetch compilation summary and raise most relevant success message
     */
    public function getSummary():Loco_mvc_ViewParams {
        $pofile = $this->files->getSource();
        // Avoid calling this unless the initial PO save was successful
        if( ! $this->progress['pobytes'] ){
            throw new LogicException('PO not saved');
        }
        // Summary for localised file includes MO+JSONs
        $mobytes = $this->progress['mobytes'];
        $numjson = $this->progress['numjson'];
        if( $mobytes && $numjson ){
            Loco_error_AdminNotices::success( __('PO file saved and MO/JSON files compiled','loco-translate') );
        }
        else if( $mobytes ){
            Loco_error_AdminNotices::success( __('PO file saved and MO file compiled','loco-translate') );
        }
        else {
            // translators: Success notice where %s is a file extension, e.g. "PO"
            Loco_error_AdminNotices::success( sprintf(__('%s file saved','loco-translate'),strtoupper($pofile->extension())) );
        }
        return $this->progress;
    }


    /**
     * Obtain non-standard JavaScript file extensions.
     * @return string[] where keys are PCRE safe extensions, all mapped to "js"
     */
    private function getJsExtMap():array {
        $map = ['js'=>'js','jsx'=>'js'];
        $exts = Loco_data_Settings::get()->jsx_alias;
        if( is_array($exts) && $exts ){
            $exts = array_map( [__CLASS__,'pregQuote'], $exts);
            $map = array_fill_keys($exts,'js') + $map;
        }
        return $map;
    }


    /**
     * @internal
     */
    private static function pregQuote( string $value ):string {
        return preg_quote($value,'/');
    }


    /**
     * @param Loco_fs_File $file
     * @param string $data to write to given file
     * @return int bytes written
     */
    public function writeFile( Loco_fs_File $file, string $data ):int {
        if( $this->fs ) {
            $this->fs->authorizeSave( $file );
        }
        $bytes = $file->putContents($data);
        if( 0 !== $bytes ){
            $this->done->add($file );
        }
        return $bytes;
    }

}