add support for aching all of the translations
[Pman.Core] / DataObjects / I18n.php
1 <?php
2 /**
3  * Table Definition for i18n
4  *
5  * This is heavily related to the Pman_I18n implementation..
6  *
7  * It should eventually replace most of that..
8  * 
9  */
10 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
11
12 class Pman_Core_DataObjects_I18n extends DB_DataObject 
13 {
14     ###START_AUTOCODE
15     /* the code below is auto generated do not remove the above tag */
16
17     public $__table = 'i18n';                            // table name
18     public $id;                              // int(11)  not_null primary_key auto_increment
19     public $ltype;                           // string(1)  not_null multiple_key
20     public $lkey;                            // string(8)  not_null
21     public $inlang;                          // string(8)  not_null
22     public $lval;                            // string(64)  not_null
23
24     
25     /* the code above is auto generated do not remove the tag below */
26     ###END_AUTOCODE
27     
28     // we have a small default set of languages available..
29     // you can modify this by making this setting in the index.php loader.
30     // Pman_Core_i18n = array( 'c' => *, 'l' => '*', 'm' => '*')
31     
32     static $cfg = array(
33         // translated versions availalable
34         
35         't' => array(
36             'en', 'zh_CN',   'zh_HK', 
37         ),
38         // languages available
39         'l' => array(
40             
41             'en', 'zh_CN',   'zh_HK',  'zh_TW', //'th', 'ko', 'ja', 'ms', 
42             //'id', // indonesian
43            // 'tl', // tagalog
44            // 'vi', //vietnamise
45           //  'hi', // hindi
46           //  'ta', // tamil
47           //  '**', // other
48         ),
49         'c' => '*', // array(
50              //'AU', 'CN', 'HK', 'IN', 'ID', 'JP', 'MY', 'NZ', 'TW', 'SG', 'TH', 'KR', 'US', 'PH', 'VN','**'
51         //),
52         'm' => array(
53             'USD', 'HKD', 'GBP', 'CNY', 'SGD', 'JPY'
54         ),
55         'p' => '*',
56         'add_l'=> array(), // key -> value additional languages... 
57         'add_c'=> array(), // additional countries...(eg. '-R' => 'Regional' )
58         'add_m'=> array(), // additional currencies...
59         'add_p'=> array(), // additional currencies...
60
61         
62     );
63     /**
64      * initalizie the cfg aray
65      *
66      */
67     function cfg()
68     {
69         static $loaded  = false;
70         if ($loaded) {
71             return self::$cfg;
72         }
73          
74         $loaded =true;
75         $ff= HTML_FlexyFramework::get();
76         
77         // BC compatible.. if any of these are set, then we use them as the settings..
78         $opts = array();
79         foreach(array('Pman_Core_I18n', 'Pman_Core_I18N', 'Pman_I18N','Pman_I18n') as $pk) {
80             if (isset($ff->$pk)) {
81                 //var_dump($pk);
82                 $opts =  $ff->$pk;
83                 break;
84             }
85         }
86         //echo '<PRE>';print_R($opts);//exit;
87         
88          
89         // var_dump($opts);exit;
90         
91         $i = DB_DataObject::Factory('I18n');
92         // load the cofiguration
93         foreach($opts as $k=>$v) {
94             
95             if ($v == '*') { // everything..
96                // self::$cfg[$k] = $i->availableCodes($k, false);
97                 continue;
98             }
99              
100             self::$cfg[$k] = is_array($v) ? $v  : explode(',', $v);
101         }
102         // available codes recursively calls this... -- so the above has to be set first..
103         foreach($opts as $k=>$v) {
104             
105             if ($v == '*') { // everything..
106                 self::$cfg[$k] = '*'; //$i->availableCodes($k, false);
107                 continue;
108             }
109            
110         }
111         
112         
113         return self::$cfg;
114         
115         
116     }
117     
118     
119       // the default configuration.
120     
121     function applyFilters($q, $au)
122     {
123         $this->buildDB();
124         //DB_DataObject::debugLevel(1);
125         if (!empty($q['query']['_with_en'])) {
126             
127             $this->buildDB(); // ensure we have the full database...
128             
129             $this->selectAdd("
130                 id as id,
131                 i18n_translate(ltype, lkey, 'en') as lval_en
132             ");
133         }
134         
135         if (!empty($q['_as_code_and_title'])) {
136             $tn = $this->tableName();
137             
138             $this->selectAdd();
139             $this->selectAdd("
140                     {$tn}.lval as title,
141                     {$tn}.lkey as code
142             ");
143             $this->is_active = 1;
144             if (!empty($q['_title'])) {
145                 $this->whereAdd("{$tn}.lval like '{$this->escape($_REQUEST['_title'])}%'");
146             }
147         }
148          
149         if (!empty($q['!code'])) {
150             $this->whereAddIn('!lkey', explode(',', $q['!code']), 'string'); 
151         }
152         if (!empty($q['query']['name'])) {
153             //DB_DAtaObject::debugLevel(1);
154             $v = strtoupper($this->escape($q['query']['name']));
155             $this->whereAdd("upper(lval) LIKE '%{$v}%'");
156         }
157         
158          if (!empty($q['query']['name_starts'])) {
159             $this->whereAdd("lval LIKE '". $this->escape($q['query']['name_starts']). "%'");
160         }
161         
162         if (!empty($q['_filtered']) && !empty($this->ltype)) {
163             $cfg = $this->cfg();
164             $filter = $cfg[$this->ltype];
165             if(is_array($filter)){
166                 $this->whereAddIn('lkey', $filter, 'string'); 
167             }
168             
169         }
170         
171         if(!empty($q['_with_geoip_count'])) {
172             
173             $this->selectAdd("
174                 (
175                     SELECT
176                             COUNT(geoip_division.id)
177                     FROM
178                             geoip_division
179                     WHERE
180                             geoip_division.country = i18n.lkey
181                 ) AS no_of_division,
182                 (
183                     SELECT
184                             COUNT(geoip_city.id)
185                     FROM
186                             geoip_city
187                     WHERE
188                             geoip_city.country = i18n.lkey
189                 ) AS no_of_city
190             ");
191         }
192         
193         if(!empty($q['_hide_unused'])) {
194             $this->whereAdd("
195                 (
196                     SELECT
197                             COUNT(geoip_division.id)
198                     FROM
199                             geoip_division
200                     WHERE
201                             geoip_division.country = i18n.lkey
202                 ) > 0
203             ");
204         }
205     }
206     
207     function lookupCode($inlang,$ltype,$name)
208     {
209         $x = DB_DataObject::factory('i18n');
210         $x->ltype = $ltype;
211         $x->lval = $name;
212         $x->inlang= $inlang;
213         
214         $x->limit(1);
215         if ($x->find(true) && !empty($x->lkey)) {
216             return $x->lkey;
217         }
218         return '';
219         
220         
221     }
222     
223     // load all all to reduce future queries..
224     function translateCache($inlang, $ltype, $build)
225     {
226         static $cache;
227         $key = "{$inlang} {$ltype}";
228         if (isset($cache[$key])) {
229             return $cache[$key];
230         }
231         if (!$build) {
232             return false;
233         }
234         
235         $x = DB_DataObject::factory('i18n');
236         $x->ltype = $ltype;
237         
238         $x->inlang= $inlang;
239         $cache[$key] = $x->fetchAll('lkey', 'lval');
240         
241         return $cache[$key] ;
242
243     }
244     
245     
246     function translate($inlang,$ltype,$kval)
247     {
248         
249         $tc = $this->translateCache($inlang, $ltype, false);
250         if ($tc !== false && isset($tc[$kval])) {
251             return $tc[$kval];
252         }
253         
254         static $cache = array();
255         $cache_key = implode(' ', array($inlang,$ltype,$kval));
256         if (isset($cache[$cache_key ])) {
257             return $cache[$cache_key];
258         }
259         
260         $x = DB_DataObject::factory('i18n');
261         $x->ltype = $ltype;
262         $x->lkey = $kval;
263         $x->inlang= $inlang;
264         $fallback = clone($x);
265         
266         $x->limit(1);
267         if ($x->find(true) && !empty($x->lval)) {
268             $cache[$cache_key] = $x->lval;
269             return $x->lval;
270         }
271         $fallback->inlang = 'en';
272         if ($fallback->find(true) && !empty($fallback->lval)) {
273             $cache[$cache_key] = $fallback->lval;
274             return $fallback->lval;
275         }
276          $cache[$cache_key] = $kval;
277         return $kval;
278     }
279     
280     
281     
282     function toTransList($ltype, $inlang)
283     {
284         
285         $this->is_active = 1;
286         $this->ltype = $ltype;
287         $this->inlang= $inlang;
288         $this->selectAdd();
289         $this->selectAdd('lkey as code, lval as title');
290         
291         $this->find();
292         $ret = array();
293         while ($this->fetch()) {
294             $ret[] = array(
295                 'code'  => $this->code,
296                 'title' => $this->title
297             );
298         }
299         return $ret;
300     }
301      
302     
303     
304     
305     // -------------- code to handle importing into database..
306     
307     
308     
309     
310     // returns a list of all countries/languages etc.. (with '*')
311     function availableCodes($t, $filtered = true)
312     {
313         $ret = array();
314         $cfg = $this->cfg();
315         //echo '<PRE>';print_r($cfg);
316         switch ($t) {
317             case 'c':
318                 require_once 'I18Nv2/Country.php';
319                 
320                 $c = new I18Nv2_Country('en');
321                 $ret =  array_keys($c->codes);
322                 if (!empty($cfg['add_c'])) {
323                     $ret = array_merge($ret, array_keys($cfg['add_c']));
324                 }
325                 
326                 
327                  
328                 
329                 $ret[] = '**';
330                 //echo '<PRE>';print_R($cfg); print_r($ret); exit;
331                 break;
332             
333             case 'l':
334                 require_once 'I18Nv2/Language.php';
335                 $c = new I18Nv2_Language('en');
336                 $ret =  array_keys($c->codes); // we need to make sure these are lowercase!!!
337                 
338                 
339                 foreach ($cfg['add_l'] as $k=>$v){
340                     // make sure that add_l is formated correctly.. (lower_UPPER?)
341                     $tolang = explode('_', $k);
342                     $tolang[0] = strtolower($tolang[0]);
343                     $tolang = implode('_', $tolang);
344                     
345                     unset($cfg['add_l'][$k]); // if they match..unset first.. then set
346                     
347                     $cfg['add_l'][$tolang] = $v;
348                 }
349                 if (!empty($cfg['add_l'])) {
350                     $ret = array_merge($ret, array_keys($cfg['add_l']));
351                 }
352
353                 $ret[] = '**';
354                 break;
355             case 'm':
356                 require_once 'I18Nv2/Currency.php';
357                 $c = new I18Nv2_Currency('en');
358                 $ret =  array_keys($c->codes);
359                 if (!empty($cfg['add_m'])) {
360                     $ret = array_merge($ret, array_keys($cfg['add_m']));
361                 }
362                 $ret[] = '**';
363                 break;
364             case 'p':
365                 require_once 'I18Nv2/PhonePrefix.php';
366                 $c = new I18Nv2_PhonePrefix('en');
367                 $ret =  array_keys($c->codes);
368                 if (!empty($cfg['add_p'])) {
369                     $ret = array_merge($ret, array_keys($cfg['add_p']));
370                 }
371                 $ret[] = '**';
372                 break;
373         }
374         
375         
376         
377         if ($filtered  && !empty($cfg[$t]) && is_array($cfg[$t])) {
378             // then there is a filter. - we should include all of them, even if they are not relivatn??
379             return $cfg[$t]; //array_intersect($cfg[$t], $ret);
380             
381         }
382         
383         // why upper case everyting?!?!?
384         
385         //foreach ($ret as $k=>$v) {
386         //    $ret[$k] = ($t=='l') ? $ret[$k] : strtoupper($v);
387         //}
388
389         return $ret;
390     }
391     
392     
393     function buildDB($ltype= false, $inlang= false )
394     {
395         $cfg = $this->cfg();
396         
397         if ($ltype === false) {
398             // trigger all builds.
399             //DB_DataObject::debugLevel(1);
400             $this->buildDB('c');
401             $this->buildDB('l');
402             $this->buildDB('m');
403             $this->buildDB('p', 'en');
404             return;
405         }
406         
407         if ($inlang == '**') {
408             return; // dont bother building generic..
409         }
410         
411         
412         if ($inlang === false) {
413             // do we want to add our 'configured ones..'
414             // We only build translatiosn for our configured ones..
415             //foreach( $this->availableCodes('l') as $l) {
416                 
417             foreach( $cfg['t'] as $l) {
418                 $this->buildDB($ltype, $l);
419             }
420             return;
421         }
422         
423         
424         //DB_DataObject::debugLevel(1);
425         $x = DB_DataObject::factory('I18n');
426         $x->inlang= $inlang;
427         $x->ltype = $ltype;
428         
429         $complete = $x->fetchAll('lkey');
430         
431         $list =  $this->availableCodes($ltype);
432         
433         foreach($list as $lkey) {
434             // skip ones we know we have done...
435             if (in_array($lkey, $complete)) {
436                 continue;
437             }
438             if (empty($lkey)) { // not sure why we get empty values here.
439                 continue;
440             }
441             $x = DB_DataObject::factory('I18n');
442             $x->ltype = $ltype;
443             $x->lkey = $lkey;  
444             $x->inlang= $inlang;
445             if ($x->find(true)) {
446                 $xx= clone($x);
447                 $x->lval = $this->defaultTranslate($inlang, $ltype, $lkey);
448                 $x->update($xx);
449                 continue;
450             }
451             $x->lval = $this->defaultTranslate($inlang, $ltype, $lkey);
452             $x->insert();
453             
454         }
455          
456         
457     }
458     
459     /**
460      * default translate  - use i18n classes to provide a value.
461      *
462      * 
463      */
464      
465     function defaultTranslate($lang, $type, $k) 
466     {
467       
468         static $cache;
469         
470         
471         $cfg = $this->cfg();
472         if (empty($k)) {
473             return '??';
474         }
475         
476         //$lbits = explode('_', strtoupper($lang));
477         $lbits = explode('_', $lang);
478         $orig_lang = $lang;
479         $lang = $lbits[0];
480         
481         if (!isset($cache[$lang])) {
482             require_once 'I18Nv2/Country.php';
483             require_once 'I18Nv2/Language.php';
484             require_once 'I18Nv2/Currency.php';
485             require_once 'I18Nv2/PhonePrefix.php';
486             $cache[$lang] = array(
487                 'l' =>  new I18Nv2_Language($lang, 'UTF-8'),
488                 'c' => new I18Nv2_Country($lang, 'UTF-8'),
489                 'm' => new I18Nv2_Currency($lang, 'UTF-8'),
490                 'p' => new I18Nv2_PhonePrefix($lang, 'UTF-8')
491             );
492             //echo '<PRE>';print_r(array($lang, $cache[$lang]['c']));
493         }
494         
495         if ($k == '**') {
496             return 'Other / Unknown';
497         }
498         
499         
500         // for languages if we get zh_HK then we write out Chinese ( HK )
501         
502         
503         if ($type == 'l' && strpos($k, '_') > -1) {
504             $tolang = explode('_', $k);
505             $ret = $cache[$lang][$type]->getName(strtolower($tolang[0])) .  '('.$tolang[1].')'; 
506             
507         } else {
508             $ret = $cache[$lang][$type]->getName($k);
509         }
510         
511         if ($orig_lang == 'zh_HK' || $orig_lang == 'zh_TW' ) {
512             // then translation is by default in simplified.
513             //print_r($ret);
514             $ret = @iconv("UTF-8", "GB2312//IGNORE", $ret);
515             //print_r($ret);
516             $ret = @iconv("GB2312", "BIG5//IGNORE", $ret);
517             //print_r($ret);
518             
519             $ret = @iconv("BIG5", "UTF-8//IGNORE", $ret);
520             //print_r($ret);
521          }
522         
523         
524         
525         // our wierd countries/langs etc..
526         if (isset($cfg['add_' . $type][$k])) {
527             return $cfg['add_' . $type][$k];
528             
529         }
530         
531         return $ret;
532         
533         
534     }
535     
536     
537 }