aboutsummaryrefslogtreecommitdiffstats
path: root/include/attach.php
blob: 40410d41ec01ed713ee3d320fc86da0f13bc49ea (plain) (blame)
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
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
<?php
/**
 * @file include/attach.php
 *
 * @brief File/attach API with the potential for revision control.
 *
 * @TODO A filesystem storage abstraction which maintains security (and 'data'
 * contains a system filename which is inaccessible from the web). This could
 * get around PHP storage limits and store videos and larger items, using fread
 * or OS methods or native code to read/write or chunk it through.
 * @todo Also an 'append' option to the storage function might be a useful addition.
 */

require_once('include/permissions.php');
require_once('include/security.php');
require_once('include/group.php');

/**
 * @brief Guess the mimetype from file ending.
 *
 * This function takes a file name and guess the mimetype from the
 * filename extension.
 *
 * @param $filename a string filename
 * @return string The mimetype according to a file ending.
 */
function z_mime_content_type($filename) {

	$mime_types = array(

	'txt' => 'text/plain',
	'htm' => 'text/html',
	'html' => 'text/html',
	'php' => 'text/html',
	'css' => 'text/css',
	'js' => 'application/javascript',
	'json' => 'application/json',
	'xml' => 'application/xml',
	'swf' => 'application/x-shockwave-flash',
	'flv' => 'video/x-flv',
	'epub' => 'application/epub+zip',

	// images
	'png' => 'image/png',
	'jpe' => 'image/jpeg',
	'jpeg' => 'image/jpeg',
	'jpg' => 'image/jpeg',
	'gif' => 'image/gif',
	'bmp' => 'image/bmp',
	'ico' => 'image/vnd.microsoft.icon',
	'tiff' => 'image/tiff',
	'tif' => 'image/tiff',
	'svg' => 'image/svg+xml',
	'svgz' => 'image/svg+xml',

	// archives
	'zip' => 'application/zip',
	'rar' => 'application/x-rar-compressed',
	'exe' => 'application/x-msdownload',
	'msi' => 'application/x-msdownload',
	'cab' => 'application/vnd.ms-cab-compressed',

	// audio/video
	'mp3' => 'audio/mpeg',
	'wav' => 'audio/wav',
	'qt' => 'video/quicktime',
	'mov' => 'video/quicktime',
	'ogg' => 'audio/ogg',
	'ogv' => 'video/ogg',
	'ogx' => 'application/ogg',
	'flac' => 'audio/flac',
	'opus' => 'audio/ogg',
	'webm' => 'video/webm',
//	'webm' => 'audio/webm',
	'mp4' => 'video/mp4',
//	'mp4' => 'audio/mp4',

	// adobe
	'pdf' => 'application/pdf',
	'psd' => 'image/vnd.adobe.photoshop',
	'ai' => 'application/postscript',
	'eps' => 'application/postscript',
	'ps' => 'application/postscript',

	// ms office
	'doc' => 'application/msword',
	'rtf' => 'application/rtf',
	'xls' => 'application/vnd.ms-excel',
	'ppt' => 'application/vnd.ms-powerpoint',

	// open office
	'odt' => 'application/vnd.oasis.opendocument.text',
	'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
	'odp' => 'application/vnd.oasis.opendocument.presentation',
	'odg' => 'application/vnd.oasis.opendocument.graphics',
	'odc' => 'application/vnd.oasis.opendocument.chart',
	'odf' => 'application/vnd.oasis.opendocument.formula',
	'odi' => 'application/vnd.oasis.opendocument.image',
	'odm' => 'application/vnd.oasis.opendocument.text-master',
	'odb' => 'application/vnd.oasis.opendocument.base',
	'odb' => 'application/vnd.oasis.opendocument.database',
	'ott' => 'application/vnd.oasis.opendocument.text-template',
	'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
	'otp' => 'application/vnd.oasis.opendocument.presentation-template',
	'otg' => 'application/vnd.oasis.opendocument.graphics-template',
	'otc' => 'application/vnd.oasis.opendocument.chart-template',
	'otf' => 'application/vnd.oasis.opendocument.formula-template',
	'oti' => 'application/vnd.oasis.opendocument.image-template',
	'oth' => 'application/vnd.oasis.opendocument.text-web'
	);

	$last_dot = strrpos($filename, '.');
	if ($last_dot !== false) {
		$ext = strtolower(substr($filename, $last_dot + 1));
		if (array_key_exists($ext, $mime_types)) {
			return $mime_types[$ext];
		}
	}

	return 'application/octet-stream';
}

/**
 * @brief Count files/attachments.
 *
 * @param int $channel_id
 * @param string $observer
 * @param string $hash (optional)
 * @param string $filename (optional)
 * @param string $filetype (optional)
 * @return associative array with:
 *  * \e boolean \b success
 *  * \e int|boolean \b results amount of found results, or false
 *  * \e string \b message with error messages if any
 */
function attach_count_files($channel_id, $observer, $hash = '', $filename = '', $filetype = '') {

	$ret = array('success' => false);

	if(! perm_is_allowed($channel_id, $observer, 'read_storage')) {
		$ret['message'] = t('Permission denied.');
		return $ret;
	}

	require_once('include/security.php');
	$sql_extra = permissions_sql($channel_id);

	if($hash)
		$sql_extra .= protect_sprintf(" and hash = '" . dbesc($hash) . "' ");

	if($filename)
		$sql_extra .= protect_sprintf(" and filename like '@" . dbesc($filename) . "@' ");

	if($filetype)
		$sql_extra .= protect_sprintf(" and filetype like '@" . dbesc($filetype) . "@' ");

	$r = q("select id, uid, folder from attach where uid = %d $sql_extra",
		intval($channel_id)
	);


	$ret['success'] = ((is_array($r)) ? true : false);
	$ret['results'] = ((is_array($r)) ? count($r) : false);

	return $ret;
}

/**
 * @brief Returns a list of files/attachments.
 *
 * @param $channel_id
 * @param $observer
 * @param $hash (optional)
 * @param $filename (optional)
 * @param $filetype (optional)
 * @param $orderby
 * @param $start
 * @param $entries
 * @return associative array with:
 *  * \e boolean \b success
 *  * \e array|boolean \b results array with results, or false
 *  * \e string \b message with error messages if any
 */
function attach_list_files($channel_id, $observer, $hash = '', $filename = '', $filetype = '', $orderby = 'created desc', $start = 0, $entries = 0) {

	$ret = array('success' => false);

	if(! perm_is_allowed($channel_id,$observer, 'view_storage')) {
		$ret['message'] = t('Permission denied.');
		return $ret;
	}

	require_once('include/security.php');
	$sql_extra = permissions_sql($channel_id);

	if($hash)
		$sql_extra .= protect_sprintf(" and hash = '" . dbesc($hash) . "' ");

	if($filename)
		$sql_extra .= protect_sprintf(" and filename like '@" . dbesc($filename) . "@' ");

	if($filetype)
		$sql_extra .= protect_sprintf(" and filetype like '@" . dbesc($filetype) . "@' ");

	if($entries)
		$limit = " limit " . intval($start) . ", " . intval(entries) . " ";

	// Retrieve all columns except 'data'

	$r = q("select id, aid, uid, hash, filename, filetype, filesize, revision, folder, os_storage, is_dir, is_photo, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid from attach where uid = %d $sql_extra ORDER BY $orderby $limit",
		intval($channel_id)
	);

	$ret['success'] = ((is_array($r)) ? true : false);
	$ret['results'] = ((is_array($r)) ? $r : false);

	return $ret;
}

/**
 * @brief Find an attachment by hash and revision.
 *
 * Returns the entire attach structure including data.
 *
 * This could exhaust memory so most useful only when immediately sending the data.
 *
 * @param string $hash
 * @param int $rev Revision
 * @return array
 */
function attach_by_hash($hash, $rev = 0) {

	$ret = array('success' => false);

	// Check for existence, which will also provide us the owner uid

	$sql_extra = '';
	if($rev == (-1))
		$sql_extra = " order by revision desc ";
	elseif($rev)
		$sql_extra = " and revision = " . intval($rev) . " ";

	$r = q("SELECT uid FROM attach WHERE hash = '%s' $sql_extra LIMIT 1",
		dbesc($hash)
	);
	if(! $r) {
		$ret['message'] = t('Item was not found.');
		return $ret;
	}

	if(! perm_is_allowed($r[0]['uid'], get_observer_hash(), 'view_storage')) {
		$ret['message'] = t('Permission denied.');
		return $ret;
	}

	$sql_extra = permissions_sql($r[0]['uid']);

	// Now we'll see if we can access the attachment

	$r = q("SELECT * FROM attach WHERE hash = '%s' and uid = %d $sql_extra LIMIT 1",
		dbesc($hash),
		intval($r[0]['uid'])
	);

	if(! $r) {
		$ret['message'] = t('Permission denied.');
		return $ret;
	}

	if($r[0]['folder']) {
		$x = attach_can_view_folder($r[0]['uid'],get_observer_hash(),$r[0]['folder']);
		if(! $x) {
			$ret['message'] = t('Permission denied.');
			return $ret;
		}
	}

	$ret['success'] = true;
	$ret['data'] = $r[0];

	return $ret;
}

function attach_can_view_folder($uid,$ob_hash,$folder_hash) {

	$sql_extra = permissions_sql($uid,$ob_hash);
	$hash = $folder_hash;	
	$result = false;

	do {
		$r = q("select folder from attach where hash = '%s' and uid = %d $sql_extra",
			dbesc($hash),
			intval($uid)
		);
		if(! $r)
			return false;
		$hash = $r[0]['folder'];
	}
	while($hash);
	return true;
}


/**
 * @brief Find an attachment by hash and revision.
 *
 * Returns the entire attach structure excluding data.
 *
 * @see attach_by_hash()
 * @param $hash
 * @param $rev revision default 0
 * @return associative array with everything except data
 *  * \e boolean \b success boolean true or false
 *  * \e string \b message (optional) only when success is false
 *  * \e array \b data array of attach DB entry without data component
 */
function attach_by_hash_nodata($hash, $rev = 0) {

	$ret = array('success' => false);

	// Check for existence, which will also provide us the owner uid

	$sql_extra = '';
	if($rev == (-1))
		$sql_extra = " order by revision desc ";
	elseif($rev)
		$sql_extra = " and revision = " . intval($rev) . " ";

	$r = q("SELECT uid FROM attach WHERE hash = '%s' $sql_extra LIMIT 1",
		dbesc($hash)
	);
	if(! $r) {
		$ret['message'] = t('Item was not found.');
		return $ret;
	}

	if(! perm_is_allowed($r[0]['uid'],get_observer_hash(),'view_storage')) {
		$ret['message'] = t('Permission denied.');
		return $ret;
	}

	$sql_extra = permissions_sql($r[0]['uid']);

	// Now we'll see if we can access the attachment

	$r = q("select id, aid, uid, hash, creator, filename, filetype, filesize, revision, folder, os_storage, is_photo, is_dir, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid from attach where uid = %d and hash = '%s' $sql_extra limit 1",
		intval($r[0]['uid']),
		dbesc($hash)
	);

	if(! $r) {
		$ret['message'] = t('Permission denied.');
		return $ret;
	}

	if($r[0]['folder']) {
		$x = attach_can_view_folder($r[0]['uid'],get_observer_hash(),$r[0]['folder']);
		if(! $x) {
			$ret['message'] = t('Permission denied.');
			return $ret;
		}
	}


	$ret['success'] = true;
	$ret['data'] = $r[0];

	return $ret;
}

/**
 * @brief Stores an attachment from a POST file upload.
 *
 * This function stores an attachment. It can be a new one, a replacement or a
 * new revision depending on value set in \e $options.
 *
 * @note Requires an input field \e userfile and does not accept multiple files
 * in one request.
 *
 * @param array $channel channel array of owner
 * @param string $observer_hash hash of current observer
 * @param string $options (optional) one of update, replace, revision
 * @param array $arr (optional) associative array
 */

/**
 * A lot going on in this function, and some of it is old cruft and some is new cruft
 * and the entire thing probably needs to be refactored. It started out just storing
 * files, before we had DAV. It was made extensible to do extra stuff like edit an 
 * existing file or optionally store a separate revision using $options to choose between different
 * storage models. Along the way we moved from
 * DB data storage to file system storage. 
 * Then DAV came along and used different upload methods depending on whether the 
 * file was stored as a DAV directory object or updated as a file object. One of these 
 * is essentially an update and the other is basically an upload, but doesn't use the traditional PHP
 * upload workflow. 
 * Then came hubzilla and we tried to merge photo functionality with the file storage. Most of
 * that integration occurs within this function. 
 * This required overlap with the old photo_upload stuff and photo albums were
 * completely different concepts from directories which needed to be reconciled somehow.
 * The old revision stuff is kind of orphaned currently. There's new revision stuff for photos
 * which attaches (2) etc. onto the name, but doesn't integrate with the attach table revisioning.
 * That's where it sits currently. I repeat it needs to be refactored, and this note is here
 * for future explorers and those who may be doing that work to understand where it came
 * from and got to be the monstrosity of tangled unrelated code that it currently is.
 */

function attach_store($channel, $observer_hash, $options = '', $arr = null) {

	require_once('include/photos.php');

	call_hooks('photo_upload_begin',$arr);

	$ret = array('success' => false);
	$channel_id = $channel['channel_id'];
	$sql_options = '';
	$source = (($arr) ? $arr['source'] : '');
	$album = (($arr) ? $arr['album'] : '');
	$newalbum = (($arr) ? $arr['newalbum'] : '');
	$hash = (($arr && $arr['hash']) ? $arr['hash'] : null);
	$upload_path = (($arr && $arr['directory']) ? $arr['directory'] : '');
	$visible = (($arr && $arr['visible']) ? $arr['visible'] : '');

	$observer = array();

	$dosync = ((array_key_exists('nosync',$arr) && $arr['nosync']) ? 0 : 1);

	if($observer_hash) {
		$x = q("select * from xchan where xchan_hash = '%s' limit 1",
			dbesc($observer_hash)
		);
		if($x)
			$observer = $x[0];
	}

	logger('arr: ' . print_r($arr,true), LOGGER_DATA);

	if(! perm_is_allowed($channel_id,$observer_hash, 'write_storage')) {
		$ret['message'] = t('Permission denied.');
		return $ret;
	}

	$str_group_allow   = perms2str($arr['group_allow']); 
	$str_contact_allow = perms2str($arr['contact_allow']);
	$str_group_deny    = perms2str($arr['group_deny']);
	$str_contact_deny  = perms2str($arr['contact_deny']);


	// The 'update' option sets db values without uploading a new attachment
	// 'replace' replaces the existing uploaded data
	// 'revision' creates a new revision with new upload data
	// Default is to upload a new file

	// revise or update must provide $arr['hash'] of the thing to revise/update

	// By default remove $src when finished

	$remove_when_processed = true;

	if($options === 'import') {		
		$src      = $arr['src'];
		$filename = $arr['filename'];
		$filesize = @filesize($src);

		$hash     = $arr['resource_id'];

		if(array_key_exists('hash',$arr))
			$hash = $arr['hash'];
		if(array_key_exists('type',$arr))
			$type = $arr['type'];

		if($arr['preserve_original'])
			$remove_when_processed = false;

		// if importing a directory, just do it now and go home - we're done.

		if(array_key_exists('is_dir',$arr) && intval($arr['is_dir'])) {
			$x = attach_mkdir($channel,$observer_hash,$arr);
			if($x['message'])
				logger('import_directory: ' . $x['message']);
			return;
		}
	}
	elseif($options !== 'update') {
		$f = array('src' => '', 'filename' => '', 'filesize' => 0, 'type' => '');

        call_hooks('photo_upload_file',$f);
		call_hooks('attach_upload_file',$f);

        if (x($f,'src') && x($f,'filesize')) {
            $src      = $f['src'];
            $filename = $f['filename'];
            $filesize = $f['filesize'];
            $type     = $f['type'];

        } else {

			if(! x($_FILES,'userfile')) {
				$ret['message'] = t('No source file.');
				return $ret;
			}

			$src      = $_FILES['userfile']['tmp_name'];
			$filename = basename($_FILES['userfile']['name']);
			$filesize = intval($_FILES['userfile']['size']);
		}
	}

	// AndStatus sends jpegs with a non-standard mimetype
	if($type === 'image/jpg')
		$type = 'image/jpeg';

	$existing_size = 0;

	if($options === 'replace') {
		$x = q("select id, hash, filesize from attach where id = %d and uid = %d limit 1",
			intval($arr['id']),
			intval($channel_id)
		);
		if(! $x) {
			$ret['message'] = t('Cannot locate file to replace');
			return $ret;
		}
		$existing_id = $x[0]['id'];
		$existing_size = intval($x[0]['filesize']);
		$hash = $x[0]['hash'];
	}

	if($options === 'revise' || $options === 'update') {
		$sql_options = " order by revision desc ";
		if($options === 'update' &&  $arr && array_key_exists('revision',$arr))
			$sql_options = " and revision = " . intval($arr['revision']) . " ";

		$x = q("select id, aid, uid, filename, filetype, filesize, hash, revision, folder, os_storage, is_photo, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid from attach where hash = '%s' and uid = %d $sql_options limit 1",
			dbesc($arr['hash']),
			intval($channel_id)
		);
		if(! $x) {
			$ret['message'] = t('Cannot locate file to revise/update');
			return $ret;
		}
		$hash = $x[0]['hash'];
	}



	$def_extension = '';
	$is_photo = 0;
	$gis = @getimagesize($src);
	logger('getimagesize: ' . print_r($gis,true), LOGGER_DATA); 
	if(($gis) && ($gis[2] === IMAGETYPE_GIF || $gis[2] === IMAGETYPE_JPEG || $gis[2] === IMAGETYPE_PNG)) {
		$is_photo = 1;
		if($gis[2] === IMAGETYPE_GIF)
			$def_extension =  '.gif';
		if($gis[2] === IMAGETYPE_JPEG)
			$def_extension =  '.jpg';
		if($gis[2] === IMAGETYPE_PNG)
			$def_extension =  '.png';

	}

	$pathname = '';

	if($is_photo) {
		if($newalbum) {
			$pathname = filepath_macro($newalbum);
		}
		elseif(array_key_exists('folder',$arr)) {
			$x = q("select filename from attach where hash = '%s' and uid = %d limit 1",
				dbesc($arr['folder']),
				intval($channel['channel_id'])
			);
			if($x)
				$pathname = $x[0]['filename'];
		}
		else {
			$pathname = filepath_macro($album);
		}
	}
	else {
		$pathname = filepath_macro($upload_path);
	}

	$darr = array('pathname' => $pathname);

	// if we need to create a directory, use the channel default permissions.

	$darr['allow_cid'] = $channel['allow_cid'];
	$darr['allow_gid'] = $channel['allow_gid'];
	$darr['deny_cid']  = $channel['deny_cid'];
	$darr['deny_gid']  = $channel['deny_gid'];


	$direct = null;

	if($pathname) {
		$x = attach_mkdirp($channel, $observer_hash, $darr);
		$folder_hash = (($x['success']) ? $x['data']['hash'] : '');
		$direct = (($x['success']) ? $x['data'] : null);
		if((! $str_contact_allow) && (! $str_group_allow) && (! $str_contact_deny) && (! $str_group_deny)) {
			$str_contact_allow = $x['data']['allow_cid'];
			$str_group_allow = $x['data']['allow_gid'];
			$str_contact_deny = $x['data']['deny_cid'];
			$str_group_deny = $x['data']['deny_gid'];
		}
	}
	else {
		$folder_hash = ((($arr) && array_key_exists('folder',$arr)) ? $arr['folder'] : '');
	}		

	if((! $options) || ($options === 'import')) {

		// A freshly uploaded file. Check for duplicate and resolve with the channel's overwrite settings.

		$r = q("select filename, id, hash, filesize from attach where filename = '%s' and folder = '%s' ",
			dbesc($filename),
			dbesc($folder_hash)
		);
		if($r) {
			$overwrite = get_pconfig($channel_id,'system','overwrite_dup_files');
			if(($overwrite) || ($options === 'import')) {
				$options = 'replace';
				$existing_id = $x[0]['id'];
				$existing_size = intval($x[0]['filesize']);
				$hash = $x[0]['hash'];
			}
			else {
				if(strpos($filename,'.') !== false) {
					$basename = substr($filename,0,strrpos($filename,'.'));
					$ext = substr($filename,strrpos($filename,'.'));
				}
				else {
					$basename = $filename;
					$ext = $def_extension;
				}

				$r = q("select filename from attach where ( filename = '%s' OR filename like '%s' ) and folder = '%s' ",
					dbesc($basename . $ext),
					dbesc($basename . '(%)' . $ext),
					dbesc($folder_hash)
				);

				if($r) {
					$x = 1;

					do {
						$found = false;
						foreach($r as $rr) {
							if($rr['filename'] === $basename . '(' . $x . ')' . $ext) {
								$found = true;
								break;
							}
						}
						if($found)
							$x++;
					}			
					while($found);
					$filename = $basename . '(' . $x . ')' . $ext;
				}
				else
					$filename = $basename . $ext;
			}
		}
	}

	if(! $hash)
		$hash = random_string();

	// Check storage limits
	if($options !== 'update') {
		$maxfilesize = get_config('system','maxfilesize');

		if(($maxfilesize) && ($filesize > $maxfilesize)) {
			$ret['message'] = sprintf( t('File exceeds size limit of %d'), $maxfilesize);
			if($remove_when_processed)
				@unlink($src);
			call_hooks('photo_upload_end',$ret);
			return $ret;
		}

		$limit = service_class_fetch($channel_id, 'attach_upload_limit');

		if($limit !== false) {
			$r = q("select sum(filesize) as total from attach where aid = %d ",
				intval($channel['channel_account_id'])
			);
			if(($r) &&  (($r[0]['total'] + $filesize) > ($limit - $existing_size))) {
				$ret['message'] = upgrade_message(true) . sprintf(t("You have reached your limit of %1$.0f Mbytes attachment storage."), $limit / 1024000);
				if($remove_when_processed)
					@unlink($src);

				call_hooks('photo_upload_end',$ret);
				return $ret;
			}
		}
		$mimetype = ((isset($type) && $type) ? $type : z_mime_content_type($filename));
	}

	$os_basepath = 'store/' . $channel['channel_address'] . '/' ;
	$os_relpath = '';

	if($folder_hash) {
		$curr = find_folder_hash_by_attach_hash($channel_id,$folder_hash,true);
		if($curr) 
			$os_relpath .= $curr . '/';
		$os_relpath .= $folder_hash . '/';
	}

	$os_relpath .= $hash;

	if($src)
		@file_put_contents($os_basepath . $os_relpath,@file_get_contents($src));

	if(array_key_exists('created', $arr))
		$created = $arr['created'];
	else
		$created = datetime_convert();

	if(array_key_exists('edited', $arr))
		$edited = $arr['edited'];
	else
		$edited = $created;

	if($options === 'replace') {
		$r = q("update attach set filename = '%s', filetype = '%s', folder = '%s', filesize = %d, os_storage = %d, is_photo = %d, content = '%s', edited = '%s' where id = %d and uid = %d",
			dbesc($filename),
			dbesc($mimetype),
			dbesc($folder_hash),
			intval($filesize),
			intval(1),
			intval($is_photo),
			dbesc($os_basepath . $os_relpath),
			dbesc($created),
			intval($existing_id),
			intval($channel_id)
		);
	}
	elseif($options === 'revise') {
		$r = q("insert into attach ( aid, uid, hash, creator, filename, filetype, folder, filesize, revision, os_storage, is_photo, content, created, edited, allow_cid, allow_gid, deny_cid, deny_gid )
			VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
			intval($x[0]['aid']),
			intval($channel_id),
			dbesc($x[0]['hash']),
			dbesc($observer_hash),
			dbesc($filename),
			dbesc($mimetype),
			dbesc($folder_hash),
			intval($filesize),
			intval($x[0]['revision'] + 1),
			intval(1),
			intval($is_photo),
			dbesc($os_basepath . $os_relpath),
			dbesc($created),
			dbesc($created),
			dbesc($x[0]['allow_cid']),
			dbesc($x[0]['allow_gid']),
			dbesc($x[0]['deny_cid']),
			dbesc($x[0]['deny_gid'])
		);
	}
	elseif($options === 'update') {
		$r = q("update attach set filename = '%s', filetype = '%s', folder = '%s', edited = '%s', os_storage = %d, is_photo = %d, 
			allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid  = '%s' where id = %d and uid = %d",
			dbesc((array_key_exists('filename',$arr))  ? $arr['filename']  : $x[0]['filename']),
			dbesc((array_key_exists('filetype',$arr))  ? $arr['filetype']  : $x[0]['filetype']),
			dbesc(($folder_hash) ? $folder_hash : $x[0]['folder']),
			dbesc($created),
			dbesc((array_key_exists('os_storage',$arr))  ? $arr['os_storage']  : $x[0]['os_storage']),
			dbesc((array_key_exists('is_photo',$arr))  ? $arr['is_photo']  : $x[0]['is_photo']),
			dbesc((array_key_exists('allow_cid',$arr)) ? $arr['allow_cid'] : $x[0]['allow_cid']),
			dbesc((array_key_exists('allow_gid',$arr)) ? $arr['allow_gid'] : $x[0]['allow_gid']),
			dbesc((array_key_exists('deny_cid',$arr))  ? $arr['deny_cid']  : $x[0]['deny_cid']),
			dbesc((array_key_exists('deny_gid',$arr))  ? $arr['deny_gid']  : $x[0]['deny_gid']),
			intval($x[0]['id']),
			intval($x[0]['uid'])
		);
	}
	else {

		$r = q("INSERT INTO attach ( aid, uid, hash, creator, filename, filetype, folder, filesize, revision, os_storage, is_photo, content, created, edited, allow_cid, allow_gid,deny_cid, deny_gid )
			VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
			intval($channel['channel_account_id']),
			intval($channel_id),
			dbesc($hash),
			dbesc(get_observer_hash()),
			dbesc($filename),
			dbesc($mimetype),
			dbesc($folder_hash),
			intval($filesize),
			intval(0),
			intval(1),
			intval($is_photo),
			dbesc($os_basepath . $os_relpath),
			dbesc($created),
			dbesc($created),
			dbesc(($arr && array_key_exists('allow_cid',$arr)) ? $arr['allow_cid'] : $str_contact_allow),
			dbesc(($arr && array_key_exists('allow_gid',$arr)) ? $arr['allow_gid'] : $str_group_allow),
			dbesc(($arr && array_key_exists('deny_cid',$arr))  ? $arr['deny_cid']  : $str_contact_deny),
			dbesc(($arr && array_key_exists('deny_gid',$arr))  ? $arr['deny_gid']  : $str_group_deny)
		);
	}

	if($is_photo) {

		$args = array( 'source' => $source, 'visible' => $visible, 'resource_id' => $hash, 'album' => basename($pathname), 'os_path' => $os_basepath . $os_relpath, 'filename' => $filename, 'getimagesize' => $gis, 'directory' => $direct, 'options' => $options );
		if($arr['contact_allow'])
			$args['contact_allow'] = $arr['contact_allow'];
		if($arr['group_allow'])
			$args['group_allow'] = $arr['group_allow'];
		if($arr['contact_deny'])
			$args['contact_deny'] = $arr['contact_deny'];
		if($arr['group_deny'])
			$args['group_deny'] = $arr['group_deny'];
		if(array_key_exists('allow_cid',$arr))
			$args['allow_cid'] = $arr['allow_cid'];
		if(array_key_exists('allow_gid',$arr))
			$args['allow_gid'] = $arr['allow_gid'];
		if(array_key_exists('deny_cid',$arr))
			$args['deny_cid'] = $arr['deny_cid'];
		if(array_key_exists('deny_gid',$arr))
			$args['deny_gid'] = $arr['deny_gid'];

		$args['created'] = $created;
		$args['edited'] = $edited;
		if($arr['item'])
			$args['item'] = $arr['item'];

		if($arr['body'])
			$args['body'] = $arr['body'];

		if($arr['description'])
			$args['description'] = $arr['description'];

		$args['deliver'] = $dosync;

		$p = photo_upload($channel,$observer,$args);
		if($p['success']) {
			$ret['body'] = $p['body'];
		}
	}

	if(($options !== 'update') && ($remove_when_processed))
		@unlink($src);

	if(! $r) {
		$ret['message'] = t('File upload failed. Possible system limit or action terminated.');
		call_hooks('photo_upload_end',$ret);
		return $ret;
	}

	// Caution: This re-uses $sql_options set further above

	$r = q("select * from attach where uid = %d and hash = '%s' $sql_options limit 1",
		intval($channel_id),
		dbesc($hash)
	);

	if(! $r) {
		$ret['message'] = t('Stored file could not be verified. Upload failed.');
		call_hooks('photo_upload_end',$ret);
		return $ret;
	}


	$ret['success'] = true;
	$ret['data'] = $r[0];
	if(! $is_photo) {
		// This would've been called already with a success result in photos_upload() if it was a photo.
		call_hooks('photo_upload_end',$ret);
	}

	if($dosync) {
		$sync = attach_export_data($channel,$hash);

		if($sync) 
			build_sync_packet($channel['channel_id'],array('file' => array($sync)));
	}

	return $ret;
}

/**
 * @brief Read a virtual directory and return contents.
 *
 * Also checking permissions of all parent components.
 *
 * @param integer $channel_id
 * @param string $observer_hash hash of current observer
 * @param string $pathname
 * @param string $parent_hash (optional)
 *
 * @return array $ret
 *  * \e boolean \b success boolean true or false
 *  * \e string \b message error message if success is false
 *  * \e array \b data array of attach DB entries without data component
 */
function z_readdir($channel_id, $observer_hash, $pathname, $parent_hash = '') {
	$ret = array('success' => false);

	if(! perm_is_allowed($channel_id, get_observer_hash(), 'view_storage')) {
		$ret['message'] = t('Permission denied.');
		return $ret;
	}

	if(strpos($pathname, '/')) {
		$paths = explode('/', $pathname);
		if(count($paths) > 1) {
			$curpath = array_shift($paths);

			$r = q("select hash, id, is_dir from attach where uid = %d and filename = '%s' and is_dir != 0 " . permissions_sql($channel_id) . " limit 1",
				intval($channel_id),
				dbesc($curpath)
			);
			if(! $r) {
				$ret['message'] = t('Path not available.');
				return $ret;
			}

			return z_readdir($channel_id, $observer_hash, implode('/', $paths), $r[0]['hash']);
		}
	}
	else
		$paths = array($pathname);

	$r = q("select id, aid, uid, hash, creator, filename, filetype, filesize, revision, folder, is_photo, is_dir, os_storage, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid from attach where id = %d and folder = '%s' and filename = '%s' and is_dir != 0 " . permissions_sql($channel_id),
		intval($channel_id),
		dbesc($parent_hash),
		dbesc($paths[0])
	);
	if(! $r) {
		$ret['message'] = t('Path not available.');
		return $ret;
	}
	$ret['success'] = true;
	$ret['data'] = $r;

	return $ret;
}

/**
 * @brief Create directory.
 *
 * @param array $channel channel array of owner
 * @param string $observer_hash hash of current observer
 * @param array $arr parameter array to fulfil request
 * - Required:
 *  * \e string \b filename
 *  * \e string \b folder hash of parent directory, empty string for root directory
 * - Optional:
 *  * \e string \b hash precomputed hash for this node
 *  * \e tring  \b allow_cid
 *  * \e string \b allow_gid
 *  * \e string \b deny_cid
 *  * \e string \b deny_gid
 * @return array
 */
function attach_mkdir($channel, $observer_hash, $arr = null) {

	$ret = array('success' => false);
	$channel_id = $channel['channel_id'];

	$sql_options = '';

	$basepath = 'store/' . $channel['channel_address'];

	logger('attach_mkdir: basepath: ' . $basepath);

	if(! is_dir($basepath))
		os_mkdir($basepath,STORAGE_DEFAULT_PERMISSIONS, true);

	if(! perm_is_allowed($channel_id, $observer_hash, 'write_storage')) {
		$ret['message'] = t('Permission denied.');
		return $ret;
	}

	if(! $arr['filename']) {
		$ret['message'] = t('Empty pathname');
		return $ret;
	}

	$arr['hash'] = (($arr['hash']) ? $arr['hash'] : random_string());

	// Check for duplicate name.
	// Check both the filename and the hash as we will be making use of both.

	$r = q("select id, hash, is_dir, flags from attach where ( filename = '%s' or hash = '%s' ) and folder = '%s' and uid = %d limit 1",
		dbesc($arr['filename']),
		dbesc($arr['hash']),
		dbesc($arr['folder']),
		intval($channel['channel_id'])
	);
	if($r) {
		if(array_key_exists('force',$arr) && intval($arr['force']) 
			&& (intval($r[0]['is_dir']))) {
				$ret['success'] = true;
				$r = q("select * from attach where id = %d limit 1",
					intval($r[0]['id'])
				);
				if($r)
					$ret['data'] = $r[0];
				return $ret;
		}
		$ret['message'] = t('duplicate filename or path');
		return $ret;
	}

	if($arr['folder']) {

		// Walk the directory tree from parent back to root to make sure the parent is valid and name is unique and we
		// have permission to see this path. This implies the root directory itself is public since we won't have permissions
		// set on the psuedo-directory. We can however set permissions for anything and everything contained within it.

		$lpath = '';
		$lfile = $arr['folder'];
		$sql_options = permissions_sql($channel['channel_id']);

		do {
			$r = q("select filename, hash, flags, is_dir, folder from attach where uid = %d and hash = '%s' and is_dir != 0
				$sql_options limit 1",
				intval($channel['channel_id']),
				dbesc($lfile)
			);
			if(! $r) {
				logger('attach_mkdir: hash ' . $lfile . ' not found in ' . $lpath);
				$ret['message'] = t('Path not found.');
				return $ret;
			}
			if($lfile)
				$lpath = $r[0]['hash'] . '/' . $lpath;
			$lfile = $r[0]['folder'];
		} while ( ($r[0]['folder']) && intval($r[0]['is_dir'])) ;
		$path = $basepath . '/' . $lpath;
	}
	else
		$path = $basepath . '/';

	$path .= $arr['hash'];

	$created = datetime_convert();

	$r = q("INSERT INTO attach ( aid, uid, hash, creator, filename, filetype, filesize, revision, folder, os_storage, is_dir, content, created, edited, allow_cid, allow_gid, deny_cid, deny_gid )
		VALUES ( %d, %d, '%s', '%s', '%s', '%s', %d, %d, '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
		intval($channel['channel_account_id']),
		intval($channel_id),
		dbesc($arr['hash']),
		dbesc(get_observer_hash()),
		dbesc($arr['filename']),
		dbesc('multipart/mixed'),
		intval(0),
		intval(0),
		dbesc($arr['folder']),
		intval(1),
		intval(1),
		dbesc($path),
		dbesc($created),
		dbesc($created),
		dbesc(($arr && array_key_exists('allow_cid',$arr)) ? $arr['allow_cid'] : $channel['channel_allow_cid']),
		dbesc(($arr && array_key_exists('allow_gid',$arr)) ? $arr['allow_gid'] : $channel['channel_allow_gid']),
		dbesc(($arr && array_key_exists('deny_cid',$arr))  ? $arr['deny_cid']  : $channel['channel_deny_cid']),
		dbesc(($arr && array_key_exists('deny_gid',$arr))  ? $arr['deny_gid']  : $channel['channel_deny_gid'])
	);

	if($r) {
		if(os_mkdir($path, STORAGE_DEFAULT_PERMISSIONS, true)) {
			$ret['success'] = true;

			// update the parent folder's lastmodified timestamp
			$e = q("UPDATE attach SET edited = '%s' WHERE hash = '%s' AND uid = %d",
				dbesc($created),
				dbesc($arr['folder']),
				intval($channel_id)
			);

			$z = q("select * from attach where hash = '%s' and uid = %d and is_dir = 1 limit 1",
				dbesc($arr['hash']),
				intval($channel_id)
			);
			if($z)
				$ret['data'] = $z[0];
		}
		else {
			logger('attach_mkdir: ' . mkdir . ' ' . $path . ' failed.');
			$ret['message'] = t('mkdir failed.');
		}
	}
	else {
		$ret['message'] = t('database storage failed.');
	}

	return $ret;
}

/**
 * @brief Create directory (recursive).
 *
 * @param array $channel channel array of owner
 * @param string $observer_hash hash of current observer
 * @param array $arr parameter array to fulfil request
 * - Required:
 *  * \e string \b pathname
 *  * \e string \b folder hash of parent directory, empty string for root directory
 * - Optional:
 *  * \e string \b allow_cid
 *  * \e string \b allow_gid
 *  * \e string \b deny_cid
 *  * \e string \b deny_gid
 * @return array
 */
function attach_mkdirp($channel, $observer_hash, $arr = null) {

	$ret = array('success' => false);
	$channel_id = $channel['channel_id'];

	$sql_options = '';

	$basepath = 'store/' . $channel['channel_address'];

	logger('attach_mkdirp: basepath: ' . $basepath);

	if(! is_dir($basepath))
		os_mkdir($basepath,STORAGE_DEFAULT_PERMISSIONS, true);

	if(! perm_is_allowed($channel_id, $observer_hash, 'write_storage')) {
		$ret['message'] = t('Permission denied.');
		return $ret;
	}

	if(! $arr['pathname']) {
		$ret['message'] = t('Empty pathname');
		return $ret;
	}

	$paths = explode('/',$arr['pathname']);
	if(! $paths) {
		$ret['message'] = t('Empty path');
		return $ret;
	}

	$current_parent = '';

	foreach($paths as $p) {
		if(! $p)
			continue;
		$arx = array(
			'filename' => $p, 
			'folder' => $current_parent,
			'force' => 1
		);
		if(array_key_exists('allow_cid',$arr))
			$arx['allow_cid'] = $arr['allow_cid'];
		if(array_key_exists('deny_cid',$arr))
			$arx['deny_cid'] = $arr['deny_cid'];
		if(array_key_exists('allow_gid',$arr))
			$arx['allow_gid'] = $arr['allow_gid'];
		if(array_key_exists('deny_gid',$arr))
			$arx['deny_gid'] = $arr['deny_gid'];

		$x = attach_mkdir($channel, $observer_hash, $arx);		
		if($x['success']) {
			$current_parent = $x['data']['hash'];
		}
		else {
			$ret['message'] = $x['message'];
			return $ret;
		}
	}
	if(isset($x)) {
		$ret['success'] = true;
		$ret['data'] = $x['data'];
	}

	return $ret;	

}







/**
 * @brief Changes permissions of a file.
 *
 * @param int $channel_id
 * @param array $resource
 * @param string $allow_cid
 * @param string $allow_gid
 * @param string $deny_cid
 * @param string $deny_gid
 * @param boolean $recurse (optional) default false
 */
function attach_change_permissions($channel_id, $resource, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $recurse = false) {

	$r = q("select hash, flags, is_dir, is_photo from attach where hash = '%s' and uid = %d limit 1",
		dbesc($resource),
		intval($channel_id)
	);

	if(! $r)
		return;

	if(intval($r[0]['is_dir'])) {
		if($recurse) {
			$r = q("select hash, flags, is_dir from attach where folder = '%s' and uid = %d",
				dbesc($resource),
				intval($channel_id)
			);
			if($r) {
				foreach($r as $rr) {
					attach_change_permissions($channel_id, $rr['hash'], $allow_cid, $allow_gid, $deny_cid, $deny_gid, $recurse);
				}
			}
		}
	}

	$x = q("update attach set allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid = '%s' where hash = '%s' and uid = %d",
		dbesc($allow_cid),
		dbesc($allow_gid),
		dbesc($deny_cid),
		dbesc($deny_gid),
		dbesc($resource),
		intval($channel_id)
	);
	if($r[0]['is_photo']) {
		$x = q("update photo set allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid = '%s' where resource_id = '%s' and uid = %d",
			dbesc($allow_cid),
			dbesc($allow_gid),
			dbesc($deny_cid),
			dbesc($deny_gid),
			dbesc($resource),
			intval($channel_id)
		);
	}
}

/**
 * @brief Delete a file/directory from a channel.
 *
 * If the provided resource hash is from a directory it will delete everything
 * recursively under this directory.
 *
 * @param int $channel_id
 *  The id of the channel
 * @param string $resource
 *  The hash to delete
 * @return void
 */
function attach_delete($channel_id, $resource, $is_photo = 0) {

	$c = q("SELECT channel_address FROM channel WHERE channel_id = %d LIMIT 1",
		intval($channel_id)
	);

	$channel_address = (($c) ? $c[0]['channel_address'] : 'notfound');
	$photo_sql = (($is_photo) ? " and is_photo = 1 " : '');

	$r = q("SELECT hash, os_storage, flags, is_dir, is_photo, folder FROM attach WHERE hash = '%s' AND uid = %d $photo_sql limit 1",
		dbesc($resource),
		intval($channel_id)
	);

	if(! $r)
		return;

	$cloudpath = get_parent_cloudpath($channel_id, $channel_address, $resource);
	$object = get_file_activity_object($channel_id, $resource, $cloudpath);

	// If resource is a directory delete everything in the directory recursive
	if(intval($r[0]['is_dir'])) {
		$x = q("SELECT hash, os_storage, is_dir, flags FROM attach WHERE folder = '%s' AND uid = %d",
			dbesc($resource),
			intval($channel_id)
		);
		if($x) {
			foreach($x as $xx) {
				attach_delete($channel_id, $xx['hash']);
			}
		}
	}

	// delete a file from filesystem
	if(intval($r[0]['os_storage'])) {
		$y = q("SELECT content FROM attach WHERE hash = '%s' AND uid = %d LIMIT 1",
			dbesc($resource),
			intval($channel_id)
		);

		if($y) {
			if(strpos($y[0]['content'],'store') === false)
				$f = 'store/' . $channel_address . '/' . $y[0]['content'];
			else
				$f = $y[0]['content'];

			if(is_dir($f))
				@rmdir($f);
			elseif(file_exists($f))
				unlink($f);
		}
	}

	// delete from database
	$z = q("DELETE FROM attach WHERE hash = '%s' AND uid = %d",
		dbesc($resource),
		intval($channel_id)
	);

	if($r[0]['is_photo']) {
		$x = q("select id, item_hidden from item where resource_id = '%s' and resource_type = 'photo' and uid = %d",
			dbesc($resource),
			intval($channel_id)
		);
		if($x) {
			drop_item($x[0]['id'],false,(($x[0]['item_hidden']) ? DROPITEM_NORMAL : DROPITEM_PHASE1),true);
		}
		q("DELETE FROM photo WHERE uid = %d AND resource_id = '%s'",
			intval($channel_id),
			dbesc($resource)
		);
	}
			
	// update the parent folder's lastmodified timestamp
	$e = q("UPDATE attach SET edited = '%s' WHERE hash = '%s' AND uid = %d",
		dbesc(datetime_convert()),
		dbesc($r[0]['folder']),
		intval($channel_id)
	);

	file_activity($channel_id, $object, $object['allow_cid'], $object['allow_gid'], $object['deny_cid'], $object['deny_gid'], 'update', $notify=1);

	return;
}

/**
 * @brief Returns path to file in cloud/.
 *
 * @warning This function cannot be used with mod/dav as it always returns a
 * path valid under mod/cloud.
 *
 * @param array $arr associative array with:
 *  * \e int \b uid the channel's uid
 *  * \e string \b folder
 *  * \e string \b filename
 * @return string
 *  path to the file in cloud/
 */
function get_cloudpath($arr) {
	$basepath = 'cloud/';

	if($arr['uid']) {
		$r = q("select channel_address from channel where channel_id = %d limit 1",
			intval($arr['uid'])
		);
		if($r)
			$basepath .= $r[0]['channel_address'] . '/';
	}

	$path = $basepath;

	if($arr['folder']) {
		$lpath = '';
		$lfile = $arr['folder'];

		do {
			$r = q("select filename, hash, flags, is_dir, folder from attach where uid = %d and hash = '%s' and is_dir != 0
				limit 1",
				intval($arr['uid']),
				dbesc($lfile)
			);

			if(! $r)
				break;

			if($lfile)
				$lpath = $r[0]['filename'] . '/' . $lpath;
			$lfile = $r[0]['folder'];

		} while ( ($r[0]['folder']) && intval($r[0]['is_dir']));

		$path .= $lpath;
	}
	$path .= $arr['filename'];

	return $path;
}

/**
 * @brief Returns path to parent folder in cloud/.
 * This function cannot be used with mod/dav as it always returns a path valid under mod/cloud
 *
 * @param int $channel_id
 *  The id of the channel
 * @param string $channel_name
 *  The name of the channel
 * @param string $attachHash
 * @return string with the full folder path
 */
function get_parent_cloudpath($channel_id, $channel_name, $attachHash) {
	$parentFullPath = '';
	// build directory tree
	$parentHash = $attachHash;
	do {
		$parentHash = find_folder_hash_by_attach_hash($channel_id, $parentHash);
		if ($parentHash) {
			$parentName = find_filename_by_hash($channel_id, $parentHash);
			$parentFullPath = $parentName . '/' . $parentFullPath;
		}
	} while ($parentHash);
	$parentFullPath = z_root() . '/cloud/' . $channel_name . '/' . $parentFullPath;

	return $parentFullPath;
}

/**
 * @brief Return the hash of an attachment's folder.
 *
 * @param int $channel_id
 *  The id of the channel
 * @param string $attachHash
 *  The hash of the attachment
 * @return string
 */
function find_folder_hash_by_attach_hash($channel_id, $attachHash, $recurse = false) {

logger('attach_hash: ' . $attachHash);
	$r = q("SELECT folder FROM attach WHERE uid = %d AND hash = '%s' LIMIT 1",
		intval($channel_id),
		dbesc($attachHash)
	);
	$hash = '';
	if($r && $r[0]['folder']) {
		if($recurse)
			$hash = find_folder_hash_by_attach_hash($channel_id,$r[0]['folder'],true) . '/' . $r[0]['folder']; 
		else
			$hash = $r[0]['folder'];
	}
	return $hash;
}

/**
 * @brief Returns the filename of an attachment in a given channel.
 *
 * @param int $channel_id
 *  The id of the channel
 * @param string $attachHash
 *  The hash of the attachment
 * @return string
 *  The filename of the attachment
 */
function find_filename_by_hash($channel_id, $attachHash) {
	$r = q("SELECT filename FROM attach WHERE uid = %d AND hash = '%s' LIMIT 1",
		intval($channel_id),
		dbesc($attachHash)
	);
	$filename = '';
	if ($r) {
		$filename = $r[0]['filename'];
	}

	return $filename;
}

/**
 *
 * @param $in
 * @param $out
 */
function pipe_streams($in, $out) {
	$size = 0;
	while (!feof($in))
		$size += fwrite($out, fread($in, 16384));

	return $size;
}

/**
 * @brief Activity for files.
 *
 * @param int $channel_id
 * @param array $object
 * @param string $allow_cid
 * @param string $allow_gid
 * @param string $deny_cid
 * @param string $deny_gid
 * @param string $verb
 * @param boolean $notify
 */
function file_activity($channel_id, $object, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $verb, $notify) {

	require_once('include/items.php');

	$poster = App::get_observer();

	//if we got no object something went wrong
	if(!$object)
		return;

	//turn strings into arrays
	$arr_allow_cid = expand_acl($allow_cid);
	$arr_allow_gid = expand_acl($allow_gid);
	$arr_deny_cid = expand_acl($deny_cid);
	$arr_deny_gid = expand_acl($deny_gid);

	//filter out receivers which do not have permission to view filestorage
	$arr_allow_cid = check_list_permissions($channel_id, $arr_allow_cid, 'view_storage');

	$is_dir = (intval($object['is_dir']) ? true : false);

	//do not send activity for folders for now
	if($is_dir)
		return;

	//check for recursive perms if we are in a folder
	if($object['folder']) {

		$folder_hash = $object['folder'];

		$r_perms = recursive_activity_recipients($arr_allow_cid, $arr_allow_gid, $arr_deny_cid, $arr_deny_gid, $folder_hash);

		//split up returned perms
		$arr_allow_cid = $r_perms['allow_cid'];
		$arr_allow_gid = $r_perms['allow_gid'];
		$arr_deny_cid = $r_perms['deny_cid'];
		$arr_deny_gid = $r_perms['deny_gid'];

		//filter out receivers which do not have permission to view filestorage
		$arr_allow_cid = check_list_permissions($channel_id, $arr_allow_cid, 'view_storage');
	}

	$mid = item_message_id();

	$objtype = ACTIVITY_OBJ_FILE;

	$arr = array();
	$arr['aid']           = get_account_id();
	$arr['uid']           = $channel_id;
	$arr['item_wall'] = 1; 
	$arr['item_origin'] = 1;
	$arr['item_unseen'] = 1;
	$arr['author_xchan']  = $poster['xchan_hash'];
	$arr['owner_xchan']   = $poster['xchan_hash'];
	$arr['title']         = '';
	$arr['item_hidden']   = 1;
	$arr['obj_type']      = $objtype;
	$arr['resource_id']   = $object['hash'];
	$arr['resource_type'] = 'attach';

	$private = (($arr_allow_cid[0] || $arr_allow_gid[0] || $arr_deny_cid[0] || $arr_deny_gid[0]) ? 1 : 0);

	$jsonobject = json_encode($object);

	//check if item for this object exists
	$y = q("SELECT mid FROM item WHERE verb = '%s' AND obj_type = '%s' AND resource_id = '%s' AND uid = %d LIMIT 1",
		dbesc(ACTIVITY_POST),
		dbesc($objtype),
		dbesc($object['hash']),
		intval(local_channel())
	);

	if($y) {
		$update = true;
		$object['d_mid'] = $y[0]['mid']; //attach mid of the old object
		$u_jsonobject = json_encode($object);

		//we have got the relevant info - delete the old item before we create the new one
		$z = q("DELETE FROM item WHERE obj_type = '%s' AND verb = '%s' AND mid = '%s'",
			dbesc(ACTIVITY_OBJ_FILE),
			dbesc(ACTIVITY_POST),
			dbesc($y[0]['mid'])
		);

	}

	//send update activity and create a new one
	if($update && $verb == 'post' ) {
		//updates should be sent to everybody with recursive perms and all eventual former allowed members ($object['allow_cid'] etc.).
		$u_arr_allow_cid = array_unique(array_merge($arr_allow_cid, expand_acl($object['allow_cid'])));
		$u_arr_allow_gid = array_unique(array_merge($arr_allow_gid, expand_acl($object['allow_gid'])));
		$u_arr_deny_cid = array_unique(array_merge($arr_deny_cid, expand_acl($object['deny_cid'])));
		$u_arr_deny_gid = array_unique(array_merge($arr_deny_gid, expand_acl($object['deny_gid'])));

		$private = (($u_arr_allow_cid[0] || $u_arr_allow_gid[0] || $u_arr_deny_cid[0] || $u_arr_deny_gid[0]) ? 1 : 0);

		$u_mid = item_message_id();

		$arr['mid']           = $u_mid;
		$arr['parent_mid']    = $u_mid;
		$arr['allow_cid']     = perms2str($u_arr_allow_cid);
		$arr['allow_gid']     = perms2str($u_arr_allow_gid);
		$arr['deny_cid']      = perms2str($u_arr_deny_cid);
		$arr['deny_gid']      = perms2str($u_arr_deny_gid);
		$arr['item_private']  = $private;
		$arr['verb']          = ACTIVITY_UPDATE;
		$arr['obj']           = $u_jsonobject;
		$arr['body']          = '';

		$post = item_store($arr);
		$item_id = $post['item_id'];
		if($item_id) {
			Zotlabs\Daemon\Master::Summon(array('Notifier','activity',$item_id));
		}

		call_hooks('post_local_end', $arr);

		$update = false;

		//notice( t('File activity updated') . EOL);
	}

	//don't create new activity if notify was not enabled
	if(! $notify) {
		return;
	}

	//don't create new activity if we have an update request but there is no item to update
	//this can e.g. happen when deleting images
	if(! $y && $verb == 'update') {
		return;
	}

	$arr['mid']           = $mid;
	$arr['parent_mid']    = $mid;
	$arr['allow_cid']     = perms2str($arr_allow_cid);
	$arr['allow_gid']     = perms2str($arr_allow_gid);
	$arr['deny_cid']      = perms2str($arr_deny_cid);
	$arr['deny_gid']      = perms2str($arr_deny_gid);
	$arr['item_private']  = $private;
	$arr['verb']          = (($update) ? ACTIVITY_UPDATE : ACTIVITY_POST);
	$arr['obj']           = (($update) ? $u_jsonobject : $jsonobject);
	$arr['body']          = '';

	$post = item_store($arr);
	$item_id = $post['item_id'];

	if($item_id) {
		Zotlabs\Daemon\Master::Summon(array('Notifier','activity',$item_id));
	}

	call_hooks('post_local_end', $arr);

	//(($verb === 'post') ?  notice( t('File activity posted') . EOL) : notice( t('File activity dropped') . EOL));

	return;
}

/**
 * @brief Create file activity object
 *
 * @param int $channel_id
 * @param string $hash
 * @param string $cloudpath
 */
function get_file_activity_object($channel_id, $hash, $cloudpath) {

	$x = q("SELECT creator, filename, filetype, filesize, revision, folder, os_storage, is_photo, is_dir, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid FROM attach WHERE uid = %d AND hash = '%s' LIMIT 1",
		intval($channel_id),
		dbesc($hash)
	);

	$url = rawurlencode($cloudpath . $x[0]['filename']);

	$links   = array();
	$links[] = array(
		'rel'  => 'alternate',
		'type' => 'text/html',
		'href' => $url
	);

	$object = array(
		'type'  => ACTIVITY_OBJ_FILE,
		'title' => $x[0]['filename'],
		'id'    => $url,
		'link'  => $links,

		'hash'		=> $hash,
		'creator'	=> $x[0]['creator'],
		'filename'	=> $x[0]['filename'],
		'filetype'	=> $x[0]['filetype'],
		'filesize'	=> $x[0]['filesize'],
		'revision'	=> $x[0]['revision'],
		'folder'	=> $x[0]['folder'],
		'flags'		=> $x[0]['flags'],
		'os_storage' => $x[0]['os_storage'],
		'is_photo'  => $x[0]['is_photo'],
		'is_dir'    => $x[0]['is_dir'],
		'created'	=> $x[0]['created'],
		'edited'	=> $x[0]['edited'],
		'allow_cid'	=> $x[0]['allow_cid'],
		'allow_gid'	=> $x[0]['allow_gid'],
		'deny_cid'	=> $x[0]['deny_cid'],
		'deny_gid'	=> $x[0]['deny_gid']
	);

	return $object;
}

/**
 * @brief Returns array of channels which have recursive permission for a file
 *
 * @param $arr_allow_cid
 * @param $arr_allow_gid
 * @param $arr_deny_cid
 * @param $arr_deny_gid
 * @param $folder_hash
 */
function recursive_activity_recipients($arr_allow_cid, $arr_allow_gid, $arr_deny_cid, $arr_deny_gid, $folder_hash) {

	$ret = array();
	$parent_arr = array();
	$count_values = array();
	$poster = App::get_observer();

	//turn allow_gid into allow_cid's
	foreach($arr_allow_gid as $gid) {
		$in_group = group_get_members($gid);
		$arr_allow_cid = array_unique(array_merge($arr_allow_cid, $in_group));
	}

	$count = 0;
	while($folder_hash) {
		$x = q("SELECT allow_cid, allow_gid, deny_cid, deny_gid, folder FROM attach WHERE hash = '%s' LIMIT 1",
			dbesc($folder_hash)
		);

		//only process private folders
		if($x[0]['allow_cid'] || $x[0]['allow_gid'] || $x[0]['deny_cid'] || $x[0]['deny_gid']) {

			$parent_arr['allow_cid'][] = expand_acl($x[0]['allow_cid']);
			$parent_arr['allow_gid'][] = expand_acl($x[0]['allow_gid']);

			/**
			 * @TODO should find a much better solution for the allow_cid <-> allow_gid problem.
			 * Do not use allow_gid for now. Instead lookup the members of the group directly and add them to allow_cid.
			 * */
			if($parent_arr['allow_gid']) {
				foreach($parent_arr['allow_gid'][$count] as $gid) {
					$in_group = group_get_members($gid);
					$parent_arr['allow_cid'][$count] = array_unique(array_merge($parent_arr['allow_cid'][$count], $in_group));
				}
			}

			$parent_arr['deny_cid'][] = expand_acl($x[0]['deny_cid']);
			$parent_arr['deny_gid'][] = expand_acl($x[0]['deny_gid']);

			$count++;
		}

		$folder_hash = $x[0]['folder'];
	}

	//if none of the parent folders is private just return file perms
	if(!$parent_arr['allow_cid'] && !$parent_arr['allow_gid'] && !$parent_arr['deny_cid'] && !$parent_arr['deny_gid']) {
		$ret['allow_gid'] = $arr_allow_gid;
		$ret['allow_cid'] = $arr_allow_cid;
		$ret['deny_gid'] = $arr_deny_gid;
		$ret['deny_cid'] = $arr_deny_cid;

		return $ret;
	}

	//if there are no perms on the file we get them from the first parent folder
	if(!$arr_allow_cid && !$arr_allow_gid && !$arr_deny_cid && !$arr_deny_gid) {
		$arr_allow_cid = $parent_arr['allow_cid'][0];
		$arr_allow_gid = $parent_arr['allow_gid'][0];
		$arr_deny_cid = $parent_arr['deny_cid'][0];
		$arr_deny_gid = $parent_arr['deny_gid'][0];
	}

	//allow_cid
	$r_arr_allow_cid = false;
	foreach ($parent_arr['allow_cid'] as $folder_arr_allow_cid) {
		foreach ($folder_arr_allow_cid as $ac_hash) {
			$count_values[$ac_hash]++;
		}
	}
	foreach ($arr_allow_cid as $fac_hash) {
		if($count_values[$fac_hash] == $count)
			$r_arr_allow_cid[] = $fac_hash;
	}

	//allow_gid
	$r_arr_allow_gid = false;
	foreach ($parent_arr['allow_gid'] as $folder_arr_allow_gid) {
		foreach ($folder_arr_allow_gid as $ag_hash) {
			$count_values[$ag_hash]++;
		}
	}
	foreach ($arr_allow_gid as $fag_hash) {
		if($count_values[$fag_hash] == $count)
			$r_arr_allow_gid[] = $fag_hash;
	}

	//deny_gid
	foreach($parent_arr['deny_gid'] as $folder_arr_deny_gid) {
		$r_arr_deny_gid = array_merge($arr_deny_gid, $folder_arr_deny_gid);
	}
	$r_arr_deny_gid = array_unique($r_arr_deny_gid);

	//deny_cid
	foreach($parent_arr['deny_cid'] as $folder_arr_deny_cid) {
		$r_arr_deny_cid = array_merge($arr_deny_cid, $folder_arr_deny_cid);
	}
	$r_arr_deny_cid = array_unique($r_arr_deny_cid);

	//if none is allowed restrict to self
	if(($r_arr_allow_gid === false) && ($r_arr_allow_cid === false)) {
		$ret['allow_cid'] = $poster['xchan_hash'];
	} else {
		$ret['allow_gid'] = $r_arr_allow_gid;
		$ret['allow_cid'] = $r_arr_allow_cid;
		$ret['deny_gid'] = $r_arr_deny_gid;
		$ret['deny_cid'] = $r_arr_deny_cid;
	}

	return $ret;
}

function filepath_macro($s) {

	return str_replace(
		array( '%Y', '%m', '%d' ),
		array( datetime_convert('UTC',date_default_timezone_get(),'now', 'Y'),
			datetime_convert('UTC',date_default_timezone_get(),'now', 'm'),
			datetime_convert('UTC',date_default_timezone_get(),'now', 'd')
		), $s);

}

function attach_export_data($channel, $resource_id, $deleted = false) {

	$ret = array();

	$paths = array();

	$hash_ptr = $resource_id;

	$ret['fetch_url'] = z_root() . '/getfile';
	$ret['original_channel'] = $channel['channel_address'];


	if($deleted) {
		$ret['attach'] = array(array('hash' => $resource_id, 'deleted' => 1));
		return $ret;
	}

	do {
		$r = q("select * from attach where hash = '%s' and uid = %d limit 1",
			dbesc($hash_ptr),
			intval($channel['channel_id'])
		);
		if(! $r)
			break;

		if($hash_ptr === $resource_id) {
			$attach_ptr = $r[0];
		}

		$hash_ptr = $r[0]['folder'];
		$paths[] = $r[0];
	} while($hash_ptr);


	$paths = array_reverse($paths);

	$ret['attach'] = $paths;


	if($attach_ptr['is_photo']) {
		$r = q("select * from photo where resource_id = '%s' and uid = %d order by imgscale asc",
			dbesc($resource_id),
			intval($channel['channel_id'])
		);
		if($r) {
			for($x = 0; $x < count($r); $x ++) {
				$r[$x]['content'] = base64_encode($r[$x]['content']);
			}
			$ret['photo'] = $r;
		}

		$r = q("select * from item where resource_id = '%s' and resource_type = 'photo' and uid = %d ",
			dbesc($resource_id),
			intval($channel['channel_id'])
		);
		if($r) {
			$ret['item'] = array();
			$items = q("select item.*, item.id as item_id from item where item.parent = %d ",
				intval($r[0]['id'])
			);
			if($items) {
				xchan_query($items);
				$items = fetch_post_tags($items,true);
				foreach($items as $rr)
					$ret['item'][] = encode_item($rr,true);
			}
		}
	}

	return $ret;

}


/* strip off 'store/nickname/' from the provided path */

function get_attach_binname($s) {
	$p = $s;
	if(strpos($s,'store/') === 0) {
		$p = substr($s,6);
		$p = substr($p,strpos($p,'/')+1);
	}
	return $p;
}


function get_dirpath_by_cloudpath($channel, $path) {
	
	// Warning: Do not edit the following line. The first symbol is UTF-8 &#65312; 
	$path = str_replace('@','@',notags(trim($path)));		

	$h = @parse_url($path);

	if(! $h || !x($h, 'path')) {
		return null;
	}
	if(substr($h['path'],-1,1) === '/') {
		$h['path'] = substr($h['path'],0,-1);
	}
	if(substr($h['path'],0,1) === '/') {
		$h['path'] = substr($h['path'],1);
	}
	$folders = explode('/', $h['path']);
	$f = array_shift($folders);
	
	$nick = $channel['channel_address'];
	//check to see if the absolute path was provided (/cloud/channelname/path/to/folder)
	if($f === 'cloud' ) { 
		$g = array_shift($folders);
		if( $g !== $nick) {
			// if nick does not follow "cloud", then the top level folder must be called  "cloud"
			// and the given path must be relative to "/cloud/channelname/". 
			$folders = array_unshift(array_unshift($folders, $g), $f);
		} 
	} else {
		array_unshift($folders, $f);
	}
	$clouddir = 'store/' . $nick . '/' ;
	$subdir = '/';
	$valid = true;
	while($folders && $valid && is_dir($clouddir . $subdir) && is_readable($clouddir . $subdir)) {
		$valid = false;
		$f = array_shift($folders);
		$items = array_diff(scandir($clouddir . $subdir), array('.', '..')); // hashed names
		foreach($items as $item) {
			$filename = find_filename_by_hash($channel['channel_id'], $item);
			if($filename === $f) {
				$subdir .= $item . '/';
				$valid = true;
			}
		}
	}
	if(!$valid) {
		return null;
	} else {
		return $clouddir . $subdir;
	}
	
	
}

function get_filename_by_cloudname($cloudname, $channel, $storepath) {
	$items = array_diff(scandir($storepath), array('.', '..')); // hashed names
	foreach($items as $item) {
		$filename = find_filename_by_hash($channel['channel_id'], $item);
		if($filename === $cloudname) {
			return $item;
		}
	}
	return null;
}