Skip to content

Commit

Permalink
Merge pull request #4214 from rldhont/etag-project-illustration
Browse files Browse the repository at this point in the history
Add ETAG header to project illustration
  • Loading branch information
rldhont authored Feb 20, 2024
2 parents d48a18d + 0b071b1 commit d36b652
Showing 1 changed file with 72 additions and 2 deletions.
74 changes: 72 additions & 2 deletions lizmap/modules/view/controllers/media.classic.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,53 @@

class mediaCtrl extends jController
{
/**
* Check if cache can be used because it is impossible
* to use cache on other request type that GET or HEAD.
*
* @return bool
*/
protected function canBeCached()
{
return in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD'));
}

/**
* @param jResponse $resp
* @param string $etag
*
* @return jResponse the response updated
*/
protected function setEtagCacheHeaders($resp, $etag)
{
if ($this->canBeCached()) {
$resp->addHttpHeader('ETag', $etag);
$resp->addHttpHeader('Cache-Control', 'no-cache');
}

return $resp;
}

protected function defaultIllustrationPath()
{
// default illustration
$themePath = jApp::wwwPath().'themes/'.jApp::config()->theme.'/';

return $themePath.'css/img/250x250_mappemonde.jpg';
}

protected function defaultIllustrationEtag()
{
if ($this->canBeCached()) {
$etag = 'default-illustration-';
$etag .= filemtime($this->defaultIllustrationPath());

return sha1($etag);
}

return '';
}

/**
* Returns error.
*
Expand Down Expand Up @@ -334,7 +381,24 @@ public function illustration()
}
$rep->mimeType = $mime;

// Etag header and cache control
$etag = '';
if ($this->canBeCached()) {
$etag = 'illustration';
$etag .= '-'.$lrep->getKey().'~'.$lproj->getKey();
$etag .= '-'.$type;
$etag .= '-'.filemtime($rep->fileName);
$etag = sha1($etag);
}

if ($etag !== '' && $rep->isValidCache(null, $etag)) {
return $rep;
}

$rep->setExpires('+1 days');
if ($etag !== '') {
$this->setEtagCacheHeaders($rep, $etag);
}

return $rep;
}
Expand All @@ -351,12 +415,18 @@ public function defaultIllustration()
$rep->doDownload = false;

// default illustration
$themePath = jApp::wwwPath().'themes/'.jApp::config()->theme.'/';
$rep->fileName = $themePath.'css/img/250x250_mappemonde.jpg';
$rep->fileName = $this->defaultIllustrationPath();
$rep->outputFileName = 'lizmap_mappemonde.jpg';
$rep->mimeType = 'image/jpeg';
$etag = $this->defaultIllustrationEtag();
if ($etag !== '' && $rep->isValidCache(null, $etag)) {
return $rep;
}

$rep->setExpires('+7 days');
if ($etag !== '') {
$this->setEtagCacheHeaders($rep, $etag);
}

return $rep;
}
Expand Down

0 comments on commit d36b652

Please sign in to comment.