aboutsummaryrefslogtreecommitdiff
path: root/engine/lib/filestore.php
blob: 9e114c262ff69d2ec1a567b473d0019fcd3187c4 (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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
<?php
/**
 * Elgg filestore.
 * This file contains classes, interfaces and functions for saving and retrieving data to various file
 * stores.
 *
 * @package Elgg
 * @subpackage API
 * @author Curverider Ltd
 * @link http://elgg.org/
 */

include_once("objects.php");

/**
 * @class ElggFilestore
 * This class defines the interface for all elgg data repositories.
 * @author Curverider Ltd
 */
abstract class ElggFilestore {
	/**
	 * Attempt to open the file $file for storage or writing.
	 *
	 * @param ElggFile $file
	 * @param string $mode "read", "write", "append"
	 * @return mixed A handle to the opened file or false on error.
	 */
	abstract public function open(ElggFile $file, $mode);

	/**
	 * Write data to a given file handle.
	 *
	 * @param mixed $f The file handle - exactly what this is depends on the file system
	 * @param string $data The binary string of data to write
	 * @return int Number of bytes written.
	 */
	abstract public function write($f, $data);

	/**
	 * Read data from a filestore.
	 *
	 * @param mixed $f The file handle
	 * @param int $length Length in bytes to read.
	 * @param int $offset The optional offset.
	 * @return mixed String of data or false on error.
	 */
	abstract public function read($f, $length, $offset = 0);

	/**
	 * Seek a given position within a file handle.
	 *
	 * @param mixed $f The file handle.
	 * @param int $position The position.
	 */
	abstract public function seek($f, $position);

	/**
	 * Return a whether the end of a file has been reached.
	 *
	 * @param mixed $f The file handle.
	 * @return boolean
	 */
	abstract public function eof($f);

	/**
	 * Return the current position in an open file.
	 *
	 * @param mixed $f The file handle.
	 * @return int
	 */
	abstract public function tell($f);

	/**
	 * Close a given file handle.
	 *
	 * @param mixed $f
	 */
	abstract public function close($f);

	/**
	 * Delete the file associated with a given file handle.
	 *
	 * @param ElggFile $file
	 */
	abstract public function delete(ElggFile $file);

	/**
	 * Return the size in bytes for a given file.
	 *
	 * @param ElggFile $file
	 */
	abstract public function getFileSize(ElggFile $file);

	/**
	 * Return the filename of a given file as stored on the filestore.
	 *
	 * @param ElggFile $file
	 */
	abstract public function getFilenameOnFilestore(ElggFile $file);

	/**
	 * Get the filestore's creation parameters as an associative array.
	 * Used for serialisation and for storing the creation details along side a file object.
	 *
	 * @return array
	 */
	abstract public function getParameters();

	/**
	 * Set the parameters from the associative array produced by $this->getParameters().
	 */
	abstract public function setParameters(array $parameters);

	/**
	 * Get the contents of the whole file.
	 *
	 * @param mixed $file The file handle.
	 * @return mixed The file contents.
	 */
	abstract public function grabFile(ElggFile $file);

	/**
	 * Return whether a file physically exists or not.
	 *
	 * @param ElggFile $file
	 */
	abstract public function exists(ElggFile $file);
}

/**
 * @class ElggDiskFilestore
 * This class uses disk storage to save data.
 * @author Curverider Ltd
 */
class ElggDiskFilestore extends ElggFilestore {
	/**
	 * Directory root.
	 */
	private $dir_root;

	/**
	 * Default depth of file directory matrix
	 */
	private $matrix_depth = 5;

	/**
	 * Construct a disk filestore using the given directory root.
	 *
	 * @param string $directory_root Root directory, must end in "/"
	 */
	public function __construct($directory_root = "") {
		global $CONFIG;

		if ($directory_root) {
			$this->dir_root = $directory_root;
		} else {
			$this->dir_root = $CONFIG->dataroot;
		}
	}

	public function open(ElggFile $file, $mode) {
		$fullname = $this->getFilenameOnFilestore($file);

		// Split into path and name
		$ls = strrpos($fullname,"/");
		if ($ls===false) {
			$ls = 0;
		}

		$path = substr($fullname, 0, $ls);
		$name = substr($fullname, $ls);

		// Try and create the directory
		try {
			$this->make_directory_root($path);
		} catch (Exception $e) {

		}

		if (($mode!='write') && (!file_exists($fullname))) {
			return false;
		}

		switch ($mode) {
			case "read" :
				$mode = "r+b";
				break;
			case "write" :
				$mode = "w+b";
				break;
			case "append" :
				$mode = "a+b";
				break;
			default:
				throw new InvalidParameterException(sprintf(elgg_echo('InvalidParameterException:UnrecognisedFileMode'), $mode));
		}

		return fopen($fullname, $mode);

	}

	public function write($f, $data) {
		return fwrite($f, $data);
	}

	public function read($f, $length, $offset = 0) {
		if ($offset) {
			$this->seek($f, $offset);
		}

		return fread($f, $length);
	}

	public function close($f) {
		return fclose($f);
	}

	public function delete(ElggFile $file) {
		$filename = $this->getFilenameOnFilestore($file);
		if (file_exists($filename)) {
			return unlink($filename);
		} else {
			return true;
		}
	}

	public function seek($f, $position) {
		return fseek($f, $position);
	}

	public function tell($f) {
		return ftell($f);
	}

	public function eof($f) {
		return feof($f);
	}

	public function getFileSize(ElggFile $file) {
		return filesize($this->getFilenameOnFilestore($file));
	}

	public function getFilenameOnFilestore(ElggFile $file) {
		$owner = $file->getOwnerEntity();
		if (!$owner) {
			$owner = get_loggedin_user();
		}

		if ((!$owner) || (!$owner->username)) {
			throw new InvalidParameterException(sprintf(elgg_echo('InvalidParameterException:MissingOwner'), $file->getFilename(), $file->guid));
		}

		return $this->dir_root . $this->make_file_matrix($owner->guid) . $file->getFilename();
	}

	public function grabFile(ElggFile $file) {
		return file_get_contents($file->getFilenameOnFilestore());
	}

	public function exists(ElggFile $file) {
		return file_exists($this->getFilenameOnFilestore($file));
	}

	public function getSize($prefix,$container_guid) {
		if ($container_guid) {
			return get_dir_size($this->dir_root.$this->make_file_matrix($container_guid).$prefix);
		} else {
			return false;
		}
	}

	/**
	 * Make the directory root.
	 *
	 * @param string $dirroot
	 */
	protected function make_directory_root($dirroot) {
		if (!file_exists($dirroot)) {
			if (!@mkdir($dirroot, 0700, true)) {
				throw new IOException(sprintf(elgg_echo('IOException:CouldNotMake'), $dirroot));
			}
		}

		return true;
	}

	/**
	 * Multibyte string tokeniser.
	 *
	 * Splits a string into an array. Will fail safely if mbstring is not installed (although this may still
	 * not handle .
	 *
	 * @param string $string String
	 * @param string $charset The charset, defaults to UTF8
	 * @return array
	 */
	private function mb_str_split($string, $charset = 'UTF8') {
		if (is_callable('mb_substr')) {
			$length = mb_strlen($string);
			$array = array();

			while ($length) {
				$array[] = mb_substr($string, 0, 1, $charset);
				$string = mb_substr($string, 1, $length, $charset);

				$length = mb_strlen($string);
			}

			return $array;
		} else {
			return str_split($string);
		}

		return false;
	}

	/**
	 * Construct the filename matrix.
	 *
	 * @param int | string $identifier
	 * @return str
	 */
	protected function make_file_matrix($identifier) {
		if (is_numeric($identifier)) {
			return $this->user_file_matrix($identifier);
		}

		return $this->deprecated_file_matrix($identifier);
	}

	/**
	 * Construct the filename matrix with user info
	 *
	 * This method will generate a matrix using the entity's creation time and
	 * unique guid. This is intended only to determine a user's data directory.
	 *
	 * @param int $guid
	 * @return str
	 */
	protected function user_file_matrix($guid) {
		// lookup the entity
		$user = get_entity($guid);
		if ($user->type != 'user')
		{
			// only to be used for user directories
			return FALSE;
		}

		if (!$user->time_created) {
			// fall back to deprecated method
			return $this->deprecated_file_matrix($user->username);
		}

		$time_created = date('Y/m/d', $user->time_created);
		return "$time_created/$user->guid/";
	}

	/**
	 * Construct the filename matrix using a string
	 *
	 * Particularly, this is used with a username to generate the file storage
	 * location.
	 *
	 * @deprecated for user directories: use user_file_matrix() instead.
	 *
	 * @param str $filename
	 * @return str
	 */
	protected function deprecated_file_matrix($filename) {
		// throw a warning for using deprecated method
		$error  = 'Deprecated use of ElggDiskFilestore::make_file_matrix. ';
		$error .= 'Username passed instead of guid.';
		elgg_log($error, WARNING);

		$user = new ElggUser($filename);
		return $this->user_file_matrix($user->guid);
	}

	public function getParameters() {
		return array("dir_root" => $this->dir_root);
	}

	public function setParameters(array $parameters) {
		if (isset($parameters['dir_root'])) {
			$this->dir_root = $parameters['dir_root'];
			return true;
		}

		return false;
	}
}

/**
 * @class ElggFile
 * This class represents a physical file.
 *
 * Usage:
 *		Create a new ElggFile object and specify a filename, and optionally a FileStore (if one isn't specified
 *		then the default is assumed.
 *
 * 		Open the file using the appropriate mode, and you will be able to read and write to the file.
 *
 * 		Optionally, you can also call the file's save() method, this will turn the file into an entity in the
 * 		system and permit you to do things like attach tags to the file etc. This is not done automatically since
 * 		there are many occasions where you may want access to file data on datastores using the ElggFile interface
 * 		but do not want to create an Entity reference to it in the system (temporary files for example).
 *
 * @author Curverider Ltd
 */
class ElggFile extends ElggObject {
	/** Filestore */
	private $filestore;

	/** File handle used to identify this file in a filestore. Created by open. */
	private $handle;

	protected function initialise_attributes() {
		parent::initialise_attributes();

		$this->attributes['subtype'] = "file";
	}

	public function __construct($guid = null) {
		parent::__construct($guid);

		// Set default filestore
		$this->filestore = $this->getFilestore();
	}

	/**
	 * Set the filename of this file.
	 *
	 * @param string $name The filename.
	 */
	public function setFilename($name) {
		$this->filename = $name;
	}

	/**
	 * Return the filename.
	 */
	public function getFilename() {
		return $this->filename;
	}

	/**
	 * Return the filename of this file as it is/will be stored on the filestore, which may be different
	 * to the filename.
	 */
	public function getFilenameOnFilestore() {
		return $this->filestore->getFilenameOnFilestore($this);
	}

	/*
	 * Return the size of the filestore associated with this file
	 *
	 */
	public function getFilestoreSize($prefix='',$container_guid=0) {
		if (!$container_guid) {
			$container_guid = $this->container_guid;
		}
		$fs = $this->getFilestore();
		return $fs->getSize($prefix,$container_guid);
	}

	/**
	 * Get the mime type of the file.
	 */
	public function getMimeType() {
		if ($this->mimetype) {
			return $this->mimetype;
		}

		// TODO : Guess mimetype if not here
	}

	/**
	 * Set the mime type of the file.
	 *
	 * @param $mimetype The mimetype
	 */
	public function setMimeType($mimetype) {
		return $this->mimetype = $mimetype;
	}

	/**
	 * Set the optional file description.
	 *
	 * @param string $description The description.
	 */
	public function setDescription($description) {
		$this->description = $description;
	}

	/**
	 * Open the file with the given mode
	 *
	 * @param string $mode Either read/write/append
	 */
	public function open($mode) {
		if (!$this->getFilename()) {
			throw new IOException(elgg_echo('IOException:MissingFileName'));
		}

		// See if file has already been saved
		// seek on datastore, parameters and name?

		// Sanity check
		if (
			($mode!="read") &&
			($mode!="write") &&
			($mode!="append")
		) {
			throw new InvalidParameterException(sprintf(elgg_echo('InvalidParameterException:UnrecognisedFileMode'), $mode));
		}

		// Get the filestore
		$fs = $this->getFilestore();

		// Ensure that we save the file details to object store
		//$this->save();

		// Open the file handle
		$this->handle = $fs->open($this, $mode);

		return $this->handle;
	}

	/**
	 * Write some data.
	 *
	 * @param string $data The data
	 */
	public function write($data) {
		$fs = $this->getFilestore();

		return $fs->write($this->handle, $data);
	}

	/**
	 * Read some data.
	 *
	 * @param int $length Amount to read.
	 * @param int $offset The offset to start from.
	 */
	public function read($length, $offset = 0) {
		$fs = $this->getFilestore();

		return $fs->read($this->handle, $length, $offset);
	}

	/**
	 * Gets the full contents of this file.
	 *
	 * @return mixed The file contents.
	 */
	public function grabFile() {
		$fs = $this->getFilestore();
		return $fs->grabFile($this);
	}

	/**
	 * Close the file and commit changes
	 */
	public function close() {
		$fs = $this->getFilestore();

		if ($fs->close($this->handle)) {
			$this->handle = NULL;

			return true;
		}

		return false;
	}

	/**
	 * Delete this file.
	 */
	public function delete() {
		$fs = $this->getFilestore();
		if ($fs->delete($this)) {
			return parent::delete();
		}
	}

	/**
	 * Seek a position in the file.
	 *
	 * @param int $position
	 */
	public function seek($position) {
		$fs = $this->getFilestore();

		return $fs->seek($this->handle, $position);
	}

	/**
	 * Return the current position of the file.
	 *
	 * @return int The file position
	 */
	public function tell() {
		$fs = $this->getFilestore();

		return $fs->tell($this->handle);
	}

	/**
	 * Return the size of the file in bytes.
	 */
	public function size() {
		return $this->filestore->getFileSize($this);
	}

	/**
	 * Return a boolean value whether the file handle is at the end of the file
	 */
	public function eof() {
		$fs = $this->getFilestore();

		return $fs->eof($this->handle);
	}

	public function exists() {
		$fs = $this->getFilestore();

		return $fs->exists($this);
	}

	/**
	 * Set a filestore.
	 *
	 * @param ElggFilestore $filestore The file store.
	 */
	public function setFilestore(ElggFilestore $filestore) {
		$this->filestore = $filestore;
	}

	/**
	 * Return a filestore suitable for saving this file.
	 * This filestore is either a pre-registered filestore, a filestore loaded from metatags saved
	 * along side this file, or the system default.
	 */
	protected function getFilestore() {
		// Short circuit if already set.
		if ($this->filestore) {
			return $this->filestore;
		}

		// If filestore meta set then retrieve filestore TODO: Better way of doing this?
		$metas = get_metadata_for_entity($this->guid);
		$parameters = array();
		if (is_array($metas)) {
			foreach ($metas as $meta) {
				if (strpos($meta->name, "filestore::")!==false) {
					// Filestore parameter tag
					$comp = explode("::", $meta->name);
					$name = $comp[1];

					$parameters[$name] = $meta->value;
				}
			}
		}

		// If parameters loaded then create new filestore
		if (count($parameters)!=0) {
			// Create new filestore object
			if ((!isset($parameters['filestore'])) || (!class_exists($parameters['filestore']))) {
				throw new ClassNotFoundException(elgg_echo('ClassNotFoundException:NotFoundNotSavedWithFile'));
			}

			$this->filestore = new $parameters['filestore']();

			// Set parameters
			$this->filestore->setParameters($parameters);
		}


		// if still nothing then set filestore to default
		if (!$this->filestore) {
			$this->filestore = get_default_filestore();
		}

		return $this->filestore;
	}

	public function save() {
		if (!parent::save()) {
			return false;
		}

		// Save datastore metadata
		$params = $this->filestore->getParameters();
		foreach ($params as $k => $v) {
			$this->setMetaData("filestore::$k", $v);
		}

		// Now make a note of the filestore class
		$this->setMetaData("filestore::filestore", get_class($this->filestore));

		return true;
	}
}

/**
 * Get the size of the specified directory.
 *
 * @param string $dir The full path of the directory
 * @return int The size of the directory.
 */
function get_dir_size($dir, $totalsize = 0){
	$handle = @opendir($dir);
	while ($file = @readdir ($handle)){
		if (eregi("^\.{1,2}$", $file)) {
			continue;
		}
		if(is_dir($dir . $file)) {
			$totalsize = get_dir_size($dir . $file . "/", $totalsize);
		} else{
			$totalsize += filesize($dir . $file);
		}
	}
	@closedir($handle);

	return($totalsize);
}

/**
 * Get the contents of an uploaded file.
 * (Returns false if there was an issue.)
 *
 * @param string $input_name The name of the file input field on the submission form
 * @return mixed|false The contents of the file, or false on failure.
 */
function get_uploaded_file($input_name) {
	// If the file exists ...
	if (isset($_FILES[$input_name]) && $_FILES[$input_name]['error'] == 0) {
		return file_get_contents($_FILES[$input_name]['tmp_name']);
	}
	return false;
}

/**
 * Gets the jpeg contents of the resized version of an uploaded image
 * (Returns false if the uploaded file was not an image)
 *
 * @param string $input_name The name of the file input field on the submission form
 * @param int $maxwidth The maximum width of the resized image
 * @param int $maxheight The maximum height of the resized image
 * @param true|false $square If set to true, will take the smallest of maxwidth and maxheight and use it to set the dimensions on all size; the image will be cropped.
 * @return false|mixed The contents of the resized image, or false on failure
 */
function get_resized_image_from_uploaded_file($input_name, $maxwidth, $maxheight, $square = false) {
	// If our file exists ...
	if (isset($_FILES[$input_name]) && $_FILES[$input_name]['error'] == 0) {
		return get_resized_image_from_existing_file($_FILES[$input_name]['tmp_name'], $maxwidth, $maxheight, $square);
	}

	return false;
}

/**
 * Gets the jpeg contents of the resized version of an already uploaded image
 * (Returns false if the file was not an image)
 *
 * @param string $input_name The name of the file on the disk
 * @param int $maxwidth The desired width of the resized image
 * @param int $maxheight The desired height of the resized image
 * @param true|false $square If set to true, takes the smallest of maxwidth and
 * 			maxheight and use it to set the dimensions on the new image. If no
 * 			crop parameters are set, the largest square that fits in the image
 * 			centered will be used for the resize. If square, the crop must be a
 * 			square region.
 * @param int $x1 x coordinate for top, left corner
 * @param int $y1 y coordinate for top, left corner
 * @param int $x2 x coordinate for bottom, right corner
 * @param int $y2 y coordinate for bottom, right corner
 * @param bool $upscale Resize images smaller than $maxwidth x $maxheight?
 * @return false|mixed The contents of the resized image, or false on failure
 */
function get_resized_image_from_existing_file($input_name, $maxwidth, $maxheight, $square = FALSE, $x1 = 0, $y1 = 0, $x2 = 0, $y2 = 0, $upscale = FALSE) {
	// Get the size information from the image
	$imgsizearray = getimagesize($input_name);
	if ($imgsizearray == FALSE) {
		return FALSE;
	}

	// Get width and height
	$width = $imgsizearray[0];
	$height = $imgsizearray[1];

	// make sure we can read the image
	$accepted_formats = array(
		'image/jpeg' => 'jpeg',
		'image/pjpeg' => 'jpeg',
		'image/png' => 'png',
		'image/x-png' => 'png',
		'image/gif' => 'gif'
	);

	// make sure the function is available
	$load_function = "imagecreatefrom" . $accepted_formats[$imgsizearray['mime']];
	if (!is_callable($load_function)) {
		return FALSE;
	}

	// crop image first?
	$crop = TRUE;
	if ($x1 == 0 && $y1 == 0 && $x2 == 0 && $y2 == 0) {
		$crop = FALSE;
	}

	// how large a section of the image has been selected
	if ($crop) {
		$region_width = $x2 - $x1;
		$region_height = $y2 - $y1;
	} else {
		// everything selected if no crop parameters
		$region_width = $width;
		$region_height = $height;
	}

	// determine cropping offsets
	if ($square) {
		// asking for a square image back

		// detect case where someone is passing crop parameters that are not for a square
		if ($crop == TRUE && $region_width != $region_height) {
			return FALSE;
		}

		// size of the new square image
		$new_width = $new_height = min($maxwidth, $maxheight);

		// find largest square that fits within the selected region
		$region_width = $region_height = min($region_width, $region_height);

		// set offsets for crop
		if ($crop) {
			$widthoffset = $x1;
			$heightoffset = $y1;
			$width = $x2 - $x1;
			$height = $width;
		} else {
			// place square region in the center
			$widthoffset = floor(($width - $region_width) / 2);
			$heightoffset = floor(($height - $region_height) / 2);
		}
	} else {
		// non-square new image

		$new_width = $maxwidth;
		$new_height = $maxwidth;

		// maintain aspect ratio of original image/crop
		if (($region_height / (float)$new_height) > ($region_width / (float)$new_width)) {
			$new_width = floor($new_height * $region_width / (float)$region_height);
		} else {
			$new_height = floor($new_width * $region_height / (float)$region_width);
		}

		// by default, use entire image
		$widthoffset = 0;
		$heightoffset = 0;

		if ($crop) {
			$widthoffset = $x1;
			$heightoffset = $y1;
		}
	}

	// check for upscaling
	// @todo This ignores squares, coordinates, and cropping. It's probably not the best idea.
	// Size checking should be done in action code, but for backward compatibility
	// this duplicates the previous behavior.
	if (!$upscale && ($height < $new_height || $width < $new_width)) {
		// determine if we can scale it down at all
		// (ie, if only one dimension is too small)
		// if not, just use original size.
		if ($height < $new_height && $width < $new_width) {
			$ratio = 1;
		} elseif ($height < $new_height) {
			$ratio = $new_width / $width;
		} elseif ($width < $new_width) {
			$ratio = $new_height / $height;
		}

		$new_height = floor($height * $ratio);
		$new_width = floor($width * $ratio);
	}

	// load original image
	$orig_image = $load_function($input_name);
	if (!$orig_image) {
		return FALSE;
	}

	// allocate the new image
	$newimage = imagecreatetruecolor($new_width, $new_height);
	if (!$newimage) {
		return FALSE;
	}

	// create the new image
	$rtn_code = imagecopyresampled(	$newimage,
									$orig_image,
									0,
									0,
									$widthoffset,
									$heightoffset,
									$new_width,
									$new_height,
									$region_width,
									$region_height );
	if (!$rtn_code) {
		return FALSE;
	}

	// grab contents for return
	ob_start();
	imagejpeg($newimage, null, 90);
	$jpeg = ob_get_clean();

	imagedestroy($newimage);
	imagedestroy($orig_image);

	return $jpeg;
}


// putting these here for now
function file_delete($guid) {
	if ($file = get_entity($guid)) {
		if ($file->canEdit()) {
			$container = get_entity($file->container_guid);

			$thumbnail = $file->thumbnail;
			$smallthumb = $file->smallthumb;
			$largethumb = $file->largethumb;
			if ($thumbnail) {
				$delfile = new ElggFile();
				$delfile->owner_guid = $file->owner_guid;
				$delfile->setFilename($thumbnail);
				$delfile->delete();
			}
			if ($smallthumb) {
				$delfile = new ElggFile();
				$delfile->owner_guid = $file->owner_guid;
				$delfile->setFilename($smallthumb);
				$delfile->delete();
			}
			if ($largethumb) {
				$delfile = new ElggFile();
				$delfile->owner_guid = $file->owner_guid;
				$delfile->setFilename($largethumb);
				$delfile->delete();
			}

			return $file->delete();
		}
	}

	return false;
}

/**
 * Returns an overall file type from the mimetype
 *
 * @param string $mimetype The MIME type
 * @return string The overall type
 */
function file_get_general_file_type($mimetype) {
	switch($mimetype) {

		case "application/msword":
			return "document";
			break;
		case "application/pdf":
			return "document";
			break;
	}

	if (substr_count($mimetype,'text/')) {
		return "document";
	}

	if (substr_count($mimetype,'audio/')) {
		return "audio";
	}

	if (substr_count($mimetype,'image/')) {
		return "image";
	}

	if (substr_count($mimetype,'video/')) {
		return "video";
	}

	if (substr_count($mimetype,'opendocument')) {
		return "document";
	}

	return "general";
}

function file_handle_upload($prefix,$subtype,$plugin) {
	$desc = get_input("description");
	$tags = get_input("tags");
	$tags = explode(",", $tags);
	$folder = get_input("folder_text");
	if (!$folder) {
		$folder = get_input("folder_select");
	}
	$access_id = (int) get_input("access_id");
	$container_guid = (int) get_input('container_guid', 0);
	if (!$container_guid) {
		$container_guid == get_loggedin_userid();
	}

	// Extract file from, save to default filestore (for now)

	// see if a plugin has set a quota for this user
	$file_quota = trigger_plugin_hook("$plugin:quotacheck",'user',array('container_guid'=>$container_guid));
	if (!$file_quota) {
		// no, see if there is a generic quota set
		$file_quota = get_plugin_setting('quota', $plugin);
	}
	if ($file_quota) {
		// convert to megabytes
		$file_quota = $file_quota*1000*1024;
	}

	// handle uploaded files
	$number_of_files = get_input('number_of_files',0);
	$quota_exceeded = false;
	$bad_mime_type = false;

	for ($i = 0; $i < $number_of_files; $i++) {
		$title = get_input("title_".$i);
		$uploaded = $_FILES["upload_".$i];
		if (!$uploaded || !$uploaded['name']) {
			// no such file, so skip it
			continue;
		}
		if ($plugin == "photo") {
			// do a mime type test
			if (in_array($uploaded['type'],array('image/jpeg','image/gif','image/png','image/jpg','image/jpe','image/pjpeg','image/x-png'))) {
				$file = new PhotoPluginFile();
			} else {
				$bad_mime_type = true;
				break;
			}
		} else {
			$file = new FilePluginFile();
		}
		$dir_size = $file->getFilestoreSize($prefix,$container_guid);
		$filestorename = strtolower(time().$uploaded['name']);
		$file->setFilename($prefix.$filestorename);
		$file->setMimeType($uploaded['type']);

		$file->originalfilename = $uploaded['name'];

		$file->subtype = $subtype;

		$file->access_id = $access_id;

		$uf = get_uploaded_file('upload_'.$i);

		if ($file_quota) {
			$file_size = strlen($uf);
			if (($dir_size + $file_size) > $file_quota) {
				$quota_exceeded = true;
			}
		}

		if (!$quota_exceeded) {
			// all clear, so try to save the data

			$file->open("write");
			$file->write($uf);
			$file->close();

			$file->title = $title;
			$file->description = $desc;
			if ($container_guid) {
				$file->container_guid = $container_guid;
			}

			// Save tags
			$file->tags = $tags;

			$file->simpletype = file_get_general_file_type($uploaded['type']);
			$file->folder = $folder;

			$result = $file->save();

			if ($result) {

				// Generate thumbnail (if image)
				if (substr_count($file->getMimeType(),'image/')) {
					$thumbnail = get_resized_image_from_existing_file($file->getFilenameOnFilestore(),60,60, true);
					$thumbsmall = get_resized_image_from_existing_file($file->getFilenameOnFilestore(),153,153, true);
					$thumblarge = get_resized_image_from_existing_file($file->getFilenameOnFilestore(),600,600, false);
					if ($thumbnail) {
						$thumb = new ElggFile();
						$thumb->setMimeType($uploaded['type']);

						$thumb->setFilename($prefix."thumb".$filestorename);
						$thumb->open("write");
						$thumb->write($thumbnail);
						$thumb->close();

						$file->thumbnail = $prefix."thumb".$filestorename;

						$thumb->setFilename($prefix."smallthumb".$filestorename);
						$thumb->open("write");
						$thumb->write($thumbsmall);
						$thumb->close();
						$file->smallthumb = $prefix."smallthumb".$filestorename;

						$thumb->setFilename($prefix."largethumb".$filestorename);
						$thumb->open("write");
						$thumb->write($thumblarge);
						$thumb->close();
						$file->largethumb = $prefix."largethumb".$filestorename;
					}
				}

				// add to this user's file folders
				file_add_to_folders($folder,$container_guid,$plugin);

				add_to_river("river/object/$plugin/create",'create',$_SESSION['user']->guid,$file->guid);
			} else {
				break;
			}
		} else {
			break;
		}
	}

	if ($quota_exceeded) {
		echo elgg_echo("$plugin:quotaexceeded");
	} else if ($bad_mime_type)	{
		echo elgg_echo("$plugin:badmimetype");
	} else if ($result) {
		if ($number_of_files > 1) {
			echo elgg_echo("$plugin:saved_multi");
		} else {
			echo elgg_echo("$plugin:saved");
		}
	} else {
		if ($number_of_files > 1) {
			echo elgg_echo("$plugin:uploadfailed_multi");
		} else {
			echo elgg_echo("$plugin:uploadfailed");
		}
	}
}

function file_add_to_folders($folder,$container_guid,$plugin) {
	if ($container_guid && ($container = get_entity($container_guid))) {
		$folder_field_name = 'elgg_'.$plugin.'_folders';
		$folders = $container->$folder_field_name;
		if ($folders) {
			if (is_array($folders)) {
				if (!in_array($folder,$folders)) {
					$folders[] = $folder;
					$container->$folder_field_name = $folders;
				}
			} else {
				if ($folders != $folder) {
					$container->$folder_field_name = array($folders,$folder);
				}
			}
		} else {
			$container->$folder_field_name = $folder;
		}
	}
}

function file_handle_save($forward,$plugin) {
	// Get variables
	$title = get_input("title");
	$desc = get_input("description");
	$tags = get_input("tags");
	$folder = get_input("folder_text");
	if (!$folder) {
		$folder = get_input("folder_select");
	}
	$access_id = (int) get_input("access_id");

	$guid = (int) get_input('file_guid');

	if (!$file = get_entity($guid)) {
		register_error(elgg_echo("$plugin:uploadfailed"));
		forward($forward . $_SESSION['user']->username);
		exit;
	}

	$result = false;

	$container_guid = $file->container_guid;
	$container = get_entity($container_guid);

	if ($file->canEdit()) {
		$file->access_id = $access_id;
		$file->title = $title;
		$file->description = $desc;
		$file->folder = $folder;
		// add to this user's file folders
		file_add_to_folders($folder,$container_guid,$plugin);

		// Save tags
		$tags = explode(",", $tags);
		$file->tags = $tags;

		$result = $file->save();
	}

	if ($result) {
		system_message(elgg_echo("$plugin:saved"));
	} else {
		register_error(elgg_echo("$plugin:uploadfailed"));
	}
	forward($forward . $container->username);
}

/**
 * Manage a file download.
 *
 * @param unknown_type $plugin
 * @param unknown_type $file_guid If not specified then file_guid will be found in input.
 */
function file_manage_download($plugin, $file_guid = "") {
	// Get the guid
	$file_guid = (int)$file_guid;

	if (!$file_guid) {
		$file_guid = (int)get_input("file_guid");
	}

	// Get the file
	$file = get_entity($file_guid);

	if ($file) {
		$mime = $file->getMimeType();
		if (!$mime) {
			$mime = "application/octet-stream";
		}

		$filename = $file->originalfilename;

		header("Content-type: $mime");
		if (strpos($mime, "image/")!==false) {
			header("Content-Disposition: inline; filename=\"$filename\"");
		} else {
			header("Content-Disposition: attachment; filename=\"$filename\"");
		}

		echo $file->grabFile();
		exit;
	} else {
		register_error(elgg_echo("$plugin:downloadfailed"));
	}
}

/**
 * Manage the download of a file icon.
 *
 * @param unknown_type $plugin
 * @param unknown_type $file_guid The guid, if not specified this is obtained from the input.
 */
function file_manage_icon_download($plugin, $file_guid = "") {
	// Get the guid
	$file_guid = (int)$file_guid;

	if (!$file_guid) {
		$file_guid = (int)get_input("file_guid");
	}

	// Get the file
	$file = get_entity($file_guid);

	if ($file) {
		$mime = $file->getMimeType();
		if (!$mime) {
			$mime = "application/octet-stream";
		}

		$filename = $file->thumbnail;

		header("Content-type: $mime");
		if (strpos($mime, "image/")!==false) {
			header("Content-Disposition: inline; filename=\"$filename\"");
		} else {
			header("Content-Disposition: attachment; filename=\"$filename\"");
		}

		$readfile = new ElggFile();
		$readfile->owner_guid = $file->owner_guid;
		$readfile->setFilename($filename);

		/*
		if ($file->open("read"));
		{
			while (!$file->eof())
			{
				echo $file->read(10240, $file->tell());
			}
		}
		*/

		$contents = $readfile->grabFile();
		if (empty($contents)) {
			echo file_get_contents(dirname(dirname(__FILE__)) . "/graphics/icons/general.jpg" );
		} else {
			echo $contents;
		}
		exit;
	} else {
		register_error(elgg_echo("$plugin:downloadfailed"));
	}
}

function file_display_thumbnail($file_guid,$size) {
	// Get file entity
	if ($file = get_entity($file_guid)) {
		$simpletype = $file->simpletype;
		if ($simpletype == "image") {
			// Get file thumbnail
			if ($size == "small") {
				$thumbfile = $file->smallthumb;
			} else {
				$thumbfile = $file->largethumb;
			}

			// Grab the file
			if ($thumbfile && !empty($thumbfile)) {
				$readfile = new ElggFile();
				$readfile->owner_guid = $file->owner_guid;
				$readfile->setFilename($thumbfile);
				$mime = $file->getMimeType();
				$contents = $readfile->grabFile();

				header("Content-type: $mime");
				echo $contents;
				exit;
			}
		}
	}
}

function file_set_page_owner($file) {
	$page_owner = page_owner_entity();
	if ($page_owner === false || is_null($page_owner)) {
		$container_guid = $file->container_guid;
		if (!empty($container_guid)) {
			if ($page_owner = get_entity($container_guid)) {
				set_page_owner($page_owner->guid);
			}
		}

		if (empty($page_owner)) {
			$page_owner = $_SESSION['user'];
			set_page_owner($_SESSION['guid']);
		}
	}
}

/**
 * Recursively delete a directory
 *
 * @param str $directory
 */
function delete_directory($directory) {
	// sanity check: must be a directory
	if (!$handle = opendir($directory)) {
		return FALSE;
	}

	// loop through all files
	while (($file = readdir($handle)) !== FALSE) {
		if (in_array($file, array('.', '..'))) {
			continue;
		}

		$path = "$directory/$file";
		if (is_dir($path)) {
			// recurse down through directory
			if (!delete_directory($path)) {
				return FALSE;
			}
		} else {
			// delete file
			unlink($path);
		}
	}

	// remove empty directory
	closedir($handle);
	return rmdir($directory);
}

/**
 * Removes all user files
 *
 * @param ElggUser $user
 * @return void
 */
function clear_user_files($user) {
	global $CONFIG;

	$time_created = date('Y/m/d', $user->time_created);
	$file_path = "$CONFIG->dataroot$time_created/$user->guid";
	if (file_exists($file_path)) {
		delete_directory($file_path);
	}
}


/// Variable holding the default datastore
$DEFAULT_FILE_STORE = NULL;

/**
 * Return the default filestore.
 *
 * @return ElggFilestore
 */
function get_default_filestore() {
	global $DEFAULT_FILE_STORE;

	return $DEFAULT_FILE_STORE;
}

/**
 * Set the default filestore for the system.
 */
function set_default_filestore(ElggFilestore $filestore) {
	global $DEFAULT_FILE_STORE;

	$DEFAULT_FILE_STORE = $filestore;

	return true;
}

/**
 * Run once and only once.
 */
function filestore_run_once() {
	// Register a class
	add_subtype("object", "file", "ElggFile");
}

/**
 * Initialise the file modules.
 * Listens to system boot and registers any appropriate file types and classes
 */
function filestore_init() {
	global $CONFIG;

	// Now register a default filestore
	set_default_filestore(new ElggDiskFilestore($CONFIG->dataroot));

	// Now run this stuff, but only once
	run_function_once("filestore_run_once");
}

// Register a startup event
register_elgg_event_handler('init', 'system', 'filestore_init', 100);

// Unit testing
register_plugin_hook('unit_test', 'system', 'filestore_test');
function filestore_test($hook, $type, $value, $params) {
	global $CONFIG;
	$value[] = "{$CONFIG->path}engine/tests/objects/filestore.php";
	return $value;
}