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