skip check if in english
[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
266         $t = DB_DataObject::factory($this->tableName());
267         $t->template_id = $tmpl->id;
268         $t->whereAdd("lang = ''");
269         
270         
271         // we have a situation where old md sums where created..
272         
273         
274         
275         $cur = $t->fetchAll('mdsum', 'id'); 
276         
277         
278         
279         
280         
281         
282         
283         // now loop through current..
284         $cwords = array();// not in used??
285         $active = array();
286 //        echo "sync Template Words... \n";
287 //        print_r($words);
288         
289         foreach($words as $k=>$v) {
290             
291             
292             $v = trim($v);
293             
294             $md = $keyvalue ? $k : md5($v);
295             
296             // check to see if there are more that one versions of that md5
297             
298             
299             if (!isset($cur[$md])) {
300                 // create a record for it..
301                 $t = DB_DataObject::factory($this->tableName());
302                 $t->setFrom(array(
303                     'txt' => $v,
304                     'lang' => '',// by default should a english 
305                     'updated' => date('Y-m-d H:i:s', strtotime("YESTERDAY")),
306                     'template_id'=>$tmpl->id,
307                     'mdsum' => $md,
308                     'src_id' => 0,
309                     'active' => 1,
310                 ));
311                 $active[] =  $t->insert();
312                 continue;
313             }  
314             $cur[$md] = $this->checkDupes($tmpl->id, '',  $cur[$md] , $md);
315             
316             $active[] = $cur[$md];
317             
318             // we have it already? - 
319             $tt->query("UPDATE {$this->tableName()}
320                         SET active= 1
321                         WHERE
322                         id = ".$cur[$md]);
323             unset($cur[$md]);
324             
325         }
326         // delete unused.
327         
328         
329         
330
331         $deactive = array();
332         if (count(array_values($cur))) {// de-active unused
333
334             $t = DB_DataObject::factory($this->tableName());
335 //            echo "de-active current?? \n";
336 //            print_r($cur);
337 //            echo "\n";
338             $deactive = array_values($cur);
339             $t->query("UPDATE core_templatestr
340                       SET active = 0 WHERE id in (" . implode(',' ,$deactive) . ")
341                      ");
342         }
343         
344         // delete all the items that are not relivant.
345         // clear orphaned chidren - it just blanks out the src id, so they can be used as suggestions..?
346         // this does not help - as it just puts random strings in there.. - with no reference to the original text..
347         $t = DB_DataObject::factory($this->tableName());
348     
349         // this will active the child data
350         if (empty($active)) {// set the active array to empty
351             $active = array(-1);
352         }
353         $t->query("UPDATE  core_templatestr 
354                 SET active = 1
355                   WHERE
356                      src_id IN (". implode(',' ,$active) . ")
357                     AND
358                     template_id = {$tmpl->id}
359         ");
360         //deactive the child data
361         if (empty($deactive)) {
362             $deactive = array(-1);
363         }
364         $t->query("UPDATE  core_templatestr 
365                 SET active = 0
366                   WHERE
367                     src_id IN (". implode(',' ,$deactive) . ")
368                     AND
369                     template_id = {$tmpl->id}
370                     AND
371                     lang != ''
372         ");
373     }
374     
375     function checkDupes($tid, $lang, $id, $mdsum) {
376         
377         $t = DB_DataObject::factory($this->tableName());
378         $t->template_id = $tid;
379         $t->mdsum = $mdsum;
380         $t->whereAdd("lang = '{$lang}'");
381         if ($t->count() == 1) {
382             return $id; // only got one ... no issues..
383         }
384         
385         //echo "GOT DUPES : $id, $lang, $id , $mdsum\n";
386         
387         //DB_DataObject::debugLevel(1);
388         // find out if any of them have got translations.
389         $ids = $t->fetchAll('id');
390         
391         
392         $t = DB_DataObject::factory($this->tableName());
393         $t->whereAddIn('src_id', $ids, 'int');
394         $t->whereAdd("txt != ''");
395         $t->orderBy('updated DESC');
396         if ($t->count()) {
397             $t->limit(1);
398             // do any translations exist?
399             $t->find(true);
400             $id = $t->src_id;
401         }
402         
403         
404         // delete all the others...
405         $t = DB_DataObject::factory($this->tableName());
406         $t->whereAddIn('src_id', $ids, 'int');
407         $t->whereAdd("src_id != $id");
408         $t->find();
409         while($t->fetch()) {
410             $tt = clone($t);
411             $tt->mdsum = $t->mdsum . '-bad-'. $t->id;
412             $tt->update($t);
413         }
414         $t = DB_DataObject::factory($this->tableName());
415         $t->whereAddIn('id', $ids, 'int');
416         $t->whereAdd("id != $id");
417         $t->find();
418         while($t->fetch()) {
419             $tt = clone($t);
420             $tt->mdsum = $t->mdsum . '-bad-'. $t->id;
421             $tt->update($t);
422         }
423         // this is done by calling code 
424         //$t = DB_DataObject::factory($this->tableName());
425         //$t->query("update core_templatestr set active= 1 where src_id = $id");
426         
427         
428         
429        //exit;
430         return $id;
431     
432                
433          
434     }
435     
436     function syncLang($lang)
437     {
438         // bugs with our old code...
439 //        die('in?');
440         $tn = $this->tableName();
441         $t = DB_DataObject::factory($tn);
442         $t->query("DELETE FROM {$tn} WHERE lang !='' AND src_id = 0 AND on_table  = ''");
443         
444         // find all the id's from lang that have not been generated..
445         
446         //find the origanal 
447         $t = DB_DataObject::factory($tn);
448         $t->whereAdd("lang = ''");
449         $t->active = 1;
450         
451         //old code, this did not support the on_table
452 //        $id_tmp = $t->fetchAll('id','template_id');
453 //        $ids = array_keys($id_tmp);
454         $id_tmp = array();
455         //new code for support the sync tables 
456         foreach($t->fetchAll() as $ori){
457             $id_tmp[$ori->id] = $ori;
458         }
459         $ids = array_keys($id_tmp);
460         
461         // matching by language:
462         $t = DB_DataObject::factory($tn);
463         $t->whereAddIn('src_id', $ids , 'int');
464         $t->lang = $lang;
465         //$t->active = 1;
466         $got = $t->fetchAll('src_id');
467         $missing = array_diff($ids, $got);
468         foreach($missing as $id) {
469             
470             $t = DB_DataObject::factory($tn);
471             $t->setFrom(array(
472                 'src_id' => $id,
473                 'txt' =>  '',
474                 'lang' => $lang,
475                 'updated' => date('Y-m-d H:i:s', strtotime("NOW")),
476                 'template_id'=> $id_tmp[$id]->template_id,
477                 'on_table' => $id_tmp[$id]->on_table,
478                 'on_id' => $id_tmp[$id]->on_id,
479                 'on_col' => $id_tmp[$id]->on_col,
480                 'active' => 1,
481                 // no md5um
482             ));
483             $t->insert();
484         }
485         
486         
487         
488     }
489     
490     // called from flexy to translate a string.
491     
492     
493     function translateFlexyString($flexy, $string)
494     {
495          $debug = false;;
496         //if (!empty($_REQUEST['_debug'])) { $debug= true; }
497         
498         // using $flexy->currentTemplate -> find the template we are looking at..
499         // then find the string for $flexy->options['locale']
500         //DB_DataObject::debugLevel(1);
501         if ($debug) { var_dump($string); }
502         
503         static $cache = array(); // cache of templates..
504         
505         $ff = HTML_FlexyFramework::get();
506         $view_name = isset($ff->Pman_Core['view_name']) ? $ff->Pman_Core['view_name'] : false;
507         if (empty($view_name)) {
508             $pg = HTML_FlexyFramework::get()->page;
509             if (isset($pg->templateViewName)) {
510                 $view_name = $pg->templateViewName;
511             }
512             
513         }
514         
515         
516         
517         if ($debug) { var_dump(array('view_name'=> $view_name)); }
518         
519         $tempdir = '';
520         foreach($flexy->options['templateDir'] as $td) {
521             if (substr($flexy->currentTemplate, 0, strlen($td)) == $td) {
522                 $tempdir = $td;
523                 break;
524             }
525         }
526         
527         
528         $tmpname = substr($flexy->currentTemplate, strlen($td) +1);
529         
530          
531         if (isset($cache[$tmpname]) && $cache[$tmpname] === false) {
532             if ($debug) { echo "from cache no match - $string\n"; }
533             return $string;
534         }
535         
536         if (!isset($cache[$tmpname])) {
537                 
538             
539             
540             $tmpl = DB_DataObject::factory('core_template');
541             if ($view_name !== false) {
542                 $tmpl->view_name = $view_name;
543             }
544             if(!$tmpl->get('template', $tmpname)){
545                 // strip of site prefix if set...
546                  
547                 $tmpl = DB_DataObject::factory('core_template');
548                 if(!$tmpl->get('template', $tmpname)){
549                     //var_dump("no template? {$tmpname} or {$relpath}" );
550                     $cache[$tmpname] = false;
551                     if ($debug) { echo "no template found - no match - $string\n"; }
552                     return $string;
553                 }
554             }
555             $cache[$tmpname] = $tmpl;
556         } else {
557             $tmpl = $cache[$tmpname] ;
558         }
559         
560         
561     
562         //get original template id
563         /*
564         $orig = DB_DataObject::factory($this->tableName());
565         $orig->lang = '';
566         $orig->template_id = $tmpl->id;
567         $orig->active = 1;
568         
569         $cache[$tmpname]->words = 
570         
571         if(!$orig->get( 'mdsum' , md5(trim($string)))){
572              //var_dump('no text? '. $string);
573             if ($debug) { echo "no original string found tplid: {$tmpl->id}\n"; }
574             return false;
575         }
576         */
577         
578         if (empty($cache[$tmpname]->translations)) {
579         
580             //find out the text by language
581             //DB_DataObject::DebugLevel(1);
582             $x = DB_DataObject::factory($this->tableName());
583             $x->lang = $flexy->options['locale'];
584             $x->template_id = $tmpl->id;
585             $x->autoJoin();
586             $cache[$tmpname]->translations = $x->fetchAll('src_id_mdsum', 'txt');
587             if (empty($cache[$tmpname]->translations)) {
588                 $cache[$tmpname]->translations = true;
589             }
590             //var_Dump($cache[$tmpname]->translations);
591         }
592         
593         
594         if ($cache[$tmpname]->translations === true) {
595             return $string;
596         }
597         //var_dump("Checking: " . md5(trim($string)));
598         
599         if (!empty($cache[$tmpname]->translations [md5(trim($string))])){
600            // var_dump("RETURNING: ". $cache[$tmpname]->translations [md5(trim($string))]);
601             return $cache[$tmpname]->translations [md5(trim($string))];
602         }
603         return $string;
604         
605     }
606     
607     // determine if a complied template need recompling
608     
609     function translateChanged($flexy)
610     {
611         //return true;
612         // var_dump('check changed?');
613         //DB_DataObject::debugLevel(1);
614         //var_Dump(array($flexy->options['templateDir'][0], $flexy->currentTemplate));
615         
616         //var_dump($flexy->compiledTemplate);
617         $utime = file_exists($flexy->compiledTemplate) ?  filemtime( $flexy->compiledTemplate) : 0;
618         
619         
620         static $cache = array(); // cache of templates..
621         
622         $ff = HTML_FlexyFramework::get();
623         $view_name = isset($ff->Pman_Core['view_name']) ? $ff->Pman_Core['view_name'] : false;
624         
625         $tempdir = '';
626         foreach($flexy->options['templateDir'] as $td) {
627             if (substr($flexy->currentTemplate, 0, strlen($td)) == $td) {
628                 $tempdir = $td;
629                 break;
630             }
631         }
632         
633         
634         $tmpname = substr($flexy->currentTemplate, strlen($td) +1);
635         
636         if (isset($cache[$tmpname]) && $cache[$tmpname] === false) {
637             return false;
638         }
639         
640         if (!isset($cache[$tmpname])) {
641                 
642             
643             
644             $tmpl = DB_DataObject::factory('core_template');
645             if ($view_name !== false) {
646                 $tmpl->view_name = $view_name;
647             }
648             if(!$tmpl->get('template', $tmpname)){
649                 // strip of site prefix if set...
650                  
651                 $tmpl = DB_DataObject::factory('core_template');
652                 if(!$tmpl->get('template', $tmpname)){
653                     //var_dump("no template? {$tmpname} or {$relpath}" );
654                     $cache[$tmpname] = false;
655                     return false;
656                 }
657             }
658             $cache[$tmpname] = $tmpl;
659         } else {
660             $tmpl = $cache[$tmpname] ;
661         }
662           
663          
664         
665         $x = DB_DataObject::factory($this->tableName());
666         $x->lang = $flexy->options['locale'];
667         $x->active = 1;
668         $x->template_id = $tmpl->id;
669         $x->whereAdd("updated > '". date('Y-m-d H:i:s', $utime)."'");
670         
671         return $x->count() ? true : false;
672         
673         
674     }
675     
676 }