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