2382eb897bec2eb11d324b33521ab9d8c83e9ac7
[Pman.Cms] / DataObjects / Cms_template.php
1 <?php
2 /**
3  * Table Definition for cms_template 
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_template  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_template';         // table name
18     public $id;                              // int(11)  not_null primary_key auto_increment
19     public $template;                           // string(64)  not_null
20
21     public $updated;                        // blob(65535)  blob
22     public $lang;    // text  NOT NULL;
23     public $view_name; // eg mobile or desktop
24     /* the code above is auto generated do not remove the tag below */
25     ###END_AUTOCODE
26     
27     
28     function applyFilters($q, $au, $roo)
29     {
30         //DB_DataObject::debugLEvel(1);
31 //        $x = DB_Dataobject::Factory($this->tableName());
32         
33         
34         // template scanning and syncing should be done by the UpdateDatabase Code.
35         //if (!$x->count() || !empty($q['_rescan'])) {
36             //DB_DataObject::debugLEvel(1);
37             //$tp = DB_DataObject::factory('cms_template');
38             //$opts = HTML_FlexyFramework::get()->Pman_Cms;
39             //$tp->syncTemplateDir(false, '', !empty($q['_rescan']));
40             //if (isset($q['lang'])) {
41             //    $this->syncLang($q['lang']);
42             //}
43         //} 
44 //        $this->whereAdd("
45 //                join_
46 //            ");
47         
48     }
49         
50     function toRooArray($req)
51     {
52         $ret = $this->toArray();
53         if (!empty($req['_clean_name']) ) {
54             $ret['template_clean'] = preg_replace('#\.html$#i', '', $this->template);
55             
56         }
57         return $ret;
58         
59     }
60     
61     /*
62      * @param base (should be full path to template directory)
63      * @param subdir = empty for top or subpath.
64      */
65     function syncTemplateDir($base = false,  $subdir = '', $force = false)
66     {
67         echo "syncTemplateDir: $base , $subdir, $force \n";
68         //print_r(func_get_args());
69         if (!$base) {
70             $ff = HTML_FlexyFramework::get();
71             if (!isset($ff->Pman_Cms)) {
72                 echo "[ERROR] Not scanning template directory - no set in Pman_Cms[templateDir]\n";
73                 return;
74             }
75             $opts = $ff->Pman_Cms;
76             if (is_array($opts['templateDir'])) {
77                 foreach($opts['templateDir'] as $type=>$dir) {
78                     $this->syncTemplateDir($dir, '', $force);
79                 }
80                 return;
81             }
82             
83             $base = $opts['templateDir'];
84             
85             
86         }
87         if($force){
88             $tmpls = DB_DataObject::factory('cms_template');
89             $this->tmpls = $tmpls->fetchAll('template','id'); // dupes??
90         }
91         
92         $tmp_dir = $base . (empty($subdir) ? '' : '/') . $subdir;
93         
94         if(!is_dir($tmp_dir)){
95             return;
96         }
97         
98         $dh = opendir($tmp_dir);
99         if(!$dh){
100             return; // something went wrong!?
101         }
102         
103         while (($fn = readdir($dh)) !== false) {
104             // do we care that it will try and parse the template directory??? - not really..
105             // as we are only looking for php files..
106             if(empty($fn) || $fn[0] == '.'){
107                 continue;
108             }
109
110             $fullpath = $tmp_dir."/".$fn;
111 //            echo "filename: ".$fullpath." \n";    
112              
113             $relpath = $subdir . (empty($subdir) ? '' : '/') . $fn;
114             
115             if(is_dir($fullpath)){
116                 // then recursively call self...
117 //                var_Dump($base);
118 //                var_Dump($subdir . (empty($subdir) ? '' : '/') . $fn);
119                 $this->syncTemplateDir($base, $subdir . (empty($subdir) ? '' : '/') . $fn );
120                 
121                 continue;
122             }
123             if (!preg_match('/(\.html|\.txt)$/', $fn)) {
124                 continue;
125             }
126             
127              
128 //            var_dump($tmp);
129 //            var_dump($tmp_path);
130 //            $fn = basename($fn);
131             if (isset($this->tmpls[$relpath])) {
132                 unset($this->tmpls[$relpath]);
133             }
134             
135             
136             
137                
138             $template = $this->syncTemplate($relpath, true, false);
139 //            var_dump($template);
140             if (is_a($template, 'PEAR_Error')) {
141                 continue;
142             }
143         }
144         closedir($dh);
145 //        
146  
147         if($force){
148             foreach($this->tmpls as $id) {
149                 $x = DB_DataObject::factory($this->tableName());
150                 if ($x->get($id)) {
151                     $x->delete();
152                 }
153             }
154         }
155     }
156     
157     
158        /**
159       *
160       * sync a single template
161       * This should only be called by the UpdateDatabase code.
162       * @param string $n      name of template
163       * @param boolean $force  force parsing.
164       * @param string $link ??? related to CMS page???
165         
166       * @return boolean|PEAR_Error errors if compile fails..
167       *
168       */
169      /*
170     function syncTemplate($n, $force = false, $link = '')
171     {
172         // read the template and extract the translatable strings.
173         ini_set('memory_limit', '512M');
174         
175         //var_dump($n);
176         $n= ltrim($n,'/');  // remove trailing slash..
177         
178         $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
179         $opts = HTML_FlexyFramework::get()->Pman_Cms;
180         //print_R($opts);
181         //$dir = $opts['templateDir'] . '/' . $node;
182         
183         $oo['templateDir'] = $opts['templateDir'] ;
184         $oo['compileDir'] = $fopts['compileDir'] . '_translation_files';
185         $oo['forceCompile'] = true; //?? only for force above???
186          
187         $prefix = explode('/', $link);
188         
189         $n_split  = explode('/', $n);
190         // this is project specific and should not be put in here..
191         // we need a better way to handle it...
192         // if first part of template dire matches an option in our settings...
193         $pf = false;
194         if (is_array($opts['templateDir']) &&  strlen($link) && isset($opts['templateDir'][$prefix[0]] )) {
195             //echo "renaming templatedir/file (2)\n";
196             $pf = $prefix[0];
197             $oo['templateDir'] = $opts['templateDir'][$pf];
198             
199             
200         }
201         
202         if (is_array($opts['templateDir']) &&  count($n_split) > 1 && isset($opts['templateDir'][$n_split[0]] )) {
203             //echo "renaming templatedir/file (2)\n";
204             $pf = $n_split[0];
205             $oo['templateDir'] = $opts['templateDir'][$pf];
206             $n = substr($n,  (strlen($pf)+1));
207             //var_dump($n);
208         }
209         // non-html templates - treat as such..
210         if (!preg_match('/\.html$/i', $n)) {
211             $oo['nonHTML'] = true;
212         }
213         ///print_r(array($oo, $n));
214         
215         
216         $flexy = new HTML_Template_Flexy( $oo );
217           
218         $r = $flexy->compile($n);
219        
220 //        print_r( $flexy->compiler);
221       
222         //printf(" %0.3fs : $fname<BR>", $time);
223         if (is_a($r,'PEAR_Error')) {
224             return $r;
225         }
226         //print_R(number_format(memory_get_usage(),0, '.', ','))  ;
227         $words = file_exists($flexy->getTextStringsFile) ?
228                 unserialize(file_get_contents($flexy->getTextStringsFile)) :
229                 array();
230         
231         $contentStrings =  $flexy->compiler->contentStrings;
232         
233         print_R($contentStrings);
234         $ori_n = $n;
235         if($pf){// support prefix
236             
237             $n = $pf.'/'.$n;
238         }
239         
240         //check the template is static page or not 
241         $link_split = explode('/', $link);
242         $is_static = ($link_split[0] == 'Static') ? 1 : 0;
243         
244         $tmpl = DB_DataObject::Factory($this->tableName());
245         if (!$tmpl->get('template', $n)) {
246             $nn = $n;
247             if($is_static)
248             {
249                 $nn = 'static/'.$n;
250             }
251             $tmpl->template = $nn;
252             $tmpl->lang = 'en'; /// ??? hard coded??
253             $tmpl->updated = date('Y-m-d H:i:s', filemtime($flexy->currentTemplate));
254             $tmpl->insert();
255         } else {
256             $xx =clone($tmpl);
257             // has it been cahnged...
258             if (!$force && filemtime($flexy->currentTemplate) == strtotime($tmpl->updated)) {
259                 // nothing changed..
260                 return $tmpl;
261             }
262             if (empty($tmpl->lang))  {
263                 //echo "FIX LANG?";exit;
264                 $tmpl->lang = 'en'; /// ??? hard coded??
265             }
266             
267             $tmpl->updated = date('Y-m-d H:i:s', filemtime($flexy->currentTemplate));
268             $tmpl->update($xx);
269         }
270         $cmsPage = false;
271         
272         
273         
274         if(!empty($link) && empty($is_static)){
275             
276             $page_id = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'page');
277             echo "$link \n";
278             $cmsPage = DB_DataObject::factory('cms_page');
279             $cmsPage->setFrom(array(
280                 'page_link'  => $link,
281                 'page_type_id'  => $page_id,
282                 'translation_of_id' => 0,
283                 'is_element' => 0,
284             ));
285             $parent = 0;
286             if(!$cmsPage->find(true)){
287                 $cmsPage = DB_DataObject::factory('cms_page');
288             } else {
289                 // existing parent..
290                 $parent = $cmsPage->parent_id;
291             }
292             
293             if (!$parent && strpos($link,'/') !== false) {
294                 $par = explode('/', $link);
295                 array_pop($par);
296                 $pname = implode('/', $par);
297                 $cmsPageP = DB_DataObject::factory('cms_page');
298                 if ($cmsPageP->get('page_link',$pname)) {
299                     $parent = $cmsPageP->id;
300                 }
301             }
302             
303             //if not php was found then the page should be a static
304             $php = explode('/', $link);
305             array_shift($php);
306             
307             
308             $file = explode('/', $oo['templateDir']);
309             array_pop($file);
310             $file = implode('/', $file).'/'.implode('/', $php).'.php';
311             
312             $is_static = 1;
313         
314             // not sure how this is supposed to work..
315             // if a tempalte exists then static = 0 ??
316         
317             if(preg_match('/\.html$/', $ori_n) && file_exists($file)){
318                 $is_static = 0;
319             }
320
321 //            echo "$ori_n <<<< $is_static \n";
322             $run_opts  = HTML_FlexyFramework::get()->page->opts;
323             
324             $cmsPage->setFrom(array(
325                 'parent_id' => $parent,
326                 'page_link'  => $link,
327                 'title' => basename($link),
328                 'page_type_id'  => $page_id,
329                 'template_id' => $tmpl->id,
330                 'language' => 'en',
331                 'translation_of_id' => 0,
332                 'is_system_page' => 1,
333                 'is_element' => 0,
334                 'is_static' => $is_static,
335             ));
336             //print_r($contentStrings);
337             
338             if (!empty($run_opts['force-content-update']) || !$cmsPage->id) { // only do this for the initila load
339                 foreach( array('title', 'body', 'extended') as $prop) {
340                     if (isset($contentStrings['{page.'. $prop.'}'])) {
341                         $cmsPage->{$prop} = $contentStrings['{page.'. $prop.'}'];
342                     }
343                     if (isset($contentStrings['{page.'. $prop.':h}'])) {
344                         $cmsPage->{$prop} = $contentStrings['{page.'. $prop.':h}'];
345                     }
346                     if (isset($contentStrings['{page.'. $prop.'ToDisplayHtml():h}'])) {
347                         $cmsPage->{$prop} = $contentStrings['{page.'. $prop.'ToDisplayHtml():h}'];
348                     }
349                     echo "cmrpage->{$prop} = ". $cmsPage->{$prop} ."\n";
350                 }
351             }   
352             
353              
354             
355             if(!$cmsPage->id){
356                 $cmsPage->insert();
357             } else {
358                 $cmsPage->update();
359             }
360         }
361         
362         $x = DB_DataObject::Factory('cms_templatestr');
363         $x->syncTemplateWords($tmpl, $words);
364         
365         // if file_exists ( template/path/name.php << eg. a matching view..)
366         // then create a system page for this. 
367         
368         
369         
370         $x = DB_DataObject::Factory('cms_template_element');
371         $x->syncTemplateElement($tmpl, file_get_contents($flexy->currentTemplate), $flexy->compiler->contentStrings, $cmsPage);
372         
373         return $tmpl;
374     
375     }
376     */
377     function syncTemplatePage($pgdata)
378     {
379         $force = true;
380         echo "compiling:"; print_r($pgdata);
381         // read the template and extract the translatable strings.
382         ini_set('memory_limit', '512M');
383         
384         //var_dump($n);
385         $n= $pgdata['template'];  // remove trailing slash..
386         
387         $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
388         $opts = HTML_FlexyFramework::get()->Pman_Cms;
389         //print_R($opts);
390         //$dir = $opts['templateDir'] . '/' . $node;
391         $oo = array(
392             'disableTranslate' => false,
393             'templateDir' => $pgdata['template_dir'],
394             'compileDir' => $fopts['compileDir'] . '_translation_files',
395             'forceCompile' => true, //?? only for force above???
396         );
397          
398         // non-html templates - treat as such..
399         if (!preg_match('/\.html$/i', $pgdata['template'])) {
400             $oo['nonHTML'] = true;
401         }
402         
403         //print_r(array($oo, $n));
404         
405         
406         $flexy = new HTML_Template_Flexy( $oo );
407           
408         if (!$flexy->resolvePath ($pgdata['template'])) {
409             
410             echo "SKIP - could not resolve path?\n";
411             print_r($oo);
412             return false;
413         }
414           
415           
416         $r = $flexy->compile($pgdata['template']);
417        
418         //print_r( $flexy);
419       
420         //printf(" %0.3fs : $fname<BR>", $time);
421         if (is_a($r,'PEAR_Error')) {
422             
423             echo $r->toString(). "\n";
424             return $r;
425         }
426         //print_R(number_format(memory_get_usage(),0, '.', ','))  ;
427          
428         $tmpl = DB_DataObject::Factory($this->tableName());
429         $tmpl->words = file_exists($flexy->getTextStringsFile) ?
430                 unserialize(file_get_contents($flexy->getTextStringsFile)) :
431                 array();
432         
433         $tmpl->contentStrings   = $flexy->compiler->contentStrings;
434         //var_dump(file_exists($flexy->getTextStringsFile));
435         print_r($tmpl->words);
436         $tmpl->currentTemplate  = $flexy->currentTemplate;
437         
438         $tmpl->view_name = $pgdata['base'];
439         
440         
441         if (!$tmpl->get('template',  $pgdata['template'])) {
442             
443             $tmpl->template = $pgdata['template'];
444             $tmpl->lang = 'en'; /// ??? hard coded??
445             $tmpl->updated = date('Y-m-d H:i:s', filemtime($flexy->currentTemplate));
446             $tmpl->insert();
447         } else {
448             $xx =clone($tmpl);
449             // has it been cahnged...
450             //if (!$force && filemtime($flexy->currentTemplate) == strtotime($tmpl->updated)) {
451                 // nothing changed..
452             //    return $tmpl;
453             //}
454             if (empty($tmpl->lang))  {
455                 //echo "FIX LANG?";exit;
456                 $tmpl->lang = 'en'; /// ??? hard coded??
457             }
458             
459             $tmpl->updated = date('Y-m-d H:i:s', filemtime($flexy->currentTemplate));
460             $tmpl->update($xx);
461         }
462       
463         
464         $x = DB_DataObject::Factory('cms_templatestr');
465         $x->syncTemplateWords($tmpl);
466         
467         // if file_exists ( template/path/name.php << eg. a matching view..)
468         // then create a system page for this. 
469         
470         
471         
472         $x = DB_DataObject::Factory('cms_template_element');
473         $tmpl->elements = $x->syncTemplateElement($tmpl,
474                 file_get_contents($flexy->currentTemplate),
475                 $flexy->compiler->contentStrings,
476                 false);
477         
478         
479         
480         return clone($tmpl);
481     
482     }
483 }