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