-
Notifications
You must be signed in to change notification settings - Fork 0
/
tiki-download_file.php
403 lines (353 loc) · 15 KB
/
tiki-download_file.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
<?php
/**
* @package tikiwiki
*/
// (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id: tiki-download_file.php 50614 2014-04-02 12:08:44Z jp_eagle $
$force_no_compression = true;
$skip = false;
$thumbnail_format = 'jpeg';
if ( isset($_GET['fileId']) && isset($_GET['thumbnail']) && isset($_COOKIE[ session_name() ]) && count($_GET) == 2 ) {
$tikiroot = dirname($_SERVER['PHP_SELF']);
$session_params = session_get_cookie_params();
session_set_cookie_params($session_params['lifetime'], $tikiroot);
unset($session_params);
session_start();
if ( isset($_SESSION['allowed'][$_GET['fileId']]) ) {
require_once 'tiki-setup_base.php';
$query = "select * from `tiki_files` where `fileId`=?";
$result = $tikilib->query($query, array((int)$_GET['fileId']));
if ( $result ) {
$info = $result->fetchRow();
$skip = true;
} else {
$info = array();
}
} else {
session_write_close();
}
}
if (!$skip) {
require_once('tiki-setup.php');
include_once('lib/filegals/filegallib.php');
$access->check_feature('feature_file_galleries');
}
if ($prefs["user_store_file_gallery_picture"] == 'y' && isset($_REQUEST["avatar"])) {
require_once ('lib/userprefs/userprefslib.php');
if ($user_picture_id = $userprefslib->get_user_picture_id($_REQUEST["avatar"])) {
$_REQUEST['fileId'] = $user_picture_id;
} elseif (!empty($prefs['user_default_picture_id'])) {
$_REQUEST['fileId'] = $prefs['user_default_picture_id'];
}
}
if ( ! ini_get('safe_mode') ) {
@set_time_limit(0);
}
$zip = false;
$error = '';
if (!$skip) {
if ( isset($_REQUEST['fileId']) && !is_array($_REQUEST['fileId'])) {
if (isset($_GET['draft'])) {
$info = $filegallib->get_file_draft($_REQUEST['fileId']);
} else {
$info = $filegallib->get_file($_REQUEST['fileId']);
}
} elseif ( isset($_REQUEST['galleryId']) && isset($_REQUEST['name']) ) {
$info = $filegallib->get_file_by_name($_REQUEST['galleryId'], $_REQUEST['name']);
} elseif ( isset($_REQUEST['fileId']) && is_array($_REQUEST['fileId'])) {
$info = $filegallib->zip($_REQUEST['fileId'], $error);
$zip = true;
} elseif ( !empty($_REQUEST['randomGalleryId'])) {
$info = $filegallib->get_file(0, $_REQUEST['randomGalleryId']);
} else {
$access->display_error('', tra('Incorrect param'), 400);
}
if ( ! is_array($info) ) {
$access->display_error(NULL, tra('File has been deleted'), 404);
}
if ( $prefs['auth_token_access'] != 'y' || !$is_token_access ) {
// Check permissions except if the user comes with a valid Token
if ( !$zip && $tiki_p_admin_file_galleries != 'y' && !$userlib->user_has_perm_on_object($user, $info['galleryId'], 'file gallery', 'tiki_p_download_files') && !($info['backlinkPerms'] == 'y' && !$filegallib->hasOnlyPrivateBacklinks($info['fileId']))) {
if (!$user) $_SESSION['loginfrom'] = $_SERVER['REQUEST_URI'];
$access->display_error('', tra('Permission denied'), 401);
}
if ( isset($_GET['thumbnail']) && is_numeric($_GET['thumbnail'])) { //check also perms on thumb
$info_thumb = $filegallib->get_file($_GET['thumbnail']);
if ( !$zip && $tiki_p_admin_file_galleries != 'y' && !$userlib->user_has_perm_on_object($user, $info_thumb['galleryId'], 'file gallery', 'tiki_p_download_files') && !($info['backlinkPerms'] == 'y' && !$filegallib->hasOnlyPrivateBacklinks($info_thumb['fileId']))) {
if (!$user) $_SESSION['loginfrom'] = $_SERVER['REQUEST_URI'];
$access->display_error('', tra('Permission denied'), 401);
}
}
if ($prefs['feature_use_fgal_for_user_files'] === 'y' && $tiki_p_admin_file_galleries !== 'y' && $prefs['userfiles_private'] === 'y') {
$gal_info = $filegallib->get_file_gallery_info($info['galleryId']);
if ($gal_info['type'] === 'user' && $gal_info['visible'] !== 'y' && $gal_info['user'] !== $user ) {
$access->display_error('', tra('Permission denied'), 401);
}
}
}
}
//if the file is remote, display, and don't cache
$attributelib = TikiLib::lib('attribute');
$attributes = $attributelib->get_attributes('file', $info['fileId']);
if (isset($attributes['tiki.content.url'])) {
$smarty->loadPlugin('smarty_modifier_sefurl');
$src = smarty_modifier_sefurl($info['fileId'], 'file');
session_write_close();
$client = $tikilib->get_http_client($src);
$response = $client->request();
header('Content-Type: ' . $response->getHeader('Content-Type'));
echo $response->getBody();
exit();
}
// Add hits ( if download or display only ) + lock if set
if ( ! isset($_GET['thumbnail']) && ! isset($_GET['icon']) ) {
require_once('lib/stats/statslib.php');
$filegallib = TikiLib::lib('filegal');
if ( ! $filegallib->add_file_hit($info['fileId']) ) {
$access->display_error('', tra('You cannot download this file right now. Your score is low or file limit was reached.'), 401);
}
$statslib->stats_hit($info['filename'], 'file', $info['fileId']);
if ( $prefs['feature_actionlog'] == 'y' ) {
global $logslib; require_once('lib/logs/logslib.php');
$logslib->add_action('Downloaded', $info['galleryId'], 'file gallery', 'fileId='.$info['fileId']);
}
if ( ! empty($_REQUEST['lock']) ) {
if (!empty($info['lockedby']) && $info['lockedby'] != $user) {
$access->display_error('', tra(sprintf('The file is locked by %s', $info['lockedby'])), 401);
}
$filegallib->lock_file($info['fileId'], $user);
}
}
session_write_close(); // close the session in case of large downloads to enable further browsing
error_reporting(E_ALL);
while (ob_get_level()>1) {
ob_end_clean();
}// Be sure output buffering is turned off
$content_changed = false;
$content = &$info['data'];
$md5 = '';
$filepath = '';
if ( ! empty($info['path']) ) {
if (!$skip and $filegallib->isPodCastGallery($info['galleryId'])) {
$filepath = $prefs['fgal_podcast_dir'].$info['path'];
} else {
$filepath = $prefs['fgal_use_dir'].$info['path'];
}
if ( is_readable($filepath) ) {
$file_stats = stat($filepath);
$last_modified = $file_stats['mtime'];
$md5 = empty($info['hash']) ?
md5($file_stats['mtime'].'='.$file_stats['ino'].'='.$file_stats['size'])
: md5($info['hash'] . $last_modified);
} else {
// File missing or not readable
header("HTTP/1.0 404 Not Found");
header('Content-Type: text/plain');
echo "Unable to access file: " . ($tiki_p_admin == 'y' ? $filepath : $info['path']);
die;
}
} elseif ( ! empty($content) ) {
$last_modified = $info['lastModif'];
$md5 = empty($info['hash']) ? md5($content) : md5($info['hash'] . $last_modified);
} else {
// Empty content
die;
}
// ETag: Entity Tag used for strong cache validation.
if ( ! isset($_GET['display']) || isset($_GET['x']) || isset($_GET['y']) || isset($_GET['scale']) || isset($_GET['max']) || isset($_GET['format']) ) {
// if image will be modified, emit a different ETag for modifications.
$str = isset($_GET['x']) ? $_GET['x'] . 'x' : '';
$str .= isset($_GET['y']) ? $_GET['y'] . 'y' : '';
$str .= isset($_GET['scale']) ? $_GET['scale'] . 's' : '';
$str .= isset($_GET['max']) ? $_GET['max'] . 'm' : '';
$str .= isset($_GET['format']) ? $_GET['format'] . 'f' : '';
$etag = '"' . $md5 . '-' . crc32($md5) . '-' . crc32($str) . '"';
} else {
$etag = '"' . $md5 . '-' . crc32($md5) . '"';
}
header('ETag: '.$etag);
$use_client_cache = false;
if ( isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $last_modified == strtotime(current($a = explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE']))) ) {
$use_client_cache = true;
} elseif ( isset($_SERVER['HTTP_IF_NONE_MATCH']) ) {
$tmp = array_map('trim', explode(',', $_SERVER['HTTP_IF_NONE_MATCH']));
foreach ( $tmp as $v ) {
if ( $v == '*' || $v == $etag ) {
$use_client_cache = true;
break;
}
}
unset($tmp);
}
header("Pragma: ");
header('Expires: ');
header('Cache-Control: '.( !empty($user) ? 'private' : 'public' ).',must-revalidate,post-check=0,pre-check=0');
if ( $use_client_cache) {
header('Status: 304 Not Modified', true, 304);
exit;
} else {
if ( !empty($last_modified) ) header('Last-Modified: '.gmdate('D, d M Y H:i:s', $last_modified). ' GMT');
}
// Handle images display, files thumbnails and icons
if ( isset($_GET['preview']) || isset($_GET['thumbnail']) || isset($_GET['display']) || isset($_GET['icon']) ) {
$use_cache = false;
// Cache only thumbnails to avoid DOS attacks
$cacheName = '';
$cacheType = '';
if ( ( isset($_GET['thumbnail']) || isset($_GET['preview']) ) && ! isset($_GET['display']) && ! isset($_GET['icon']) && ! isset($_GET['scale']) && ! isset($_GET['x']) && ! isset($_GET['y']) && ! isset($_GET['format']) && ! isset($_GET['max']) ) {
global $cachelib; include_once('lib/cache/cachelib.php');
$cacheName = $md5;
$cacheType = ( isset($_GET['thumbnail']) ? 'thumbnail_' : 'preview_' ) . ((int)$_REQUEST['fileId']).'_';
$use_cache = true;
}
$build_content = true;
$content_temp = $cachelib->getCached($cacheName, $cacheType);
if ( $use_cache && $content_temp ) {
if ($content_temp !== serialize(false) and $content_temp != "") {
$build_content = false;
$content = $content_temp;
}
$content_changed = true;
}
unset($content_temp);
if ($build_content) {
// Modify the original image if needed
if ( ! isset($_GET['display']) || isset($_GET['x']) || isset($_GET['y']) || isset($_GET['scale']) || isset($_GET['max']) || isset($_GET['format']) || isset($_GET['thumbnail']) ) {
require_once('lib/images/images.php');
if (!class_exists('Image')) die();
$content_changed = true;
$format = substr($info['filename'], strrpos($info['filename'], '.') + 1);
// Fallback to an icon if the format is not supported
$tmp = new Image('img/icons/pixel_trans.gif', true, 'gif'); // needed to call non-static Image functions non-statically
if ( ! $tmp->is_supported($format) ) {
// Is the filename correct? Maybe it doesn't have an extenstion?
// Try to determine the format from the filetype too
$format = substr($info['filetype'], strrpos($info['filetype'], '/') + 1);
if ( ! $tmp->is_supported($format) ) {
$_GET['icon'] = 'y';
$_GET['max'] = 32;
}
}
do {
$tryIconFallback = false;
if ( isset($_GET['icon']) ) {
unset($info['path']);
$content = null; // Explicitely free memory before generating icon
if ( isset($_GET['max']) ) {
$icon_x = $_GET['max'];
$icon_y = $_GET['max'];
} else {
$icon_x = isset($_GET['x']) ? $_GET['x'] : 0;
$icon_y = isset($_GET['y']) ? $_GET['y'] : 0;
}
$ext = pathinfo($info['filename']); // TODO replace with mimelib functions
$format = isset($ext['extension']) ? $ext['extension'] : $format;
$content = $tmp->icon($format, $icon_x, $icon_y);
$format = $tmp->get_icon_default_format();
$info['filetype'] = 'image/'.$format;
$info['lastModif'] = 0;
}
if ( ! isset($_GET['icon']) || ( isset($_GET['format']) && $_GET['format'] != $format ) ) {
if ( ! empty($info['path']) ) {
$image = new Image($prefs['fgal_use_dir'].$info['path'], true);
} else {
$image = new Image($content, false, $format);
$content = null; // Explicitely free memory before getting cache
}
if ( $image->is_empty() ) die;
$resize = false;
// We resize if needed
if ( isset($_GET['x']) || isset($_GET['y']) ) {
$image->resize(isset($_GET['x']) ? (int) $_GET['x'] : 0, isset($_GET['y']) ? (int) $_GET['y'] : 0);
$resize = true;
} elseif ( isset($_GET['scale']) ) {
// We scale if needed
$image->scale($_GET['scale']+0);
$resize = true;
} elseif ( isset($_GET['max']) ) {
// We reduce size if length or width is greater that $_GET['max'] if needed
$image->resizemax($_GET['max']+0);
$resize = true;
} elseif ( isset($_GET['thumbnail']) ) {
// We resize to a thumbnail size if needed
if (is_numeric($_GET['thumbnail'])) {
if (empty($info_thumb)) {
$info_thumb = $filegallib->get_file($_GET['thumbnail']);
}
if ( ! empty($info_thumb['path']) ) {
$image = new Image($prefs['fgal_use_dir'].$info_thumb['path'], true);
} else {
$image = new Image($info_thumb['data']);
$content = null; // Explicitely free memory before getting cache
}
if ( $image->is_empty() ) die;
}
$image->resizethumb();
} elseif ( isset($_GET['preview']) ) {
// We resize to a preview size if needed
$image->resizemax('800');
$resize = true;
}
// We change the image format if needed
if ( isset($_GET['format']) && $image->is_supported($_GET['format']) ) {
$image->convert($_GET['format']);
} elseif ( isset($_GET['thumbnail']) && $image->format != 'svg') {
// Or, if no format is explicitely specified and a thumbnail has to be created, we convert the image to the $thumbnail_format
if ($image->format == 'png') {
$thumbnail_format = 'png'; // preserves transparency
}
$image->convert($thumbnail_format);
}
$content = $image->display();
// If the new image creating has failed, fallback to an icon
if ( ! isset($_GET['icon']) && ( $content === null || $content === false ) ) {
$tryIconFallback = true;
$_GET['icon'] = 'y';
$_GET['max'] = 32;
} else {
$info['filetype'] = $image->get_mimetype();
}
}
} while ( $tryIconFallback );
}
if (strpos($info['filetype'], 'image/svg') !== false) {
$info['filetype'] = 'image/svg+xml';
$content = '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' . "\n" . $content;
}
if ( $use_cache && !empty($content) ) {
// Remove all existing thumbnails for this file, to avoid taking too much disk space
// (only one thumbnail size is handled at the same time)
$cachelib->empty_type_cache($cacheType);
// Cache Thumbnail
$cachelib->cacheItem($cacheName, $content, $cacheType);
}
}
}
$mimelib = TikiLib::lib('mime');
if ( empty($info['filetype']) || $info['filetype'] == 'application/x-octetstream'
|| $info['filetype'] == 'application/octet-stream' || $info['filetype'] == 'unknown') {
$info['filetype'] = $mimelib->from_path($info['filename'], $filepath);
} else if (isset($_GET['thumbnail']) && (strpos($info['filetype'], 'image') === false || ($content_changed && strpos($info['filetype'], 'image/svg') === false))) { // use thumb format
$info['filetype'] = $mimelib->from_content($info['filename'], $content);
}
header('Content-type: '.$info['filetype']);
// IE6 can not download file with / in the name (the / can be there from a previous bug)
$file = basename($info['filename']);
// If the content has not changed, ask the browser to download it (instead of displaying it)
if ( ! $content_changed and !isset($_GET['display']) ) {
header("Content-Disposition: attachment; filename=\"$file\"");
}
if ( !empty($filepath) and !$content_changed ) {
header('Content-Length: '.filesize($filepath));
readfile($filepath);
} else {
if ( function_exists('mb_strlen') ) {
header('Content-Length: '.mb_strlen($content, '8bit'));
} else {
header('Content-Length: '.strlen($content));
}
echo "$content";
}