Minor fix
[pmwiki-versioned-assets.git] / versioned-assets.php
blob7206bb1bcbb4bf9453f56e6ba888cb7d1161006d
1 <?php
2 /** \versioned_assets.php
3 * \Copyright 2017-2021 Said Achmiz
4 * \Licensed under the MIT License
5 * \brief Adds versions (modification timestamps) to attachment URLs, so that browser
6 * caches invalidate properly when attachments are updated.
7 */
8 $RecipeInfo['VersionedAssets']['Version'] = '2021-12-12';
10 global $LinkFunctions;
11 $LinkFunctions['Attach:'] = 'LinkUploadVersioned';
13 SDV($VersionedAssetsReattachFileExtension, true);
15 function LinkUploadVersioned($pagename, $imap, $path, $alt, $txt, $fmt=NULL) {
16 global $FmtV, $UploadFileFmt, $LinkUploadCreateFmt,
17 $UploadUrlFmt, $UploadPrefixFmt, $EnableDirectDownload;
18 if (preg_match('!^(.*)/([^/]+)$!', $path, $match)) {
19 $pagename = MakePageName($pagename, $match[1]);
20 $path = $match[2];
22 $upname = MakeUploadName($pagename, $path);
23 $encname = rawurlencode($upname);
24 $filepath = FmtPageName("$UploadFileFmt/$upname", $pagename);
25 $FmtV['$LinkUpload'] =
26 FmtPageName("\$PageUrl?action=upload&amp;upname=$encname", $pagename);
27 $FmtV['$LinkText'] = $txt;
28 if (!file_exists($filepath))
29 return FmtPageName($LinkUploadCreateFmt, $pagename);
30 $path = PUE(FmtPageName(IsEnabled($EnableDirectDownload, 1)
31 ? "$UploadUrlFmt$UploadPrefixFmt/$encname"
32 : "{\$PageUrl}?action=download&amp;upname=$encname",
33 $pagename));
35 ## Append the modification time to the URL as a GET parameter; this should be ignored
36 ## by the web server, but is seen as part of the unique URL of the remote resource by
37 ## the browser; when it changes (because the attachment has been modified), the
38 ## browser will see that it doesn’t have a cached version of the resource under the
39 ## new URL, and will retrieve the updated version.
40 $versioned_path = $path . "?v=" . filemtime($filepath);
42 global $VersionedAssetsReattachFileExtension;
43 if ($VersionedAssetsReattachFileExtension == true) {
44 ## Re-attach the file extension, so that LinkIcons and such things work properly.
45 preg_match('/\.[^\.]+$/', $path, $matches);
46 $versioned_path .= $matches[0];
49 return LinkIMap($pagename, $imap, $versioned_path, $alt, $txt, $fmt);