예제 #1
0
 /**
  * buildHashFile
  *
  * This constructs a file, usually named something.mo.php, which will
  * contain a PHP hash array literal. The literal can be included later
  * and used by this class to provide a translation via functions
  * declared below such as __()
  */
 static function buildHashFile($mofile, $outfile = false, $return = false)
 {
     if (!$outfile) {
         $stream = fopen('php://stdout', 'w');
     } elseif (is_string($outfile)) {
         $stream = fopen($outfile, 'w');
     } elseif (is_resource($outfile)) {
         $stream = $outfile;
     }
     if (!$stream) {
         throw new InvalidArgumentException('Expected a filename or valid resource');
     }
     if (!$mofile instanceof FileReader) {
         $mofile = new FileReader($mofile);
     }
     $reader = new parent($mofile, true);
     if ($reader->short_circuit || $reader->error) {
         throw new Exception('Unable to initialize MO input file');
     }
     $reader->load_tables();
     // Get basic table
     if (!($table = $reader->cache_translations)) {
         throw new Exception('Unable to read translations from file');
     }
     // Transcode the table to UTF-8
     $header = $table[""];
     $info = array();
     preg_match('/^content-type: (.*)$/im', $header, $info);
     $charset = false;
     if ($content_type = $info[1]) {
         // Find the charset property
         $settings = explode(';', $content_type);
         foreach ($settings as $v) {
             @(list($prop, $value) = explode('=', trim($v), 2));
             if (strtolower($prop) == 'charset') {
                 $charset = trim($value);
                 break;
             }
         }
     }
     if ($charset && strcasecmp($charset, 'utf-8') !== 0) {
         foreach ($table as $orig => $trans) {
             // Format::encode defaults to UTF-8 output
             $source = new Unicode($orig, $charset);
             $trans = new Unicode($trans, $charset);
             $table[(string) $source->encode('utf-8')] = (string) $trans->encode('utf-8');
             unset($table[$orig]);
         }
     }
     // Add in some meta-data
     $table[self::META_HEADER] = array('Revision' => $reader->revision, 'Total-Strings' => $reader->total, 'Table-Size' => count($table), 'Build-Timestamp' => gmdate(DATE_RFC822), 'Format-Version' => 'A', 'Encoding' => 'UTF-8');
     // Serialize the PHP array and write to output
     $contents = sprintf('<?php return %s;', var_export($table, true));
     if ($return) {
         return $contents;
     } else {
         fwrite($stream, $contents);
     }
 }