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         $ff = HTML_FlexyFramework::get()->Pman_Core;
88             
89         if(empty($ff['DataObjects_Core_templatestr']['tables'])){
90             return;
91         }
92         $tn = $obj->tableName();
93         if(empty($ff['DataObjects_Core_templatestr']['tables'][$tn])){
94             return;
95         }
96         $cols = $ff['DataObjects_Core_templatestr']['tables'][$tn];
97
98         $used = array();
99         foreach($cols as $c) {
100             
101             if(strpos($c, ',') !== false) {
102                 $arr = explode(',', $c);
103                 $c = $arr[0];
104                 $cond = $arr[1];
105
106                 $ar = explode('=', $cond);
107                 $key = $ar[0];
108
109                 // skip if condition not fulfilled
110                 if($obj->{$ar[0]} != $ar[1]) {
111                     continue;
112                 }
113             }
114
115             // skip if empty string
116             if(empty($obj->$c)) {
117                 continue;
118             }
119
120             $x = $this->factory($this->tableName());
121             $x->on_id = $obj->pid();
122             $x->on_table = $tn;
123             $x->on_col = $c;
124             $x->lang = ''; /// eg. base language..
125             $up = $x->find(true);
126
127             // skip when no change
128             if($up && $x->txt == $obj->$c) {
129                 $used[] = $x->id;
130                 continue;
131             }
132
133             $x->active = 1;
134             $x->src_id = 0;
135             $x->txt = $obj->$c;
136             $x->mdsum = md5($obj->$c);
137             $x->template_id = 0;
138             $x->updated = date('Y-m-d H:i:s', strtotime("NOW"));
139             $up ? $x->update() : $x->insert();
140         }
141
142         // make sure the used one are active
143         if(count($used)) {
144             $t = DB_DataObject::factory($this->tableName());
145             // activate the aprent data
146             $t->query("UPDATE core_templatestr
147                 SET active = 1 WHERE id in (" . implode(',' ,$used) . ")
148             ");
149             // activate the child data
150             $t->query("UPDATE  core_templatestr 
151             SET active = 1
152               WHERE
153                  src_id IN (". implode(',' ,$used) . ")
154                 AND
155                 lang != ''
156             ");
157         }
158         
159         
160     }
161     
162     
163     function applyFiltersTree($q,$roo)
164     {
165         if (empty($q['node'])) {
166             $roo->jerr("invalid node");
167         }
168         switch(true) {
169             
170             case ($q['node'] == 'transtree'):
171             case ($q['node'] == 'langlist'):
172                // DB_DataObject::debugLevel(1);
173                 $x = DB_Dataobject::Factory($this->tableName());
174                 $x->selectAdd();
175                 $x->selectAdd('distinct(lang) as lang');
176                 
177                 $x->selectAdd("i18n_translate('l', lang, 'en') as lang_name");
178                 $x->whereAdd("lang != ''");
179                 $ret= array();
180                 foreach( $x->fetchAll() as $l) {
181                     $ret[] = array(
182                         'text'=>$l->lang_name,
183                         'id' => $q['node'] == 'langlist' ? $l->lang : 'lang:'.$l->lang ,
184                         'language' => true
185                     );
186                 }
187                 if (empty($ret)) {
188                     $ret[] = array(
189                         'text'=>'English',
190                         'id' => 'lang:en',
191                         'language' => true
192                     );
193                 }
194                 $roo->jdata($ret);
195             
196             case  preg_match('/^lang:/', $q['node']):
197                 
198                 $lang = preg_replace('/^lang:/', '', $q['node']);
199                 $ret= array();  
200                 $x = DB_DataObject::factory('core_templatestr');
201                 $x->autoJoin();
202                 $x->selectAdd();
203                 $x->selectAdd('distinct(view_name) as view_name');
204                 $x->lang = $lang;
205                 $x->whereAdd('join_template_id_id.is_deleted = 0');
206                 $x->orderBy('view_name DESC');
207                 $x->find();
208                 while($x->fetch()) {
209                     $ret[] = array( 
210                         'text'=> $x->view_name,
211                         'id' => 'view:'. $lang .':'.  $x->view_name,
212                         'leaf' => false
213                     );
214                 }
215
216                 $ff = HTML_FlexyFramework::get()->Pman_Core;
217
218                 if(!empty($ff['DataObjects_Core_templatestr']['tables'])){
219                     foreach($ff['DataObjects_Core_templatestr']['tables'] as $table=>$v){
220                         $ret[] = array(
221                             'text'=> $table,
222                             'on_table' => $table,
223                             'id' => 'table:'. $lang .':'. $table,
224                             'leaf' => true
225                         );
226                     }
227                 }
228                 
229                  
230                 $roo->jdata($ret);
231                 
232                 break;
233                 
234                 
235             case  preg_match('/^view:/', $q['node']):
236                 
237                
238                 $bits= explode(":",preg_replace('/^view:/', '', $q['node']));
239                 
240                 $x = DB_DataObject::factory($this->tableName());
241                 $x->autoJoin();
242                 $x->selectAdd();
243                 $x->selectAdd('distinct(core_templatestr.template_id) as template_id');
244                 $x->whereAdd("join_template_id_id.view_name = '{$x->escape($bits[1])}'");
245                 $x->whereAdd('join_template_id_id.is_deleted = 0');
246                 $x->lang = $bits[0];
247                 $ids = $x->fetchAll('template_id');
248                 
249                 $ret= array();
250                 //add the table type lists
251                 /*
252                 $ff = HTML_FlexyFramework::get()->Pman_Core;
253                 
254                 
255 //                $x->orderBy('template ASC');
256 //                $x->whereAdd("lang != ''");
257                 */
258                 //below are old code
259                 $xx = DB_Dataobject::Factory('core_template');
260                 $xx->whereAddIn('id', $ids, 'int');
261                 $xx->selectAdd();
262                 $xx->selectAdd("
263                                
264                     id, concat(  template) as template_name
265                 ");
266                 $xx->orderBy('template_name ASC');
267                 
268                 foreach( $xx->fetchAll('id', 'template_name') as $l =>$n) {
269                     $ret[] = array(
270                         'text'=> $n,
271                         'id' => $l,
272                         'leaf' => true
273                     );
274                 }
275                 
276                 $roo->jdata($ret);
277                  break;
278         }
279                 
280         
281         
282     }
283     
284     
285     /**
286      *
287      * 
288      * @param object $tmpl core_template data object
289      * @param array $words array of words 
290      */ 
291     function syncTemplateWords($tmpl, $keyvalue = false)
292     {
293         
294         $words = $tmpl->words;
295         // mapping for template : 
296         //tablename => $n (templatename) 
297         //tableid => $k (key value)
298         //colname => $n (templatename) 
299         // mdsum => md5(sum)
300         //
301         //print_r($words);exit;
302         // grab original
303         $tt = DB_DataObject::factory($this->tableName());
304  
305         $t = clone($tt);
306         $t->template_id = $tmpl->id;
307         $t->whereAdd("lang = ''");
308         
309         
310         // we have a situation where old md sums where created..
311         
312         
313         
314         $cur = $t->fetchAll('mdsum', 'id'); 
315         
316         
317         
318         
319         
320         
321         
322         // now loop through current..
323         $cwords = array();// not in used??
324         $active = array();
325 //        echo "sync Template Words... \n";
326 //        print_r($words);
327         
328         foreach($words as $k=>$v) {
329             
330             
331             $v = trim($v);
332
333             // skip empty words
334             if(empty($v)) {
335                 continue;
336             }
337             
338             $md = $keyvalue ? $k : md5($v);
339             
340             // check to see if there are more that one versions of that md5
341             
342             
343             if (!isset($cur[$md])) {
344                 // create a record for it..
345                 $t = DB_DataObject::factory($this->tableName());
346                 $t->setFrom(array(
347                     'txt' => $v,
348                     'lang' => '',// by default should a english 
349                     'updated' => date('Y-m-d H:i:s', strtotime("YESTERDAY")),
350                     'template_id'=>$tmpl->id,
351                     'mdsum' => $md,
352                     'src_id' => 0,
353                     'active' => 1,
354                 ));
355                 $active[] =  $t->insert();
356                 continue;
357             }  
358             $cur[$md] = $this->checkDupes($tmpl->id, '',  $cur[$md] , $md);
359             
360             $active[] = $cur[$md];
361             
362             // we have it already? - 
363             $t = DB_DataObject::factory($this->tableName());
364             $t->query("UPDATE {$this->tableName()}
365                         SET active= 1
366                         WHERE
367                         id = ".$cur[$md]);
368             unset($cur[$md]);
369             
370         }
371         // delete unused.
372         
373         
374         
375
376         $deactive = array();
377         if (count(array_values($cur))) {// de-active unused
378
379             $t = DB_DataObject::factory($this->tableName());
380 //            echo "de-active current?? \n";
381 //            print_r($cur);
382 //            echo "\n";
383             $deactive = array_values($cur);
384             $t->query("UPDATE core_templatestr
385                       SET active = 0 WHERE id in (" . implode(',' ,$deactive) . ")
386                      ");
387         }
388         
389         // delete all the items that are not relivant.
390         // clear orphaned chidren - it just blanks out the src id, so they can be used as suggestions..?
391         // this does not help - as it just puts random strings in there.. - with no reference to the original text..
392         $t = DB_DataObject::factory($this->tableName());
393     
394         // this will active the child data
395         if (empty($active)) {// set the active array to empty
396             $active = array(-1);
397         }
398         $t->query("UPDATE  core_templatestr 
399                 SET active = 1
400                   WHERE
401                      src_id IN (". implode(',' ,$active) . ")
402                     AND
403                     template_id = {$tmpl->id}
404         ");
405         //deactive the child data
406         if (empty($deactive)) {
407             $deactive = array(-1);
408         }
409         $t->query("UPDATE  core_templatestr 
410                 SET active = 0
411                   WHERE
412                     src_id IN (". implode(',' ,$deactive) . ")
413                     AND
414                     template_id = {$tmpl->id}
415                     AND
416                     lang != ''
417         ");
418     }
419     
420     function checkDupes($tid, $lang, $id, $mdsum) {
421         
422         $t = DB_DataObject::factory($this->tableName());
423         $t->template_id = $tid;
424         $t->mdsum = $mdsum;
425         $t->whereAdd("lang = '{$lang}'");
426         if ($t->count() == 1) {
427             return $id; // only got one ... no issues..
428         }
429         
430         //echo "GOT DUPES : $id, $lang, $id , $mdsum\n";
431         
432         //DB_DataObject::debugLevel(1);
433         // find out if any of them have got translations.
434         $ids = $t->fetchAll('id');
435         
436         
437         $t = DB_DataObject::factory($this->tableName());
438         $t->whereAddIn('src_id', $ids, 'int');
439         $t->whereAdd("txt != ''");
440         $t->orderBy('updated DESC');
441         if ($t->count()) {
442             $t->limit(1);
443             // do any translations exist?
444             $t->find(true);
445             $id = $t->src_id;
446         }
447         
448         
449         // delete all the others...
450         $t = DB_DataObject::factory($this->tableName());
451         $t->whereAddIn('src_id', $ids, 'int');
452         $t->whereAdd("src_id != $id");
453         $t->find();
454         while($t->fetch()) {
455             $tt = clone($t);
456             $tt->mdsum = $t->mdsum . '-bad-'. $t->id;
457             $tt->update($t);
458         }
459         $t = DB_DataObject::factory($this->tableName());
460         $t->whereAddIn('id', $ids, 'int');
461         $t->whereAdd("id != $id");
462         $t->find();
463         while($t->fetch()) {
464             $tt = clone($t);
465             $tt->mdsum = $t->mdsum . '-bad-'. $t->id;
466             $tt->update($t);
467         }
468         // this is done by calling code 
469         //$t = DB_DataObject::factory($this->tableName());
470         //$t->query("update core_templatestr set active= 1 where src_id = $id");
471         
472         
473         
474        //exit;
475         return $id;
476     
477                
478          
479     }
480     
481     function syncLang($lang)
482     {
483         // bugs with our old code...
484 //        die('in?');
485         $tn = $this->tableName();
486         $t = DB_DataObject::factory($tn);
487         $t->query("DELETE FROM {$tn} WHERE lang !='' AND src_id = 0 AND on_table  = ''");
488         
489         // find all the id's from lang that have not been generated..
490         
491         
492         static $id_tmp = false;
493         
494         if ($id_tmp == false) {
495             //find the origanal 
496             $t = DB_DataObject::factory($tn);
497             $t->whereAdd("lang = ''");
498             $t->active = 1;
499             
500             //old code, this did not support the on_table
501     //        $id_tmp = $t->fetchAll('id','template_id');
502     //        $ids = array_keys($id_tmp);
503             $id_tmp = array();
504             //new code for support the sync tables 
505             foreach($t->fetchAll() as $ori){
506                 $id_tmp[$ori->id] = $ori;
507             }
508         }
509         $ids = array_keys($id_tmp);
510         
511         // matching by language:
512         $t = DB_DataObject::factory($tn);
513         $t->whereAddIn('src_id', $ids , 'int');
514         $t->lang = $lang;
515         //$t->active = 1;
516         $got = $t->fetchAll('src_id');
517         $missing = array_diff($ids, $got);
518         
519         if (empty($missing)) {
520             return;
521         }
522         $t = DB_DataObject::factory($tn);
523         $q = "CREATE TEMPORARY TABLE core_templatestr_insert SELECT
524             id as src_id,
525             '' as txt,
526             '$lang' as lang,
527             NOW() as updated,
528             template_id,
529             on_table,
530             on_id,
531             on_col,
532             1 as active
533             FROM core_templatestr
534             WHERE
535             id IN (". implode(',', $missing) . ")
536         ";
537         //echo $q; exit;
538         DB_DataObject::factory($tn)->query($q);
539         $q = "INSERT INTO $tn (src_id, txt, lang, updated, template_id, on_table,on_id, on_col, active) SELECT * FROM core_templatestr_insert";
540         DB_DataObject::factory($tn)->query($q);
541         $q = "DROP TEMPORARY TABLE core_templatestr_insert";
542         DB_DataObject::factory($tn)->query($q);
543             
544       
545         
546     }
547     
548     // called from flexy to translate a string.
549     
550     
551     function translateFlexyString($flexy, $string)
552     {
553          $debug = false;;
554         //if (!empty($_REQUEST['_debug'])) { $debug= true; }
555         
556         // using $flexy->currentTemplate -> find the template we are looking at..
557         // then find the string for $flexy->options['locale']
558         //DB_DataObject::debugLevel(1);
559         if ($debug) { var_dump($string); }
560         
561         static $cache = array(); // cache of templates..
562         
563         $ff = HTML_FlexyFramework::get();
564         $view_name = isset($ff->Pman_Core['view_name']) ? $ff->Pman_Core['view_name'] : false;
565         if (empty($view_name)) {
566             $pg = HTML_FlexyFramework::get()->page;
567             if (isset($pg->templateViewName)) {
568                 $view_name = $pg->templateViewName;
569             }
570             
571         }
572         
573         
574         
575         if ($debug) { var_dump(array('view_name'=> $view_name)); }
576         
577         $tempdir = '';
578         foreach($flexy->options['templateDir'] as $td) {
579             if (substr($flexy->currentTemplate, 0, strlen($td)) == $td) {
580                 $tempdir = $td;
581                 break;
582             }
583         }
584         
585         
586         $tmpname = substr($flexy->currentTemplate, strlen($td) +1);
587         
588          
589         if (isset($cache[$tmpname]) && $cache[$tmpname] === false) {
590             if ($debug) { echo "from cache no match - $string\n"; }
591             return $string;
592         }
593         
594         if (!isset($cache[$tmpname])) {
595                 
596             
597             
598             $tmpl = DB_DataObject::factory('core_template');
599             if ($view_name !== false) {
600                 $tmpl->view_name = $view_name;
601             }
602             if(!$tmpl->get('template', $tmpname)){
603                 // strip of site prefix if set...
604                  
605                 $tmpl = DB_DataObject::factory('core_template');
606                 if(!$tmpl->get('template', $tmpname)){
607                     //var_dump("no template? {$tmpname} or {$relpath}" );
608                     $cache[$tmpname] = false;
609                     if ($debug) { echo "no template found - no match - $string\n"; }
610                     return $string;
611                 }
612             }
613             $cache[$tmpname] = $tmpl;
614         } else {
615             $tmpl = $cache[$tmpname] ;
616         }
617         
618         
619     
620         //get original template id
621         /*
622         $orig = DB_DataObject::factory($this->tableName());
623         $orig->lang = '';
624         $orig->template_id = $tmpl->id;
625         $orig->active = 1;
626         
627         $cache[$tmpname]->words = 
628         
629         if(!$orig->get( 'mdsum' , md5(trim($string)))){
630              //var_dump('no text? '. $string);
631             if ($debug) { echo "no original string found tplid: {$tmpl->id}\n"; }
632             return false;
633         }
634         */
635         
636         if (empty($cache[$tmpname]->translations)) {
637         
638             //find out the text by language
639             //DB_DataObject::DebugLevel(1);
640             $x = DB_DataObject::factory($this->tableName());
641             $x->lang = $flexy->options['locale'];
642             $x->template_id = $tmpl->id;
643             $x->autoJoin();
644             $cache[$tmpname]->translations = $x->fetchAll('src_id_mdsum', 'txt');
645             if (empty($cache[$tmpname]->translations)) {
646                 $cache[$tmpname]->translations = true;
647             }
648             //var_Dump($cache[$tmpname]->translations);
649         }
650         
651         
652         if ($cache[$tmpname]->translations === true) {
653             return $string;
654         }
655         //var_dump("Checking: " . md5(trim($string)));
656         
657         if (!empty($cache[$tmpname]->translations [md5(trim($string))])){
658            // var_dump("RETURNING: ". $cache[$tmpname]->translations [md5(trim($string))]);
659             return $cache[$tmpname]->translations [md5(trim($string))];
660         }
661         return $string;
662         
663     }
664     
665     
666     function translateChanged($flexy)
667     {
668         
669         $date = $this->lastUpdated($flexy);
670         if ($date === false) {
671             return false;
672         }
673         $utime = file_exists($flexy->compiledTemplate) ?  filemtime( $flexy->compiledTemplate) : 0;
674         return strtotime($date) >  $utime;
675     }
676     
677     // determine if a complied template need recompling
678     
679     function lastUpdated($flexy)
680     {
681         //return true;
682         // var_dump('check changed?');
683         //DB_DataObject::debugLevel(1);
684         //var_Dump(array($flexy->options['templateDir'][0], $flexy->currentTemplate));
685         
686         //var_dump($flexy->compiledTemplate);
687         $utime = file_exists($flexy->compiledTemplate) ?  filemtime( $flexy->compiledTemplate) : 0;
688         
689        
690         static $cache = array(); // cache of templates..
691         
692         $ff = HTML_FlexyFramework::get();
693         $view_name = isset($ff->Pman_Core['view_name']) ? $ff->Pman_Core['view_name'] : false;
694         
695         // find which of the template directories was actually used for the template.
696         
697         $tempdir = '';
698         foreach($flexy->options['templateDir'] as $td) {
699             if (substr($flexy->currentTemplate, 0, strlen($td)) == $td) {
700                 $tempdir = $td;
701                 break;
702             }
703         }
704         
705         
706         $tmpname = substr($flexy->currentTemplate, strlen($td) +1);
707         
708         // we do not have any record of this template..
709         if (isset($cache[$tmpname]) && $cache[$tmpname] === false) {
710             return false;
711         }
712         
713         if (!isset($cache[$tmpname])) {
714                 
715             
716             
717             $tmpl = DB_DataObject::factory('core_template');
718             if ($view_name !== false) {
719                 $tmpl->view_name = $view_name;
720             }
721             if(!$tmpl->get('template', $tmpname)){
722                 // strip of site prefix if set...
723                  
724                 $tmpl = DB_DataObject::factory('core_template');
725                 if(!$tmpl->get('template', $tmpname)){
726                     //var_dump("no template? {$tmpname} or {$relpath}" );
727                     $cache[$tmpname] = false;
728                     return false;
729                 }
730             }
731             $cache[$tmpname] = $tmpl;
732         } else {
733             $tmpl = $cache[$tmpname] ;
734         }
735           
736          
737         
738         $x = DB_DataObject::factory($this->tableName());
739         $x->lang = $flexy->options['locale'];
740         $x->active = 1;
741         $x->template_id = $tmpl->id;
742         //$x->whereAdd("updated > '". date('Y-m-d H:i:s', $utime)."'");
743         if ($x->count() < 1) {
744             return false; // we don't have any record of it.
745         }
746         $x->selectAdd();
747         $x->selectAdd('max(updated) as max_updated');
748         $x->find(true);
749         return $x->max_updated;
750         
751         
752     }
753     
754     function toRooArray($req) {
755         $ret = $this->toArray();
756
757         if (empty($req['csvCols'])) {
758             return $ret;
759         }
760
761         // for download
762
763         // translations for table columns
764         if(!empty($ret['on_table']) && !empty($ret['on_id']) && !empty($ret['on_col'])) {
765             $ret['template_id_view_name'] = 'database';
766             $ret['template_id_template'] = $ret['on_table'] . ':' . $ret['on_col'];
767         }
768
769         return $ret;
770     }
771
772     function postListFilter($ar, $au, $req)
773     {
774         if (empty($req['csvCols'])) {
775             return $ar;
776         }
777
778         // for download
779
780         $ret = array();
781
782         foreach($ar as $v) {
783             if(empty($v['on_table']) || empty($v['on_id']) || empty($v['on_col'])) {
784                 $ret[] = $v;
785                 continue;
786             }
787
788             // translations for table columns
789             // avoid duplicate (same src_id_mdsum, same on_table, same on_col, but different on_id)
790
791             $key = $v['on_table'] . ':' . $v['on_col'] . ':' . $v['src_id_mdsum'];
792
793             if(!empty($ret[$key])) {
794                 continue;
795             }
796
797             $ret[$key] = $v;
798         }
799
800         $ret = array_values($ret);
801         
802         return $ret;
803
804     }
805 }