-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathextension.driver.php
executable file
·850 lines (764 loc) · 27.2 KB
/
extension.driver.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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
<?php
class Extension_cachelite extends Extension
{
protected $_cacheLite = null;
protected $_lifetime = null;
protected $_url = null;
protected $_get = null;
private $_sections = array();
private $_entries = array();
private $_pagedata = array();
const CACHE_GROUP = 'cachelite';
public function __construct()
{
require_once('lib/class.cachelite.php');
$this->_lifetime = $this->getLifetime();
$this->_cacheLite = new Cache_Lite(array(
'cacheDir' => CACHE . '/',
'lifeTime' => $this->_lifetime
));
$this->updateFromGetValues();
}
/*-------------------------------------------------------------------------
Extension
-------------------------------------------------------------------------*/
public function uninstall()
{
// Remove preferences
Symphony::Configuration()->remove('cachelite');
Symphony::Configuration()->write();
// Remove file
if (@file_exists(MANIFEST . '/cachelite-excluded-pages')) {
@unlink(MANIFEST . '/cachelite-excluded-pages');
}
// Remove extension tables
$this->dropInvalidTable();
return $this->dropPageTable();
}
public function install()
{
// Create extension tables
$this->createPageTable();
$this->createInvalidTable();
if (!@file_exists(MANIFEST . '/cachelite-excluded-pages')) {
@touch(MANIFEST . '/cachelite-excluded-pages');
}
// Base configuration
Symphony::Configuration()->set('lifetime', '86400', 'cachelite');
Symphony::Configuration()->set('show-comments', 'no', 'cachelite');
Symphony::Configuration()->set('backend-delegates', 'no', 'cachelite');
return Symphony::Configuration()->write();
}
public function update($previousVersion = false)
{
if (version_compare($previousVersion, '2.0.0', '<')) {
$this->dropPageTable();
$this->createPageTable();
}
if (version_compare($previousVersion, '2.1.0', '<')) {
$this->createInvalidTable();
}
return true;
}
public function getSubscribedDelegates()
{
return array(
array(
'page' => '/frontend/',
'delegate' => 'FrontendPageResolved',
'callback' => 'interceptPage'
),
array(
'page' => '/frontend/',
'delegate' => 'FrontendOutputPreGenerate',
'callback' => 'parsePageData'
),
array(
'page' => '/frontend/',
'delegate' => 'FrontendOutputPostGenerate',
'callback' => 'writePageCache'
),
array(
'page' => '/frontend/',
'delegate' => 'FrontendPreRenderHeaders',
'callback' => 'preRenderHeaders'
),
array(
'page' => '/system/preferences/',
'delegate' => 'AddCustomPreferenceFieldsets',
'callback' => 'appendPreferences'
),
array(
'page' => '/system/preferences/success/',
'delegate' => 'AddCustomPreferenceFieldsets',
'callback' => 'appendPreferences'
),
array(
'page' => '/system/preferences/',
'delegate' => 'Save',
'callback' => 'savePreferences'
),
array(
'page' => '/publish/new/',
'delegate' => 'EntryPostCreate',
'callback' => 'entryCreate'
),
array(
'page' => '/publish/edit/',
'delegate' => 'EntryPreEdit',
'callback' => 'entryEdit'
),
array(
'page' => '/publish/',
'delegate' => 'EntryPreDelete',
'callback' => 'entryDelete'
),
array(
'page' => '/blueprints/sections/',
'delegate' => 'SectionPostEdit',
'callback' => 'sectionEdit'
),
array(
'page' => '/blueprints/events/new/',
'delegate' => 'AppendEventFilter',
'callback' => 'addFilterToEventEditor'
),
array(
'page' => '/blueprints/events/edit/',
'delegate' => 'AppendEventFilter',
'callback' => 'addFilterToEventEditor'
),
array(
'page' => '/blueprints/events/new/',
'delegate' => 'AppendEventFilterDocumentation',
'callback' => 'addFilterDocumentationToEvent'
),
array(
'page' => '/blueprints/events/edit/',
'delegate' => 'AppendEventFilterDocumentation',
'callback' => 'addFilterDocumentationToEvent'
),
array(
'page' => '/frontend/',
'delegate' => 'EventPreSaveFilter',
'callback' => 'processEventData'
),
array(
'page' => '/frontend/',
'delegate' => 'EventPostSaveFilter',
'callback' => 'processPostSaveData'
),
array(
'page' => '/backend/',
'delegate' => 'AppendPageAlert',
'callback' => 'appendPageAlert'
),
);
}
public function extensionCacheBypass()
{
$cachebypass = false;
/**
* Allows extensions to make this request
* bypass the cache.
*
* @delegate CacheliteBypass
* @since 2.0.0
* @param string $context
* '/frontend/'
* @param bool $bypass
* A flag to tell if the user is logged in and cache must be disabled
*/
Symphony::ExtensionManager()->notifyMembers('CacheliteBypass', '/frontend/', array(
'bypass' => &$cachebypass,
));
return $cachebypass;
}
public function preRenderHeaders(array $context)
{
if ($this->extensionCacheBypass()) {
Frontend::Page()->addHeaderToPage('X-Cache-Status', 'BYPASS');
}
}
/*-------------------------------------------------------------------------
Preferences
-------------------------------------------------------------------------*/
public function appendPreferences($context)
{
// Add new fieldset
$group = new XMLElement('fieldset');
$group->setAttribute('class', 'settings');
$group->appendChild(new XMLElement('legend', 'CacheLite'));
// Add Site Reference field
$label = Widget::Label(__('Cache Period'));
$label->appendChild(Widget::Input('settings[cachelite][lifetime]', General::sanitize($this->getLifetime())));
$group->appendChild($label);
$group->appendChild(new XMLElement('p', __('Length of cache period in seconds.'), array('class' => 'help')));
$label = Widget::Label(__('Excluded URLs'));
$label->appendChild(Widget::Textarea('cachelite[excluded-pages]', 10, 50, $this->getExcludedPages()));
$group->appendChild($label);
$group->appendChild(new XMLElement('p', __('Add a line for each URL you want to be excluded from the cache. Add a <code>*</code> to the end of the URL for wildcard matches.'), array('class' => 'help')));
$label = Widget::Label();
$label->setAttribute('for', 'cachelite-show-comments');
$hidden = Widget::Input('settings[cachelite][show-comments]', 'no', 'hidden');
$input = Widget::Input('settings[cachelite][show-comments]', 'yes', 'checkbox');
$input->setAttribute('id', 'cachelite-show-comments');
if (Symphony::Configuration()->get('show-comments', 'cachelite') == 'yes') {
$input->setAttribute('checked', 'checked');
}
$label->setValue(__('%s Show comments in page source?', array($hidden->generate() . $input->generate())));
$group->appendChild($label);
$label = Widget::Label();
$label->setAttribute('for', 'cachelite-backend-delegates');
$hidden = Widget::Input('settings[cachelite][backend-delegates]', 'no', 'hidden');
$input = Widget::Input('settings[cachelite][backend-delegates]', 'yes', 'checkbox');
$input->setAttribute('id', 'cachelite-backend-delegates');
if (Symphony::Configuration()->get('backend-delegates', 'cachelite') == 'yes') {
$input->setAttribute('checked', 'checked');
}
$label->setValue( __('%s Expire cache when entries are created/updated through the backend?', array($hidden->generate() . $input->generate())));
$group->appendChild($label);
$context['wrapper']->appendChild($group);
}
public function savePreferences($context)
{
$this->saveExcludedPages(stripslashes($_POST['cachelite']['excluded-pages']));
}
/*-------------------------------------------------------------------------
Events
-------------------------------------------------------------------------*/
public function addFilterToEventEditor($context)
{
// adds filters to Filters select box on Event editor page
$context['options'][] = array('cachelite-entry', @in_array('cachelite-entry', $context['selected']) , 'CacheLite: ' . __('Expire cache for pages showing this entry'));
$context['options'][] = array('cachelite-section', @in_array('cachelite-section', $context['selected']) , 'CacheLite: ' . __('Expire cache for pages showing content from this section'));
$context['options'][] = array('cachelite-url', @in_array('cachelite-url', $context['selected']) , 'CacheLite: ' . __('Expire cache for the passed URL'));
}
public function processEventData($context)
{
// flush the cache based on entry IDs
if (in_array('cachelite-entry', $context['event']->eParamFILTERS) && isset($_POST['cachelite']['flush-entry'])) {
if (is_array($_POST['id'])) {
foreach($_POST['id'] as $id) {
$this->clearPagesByStrategy($id, 'entry');
}
} elseif (isset($_POST['id'])) {
$this->clearPagesByStrategy($_POST['id'], 'entry');
}
}
// flush cache based on the Section ID of the section this Event accesses
if (in_array('cachelite-section', $context['event']->eParamFILTERS) && isset($_POST['cachelite']['flush-section'])) {
$this->clearPagesByStrategy($context['event']->getSource(), 'section');
}
}
public function processPostSaveData($context)
{
// flush the cache based on explicit value
if (in_array('cachelite-url', $context['event']->eParamFILTERS)) {
$flush = (empty($_POST['cachelite']['flush-url']))
? $this->_url
: $this->computeHash(General::sanitize($_POST['cachelite']['flush-url']));
$this->_cacheLite->remove($flush, self::CACHE_GROUP, true);
}
}
public function addFilterDocumentationToEvent($context)
{
if (in_array('cachelite-entry', $context['selected']) || in_array('cachelite-section', $context['selected'])) $context['documentation'][] = new XMLElement('h3', __('CacheLite: Expiring the cache'));
if (in_array('cachelite-entry', $context['selected']))
{
$context['documentation'][] = new XMLElement('h4', __('Expire cache for pages showing this entry'));
$context['documentation'][] = new XMLElement('p', __('When editing existing entries (one or many, supports the <em>Allow Multiple</em> option) any pages showing this entry will be flushed. Add the following in your form to trigger this filter:'));
$code = '<input type="hidden" name="cachelite[flush-entry]" value="yes"/>';
$context['documentation'][] = contentBlueprintsEvents::processDocumentationCode($code);
}
if (in_array('cachelite-section', $context['selected']))
{
$context['documentation'][] = new XMLElement('h4', __('Expire cache for pages showing content from this section'));
$context['documentation'][] = new XMLElement('p', __('This will flush the cache of pages using any entries from this event’s section. Since you may want to only run it when creating new entries, this will only run if you pass a specific field in your HTML:'));
$code = '<input type="hidden" name="cachelite[flush-section]" value="yes"/>';
$context['documentation'][] = contentBlueprintsEvents::processDocumentationCode($code);
}
if (in_array('cachelite-url', $context['selected']))
{
$context['documentation'][] = new XMLElement('h4', __('Expire cache for the passed URL'));
$context['documentation'][] = new XMLElement('p', __('This will expire the cache of the URL at the value you pass it. For example'));
$code = '<input type="hidden" name="cachelite[flush-url]" value="/article/123/"/>';
$context['documentation'][] = contentBlueprintsEvents::processDocumentationCode($code);
$context['documentation'][] = new XMLElement('p', __('Will flush the cache for <code>http://domain.tld/article/123/</code>. If no value is passed it will flush the cache of the current page (i.e., the value of <code>action=""</code> in you form):'));
$code = '<input type="hidden" name="cachelite[flush-url]"/>';
$context['documentation'][] = contentBlueprintsEvents::processDocumentationCode($code);
}
return;
}
/*-------------------------------------------------------------------------
Caching
-------------------------------------------------------------------------*/
protected function computeEtag()
{
$lastModified = $this->_cacheLite->lastModified();
return md5($lastModified . $this->_url);
}
public function writeCacheHeaders($cacheHit = 'MISS')
{
// Kill session
@session_unset();
@session_destroy();
header_remove('Set-Cookie');
// Cache headers
$lastModified = $this->_cacheLite->lastModified();
$etag = $this->computeEtag();
header("Cache-Control: public, max-age=" . $this->_lifetime . ", must-revalidate");
header("Expires: " . gmdate("D, d M Y H:i:s", $lastModified + $this->_lifetime) . " GMT");
header("Last-Modified: " . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
header("ETag: \"$etag\"");
header("Access-Control-Allow-Origin: " . URL);
header("X-Frame-Options: SAMEORIGIN");
header("X-Cache-Status: $cacheHit");
header_remove('Pragma');
// Add custom content type
if (!isset($this->_pagedata['type']) || !is_array($this->_pagedata['type']) || empty($this->_pagedata['type'])) {
header('Content-Type: text/html; charset=utf-8');
} else if (@in_array('XML', $this->_pagedata['type']) || @in_array('xml', $this->_pagedata['type'])) {
header('Content-Type: text/xml; charset=utf-8');
} else {
foreach($this->_pagedata['type'] as $type) {
$content_type = Symphony::Configuration()->get(strtolower($type), 'content-type-mappings');
if (!is_null($content_type)){
header("Content-Type: $content_type;");
}
if ($type{0} == '.') {
$FileName = $this->_pagedata['handle'];
header("Content-Disposition: attachment; filename={$FileName}{$type}");
}
}
}
}
public function interceptPage($context)
{
$this->_pagedata = $context['page_data'];
if ($this->inExcludedPages() || !$this->isGetRequest() || $this->isErrorTemplate()) {
return;
}
$logged_in = Symphony::isLoggedIn();
if ($logged_in && array_key_exists('flush', $this->_get) && $this->_get['flush'] == 'site') {
unset($this->_get['flush']);
$this->_cacheLite->clean(self::CACHE_GROUP);
$this->updateFromGetValues();
} else if ($logged_in && array_key_exists('flush', $this->_get)) {
unset($this->_get['flush']);
$this->updateFromGetValues();
$this->_cacheLite->remove($this->_url, self::CACHE_GROUP, true);
} else if (!$logged_in && !$this->extensionCacheBypass()) {
$this->updateFromGetValues();
$output = $this->_cacheLite->get($this->_url, self::CACHE_GROUP);
// no cache entry found
if (!$output) {
return;
}
// Try to return 304
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) || isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
$modified = $this->_cacheLite->lastModified();
$modified_gmt = gmdate('r', $modified);
if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] == $modified_gmt ||
str_replace('"', NULL, stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])) == $this->computeEtag()){
Page::renderStatusCode(Page::HTTP_NOT_MODIFIED);
exit();
}
}
// Add comment
if ($this->getCommentPref() === 'yes') {
$output .= "<!-- Cache hit: ". $this->_cacheLite->_fileName ." -->";
}
// Write headers
$this->writeCacheHeaders('HIT');
// Send response
print $output;
exit();
}
}
public function writePageCache(&$output)
{
if ($this->inExcludedPages() || !$this->isGetRequest() || $this->isErrorTemplate()) {
return;
}
$logged_in = Symphony::isLoggedIn();
if (!$logged_in && !$this->extensionCacheBypass()) {
$render = $output['output'];
// rebuild entry/section reference list for this page
$this->deletePageReferences($this->_url);
$this->savePageReferences($this->_url, $this->_sections, $this->_entries);
// Actually write the cache
$this->_cacheLite->save($render, $this->_url, self::CACHE_GROUP);
// Add comment
if ($this->getCommentPref() === 'yes') {
$render .= "<!-- Cache miss: ". $this->_cacheLite->_fileName ." -->";
}
// Write headers
$this->writeCacheHeaders();
// Send response
echo $render;
exit();
}
}
// Parse any Event or Section elements from the page XML
public function parsePageData($context)
{
if ($this->inExcludedPages() || !$this->isGetRequest() || $this->isErrorTemplate()) {
return;
}
$logged_in = Symphony::isLoggedIn();
if ($logged_in || $this->extensionCacheBypass()) {
return;
}
try {
$xml = @DomDocument::loadXML($context['xml']->generate());
if (!$xml) {
return;
}
$xpath = new DOMXPath($xml);
$sections_xpath = $xpath->query('//section[@id]');
$sections = array();
foreach($sections_xpath as $section) {
$sections[] = $section->getAttribute('id');
}
$entries_xpath = $xpath->query('//entry[@id] | //item[@id]');
$entries = array();
foreach($entries_xpath as $entry) {
$entries[] = $entry->getAttribute('id');
}
$this->_sections = array_unique($sections);
$this->_entries = array_unique($entries);
} catch (Exception $ex) {
Symphony::Log()->pushExceptionToLog($ex);
}
}
public function entryCreate($context)
{
if (Symphony::Configuration()->get('backend-delegates', 'cachelite') == 'no') return;
// flush by Section ID
if (isset($context['section'])) {
$this->clearPagesByStrategy($context['section']->get('id'), 'section');
}
}
public function entryEdit($context)
{
if (Symphony::Configuration()->get('backend-delegates', 'cachelite') == 'no') return;
// flush by Entry ID
if (isset($context['entry'])) {
$this->clearPagesByStrategy($context['entry']->get('id'), 'entry');
}
}
public function entryDelete($context)
{
if (Symphony::Configuration()->get('backend-delegates', 'cachelite') == 'no') return;
$ids = !is_array($context['entry_id']) ? array($context['entry_id']) : $context['entry_id'];
// flush by Entry ID
foreach ($ids as $id) {
$this->clearPagesByStrategy($id, 'entry');
}
}
public function sectionEdit($context)
{
// flush by Section ID
if (isset($context['section_id'])) {
$this->clearPagesByStrategy($context['section_id'], 'section');
}
}
public function appendPageAlert($context)
{
$callback = Administration::instance()->getPageCallback();
$context = $callback['context'];
$alert = null;
if (!empty($context['section_handle'])) {
$section = SectionManager::fetchIDFromHandle($context['section_handle']);
if ($this->isInvalidByContent($section, 'section')) {
$alert = __('This section is scheduled to be removed from the cache. Website will reflect the new state soon.');
}
}
if (!empty($context['entry_id'])) {
if ($this->isInvalidByContent($context['entry_id'], 'entry')) {
$alert = __('This entry is scheduled to be removed from the cache. Website will reflect the new state soon.');
}
}
if ($alert) {
Administration::instance()->Page->pageAlert($alert, Alert::NOTICE);
}
}
public function clearPagesByStrategy($id, $type)
{
$strategy = Symphony::Configuration()->get('clean-strategy', 'cachelite');
if ($strategy === 'cron') {
return $this->saveInvalid($id, $type);
}
return $this->clearPagesByReference($id, $type);
}
public function clearPagesByReference($id, $type)
{
// get a list of pages matching this entry/section ID
$pages = $this->getPagesByContent($id, $type);
// flush the cache for each
foreach($pages as $page) {
$this->removeByUrl($page['page']);
}
$this->optimizePageTable();
}
public function removeByUrl($url)
{
$this->_cacheLite->remove($url, self::CACHE_GROUP, true);
$this->deletePageReferences($url);
}
/*-------------------------------------------------------------------------
Helpers
-------------------------------------------------------------------------*/
private function getLifetime()
{
$default_lifetime = 86400;
$val = General::intval(Symphony::Configuration()->get('lifetime', 'cachelite'));
return $val > -1 ? $val : $default_lifetime;
}
private function getCommentPref()
{
return Symphony::Configuration()->get('show-comments', 'cachelite');
}
private function getExcludedPages()
{
return @file_get_contents(MANIFEST . '/cachelite-excluded-pages');
}
private function saveExcludedPages($string)
{
return @file_put_contents(MANIFEST . '/cachelite-excluded-pages', $string);
}
private function inExcludedPages()
{
$segments = explode('/', $this->_get['symphony-page']);
$domain = explode('/', DOMAIN);
foreach($segments as $key => $segment) {
if (in_array($segment, $domain) || empty($segment)) {
unset($segments[$key]);
}
}
$path = implode('/', $segments);
$rules = file(MANIFEST . '/cachelite-excluded-pages', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$rules = array_filter(array_map('trim', $rules));
foreach ($rules as $r) {
if (static::doesRuleExcludesPath($path, $r)) {
return true;
}
}
return false;
}
public static function doesRuleExcludesPath($path, $r)
{
// Make sure we're matching `url/blah` not `/url/blah`
$r = trim($r, '/');
// comment
if (substr($r, 0, 1) === '#') {
return false;
}
// full wildcard
else if ($r === '*') {
return true;
}
// perfect match
else if (strcasecmp($r, $path) == 0) {
return true;
}
// wildcards
else if (!!$path && strlen($path) >= strlen($r)) {
$ruleStartsWithStar = substr($r, 0, 1) === '*';
$ruleEndsWithStar = substr($r, -1) === '*';
// wildcard before and after (*test*)
if ($ruleStartsWithStar && $ruleEndsWithStar) {
// Remove both char
$r = substr($r, 1, strlen($r) - 2);
// Lookup
$rPos = strpos($path, $r);
// Rule is found in path
if ($rPos !== false && $rPos > 0 && $rPos < strlen($path) - strlen($r)) {
return true;
}
}
// wildcard before (*test)
else if ($ruleStartsWithStar) {
// Remove first char
$r = substr($r, 1);
// path must end with rule
if (strpos($path, $r) > 0) {
return true;
}
}
// wildcard after (test*)
else if ($ruleEndsWithStar) {
// Remove last char
$r = substr($r, 0, strlen($r) - 1);
// path must start with rule
if (strpos($path, $r) === 0) {
return true;
}
}
}
return false;
}
/*-------------------------------------------------------------------------
Database Helpers
-------------------------------------------------------------------------*/
public function getPagesByContent($id, $type)
{
try {
$col = $type == 'entry' ? 'entry_id' : 'section_id';
$id = General::intval($id);
return Symphony::Database()->fetch(
"SELECT DISTINCT `page` FROM `tbl_cachelite_references`
WHERE `$col` = $id"
);
} catch (Exception $ex) {
Symphony::Log()->pushExceptionToLog($ex);
}
return array();
}
public function isInvalidByContent($id, $type)
{
try {
$col = $type == 'entry' ? 'entry_id' : 'section_id';
$id = General::intval($id);
return !empty(Symphony::Database()->fetch(
"SELECT DISTINCT `$col` FROM `tbl_cachelite_invalid`
WHERE `$col` = $id"
));
} catch (Exception $ex) {
Symphony::Log()->pushExceptionToLog($ex);
}
return false;
}
public function deletePageReferences($url)
{
try {
$url = Symphony::Database()->cleanValue($url);
return Symphony::Database()->query(
"DELETE FROM `tbl_cachelite_references` WHERE `page` = '$url'"
);
} catch (Exception $ex) {
Symphony::Log()->pushExceptionToLog($ex);
}
return false;
}
protected function saveReferences($reference, $url, $ids)
{
try {
$now = DateTimeObj::get('Y-m-d H:i:s');
$values = array();
foreach ($ids as $id) {
$id = General::intval($id);
$values[] = "('$url', $id, '$now')";
}
$values = implode(',', $values);
return Symphony::Database()->query(
"INSERT INTO `tbl_cachelite_references` (`page`, `$reference`, `timestamp`)
VALUES $values
ON DUPLICATE KEY UPDATE `timestamp` = '$now'"
);
} catch (Exception $ex) {
Symphony::Log()->pushExceptionToLog($ex);
}
return false;
}
protected function savePageReferences($url, array $sections, array $entries)
{
$url = Symphony::Database()->cleanValue($url);
// Create sections rows
$sections = $this->saveReferences('section_id', $url, $sections);
// Create entries rows
$entries = $this->saveReferences('entry_id', $url, $entries);
return $sections && $entries;
}
protected function saveInvalid($id, $type)
{
$col = $type == 'entry' ? 'entry_id' : 'section_id';
try {
$id = General::intval(Symphony::Database()->cleanValue($id));
return Symphony::Database()->query(
"INSERT INTO `tbl_cachelite_invalid` (`$col`)
VALUES ($id)
ON DUPLICATE KEY UPDATE `$col` = `$col`"
);
} catch (Exception $ex) {
Symphony::Log()->pushExceptionToLog($ex);
throw $ex;
}
return false;
}
protected function createPageTable()
{
// Create extension table
return Symphony::Database()->query("
CREATE TABLE `tbl_cachelite_references` (
`page` char(128) NOT NULL,
`section_id` int(11) NOT NULL default 0,
`entry_id` int(11) NOT NULL default 0,
`timestamp` datetime NOT NULL /*!50600 default CURRENT_TIMESTAMP */,
PRIMARY KEY (`page`, `section_id`, `entry_id`),
KEY `page` (`page`),
KEY `section_page` (`page`, `section_id`),
KEY `entry_page` (`page`, `entry_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
");
}
protected function createInvalidTable()
{
// Create extension table
return Symphony::Database()->query("
CREATE TABLE `tbl_cachelite_invalid` (
`section_id` int(11) NOT NULL default 0,
`entry_id` int(11) NOT NULL default 0,
PRIMARY KEY (`section_id`, `entry_id`),
KEY `section_id` (`section_id`),
KEY `entry_id` (`entry_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
");
}
public function dropPageTable()
{
return Symphony::Database()->query("DROP TABLE IF EXISTS `tbl_cachelite_references`");
}
public function dropInvalidTable()
{
return Symphony::Database()->query("DROP TABLE IF EXISTS `tbl_cachelite_invalid`");
}
public function optimizePageTable()
{
return Symphony::Database()->query("OPTIMIZE TABLE `tbl_cachelite_references`");
}
public function optimizeInvalidTable()
{
return Symphony::Database()->query("OPTIMIZE TABLE `tbl_cachelite_invalid`");
}
/*-------------------------------------------------------------------------
Utilities
-------------------------------------------------------------------------*/
private function computeHash($url)
{
return hash('sha512', (__SECURE__ ? 'https:' : '').serialize($url));
}
private function updateFromGetValues()
{
// Cache sorted $_GET;
$this->_get = array_merge(array(), $_GET);
ksort($this->_get);
// hash it to make sure it wont overflow
$this->_url = $this->computeHash($this->_get);
}
private function isGetRequest()
{
return $_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD';
}
private function isErrorTemplate()
{
$types = $this->_pagedata['type'];
if (empty($types) || !is_array($types)) {
return $this->_errorTemplate;
}
// Check for custom http status
$this->_errorTemplate = @in_array('404', $types) || @in_array('403', $types);
return $this->_errorTemplate;
}
}