xref: /dokuwiki/inc/fetch.functions.php (revision d868eb89f182718a31113373a6272670bd7f8012)
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', PhpString::basename($orig)) . ';'
81        );
82    } else {
83        header('Content-Disposition: inline;' . rfc2231_encode(
84                'filename', PhpString::basename($orig)) . ';'
85        );
86    }
87
88    //use x-sendfile header to pass the delivery to compatible webservers
89    http_sendfile($file);
90
91    // send file contents
92    $fp = @fopen($file, "rb");
93    if($fp) {
94        http_rangeRequest($fp, filesize($file), $mime);
95    } else {
96        http_status(500);
97        print "Could not read $file - bad permissions?";
98    }
99}
100
101/**
102 * Try an rfc2231 compatible encoding. This ensures correct
103 * interpretation of filenames outside of the ASCII set.
104 * This seems to be needed for file names with e.g. umlauts that
105 * would otherwise decode wrongly in IE.
106 *
107 * There is no additional checking, just the encoding and setting the key=value for usage in headers
108 *
109 * @author Gerry Weissbach <gerry.w@gammaproduction.de>
110 * @param string $name      name of the field to be set in the header() call
111 * @param string $value     value of the field to be set in the header() call
112 * @param string $charset   used charset for the encoding of value
113 * @param string $lang      language used.
114 * @return string           in the format " name=value" for values WITHOUT special characters
115 * @return string           in the format " name*=charset'lang'value" for values WITH special characters
116 */
117function rfc2231_encode($name, $value, $charset = 'utf-8', $lang = 'en')
118{
119    $internal = preg_replace_callback(
120        '/[\x00-\x20*\'%()<>@,;:\\\\"\/[\]?=\x80-\xFF]/',
121        static fn($match) => rawurlencode($match[0]),
122        $value
123    );
124    if ( $value != $internal ) {
125        return ' '.$name.'*='.$charset."'".$lang."'".$internal;
126    } else {
127        return ' '.$name.'="'.$value.'"';
128    }
129}
130
131/**
132 * Check for media for preconditions and return correct status code
133 *
134 * READ: MEDIA, MIME, EXT, CACHE
135 * WRITE: MEDIA, FILE, array( STATUS, STATUSMESSAGE )
136 *
137 * @author Gerry Weissbach <gerry.w@gammaproduction.de>
138 *
139 * @param string $media  reference to the media id
140 * @param string $file   reference to the file variable
141 * @param string $rev
142 * @param int    $width
143 * @param int    $height
144 * @return array as array(STATUS, STATUSMESSAGE)
145 */
146function checkFileStatus(&$media, &$file, $rev = '', $width = 0, $height = 0)
147{
148    global $MIME, $EXT, $CACHE, $INPUT;
149
150    //media to local file
151    if(media_isexternal($media)) {
152        //check token for external image and additional for resized and cached images
153        if(media_get_token($media, $width, $height) !== $INPUT->str('tok')) {
154            return [412, 'Precondition Failed'];
155        }
156        //handle external images
157        if(strncmp($MIME, 'image/', 6) == 0) $file = media_get_from_URL($media, $EXT, $CACHE);
158        if(!$file) {
159            //download failed - redirect to original URL
160            return [302, $media];
161        }
162    } else {
163        $media = cleanID($media);
164        if(empty($media)) {
165            return [400, 'Bad request'];
166        }
167        // check token for resized images
168        if (($width || $height) && media_get_token($media, $width, $height) !== $INPUT->str('tok')) {
169            return [412, 'Precondition Failed'];
170        }
171
172        //check permissions (namespace only)
173        if(auth_quickaclcheck(getNS($media).':X') < AUTH_READ) {
174            return [403, 'Forbidden'];
175        }
176        $file = mediaFN($media, $rev);
177    }
178
179    //check file existance
180    if(!file_exists($file)) {
181        return [404, 'Not Found'];
182    }
183
184    return [200, null];
185}
186
187/**
188 * Returns the wanted cachetime in seconds
189 *
190 * Resolves named constants
191 *
192 * @author  Andreas Gohr <andi@splitbrain.org>
193 *
194 * @param string $cache
195 * @return int cachetime in seconds
196 */
197function calc_cache($cache)
198{
199    global $conf;
200
201    if(strtolower($cache) == 'nocache') return 0; //never cache
202    if(strtolower($cache) == 'recache') return $conf['cachetime']; //use standard cache
203    return -1; //cache endless
204}
205