summaryrefslogtreecommitdiff
path: root/it_text.class
blob: ab9f3adf90000cf20284eb9c6f550f0a0bd5375e (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
<?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 $actlanguage;			# Selected language
	var $defaultlanguage;			# Browser language
	var $languages = array();		# Active languages
	var $languages_available = array();	# Available languages
	var $statictext = array();		# Text array, read from php file on init

/**
 * Constructor
 * @param $p['cookiename'] optional cookie name (default: 'LANGUAGE')
 * @param $p['debug'] optional debug mode: display label of unknown texts, set to 'label' to always display labels instead of actual text
 * @param $p['fallbacklanguage'] optional language to use for undefined texts (useful for partially translated projects)
 * @param $p['forcelanguage'] optional language to use instead of user's preferred language
 * @param $p['phpfile'] optional texts file, defaults to service's phpinclude/texts.php
 */
function it_text($p = null)
{
	$this->p = (array)$p + array('cookiename' => 'LANGUAGE', 'debug' => false, 'phpfile' => $GLOBALS['ULTRAHOME'] . '/phpinclude/texts.php');

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

	# Get array of supported languages and their names
	$this->languages_available = $this->statictext['_'];
	foreach($this->languages_available as $code => $languagename)
	{
		# Only use a language in browser/cookie detection below if it's not disabled by a leading '-'
		if (substr($languagename, 0, 1) != '-')
		{
			$this->languages[$code] = $languagename;
			if (!$this->actlanguage)
				$this->initlang($code, "setting failsafe language");
		}
	}

	# Set our default language according to browser preference
	if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
	{
		foreach(explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $code)
			if ($this->initlang($code, "setting language from browser") || $this->initlang(substr($code, 0, 2), "setting language family from browser"))
				break;
	}
	$this->defaultlanguage = $this->actlanguage;

	$this->initlang(it::match('\.([a-z]{2})\.[^./]+$', $_SERVER['PHP_SELF']), "setting language from url override");
	$this->initlang($this->languages[$_COOKIE[$this->p['cookiename']]], "setting language from cookie");
	$this->initlang($this->p['forcelanguage'], "setting language from programmer override");

	# Make this object available under $GLOBALS['it_text'], or add my texts to $GLOBALS['it_text'] if it exists
	if (!$GLOBALS['it_text'])
		$GLOBALS['it_text'] =& $this;
	else
		$GLOBALS['it_text']->statictext += $this->statictext;
}


# internal: overwrite language setting if code is valid, return success
function initlang($code, $debugmsg)
{
	if ($this->languages[$code])
		$this->actlanguage = $code;

	return $this->languages[$code];
}


/**
 * Instanciate singleton if necessary
 */
function init()
{
	if (!$GLOBALS['it_text'])
		new it_text;
}



/**
 * INTERNAL function for T(): 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->p['debug'] === 'label')
		return $label;
	
	if (!isset($language))
		$language = $this->actlanguage;

	if (isset($this->statictext[$label][$language]))
		return $this->statictext[$label][$language];
	elseif ($this->p['fallbacklanguage'] && isset($this->statictext[$label][$this->p['fallbacklanguage']]))
		return $this->statictext[$label][$this->p['fallbacklanguage']];

	if ($fh = fopen($GLOBALS['ULTRAHOME'] . "/log/text_log", "a"))
	{
		fputs($fh, date("Y-m-d H:i:s") . "\t" . $_SERVER['REQUEST_URI'] . "\t" . $label . "\t" . $language . "\t" . it::replace(array('auto_prepend\S+\s+'=>''), it_debug::backtrace()) . "\n");
		fclose($fh);
	}

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


/**
 * INTERNAL function for ET(): Return a text in the selected language
 * 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 $this->transmogrify($this->text($label, null, $language), $values);
}


/**
 * INTERNAL function for T_set_language(): 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 $language is unknown, 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->p['cookiename'], $this->actlanguage, time() + 31536000, '/');	# 1 year
	}
	else
	{
		$this->actlanguage = $this->defaultlanguage;
		if ($setcookie)
			SetCookie($this->p['cookiename'], '', time() + 31536000, '/');
	}
}


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


/**
 * INTERNAL function for T_exists(): 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;
}


/**
 * 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 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;
}


/**
 * 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->p['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 */
?>