Revert "MDL-39832 Files: Revert MDL-39688 commit, 6ce0c9ce42fa7849e67d7611a628ece51c3...
[moodle.git] / lib / xsendfilelib.php
CommitLineData
d5dd0540
PS
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * X-Sendfile support
19 *
20 * @package core_files
21 * @copyright 2012 Petr Skoda {@link http://skodak.org}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25//NOTE: do not verify MOODLE_INTERNAL here, this is used from themes too
26
27/**
28 * Serve file using X-Sendfile header, this needs special server module
29 * or configuration. Please make sure that all headers are already sent
30 * and the all access control checks passed.
31 *
32 * @param string $filepath
33 * @return bool success
34 */
35function xsendfile($filepath) {
36 global $CFG;
37
38 if (empty($CFG->xsendfile)) {
39 return false;
40 }
41
42 if (!file_exists($filepath)) {
43 return false;
44 }
45
46 if (headers_sent()) {
47 return false;
48 }
49
f7d26a05
PS
50 $filepath = realpath($filepath);
51
52 $aliased = false;
53 if (!empty($CFG->xsendfilealiases) and is_array($CFG->xsendfilealiases)) {
54 foreach ($CFG->xsendfilealiases as $alias=>$dir) {
e61f888d
PS
55 $dir = realpath($dir);
56 if ($dir === false) {
57 continue;
58 }
59 if (substr($dir, -1) !== DIRECTORY_SEPARATOR) {
60 // add trailing dir separator
61 $dir .= DIRECTORY_SEPARATOR;
62 }
f7d26a05
PS
63 if (strpos($filepath, $dir) === 0) {
64 $filepath = $alias.substr($filepath, strlen($dir));
65 $aliased = true;
66 break;
67 }
68 }
69 }
70
c5338156
DP
71 // Remove Etag because is is not strictly defined for byteserving,
72 // is it tag of this range or whole file?
73 if (!empty($_SERVER['HTTP_RANGE'])) {
74 header_remove('Etag');
75 }
76
d5dd0540
PS
77 if ($CFG->xsendfile === 'X-LIGHTTPD-send-file') {
78 // http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file says 1.4 it does not support byteserving
79 header('Accept-Ranges: none');
80
81 } else if ($CFG->xsendfile === 'X-Accel-Redirect') {
82 // http://wiki.nginx.org/XSendfile
f7d26a05
PS
83 // Nginx requires paths relative to aliases, you need to specify them in config.php
84 if (!$aliased) {
d5dd0540
PS
85 return false;
86 }
d5dd0540
PS
87 }
88
89 header("$CFG->xsendfile: $filepath");
90
91 return true;
92}