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