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