96d39648176063480b80b6f99ffd62c93cccf3d5
[acontent.git] / docs / include / classes / Language / LanguageManager.class.php
1 <?php
2 /************************************************************************/
3 /* AContent                                                             */
4 /************************************************************************/
5 /* Copyright (c) 2010                                                   */
6 /* Inclusive Design Institute                                           */
7 /*                                                                      */
8 /* This program is free software. You can redistribute it and/or        */
9 /* modify it under the terms of the GNU General Public License          */
10 /* as published by the Free Software Foundation.                        */
11 /************************************************************************/
12
13 require_once(dirname(__FILE__) . '/Language.class.php');
14
15 //define('TR_LANG_STATUS_EMPTY',       0);
16 //define('TR_LANG_STATUS_INCOMPLETE',  1);
17 //define('TR_LANG_STATUS_COMPLETE',    2);
18 //define('TR_LANG_STATUS_PUBLISHED',   3);
19
20 /**
21 * LanguageManager
22 * Class for managing available languages as Language Objects.
23 * @access       public
24 * @author       Joel Kronenberg
25 * @see          Language.class.php
26 * @package      Language
27 */
28 class LanguageManager {
29
30         /**
31         * This array stores references to all the Language Objects
32         * that are available in this installation.
33         * @access private
34         * @var array
35         */
36         var $allLanguages;
37         
38         /**
39         * This array stores references to the Language Objects
40         * that are available in this installation.
41         * @access private
42         * @var array
43         */
44         var $availableLanguages;
45
46         /**
47         * The number of languages that are available. Does not include
48         * character set variations.
49         * @access private
50         * @var integer
51         */
52         var $numEnabledLanguages;
53
54         /**
55         * Constructor.
56         * 
57         * Initializes availableLanguages and numLanguages.
58         */
59         function LanguageManager() {
60                 require_once(TR_INCLUDE_PATH. 'classes/DAO/LanguagesDAO.class.php');
61                 $languagesDAO = new LanguagesDAO();
62                 
63                 // initialize available lanuguages. Available languages are the ones with status "enabled"
64                 $rows = $languagesDAO->getAllEnabled();
65                 
66                 // if there's no enabled language, set to default language and default charset
67                 if (!is_array($rows))
68                 {
69                         $rows = array($languagesDAO->getByLangCodeAndCharset(DEFAULT_LANGUAGE_CODE, DEFAULT_CHARSET));
70                 }
71                 foreach ($rows as $i => $row) {
72                         $this->availableLanguages[$row['language_code']][$row['charset']] = new Language($row);
73                 }
74                 $this->numEnabledLanguages = count($this->availableLanguages);
75
76                         // initialize available lanuguages. Available languages are the ones with status "enabled"
77                 $rows = $languagesDAO->getAll();
78                 
79                 foreach ($rows as $i => $row) {
80                         $this->allLanguages[$row['language_code']][$row['charset']] = new Language($row);
81                 }
82                 $this->numLanguages = count($this->allLanguages);
83         }
84
85
86         /**
87         * Returns a valid Language Object based on the given language $code and optional
88         * $charset, FALSE if it can't be found.
89         * @access       public
90         * @param        string $code            The language code of the language to return.
91         * @param        string $charset         Optionally, the character set of the language to find.
92         * @return       boolean|Language        Returns FALSE if the requested language code and
93         *                                                               character set cannot be found. Returns a Language Object for the
94         *                                                               specified language code and character set.
95         * @see          getMyLanguage()
96         */
97         function getLanguage($code, $charset = '') {
98                 if (!$charset) {
99                         if (isset($this->allLanguages[$code])) {
100                                 if (is_array($this->allLanguages[$code]))
101                                         foreach ($this->allLanguages[$code] as $language)
102                                                 return $language;
103 //                              return current($this->allLanguages[$code]);
104                         } else {
105                                 return FALSE;
106                         }
107                 }
108
109                 foreach ($this->allLanguages[$code] as $language) {
110                         if ($language->getCharacterSet() == $charset) {
111                                 return $language;
112                         }
113                 }
114                 return FALSE;
115         }
116
117         /**
118         * Tries to detect the user's current language preference/setting from (in order):
119         * _GET, _POST, _SESSION, HTTP_ATCEPT_LANGUAGE, HTTP_USER_AGENT. If no match can be made
120         * then it tries to detect a default setting (defined in config.inc.php) or a fallback
121         * setting, false if all else fails.
122         * @access       public
123         * @return       boolean|Language        Returns a Language Object matching the user's current session.
124         *                                                               Returns FALSE if a valid Language Object cannot be found
125         *                                                               to match the request
126         * @see          getLanguage()
127         */
128         function getMyLanguage() {
129                 global $addslashes, $db, $_config; 
130
131                 if (isset($_GET) && !empty($_GET['lang']) && isset($this->availableLanguages[$_GET['lang']])) {
132                         $language = $this->getLanguage($_GET['lang']);
133
134                         if ($language) {
135                                 return $language;
136                         }
137                 } 
138                 
139                 if (isset($_POST) && !empty($_POST['lang']) && isset($this->availableLanguages[$_POST['lang']])) {
140                         $language = $this->getLanguage($_POST['lang']);
141
142                         if ($language) {
143                                 return $language;
144                         }
145                 }
146
147                 if (isset($_SESSION) && isset($_SESSION['lang']) && !empty($_SESSION['lang']) && isset($this->availableLanguages[$_SESSION['lang']])) {
148                         $language = $this->getLanguage($_SESSION['lang']);
149
150                         if ($language) {
151                                 return $language;
152                         }
153                 }
154
155                 // Didn't catch any valid lang : we use the default settings
156                 if (isset($_config['default_language'])) $default_lang = $_config['default_language'];
157                 else $default_lang = DEFAULT_LANGUAGE_CODE;
158                 
159                 if (isset($this->availableLanguages[$default_lang])) {
160                         $language = $this->getLanguage($default_lang, DEFAULT_CHARSET);
161
162                         if ($language) {
163                                 return $language;
164                         }
165                 }
166
167                 if (!empty($_SERVER['HTTP_ATCEPT_LANGUAGE'])) {
168                         // Language is not defined yet :
169                         // try to find out user's language by checking its HTTP_ATCEPT_LANGUAGE
170                         $accepted    = explode(',', $_SERVER['HTTP_ATCEPT_LANGUAGE']);
171                         $acceptedCnt = count($accepted);
172                         reset($accepted);
173                         for ($i = 0; $i < $acceptedCnt; $i++) {
174                                 foreach ($this->availableLanguages as $codes) {
175                                         foreach ($codes as $language) {
176                                                 if ($language->isMatchHttpAcceptLanguage($accepted[$i])) {
177                                                         return $language;
178                                                 }
179                                         }
180                                 }
181                         }
182                 }
183                 
184                 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
185                         // Language is not defined yet :
186                         // try to find out user's language by checking its HTTP_USER_AGENT
187                         foreach ($this->availableLanguages as $codes) {
188                                 foreach ($codes as $language) {
189                                         if ($language->isMatchHttpUserAgent($_SERVER['HTTP_USER_AGENT'])) {
190                                                 return $language;
191                                         }
192                                 }
193                         }
194                 }
195
196                 // else pick one at random:
197                 reset($this->availableLanguages);
198                 $uknown_language = current($this->availableLanguages);
199                 if ($unknown_language) {
200                         return FALSE;
201                 }
202                 
203                 return current($uknown_language);
204         }
205
206         function getAvailableLanguages() {
207                 return $this->availableLanguages;
208         }
209
210         // public
211         function printDropdown($current_language, $name, $id) {
212                 echo '<select name="'.$name.'" id="'.$id.'">';
213
214                 foreach ($this->availableLanguages as $codes) {
215                         $language = current($codes);
216                         if ($language->getStatus() == TR_STATUS_ENABLED) {
217                                 echo '<option value="'.$language->getCode().'"';
218                                 if ($language->getCode() == $current_language) {
219                                         echo ' selected="selected"';
220                                 }
221                                 echo '>'.$language->getNativeName().'</option>';
222                         }
223                 }
224                 echo '</select>';
225         }
226
227         // public
228         function printList($current_language, $name, $id, $url) {
229
230                 $delim = false;
231                 
232                 foreach ($this->availableLanguages as $codes) {
233                         $language = current($codes);
234
235                         if ($language->getStatus() == TR_STATUS_ENABLED) {
236
237                                 if ($delim){
238                                         echo ' | ';
239                                 }
240
241                                 if ($language->getCode() == $current_language) {
242                                         echo '<strong>'.$language->getNativeName().'</strong>';
243                                 } else {
244                                         echo '<a href="'.$url.'lang='.$language->getCode().'">'.$language->getNativeName().'</a> ';
245                                 }
246
247                                 $delim = true;
248                         }
249                 }
250         }
251
252         // public
253         function getNumEnabledLanguages() {
254                 return $this->numEnabledLanguages;
255         }
256
257         function getNumLanguages() {
258                 return $this->numLanguages;
259         }
260         
261         // public
262         // checks whether or not the language exists
263         function exists($code) {
264                 return isset($this->allLanguages[$code]);
265         }
266
267         // public
268         // import language pack from specified file
269         function import($filename) {
270                 require_once(TR_INCLUDE_PATH . 'lib/pclzip.lib.php');
271                 require_once(TR_INCLUDE_PATH . 'classes/Language/LanguageParser.class.php');
272                 require_once(TR_INCLUDE_PATH . 'classes/DAO/LanguagesDAO.class.php');
273                 
274                 global $languageManager, $msg;
275
276                 $import_path = TR_CONTENT_DIR . 'import/';
277
278                 $archive = new PclZip($filename);
279                 if ($archive->extract(PCLZIP_OPT_PATH,  $import_path) == 0) {
280                         exit('Error : ' . $archive->errorInfo(true));
281                 }
282
283                 $language_xml = @file_get_contents($import_path.'language.xml');
284
285                 $languageParser = new LanguageParser();
286                 $languageParser->parse($language_xml);
287                 $languageEditor =& $languageParser->getLanguageEditor(0);
288
289                 $lang_code = $languageEditor->getCode();
290                 if ($languageManager->exists($lang_code)) {
291                         $msg->addError('LANG_EXISTS');
292                 }
293
294                 if (!$msg->containsErrors()) {
295                         $languageEditor->import($import_path . 'language_text.sql');
296                         $languagesDAO = new LanguagesDAO();
297                         $languagesDAO->UpdateField($lang_code, "status", TR_STATUS_ENABLED);
298                         $msg->addFeedback('IMPORT_LANG_SUCCESS');
299                         
300                         $version_in_pack = $languageEditor->getTransformableVersion();
301                         if ($version_in_pack != VERSION) 
302                         {
303                                         $msg->addFEEDBACK(array('LANG_MISMATCH_VERSION', $version_in_pack, VERSION));
304                         }
305
306                 }
307
308                 // remove the files:
309                 @unlink($import_path . 'language.xml');
310                 @unlink($import_path . 'language_text.sql');
311                 @unlink($import_path . 'readme.txt');
312                 @unlink($filename);
313         }
314
315         // public
316         // imports LIVE language from the AContent  language database
317         function liveImport($language_code) {
318                 global $db;
319
320                 $tmp_lang_db = mysql_connect(TR_LANG_DB_HOST, TR_LANG_DB_USER, TR_LANG_DB_PASS);
321                 // set database connection using utf8
322                 mysql_query("SET NAMES 'utf8'", $tmp_lang_db);
323                 
324                 if (!$tmp_lang_db) {
325                         /* TR_ERROR_NO_DB_CONNECT */
326                         echo 'Unable to connect to db.';
327                         exit;
328                 }
329                 if (!mysql_select_db('dev_ATansformable_langs', $tmp_lang_db)) {
330                         echo 'DB connection established, but database "dev_ATansformable_langs" cannot be selected.';
331                         exit;
332                 }
333
334                 $sql = "SELECT * FROM languages_SVN WHERE language_code='$language_code'";
335                 $result = mysql_query($sql, $tmp_lang_db);
336
337                 if ($row = mysql_fetch_assoc($result)) {
338                         $row['reg_exp'] = addslashes($row['reg_exp']);
339                         $row['native_name'] = addslashes($row['native_name']);
340                         $row['english_name'] = addslashes($row['english_name']);
341
342                         $sql = "REPLACE INTO ".TABLE_PREFIX."languages VALUES ('{$row['language_code']}', '{$row['charset']}', '{$row['reg_exp']}', '{$row['native_name']}', '{$row['english_name']}', 3)";
343                         $result = mysql_query($sql, $db);
344
345                         $sql = "SELECT * FROM language_text_SVN WHERE language_code='$language_code'";
346                         $result = mysql_query($sql, $tmp_lang_db);
347
348                         $sql = "REPLACE INTO ".TABLE_PREFIX."language_text VALUES ";
349                         while ($row = mysql_fetch_assoc($result)) {
350                                 $row['text'] = addslashes($row['text']);
351                                 $row['context'] = addslashes($row['context']);
352                                 $sql .= "('{$row['language_code']}', '{$row['variable']}', '{$row['term']}', '{$row['text']}', '{$row['revised_date']}', '{$row['context']}'),";
353                         }
354                         $sql = substr($sql, 0, -1);
355                         mysql_query($sql, $db);
356                 }
357         }
358         
359 }
360
361
362 ?>