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