aboutsummaryrefslogtreecommitdiffstats
path: root/Zotlabs/Storage/Directory.php
blob: 73548fda09da45efdad5860b818c57306da22ecb (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
<?php

namespace Zotlabs\Storage;

use Sabre\DAV;

/**
 * @brief RedDirectory class.
 *
 * A class that represents a directory.
 *
 * @extends \\Sabre\\DAV\\Node
 * @implements \\Sabre\\DAV\\ICollection
 * @implements \\Sabre\\DAV\\IQuota
 *
 * @link http://github.com/friendica/red
 * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
 */
class Directory extends DAV\Node implements DAV\ICollection, DAV\IQuota, DAV\IMoveTarget {

	/**
	 * @brief The path inside /cloud
	 *
	 * @var string $red_path
	 */
	private $red_path;
	private $folder_hash;
	/**
	 * @brief The full path as seen in the browser.
	 * /cloud + $red_path
	 * @todo I think this is not used anywhere, we always strip '/cloud' and only use it in debug
	 * @var string $ext_path
	 */
	private $ext_path;
	private $root_dir = '';
	private $auth;
	/**
	 * @brief The real path on the filesystem.
	 * The actual path in store/ with the hashed names.
	 *
	 * @var string $os_path
	 */
	private $os_path = '';

	/**
	 * @brief Sets up the directory node, expects a full path.
	 *
	 * @param string $ext_path a full path
	 * @param BasicAuth &$auth_plugin
	 */
	public function __construct($ext_path, &$auth_plugin) {
		//		$ext_path = urldecode($ext_path);
		logger('directory ' . $ext_path, LOGGER_DATA);
		$this->ext_path = $ext_path;
		// remove "/cloud" from the beginning of the path
		$modulename = \App::$module;
		$this->red_path = ((strpos($ext_path, '/' . $modulename) === 0) ? substr($ext_path, strlen($modulename) + 1) : $ext_path);
		if(! $this->red_path) {
			$this->red_path = '/';
		}
		$this->auth = $auth_plugin;
		$this->folder_hash = '';
		$this->getDir();

		if($this->auth->browser) {
			$this->auth->browser->set_writeable();
		}
	}

	private function log() {
		logger('ext_path ' . $this->ext_path, LOGGER_DATA);
		logger('os_path  ' . $this->os_path, LOGGER_DATA);
		logger('red_path ' . $this->red_path, LOGGER_DATA);
	}

	/**
	 * @brief Returns an array with all the child nodes.
	 *
	 * @throw "\Sabre\DAV\Exception\Forbidden"
	 * @return array \\Sabre\\DAV\\INode[]
	 */
	public function getChildren() {
		logger('children for ' . $this->ext_path, LOGGER_DATA);
		$this->log();

		if (get_config('system', 'block_public') && (! $this->auth->channel_id) && (! $this->auth->observer)) {
			throw new DAV\Exception\Forbidden('Permission denied.');
		}

		if (($this->auth->owner_id) && (! perm_is_allowed($this->auth->owner_id, $this->auth->observer, 'view_storage'))) {
			throw new DAV\Exception\Forbidden('Permission denied.');
		}

		$contents = $this->CollectionData($this->red_path, $this->auth);
		return $contents;
	}

	/**
	 * @brief Returns a child by name.
	 *
	 * @throw "\Sabre\DAV\Exception\Forbidden"
	 * @throw "\Sabre\DAV\Exception\NotFound"
	 * @param string $name
	 */
	public function getChild($name) {
		logger($name, LOGGER_DATA);

		if (get_config('system', 'block_public') && (! $this->auth->channel_id) && (! $this->auth->observer)) {
			throw new DAV\Exception\Forbidden('Permission denied.');
		}

		if (($this->auth->owner_id) && (! perm_is_allowed($this->auth->owner_id, $this->auth->observer, 'view_storage'))) {
			throw new DAV\Exception\Forbidden('Permission denied.');
		}

		$modulename = \App::$module;
		if ($this->red_path === '/' && $name === $modulename) {
			return new Directory('/' . $modulename, $this->auth);
		}

		$x = $this->FileData($this->ext_path . '/' . $name, $this->auth);
		if ($x) {
			return $x;
		}

		throw new DAV\Exception\NotFound('The file with name: ' . $name . ' could not be found.');
	}

	/**
	 * @brief Returns the name of the directory.
	 *
	 * @return string
	 */
	public function getName() {
		//logger(basename($this->red_path), LOGGER_DATA);
		return (basename($this->red_path));
	}

	/**
	 * @brief Renames the directory.
	 *
	 * @todo handle duplicate directory name
	 *
	 * @throw "\Sabre\DAV\Exception\Forbidden"
	 * @param string $name The new name of the directory.
	 * @return void
	 */
	public function setName($name) {
		logger('old name ' . basename($this->red_path) . ' -> ' . $name, LOGGER_DATA);

		if ((! $name) || (! $this->auth->owner_id)) {
			logger('permission denied ' . $name);
			throw new DAV\Exception\Forbidden('Permission denied.');
		}

		if (! perm_is_allowed($this->auth->owner_id, $this->auth->observer, 'write_storage')) {
			logger('permission denied '. $name);
			throw new DAV\Exception\Forbidden('Permission denied.');
		}

		list($parent_path, ) = \Sabre\Uri\split($this->red_path);
		$new_path = $parent_path . '/' . $name;

		$r = q("UPDATE attach SET filename = '%s' WHERE hash = '%s' AND uid = %d",
			dbesc($name),
			dbesc($this->folder_hash),
			intval($this->auth->owner_id)
		);

		$x = attach_syspaths($this->auth->owner_id,$this->folder_hash);

		$y = q("update attach set display_path = '%s' where hash = '%s' and uid = %d",
			dbesc($x['path']),
			dbesc($this->folder_hash),
			intval($this->auth->owner_id)
		);

		$ch = channelx_by_n($this->auth->owner_id);
		if ($ch) {
			$sync = attach_export_data($ch, $this->folder_hash);
			if ($sync)
				build_sync_packet($ch['channel_id'], array('file' => array($sync)));
		}

		$this->red_path = $new_path;
	}

	/**
	 * @brief Creates a new file in the directory.
	 *
	 * Data will either be supplied as a stream resource, or in certain cases
	 * as a string. Keep in mind that you may have to support either.
	 *
	 * After successful creation of the file, you may choose to return the ETag
	 * of the new file here.
	 *
	 * @throw "\Sabre\DAV\Exception\Forbidden"
	 * @param string $name Name of the file
	 * @param resource|string $data Initial payload
	 * @return null|string ETag
	 */
	public function createFile($name, $data = null) {
		logger('create file in directory ' . $name, LOGGER_DEBUG);

		if (! $this->auth->owner_id) {
			logger('permission denied ' . $name);
			throw new DAV\Exception\Forbidden('Permission denied.');
		}

		if (! perm_is_allowed($this->auth->owner_id, $this->auth->observer, 'write_storage')) {
			logger('permission denied ' . $name);
			throw new DAV\Exception\Forbidden('Permission denied.');
		}

		$mimetype = z_mime_content_type($name);

		$c = q("SELECT * FROM channel WHERE channel_id = %d AND channel_removed = 0 LIMIT 1",
			intval($this->auth->owner_id)
		);

		if (! $c) {
			logger('no channel');
			throw new DAV\Exception\Forbidden('Permission denied.');
		}

		$filesize = 0;
		$hash = random_string();

		$f = 'store/' . $this->auth->owner_nick . '/' . (($this->os_path) ? $this->os_path . '/' : '') . $hash;

		$direct = null;

		if ($this->folder_hash) {
			$r = q("select * from attach where hash = '%s' and is_dir = 1 and uid = %d limit 1",
				dbesc($this->folder_hash),
				intval($c[0]['channel_id'])
			);
			if ($r)
				$direct = $r[0];
		}

		if (($direct) && (($direct['allow_cid']) || ($direct['allow_gid']) || ($direct['deny_cid']) || ($direct['deny_gid']))) {
			$allow_cid = $direct['allow_cid'];
			$allow_gid = $direct['allow_gid'];
			$deny_cid = $direct['deny_cid'];
			$deny_gid = $direct['deny_gid'];
		}
		else {
			$allow_cid = $c[0]['channel_allow_cid'];
			$allow_gid = $c[0]['channel_allow_gid'];
			$deny_cid = $c[0]['channel_deny_cid'];
			$deny_gid = $c[0]['channel_deny_gid'];
		}

		$r = q("INSERT INTO attach ( aid, uid, hash, creator, filename, folder, os_storage, filetype, filesize, revision, is_photo, content, created, edited, os_path, display_path, allow_cid, allow_gid, deny_cid, deny_gid )
			VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
			intval($c[0]['channel_account_id']),
			intval($c[0]['channel_id']),
			dbesc($hash),
			dbesc($this->auth->observer),
			dbesc($name),
			dbesc($this->folder_hash),
			intval(1),
			dbesc($mimetype),
			intval($filesize),
			intval(0),
			intval($is_photo),
			dbesc($f),
			dbesc(datetime_convert()),
			dbesc(datetime_convert()),
			'', 
			'', 
			dbesc($allow_cid),
			dbesc($allow_gid),
			dbesc($deny_cid),
			dbesc($deny_gid)
		);

		// fetch the actual storage paths

		$xpath = attach_syspaths($this->auth->owner_id, $hash);

		// returns the number of bytes that were written to the file, or FALSE on failure
		$size = file_put_contents($f, $data);
		// delete attach entry if file_put_contents() failed
		if ($size === false) {
			logger('file_put_contents() failed to ' . $f);
			attach_delete($c[0]['channel_id'], $hash);
			return;
		}

		// returns now
		$edited = datetime_convert();

		$is_photo = 0;
		$gis = @getimagesize($f);
		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 we know it's a photo, over-ride the type in case the source system could not determine what it was

		if($is_photo) {
			q("update attach set filetype = '%s' where hash = '%s' and uid = %d",
				dbesc($gis['mime']),
				dbesc($hash),
				intval($c[0]['channel_id'])
			);
		}


		// updates entry with filesize and timestamp
		$d = q("UPDATE attach SET filesize = '%s', os_path = '%s', display_path = '%s', is_photo = %d, edited = '%s' WHERE hash = '%s' AND uid = %d",
			dbesc($size),
			dbesc($xpath['os_path']),
			dbesc($xpath['display_path']),
			intval($is_photo),
			dbesc($edited),
			dbesc($hash),
			intval($c[0]['channel_id'])
		);

		// update the folder's lastmodified timestamp
		$e = q("UPDATE attach SET edited = '%s' WHERE hash = '%s' AND uid = %d",
			dbesc($edited),
			dbesc($this->folder_hash),
			intval($c[0]['channel_id'])
		);

		$maxfilesize = get_config('system', 'maxfilesize');
		if (($maxfilesize) && ($size > $maxfilesize)) {
			attach_delete($c[0]['channel_id'], $hash);
			return;
		}

		// check against service class quota
		$limit = engr_units_to_bytes(service_class_fetch($c[0]['channel_id'], 'attach_upload_limit'));
		if ($limit !== false) {
			$z = q("SELECT SUM(filesize) AS total FROM attach WHERE aid = %d ",
				intval($c[0]['channel_account_id'])
			);
			if (($z) && ($z[0]['total'] + $size > $limit)) {
				logger('service class limit exceeded for ' . $c[0]['channel_name'] . ' total usage is ' . $z[0]['total'] . ' limit is ' . userReadableSize($limit));
				attach_delete($c[0]['channel_id'], $hash);
				return;
			}
		}

		if($is_photo) {
			$album = '';
			if ($this->folder_hash) {
				$f1 = q("select filename, display_path from attach WHERE hash = '%s' AND uid = %d",
					dbesc($this->folder_hash),
					intval($c[0]['channel_id'])
				);
				if ($f1)
					$album = (($f1[0]['display_path']) ? $f1[0]['display_path'] : $f1[0]['filename']);
			}

			require_once('include/photos.php');
			$args = array( 'resource_id' => $hash, 'album' => $album, 'os_syspath' => $f, 'os_path' => $xpath['os_path'], 'display_path' => $xpath['path'], 'filename' => $name, 'getimagesize' => $gis, 'directory' => $direct);
			$p = photo_upload($c[0], \App::get_observer(), $args);
		}
		
		\Zotlabs\Daemon\Master::Summon([ 'Thumbnail' , $this->folder_hash ]);

		$sync = attach_export_data($c[0], $hash);

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

	/**
	 * @brief Creates a new subdirectory.
	 *
	 * @param string $name the directory to create
	 * @return void
	 */
	public function createDirectory($name) {
		logger('create directory ' . $name, LOGGER_DEBUG);

		if ((! $this->auth->owner_id) || (! perm_is_allowed($this->auth->owner_id, $this->auth->observer, 'write_storage'))) {
			throw new DAV\Exception\Forbidden('Permission denied.');
		}

		$r = q("SELECT * FROM channel WHERE channel_id = %d AND channel_removed = 0 LIMIT 1",
			intval($this->auth->owner_id)
		);

		if ($r) {

			// When initiated from DAV, set the 'force' flag on attach_mkdir(). This will cause the operation to report success even if the 
			// folder already exists. 

			require_once('include/attach.php');
			$result = attach_mkdir($r[0], $this->auth->observer, array('filename' => $name, 'folder' => $this->folder_hash, 'force' => true));

			if($result['success']) {
				$sync = attach_export_data($r[0],$result['data']['hash']);
				logger('createDirectory: attach_export_data returns $sync:' . print_r($sync, true), LOGGER_DEBUG);

				if($sync) {
					build_sync_packet($r[0]['channel_id'], array('file' => array($sync)));
				}
			}
			else {
				logger('error ' . print_r($result, true), LOGGER_DEBUG);
			}
		}
	}

	/**
	 * @brief delete directory
	 */
	public function delete() {
		logger('delete file ' . basename($this->red_path), LOGGER_DEBUG);

		if ((! $this->auth->owner_id) || (! perm_is_allowed($this->auth->owner_id, $this->auth->observer, 'write_storage'))) {
			throw new DAV\Exception\Forbidden('Permission denied.');
		}

		if ($this->auth->owner_id !== $this->auth->channel_id) {
			if (($this->auth->observer !== $this->data['creator']) || intval($this->data['is_dir'])) {
				throw new DAV\Exception\Forbidden('Permission denied.');
			}
		}

		attach_delete($this->auth->owner_id, $this->folder_hash);

		$ch = channelx_by_n($this->auth->owner_id);
		if ($ch) {
			$sync = attach_export_data($ch, $this->folder_hash, true);
			if ($sync)
				build_sync_packet($ch['channel_id'], array('file' => array($sync)));
		}
	}


	/**
	 * @brief Checks if a child exists.
	 *
	 * @param string $name
	 *  The name to check if it exists.
	 * @return boolean
	 */
	public function childExists($name) {
		// On /cloud we show a list of available channels.
		// @todo what happens if no channels are available?
		$modulename = \App::$module;
		if ($this->red_path === '/' && $name === $modulename) {
			//logger('We are at ' $modulename . ' show a channel list', LOGGER_DEBUG);
			return true;
		}

		$x = $this->FileData($this->ext_path . '/' . $name, $this->auth, true);
		//logger('FileData returns: ' . print_r($x, true), LOGGER_DATA);
		if ($x)
			return true;

		return false;
	}


	public function moveInto($targetName,$sourcePath, DAV\INode $sourceNode) {

		if(! $this->auth->owner_id) {
			return false;
		}

		if(! ($sourceNode->data && $sourceNode->data->hash)) {
			return false;
		}

		return attach_move($this->auth->owner_id, $sourceNode->data->hash, $this->folder_hash);

	}


	/**
	 * @todo add description of what this function does.
	 *
	 * @throw "\Sabre\DAV\Exception\NotFound"
	 * @return void
	 */
	function getDir() {

		logger('GetDir: ' . $this->ext_path, LOGGER_DEBUG);
		$this->auth->log();
		$modulename = \App::$module;

		$file = $this->ext_path;

		$x = strpos($file, '/' . $modulename);
		if ($x === 0) {
			$file = substr($file, strlen($modulename) + 1);
		}

		if ((! $file) || ($file === '/')) {
			return;
		}

		$file = trim($file, '/');
		$path_arr = explode('/', $file);

		if (! $path_arr)
			return;

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

		$channel_name = $path_arr[0];

		$r = q("SELECT channel_id FROM channel WHERE channel_address = '%s' AND channel_removed = 0 LIMIT 1",
			dbesc($channel_name)
		);

		if (! $r) {
			throw new DAV\Exception\NotFound('The file with name: ' . $channel_name . ' could not be found.');
		}

		$channel_id = $r[0]['channel_id'];
		$this->auth->owner_id = $channel_id;
		$this->auth->owner_nick = $channel_name;

		$path = '/' . $channel_name;
		$folder = '';
		$os_path = '';

		for ($x = 1; $x < count($path_arr); $x++) {
			$r = q("select id, hash, filename, flags, is_dir from attach where folder = '%s' and filename = '%s' and uid = %d and is_dir != 0",
				dbesc($folder),
				dbesc($path_arr[$x]),
				intval($channel_id)
			);
			if ($r && intval($r[0]['is_dir'])) {
				$folder = $r[0]['hash'];
				if (strlen($os_path))
					$os_path .= '/';
				$os_path .= $folder;

				$path = $path . '/' . $r[0]['filename'];
			}
		}
		$this->folder_hash = $folder;
		$this->os_path = $os_path;
	}

	/**
	 * @brief Returns the last modification time for the directory, as a UNIX
	 * timestamp.
	 *
	 * It looks for the last edited file in the folder. If it is an empty folder
	 * it returns the lastmodified time of the folder itself, to prevent zero
	 * timestamps.
	 *
	 * @return int last modification time in UNIX timestamp
	 */
	public function getLastModified() {
		$r = q("SELECT edited FROM attach WHERE folder = '%s' AND uid = %d ORDER BY edited DESC LIMIT 1",
			dbesc($this->folder_hash),
			intval($this->auth->owner_id)
		);
		if (! $r) {
			$r = q("SELECT edited FROM attach WHERE hash = '%s' AND uid = %d LIMIT 1",
				dbesc($this->folder_hash),
				intval($this->auth->owner_id)
			);
			if (! $r)
				return '';
		}
		return datetime_convert('UTC', 'UTC', $r[0]['edited'], 'U');
	}


	/**
	 * @brief Array with all Directory and File DAV\\Node items for the given path.
 	 *
	 * @param string $file path to a directory
	 * @param \Zotlabs\Storage\BasicAuth &$auth
	 * @returns null|array \\Sabre\\DAV\\INode[]
	 * @throw "\Sabre\DAV\Exception\Forbidden"
	 * @throw "\Sabre\DAV\Exception\NotFound"
	 */
	function CollectionData($file, &$auth) {
		$ret = array();

		$x = strpos($file, '/cloud');
		if ($x === 0) {
			$file = substr($file, 6);
		}

		// return a list of channel if we are not inside a channel
		if ((! $file) || ($file === '/')) {
			return $this->ChannelList($auth);
		}

		$file = trim($file, '/');
		$path_arr = explode('/', $file);

		if (! $path_arr)
			return null;

		$channel_name = $path_arr[0];

		$r = q("SELECT channel_id FROM channel WHERE channel_address = '%s' LIMIT 1",
			dbesc($channel_name)
		);

		if (! $r)
			return null;

		$channel_id = $r[0]['channel_id'];
		$perms = permissions_sql($channel_id);

		$auth->owner_id = $channel_id;

		$path = '/' . $channel_name;

		$folder = '';
		$errors = false;
		$permission_error = false;

		for ($x = 1; $x < count($path_arr); $x++) {
			$r = q("SELECT id, hash, filename, flags, is_dir FROM attach WHERE folder = '%s' AND filename = '%s' AND uid = %d AND is_dir != 0 $perms LIMIT 1",
				dbesc($folder),
				dbesc($path_arr[$x]),
				intval($channel_id)
			);
			if (! $r) {
				// path wasn't found. Try without permissions to see if it was the result of permissions.
				$errors = true;
				$r = q("select id, hash, filename, flags, is_dir from attach where folder = '%s' and filename = '%s' and uid = %d and is_dir != 0 limit 1",
					dbesc($folder),
					basename($path_arr[$x]),
					intval($channel_id)
				);
				if ($r) {
					$permission_error = true;
				}
				break;
			}

			if ($r && intval($r[0]['is_dir'])) {
				$folder = $r[0]['hash'];
				$path = $path . '/' . $r[0]['filename'];
			}
		}

		if ($errors) {
			if ($permission_error) {
				throw new DAV\Exception\Forbidden('Permission denied.');
			}
			else {
				throw new DAV\Exception\NotFound('A component of the requested file path could not be found.');
			}
		}

		// This should no longer be needed since we just returned errors for paths not found
		if ($path !== '/' . $file) {
			logger("Path mismatch: $path !== /$file");
			return NULL;
		}

		$prefix = '';

		if(! array_key_exists('cloud_sort',$_SESSION))
			$_SESSION['cloud_sort'] = 'name';

		switch($_SESSION['cloud_sort']) {
			case 'size': 
				$suffix = ' order by is_dir desc, filesize asc ';
				break;
			// The following provides inconsistent results for directories because we re-calculate the date for directories based on the most recent change
			case 'date':
				$suffix = ' order by is_dir desc, edited asc ';
				break;
			case 'name':
			default:
				$suffix = ' order by is_dir desc, filename asc ';
				break;
		}

		$r = q("select $prefix id, uid, hash, filename, filetype, filesize, revision, folder, flags, is_dir, created, edited from attach where folder = '%s' and uid = %d $perms $suffix",
			dbesc($folder),
			intval($channel_id)
		);

		foreach ($r as $rr) {
			if(\App::$module === 'cloud' && (strpos($rr['filename'],'.') === 0) && (! get_pconfig($channel_id,'system','show_dot_files')) )
				continue;

			// @FIXME I don't think we use revisions currently in attach structures.
			// In case we see any in the wild provide a unique filename. This 
			// name may or may not be accessible

			if($rr['revision'])
				$rr['filename'] .= '-' . $rr['revision'];

			//logger('filename: ' . $rr['filename'], LOGGER_DEBUG);
			if (intval($rr['is_dir'])) {
				$ret[] = new Directory($path . '/' . $rr['filename'], $auth);
			}
			else {
				$ret[] = new File($path . '/' . $rr['filename'], $rr, $auth);
			}
		}

		return $ret;
	}


	/**
	 * @brief Returns an array with viewable channels.
	 *
	 * Get a list of Directory objects with all the channels where the visitor
	 * has <b>view_storage</b> perms.
	 *
	 *
	 * @param BasicAuth &$auth
	 * @return array Directory[]
 	 */
	function ChannelList(&$auth) {
		$ret = array();

		$r = q("SELECT channel_id, channel_address FROM channel WHERE channel_removed = 0
			AND channel_system = 0 AND (channel_pageflags & %d) = 0",
			intval(PAGE_HIDDEN)
		);

		if ($r) {
			foreach ($r as $rr) {
				if (perm_is_allowed($rr['channel_id'], $auth->observer, 'view_storage')) {
					logger('found channel: /cloud/' . $rr['channel_address'], LOGGER_DATA);
					// @todo can't we drop '/cloud'? It gets stripped off anyway in RedDirectory
					$ret[] = new Directory('/cloud/' . $rr['channel_address'], $auth);
				}
			}
		}
		return $ret;
	}


	/**
	 * @brief
	 *
	 * @param string $file
	 *  path to file or directory
	 * @param BasicAuth &$auth
	 * @param boolean $test (optional) enable test mode
	 * @return File|Directory|boolean|null
	 * @throw "\Sabre\DAV\Exception\Forbidden"
	 */
	function FileData($file, &$auth, $test = false) {
		logger($file . (($test) ? ' (test mode) ' : ''), LOGGER_DATA);

		$x = strpos($file, '/cloud');
		if ($x === 0) {
			$file = substr($file, 6);
		}
		else {
			$x = strpos($file, '/dav');
			if($x === 0)
				$file = substr($file, 4);
		}

		if ((! $file) || ($file === '/')) {
			return new Directory('/', $auth);
		}

		$file = trim($file, '/');

		$path_arr = explode('/', $file);

		if (! $path_arr)
			return null;

		$channel_name = $path_arr[0];

		$r = q("select channel_id from channel where channel_address = '%s' limit 1",
			dbesc($channel_name)
		);

		if (! $r)
			return null;

		$channel_id = $r[0]['channel_id'];

		$path = '/' . $channel_name;

		$auth->owner_id = $channel_id;

		$permission_error = false;

		$folder = '';

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

		$errors = false;

		for ($x = 1; $x < count($path_arr); $x++) {
			$r = q("select id, hash, filename, flags, is_dir from attach where folder = '%s' and filename = '%s' and uid = %d and is_dir != 0 $perms",
				dbesc($folder),
				dbesc($path_arr[$x]),
				intval($channel_id)
			);

			if ($r && intval($r[0]['is_dir'])) {
				$folder = $r[0]['hash'];
				$path = $path . '/' . $r[0]['filename'];
			}
			if (! $r) {
				$r = q("select id, uid, hash, filename, filetype, filesize, revision, folder, flags, is_dir, os_storage, created, edited from attach
					where folder = '%s' and filename = '%s' and uid = %d $perms order by filename limit 1",
					dbesc($folder),
					dbesc(basename($file)),
					intval($channel_id)
				);
			}
			if (! $r) {
				$errors = true;
				$r = q("select id, uid, hash, filename, filetype, filesize, revision, folder, flags, is_dir, os_storage, created, edited from attach
					where folder = '%s' and filename = '%s' and uid = %d order by filename limit 1",
					dbesc($folder),
					dbesc(basename($file)),
					intval($channel_id)
				);
				if ($r)
					$permission_error = true;
			}
		}

		if ($path === '/' . $file) {
			if ($test)
				return true;
			// final component was a directory.
			return new Directory($file, $auth);
		}

		if ($errors) {
			logger('not found ' . $file);
			if ($test)
				return false;
			if ($permission_error) {
				logger('permission error ' . $file);
				throw new DAV\Exception\Forbidden('Permission denied.');
			}
			return;
		}

		if ($r) {
			if ($test)
				return true;

			if (intval($r[0]['is_dir'])) {
				return new Directory($path . '/' . $r[0]['filename'], $auth);
			}
			else {
				return new File($path . '/' . $r[0]['filename'], $r[0], $auth);
			}
		}
		return false;
	}

	public function getQuotaInfo() {

		/**
		 * Returns the quota information
		 *
		 * This method MUST return an array with 2 values, the first being the total used space,
		 * the second the available space (in bytes)
		 */

		$used  = 0;
		$limit = 0;
		$free  = 0;
		
		if ($this->auth->owner_id) {
			$channel = channelx_by_n($this->auth->owner_id);
			if($channel) {
				$r = q("SELECT SUM(filesize) AS total FROM attach WHERE aid = %d",
					intval($channel['channel_account_id'])
				);
				$used  = (($r) ? (float) $r[0]['total'] : 0);
				$limit = (float) service_class_fetch($this->auth->owner_id, 'attach_upload_limit');
				if($limit) {
					// Don't let the result go negative
					$free = (($limit > $used) ? $limit - $used : 0);
				}
			}
		}

		if(! $limit) {
			$free = disk_free_space('store');
			$used = disk_total_space('store') - $free;
		}

		// prevent integer overflow on 32-bit systems

		if($used > (float) PHP_INT_MAX)
			$used = PHP_INT_MAX;
		if($free > (float) PHP_INT_MAX)
			$free = PHP_INT_MAX;

		return [ (int) $used, (int) $free ];

	}

}