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