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