summaryrefslogtreecommitdiff
path: root/text.class
blob: 9db215b988733ddb9999deb586d67cfb82e892a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
<?php
/*
**	$Id$
**
**	ITools - the Internet Tools Library
**
**	Copyright (C) 1995-2006 by the ITools Authors.
**	This program is free software; you can redistribute it and/or
**	modify it under the terms of either the GNU General Public License
**	or the GNU Lesser General Public License, as published by the Free
**	Software Foundation. See http://www.gnu.org/licenses/ for details.
**
*/

class it_text
{
	var $defaultlanguage;			# Preferred language (without cookie)
	var $actlanguage;			# Selected language
	var $actlanguagename;			# Name of selected language
	var $languages = array();		# Active languages
	var $languages_available = array();	# Available languages
	var $language_failsafe;			# First available language
	var $statictext = array();		# Text array, read from php file on init
	var $debug;				# Non-empty if debug mode is desired
	var $cookiename;			# Name of the language cookie, default is "LANGUAGE"
	var $unknown_labels = array();		# array for spooling unknown labels in debug mode

/**
 * Constructor
 * @param $defaultlanguage Optional default language to use
 * @param $tablename Optional name of text database table (default: 'it_texts')
 * @param $debug Optional debug mode: display label of unknown texts, set to 'label' to always display labels instead of actual text
 * @param $db Optional database object, defaults to global $it_db
 * @param $cookiename Optional cookie name (default: 'LANGUAGE')
 */
function it_text($defaultlanguage = 'de', $tablename = 'it_texts', $debug = '', $db = 0, $cookiename = 'LANGUAGE')
{
	$this->phpfile = isset($phpfile) ? $phpfile : ($GLOBALS['ULTRAHOME'] . '/phpinclude/texts.php');
	$this->debug = $debug;
	$this->cookiename = $cookiename;

	# Read $this->statictext from php file if it's not defined yet
	if (!$this->statictext)
		include($this->phpfile);

	# $$$ MIGRATION: Try to create texts.php from database if it doesn't exist
	if (!$this->statictext)
	{
		$db = is_object($db) ? $db : $GLOBALS['it_db'];
		$table = new it_db_table($db, $tablename);
		$record = new it_db_record($table, 'Label');
		for ($record->select(); $record->fetch_next();)
		{
			$data = $record->data;
			unset($data['Label']);
			$this->statictext[$record->data['Label']] = $data;
		}
		$this->dump_php();
	}

	# Get array of supported languages and their names
	foreach(array_keys($this->statictext['_']) as $code)
	{
		# If a language's name in '_' is unset, ignore it
		if ($languagename = $this->statictext['_'][$code])
		{
			$this->languages_available[$code] = $languagename;
			# Only use a language in browser/cookie detection below if it's not diasbled by a leading '-'
			if (substr($languagename, 0, 1) != '-')
			{
				$this->languages[$code] = $languagename;
				if (!isset($this->language_failsafe))
					$this->language_failsafe = $code;
			}
		}
	}

	# Set our default language according to browser preference
	if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
	{
		foreach(explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang)
		{
			if (isset($this->languages[$lang]))
			{
				$this->defaultlanguage = $lang;
				debug("Got language from browser: {$this->defaultlanguage}", 6);
				break;
			}
			else
			{
				$short = substr($lang, 0, 2);
				if (isset($this->languages[$short]))
				{
					$this->defaultlanguage = $short;
					debug("Got language family from browser: {$this->defaultlanguage}", 6);
					break;
				}
			}
		}
		if (count($this->languages) == 0)
			debug("No active languages found!", 5);
	}

	# If no language matched, use the one that was supplied by our caller
	if (!isset($this->defaultlanguage))
		$this->defaultlanguage = $defaultlanguage;

	# If language is still invalid, use failsafe language
	if (!$this->languages[$this->defaultlanguage])
	{
		debug("Bad language \"{$this->defaultlanguage}\", using first entry \"{$this->languages[$this->language_failsafe]}\"", 5);
		$this->defaultlanguage = $this->language_failsafe;
	}

	# If a cookie is set, we use its value as our active language
	if (isset($_COOKIE[$this->cookiename]) && ($cookie = $_COOKIE[$this->cookiename]))
	{
		if ($this->languages[$cookie])	# Is this language available?
		{
			$this->actlanguage = $cookie;
			debug("Got language from cookie: {$this->actlanguage}", 6);
		}
	}

	# If the cookie supplied no valid language, we use our calculated default language
	if (!isset($this->actlanguage))
		$this->actlanguage = $this->defaultlanguage;

	# And finally, record the name of our active language.
	$this->actlanguagename = $this->languages[$this->actlanguage];

	debug("Used language is {$this->actlanguagename}, default language is {$this->defaultlanguage}.", 6);
}


/**
 * Return a text in the selected language.
 * @param $label Label of text to return
 * @param $raw Optional unused obsolete parameter
 * @param $language Optional language to return text in.
 * @return Localized text string
 */
function text($label, $raw = null, $language = null)
{
	if ($this->debug === 'label')
		return $label;
	
	if (!isset($language))
		$language = $this->actlanguage;

	if (isset($this->statictext[$label][$language]))
		return $this->statictext[$label][$language];

	$this->unknown_labels[] = $label;
	return $this->debug ? "<blink>$label ($language)</blink>" : $this->label_unknown($label);
}


/**
 * Localized function called when a label is not found
 * overload this if for example you want to have a silent error behaviour
 * @param $label Text label that was not found in database
 */
function label_unknown($label)
{
	internal_error("No text found for label \"$label\"");
}


/**
 * Return a text in the selected language, with correctly encoded umlauts.
 * Replaces variables of the form {obj.var} with value, e.g. {user.name}
 * NOTE: Invalid object names or non-existing variables are simply deleted.
 * @param $label Label of text to return
 * @param $values Associative array containing values to fill in
 * @param $language Optional language to return text in.
 * @return Localized text string with variables replaced by their values
 */
function etext($label, $values = null, $language = null)
{
	return it_text_transmogrify($this->text($label, null, $language), $values);
}


/**
 * Change language
 * @param $language New language to set
 * @param $setcookie Optional flag if a cookie is to be set (default: true)
 */
function set_language($language, $setcookie = true)
{
	/* If set to an invalid language (via forged GET?) we delete the cookie */
	if ($this->languages_available[$language])
	{
		if (!$this->languages[$language])
			debug('Selected an existing but currently disabled language!', 6);
		$this->actlanguage = $language;
		if ($setcookie)
			SetCookie($this->cookiename, $this->actlanguage, time() + 31536000, '/');	# 1 year
	}
	else
	{
		$this->actlanguage = $this->defaultlanguage;
		if ($setcookie)
			SetCookie($this->cookiename, '', time() + 31536000, '/');
	}
}


/**
 * Get active language
 * @return currently active language
 */
function get_language()
{
	return $this->actlanguage;
}


/**
 * Get default language
 * @return default language
 */
function get_default_language()
{
	return $this->defaultlanguage;
}


/**
 * Check if a text entry for a specific label exists
 * @param $label Label to check
 * @return true if text exists in actual (or supplied) language, false otherwise.
 */
function text_exists($label, $language = null)
{
	return isset($this->statictext[$label][isset($language) ? $language : $this->actlanguage]);
}


/**
 * Create / overwrite a text in the selected language. Call dump_php() to make the change permanent.
 * @param $label Label of text to change
 * @param $text New text to set
 * @param $language Optional language that is to be manipulated
 */
function set($label, $text = null, $language = null)
{
	if (!isset($language))
		$language = $this->actlanguage;

	$this->statictext[$label][$language] = $text;
}


/**
 * when running it_text in debug mode, you can use this to die (internal_error)
 * in case there were unknown labels with a list of all unknown labels
 */
function checkout_unknown_labels()
{
	if ($this->unknown_labels)
		internal_error('No text found for labels: ' . implode(',', $this->unknown_labels));
}
	

/**
 * Replaces special chars with their TeX equivalent
 * @param $text Text to convert from ISO-8859-1 to TeX encoding
 * @param $convertlinebreaks Whether to convert LFs to TeX linebreaks
 * @return TeX encoded text to be inserted into TeX template
 */
function texify($text, $convertlinebreaks = true)
{
	$translation = array
	(
		'À' => '{\`A}',
		'Á' => "{\'A}",
		'Â' => '{\^A}',
		'Ã' => '{\~A}',
		'Ä' => '{\"A}',
		'Ç' => '{\c C}',
		'È' => '{\`E}',
		'É' => "{\'E}",
		'Ê' => '{\^E}',
		'Ë' => '{\"E}',
		'Ì' => '{\`I}',
		'Í' => "{\'I}",
		'Î' => '{\^I}',
		'Ï' => '{\"I}',
		'Ñ' => '{\~N}',
		'Ò' => '{\`O}',
		'Ó' => "{\'O}",
		'Ô' => '{\^O}',
		'Õ' => '{\~O}',
		'Ö' => '{\"O}',
		'Ù' => '{\`U}',
		'Ú' => "{\'U}",
		'Û' => '{\^U}',
		'Ü' => '{\"U}',
		'ß' => '{\ss}',
		'à' => '{\`a}',
		'á' => "{\'a}",
		'â' => '{\^a}',
		'ã' => '{\~a}',
		'ä' => '{\"a}',
		'ç' => '{\c c}',
		'è' => '{\`e}',
		'é' => "{\'e}",
		'ê' => '{\^e}',
		'ë' => '{\"e}',
		'ì' => '{\`i}',
		'í' => "{\'i}",
		'î' => '{\^i}',
		'ï' => '{\"i}',
		'ñ' => '{\~n}',
		'ò' => '{\`o}',
		'ó' => "{\'o}",
		'ô' => '{\^o}',
		'õ' => '{\~o}',
		'ö' => '{\"o}',
		'ù' => '{\`u}',
		'ú' => "{\'u}",
		'û' => '{\^u}',
		'ü' => '{\"u}',
		'ÿ' => '{\"y}',
		'"' => "''",
		'\\' => '/',
		'%' => '\%',
		'$' => '\$',
		'#' => '\#',
		'&' => '\&',
		'_' => '\_',
		'^' => '',
	);

	if ($convertlinebreaks)
		$translation["\n"] = "\\\\\n";

	return strtr($text, $translation);
}

/**
 * Re-create php text file from $this->statictext
 * @return true if successful, false if not (usually if file is not writeable by user www)
 */
function dump_php()
{
	$result = false;

	# Special sorting: natural, but _ is the first entry
	$keys = array_keys($this->statictext);
	natsort($keys);
	foreach($keys as $key)
		$text[$key] = $this->statictext[$key];
	$this->statictext = array_merge(array('_' => $text['_']), $text);

	$oldmask = umask(002);
	if ($f = fopen($this->phpfile, 'w'))
	{
		$result = (fputs($f, '<?php $this->statictext = ' . strtr(var_export($this->statictext, TRUE), array("=> \n  array (" => "=> array(", "array (\n  '_'" => "array(\n'_'", "\n  ),\n  " => "\n),\n", "\n  ),\n" => "\n)\n")) . ";\n?>\n") !== false);
		fclose($f);
	}

	umask($oldmask);
	return $result;
}

} /* End class it_text */


/*
 * Globally available functions without need for object
 */

/**
 * Replaces variables of the form {obj.var} with value, e.g. {user.name}
 * NOTE: Invalid object names or non-existing variables are simply deleted.
 */
function it_text_transmogrify($text, $values = null)
{
	while (preg_match('/{([\w.]+)}/', $text, $regs))
	{
		$path = explode('.', $regs[1]);
		if ($values)
			$value =& $values;
		else
			$value =& $GLOBALS;

		/* Recurse into nested arrays/object members */
		foreach ($path as $key)
		{
			if (is_object($value))
				$value =& $value->$key;
			else
				$value =& $value[$key];
		}

		$text = str_replace($regs[0], $value, $text);
	}

	return $text;
}


/*
 * Shortcut to $it_text->Text()
 */
function T($label, $raw = null, $language = null)
{
	return $GLOBALS['it_text']->text($label, $raw, $language);
}


/*
 * Shortcut to $it_text->etext()
 */
function ET($label, $values = null, $language = null)
{
	return $GLOBALS['it_text']->etext($label, $values, $language);
}

/**
 * Shortcut to $it_text->get_language()
 */
function T_lang()
{
	return isset($GLOBALS['it_text']) ? $GLOBALS['it_text']->get_language() : "de";
}

/**
 * Shortcut to $it_text->get_language()
 */
function T_set_language($language, $setcookie = true)
{
	return $GLOBALS['it_text']->set_language($language, $setcookie);
}

/**
 * Shortcut to $it_text->text_exists()
 */
function T_exists($label, $language = null)
{
	return $GLOBALS['it_text']->text_exists($label, $language);
}
?>