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