forked from uxturtle/pages-module
/
pages.php
815 lines (684 loc) · 20.6 KB
/
pages.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
<?php defined('SYSPATH') or die('No direct script access.');
/**
* Pages Library
*
* @package Pages Module
* @author Sam Soffes
* @author Josh Turmel
* @author Ben Haan
*/
class Pages {
private static $url_pre_counter = 0;
private static $url_pre = 1;
protected $html = '';
protected $head = '';
protected $js_output = '';
// Title
protected $title = array();
protected $title_rev = FALSE;
protected $title_sep;
// Head pieces
protected $meta = array();
protected $link = array();
protected $css = array();
protected $js = array();
protected $raw_js = array();
public $ext_url;
public $css_url;
public $js_url;
// Content pieces
public $template;
// Misc variables
protected $format_output;
protected $eol = "\r\n"; // Windows compatible line breaking
protected $version; // Version number to append to end of JS and CSS files to combat caching
// Cache Externals
protected $cache_css_exists = FALSE;
protected $cache_js_exists = FALSE;
protected $cache_css_key;
protected $cache_js_key;
protected $cache_css = array
(
'data' => '',
'file' => ''
);
protected $cache_js = array
(
'data' => '',
'file' => ''
);
protected $css_cache_list = array();
protected $js_cache_list = array();
// Cache Externals Temporary Containers
protected $cache_container_css = '';
protected $cache_container_js = '';
// Site wide variables passed to views
protected $config = array();
/**
* Returns a singleton instance of URI.
*
* @return object
*/
public static function instance()
{
static $instance;
if ($instance == NULL)
{
// Initialize the URI instance
$instance = new Pages;
}
return $instance;
}
public function __construct()
{
// Setup <head> variables from config file
$this->title[] = Kohana::config('pages.title');
$this->title_sep = Kohana::config('pages.title_seperator');
$this->title_rev = Kohana::config('pages.title_reverse');
$this->ext_url = Kohana::config('pages.ext_url');
$this->css_url = $this->ext_url.Kohana::config('pages.css_dir');
$this->js_url = $this->ext_url.Kohana::config('pages.js_url');
$this->template = Kohana::config('pages.template');
$this->cache_lifetime = Kohana::config('pages.cache_lifetime');
$this->format_output = Kohana::config('pages.format_output');
// Make sure that urls have a trailing slash
$this->css_url = ((substr($this->css_url, -1) != '/') ? $this->css_url.'/' : $this->css_url);
$this->js_url = ((substr($this->js_url, -1) != '/') ? $this->js_url.'/' : $this->js_url);
$this->ext_path = Kohana::config('pages.ext_path');
$this->css_path = $this->ext_path.Kohana::config('pages.css_dir');
$this->js_path = $this->ext_path.Kohana::config('pages.js_dir');
// Setup misc switches and vars
$this->cache_externals = Kohana::config('pages.cache_externals');
$this->version = (Kohana::config('pages.version') ? '?'.Kohana::config('pages.version') : '');
}
public function addTitle($title)
{
$this->title[] = $title;
}
public function clearTitle()
{
$this->title = array();
}
public function reverseTitle()
{
$this->title_rev = TRUE;
}
public function setTitleSep($sep)
{
$this->title_sep = $sep;
}
public function getCacheIdForView($name)
{
return 'page_view_'.(($this->lang) ? $this->lang.'_' : '').md5(url::current().$name);
}
public function addLink($rel, $href, $type = FALSE, $title = FALSE) {
// By using href as key, it allows us to override in extended controllers.
$this->link[md5($rel.$href.$type.$title)] = '<link rel="'.$rel.'" href="'.$href.'" '.($title !== FALSE ? 'title="'.$title.'" ' : '').($type !== FALSE ? 'type="'.$type.'" ' : '').'/>';
}
public function addOpenSearch($href, $title = FALSE)
{
$this->addLink('search', 'application/opensearchdescription+xml', $href, $title);
}
public function addRSS($href, $title = FALSE)
{
$this->addLink('alternate', $href, 'application/rss+xml', $title);
}
public function addMeta($name, $content)
{
$this->meta[$name] = '<meta name="'.$name.'" content="'.$content.'" />';
}
/**
* Protected method to add a script (css or js) to the head
*
* @throws Kohana_Exception
* @param string type ('css' or 'js')
* @param string filename
* @param boolean embed the script or link to it
* @return void
*/
protected function addScript($type, $file, $cache = null)
{
// Set cache defult
if ($cache === null && Kohana::config('pages.cache_externals') === TRUE)
{
$cache_list = $type.'_cache_list';
$list = &$this->$cache_list;
$list[$file] = TRUE;
$cache = TRUE;
}
elseif ($cache === null)
{
$cache = FALSE;
}
$url = $type.'_url';
$scripts = &$this->$type;
if (strpos($file, '://') !== FALSE)
{
$scripts[$file]['file'] = $file;
}
elseif (strpos($this->$url, '://') >= 0)
{
$scripts[$file]['file'] = $this->$url.$file.'.'.$type.$this->version;
}
else
{
$scripts[$file]['file'] = URL::site($this->$url.$file.'.'.$type.$this->version);
}
$scripts[$file]['cache'] = (bool) $cache;
}
/**
* Public method for adding css files to the head
*
* @param string filename
* @param boolean embed file or link to it.
* @param array create IE style and check and compare versions
* @return void
*/
public function addCSS($file, $cache = null, $ie_style = array('enable' => FALSE, 'version' => NULL, 'comparison' => NULL))
{
$this->addScript('css', $file, $cache);
if ($ie_style['enable'])
{
$this->css[$file]['ie_style'] = TRUE;
$this->css[$file]['ie_version'] = (isset($ie_style['version'])) ? $ie_style['version'] : NULL;
$this->css[$file]['ie_comparison'] = (isset($ie_style['comparison'])) ? $ie_style['comparison'] : NULL;
}
}
public function removeCSS($script)
{
unset($this->css[$script]);
}
public function removeAllCSS()
{
$this->css = array();
}
/**
* Public method for adding javascript files
*
* @param string filename
* @param boolean embed file or link to it.
* @param boolean include file in head or in $js variable
* @return void
*/
public function addJS($file, $cache = null, $separate = FALSE)
{
$this->addScript('js', $file, $cache);
if ($separate)
$this->js[$file]['separate'] = TRUE;
}
public function removeJS($script)
{
unset($this->js[$script]);
}
public function removeAllJS()
{
$this->js = array();
}
public function addRawJS($javascript)
{
$this->raw_js[] = $javascript;
}
private function buildCSSAndJS()
{
// Make the eol a local variable for less typing
$eol = $this->eol;
if (Kohana::config('pages.cache_externals'))
{
$this->cache_css_key = '_pages_'.Kohana::config('pages.version').'_'.md5(implode('', array_keys($this->css_cache_list)));
$this->cache_js_key = '_pages_'.Kohana::config('pages.version').'_'.md5(implode('', array_keys($this->js_cache_list)));
$this->cache_css_exists = $this->cacheExists('css', $this->cache_css_key);
$this->cache_js_exists = $this->cacheExists('js', $this->cache_js_key);
}
// Add regular css
foreach ($this->css as $css)
{
if ($css['cache'] === TRUE && $this->cache_css_exists === FALSE)
{
$this->fileCombine('css', $css['file']);
}
elseif ($css['cache'] === FALSE)
{
$style = '<link rel="stylesheet" href="'.$css['file'].'" type="text/css" />';
// Build IE only link tag
if (isset($css['ie_style']))
{
// Check that if a comparison is set, that a version of IE is too
if ($css['ie_comparison'] != NULL AND $css['ie_version'] == NULL)
throw new Kohana_Exception('A version of IE must be passed along with a comparison value');
$this->head .= str_replace(' ',' ','<!--[if '.$css['ie_comparison'].' IE '.$css['ie_version'].']>'.$eol);
$this->head .= "\t".$style.$eol;
$this->head .= '<![endif]-->'.$eol;
}
else
{
$this->head .= $style.$eol;
}
}
}
// Add Cached CSS
if ($this->cache_container_css != '')
{
if ($this->cache_css['data'] === '' || $this->cache_css['data'] === null)
{
$this->removeExpiredCache('css');
$cache = $this->setCache('css', $this->cache_css_key, $this->cache_container_css);
$this->head .= '<link rel="stylesheet" href="'.$this->css_url.$cache['filename'].'" type="text/css" />'.$eol;
}
else
{
$filename = str_replace(realpath(Kohana::config('pages.css_path')).'/', '', $this->cache_css['file']);
$this->head .= '<link rel="stylesheet" href="'.$this->css_url.$filename.'" type="text/css" />'.$eol;
}
}
elseif ($this->cache_css_exists === TRUE)
{
$this->head .= '<link rel="stylesheet" href="'.$this->css_url.$this->cache_css_key.'.css'.'" type="text/css" />'.$eol;
}
// Add regular js
foreach ($this->js as $js)
{
if ($js['cache'] === TRUE && $this->cache_js_exists === FALSE)
{
$this->fileCombine('js', $js['file']);
}
elseif ($js['cache'] === FALSE)
{
$output = '<script type="text/javascript" src="'.$js['file'].'"></script>'.$eol;
if (Kohana::config('pages.separate_js_output') === TRUE || $js['separate'])
{
$this->js_output .= $output;
}
else
{
$this->head .= $output;
}
}
}
// Add Cached JS
if ($this->cache_container_js != '')
{
if ($this->cache_js['data'] === '' || $this->cache_js['data'] === null)
{
$this->removeExpiredCache('js');
$cache = $this->setCache('js', $this->cache_js_key, $this->cache_container_js);
$output = '<script type="text/javascript" src="'.$this->js_url.$cache['filename'].'"></script>'.$eol;
if (Kohana::config('pages.separate_js_output') === TRUE)
{
$this->js_output .= $output;
}
else
{
$this->head .= $output;
}
}
else
{
$filename = str_replace(realpath(Kohana::config('pages.js_path')).'/', '', $this->cache_js['file']);
$output = '<script type="text/javascript" src="'.$this->js_url.$filename.'.js"></script>'.$eol;
if (Kohana::config('pages.separate_js_output') === TRUE || $cache['separate'])
{
$this->js_output .= $output;
}
else
{
$this->head .= $output;
}
}
}
elseif ($this->cache_js_exists === TRUE)
{
$output = '<script type="text/javascript" src="'.$this->js_url.$this->cache_js_key.'.js"></script>'.$eol;
if (Kohana::config('pages.separate_js_output') === TRUE)
{
$this->js_output .= $output;
}
else
{
$this->head .= $output;
}
}
// Add raw js
if (count($this->raw_js) > 0)
{
$output = '<script type="text/javascript">'.$eol.
implode($eol, $this->raw_js).$eol.
'</script>'.$eol;
if (Kohana::config('pages.separate_js_output') === TRUE)
{
$this->js_output .= $output;
}
else
{
$this->head .= $output;
}
}
}
private function buildHead()
{
// Make the eol a local variable for less typing
$eol = $this->eol;
// Start with nothing
$this->head = '';
// Meta tags
$this->head .= (count($this->meta)) ? implode($eol, $this->meta).$eol : '';
// Link tags
$this->head .= (count($this->link)) ? implode($eol, $this->link).$eol : '';
// Reverse Title
if ($this->title_rev)
{
$this->title = array_reverse($this->title);
}
// Title
$this->head .= '<title>'.implode($this->title_sep, $this->title).'</title>'.$eol;
// Build all of the CSS and JS
$this->buildCSSAndJS();
}
/**
* Assigns a value by reference. Gives same functionality as the View's bind method.
* Used for setting variables for every view.
*
* @param string variable name
* @param mixed referenced variable
* @return Pages
*/
public function bind($key, & $content)
{
$this->config[$key] =& $content;
return $this;
}
public function display($content = FALSE, $config = array(), $type = FALSE) {
// Make the eol a local variable for less typing
$eol = $this->eol;
// Construct the <head>
$this->buildHead();
// Grab the inner view
if ($content)
{
// Add the rest of the config if there isn't a template
if (!$this->template)
{
$config = array_merge(
$config,
array(
'head' => $this->head,
'js' => $this->js_output
)
);
// Add any global config array data and add it to data passed in
if ( ! empty($this->config))
$config = array_merge($config, $this->config);
}
$content = self::view($content, $config, $type);
}
// Display the page with a template
if ($this->template)
{
// Setup the main template config array and merge with config data passed in
$config = array_merge(
$config,
array(
'head' => $this->head,
'content' => $content.$eol,
'js' => $this->js_output
)
);
// Add any global config array data and add it to data passed in
if ( ! empty($this->config))
$config = array_merge($config, $this->config);
// Display the view
$view = View::factory($this->template, $config);
$output = $view->render();
}
else
{
$output = $content;
}
// Format output
$output = $this->formatHTML($output);
// Display the page
echo $output;
}
/**
* Returns the value of a view ane merges the config with any data passed to it
*
* @param string name of view
* @param boolean|array optional array of data to pass to the view
* @param string file extension
* @param boolean|int lifetime of cache. if set to true it will use the default
* cache from the pages config or use an int if it is passed one
* @return string contents of view or cache file
*/
public static function view($view, $config = FALSE, $type = FALSE, $lifetime = FALSE)
{
$page = self::instance();
// Setup caching and return the cache file it it works
if ($lifetime)
{
$cache = new Cache;
$cache_name = $page->getCacheIdForView($view.$type.serialize($data));
if ($output = $cache->get($cache_name))
{
return $output;
}
}
// Load the view
$view = View::factory($view, $config);
$output = $view->render();
// Convert to markdown automatically
if ($type == 'markdown' || $type == 'mdown' || $type == 'md')
{
$output = Pages_Markdown::to_html($output);
}
// Store into cache
if ($lifetime)
{
// Setup lifetime
if ($lifetime === TRUE)
{
$lifetime = $page->cache_lifetime;
}
else
{
$lifetime = (int) $lifetime;
}
// Store the cache
$cache->set($cache_name, $output, NULL, $lifetime);
}
return $output;
}
/**
* Returns compressed xml or html
*
* @param string input
* @return string compressed version
*/
public static function compress($input)
{
$input = str_replace(array("\r\n", "\r", "\n", "\t"), '', $input);
$input = preg_replace(array('/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s'), array('>', '<', '\\1'), $input);
return $input;
}
public static function indent($input)
{
$xml = new DOMDocument;
$xml->preserveWhiteSpace = FALSE;
$xml->formatOutput = TRUE;
$xml->loadXML($input);
$output = substr($xml->saveXML(), 22); // Strip the <?xml> at the beginning
$output = str_replace('<![CDATA[', '//<![CDATA[', $output);
return str_replace(']]>', '//]]>', $output);
}
/**
* Returns compressed css
*
* @param string buffer
* @return string compressed version
*/
public static function compressCSS($buffer)
{
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
return $buffer;
}
/**
* Returns packed js
*
* @param string script to pack
* @return string packed version
*/
public static function packJS($script)
{
$packer = new Pages_JavaScriptPacker($script);
return $packer->pack();
}
/**
* Returns minified js
*
* @param string script to minify
* @return string minified version
*/
public static function minifyJS($script)
{
return JSMin::minify($script);
}
public static function ext($url)
{
if (Kohana::config('pages.cache_externals') === TRUE)
{
self::$url_pre_counter++;
if (self::$url_pre_counter % 2 === 0)
{
self::$url_pre_counter = 0;
self::$url_pre++;
}
return str_replace('ext', self::$url_pre.'.ext', Kohana::config($url));
}
else
{
return Kohana::config($url);
}
}
private function fileCombine($type, $file)
{
$exists = 'cache_'.$type.'_exists';
$cache = 'cache_'.$type;
$key = 'cache_'.$type.'_key';
$path = $this->ext_path.Kohana::config('pages.'.$type.'_dir');
$container = 'cache_container_'.$type;
if ($this->$exists === FALSE)
{
// If we haven't attempted loading the css cache, try to get it
$cur_cache = $this->$cache;
if ($cur_cache['data'] === '')
{
$this->$cache = $this->getCache($type, $this->$key);
}
$cur_cache = $this->$cache;
if ($cur_cache['data'] === null)
{
$output = FALSE;
// Open actual file to load it into our container
// Use cURL incase it's an external file
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $file);
$output = curl_exec($ch);
curl_close($ch);
if ($output !== FALSE)
{
$this->$container = $this->$container."\n".$output;
}
}
else
{
$this->$container = $this->$cache;
}
}
}
private function formatHTML($output, $format = FALSE)
{
$format = (($format) ? $format : $this->format_output);
switch($format)
{
case 'compress':
$output = self::compress($output);
break;
case 'indent':
$output = self::indent($output);
break;
}
return $output;
}
private function cacheExists($type, $key)
{
return (bool) file_exists($this->ext_path.Kohana::config('pages.'.$type.'_dir').$key.'.'.$type);
}
private function getCache($type, $key)
{
$data = FALSE;
if (file_exists($this->ext_path.Kohana::config('pages.'.$type.'_dir').$key.'.'.$type))
{
$data = file_get_contents($this->ext_path.Kohana::config('pages.'.$type.'_dir').$key.'.'.$type);
}
if ($data !== FALSE)
{
return array('data' => $data, 'file' => $key.'.'.$type);
}
return array('data' => null, 'file' => $key.'.'.$type);
}
private function removeExpiredCache($type)
{
$type_path = $type.'_path';
$version = Kohana::config('pages.version');
if (is_dir($this->$type_path))
{
if ($dir = opendir($this->$type_path))
{
while (($file = readdir($dir)) !== FALSE)
{
// Look for the version number in the filename
preg_match('/^_pages_(\d+)_(?:.*)/', $file, $matches);
if (isset($matches[1]) && is_numeric($matches[1]) && ((int) $version !== (int) $matches[1]))
{
unlink($this->$type_path.$file);
}
}
closedir($dir);
}
}
}
private function setCache($type, $key, $data)
{
$filename = $key.'.'.$type;
// When building the new combined files, if it's CSS and they
// want to roundrobin the subdomain for asynchronous downloads
if ($type === 'css' && Kohana::config('pages.subdomain_roundrobin') === TRUE)
{
$found = 0;
$count = 1;
$prefix = Kohana::config('pages.subdomain_roundrobin_prefix');
do
{
// Setup new url
$ext_url = str_replace('http://', 'http://'.$prefix.sprintf('%02d', $count).'.', $this->ext_url);
$data = preg_replace('/url\((?!http)(.+)\)/', 'url('.$ext_url.'$1)', $data, 2, $found);
++$count;
} while ($found > 1);
}
if (Kohana::config('pages.format_output') === 'compress')
{
switch (TRUE)
{
case ($type === 'js'):
$data = self::minifyJS($data);
break;
case ($type === 'css'):
$data = self::compressCSS($data);
break;
}
}
$put = (bool) file_put_contents($this->ext_path.Kohana::config('pages.'.$type.'_dir').$filename, $data);
return array('put' => $put, 'filename' => $filename);
}
}