summaryrefslogtreecommitdiffstats
path: root/application/models/mfile.php
blob: c4d2c6e68a3d434ad0e77353eeb66480513431e1 (plain)
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
<?php
/*
 * Copyright 2009-2013 Florian "Bluewind" Pritz <bluewind@server-speed.net>
 *
 * Licensed under AGPLv3
 * (see COPYING for full license text)
 *
 */

class Mfile extends CI_Model {

	function __construct()
	{
		parent::__construct();
		$this->load->model("muser");
	}

	// Returns an unused ID
	function new_id($min = 3, $max = 6)
	{
		static $id_blacklist = NULL;

		if ($id_blacklist == NULL) {
			// This prevents people from being unable to access their uploads
			// because of URL rewriting
			$id_blacklist = scandir(FCPATH);
			$id_blacklist[] = "file";
			$id_blacklist[] = "user";
		}

		$max_tries = 100;

		for ($try = 0; $try < $max_tries; $try++) {
			$id = random_alphanum($min, $max);

			if ($this->id_exists($id) || in_array($id, $id_blacklist)) {
				continue;
			}

			return $id;
		}

		show_error("Failed to find unused ID after $max_tries tries.");
	}

	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;
		}
	}

	public function stale_hash($hash)
	{
		return $this->unused_file($hash);
	}

	function get_filedata($id)
	{
		$sql = '
			SELECT id, hash, filename, mimetype, date, user, filesize
			FROM `files`
			WHERE `id` = ?
			LIMIT 1';
		$query = $this->db->query($sql, array($id));

		if ($query->num_rows() > 0) {
			return $query->row_array();
		} 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;
	}

	// Return mimetype of file
	function mimetype($file) {
		$fileinfo = new finfo(FILEINFO_MIME_TYPE);
		$mimetype = $fileinfo->file($file);

		return $mimetype;
	}

	public function image_dimension($file)
	{
		list($width, $height) = getimagesize($file);

		return "${width}x${height}";
	}

	/*
	 * This returns a square thumbnail for the input image
	 * Source: http://salman-w.blogspot.co.at/2009/04/crop-to-fit-image-using-aspphp.html
	 */
	public function makeThumb($id, $size = 150, $target_type = null)
	{
		$filedata = $this->get_filedata($id);
		if (!$filedata) {
			return false;
		}

		$source_path = $this->file($filedata["hash"]);

		$source_gdim = imagecreatefromstring(file_get_contents($source_path));
		if ($source_gdim === false) {
			show_error("Unsupported image type");
		}
		imagealphablending($source_gdim,false);
		imagesavealpha($source_gdim,true);

		list($source_width, $source_height, $source_type) = getimagesize($source_path);

		if ($target_type === null) {
			$target_type = $source_type;
		}

		$target_width = $size;
		$target_height = $size;

		$source_aspect_ratio = $source_width / $source_height;
		$desired_aspect_ratio = $target_width / $target_height;

		if ($source_aspect_ratio > $desired_aspect_ratio) {
			// Triggered when source image is wider
			$temp_height = $target_height;
			$temp_width = round(($target_height * $source_aspect_ratio));
		} else {
			// Triggered otherwise (i.e. source image is similar or taller)
			$temp_width = $target_width;
			$temp_height = round(($target_width / $source_aspect_ratio));
		}

		/*
		 * Resize the image into a temporary GD image
		 */

		$temp_gdim = imagecreatetruecolor($temp_width, $temp_height);
		imagealphablending($temp_gdim,false);
		imagesavealpha($temp_gdim,true);
		imagecopyresampled(
			$temp_gdim,
			$source_gdim,
			0, 0,
			0, 0,
			$temp_width, $temp_height,
			$source_width, $source_height
		);

		/*
		 * Copy cropped region from temporary image into the desired GD image
		 */

		$x0 = ($temp_width - $target_width) / 2;
		$y0 = ($temp_height - $target_height) / 2;
		$thumb = imagecreatetruecolor($target_width, $target_height);
		imagealphablending($thumb,false);
		imagesavealpha($thumb,true);
		imagecopy(
			$thumb,
			$temp_gdim,
			0, 0,
			$x0, $y0,
			$target_width, $target_height
		);

		/*
		 * Fix orientation according to exif tag
		 */
		try {
			$exif = exif_read_data($source_path);
		} catch (ErrorException $e) {
		}

		if (isset($exif['Orientation'])) {
			$mirror = false;
			$deg    = 0;

			switch ($exif['Orientation']) {
			case 2:
				$mirror = true;
				break;
			case 3:
				$deg = 180;
				break;
			case 4:
				$deg = 180;
				$mirror = true;
				break;
			case 5:
				$deg = 270;
				$mirror = true;
				break;
			case 6:
				$deg = 270;
				break;
			case 7:
				$deg = 90;
				$mirror = true;
				break;
			case 8:
				$deg = 90;
				break;
			}
			if ($deg) $thumb = imagerotate($thumb, $deg, 0);
			if ($mirror) $thumb = $this->_mirrorImage($thumb);
		}

		ob_start();
		switch ($target_type) {
			case IMAGETYPE_GIF:
				$ret = imagegif($thumb);
				break;
			case IMAGETYPE_JPEG:
				$ret = imagejpeg($thumb);
				break;
			case IMAGETYPE_PNG:
				$ret = imagepng($thumb);
				break;
			default:
				assert(0);
		}
		$result = ob_get_clean();

		if (!$ret) {
			show_error("Failed to create thumbnail");
		}

		imagedestroy($thumb);
		imagedestroy($temp_gdim);
		imagedestroy($source_gdim);

		return $result;
	}

	function _mirrorImage($imgsrc)
	{
		$width = imagesx($imgsrc);
		$height = imagesy($imgsrc);

		$src_x = $width -1;
		$src_y = 0;
		$src_width = -$width;
		$src_height = $height;

		$imgdest = imagecreatetruecolor($width, $height);
		imagealphablending($imgdest,false);
		imagesavealpha($imgdest,true);

		if (imagecopyresampled($imgdest, $imgsrc, 0, 0, $src_x, $src_y, $width, $height, $src_width, $src_height)) {
			return $imgdest;
		}

		return $imgsrc;
	}

	// Add a hash to the DB
	function add_file($hash, $id, $filename)
	{
		$userid = $this->muser->get_userid();

		$mimetype = $this->mimetype($this->file($hash));

		$filesize = filesize($this->file($hash));
		$this->db->insert("files", array(
			"id" => $id,
			"hash" => $hash,
			"filename" => $filename,
			"date" => time(),
			"user" => $userid,
			"mimetype" => $mimetype,
			"filesize" => $filesize,
		));
	}

	function adopt($id)
	{
		$userid = $this->muser->get_userid();

		$this->db->query("
			UPDATE files
			SET user = ?
			WHERE id = ?
			", array($userid, $id));
	}

	// 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)) {
			$this->delete_hash($filedata["hash"]);
			return false;
		}

		// 0 age disables age checks
		if ($this->config->item('upload_max_age') == 0) return true;

		// 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) {
				$this->delete_hash($filedata["hash"]);
			} else {
				$this->delete_id($id);
			}
			return false;
		}

		return true;
	}

	public function get_timeout($id)
	{
		$filedata = $this->get_filedata($id);
		$file = $this->file($filedata["hash"]);

		if ($this->config->item("upload_max_age") == 0) {
			return -1;
		}

		if (filesize($file) > $this->config->item("small_upload_size")) {
			return $filedata["date"] + $this->config->item("upload_max_age");
		} else {
			return -1;
		}
	}

	public function get_timeout_string($id)
	{
		$timeout = $this->get_timeout($id);

		if ($timeout >= 0) {
			return date("r", $timeout);
		} 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;
		}
	}

	public function delete_id($id)
	{
		$filedata = $this->get_filedata($id);

		// Delete the file and all multipastes using it
		// Note that this does not delete all relations in multipaste_file_map
		// which is actually done by a SQL contraint.
		// TODO: make it work properly without the constraint
		$this->db->query('
			DELETE m, mfm, f
			FROM files f
			LEFT JOIN multipaste_file_map mfm ON f.id = mfm.file_url_id
			LEFT JOIN multipaste m ON mfm.multipaste_id = m.multipaste_id
			WHERE f.id = ?
			', array($id));

		if ($this->id_exists($id))  {
			return false;
		}

		if ($filedata !== false) {
			assert(isset($filedata["hash"]));
			if ($this->unused_file($filedata['hash'])) {
				unlink($this->file($filedata['hash']));
				$dir = $this->folder($filedata['hash']);
				if (count(scandir($dir)) == 2) {
					rmdir($dir);
				}
			}
		}
		return true;
	}

	public function delete_hash($hash)
	{
		// Delete all files with this hash and all multipastes using any of those files
		// Note that this does not delete all relations in multipaste_file_map
		// which is actually done by a SQL contraint.
		// TODO: make it work properly without the constraint
		$this->db->query('
			DELETE m, mfm, f
			FROM files f
			LEFT JOIN multipaste_file_map mfm ON f.id = mfm.file_url_id
			LEFT JOIN multipaste m ON mfm.multipaste_id = m.multipaste_id
			WHERE f.hash = ?
			', array($hash));

		if (file_exists($this->file($hash))) {
			unlink($this->file($hash));
			$dir = $this->folder($hash);
			if (count(scandir($dir)) == 2) {
				rmdir($dir);
			}
		}
		return true;
	}

	public function get_owner($id)
	{
		return $this->db->query("
			SELECT user
			FROM files
			WHERE id = ?
			", array($id))->row_array()["user"];
	}

	public function get_lexers() {
		return cache_function('lexers', 1800, function() {
			$lexers = array();
			$last_desc = "";
			exec("python ".escapeshellarg(FCPATH."scripts/get_lexer_list.py"), $output);

			foreach ($output as $line) {
				list($name, $desc) = explode("|", $line);
				if ($desc == $last_desc) {
					continue;
				}
				$last_desc = $desc;
				$lexers[$name] = $desc;
			}
			$lexers["text"] = "Plain text";
			return $lexers;
		});
	}

	public function should_highlight($type)
	{
		if ($this->mime2lexer($type)) return true;

		return false;
	}

	// Allow certain types to be highlight without doing it automatically
	public function can_highlight($type)
	{
		$typearray = array(
			'image/svg+xml',
		);
		if (in_array($type, $typearray)) return true;

		if ($this->mime2lexer($type)) return true;

		return false;
	}

	// Return the lexer that should be used for highlighting
	public function autodetect_lexer($type, $filename)
	{
		if (!$this->can_highlight($type)) {
			return false;
		}

		$lexer = $this->mime2lexer($type);

		// filename lexers overwrite mime type mappings
		$filename_lexer = $this->filename2lexer($filename);
		if ($filename_lexer) {
			return $filename_lexer;
		}

		return $lexer;
	}

	// Map MIME types to lexers needed for highlighting
	private function mime2lexer($type)
	{
		$typearray = array(
		'application/javascript' => 'javascript',
		'application/mbox' => 'text',
		'application/smil' => 'ocaml',
		'application/x-applix-spreadsheet' => 'actionscript',
		'application/x-awk' => 'awk',
		'application/x-desktop' => 'text',
		'application/x-fluid' => 'text',
		'application/x-genesis-rom' => 'text',
		'application/x-java' => 'java',
		'application/x-m4' => 'text',
		'application/xml-dtd' => "xml",
		'application/xml' => 'xml',
		'application/x-perl' => 'perl',
		'application/x-php' => 'php',
		'application/x-ruby' => 'ruby',
		'application/x-shellscript' => 'bash',
		'application/xslt+xml' => "xml",
		'application/x-x509-ca-cert' => 'text',
		'message/rfc822' => 'text',
		'text/css' => 'css',
		'text/html' => 'xml',
		'text/plain-ascii' => 'ascii',
		'text/plain' => 'text',
		'text/troff' => 'groff',
		'text/x-asm' => 'nasm',
		'text/x-awk' => 'awk',
		'text/x-c' => 'c',
		'text/x-c++' => 'cpp',
		'text/x-c++hdr' => 'c',
		'text/x-chdr' => 'c',
		'text/x-csrc' => 'c',
		'text/x-c++src' => 'cpp',
		'text/x-diff' => 'diff',
		'text/x-gawk' => 'awk',
		'text/x-haskell' => 'haskell',
		'text/x-java' => 'java',
		'text/x-lisp' => 'cl',
		'text/x-literate-haskell' => 'haskell',
		'text/x-lua' => 'lua',
		'text/x-makefile' => 'make',
		'text/x-ocaml' => 'ocaml',
		'text/x-patch' => 'diff',
		'text/x-perl' => 'perl',
		'text/x-php' => 'php',
		'text/x-python' => 'python',
		'text/x-ruby' => 'ruby',
		'text/x-scheme' => 'scheme',
		'text/x-shellscript' => 'bash',
		'text/x-subviewer' => 'bash',
		'text/x-tcl' => 'tcl',
		'text/x-tex' => 'tex',
		);
		if (array_key_exists($type, $typearray)) return $typearray[$type];

		if (strpos($type, 'text/') === 0) return 'text';

		# default
		return false;
	}

	// Map special filenames to lexers
	private function filename2lexer($name)
	{
		$namearray = array(
			'PKGBUILD' => 'bash',
			'.vimrc' => 'vim'
		);
		if (array_key_exists($name, $namearray)) return $namearray[$name];


		if (strpos($name, ".") !== false) {
			$extension = substr($name, strrpos($name, ".") + 1);

			$extensionarray = array(
				'awk' => 'awk',
				'c' => 'c',
				'coffee' => 'coffee-script',
				'cpp' => 'cpp',
				'diff' => 'diff',
				'h' => 'c',
				'hs' => 'haskell',
				'html' => 'xml',
				'java' => 'java',
				'js' => 'js',
				'lua' => 'lua',
				'mli' => 'ocaml',
				'mll' => 'ocaml',
				'ml' => 'ocaml',
				'mly' => 'ocaml',
				'patch' => 'diff',
				'php' => 'php',
				'pl' => 'perl',
				'py' => 'python',
				'rb' => 'ruby',
				's' => 'asm',
				'sh' => 'bash',
				'tcl' => 'tcl',
				'tex' => 'tex',
			);
			if (array_key_exists($extension, $extensionarray)) return $extensionarray[$extension];
		}

		return false;
	}

	// Handle lexer aliases
	public function resolve_lexer_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: