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