forked from FriendsOfSymfony1/symfony1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsfViewCacheManager.class.php
977 lines (842 loc) · 32.4 KB
/
sfViewCacheManager.class.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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Cache class to cache the HTML results for actions and templates.
*
* This class uses a sfCache instance implementation to store cache.
*
* To disable all caching, you can set the [sf_cache] constant to false.
*
* @author Fabien Potencier <[email protected]>
*
* @version SVN: $Id$
*/
class sfViewCacheManager
{
public $options = array();
protected $cache;
protected $cacheConfig = array();
protected $context;
protected $dispatcher;
protected $controller;
protected $routing;
protected $request;
protected $loaded = array();
/**
* Class constructor.
*
* @see initialize()
*
* @param mixed $context
* @param mixed $options
*/
public function __construct($context, sfCache $cache, $options = array())
{
$this->initialize($context, $cache, $options);
}
/**
* Initializes the cache manager.
*
* @param sfContext $context Current application context
* @param sfCache $cache An sfCache instance
* @param mixed $options
*/
public function initialize($context, sfCache $cache, $options = array())
{
$this->context = $context;
$this->dispatcher = $context->getEventDispatcher();
$this->controller = $context->getController();
$this->request = $context->getRequest();
$this->options = array_merge(array(
'cache_key_use_vary_headers' => true,
'cache_key_use_host_name' => true,
), $options);
if (sfConfig::get('sf_web_debug')) {
$this->dispatcher->connect('view.cache.filter_content', array($this, 'decorateContentWithDebug'));
}
// empty configuration
$this->cacheConfig = array();
// cache instance
$this->cache = $cache;
// routing instance
$this->routing = $context->getRouting();
}
/**
* Retrieves the current cache context.
*
* @return sfContext The sfContext instance
*/
public function getContext()
{
return $this->context;
}
/**
* Retrieves the current cache object.
*
* @return sfCache The current cache object
*/
public function getCache()
{
return $this->cache;
}
/**
* Generates a unique cache key for an internal URI.
* This cache key can be used by any of the cache engines as a unique identifier to a cached resource.
*
* Basically, the cache key generated for the following internal URI:
* module/action?key1=value1&key2=value2
* Looks like:
* /localhost/all/module/action/key1/value1/key2/value2
*
* @param string $internalUri The internal unified resource identifier
* Accepts rules formatted like 'module/action?key1=value1&key2=value2'
* Does not accept rules starting with a route name, except for '@sf_cache_partial'
* @param string $hostName The host name
* Optional - defaults to the current host name bu default
* @param string $vary The vary headers, separated by |, or "all" for all vary headers
* Defaults to 'all'
* @param string $contextualPrefix The contextual prefix for contextual partials.
* Defaults to 'currentModule/currentAction/currentPAram1/currentvalue1'
* Used only by the sfViewCacheManager::remove() method
*
* @return string The cache key
* If some of the parameters contained wildcards (* or **), the generated key will also have wildcards
*/
public function generateCacheKey($internalUri, $hostName = '', $vary = '', $contextualPrefix = '')
{
if ($callable = sfConfig::get('sf_cache_namespace_callable')) {
if (!is_callable($callable)) {
throw new sfException(sprintf('"%s" cannot be called as a function.', var_export($callable, true)));
}
return call_user_func($callable, $internalUri, $hostName, $vary, $contextualPrefix, $this);
}
if (0 === strpos($internalUri, '@') && false === strpos($internalUri, '@sf_cache_partial')) {
throw new sfException('A cache key cannot be generated for an internal URI using the @rule syntax');
}
$cacheKey = '';
if ($this->isContextual($internalUri)) {
// Contextual partial
if (!$contextualPrefix) {
list($route_name, $params) = $this->controller->convertUrlStringToParameters($this->routing->getCurrentInternalUri());
// if there is no module/action, it means that we have a 404 and the user is trying to cache it
if (!isset($params['module']) || !isset($params['action'])) {
$params['module'] = sfConfig::get('sf_error_404_module');
$params['action'] = sfConfig::get('sf_error_404_action');
}
$cacheKey = $this->convertParametersToKey($params);
} else {
$cacheKey = $contextualPrefix;
}
list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
$cacheKey .= sprintf('/%s/%s/%s', $params['module'], $params['action'], isset($params['sf_cache_key']) ? $params['sf_cache_key'] : '');
} else {
// Regular action or non-contextual partial
list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
if ('sf_cache_partial' == $route_name) {
$cacheKey = 'sf_cache_partial/';
}
$cacheKey .= $this->convertParametersToKey($params);
}
// add vary headers
if ($varyPart = $this->getCacheKeyVaryHeaderPart($internalUri, $vary)) {
$cacheKey = '/'.$varyPart.'/'.ltrim($cacheKey, '/');
}
// add hostname
if ($hostNamePart = $this->getCacheKeyHostNamePart($hostName)) {
$cacheKey = '/'.$hostNamePart.'/'.ltrim($cacheKey, '/');
}
// normalize to a leading slash
if (0 !== strpos($cacheKey, '/')) {
$cacheKey = '/'.$cacheKey;
}
// distinguish multiple slashes
while (false !== strpos($cacheKey, '//')) {
$cacheKey = str_replace('//', '/'.substr(sha1($cacheKey), 0, 7).'/', $cacheKey);
}
// prevent directory traversal
return strtr($cacheKey, array(
'/.' => '/_.',
'/_' => '/__',
'\\.' => '\\_.',
'\\_' => '\\__',
));
}
/**
* Adds a cache to the manager.
*
* @param string $moduleName Module name
* @param string $actionName Action name
* @param array $options Options for the cache
*/
public function addCache($moduleName, $actionName, $options = array())
{
// normalize vary headers
if (isset($options['vary'])) {
foreach ($options['vary'] as $key => $name) {
$options['vary'][$key] = str_replace('_', '-', strtolower($name));
}
}
$options['lifeTime'] = isset($options['lifeTime']) ? $options['lifeTime'] : 0;
if (!isset($this->cacheConfig[$moduleName])) {
$this->cacheConfig[$moduleName] = array();
}
$this->cacheConfig[$moduleName][$actionName] = array(
'withLayout' => isset($options['withLayout']) ? $options['withLayout'] : false,
'lifeTime' => $options['lifeTime'],
'clientLifeTime' => isset($options['clientLifeTime']) ? $options['clientLifeTime'] : $options['lifeTime'],
'contextual' => isset($options['contextual']) ? $options['contextual'] : false,
'vary' => isset($options['vary']) ? $options['vary'] : array(),
);
}
/**
* Registers configuration options for the cache.
*
* @param string $moduleName Module name
*/
public function registerConfiguration($moduleName)
{
if (!isset($this->loaded[$moduleName])) {
require $this->context->getConfigCache()->checkConfig('modules/'.$moduleName.'/config/cache.yml');
$this->loaded[$moduleName] = true;
}
}
/**
* Retrieves the layout from the cache option list.
*
* @param string $internalUri Internal uniform resource identifier
*
* @return bool true, if have layout otherwise false
*/
public function withLayout($internalUri)
{
return $this->getCacheConfig($internalUri, 'withLayout', false);
}
/**
* Retrieves lifetime from the cache option list.
*
* @param string $internalUri Internal uniform resource identifier
*
* @return int LifeTime
*/
public function getLifeTime($internalUri)
{
return $this->getCacheConfig($internalUri, 'lifeTime', 0);
}
/**
* Retrieves client lifetime from the cache option list.
*
* @param string $internalUri Internal uniform resource identifier
*
* @return int Client lifetime
*/
public function getClientLifeTime($internalUri)
{
return $this->getCacheConfig($internalUri, 'clientLifeTime', 0);
}
/**
* Retrieves contextual option from the cache option list.
*
* @param string $internalUri Internal uniform resource identifier
*
* @return bool true, if is contextual otherwise false
*/
public function isContextual($internalUri)
{
return $this->getCacheConfig($internalUri, 'contextual', false);
}
/**
* Retrieves vary option from the cache option list.
*
* @param string $internalUri Internal uniform resource identifier
*
* @return array Vary options for the cache
*/
public function getVary($internalUri)
{
return $this->getCacheConfig($internalUri, 'vary', array());
}
/**
* Returns true if the current content is cacheable.
*
* Possible break in backward compatibility: If the sf_lazy_cache_key
* setting is turned on in settings.yml, this method is not used when
* initially checking a partial's cacheability.
*
* @see sfPartialView, isActionCacheable()
*
* @param string $internalUri Internal uniform resource identifier
*
* @return bool true, if the content is cacheable otherwise false
*/
public function isCacheable($internalUri)
{
if ($this->request instanceof sfWebRequest && !$this->request->isMethod(sfRequest::GET)) {
return false;
}
list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
if (!isset($params['module'])) {
return false;
}
$this->registerConfiguration($params['module']);
if (isset($this->cacheConfig[$params['module']][$params['action']])) {
return $this->cacheConfig[$params['module']][$params['action']]['lifeTime'] > 0;
}
if (isset($this->cacheConfig[$params['module']]['DEFAULT'])) {
return $this->cacheConfig[$params['module']]['DEFAULT']['lifeTime'] > 0;
}
return false;
}
/**
* Returns true if the action is cacheable.
*
* @param string $moduleName A module name
* @param string $actionName An action or partial template name
*
* @return bool True if the action is cacheable
*
* @see isCacheable()
*/
public function isActionCacheable($moduleName, $actionName)
{
if ($this->request instanceof sfWebRequest && !$this->request->isMethod(sfRequest::GET)) {
return false;
}
$this->registerConfiguration($moduleName);
if (isset($this->cacheConfig[$moduleName][$actionName])) {
return $this->cacheConfig[$moduleName][$actionName]['lifeTime'] > 0;
}
if (isset($this->cacheConfig[$moduleName]['DEFAULT'])) {
return $this->cacheConfig[$moduleName]['DEFAULT']['lifeTime'] > 0;
}
return false;
}
/**
* Retrieves content in the cache.
*
* @param string $internalUri Internal uniform resource identifier
*
* @return string The content in the cache
*/
public function get($internalUri)
{
// no cache or no cache set for this action
if (!$this->isCacheable($internalUri) || $this->ignore()) {
return null;
}
$retval = $this->cache->get($this->generateCacheKey($internalUri));
if (sfConfig::get('sf_logging_enabled')) {
$this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Cache for "%s" %s', $internalUri, null !== $retval ? 'exists' : 'does not exist'))));
}
return $retval;
}
/**
* Returns true if there is a cache.
*
* @param string $internalUri Internal uniform resource identifier
*
* @return bool true, if there is a cache otherwise false
*/
public function has($internalUri)
{
if (!$this->isCacheable($internalUri) || $this->ignore()) {
return null;
}
return $this->cache->has($this->generateCacheKey($internalUri));
}
/**
* Sets the cache content.
*
* @param string $data Data to put in the cache
* @param string $internalUri Internal uniform resource identifier
*
* @return bool true, if the data get set successfully otherwise false
*/
public function set($data, $internalUri)
{
if (!$this->isCacheable($internalUri)) {
return false;
}
try {
$ret = $this->cache->set($this->generateCacheKey($internalUri), $data, $this->getLifeTime($internalUri));
} catch (Exception $e) {
return false;
}
if (sfConfig::get('sf_logging_enabled')) {
$this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Save cache for "%s"', $internalUri))));
}
return true;
}
/**
* Removes the content in the cache.
*
* @param string $internalUri Internal uniform resource identifier
* @param string $hostName The host name
* @param string $vary The vary headers, separated by |, or "all" for all vary headers
* @param string $contextualPrefix The removal prefix for contextual partials. Defaults to '**' (all actions, all params)
*
* @return bool true, if the remove happened, false otherwise
*/
public function remove($internalUri, $hostName = '', $vary = '', $contextualPrefix = '**')
{
if (sfConfig::get('sf_logging_enabled')) {
$this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Remove cache for "%s"', $internalUri))));
}
$cacheKey = $this->generateCacheKey($internalUri, $hostName, $vary, $contextualPrefix);
if (strpos($cacheKey, '*')) {
return $this->cache->removePattern($cacheKey);
}
if ($this->cache->has($cacheKey)) {
return $this->cache->remove($cacheKey);
}
}
/**
* Retrieves the last modified time.
*
* @param string $internalUri Internal uniform resource identifier
*
* @return int The last modified datetime
*/
public function getLastModified($internalUri)
{
if (!$this->isCacheable($internalUri)) {
return 0;
}
return $this->cache->getLastModified($this->generateCacheKey($internalUri));
}
/**
* Retrieves the timeout.
*
* @param string $internalUri Internal uniform resource identifier
*
* @return int The timeout datetime
*/
public function getTimeout($internalUri)
{
if (!$this->isCacheable($internalUri)) {
return 0;
}
return $this->cache->getTimeout($this->generateCacheKey($internalUri));
}
/**
* Starts the fragment cache.
*
* @param string $name Unique fragment name
* @param string $lifeTime Life time for the cache
* @param string $clientLifeTime Client life time for the cache
* @param array $vary Vary options for the cache
*
* @return bool true, if success otherwise false
*/
public function start($name, $lifeTime, $clientLifeTime = null, $vary = array())
{
$internalUri = $this->routing->getCurrentInternalUri();
if (!$clientLifeTime) {
$clientLifeTime = $lifeTime;
}
// add cache config to cache manager
list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
$this->addCache($params['module'], $params['action'], array('withLayout' => false, 'lifeTime' => $lifeTime, 'clientLifeTime' => $clientLifeTime, 'vary' => $vary));
// get data from cache if available
$data = $this->get($internalUri.(strpos($internalUri, '?') ? '&' : '?').'_sf_cache_key='.$name);
if (null !== $data) {
return $data;
}
ob_start();
ob_implicit_flush(0);
return null;
}
/**
* Stops the fragment cache.
*
* @param string $name Unique fragment name
*
* @return bool true, if success otherwise false
*/
public function stop($name)
{
$data = ob_get_clean();
// save content to cache
$internalUri = $this->routing->getCurrentInternalUri();
try {
$this->set($data, $internalUri.(strpos($internalUri, '?') ? '&' : '?').'_sf_cache_key='.$name);
} catch (Exception $e) {
}
return $data;
}
/**
* Computes the cache key based on the passed parameters.
*
* @param array $parameters An array of parameters
*/
public function computeCacheKey(array $parameters)
{
if (isset($parameters['sf_cache_key'])) {
return $parameters['sf_cache_key'];
}
if (sfConfig::get('sf_logging_enabled')) {
$this->dispatcher->notify(new sfEvent($this, 'application.log', array('Generate cache key')));
}
ksort($parameters);
return md5(serialize($parameters));
}
/**
* Checks that the supplied parameters include a cache key.
*
* If no 'sf_cache_key' parameter is present one is added to the array as
* it is passed by reference.
*
* @param array $parameters An array of parameters
*
* @return string The cache key
*/
public function checkCacheKey(array &$parameters)
{
$parameters['sf_cache_key'] = $this->computeCacheKey($parameters);
return $parameters['sf_cache_key'];
}
/**
* Computes a partial internal URI.
*
* @param string $module The module name
* @param string $action The action name
* @param string $cacheKey The cache key
*
* @return string The internal URI
*/
public function getPartialUri($module, $action, $cacheKey)
{
return sprintf('@sf_cache_partial?module=%s&action=%s&sf_cache_key=%s', $module, $action, $cacheKey);
}
/**
* Returns whether a partial template is in the cache.
*
* @param string $module The module name
* @param string $action The action name
* @param string $cacheKey The cache key
*
* @return bool true if a partial is in the cache, false otherwise
*/
public function hasPartialCache($module, $action, $cacheKey)
{
return $this->has($this->getPartialUri($module, $action, $cacheKey));
}
/**
* Gets a partial template from the cache.
*
* @param string $module The module name
* @param string $action The action name
* @param string $cacheKey The cache key
*
* @return string The cache content
*/
public function getPartialCache($module, $action, $cacheKey)
{
$uri = $this->getPartialUri($module, $action, $cacheKey);
if (!$this->isCacheable($uri)) {
return null;
}
// retrieve content from cache
$cache = $this->get($uri);
if (null === $cache) {
return null;
}
$cache = unserialize($cache);
$content = $cache['content'];
$this->context->getResponse()->merge($cache['response']);
if (sfConfig::get('sf_web_debug')) {
$content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => false)), $content)->getReturnValue();
}
return $content;
}
/**
* Sets an action template in the cache.
*
* @param string $module The module name
* @param string $action The action name
* @param string $cacheKey The cache key
* @param string $content The content to cache
*
* @return string The cached content
*/
public function setPartialCache($module, $action, $cacheKey, $content)
{
$uri = $this->getPartialUri($module, $action, $cacheKey);
if (!$this->isCacheable($uri)) {
return $content;
}
$saved = $this->set(serialize(array('content' => $content, 'response' => $this->context->getResponse())), $uri);
if ($saved && sfConfig::get('sf_web_debug')) {
$content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => true)), $content)->getReturnValue();
}
return $content;
}
/**
* Returns whether an action template is in the cache.
*
* @param string $uri The internal URI
*
* @return bool true if an action is in the cache, false otherwise
*/
public function hasActionCache($uri)
{
return $this->has($uri) && !$this->withLayout($uri);
}
/**
* Gets an action template from the cache.
*
* @param string $uri The internal URI
*
* @return array An array composed of the cached content and the view attribute holder
*/
public function getActionCache($uri)
{
if (!$this->isCacheable($uri) || $this->withLayout($uri)) {
return null;
}
// retrieve content from cache
$cache = $this->get($uri);
if (null === $cache) {
return null;
}
$cache = unserialize($cache);
$content = $cache['content'];
$cache['response']->setEventDispatcher($this->dispatcher);
$this->context->getResponse()->copyProperties($cache['response']);
if (sfConfig::get('sf_web_debug')) {
$content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => false)), $content)->getReturnValue();
}
return array($content, $cache['decoratorTemplate']);
}
/**
* Sets an action template in the cache.
*
* @param string $uri The internal URI
* @param string $content The content to cache
* @param string $decoratorTemplate The view attribute holder to cache
*
* @return string The cached content
*/
public function setActionCache($uri, $content, $decoratorTemplate)
{
if (!$this->isCacheable($uri) || $this->withLayout($uri)) {
return $content;
}
$saved = $this->set(serialize(array('content' => $content, 'decoratorTemplate' => $decoratorTemplate, 'response' => $this->context->getResponse())), $uri);
if ($saved && sfConfig::get('sf_web_debug')) {
$content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => true)), $content)->getReturnValue();
}
return $content;
}
/**
* Sets a page in the cache.
*
* @param string $uri The internal URI
*/
public function setPageCache($uri)
{
if (sfView::RENDER_CLIENT != $this->controller->getRenderMode()) {
return;
}
// save content in cache
$saved = $this->set(serialize($this->context->getResponse()), $uri);
if ($saved && sfConfig::get('sf_web_debug')) {
$content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => true)), $this->context->getResponse()->getContent())->getReturnValue();
$this->context->getResponse()->setContent($content);
}
}
/**
* Gets a page from the cache.
*
* @param string $uri The internal URI
*
* @return string The cached page
*/
public function getPageCache($uri)
{
$retval = $this->get($uri);
if (null === $retval) {
return false;
}
$cachedResponse = unserialize($retval);
$cachedResponse->setEventDispatcher($this->dispatcher);
if (sfView::RENDER_VAR == $this->controller->getRenderMode()) {
$this->controller->getActionStack()->getLastEntry()->setPresentation($cachedResponse->getContent());
$this->context->getResponse()->setContent('');
} else {
$this->context->setResponse($cachedResponse);
if (sfConfig::get('sf_web_debug')) {
$content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => false)), $this->context->getResponse()->getContent())->getReturnValue();
$this->context->getResponse()->setContent($content);
}
}
return true;
}
/**
* Returns the current request's cache key.
*
* This cache key is calculated based on the routing factory's current URI
* and any GET parameters from the current request factory.
*
* @return string The cache key for the current request
*/
public function getCurrentCacheKey()
{
$cacheKey = $this->routing->getCurrentInternalUri();
if ($getParameters = $this->request->getGetParameters()) {
$cacheKey .= false === strpos((string) $cacheKey, '?') ? '?' : '&';
$cacheKey .= http_build_query($getParameters, '', '&');
}
return $cacheKey;
}
/**
* Listens to the 'view.cache.filter_content' event to decorate a chunk of HTML with cache information.
*
* @param sfEvent $event A sfEvent instance
* @param string $content The HTML content
*
* @return string The decorated HTML string
*/
public function decorateContentWithDebug(sfEvent $event, $content)
{
// don't decorate if not html or if content is null
if (!$content || false === strpos($event['response']->getContentType(), 'html')) {
return $content;
}
$this->context->getConfiguration()->loadHelpers(array('Helper', 'Url', 'Asset', 'Tag'));
$sf_cache_key = $this->generateCacheKey($event['uri']);
$bgColor = $event['new'] ? '#9ff' : '#ff9';
$lastModified = $this->cache->getLastModified($sf_cache_key);
$cacheKey = $this->cache->getOption('prefix').$sf_cache_key;
$id = md5($event['uri']);
return '
<div id="main_'.$id.'" class="sfWebDebugActionCache" style="border: 1px solid #f00">
<div id="sub_main_'.$id.'" class="sfWebDebugCache" style="background-color: '.$bgColor.'; border-right: 1px solid #f00; border-bottom: 1px solid #f00;">
<div style="height: 16px; padding: 2px"><a href="#" onclick="sfWebDebugToggle(\'sub_main_info_'.$id.'\'); return false;"><strong>cache information</strong></a> <a href="#" onclick="sfWebDebugToggle(\'sub_main_'.$id.'\'); document.getElementById(\'main_'.$id.'\').style.border = \'none\'; return false;">'.image_tag(sfConfig::get('sf_web_debug_web_dir').'/images/close.png', array('alt' => 'close')).'</a> </div>
<div style="padding: 2px; display: none" id="sub_main_info_'.$id.'">
[uri] '.htmlspecialchars($event['uri'], ENT_QUOTES, sfConfig::get('sf_charset')).'<br />
[key for cache] '.htmlspecialchars($cacheKey, ENT_QUOTES, sfConfig::get('sf_charset')).'<br />
[life time] '.$this->getLifeTime($event['uri']).' seconds<br />
[last modified] '.(time() - $lastModified).' seconds<br />
<br />
</div>
</div><div>
'.$content.'
</div></div>
';
}
/**
* Gets the vary header part of view cache key.
*
* @param string $vary
* @param mixed $internalUri
*
* @return string
*/
protected function getCacheKeyVaryHeaderPart($internalUri, $vary = '')
{
if (!$this->options['cache_key_use_vary_headers']) {
return '';
}
// prefix with vary headers
if (!$vary) {
$varyHeaders = $this->getVary($internalUri);
if (!$varyHeaders) {
return 'all';
}
sort($varyHeaders);
$request = $this->context->getRequest();
$varys = array();
foreach ($varyHeaders as $header) {
$varys[] = $header.'-'.preg_replace('/\W+/', '_', $request->getHttpHeader($header));
}
$vary = implode('-', $varys);
}
return $vary;
}
/**
* Gets the hostname part of view cache key.
*
* @param string $hostName
*/
protected function getCacheKeyHostNamePart($hostName = '')
{
if (!$this->options['cache_key_use_host_name']) {
return '';
}
if (!$hostName) {
$hostName = $this->context->getRequest()->getHost();
}
$hostName = preg_replace('/[^a-z0-9\*]/i', '_', $hostName);
$hostName = preg_replace('/_+/', '_', $hostName);
return strtolower($hostName);
}
/**
* Transforms an associative array of parameters from an URI into a unique key.
*
* @param array $params Associative array of parameters from the URI (including, at least, module and action)
*
* @return string Unique key
*/
protected function convertParametersToKey($params)
{
if (!isset($params['module']) || !isset($params['action'])) {
throw new sfException('A cache key must contain both a module and an action parameter');
}
$module = $params['module'];
unset($params['module']);
$action = $params['action'];
unset($params['action']);
ksort($params);
$cacheKey = sprintf('%s/%s', $module, $action);
foreach ($params as $key => $value) {
$cacheKey .= sprintf('/%s/%s', $key, $value);
}
return $cacheKey;
}
/**
* Gets a config option from the cache.
*
* @param string $internalUri Internal uniform resource identifier
* @param string $key Option name
* @param string $defaultValue Default value of the option
*
* @return mixed Value of the option
*/
protected function getCacheConfig($internalUri, $key, $defaultValue = null)
{
list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
if (!isset($params['module'])) {
return $defaultValue;
}
$this->registerConfiguration($params['module']);
$value = $defaultValue;
if (isset($this->cacheConfig[$params['module']][$params['action']][$key])) {
$value = $this->cacheConfig[$params['module']][$params['action']][$key];
} elseif (isset($this->cacheConfig[$params['module']]['DEFAULT'][$key])) {
$value = $this->cacheConfig[$params['module']]['DEFAULT'][$key];
}
return $value;
}
/**
* Ignores the cache functionality.
*
* @return bool true, if the cache is ignore otherwise false
*/
protected function ignore()
{
// ignore cache parameter? (only available in debug mode)
if (sfConfig::get('sf_debug') && $this->context->getRequest()->getAttribute('sf_ignore_cache')) {
if (sfConfig::get('sf_logging_enabled')) {
$this->dispatcher->notify(new sfEvent($this, 'application.log', array('Discard cache')));
}
return true;
}
return false;
}
}