MessageController.php 20.7 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

8 9
namespace yii\console\controllers;

10
use Yii;
11
use yii\console\Controller;
12
use yii\console\Exception;
13
use yii\helpers\Console;
14
use yii\helpers\FileHelper;
15
use yii\helpers\VarDumper;
16
use yii\i18n\GettextPoFile;
17

Qiang Xue committed
18
/**
19 20
 * Extracts messages to be translated from source files.
 *
Alexander Makarov committed
21 22 23 24 25 26
 * The extracted messages can be saved the following depending on `format`
 * setting in config file:
 *
 * - PHP message source files.
 * - ".po" files.
 * - Database.
Qiang Xue committed
27
 *
28
 * Usage:
29 30
 * 1. Create a configuration file using the 'message/config' command:
 *    yii message/config /path/to/myapp/messages/config.php
31
 * 2. Edit the created config file, adjusting it for your web application needs.
32
 * 3. Run the 'message/extract' command, using created config:
33 34
 *    yii message /path/to/myapp/messages/config.php
 *
Qiang Xue committed
35
 * @author Qiang Xue <qiang.xue@gmail.com>
36
 * @since 2.0
Qiang Xue committed
37
 */
38
class MessageController extends Controller
Qiang Xue committed
39
{
40 41 42 43
    /**
     * @var string controller default action ID.
     */
    public $defaultAction = 'extract';
44

45

46 47 48 49 50 51 52
    /**
     * Creates a configuration file for the "extract" command.
     *
     * The generated configuration file contains detailed instructions on
     * how to customize it to fit for your needs. After customization,
     * you may use this configuration file with the "extract" command.
     *
53
     * @param string $filePath output file name or alias.
54
     * @return integer CLI exit code
55 56 57 58 59 60 61
     * @throws Exception on failure.
     */
    public function actionConfig($filePath)
    {
        $filePath = Yii::getAlias($filePath);
        if (file_exists($filePath)) {
            if (!$this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?")) {
62
                return self::EXIT_CODE_NORMAL;
63 64 65
            }
        }
        copy(Yii::getAlias('@yii/views/messageConfig.php'), $filePath);
66
        $this->stdout("Configuration file template created at '{$filePath}'.\n\n", Console::FG_GREEN);
67
        return self::EXIT_CODE_NORMAL;
68
    }
69

70 71 72 73 74 75
    /**
     * Extracts messages to be translated from source code.
     *
     * This command will search through source code files and extract
     * messages that need to be translated in different languages.
     *
76 77 78
     * @param string $configFile the path or alias of the configuration file.
     * You may use the "yii message/config" command to generate
     * this file and then customize it for your needs.
79 80 81 82 83 84 85 86
     * @throws Exception on failure.
     */
    public function actionExtract($configFile)
    {
        $configFile = Yii::getAlias($configFile);
        if (!is_file($configFile)) {
            throw new Exception("The configuration file does not exist: $configFile");
        }
87

88 89 90 91 92 93 94
        $config = array_merge([
            'translator' => 'Yii::t',
            'overwrite' => false,
            'removeUnused' => false,
            'sort' => false,
            'format' => 'php',
        ], require($configFile));
95

96 97
        if (!isset($config['sourcePath'], $config['languages'])) {
            throw new Exception('The configuration file must specify "sourcePath" and "languages".');
98 99 100 101
        }
        if (!is_dir($config['sourcePath'])) {
            throw new Exception("The source path {$config['sourcePath']} is not a valid directory.");
        }
maxlapko committed
102 103 104
        if (empty($config['format']) || !in_array($config['format'], ['php', 'po', 'db'])) {
            throw new Exception('Format should be either "php", "po" or "db".');
        }
105
        if (in_array($config['format'], ['php', 'po'])) {
106 107 108
            if (!isset($config['messagePath'])) {
                throw new Exception('The configuration file must specify "messagePath".');
            } elseif (!is_dir($config['messagePath'])) {
109 110 111 112 113 114
                throw new Exception("The message path {$config['messagePath']} is not a valid directory.");
            }
        }
        if (empty($config['languages'])) {
            throw new Exception("Languages cannot be empty.");
        }
Qiang Xue committed
115

116
        $files = FileHelper::findFiles(realpath($config['sourcePath']), $config);
Qiang Xue committed
117

118 119 120 121 122 123 124 125 126 127
        $messages = [];
        foreach ($files as $file) {
            $messages = array_merge_recursive($messages, $this->extractMessages($file, $config['translator']));
        }
        if (in_array($config['format'], ['php', 'po'])) {
            foreach ($config['languages'] as $language) {
                $dir = $config['messagePath'] . DIRECTORY_SEPARATOR . $language;
                if (!is_dir($dir)) {
                    @mkdir($dir);
                }
128 129 130 131 132
                if ($config['format'] === 'po') {
                    $catalog = isset($config['catalog']) ? $config['catalog'] : 'messages';
                    $this->saveMessagesToPO($messages, $dir, $config['overwrite'], $config['removeUnused'], $config['sort'], $catalog);
                } else {
                    $this->saveMessagesToPHP($messages, $dir, $config['overwrite'], $config['removeUnused'], $config['sort']);
133 134 135
                }
            }
        } elseif ($config['format'] === 'db') {
136
            $db = \Yii::$app->get(isset($config['db']) ? $config['db'] : 'db');
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
            if (!$db instanceof \yii\db\Connection) {
                throw new Exception('The "db" option must refer to a valid database application component.');
            }
            $sourceMessageTable = isset($config['sourceMessageTable']) ? $config['sourceMessageTable'] : '{{%source_message}}';
            $messageTable = isset($config['messageTable']) ? $config['messageTable'] : '{{%message}}';
            $this->saveMessagesToDb(
                $messages,
                $db,
                $sourceMessageTable,
                $messageTable,
                $config['removeUnused'],
                $config['languages']
            );
        }
    }
Qiang Xue committed
152

153 154 155
    /**
     * Saves messages to database
     *
156
     * @param array $messages
157
     * @param \yii\db\Connection $db
158 159 160 161
     * @param string $sourceMessageTable
     * @param string $messageTable
     * @param boolean $removeUnused
     * @param array $languages
162 163 164 165 166
     */
    protected function saveMessagesToDb($messages, $db, $sourceMessageTable, $messageTable, $removeUnused, $languages)
    {
        $q = new \yii\db\Query;
        $current = [];
Qiang Xue committed
167

168 169 170
        foreach ($q->select(['id', 'category', 'message'])->from($sourceMessageTable)->all() as $row) {
            $current[$row['category']][$row['id']] = $row['message'];
        }
Qiang Xue committed
171

172 173
        $new = [];
        $obsolete = [];
Qiang Xue committed
174

175 176
        foreach ($messages as $category => $msgs) {
            $msgs = array_unique($msgs);
177

178 179
            if (isset($current[$category])) {
                $new[$category] = array_diff($msgs, $current[$category]);
180
                $obsolete += array_diff($current[$category], $msgs);
181 182 183 184
            } else {
                $new[$category] = $msgs;
            }
        }
185

186 187 188
        foreach (array_diff(array_keys($current), array_keys($messages)) as $category) {
            $obsolete += $current[$category];
        }
189

190 191 192 193 194 195 196
        if (!$removeUnused) {
            foreach ($obsolete as $pk => $m) {
                if (mb_substr($m, 0, 2) === '@@' && mb_substr($m, -2) === '@@') {
                    unset($obsolete[$pk]);
                }
            }
        }
197

198
        $obsolete = array_keys($obsolete);
199
        $this->stdout("Inserting new messages...");
200
        $savedFlag = false;
201

202 203 204
        foreach ($new as $category => $msgs) {
            foreach ($msgs as $m) {
                $savedFlag = true;
205

206
                $db->createCommand()
207
                   ->insert($sourceMessageTable, ['category' => $category, 'message' => $m])->execute();
208
                $lastID = $db->getLastInsertID();
209 210
                foreach ($languages as $language) {
                    $db->createCommand()
211
                       ->insert($messageTable, ['id' => $lastID, 'language' => $language])->execute();
212 213 214
                }
            }
        }
215

216 217
        $this->stdout($savedFlag ? "saved.\n" : "Nothing new...skipped.\n");
        $this->stdout($removeUnused ? "Deleting obsoleted messages..." : "Updating obsoleted messages...");
218

219
        if (empty($obsolete)) {
220
            $this->stdout("Nothing obsoleted...skipped.\n");
221 222 223
        } else {
            if ($removeUnused) {
                $db->createCommand()
224
                   ->delete($sourceMessageTable, ['in', 'id', $obsolete])->execute();
225
                $this->stdout("deleted.\n");
226 227
            } else {
                $db->createCommand()
228 229 230 231 232
                   ->update(
                       $sourceMessageTable,
                       ['message' => new \yii\db\Expression("CONCAT('@@',message,'@@')")],
                       ['in', 'id', $obsolete]
                   )->execute();
233
                $this->stdout("updated.\n");
234 235 236
            }
        }
    }
237

238 239 240
    /**
     * Extracts messages from a file
     *
241 242
     * @param string $fileName name of the file to extract messages from
     * @param string $translator name of the function used to translate messages
243 244 245 246
     * @return array
     */
    protected function extractMessages($fileName, $translator)
    {
247
        $coloredFileName = Console::ansiFormat($fileName, [Console::FG_CYAN]);
248
        $this->stdout("Extracting messages from $coloredFileName...\n");
249 250 251 252 253 254
        $subject = file_get_contents($fileName);
        $messages = [];
        if (!is_array($translator)) {
            $translator = [$translator];
        }
        foreach ($translator as $currentTranslator) {
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
            $translatorTokens = token_get_all('<?php ' . $currentTranslator);
            array_shift($translatorTokens);

            $translatorTokensCount = count($translatorTokens);
            $matchedTokensCount = 0;
            $buffer = [];

            $tokens = token_get_all($subject);
            foreach ($tokens as $token) {
                // finding out translator call
                if ($matchedTokensCount < $translatorTokensCount) {
                    if ($this->tokensEqual($token, $translatorTokens[$matchedTokensCount])) {
                        $matchedTokensCount++;
                    } else {
                        $matchedTokensCount = 0;
                    }
                } elseif ($matchedTokensCount === $translatorTokensCount) {
                    // translator found

                    // end of translator call or end of something that we can't extract
                    if ($this->tokensEqual(')', $token)) {
                        if (isset($buffer[0][0], $buffer[1], $buffer[2][0]) && $buffer[0][0] === T_CONSTANT_ENCAPSED_STRING && $buffer[1] === ',' && $buffer[2][0] === T_CONSTANT_ENCAPSED_STRING) {
                            // is valid call we can extract

                            $category = stripcslashes($buffer[0][1]);
                            $category = mb_substr($category, 1, mb_strlen($category) - 2);

                            $message = stripcslashes($buffer[2][1]);
                            $message = mb_substr($message, 1, mb_strlen($message) - 2);

                            $messages[$category][] = $message;
                        } else {
                            // invalid call or dynamic call we can't extract

                            $line = Console::ansiFormat($this->getLine($buffer), [Console::FG_CYAN]);
                            $skipping = Console::ansiFormat('Skipping line', [Console::FG_YELLOW]);
291
                            $this->stdout("$skipping $line. Make sure both category and message are static strings.\n");
292 293 294 295 296 297 298 299 300
                        }

                        // prepare for the next match
                        $matchedTokensCount = 0;
                        $buffer = [];
                    } elseif ($token !== '(' && isset($token[0]) && !in_array($token[0], [T_WHITESPACE, T_COMMENT])) {
                        // ignore comments, whitespaces and beginning of function call
                        $buffer[] = $token;
                    }
301
                }
302 303
            }
        }
304

305
        $this->stdout("\n");
306

307 308
        return $messages;
    }
309

310 311 312 313 314 315
    /**
     * Finds out if two PHP tokens are equal
     *
     * @param array|string $a
     * @param array|string $b
     * @return boolean
316
     * @since 2.0.1
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
     */
    protected function tokensEqual($a, $b)
    {
        if (is_string($a) && is_string($b)) {
            return $a === $b;
        } elseif (isset($a[0], $a[1], $b[0], $b[1])) {
            return $a[0] === $b[0] && $a[1] == $b[1];
        }
        return false;
    }

    /**
     * Finds out a line of the first non-char PHP token found
     *
     * @param array $tokens
     * @return int|string
333
     * @since 2.0.1
334 335 336 337 338 339 340 341 342 343 344
     */
    protected function getLine($tokens)
    {
        foreach ($tokens as $token) {
            if (isset($token[2])) {
                return $token[2];
            }
        }
        return 'unknown';
    }

345
    /**
346 347 348 349 350 351 352 353 354 355 356 357 358
     * Writes messages into PHP files
     *
     * @param array $messages
     * @param string $dirName name of the directory to write to
     * @param boolean $overwrite if existing file should be overwritten without backup
     * @param boolean $removeUnused if obsolete translations should be removed
     * @param boolean $sort if translations should be sorted
     */
    protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort)
    {
        foreach ($messages as $category => $msgs) {
            $file = str_replace("\\", '/', "$dirName/$category.php");
            $path = dirname($file);
359
            FileHelper::createDirectory($path);
360
            $msgs = array_values(array_unique($msgs));
361
            $coloredFileName = Console::ansiFormat($file, [Console::FG_CYAN]);
362
            $this->stdout("Saving messages to $coloredFileName...\n");
363
            $this->saveMessagesCategoryToPHP($msgs, $file, $overwrite, $removeUnused, $sort, $category);
364 365 366 367 368
        }
    }

    /**
     * Writes category messages into PHP file
369
     *
370 371 372
     * @param array $messages
     * @param string $fileName name of the file to write to
     * @param boolean $overwrite if existing file should be overwritten without backup
373
     * @param boolean $removeUnused if obsolete translations should be removed
374
     * @param boolean $sort if translations should be sorted
375
     * @param string $category message category
376
     */
377
    protected function saveMessagesCategoryToPHP($messages, $fileName, $overwrite, $removeUnused, $sort, $category)
378 379
    {
        if (is_file($fileName)) {
380
            $existingMessages = require($fileName);
381
            sort($messages);
382 383
            ksort($existingMessages);
            if (array_keys($existingMessages) == $messages) {
384
                $this->stdout("Nothing new in \"$category\" category... Nothing to save.\n\n", Console::FG_GREEN);
385
                return;
386 387 388 389
            }
            $merged = [];
            $untranslated = [];
            foreach ($messages as $message) {
390 391
                if (array_key_exists($message, $existingMessages) && strlen($existingMessages[$message]) > 0) {
                    $merged[$message] = $existingMessages[$message];
392 393 394 395 396 397 398 399 400 401
                } else {
                    $untranslated[] = $message;
                }
            }
            ksort($merged);
            sort($untranslated);
            $todo = [];
            foreach ($untranslated as $message) {
                $todo[$message] = '';
            }
402 403
            ksort($existingMessages);
            foreach ($existingMessages as $message => $translation) {
404
                if (!isset($merged[$message]) && !isset($todo[$message]) && !$removeUnused) {
405
                    if (!empty($translation) && strncmp($translation, '@@', 2) === 0 && substr_compare($translation, '@@', -2, 2) === 0) {
406 407 408 409 410 411 412 413 414 415 416 417 418
                        $todo[$message] = $translation;
                    } else {
                        $todo[$message] = '@@' . $translation . '@@';
                    }
                }
            }
            $merged = array_merge($todo, $merged);
            if ($sort) {
                ksort($merged);
            }
            if (false === $overwrite) {
                $fileName .= '.merged';
            }
419
            $this->stdout("Translation merged.\n");
420
        } else {
421 422 423
            $merged = [];
            foreach ($messages as $message) {
                $merged[$message] = '';
424
            }
425
            ksort($merged);
426
        }
427 428 429 430


        $array = VarDumper::export($merged);
        $content = <<<EOD
Qiang Xue committed
431 432 433 434
<?php
/**
 * Message translations.
 *
435
 * This file is automatically generated by 'yii {$this->id}' command.
Qiang Xue committed
436 437 438 439 440 441 442 443 444 445 446
 * It contains the localizable messages extracted from source code.
 * You may modify this file by translating the extracted messages.
 *
 * Each array element represents the translation (value) of a message (key).
 * If the value is empty, the message is considered as not translated.
 * Messages that no longer need translation will have their translations
 * enclosed between a pair of '@@' marks.
 *
 * Message string can be used with plural forms format. Check i18n section
 * of the guide for details.
 *
447
 * NOTE: this file must be saved in UTF-8 encoding.
Qiang Xue committed
448 449 450 451
 */
return $array;

EOD;
452

453
        file_put_contents($fileName, $content);
454
        $this->stdout("Translation saved.\n\n", Console::FG_GREEN);
455
    }
456 457 458 459 460 461 462 463 464 465 466 467 468 469

    /**
     * Writes messages into PO file
     *
     * @param array $messages
     * @param string $dirName name of the directory to write to
     * @param boolean $overwrite if existing file should be overwritten without backup
     * @param boolean $removeUnused if obsolete translations should be removed
     * @param boolean $sort if translations should be sorted
     * @param string $catalog message catalog
     */
    protected function saveMessagesToPO($messages, $dirName, $overwrite, $removeUnused, $sort, $catalog)
    {
        $file = str_replace("\\", '/', "$dirName/$catalog.po");
470
        FileHelper::createDirectory(dirname($file));
471
        $this->stdout("Saving messages to $file...\n");
472 473 474 475 476 477 478

        $poFile = new GettextPoFile();


        $merged = [];
        $todos = [];

479
        $hasSomethingToWrite = false;
480
        foreach ($messages as $category => $msgs) {
481
            $notTranslatedYet = [];
482 483 484 485 486 487 488 489
            $msgs = array_values(array_unique($msgs));

            if (is_file($file)) {
                $existingMessages = $poFile->load($file, $category);

                sort($msgs);
                ksort($existingMessages);
                if (array_keys($existingMessages) == $msgs) {
490
                    $this->stdout("Nothing new in \"$category\" category...\n");
491 492 493

                    sort($msgs);
                    foreach ($msgs as $message) {
494
                        $merged[$category . chr(4) . $message] = $existingMessages[$message];
495 496 497
                    }
                    ksort($merged);
                    continue;
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
                }

                // merge existing message translations with new message translations
                foreach ($msgs as $message) {
                    if (array_key_exists($message, $existingMessages) && strlen($existingMessages[$message]) > 0) {
                        $merged[$category . chr(4) . $message] = $existingMessages[$message];
                    } else {
                        $notTranslatedYet[] = $message;
                    }
                }
                ksort($merged);
                sort($notTranslatedYet);

                // collect not yet translated messages
                foreach ($notTranslatedYet as $message) {
                    $todos[$category . chr(4) . $message] = '';
                }

                // add obsolete unused messages
                foreach ($existingMessages as $message => $translation) {
                    if (!isset($merged[$category . chr(4) . $message]) && !isset($todos[$category . chr(4) . $message]) && !$removeUnused) {
519
                        if (!empty($translation) && substr($translation, 0, 2) === '@@' && substr($translation, -2) === '@@') {
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
                            $todos[$category . chr(4) . $message] = $translation;
                        } else {
                            $todos[$category . chr(4) . $message] = '@@' . $translation . '@@';
                        }
                    }
                }

                $merged = array_merge($todos, $merged);
                if ($sort) {
                    ksort($merged);
                }

                if ($overwrite === false) {
                    $file .= '.merged';
                }
            } else {
                sort($msgs);
                foreach ($msgs as $message) {
                    $merged[$category . chr(4) . $message] = '';
                }
                ksort($merged);
            }
542
            $this->stdout("Category \"$category\" merged.\n");
543 544 545 546
            $hasSomethingToWrite = true;
        }
        if ($hasSomethingToWrite) {
            $poFile->save($file, $merged);
547
            $this->stdout("Translation saved.\n", Console::FG_GREEN);
548
        } else {
549
            $this->stdout("Nothing to save.\n", Console::FG_GREEN);
550 551
        }
    }
Qiang Xue committed
552
}