Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 89
0.00% covered (danger)
0.00%
0 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
GenerateJsonI18n
0.00% covered (danger)
0.00%
0 / 86
0.00% covered (danger)
0.00%
0 / 5
650
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
72
 transformI18nFile
0.00% covered (danger)
0.00%
0 / 45
0.00% covered (danger)
0.00%
0 / 1
132
 findCommentBefore
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 getAuthorsFromComment
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2
3/**
4 * Convert a PHP messages file to a set of JSON messages files.
5 *
6 * Usage:
7 *    php generateJsonI18n.php ExtensionName.i18n.php i18n/
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 * @ingroup Maintenance
26 */
27
28use MediaWiki\Json\FormatJson;
29
30require_once __DIR__ . '/Maintenance.php';
31
32/**
33 * Maintenance script to generate JSON i18n files from a PHP i18n file.
34 *
35 * @ingroup Maintenance
36 */
37class GenerateJsonI18n extends Maintenance {
38    public function __construct() {
39        parent::__construct();
40        $this->addDescription( 'Build JSON messages files from a PHP messages file' );
41
42        $this->addArg( 'phpfile', 'PHP file defining a $messages array', false );
43        $this->addArg( 'jsondir', 'Directory to write JSON files to', false );
44        $this->addOption( 'extension', 'Perform default conversion on an extension',
45            false, true );
46        $this->addOption( 'supplementary', 'Find supplementary i18n files in subdirs and convert those',
47            false, false );
48    }
49
50    public function execute() {
51        global $IP;
52
53        $phpfile = $this->getArg( 0 );
54        $jsondir = $this->getArg( 1 );
55        $extension = $this->getOption( 'extension' );
56        $convertSupplementaryI18nFiles = $this->hasOption( 'supplementary' );
57
58        if ( $extension ) {
59            if ( $phpfile ) {
60                $this->fatalError( "The phpfile is already specified, conflicts with --extension." );
61            }
62            $phpfile = "$IP/extensions/$extension/$extension.i18n.php";
63        }
64
65        if ( !$phpfile ) {
66            $this->error( "I'm here for an argument!" );
67            $this->maybeHelp( true );
68            // dies.
69        }
70
71        if ( $convertSupplementaryI18nFiles ) {
72            if ( is_readable( $phpfile ) ) {
73                $this->transformI18nFile( $phpfile, $jsondir );
74            } else {
75                // This is non-fatal because we might want to continue searching for
76                // i18n files in subdirs even if the extension does not include a
77                // primary i18n.php.
78                $this->error( "Warning: no primary i18n file was found." );
79            }
80            $this->output( "Searching for supplementary i18n files...\n" );
81            $dir_iterator = new RecursiveDirectoryIterator( dirname( $phpfile ) );
82            $iterator = new RecursiveIteratorIterator(
83                $dir_iterator, RecursiveIteratorIterator::LEAVES_ONLY );
84            /** @var SplFileInfo $fileObject */
85            foreach ( $iterator as $path => $fileObject ) {
86                if ( fnmatch( "*.i18n.php", $fileObject->getFilename() ) ) {
87                    $this->output( "Converting $path.\n" );
88                    $this->transformI18nFile( $path );
89                }
90            }
91        } else {
92            // Just convert the primary i18n file.
93            $this->transformI18nFile( $phpfile, $jsondir );
94        }
95    }
96
97    public function transformI18nFile( $phpfile, $jsondir = null ) {
98        if ( !$jsondir ) {
99            // Assume the json directory should be in the same directory as the
100            // .i18n.php file.
101            $jsondir = dirname( $phpfile ) . "/i18n";
102        }
103        if ( !is_dir( $jsondir ) ) {
104            $this->output( "Creating directory $jsondir.\n" );
105            $success = mkdir( $jsondir );
106            if ( !$success ) {
107                $this->fatalError( "Could not create directory $jsondir" );
108            }
109        }
110
111        if ( !is_readable( $phpfile ) ) {
112            $this->fatalError( "Error reading $phpfile" );
113        }
114        $messages = null;
115        include $phpfile;
116        $phpfileContents = file_get_contents( $phpfile );
117
118        // @phan-suppress-next-line PhanImpossibleCondition Set by include of php file
119        if ( !isset( $messages ) ) {
120            $this->fatalError( "PHP file $phpfile does not define \$messages array" );
121        }
122
123        if ( !$messages ) {
124            $this->fatalError( "PHP file $phpfile contains an empty \$messages array. " .
125                "Maybe it was already converted?" );
126        }
127
128        if ( !isset( $messages['en'] ) || !is_array( $messages['en'] ) ) {
129            $this->fatalError( "PHP file $phpfile does not set language codes" );
130        }
131
132        foreach ( $messages as $langcode => $langmsgs ) {
133            $authors = $this->getAuthorsFromComment( $this->findCommentBefore(
134                "\$messages['$langcode'] =",
135                $phpfileContents
136            ) );
137            // Make sure the @metadata key is the first key in the output
138            $langmsgs = array_merge(
139                [ '@metadata' => [ 'authors' => $authors ] ],
140                $langmsgs
141            );
142
143            $jsonfile = "$jsondir/$langcode.json";
144            $success = file_put_contents(
145                $jsonfile,
146                FormatJson::encode( $langmsgs, "\t", FormatJson::ALL_OK ) . "\n"
147            );
148            if ( $success === false ) {
149                $this->fatalError( "FAILED to write $jsonfile" );
150            }
151            $this->output( "$jsonfile\n" );
152        }
153
154        $this->output(
155            "All done. To complete the conversion, please do the following:\n" .
156            "* Add \$wgMessagesDirs['YourExtension'] = __DIR__ . '/i18n';\n" .
157            "* Remove \$wgExtensionMessagesFiles['YourExtension']\n" .
158            "* Delete the old PHP message file\n" .
159            "This script no longer generates backward compatibility shims! If you need\n" .
160            "compatibility with MediaWiki 1.22 and older, use the MediaWiki 1.23 version\n" .
161            "of this script instead, or create a shim manually.\n"
162        );
163    }
164
165    /**
166     * Find the documentation comment immediately before a given search string
167     * @param string $needle String to search for
168     * @param string $haystack String to search in
169     * @return string Substring of $haystack starting at '/**' ending right before $needle, or empty
170     */
171    protected function findCommentBefore( $needle, $haystack ) {
172        $needlePos = strpos( $haystack, $needle );
173        if ( $needlePos === false ) {
174            return '';
175        }
176        // Need to pass a negative offset to strrpos() so it'll search backwards from the
177        // offset
178        $startPos = strrpos( $haystack, '/**', $needlePos - strlen( $haystack ) );
179        if ( $startPos === false ) {
180            return '';
181        }
182
183        return substr( $haystack, $startPos, $needlePos - $startPos );
184    }
185
186    /**
187     * Get an array of author names from a documentation comment containing @author declarations.
188     * @param string $comment Documentation comment
189     * @return string[] Array of author names
190     */
191    protected function getAuthorsFromComment( $comment ) {
192        return preg_match_all( '/@author (.*?)$/m', $comment, $matches ) ? $matches[1] : [];
193    }
194}
195
196$maintClass = GenerateJsonI18n::class;
197require_once RUN_MAINTENANCE_IF_MAIN;