Codestyle + check trustedproxies
[dokuwiki.git] / inc / fetch.functions.php
blobd7acd243e0ac2f05d7c243cecbf46ef796e3d2a3
1 <?php
3 use dokuwiki\HTTP\Headers;
4 use dokuwiki\Utf8\PhpString;
6 /**
7 * Functions used by lib/exe/fetch.php
8 * (not included by other parts of dokuwiki)
9 */
11 /**
12 * Set headers and send the file to the client
14 * The $cache parameter influences how long files may be kept in caches, the $public parameter
15 * influences if this caching may happen in public proxis or in the browser cache only FS#2734
17 * This function will abort the current script when a 304 is sent or file sending is handled
18 * through x-sendfile
20 * @param string $file local file to send
21 * @param string $mime mime type of the file
22 * @param bool $dl set to true to force a browser download
23 * @param int $cache remaining cache time in seconds (-1 for $conf['cache'], 0 for no-cache)
24 * @param bool $public is this a public ressource or a private one?
25 * @param string $orig original file to send - the file name will be used for the Content-Disposition
26 * @param array $csp The ContentSecurityPolicy to send
27 * @author Andreas Gohr <andi@splitbrain.org>
28 * @author Ben Coburn <btcoburn@silicodon.net>
29 * @author Gerry Weissbach <dokuwiki@gammaproduction.de>
32 function sendFile($file, $mime, $dl, $cache, $public = false, $orig = null, $csp = [])
34 global $conf;
35 // send mime headers
36 header("Content-Type: $mime");
38 // send security policy if given
39 if (!empty($csp)) Headers::contentSecurityPolicy($csp);
41 // calculate cache times
42 if ($cache == -1) {
43 $maxage = max($conf['cachetime'], 3600); // cachetime or one hour
44 $expires = time() + $maxage;
45 } elseif ($cache > 0) {
46 $maxage = $cache; // given time
47 $expires = time() + $maxage;
48 } else { // $cache == 0
49 $maxage = 0;
50 $expires = 0; // 1970-01-01
53 // smart http caching headers
54 if ($maxage) {
55 if ($public) {
56 // cache publically
57 header('Expires: ' . gmdate("D, d M Y H:i:s", $expires) . ' GMT');
58 header('Cache-Control: public, proxy-revalidate, no-transform, max-age=' . $maxage);
59 } else {
60 // cache in browser
61 header('Expires: ' . gmdate("D, d M Y H:i:s", $expires) . ' GMT');
62 header('Cache-Control: private, no-transform, max-age=' . $maxage);
64 } else {
65 // no cache at all
66 header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
67 header('Cache-Control: no-cache, no-transform');
70 //send important headers first, script stops here if '304 Not Modified' response
71 $fmtime = @filemtime($file);
72 http_conditionalRequest($fmtime);
74 // Use the current $file if is $orig is not set.
75 if ($orig == null) {
76 $orig = $file;
79 //download or display?
80 if ($dl) {
81 header('Content-Disposition: attachment;' . rfc2231_encode(
82 'filename',
83 PhpString::basename($orig)
84 ) . ';');
85 } else {
86 header('Content-Disposition: inline;' . rfc2231_encode(
87 'filename',
88 PhpString::basename($orig)
89 ) . ';');
92 //use x-sendfile header to pass the delivery to compatible webservers
93 http_sendfile($file);
95 // send file contents
96 $fp = @fopen($file, "rb");
97 if ($fp) {
98 http_rangeRequest($fp, filesize($file), $mime);
99 } else {
100 http_status(500);
101 echo "Could not read $file - bad permissions?";
106 * Try an rfc2231 compatible encoding. This ensures correct
107 * interpretation of filenames outside of the ASCII set.
108 * This seems to be needed for file names with e.g. umlauts that
109 * would otherwise decode wrongly in IE.
111 * There is no additional checking, just the encoding and setting the key=value for usage in headers
113 * @author Gerry Weissbach <gerry.w@gammaproduction.de>
114 * @param string $name name of the field to be set in the header() call
115 * @param string $value value of the field to be set in the header() call
116 * @param string $charset used charset for the encoding of value
117 * @param string $lang language used.
118 * @return string in the format " name=value" for values WITHOUT special characters
119 * @return string in the format " name*=charset'lang'value" for values WITH special characters
121 function rfc2231_encode($name, $value, $charset = 'utf-8', $lang = 'en')
123 $internal = preg_replace_callback(
124 '/[\x00-\x20*\'%()<>@,;:\\\\"\/[\]?=\x80-\xFF]/',
125 static fn($match) => rawurlencode($match[0]),
126 $value
128 if ($value != $internal) {
129 return ' ' . $name . '*=' . $charset . "'" . $lang . "'" . $internal;
130 } else {
131 return ' ' . $name . '="' . $value . '"';
136 * Check for media for preconditions and return correct status code
138 * READ: MEDIA, MIME, EXT, CACHE
139 * WRITE: MEDIA, FILE, array( STATUS, STATUSMESSAGE )
141 * @author Gerry Weissbach <gerry.w@gammaproduction.de>
143 * @param string $media reference to the media id
144 * @param string $file reference to the file variable
145 * @param string $rev
146 * @param int $width
147 * @param int $height
148 * @return array as array(STATUS, STATUSMESSAGE)
150 function checkFileStatus(&$media, &$file, $rev = '', $width = 0, $height = 0)
152 global $MIME, $EXT, $CACHE, $INPUT;
154 //media to local file
155 if (media_isexternal($media)) {
156 //check token for external image and additional for resized and cached images
157 if (media_get_token($media, $width, $height) !== $INPUT->str('tok')) {
158 return [412, 'Precondition Failed'];
160 //handle external images
161 if (str_starts_with($MIME, 'image/')) $file = media_get_from_URL($media, $EXT, $CACHE);
162 if (!$file) {
163 //download failed - redirect to original URL
164 return [302, $media];
166 } else {
167 $media = cleanID($media);
168 if (empty($media)) {
169 return [400, 'Bad request'];
171 // check token for resized images
172 if (($width || $height) && media_get_token($media, $width, $height) !== $INPUT->str('tok')) {
173 return [412, 'Precondition Failed'];
176 //check permissions (namespace only)
177 if (auth_quickaclcheck(getNS($media) . ':X') < AUTH_READ) {
178 return [403, 'Forbidden'];
180 $file = mediaFN($media, $rev);
183 //check file existance
184 if (!file_exists($file)) {
185 return [404, 'Not Found'];
188 return [200, null];
192 * Returns the wanted cachetime in seconds
194 * Resolves named constants
196 * @author Andreas Gohr <andi@splitbrain.org>
198 * @param string $cache
199 * @return int cachetime in seconds
201 function calc_cache($cache)
203 global $conf;
205 if (strtolower($cache) == 'nocache') return 0; //never cache
206 if (strtolower($cache) == 'recache') return $conf['cachetime']; //use standard cache
207 return -1; //cache endless