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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
|
<?php
/*
* Copyright 2009-2011 Florian "Bluewind" Pritz <bluewind@server-speed.net>
*
* Licensed under GPLv3
* (see COPYING for full license text)
*
*/
class File_mod extends CI_Model {
public $data;
function __construct()
{
parent::__construct();
$this->data =& get_instance()->data;
$this->load->model("muser");
}
// Returns an unused ID
// TODO: make threadsafe
function new_id()
{
$id = random_alphanum(3,6);
if ($this->id_exists($id) || $id == 'file' || $id == 'user') {
return $this->new_id();
} else {
return $id;
}
}
function id_exists($id)
{
if(!$id) {
return false;
}
$sql = '
SELECT id
FROM `files`
WHERE `id` = ?
LIMIT 1';
$query = $this->db->query($sql, array($id));
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
function get_filedata($id)
{
$sql = '
SELECT hash, filename, mimetype, date, user, filesize
FROM `files`
WHERE `id` = ?
LIMIT 1';
$query = $this->db->query($sql, array($id));
if ($query->num_rows() == 1) {
$return = $query->result_array();
return $return[0];
} else {
return false;
}
}
// return the folder in which the file with $hash is stored
function folder($hash) {
return $this->config->item('upload_path').'/'.substr($hash, 0, 3);
}
// Returns the full path to the file with $hash
function file($hash) {
return $this->folder($hash).'/'.$hash;
}
// Add a hash to the DB
// TODO: Should only update not insert; see new_id()
function add_file($hash, $id, $filename)
{
$userid = $this->muser->get_userid();
$mimetype = exec("perl ".FCPATH.'scripts/mimetype '.escapeshellarg($filename).' '.escapeshellarg($this->file($hash)));
$filesize = filesize($this->file($hash));
$query = $this->db->query('
INSERT INTO `files` (`hash`, `id`, `filename`, `user`, `date`, `mimetype`, `filesize`)
VALUES (?, ?, ?, ?, ?, ?, ?)',
array($hash, $id, $filename, $userid, time(), $mimetype, $filesize));
}
function adopt($id)
{
$userid = $this->muser->get_userid();
$this->db->query("
UPDATE files
SET user = ?
WHERE id = ?
", array($userid, $id));
}
function show_url($id, $mode)
{
$redirect = false;
if (!$this->muser->logged_in()) {
// keep the upload but require the user to login
$this->session->set_userdata("last_upload", array(
"id" => $id,
"mode" => $mode
));
$this->session->set_flashdata("uri", "file/claim_id");
$this->muser->require_access();
}
if ($mode) {
$this->data['url'] = site_url($id).'/'.$mode;
} else {
$this->data['url'] = site_url($id).'/';
$filedata = $this->get_filedata($id);
$file = $this->file($filedata['hash']);
$type = $filedata['mimetype'];
$mode = $this->mime2mode($type);
// If we detected a highlightable file redirect,
// otherwise show the URL because browsers would just show a DL dialog
if ($mode) {
$redirect = true;
}
}
if (is_cli_client()) {
$redirect = false;
}
if ($redirect) {
redirect($this->data['url'], "location", 303);
} else {
$this->load->view($this->var->view_dir.'/header', $this->data);
$this->load->view($this->var->view_dir.'/show_url', $this->data);
$this->load->view($this->var->view_dir.'/footer', $this->data);
}
}
function non_existent()
{
$this->data["title"] .= " - Not Found";
$this->output->set_status_header(404);
$this->load->view($this->var->view_dir.'/header', $this->data);
$this->load->view($this->var->view_dir.'/non_existent', $this->data);
$this->load->view($this->var->view_dir.'/footer', $this->data);
}
// remove old/invalid/broken IDs
function valid_id($id)
{
$filedata = $this->get_filedata($id);
if (!$filedata) {
return false;
}
$file = $this->file($filedata['hash']);
if (!file_exists($file)) {
if (isset($filedata["hash"])) {
$this->db->query('DELETE FROM files WHERE hash = ?', array($filedata['hash']));
}
return false;
}
// small files don't expire
if (filesize($file) <= $this->config->item("small_upload_size")) {
return true;
}
// files older than this should be removed
$remove_before = (time()-$this->config->item('upload_max_age'));
if ($filedata["date"] < $remove_before) {
// if the file has been uploaded multiple times the mtime is the time
// of the last upload
if (filemtime($file) < $remove_before) {
unlink($file);
$this->db->query('DELETE FROM files WHERE hash = ?', array($filedata['hash']));
} else {
$this->db->query('DELETE FROM files WHERE id = ? LIMIT 1', array($id));
}
return false;
}
return true;
}
private function handle_etag($etag) {
$etag = strtolower($etag);
$modified = true;
if(isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
$oldtag = trim(strtolower($_SERVER['HTTP_IF_NONE_MATCH']), '"');
if($oldtag == $etag) {
$modified = false;
} else {
$modified = true;
}
}
header('Etag: "'.$etag.'"');
if (!$modified) {
header("HTTP/1.1 304 Not Modified");
exit();
}
}
// download a given ID
// TODO: make smaller
function download()
{
$id = $this->uri->segment(1);
$mode = $this->uri->segment(2);
$filedata = $this->get_filedata($id);
$file = $this->file($filedata['hash']);
if (!$this->valid_id($id)) {
$this->non_existent();
return;
}
// don't allow unowned files to be downloaded
if ($filedata["user"] == 0) {
$this->non_existent();
return;
}
// helps to keep traffic low when reloading
$etag = $filedata["hash"]."-".$filedata["date"];
$type = $filedata['mimetype'];
// autodetect the mode for highlighting if the URL contains a / after the ID (/ID/)
// /ID/mode disables autodetection
$autodetect_mode = !$mode && substr_count(ltrim($this->uri->uri_string(), "/"), '/') >= 1;
if ($autodetect_mode) {
$mode = $this->get_highlight_mode($type, $filedata["filename"]);
}
// resolve aliases of modes
// this is mainly used for compatibility
$mode = $this->resolve_mode_alias($mode);
// create the qr code for /ID/
if ($mode == "qr") {
$this->handle_etag($etag);
header("Content-disposition: inline; filename=\"".$id."_qr.png\"\n");
header("Content-Type: image/png\n");
passthru('qrencode -s 10 -o - '.escapeshellarg(site_url($id).'/'));
exit();
}
// user wants to the the plain file
if ($mode == 'plain') {
$this->handle_etag($etag);
rangeDownload($file, $filedata["filename"], "text/plain");
exit();
}
if ($mode == 'info') {
$this->display_info($id);
return;
}
// if there is no mimetype mapping we can't highlight it
$can_highlight = $this->can_highlight($type);
$filesize_too_big = filesize($file) > $this->config->item('upload_max_text_size');
if (!$can_highlight || $filesize_too_big || !$mode) {
$this->handle_etag($etag);
foreach (array("X-WebKit-CSP", "X-Content-Security-Policy") as $header_name) {
header("$header_name: allow 'none'; img-src *; media-src *; font-src *; style-src * 'unsafe-inline'; script-src 'none'; object-src *; frame-src 'none'; ");
}
rangeDownload($file, $filedata["filename"], $type);
exit();
}
$this->data['title'] = htmlspecialchars($filedata['filename']);
$this->data['id'] = $id;
header("Content-Type: text/html\n");
$this->data['current_highlight'] = htmlspecialchars($mode);
$this->data['timeout'] = $this->get_timeout_string($id);
echo $this->load->view($this->var->view_dir.'/html_header', $this->data, true);
// highlight the file and chache the result
$this->load->library("MemcacheLibrary");
if (! $cached = $this->memcachelibrary->get($filedata['hash'].'_'.$mode)) {
ob_start();
if ($mode == "rmd") {
echo '<td class="markdownrender">'."\n";
passthru('perl '.FCPATH.'scripts/Markdown.pl '.escapeshellarg($file));
} elseif ($mode == "ascii") {
echo '<td class="code"><pre class="text">'."\n";
passthru('perl '.FCPATH.'scripts/ansi2html '.escapeshellarg($file));
echo "</pre>\n";
} else {
echo '<td class="numbers"><pre>';
// generate line numbers (links)
passthru('perl -ne \'print "<a href=\"#n$.\" class=\"no\" id=\"n$.\">$.</a>\n"\' '.escapeshellarg($file));
echo '</pre></td><td class="code">'."\n";
$this->load->library('geshi');
$this->geshi->initialize(array('set_language' => $mode, 'set_source' => file_get_contents($file), 'enable_classes' => 'true'));
echo $this->geshi->parse_code();
}
$cached = ob_get_contents();
ob_end_clean();
$this->memcachelibrary->set($filedata['hash'].'_'.$mode, $cached, 100);
}
echo $cached;
echo $this->load->view($this->var->view_dir.'/html_footer', $this->data, true);
exit();
}
function get_timeout_string($id)
{
$filedata = $this->get_filedata($id);
$file = $this->file($filedata["hash"]);
if (filesize($file) > $this->config->item("small_upload_size")) {
return date("r", $filedata["date"] + $this->config->item("upload_max_age"));
} else {
return "unknown";
}
}
private function unused_file($hash)
{
$sql = '
SELECT id
FROM `files`
WHERE `hash` = ?
LIMIT 1';
$query = $this->db->query($sql, array($hash));
if ($query->num_rows() == 0) {
return true;
} else {
return false;
}
}
function display_info($id)
{
$this->data["title"] .= " - Info $id";
$this->data["filedata"] = $this->get_filedata($id);
$this->data["id"] = $id;
$this->data['timeout'] = $this->get_timeout_string($id);
if (!isset($this->data["can_delete"])) {
$this->data["can_delete"] = false;
}
$this->load->view($this->var->view_dir.'/header', $this->data);
$this->load->view($this->var->view_dir.'/file_info', $this->data);
$this->load->view($this->var->view_dir.'/footer', $this->data);
}
function delete_id($id)
{
$this->muser->require_access();
$filedata = $this->get_filedata($id);
$userid = $this->muser->get_userid();
if(!$this->id_exists($id)) {
return false;
}
$sql = '
DELETE
FROM `files`
WHERE `id` = ?
AND user = ?
LIMIT 1';
$this->db->query($sql, array($id, $userid));
if($this->id_exists($id)) {
return false;
}
if($this->unused_file($filedata['hash'])) {
unlink($this->file($filedata['hash']));
@rmdir($this->folder($filedata['hash']));
}
return true;
}
// Allow certain types to be highlight without doing it automatically
function can_highlight($type)
{
$typearray = array(
'image/svg+xml',
);
if (in_array($type, $typearray)) return true;
if ($this->mime2mode($type)) return true;
return false;
}
// Return the mode that should be used for highlighting
function get_highlight_mode($type, $filename)
{
$mode = $this->mime2mode($type);
// filename modes overwrite mime type mappings
$filename_mode = $this->filename2mode($filename);
if ($filename_mode) {
return $filename_mode;
}
return $mode;
}
// Map MIME types to modes needed for highlighting
private function mime2mode($type)
{
$typearray = array(
'text/plain' => 'text',
'text/plain-ascii' => 'ascii',
'text/x-python' => 'python',
'text/x-csrc' => 'c',
'text/x-chdr' => 'c',
'text/x-c++hdr' => 'c',
'text/x-c++src' => 'cpp',
'text/x-patch' => 'diff',
'text/x-lua' => 'lua',
'text/x-java' => 'java',
'text/x-haskell' => 'haskell',
'text/x-literate-haskell' => 'haskell',
'text/x-subviewer' => 'bash',
'text/x-scheme' => 'scheme',
'text/x-makefile' => 'make',
#'text/x-log' => 'log',
'text/html' => 'xml',
'text/css' => 'css',
'text/x-ocaml' => 'ocaml',
'message/rfc822' => 'email',
#'image/svg+xml' => 'xml',
'application/x-perl' => 'perl',
'application/xml' => 'xml',
'application/xml-dtd' => "xml",
'application/xslt+xml' => "xml",
'application/javascript' => 'javascript',
'application/smil' => 'ocaml',
'application/x-desktop' => 'text',
'application/x-m4' => 'text',
'application/x-awk' => 'text',
'application/x-fluid' => 'text',
'application/x-java' => 'java',
'application/x-php' => 'php',
'application/x-ruby' => 'ruby',
'application/x-shellscript' => 'bash',
'application/x-x509-ca-cert' => 'text',
'application/mbox' => 'email',
'application/x-genesis-rom' => 'text',
'application/x-applix-spreadsheet' => 'actionscript'
);
if (array_key_exists($type, $typearray)) return $typearray[$type];
if (strpos($type, 'text/') === 0) return 'text';
# default
return false;
}
// Map special filenames to modes
private function filename2mode($name)
{
$namearray = array(
'PKGBUILD' => 'bash',
'.vimrc' => 'vim'
);
if (array_key_exists($name, $namearray)) return $namearray[$name];
return false;
}
// Handle mode aliases
function resolve_mode_alias($alias)
{
if ($alias === false) return false;
$aliasarray = array(
'py' => 'python',
'sh' => 'bash',
's' => 'asm',
'pl' => 'perl'
);
if (array_key_exists($alias, $aliasarray)) return $aliasarray[$alias];
return $alias;
}
}
# vim: set noet:
|