xref: /dokuwiki/lib/exe/fetch.php (revision 4005b0809260fbd36cb8652c7d726a5ee417c6f6)
1<?php
2/**
3 * DokuWiki media passthrough file
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8
9if(!defined('DOKU_INC')) define('DOKU_INC', dirname(__FILE__).'/../../');
10define('DOKU_DISABLE_GZIP_OUTPUT', 1);
11require_once(DOKU_INC.'inc/init.php');
12session_write_close(); //close session
13
14// BEGIN main (if not testing)
15if(!defined('SIMPLE_TEST')) {
16    $mimetypes = getMimeTypes();
17
18    //get input
19    $MEDIA  = stripctl(getID('media', false)); // no cleaning except control chars - maybe external
20    $CACHE  = calc_cache($INPUT->str('cache'));
21    $WIDTH  = $INPUT->int('w');
22    $HEIGHT = $INPUT->int('h');
23    $REV    = & $INPUT->ref('rev');
24    //sanitize revision
25    $REV = preg_replace('/[^0-9]/', '', $REV);
26
27    list($EXT, $MIME, $DL) = mimetype($MEDIA, false);
28    if($EXT === false) {
29        $EXT  = 'unknown';
30        $MIME = 'application/octet-stream';
31        $DL   = true;
32    }
33
34    // check for permissions, preconditions and cache external files
35    list($STATUS, $STATUSMESSAGE) = checkFileStatus($MEDIA, $FILE, $REV);
36
37    // prepare data for plugin events
38    $data = array(
39        'media'         => $MEDIA,
40        'file'          => $FILE,
41        'orig'          => $FILE,
42        'mime'          => $MIME,
43        'download'      => $DL,
44        'cache'         => $CACHE,
45        'ext'           => $EXT,
46        'width'         => $WIDTH,
47        'height'        => $HEIGHT,
48        'status'        => $STATUS,
49        'statusmessage' => $STATUSMESSAGE,
50    );
51
52    // handle the file status
53    $evt = new Doku_Event('FETCH_MEDIA_STATUS', $data);
54    if($evt->advise_before()) {
55        // redirects
56        if($data['status'] > 300 && $data['status'] <= 304) {
57            send_redirect($data['statusmessage']);
58        }
59        // send any non 200 status
60        if($data['status'] != 200) {
61            http_status($data['status'], $data['statusmessage']);
62        }
63        // die on errors
64        if($data['status'] > 203) {
65            print $data['statusmessage'];
66            exit;
67        }
68    }
69    $evt->advise_after();
70    unset($evt);
71
72    //handle image resizing/cropping
73    if((substr($MIME, 0, 5) == 'image') && $WIDTH) {
74        if($HEIGHT) {
75            $data['file'] = $FILE = media_crop_image($data['file'], $EXT, $WIDTH, $HEIGHT);
76        } else {
77            $data['file'] = $FILE = media_resize_image($data['file'], $EXT, $WIDTH, $HEIGHT);
78        }
79    }
80
81    // finally send the file to the client
82    $evt = new Doku_Event('MEDIA_SENDFILE', $data);
83    if($evt->advise_before()) {
84        sendFile($data['file'], $data['mime'], $data['download'], $data['cache']);
85    }
86    // Do something after the download finished.
87    $evt->advise_after();
88
89}// END DO main
90
91/* ------------------------------------------------------------------------ */
92
93/**
94 * Set headers and send the file to the client
95 *
96 * @author Andreas Gohr <andi@splitbrain.org>
97 * @author Ben Coburn <btcoburn@silicodon.net>
98 */
99function sendFile($file, $mime, $dl, $cache) {
100    global $conf;
101    $fmtime = @filemtime($file);
102    // send headers
103    header("Content-Type: $mime");
104    // smart http caching headers
105    if($cache == -1) {
106        // cache
107        // cachetime or one hour
108        header('Expires: '.gmdate("D, d M Y H:i:s", time() + max($conf['cachetime'], 3600)).' GMT');
109        header('Cache-Control: public, proxy-revalidate, no-transform, max-age='.max($conf['cachetime'], 3600));
110        header('Pragma: public');
111    } else if($cache > 0) {
112        // recache
113        // remaining cachetime + 10 seconds so the newly recached media is used
114        header('Expires: '.gmdate("D, d M Y H:i:s", $fmtime + $conf['cachetime'] + 10).' GMT');
115        header('Cache-Control: public, proxy-revalidate, no-transform, max-age='.max($fmtime - time() + $conf['cachetime'] + 10, 0));
116        header('Pragma: public');
117    } else if($cache == 0) {
118        // nocache
119        header('Cache-Control: must-revalidate, no-transform, post-check=0, pre-check=0');
120        header('Pragma: public');
121    }
122    //send important headers first, script stops here if '304 Not Modified' response
123    http_conditionalRequest($fmtime);
124
125    //download or display?
126    if($dl) {
127        header('Content-Disposition: attachment; filename="'.utf8_basename($file).'";');
128    } else {
129        header('Content-Disposition: inline; filename="'.utf8_basename($file).'";');
130    }
131
132    //use x-sendfile header to pass the delivery to compatible webservers
133    if(http_sendfile($file)) exit;
134
135    // send file contents
136    $fp = @fopen($file, "rb");
137    if($fp) {
138        http_rangeRequest($fp, filesize($file), $mime);
139    } else {
140        http_status(500);
141        print "Could not read $file - bad permissions?";
142    }
143}
144
145/**
146 * Check for media for preconditions and return correct status code
147 *
148 * READ: MEDIA, MIME, EXT, CACHE
149 * WRITE: MEDIA, FILE, array( STATUS, STATUSMESSAGE )
150 *
151 * @author Gerry Weissbach <gerry.w@gammaproduction.de>
152 * @param $media reference to the media id
153 * @param $file  reference to the file variable
154 * @returns array(STATUS, STATUSMESSAGE)
155 */
156function checkFileStatus(&$media, &$file, $rev = '') {
157    global $MIME, $EXT, $CACHE, $INPUT;
158
159    //media to local file
160    if(preg_match('#^(https?)://#i', $media)) {
161        //check hash
162        if(substr(md5(auth_cookiesalt().$media), 0, 6) !== $INPUT->str('hash')) {
163            return array(412, 'Precondition Failed');
164        }
165        //handle external images
166        if(strncmp($MIME, 'image/', 6) == 0) $file = media_get_from_URL($media, $EXT, $CACHE);
167        if(!$file) {
168            //download failed - redirect to original URL
169            return array(302, $media);
170        }
171    } else {
172        $media = cleanID($media);
173        if(empty($media)) {
174            return array(400, 'Bad request');
175        }
176
177        //check permissions (namespace only)
178        if(auth_quickaclcheck(getNS($media).':X') < AUTH_READ) {
179            return array(403, 'Forbidden');
180        }
181        $file = mediaFN($media, $rev);
182    }
183
184    //check file existance
185    if(!@file_exists($file)) {
186        return array(404, 'Not Found');
187    }
188
189    return array(200, null);
190}
191
192/**
193 * Returns the wanted cachetime in seconds
194 *
195 * Resolves named constants
196 *
197 * @author  Andreas Gohr <andi@splitbrain.org>
198 */
199function calc_cache($cache) {
200    global $conf;
201
202    if(strtolower($cache) == 'nocache') return 0; //never cache
203    if(strtolower($cache) == 'recache') return $conf['cachetime']; //use standard cache
204    return -1; //cache endless
205}
206
207//Setup VIM: ex: et ts=2 :
208