1: <?php
2: /**
3: * WsLocalize
4: * Translates strings in application to specific language. Create language text
5: * file in "lang" directory. Language file is in JSON format. For example:
6: * create "lang/hr.txt" file for croatian translations, with example content:
7: * <code>
8: * {
9: * 'message string':'prva poruka',
10: * 'message string2':'druga poruka'
11: * }
12: * </code>
13: *
14: * Example usage:
15: *
16: * <code>
17: * // this will display "prva poruka" if browser language is set to croatian
18: * echo WsLocalize::msg('message string');
19: * </code>
20: *
21: */
22: class WsLocalize
23: {
24: public static function msg($str)
25: {
26: /* translation file
27: * (static is used for ensure only one loading of file)
28: */
29: static $translations = NULL;
30:
31: if (is_null($translations)) {
32: // language
33: $lang = substr(
34: filter_input(INPUT_SERVER, 'HTTP_ACCEPT_LANGUAGE'),
35: 0,
36: 2
37: );
38:
39: // language file
40: $lang_file = WsROOT.'/lang/'.$lang.'.txt';
41:
42: // load default language file if specific language don't exist
43: if (!file_exists($lang_file)) {
44: // no translation file found; return unchanged message
45: return $str;
46: }
47:
48: /* Load the language file as a JSON object and transform it into
49: * an associative array
50: */
51: $lang_file_content = file_get_contents($lang_file);
52: $translations = json_decode($lang_file_content, true);
53: }
54:
55: if (!empty($translations[$str])) {
56: return $translations[$str];
57: } else {
58: return $str;
59: }
60: }
61:
62:
63: /**
64: * get current language
65: *
66: * @return string $lang
67: *
68: */
69: public static function getLang()
70: {
71: $lang = substr(
72: filter_input(INPUT_SERVER, 'HTTP_ACCEPT_LANGUAGE',
73: FILTER_SANITIZE_STRING), 0, 2);
74:
75: return($lang);
76: }
77: }
78:
79: