Merge "Change X-UA-Compatible from <meta> tag to HTTP header"
[lhc/web/wiklou.git] / maintenance / generateJsonI18n.php
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
28 require_once __DIR__ . '/Maintenance.php';
29
30 /**
31 * Maintenance script to generate JSON i18n files from a PHP i18n file.
32 *
33 * @ingroup Maintenance
34 */
35 class GenerateJsonI18n extends Maintenance {
36 public function __construct() {
37 parent::__construct();
38 $this->mDescription = "Build JSON messages files from a PHP messages file";
39 $this->addArg( 'phpfile', 'PHP file defining a $messages array', true );
40 $this->addArg( 'jsondir', 'Directory to write JSON files to. ' .
41 'Required unless <phpfile> exists and --shim-only is specified', false );
42 $this->addOption( 'langcode', 'Language code; only needed for converting core i18n files',
43 false, true );
44 $this->addOption( 'shim-only', 'Only create or update the backward-compatibility shim' );
45 }
46
47 public function execute() {
48 $phpfile = $this->getArg( 0 );
49 $jsondir = $this->getArg( 1 );
50
51 if ( $this->hasOption( 'shim-only' ) ) {
52 $this->shimOnly( $phpfile, $jsondir );
53
54 return;
55 }
56
57 if ( $jsondir === null ) {
58 $this->error( 'Argument [jsondir] is required unless --shim-only is specified.' );
59 $this->maybeHelp( true );
60 }
61
62 if ( !is_readable( $phpfile ) ) {
63 $this->error( "Error reading $phpfile\n", 1 );
64 }
65 include $phpfile;
66 $phpfileContents = file_get_contents( $phpfile );
67
68 if ( !isset( $messages ) ) {
69 $this->error( "PHP file $phpfile does not define \$messages array\n", 1 );
70 }
71
72 $extensionStyle = true;
73 if ( !isset( $messages['en'] ) || !is_array( $messages['en'] ) ) {
74 if ( !$this->hasOption( 'langcode' ) ) {
75 $this->error( "PHP file $phpfile does not set language codes, --langcode " .
76 "is required.\n", 1 );
77 }
78 $extensionStyle = false;
79 $langcode = $this->getOption( 'langcode' );
80 $messages = array( $langcode => $messages );
81 } elseif ( $this->hasOption( 'langcode' ) ) {
82 $this->output( "Warning: --langcode option set but will not be used.\n" );
83 }
84
85 foreach ( $messages as $langcode => $langmsgs ) {
86 $authors = $this->getAuthorsFromComment( $this->findCommentBefore(
87 $extensionStyle ? "\$messages['$langcode'] =" : '$messages =',
88 $phpfileContents
89 ) );
90 // Make sure the @metadata key is the first key in the output
91 $langmsgs = array_merge(
92 array( '@metadata' => array( 'authors' => $authors ) ),
93 $langmsgs
94 );
95
96 $jsonfile = "$jsondir/$langcode.json";
97 $success = file_put_contents(
98 $jsonfile,
99 FormatJson::encode( $langmsgs, "\t", FormatJson::ALL_OK ) . "\n"
100 );
101 if ( $success === false ) {
102 $this->error( "FAILED to write $jsonfile", 1 );
103 }
104 $this->output( "$jsonfile\n" );
105 }
106
107 if ( !$this->hasOption( 'langcode' ) ) {
108 $shim = $this->doShim( $jsondir );
109 file_put_contents( $phpfile, $shim );
110 }
111
112 $this->output( "All done.\n" );
113 $this->output( "Also add \$wgMessagesDirs['YourExtension'] = __DIR__ . '/i18n';\n" );
114 }
115
116 protected function shimOnly( $phpfile, $jsondir ) {
117 if ( file_exists( $phpfile ) ) {
118 if ( !is_readable( $phpfile ) ) {
119 $this->error( "Error reading $phpfile\n", 1 );
120 }
121
122 $phpfileContents = file_get_contents( $phpfile );
123 $m = array();
124 if ( !preg_match( '!"/([^"$]+)/\$csCode.json";!', $phpfileContents, $m ) ) {
125 $this->error( "Cannot recognize $phpfile as a shim.\n", 1 );
126 }
127
128 if ( $jsondir === null ) {
129 $jsondir = $m[1];
130 }
131
132 $this->output( "Updating existing shim $phpfile\n" );
133 } elseif ( $jsondir === null ) {
134 $this->error( "$phpfile does not exist.\n" .
135 "Argument [jsondir] is required in order to create a new shim.\n", 1 );
136 } else {
137 $this->output( "Creating new shim $phpfile\n" );
138 }
139
140 $shim = $this->doShim( $jsondir );
141 file_put_contents( $phpfile, $shim );
142 $this->output( "All done.\n" );
143 }
144
145 protected function doShim( $jsondir ) {
146 $shim = <<<'PHP'
147 <?php
148 /**
149 * This is a backwards-compatibility shim, generated by:
150 * https://git.wikimedia.org/blob/mediawiki%2Fcore.git/HEAD/maintenance%2FgenerateJsonI18n.php
151 *
152 * Beginning with MediaWiki 1.23, translation strings are stored in json files,
153 * and the EXTENSION.i18n.php file only exists to provide compatibility with
154 * older releases of MediaWiki. For more information about this migration, see:
155 * https://www.mediawiki.org/wiki/Requests_for_comment/Localisation_format
156 *
157 * This shim maintains compatibility back to MediaWiki 1.17.
158 */
159 $messages = array();
160 if ( !function_exists( '{{FUNC}}' ) ) {
161 function {{FUNC}}( $cache, $code, &$cachedData ) {
162 $codeSequence = array_merge( array( $code ), $cachedData['fallbackSequence'] );
163 foreach ( $codeSequence as $csCode ) {
164 $fileName = dirname( __FILE__ ) . "/{{OUT}}/$csCode.json";
165 if ( is_readable( $fileName ) ) {
166 $data = FormatJson::decode( file_get_contents( $fileName ), true );
167 foreach ( array_keys( $data ) as $key ) {
168 if ( $key === '' || $key[0] === '@' ) {
169 unset( $data[$key] );
170 }
171 }
172 $cachedData['messages'] = array_merge( $data, $cachedData['messages'] );
173 }
174
175 $cachedData['deps'][] = new FileDependency( $fileName );
176 }
177 return true;
178 }
179
180 $GLOBALS['wgHooks']['LocalisationCacheRecache'][] = '{{FUNC}}';
181 }
182
183 PHP;
184
185 $jsondir = str_replace( '\\', '/', $jsondir );
186 $shim = str_replace( '{{OUT}}', $jsondir, $shim );
187 $shim = str_replace( '{{FUNC}}', 'wfJsonI18nShim' . wfRandomString( 16 ), $shim );
188
189 return $shim;
190 }
191
192 /**
193 * Find the documentation comment immediately before a given search string
194 * @param string $needle String to search for
195 * @param string $haystack String to search in
196 * @return string Substring of $haystack starting at '/**' ending right before $needle, or empty
197 */
198 protected function findCommentBefore( $needle, $haystack ) {
199 $needlePos = strpos( $haystack, $needle );
200 if ( $needlePos === false ) {
201 return '';
202 }
203 // Need to pass a negative offset to strrpos() so it'll search backwards from the
204 // offset
205 $startPos = strrpos( $haystack, '/**', $needlePos - strlen( $haystack ) );
206 if ( $startPos === false ) {
207 return '';
208 }
209
210 return substr( $haystack, $startPos, $needlePos - $startPos );
211 }
212
213 /**
214 * Get an array of author names from a documentation comment containing @author declarations.
215 * @param string $comment Documentation comment
216 * @return array Array of author names (strings)
217 */
218 protected function getAuthorsFromComment( $comment ) {
219 $matches = null;
220 preg_match_all( '/@author (.*?)$/m', $comment, $matches );
221
222 return $matches && $matches[1] ? $matches[1] : array();
223 }
224 }
225
226 $maintClass = "GenerateJsonI18n";
227 require_once RUN_MAINTENANCE_IF_MAIN;