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