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