fix #8131 - chinese translations
[Pman.Core] / DataObjects / Core_templatestr.php
1 <?php
2 /**
3  * Table Definition for core_templatestr
4  *
5  *
6  * The idea here is that it contains all the strings in the templates with a language '' (empty)
7  * , it then generates a matching set of strings
8  * 
9  */
10 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
11
12 class Pman_Core_DataObjects_Core_templatestr extends DB_DataObject 
13 {
14     ###START_AUTOCODE
15     /* the code below is auto generated do not remove the above tag */
16
17     public $__table = 'core_templatestr';         // table name
18     public $id;                              // int(11)  not_null primary_key auto_increment
19     public $template_id;                           // string(64)  not_null
20     public $txt;                    // datetime(19)  multiple_key binary
21     public $updated;                        // blob(65535)  blob
22     public $src_id;                          // int(11)  not_null
23     public $lang;    // text  NOT NULL;
24     public $mdsum;    // text  NOT NULL;
25     public $active;
26     public $on_table;
27     public $on_id;
28     public $on_col;
29  
30     /* the code above is auto generated do not remove the tag below */
31     ###END_AUTOCODE
32     
33     function beforeInsert($q,$roo)
34     {
35         if(!empty($q['_rescan'])){
36             $this->syncLang($q['_rescan']);
37             $roo->jok('OK');
38         }
39     }
40     
41     
42     function applyFilters($q, $au, $roo)
43     {
44         if (!empty($q['_tree'])) {
45             $this->applyFiltersTree($q,$roo);
46         }
47         
48         if(!empty($q['on_table']) && (empty($q['template_id']) || !is_numeric($q['template_id']))){
49             $this->template_id = 0;
50              $this->whereAdd("  join_src_id_id.txt != ''");
51         }
52         if (!empty($q['_search_txt'])) {
53             $str = $this->escape($q['_search_txt']);
54             $this->whereAdd("core_templatestr.txt like '%{$str}%' OR join_src_id_id.txt like '%{$str}%'");
55             
56         }
57     }
58     function translateTableCol($obj, $col, $lang)
59     {
60         $cts = DB_DataObject::factory('core_templatestr');
61         $cts->lang = $lang;
62         $cts->on_table = $obj->tableName();
63         $cts->on_id = $obj->pid();
64         $cc = clone($cts);
65         if(!$cts->find(true)){
66             return $obj->$col;
67         }
68         
69         
70         if(empty($cts->txt)){
71             return $obj->$col;
72         }
73             
74         return $cts->txt;
75     }
76     /**
77      *
78      * insert the origanal table text
79      * 
80      * @param type $roo
81      * @param type $obj
82      * @param type $chg
83      * @return type 
84      */
85     function onTableChange($roo, $obj, $chg)
86     {
87         
88         $ff = HTML_FlexyFramework::get()->Pman_Core;
89             
90         if(empty($ff['DataObjects_Core_templatestr']['tables'])){
91             return;
92         }
93         $tn = $obj->tableName();
94         if(empty($ff['DataObjects_Core_templatestr']['tables'][$tn])){
95             return;
96         }
97         $cols = $ff['DataObjects_Core_templatestr']['tables'][$tn];
98         
99         
100         foreach($cols as $c) {
101             $x = $this->factory($this->tableName());
102             $x->on_id = $obj->pid();
103             $x->on_table = $tn;
104             $x->on_col = $c;
105             $x->lang = ''; /// eg. base language..
106             $up = $x->find(true);
107             if ($up && $x->txt == $obj->$c) {
108                 continue; // update an no change..
109             }
110             $x->active = 1;
111             $x->src_id = 0;
112             $x->txt = $obj->$c;
113             $x->mdsum = md5($obj->$c);
114             $x->template_id = 0;
115             $x->updated = date('Y-m-d H:i:s', strtotime("NOW"));
116             $up ? $x->update() : $x->insert();
117         }
118         
119         
120     }
121     
122     
123     function applyFiltersTree($q,$roo)
124     {
125         if (empty($q['node'])) {
126             $roo->jerr("invalid node");
127         }
128         switch(true) {
129             
130             case ($q['node'] == 'transtree'):
131             case ($q['node'] == 'langlist'):
132                // DB_DataObject::debugLevel(1);
133                 $x = DB_Dataobject::Factory($this->tableName());
134                 $x->selectAdd();
135                 $x->selectAdd('distinct(lang) as lang');
136                 
137                 $x->selectAdd("i18n_translate('l', lang, 'en') as lang_name");
138                 $x->whereAdd("lang != ''");
139                 $ret= array();
140                 foreach( $x->fetchAll() as $l) {
141                     $ret[] = array(
142                         'text'=>$l->lang_name,
143                         'id' => $q['node'] == 'langlist' ? $l->lang : 'lang:'.$l->lang ,
144                         'language' => true
145                     );
146                 }
147                 if (empty($ret)) {
148                     $ret[] = array(
149                         'text'=>'English',
150                         'id' => 'lang:en',
151                         'language' => true
152                     );
153                 }
154                 $roo->jdata($ret);
155             
156             case  preg_match('/^lang:/', $q['node']):
157                 
158                 $lang = preg_replace('/^lang:/', '', $q['node']);
159                 $ret= array();  
160                 $x = DB_DataObject::factory('core_templatestr');
161                 $x->autoJoin();
162                 $x->selectAdd();
163                 $x->selectAdd('distinct(view_name) as view_name');
164                 $x->lang = $lang;
165                 $x->whereAdd('join_template_id_id.is_deleted = 0');
166                 $x->orderBy('view_name DESC');
167                 $x->find();
168                 while($x->fetch()) {
169                     $ret[] = array( 
170                         'text'=> $x->view_name,
171                         'id' => 'view:'. $lang .':'.  $x->view_name,
172                         'leaf' => false
173                     );
174                 }
175
176                 $ff = HTML_FlexyFramework::get()->Pman_Core;
177
178                 if(!empty($ff['DataObjects_Core_templatestr']['tables'])){
179                     foreach($ff['DataObjects_Core_templatestr']['tables'] as $table=>$v){
180                         $ret[] = array(
181                             'text'=> $table,
182                             'on_table' => $table,
183                             'id' => 'table:'. $lang .':'. $table,
184                             'leaf' => true
185                         );
186                     }
187                 }
188                 
189                  
190                 $roo->jdata($ret);
191                 
192                 break;
193                 
194                 
195             case  preg_match('/^view:/', $q['node']):
196                 
197                
198                 $bits= explode(":",preg_replace('/^view:/', '', $q['node']));
199                 
200                 $x = DB_DataObject::factory($this->tableName());
201                 $x->autoJoin();
202                 $x->selectAdd();
203                 $x->selectAdd('distinct(core_templatestr.template_id) as template_id');
204                 $x->whereAdd("join_template_id_id.view_name = '{$x->escape($bits[1])}'");
205                 $x->whereAdd('join_template_id_id.is_deleted = 0');
206                 $x->lang = $bits[0];
207                 $ids = $x->fetchAll('template_id');
208                 
209                 $ret= array();
210                 //add the table type lists
211                 /*
212                 $ff = HTML_FlexyFramework::get()->Pman_Core;
213                 
214                 
215 //                $x->orderBy('template ASC');
216 //                $x->whereAdd("lang != ''");
217                 */
218                 //below are old code
219                 $xx = DB_Dataobject::Factory('core_template');
220                 $xx->whereAddIn('id', $ids, 'int');
221                 $xx->selectAdd();
222                 $xx->selectAdd("
223                                
224                     id, concat(  template) as template_name
225                 ");
226                 $xx->orderBy('template_name ASC');
227                 
228                 foreach( $xx->fetchAll('id', 'template_name') as $l =>$n) {
229                     $ret[] = array(
230                         'text'=> $n,
231                         'id' => $l,
232                         'leaf' => true
233                     );
234                 }
235                 
236                 $roo->jdata($ret);
237                  break;
238         }
239                 
240         
241         
242     }
243     
244     
245     /**
246      *
247      * 
248      * @param object $tmpl core_template data object
249      * @param array $words array of words 
250      */ 
251     function syncTemplateWords($tmpl, $keyvalue = false)
252     {
253         
254         $words = $tmpl->words;
255         // mapping for template : 
256         //tablename => $n (templatename) 
257         //tableid => $k (key value)
258         //colname => $n (templatename) 
259         // mdsum => md5(sum)
260         //
261         //print_r($words);exit;
262         // grab original
263         $tt = DB_DataObject::factory($this->tableName());
264  
265         $t = clone($tt);
266         $t->template_id = $tmpl->id;
267         $t->whereAdd("lang = ''");
268         
269         
270         // we have a situation where old md sums where created..
271         
272         
273         
274         $cur = $t->fetchAll('mdsum', 'id'); 
275         
276         
277         
278         
279         
280         
281         
282         // now loop through current..
283         $cwords = array();// not in used??
284         $active = array();
285 //        echo "sync Template Words... \n";
286 //        print_r($words);
287         
288         foreach($words as $k=>$v) {
289             
290             
291             $v = trim($v);
292             
293             $md = $keyvalue ? $k : md5($v);
294             
295             // check to see if there are more that one versions of that md5
296             
297             
298             if (!isset($cur[$md])) {
299                 // create a record for it..
300                 $t = DB_DataObject::factory($this->tableName());
301                 $t->setFrom(array(
302                     'txt' => $v,
303                     'lang' => '',// by default should a english 
304                     'updated' => date('Y-m-d H:i:s', strtotime("YESTERDAY")),
305                     'template_id'=>$tmpl->id,
306                     'mdsum' => $md,
307                     'src_id' => 0,
308                     'active' => 1,
309                 ));
310                 $active[] =  $t->insert();
311                 continue;
312             }  
313             $cur[$md] = $this->checkDupes($tmpl->id, '',  $cur[$md] , $md);
314             
315             $active[] = $cur[$md];
316             
317             // we have it already? - 
318             $tt->query("UPDATE {$this->tableName()}
319                         SET active= 1
320                         WHERE
321                         id = ".$cur[$md]);
322             unset($cur[$md]);
323             
324         }
325         // delete unused.
326         
327         
328         
329
330         $deactive = array();
331         if (count(array_values($cur))) {// de-active unused
332
333             $t = DB_DataObject::factory($this->tableName());
334 //            echo "de-active current?? \n";
335 //            print_r($cur);
336 //            echo "\n";
337             $deactive = array_values($cur);
338             $t->query("UPDATE core_templatestr
339                       SET active = 0 WHERE id in (" . implode(',' ,$deactive) . ")
340                      ");
341         }
342         
343         // delete all the items that are not relivant.
344         // clear orphaned chidren - it just blanks out the src id, so they can be used as suggestions..?
345         // this does not help - as it just puts random strings in there.. - with no reference to the original text..
346         $t = DB_DataObject::factory($this->tableName());
347     
348         // this will active the child data
349         if (empty($active)) {// set the active array to empty
350             $active = array(-1);
351         }
352         $t->query("UPDATE  core_templatestr 
353                 SET active = 1
354                   WHERE
355                      src_id IN (". implode(',' ,$active) . ")
356                     AND
357                     template_id = {$tmpl->id}
358         ");
359         //deactive the child data
360         if (empty($deactive)) {
361             $deactive = array(-1);
362         }
363         $t->query("UPDATE  core_templatestr 
364                 SET active = 0
365                   WHERE
366                     src_id IN (". implode(',' ,$deactive) . ")
367                     AND
368                     template_id = {$tmpl->id}
369                     AND
370                     lang != ''
371         ");
372     }
373     
374     function checkDupes($tid, $lang, $id, $mdsum) {
375         
376         $t = DB_DataObject::factory($this->tableName());
377         $t->template_id = $tid;
378         $t->mdsum = $mdsum;
379         $t->whereAdd("lang = '{$lang}'");
380         if ($t->count() == 1) {
381             return $id; // only got one ... no issues..
382         }
383         
384         //echo "GOT DUPES : $id, $lang, $id , $mdsum\n";
385         
386         //DB_DataObject::debugLevel(1);
387         // find out if any of them have got translations.
388         $ids = $t->fetchAll('id');
389         
390         
391         $t = DB_DataObject::factory($this->tableName());
392         $t->whereAddIn('src_id', $ids, 'int');
393         $t->whereAdd("txt != ''");
394         $t->orderBy('updated DESC');
395         if ($t->count()) {
396             $t->limit(1);
397             // do any translations exist?
398             $t->find(true);
399             $id = $t->src_id;
400         }
401         
402         
403         // delete all the others...
404         $t = DB_DataObject::factory($this->tableName());
405         $t->whereAddIn('src_id', $ids, 'int');
406         $t->whereAdd("src_id != $id");
407         $t->find();
408         while($t->fetch()) {
409             $tt = clone($t);
410             $tt->mdsum = $t->mdsum . '-bad-'. $t->id;
411             $tt->update($t);
412         }
413         $t = DB_DataObject::factory($this->tableName());
414         $t->whereAddIn('id', $ids, 'int');
415         $t->whereAdd("id != $id");
416         $t->find();
417         while($t->fetch()) {
418             $tt = clone($t);
419             $tt->mdsum = $t->mdsum . '-bad-'. $t->id;
420             $tt->update($t);
421         }
422         // this is done by calling code 
423         //$t = DB_DataObject::factory($this->tableName());
424         //$t->query("update core_templatestr set active= 1 where src_id = $id");
425         
426         
427         
428        //exit;
429         return $id;
430     
431                
432          
433     }
434     
435     function syncLang($lang)
436     {
437         // bugs with our old code...
438 //        die('in?');
439         $tn = $this->tableName();
440         $t = DB_DataObject::factory($tn);
441         $t->query("DELETE FROM {$tn} WHERE lang !='' AND src_id = 0 AND on_table  = ''");
442         
443         // find all the id's from lang that have not been generated..
444         
445         
446         static $id_tmp = false;
447         
448         if ($id_tmp == false) {
449             //find the origanal 
450             $t = DB_DataObject::factory($tn);
451             $t->whereAdd("lang = ''");
452             $t->active = 1;
453             
454             //old code, this did not support the on_table
455     //        $id_tmp = $t->fetchAll('id','template_id');
456     //        $ids = array_keys($id_tmp);
457             $id_tmp = array();
458             //new code for support the sync tables 
459             foreach($t->fetchAll() as $ori){
460                 $id_tmp[$ori->id] = $ori;
461             }
462         }
463         $ids = array_keys($id_tmp);
464         
465         // matching by language:
466         $t = DB_DataObject::factory($tn);
467         $t->whereAddIn('src_id', $ids , 'int');
468         $t->lang = $lang;
469         //$t->active = 1;
470         $got = $t->fetchAll('src_id');
471         $missing = array_diff($ids, $got);
472         
473         if (empty($missing)) {
474             return;
475         }
476         $t = DB_DataObject::factory($tn);
477         $q = "CREATE TEMPORARY TABLE core_templatestr_insert SELECT
478             id as src_id,
479             '' as txt,
480             '$lang' as lang,
481             NOW() as updated,
482             template_id,
483             on_table,
484             on_id,
485             on_col,
486             1 as active
487             FROM core_templatestr
488             WHERE
489             id IN (". implode(',', $missing) . ")
490         ";
491         //echo $q; exit;
492         DB_DataObject::factory($tn)->query($q);
493         $q = "INSERT INTO $tn (src_id, txt, lang, updated, template_id, on_table,on_id, on_col, active) SELECT * FROM core_templatestr_insert";
494         DB_DataObject::factory($tn)->query($q);
495         $q = "DROP TEMPORARY TABLE core_templatestr_insert";
496         DB_DataObject::factory($tn)->query($q);
497             
498       
499         
500     }
501     
502     // called from flexy to translate a string.
503     
504     
505     function translateFlexyString($flexy, $string)
506     {
507          $debug = false;;
508         //if (!empty($_REQUEST['_debug'])) { $debug= true; }
509         
510         // using $flexy->currentTemplate -> find the template we are looking at..
511         // then find the string for $flexy->options['locale']
512         //DB_DataObject::debugLevel(1);
513         if ($debug) { var_dump($string); }
514         
515         static $cache = array(); // cache of templates..
516         
517         $ff = HTML_FlexyFramework::get();
518         $view_name = isset($ff->Pman_Core['view_name']) ? $ff->Pman_Core['view_name'] : false;
519         if (empty($view_name)) {
520             $pg = HTML_FlexyFramework::get()->page;
521             if (isset($pg->templateViewName)) {
522                 $view_name = $pg->templateViewName;
523             }
524             
525         }
526         
527         
528         
529         if ($debug) { var_dump(array('view_name'=> $view_name)); }
530         
531         $tempdir = '';
532         foreach($flexy->options['templateDir'] as $td) {
533             if (substr($flexy->currentTemplate, 0, strlen($td)) == $td) {
534                 $tempdir = $td;
535                 break;
536             }
537         }
538         
539         
540         $tmpname = substr($flexy->currentTemplate, strlen($td) +1);
541         
542          
543         if (isset($cache[$tmpname]) && $cache[$tmpname] === false) {
544             if ($debug) { echo "from cache no match - $string\n"; }
545             return $string;
546         }
547         
548         if (!isset($cache[$tmpname])) {
549                 
550             
551             
552             $tmpl = DB_DataObject::factory('core_template');
553             if ($view_name !== false) {
554                 $tmpl->view_name = $view_name;
555             }
556             if(!$tmpl->get('template', $tmpname)){
557                 // strip of site prefix if set...
558                  
559                 $tmpl = DB_DataObject::factory('core_template');
560                 if(!$tmpl->get('template', $tmpname)){
561                     //var_dump("no template? {$tmpname} or {$relpath}" );
562                     $cache[$tmpname] = false;
563                     if ($debug) { echo "no template found - no match - $string\n"; }
564                     return $string;
565                 }
566             }
567             $cache[$tmpname] = $tmpl;
568         } else {
569             $tmpl = $cache[$tmpname] ;
570         }
571         
572         
573     
574         //get original template id
575         /*
576         $orig = DB_DataObject::factory($this->tableName());
577         $orig->lang = '';
578         $orig->template_id = $tmpl->id;
579         $orig->active = 1;
580         
581         $cache[$tmpname]->words = 
582         
583         if(!$orig->get( 'mdsum' , md5(trim($string)))){
584              //var_dump('no text? '. $string);
585             if ($debug) { echo "no original string found tplid: {$tmpl->id}\n"; }
586             return false;
587         }
588         */
589         
590         if (empty($cache[$tmpname]->translations)) {
591         
592             //find out the text by language
593             //DB_DataObject::DebugLevel(1);
594             $x = DB_DataObject::factory($this->tableName());
595             $x->lang = $flexy->options['locale'];
596             $x->template_id = $tmpl->id;
597             $x->autoJoin();
598             $cache[$tmpname]->translations = $x->fetchAll('src_id_mdsum', 'txt');
599             if (empty($cache[$tmpname]->translations)) {
600                 $cache[$tmpname]->translations = true;
601             }
602             //var_Dump($cache[$tmpname]->translations);
603         }
604         
605         
606         if ($cache[$tmpname]->translations === true) {
607             return $string;
608         }
609         //var_dump("Checking: " . md5(trim($string)));
610         
611         if (!empty($cache[$tmpname]->translations [md5(trim($string))])){
612            // var_dump("RETURNING: ". $cache[$tmpname]->translations [md5(trim($string))]);
613             return $cache[$tmpname]->translations [md5(trim($string))];
614         }
615         return $string;
616         
617     }
618     
619     
620     function translateChanged($flexy)
621     {
622         
623         $date = $this->lastUpdated($flexy);
624         if ($date === false) {
625             return false;
626         }
627         $utime = file_exists($flexy->compiledTemplate) ?  filemtime( $flexy->compiledTemplate) : 0;
628         return strtotime($date) >  $utime;
629     }
630     
631     // determine if a complied template need recompling
632     
633     function lastUpdated($flexy)
634     {
635         //return true;
636         // var_dump('check changed?');
637         //DB_DataObject::debugLevel(1);
638         //var_Dump(array($flexy->options['templateDir'][0], $flexy->currentTemplate));
639         
640         //var_dump($flexy->compiledTemplate);
641         $utime = file_exists($flexy->compiledTemplate) ?  filemtime( $flexy->compiledTemplate) : 0;
642         
643        
644         static $cache = array(); // cache of templates..
645         
646         $ff = HTML_FlexyFramework::get();
647         $view_name = isset($ff->Pman_Core['view_name']) ? $ff->Pman_Core['view_name'] : false;
648         
649         // find which of the template directories was actually used for the template.
650         
651         $tempdir = '';
652         foreach($flexy->options['templateDir'] as $td) {
653             if (substr($flexy->currentTemplate, 0, strlen($td)) == $td) {
654                 $tempdir = $td;
655                 break;
656             }
657         }
658         
659         
660         $tmpname = substr($flexy->currentTemplate, strlen($td) +1);
661         
662         // we do not have any record of this template..
663         if (isset($cache[$tmpname]) && $cache[$tmpname] === false) {
664             return false;
665         }
666         
667         if (!isset($cache[$tmpname])) {
668                 
669             
670             
671             $tmpl = DB_DataObject::factory('core_template');
672             if ($view_name !== false) {
673                 $tmpl->view_name = $view_name;
674             }
675             if(!$tmpl->get('template', $tmpname)){
676                 // strip of site prefix if set...
677                  
678                 $tmpl = DB_DataObject::factory('core_template');
679                 if(!$tmpl->get('template', $tmpname)){
680                     //var_dump("no template? {$tmpname} or {$relpath}" );
681                     $cache[$tmpname] = false;
682                     return false;
683                 }
684             }
685             $cache[$tmpname] = $tmpl;
686         } else {
687             $tmpl = $cache[$tmpname] ;
688         }
689           
690          
691         
692         $x = DB_DataObject::factory($this->tableName());
693         $x->lang = $flexy->options['locale'];
694         $x->active = 1;
695         $x->template_id = $tmpl->id;
696         //$x->whereAdd("updated > '". date('Y-m-d H:i:s', $utime)."'");
697         if ($x->count() < 1) {
698             return false; // we don't have any record of it.
699         }
700         $x->selectAdd();
701         $x->selectAdd('max(updated) as max_updated');
702         $x->find(true);
703         return $x->max_updated;
704         
705         
706     }
707     
708 }