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