/
modStaticResource.php
281 lines (248 loc) · 9.83 KB
/
modStaticResource.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
<?php
namespace MODX\Revolution;
use xPDO\xPDO;
/**
* A derivative of modResource that stores content on the filesystem.
* @package MODX\Revolution
*/
class modStaticResource extends modResource
{
/**
* @var string Path of the file containing the source content, relative to the media source or full absolute path
*/
protected $_sourceFile= '';
/**
* @var integer Size of the source file content in bytes.
*/
protected $_sourceFileSize= 0;
/**
* Overrides modResource::__construct to set the class key for this Resource type
* @param xPDO $xpdo A reference to the xPDO|modX instance
*/
public function __construct(xPDO $xpdo)
{
parent:: __construct($xpdo);
$this->set('class_key', __CLASS__);
$canCreate = (bool)$this->xpdo->hasPermission('new_static_resource');
$this->allowListingInClassKeyDropdown = $canCreate;
$this->showInContextMenu = $canCreate;
}
/**
* Get the absolute path to the static source file represented by this instance.
*
* @param array $options An array of options.
* @return string The absolute path to the static source file.
*/
public function getSourceFile(array $options = [])
{
$filename = (string)parent::getContent($options);
// Support placeholders/snippets in the filename by parsing it through the modParser
$array = array();
if ($this->xpdo->getParser() && $this->xpdo->parser->collectElementTags($filename, $array)) {
$this->xpdo->parser->processElementTags('', $filename);
}
// Sanitize to avoid ../ style path traversal
$filename = preg_replace(array("/\.*[\/|\\\]/i", "/[\/|\\\]+/i"), array('/', '/'), $filename);
// If absolute paths are allowed (disabled by default for security reasons), and a file exists at the provided path, use it
$allowAbsolute = (bool)$this->xpdo->getOption('resource_static_allow_absolute', null, false);
if ($allowAbsolute && file_exists($filename)) {
$this->_sourceFile = $filename;
$this->_sourceFileSize = filesize($filename);
}
// If absolute paths are **not** allowed or an absolute file was not found, prefix the resource_static_path setting
else {
$sourcePath = $this->xpdo->getOption('resource_static_path', $options, '{assets_path}', true);
if ($this->xpdo->getParser() && $this->xpdo->parser->collectElementTags($sourcePath, $array)) {
$this->xpdo->parser->processElementTags('', $sourcePath);
}
// If an absolute path was provided that matches the required path, strip the absolute portion as it's added again below
if (strpos($filename, $sourcePath) === 0) {
$filename = substr($filename, strlen($sourcePath));
}
// When selecting a file using the media browser, that will provide a relative url like "assets/static/foo.pdf";
// To avoid that from 404ing when the resource_static_path is set to {assets_path}, we need to check
// if the provided $filename starts with the _relative_ url, matching against the base path.
// This doesn't work for directories outside of the base path (ie a moved core), but that's too complex
// to resolve without full media source support on static resources.
$relativeSourcePath = strpos($sourcePath, MODX_BASE_PATH) === 0 ? substr($sourcePath, strlen(MODX_BASE_PATH)) : false;
// if $filename starts with the $relativeSourcePath, remove the $relativeSourcePath from the start of $filename
// to avoid that getting duplicated when adding the $sourcePath below.
if ($relativeSourcePath && strpos($filename, $relativeSourcePath) === 0) {
$filename = substr($filename, strlen($relativeSourcePath));
}
$this->_sourceFile = $sourcePath . $filename;
if (file_exists($this->_sourceFile)) {
$this->_sourceFileSize = filesize($this->_sourceFile);
}
}
return $this->_sourceFile;
}
/**
* Get the filesize of the static source file represented by this instance.
*
* @param array $options An array of options.
* @return integer The filesize of the source file in bytes.
*/
public function getSourceFileSize(array $options = array()) {
$this->getSourceFile($options);
return $this->_sourceFileSize;
}
/**
* Treats the local content as a filename to load the raw content from.
*
* For resources with a binary content type, this renders out the file to the browser immediately.
*
* {@inheritdoc}
*/
public function getContent(array $options = [])
{
$this->getSourceFile($options);
$content = $this->getFileContent($this->_sourceFile);
if ($content === false) {
$this->xpdo->sendErrorPage();
}
return $content;
}
/**
* Retrieve the resource content stored in a physical file.
*
* @param string $file @deprecated internal _sourceFile is always used
* @param array $options
* @return string The content of the file, of false if it could not be
* retrieved.
*/
public function getFileContent($file, array $options = [])
{
/** @var modContentType $contentType */
$contentType = $this->getOne('ContentType');
if (!$contentType) {
$this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "modStaticResource->getFileContent() for resource {$this->get('id')}: Could not get content type.");
return false;
}
$content = false;
if (file_exists($this->_sourceFile) && is_readable($this->_sourceFile)) {
$content = $this->_sourceFile;
}
if (empty($content)) {
$this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "modStaticResource->getFileContent() for resource {$this->get('id')}: Could not load content from file {$this->_sourceFile}");
return false;
}
// Return the content if not binary
if (!$contentType->get('binary')) {
return file_get_contents($content);
}
// Set the appropriate content type header
$mimeType = $contentType->get('mime_type') ?: 'text/html';
$header = 'Content-Type: ' . $mimeType;
header($header);
// Apply a content-length header if we know the size in bytes
$filesize = $this->getSourceFileSize($options);
if ($filesize > 0) {
header('Content-Length: ' . $filesize);
}
// Set content disposition header based on what's configured on the resource (bool)
if ($this->get('content_dispo')) {
$name = $this->getAttachmentName($contentType);
header('Content-Disposition: attachment; filename=' . $name);
}
else {
header('Content-Disposition: inline');
}
// Cache control headers
header('Cache-Control: public');
header('Vary: User-Agent');
// Custom headers defined on the content type, if any
if ($customHeaders = $contentType->get('headers')) {
foreach ($customHeaders as $headerKey => $headerString) {
header($headerString);
}
}
// Close the user session, clean out the output buffer
@session_write_close();
while (ob_get_level() && @ob_end_clean()) {}
readfile($content);
exit();
}
/**
* Converts to bytes from PHP ini_get() format.
*
* PHP ini modifiers for byte values:
* <ul>
* <li>G = gigabytes</li>
* <li>M = megabytes</li>
* <li>K = kilobytes</li>
* </ul>
*
* @access protected
* @param string $value Number of bytes represented in PHP ini value format.
* @return integer The value converted to bytes.
*/
protected function _bytes($value)
{
$value = trim($value);
$modifier = strtolower($value[strlen($value)-1]);
switch($modifier) {
case 'g':
$value *= 1024;
case 'm':
$value *= 1024;
case 'k':
$value *= 1024;
}
return $value;
}
/**
* Sets the path to the Static Resource manager controller
* @static
* @param xPDO $modx A reference to the modX instance
* @return string
*/
public static function getControllerPath(xPDO &$modx)
{
$path = modResource::getControllerPath($modx);
return $path.'staticresource/';
}
/**
* Use this in your extended Resource class to display the text for the context menu item, if showInContextMenu is
* set to true.
* @return array
*/
public function getContextMenuText()
{
return [
'text_create' => $this->xpdo->lexicon('static_resource'),
'text_create_here' => $this->xpdo->lexicon('static_resource_create_here'),
];
}
/**
* Use this in your extended Resource class to return a translatable name for the Resource Type.
* @return string
*/
public function getResourceTypeName()
{
return $this->xpdo->lexicon('static_resource');
}
/**
* Gets the name for the downloaded file for the resource
*
* @param modContentType $contentType
* @return string
*/
private function getAttachmentName(modContentType $contentType)
{
$ext = $contentType->getExtension();
if ($alias = $this->get('uri')) {
$name = basename($alias);
}
elseif ($this->get('alias')) {
$name = $this->get('alias') . $ext;
}
elseif ($name = $this->get('pagetitle')) {
$name = $this->cleanAlias($name) . $ext;
}
else {
$name = 'download' . $ext;
}
return $name;
}
}