Subversion-Projekte lars-tiefland.prado

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
 
3
/**
4
 * MessageSource_XLIFF class file.
5
 *
6
 * This program is free software; you can redistribute it and/or modify
7
 * it under the terms of the BSD License.
8
 *
9
 * Copyright(c) 2004 by Qiang Xue. All rights reserved.
10
 *
11
 * To contact the author write to {@link mailto:qiang.xue@gmail.com Qiang Xue}
12
 * The latest version of PRADO can be obtained from:
13
 * {@link http://prado.sourceforge.net/}
14
 *
15
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
16
 * @version $Revision: 1.8 $  $Date: 2005/12/17 06:11:28 $
17
 * @package System.I18N.core
18
 */
19
 
20
/**
21
 * Get the MessageSource class file.
22
 */
23
require_once(dirname(__FILE__).'/MessageSource.php');
24
 
25
/**
26
 * MessageSource_XLIFF class.
27
 *
28
 * Using XML XLIFF format as the message source for translation.
29
 * Details and example of XLIFF can be found in the following URLs.
30
 *
31
 * # http://www.opentag.com/xliff.htm
32
 * # http://www-106.ibm.com/developerworks/xml/library/x-localis2/
33
 *
34
 * See the MessageSource::factory() method to instantiate this class.
35
 *
36
 * @author Xiang Wei Zhuo <weizhuo[at]gmail[dot]com>
37
 * @version v1.0, last update on Fri Dec 24 16:18:44 EST 2004
38
 * @package System.I18N.core
39
 */
40
class MessageSource_XLIFF extends MessageSource
41
{
42
	/**
43
	 * Message data filename extension.
44
	 * @var string
45
	 */
46
	protected $dataExt = '.xml';
47
 
48
	/**
49
	 * Separator between culture name and source.
50
	 * @var string
51
	 */
52
	protected $dataSeparator = '.';
53
 
54
	/**
55
	 * Constructor.
56
	 * @param string the directory where the messages are stored.
57
	 * @see MessageSource::factory();
58
	 */
59
	function __construct($source)
60
	{
61
		$this->source = (string)$source;
62
	}
63
 
64
	/**
65
	 * Load the messages from a XLIFF file.
66
	 * @param string XLIFF file.
67
	 * @return array of messages.
68
	 */
69
	protected function &loadData($filename)
70
	{
71
		//load it.
72
 
73
		$XML = simplexml_load_file($filename);
74
 
75
		if(!$XML) return false;
76
 
77
		$translationUnit = $XML->xpath('//trans-unit');
78
 
79
		$translations = array();
80
 
81
		foreach($translationUnit as $unit)
82
		{
83
			$source = (string)$unit->source;
84
			$translations[$source][] = (string)$unit->target;
85
			$translations[$source][]= (string)$unit['id'];
86
			$translations[$source][]= (string)$unit->note;
87
		}
88
 
89
		return $translations;
90
	}
91
 
92
	/**
93
	 * Get the last modified unix-time for this particular catalogue+variant.
94
	 * Just use the file modified time.
95
	 * @param string catalogue+variant
96
	 * @return int last modified in unix-time format.
97
	 */
98
	protected function getLastModified($source)
99
	{
100
		if(is_file($source))
101
			return filemtime($source);
102
		else
103
			return 0;
104
	}
105
 
106
	/**
107
	 * Get the XLIFF file for a specific message catalogue and cultural
108
	 * vairant.
109
	 * @param string message catalogue
110
	 * @return string full path to the XLIFF file.
111
	 */
112
	protected function getSource($variant)
113
	{
114
		return $this->source.'/'.$variant;
115
	}
116
 
117
	/**
118
	 * Determin if the XLIFF file source is valid.
119
	 * @param string XLIFF file
120
	 * @return boolean true if valid, false otherwise.
121
	 */
122
	protected function isValidSource($source)
123
	{
124
		return is_file($source);
125
	}
126
 
127
	/**
128
	 * Get all the variants of a particular catalogue.
129
	 * @param string catalogue name
130
	 * @return array list of all variants for this catalogue.
131
	 */
132
	protected function getCatalogueList($catalogue)
133
	{
134
		$variants = explode('_',$this->culture);
135
		$source = $catalogue.$this->dataExt;
136
 
137
		$catalogues = array($source);
138
 
139
		$variant = null;
140
 
141
		for($i = 0, $k = count($variants); $i < $k; ++$i)
142
		{
143
			if(isset($variants[$i]{0}))
144
			{
145
				$variant .= ($variant)?'_'.$variants[$i]:$variants[$i];
146
				$catalogues[] = $catalogue.$this->dataSeparator.
147
								$variant.$this->dataExt;
148
			}
149
		}
150
 
151
		$byDir = $this->getCatalogueByDir($catalogue);
152
		$catalogues = array_merge($byDir,array_reverse($catalogues));
153
		$files = array();
154
		foreach($catalogues as $file)
155
		{
156
			$files[] = $file;
157
			$files[] = preg_replace('/\.xml$/', '.xlf', $file);
158
		}
159
		return $files;
160
	}
161
 
162
	/**
163
	 * Traverse through the directory structure to find the catalogues.
164
	 * This should only be called by getCatalogueList()
165
	 * @param string a particular catalogue.
166
	 * @return array a list of catalogues.
167
	 * @see getCatalogueList()
168
	 */
169
	private function getCatalogueByDir($catalogue)
170
	{
171
		$variants = explode('_',$this->culture);
172
		$catalogues = array();
173
 
174
		$variant = null;
175
 
176
		for($i = 0, $k = count($variants); $i < $k; ++$i)
177
		{
178
			if(isset($variants[$i]{0}))
179
			{
180
				$variant .= ($variant)?'_'.$variants[$i]:$variants[$i];
181
				$catalogues[] = $variant.'/'.$catalogue.$this->dataExt;
182
			}
183
		}
184
		return array_reverse($catalogues);
185
	}
186
 
187
	/**
188
	 * Returns a list of catalogue and its culture ID.
189
	 * E.g. array('messages','en_AU')
190
	 * @return array list of catalogues
191
	 * @see getCatalogues()
192
	 */
193
	public function catalogues()
194
	{
195
		return $this->getCatalogues();
196
	}
197
 
198
	/**
199
	 * Returns a list of catalogue and its culture ID. This takes care
200
	 * of directory structures.
201
	 * E.g. array('messages','en_AU')
202
	 * @return array list of catalogues
203
	 */
204
	protected function getCatalogues($dir=null,$variant=null)
205
	{
206
		$dir = $dir?$dir:$this->source;
207
		$files = scandir($dir);
208
 
209
		$catalogue = array();
210
 
211
		foreach($files as $file)
212
		{
213
			if(is_dir($dir.'/'.$file)
214
				&& preg_match('/^[a-z]{2}(_[A-Z]{2,3})?$/',$file))
215
			{
216
				$catalogue = array_merge($catalogue,
217
								$this->getCatalogues($dir.'/'.$file, $file));
218
			}
219
 
220
			$pos = strpos($file,$this->dataExt);
221
			if($pos >0
222
				&& substr($file,-1*strlen($this->dataExt)) == $this->dataExt)
223
			{
224
				$name = substr($file,0,$pos);
225
				$dot = strrpos($name,$this->dataSeparator);
226
				$culture = $variant;
227
				$cat = $name;
228
				if(is_int($dot))
229
				{
230
					$culture = substr($name, $dot+1,strlen($name));
231
					$cat = substr($name,0,$dot);
232
				}
233
				$details[0] = $cat;
234
				$details[1] = $culture;
235
 
236
 
237
				$catalogue[] = $details;
238
			}
239
		}
240
		sort($catalogue);
241
		return $catalogue;
242
	}
243
 
244
	/**
245
	 * Get the variant for a catalogue depending on the current culture.
246
	 * @param string catalogue
247
	 * @return string the variant.
248
	 * @see save()
249
	 * @see update()
250
	 * @see delete()
251
	 */
252
	private function getVariants($catalogue='messages')
253
	{
254
		if($catalogue === null) {
255
			$catalogue = 'messages';
256
		}
257
 
258
		foreach($this->getCatalogueList($catalogue) as $variant)
259
		{
260
			$file = $this->getSource($variant);
261
			if(is_file($file))
262
				return array($variant, $file);
263
		}
264
		return false;
265
	}
266
 
267
	/**
268
	 * Save the list of untranslated blocks to the translation source.
269
	 * If the translation was not found, you should add those
270
	 * strings to the translation source via the <b>append()</b> method.
271
	 * @param string the catalogue to add to
272
	 * @return boolean true if saved successfuly, false otherwise.
273
	 */
274
	public function save($catalogue='messages')
275
	{
276
		$messages = $this->untranslated;
277
		if(count($messages) <= 0) return false;
278
 
279
		$variants = $this->getVariants($catalogue);
280
 
281
		if($variants)
282
			list($variant, $filename) = $variants;
283
		else
284
			list($variant, $filename) = $this->createMessageTemplate($catalogue);
285
 
286
		if(is_writable($filename) == false)
287
			throw new TIOException("Unable to save to file {$filename}, file must be writable.");
288
 
289
		//create a new dom, import the existing xml
290
		$dom = new DOMDocument();
291
		$dom->load($filename);
292
 
293
		//find the body element
294
		$xpath = new DomXPath($dom);
295
    	$body = $xpath->query('//body')->item(0);
296
 
297
		$lastNodes = $xpath->query('//trans-unit[last()]');
298
		if(($last=$lastNodes->item(0))!==null)
299
			$count = (int)$last->getAttribute('id');
300
		else
301
			$count = 0;
302
 
303
		//for each message add it to the XML file using DOM
304
    	foreach($messages as $message)
305
    	{
306
			$unit = $dom->createElement('trans-unit');
307
			$unit->setAttribute('id',++$count);
308
 
309
			$source = $dom->createElement('source', $message);
310
			$target = $dom->createElement('target','');
311
 
312
			$unit->appendChild($dom->createTextNode("\n"));
313
			$unit->appendChild($source);
314
			$unit->appendChild($dom->createTextNode("\n"));
315
			$unit->appendChild($target);
316
			$unit->appendChild($dom->createTextNode("\n"));
317
 
318
			$body->appendChild($dom->createTextNode("\n"));
319
			$body->appendChild($unit);
320
			$body->appendChild($dom->createTextNode("\n"));
321
    	}
322
 
323
 
324
    	$fileNode = $xpath->query('//file')->item(0);
325
    	$fileNode->setAttribute('date', @date('Y-m-d\TH:i:s\Z'));
326
 
327
    	//save it and clear the cache for this variant
328
    	$dom->save($filename);
329
		if(!empty($this->cache))
330
	    	$this->cache->clean($variant, $this->culture);
331
 
332
    	return true;
333
	}
334
 
335
	/**
336
	 * Update the translation.
337
	 * @param string the source string.
338
	 * @param string the new translation string.
339
	 * @param string comments
340
	 * @param string the catalogue to save to.
341
	 * @return boolean true if translation was updated, false otherwise.
342
	 */
343
	public function update($text, $target, $comments, $catalogue='messages')
344
	{
345
		$variants = $this->getVariants($catalogue);
346
		if($variants)
347
			list($variant, $filename) = $variants;
348
		else
349
			return false;
350
 
351
		if(is_writable($filename) == false)
352
			throw new TIOException("Unable to update file {$filename}, file must be writable.");
353
 
354
		//create a new dom, import the existing xml
355
		$dom = DOMDocument::load($filename);
356
 
357
		//find the body element
358
		$xpath = new DomXPath($dom);
359
		$units = $xpath->query('//trans-unit');
360
 
361
		//for each of the existin units
362
		foreach($units as $unit)
363
		{
364
			$found = false;
365
			$targetted = false;
366
			$commented = false;
367
 
368
			//in each unit, need to find the source, target and comment nodes
369
			//it will assume that the source is before the target.
370
			foreach($unit->childNodes as $node)
371
			{
372
				//source node
373
				if($node->nodeName == 'source'
374
				  && $node->firstChild->wholeText == $text)
375
				{
376
					 	$found = true;
377
				}
378
 
379
				//found source, get the target and notes
380
				if($found)
381
				{
382
					//set the new translated string
383
					if($node->nodeName == 'target')
384
					{
385
						$node->nodeValue = $target;
386
						$targetted = true;
387
					}
388
					//set the notes
389
					if(!empty($comments) && $node->nodeName == 'note')
390
					{
391
						$node->nodeValue = $comments;
392
						$commented = true;
393
					}
394
				}
395
			}
396
 
397
			//append a target
398
			if($found && !$targetted)
399
				$unit->appendChild($dom->createElement('target',$target));
400
 
401
			//append a note
402
			if($found && !$commented && !empty($comments))
403
				$unit->appendChild($dom->createElement('note',$comments));
404
 
405
			//finished searching
406
			if($found) break;
407
		}
408
 
409
    	$fileNode = $xpath->query('//file')->item(0);
410
    	$fileNode->setAttribute('date', @date('Y-m-d\TH:i:s\Z'));
411
 
412
		if($dom->save($filename) >0)
413
		{
414
			if(!empty($this->cache))
415
				$this->cache->clean($variant, $this->culture);
416
			return true;
417
		}
418
 
419
		return false;
420
	}
421
 
422
	/**
423
	 * Delete a particular message from the specified catalogue.
424
	 * @param string the source message to delete.
425
	 * @param string the catalogue to delete from.
426
	 * @return boolean true if deleted, false otherwise.
427
	 */
428
	public function delete($message, $catalogue='messages')
429
	{
430
		$variants = $this->getVariants($catalogue);
431
		if($variants)
432
			list($variant, $filename) = $variants;
433
		else
434
			return false;
435
 
436
		if(is_writable($filename) == false)
437
			throw new TIOException("Unable to modify file {$filename}, file must be writable.");
438
 
439
		//create a new dom, import the existing xml
440
		$dom = DOMDocument::load($filename);
441
 
442
		//find the body element
443
		$xpath = new DomXPath($dom);
444
		$units = $xpath->query('//trans-unit');
445
 
446
		//for each of the existin units
447
		foreach($units as $unit)
448
		{
449
			//in each unit, need to find the source, target and comment nodes
450
			//it will assume that the source is before the target.
451
			foreach($unit->childNodes as $node)
452
			{
453
				//source node
454
				if($node->nodeName == 'source'
455
				  && $node->firstChild->wholeText == $message)
456
				{
457
 
458
					//we found it, remove and save the xml file.
459
					$unit->parentNode->removeChild($unit);
460
 
461
    				$fileNode = $xpath->query('//file')->item(0);
462
    				$fileNode->setAttribute('date', @date('Y-m-d\TH:i:s\Z'));
463
 
464
					if($dom->save($filename) >0)
465
					{
466
						if(!empty($this->cache))
467
							$this->cache->clean($variant, $this->culture);
468
						return true;
469
					}
470
					else return false;
471
 
472
				}
473
			}
474
 
475
		}
476
 
477
		return false;
478
	}
479
 
480
	protected function createMessageTemplate($catalogue)
481
	{
482
		if($catalogue === null) {
483
			$catalogue = 'messages';
484
		}
485
		$variants = $this->getCatalogueList($catalogue);
486
		$variant = array_shift($variants);
487
		$file = $this->getSource($variant);
488
		$dir = dirname($file);
489
		if(!is_dir($dir))
490
		{
491
			@mkdir($dir);
492
			@chmod($dir,PRADO_CHMOD);
493
		}
494
		if(!is_dir($dir))
495
			throw new TException("Unable to create directory $dir");
496
		file_put_contents($file, $this->getTemplate($catalogue));
497
		chmod($file, PRADO_CHMOD);
498
		return array($variant, $file);
499
	}
500
 
501
	protected function getTemplate($catalogue)
502
	{
503
		$date = @date('c');
504
$xml = <<<EOD
505
<?xml version="1.0" encoding="UTF-8"?>
506
<xliff version="1.0">
507
 <file
508
	source-language="EN"
509
	target-language="{$this->culture}"
510
	datatype="plaintext"
511
	original="$catalogue"
512
	date="$date"
513
	product-name="$catalogue">
514
  <body>
515
  </body>
516
 </file>
517
</xliff>
518
EOD;
519
		return $xml;
520
	}
521
}
522
 
523
?>