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