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