aboutsummaryrefslogtreecommitdiffstats
path: root/apps/files_encryption/lib/util.php
blob: eabb34f7ab0f415a16ec6b60312498836fa7d1e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
<?php
/**
 * ownCloud
 *
 * @author Sam Tuke, Frank Karlitschek
 * @copyright 2012 Sam Tuke samtuke@owncloud.com, 
 * Frank Karlitschek frank@owncloud.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

# Bugs
# ----
# Sharing a file to a user without encryption set up will not provide them with access but won't notify the sharer
# Timeouts on first login due to encryption of very large files (fix in progress, as a result streaming is currently broken)
# Sharing all files to admin for recovery purposes still in progress
# Possibly public links are broken (not tested since last merge of master)
# encryptAll during login mangles paths: /files/files/
# encryptAll is accessing files via encryption proxy - perhaps proxies should be disabled?


# Missing features
# ----------------
# Make sure user knows if large files weren't encrypted


# Test
# ----
# Test that writing files works when recovery is enabled, and sharing API is disabled
# Test trashbin support


// Old Todo:
//  - Crypt/decrypt button in the userinterface
//  - Setting if crypto should be on by default
//  - Add a setting "Don´t encrypt files larger than xx because of performance 
//    reasons"

namespace OCA\Encryption;

/**
 * @brief Class for utilities relating to encrypted file storage system
 * @param OC_FilesystemView $view expected to have OC '/' as root path
 * @param string $userId ID of the logged in user
 * @param int $client indicating status of client side encryption. Currently
 * unused, likely to become obsolete shortly
 */

class Util {
	
	
	// Web UI:
	
	//// DONE: files created via web ui are encrypted
	//// DONE: file created & encrypted via web ui are readable in web ui
	//// DONE: file created & encrypted via web ui are readable via webdav
	
	
	// WebDAV:
	
	//// DONE: new data filled files added via webdav get encrypted
	//// DONE: new data filled files added via webdav are readable via webdav
	//// DONE: reading unencrypted files when encryption is enabled works via 
	////       webdav
	//// DONE: files created & encrypted via web ui are readable via webdav
	
	
	// Legacy support:
	
	//// DONE: add method to check if file is encrypted using new system
	//// DONE: add method to check if file is encrypted using old system
	//// DONE: add method to fetch legacy key
	//// DONE: add method to decrypt legacy encrypted data
	
	
	// Admin UI:
	
	//// DONE: changing user password also changes encryption passphrase
	
	//// TODO: add support for optional recovery in case of lost passphrase / keys
	//// TODO: add admin optional required long passphrase for users
	//// TODO: add UI buttons for encrypt / decrypt everything
	//// TODO: implement flag system to allow user to specify encryption by folder, subfolder, etc.
	
	
	// Sharing:
	
	//// TODO: add support for encrypting to multiple public keys
	//// TODO: add support for decrypting to multiple private keys
	
	
	// Integration testing:
	
	//// TODO: test new encryption with versioning
	//// TODO: test new encryption with sharing
	//// TODO: test new encryption with proxies
	
	
	private $view; // OC_FilesystemView object for filesystem operations
	private $userId; // ID of the currently logged-in user
	private $pwd; // User Password
	private $client; // Client side encryption mode flag
	private $publicKeyDir; // Dir containing all public user keys
	private $encryptionDir; // Dir containing user's files_encryption
	private $keyfilesPath; // Dir containing user's keyfiles
	private $shareKeysPath; // Dir containing env keys for shared files
	private $publicKeyPath; // Path to user's public key
	private $privateKeyPath; // Path to user's private key

	public function __construct( \OC_FilesystemView $view, $userId, $client = false ) {
	
		$this->view = $view;
		$this->userId = $userId;
		$this->client = $client;
		$this->userDir =  '/' . $this->userId;
		$this->fileFolderName = 'files';
		$this->userFilesDir =  '/' . $this->userId . '/' . $this->fileFolderName; // TODO: Does this need to be user configurable?
		$this->publicKeyDir =  '/' . 'public-keys';
		$this->encryptionDir =  '/' . $this->userId . '/' . 'files_encryption';
		$this->keyfilesPath = $this->encryptionDir . '/' . 'keyfiles';
		$this->shareKeysPath = $this->encryptionDir . '/' . 'share-keys';
		$this->publicKeyPath = $this->publicKeyDir . '/' . $this->userId . '.public.key'; // e.g. data/public-keys/admin.public.key
		$this->privateKeyPath = $this->encryptionDir . '/' . $this->userId . '.private.key'; // e.g. data/admin/admin.private.key
		
	}
	
	public function ready() {
		
		if( 
		!$this->view->file_exists( $this->encryptionDir )
		or !$this->view->file_exists( $this->keyfilesPath )
		or !$this->view->file_exists( $this->shareKeysPath )
		or !$this->view->file_exists( $this->publicKeyPath )
		or !$this->view->file_exists( $this->privateKeyPath ) 
		) {
		
			return false;
			
		} else {
		
			return true;
			
		}
	
	}
	
        /**
         * @brief Sets up user folders and keys for serverside encryption
         * @param $passphrase passphrase to encrypt server-stored private key with
         */
	public function setupServerSide( $passphrase = null ) {
		
		// Set directories to check / create
		$setUpDirs = array( 
			$this->userDir
			, $this->userFilesDir
			, $this->publicKeyDir
			, $this->encryptionDir
			, $this->keyfilesPath
			, $this->shareKeysPath
		);
		
		// Check / create all necessary dirs
		foreach ( $setUpDirs as $dirPath ) {
		
			if( !$this->view->file_exists( $dirPath ) ) {
			
				$this->view->mkdir( $dirPath );
			
			}
		
		}
		
		// Create user keypair
		if ( 
			! $this->view->file_exists( $this->publicKeyPath ) 
			or ! $this->view->file_exists( $this->privateKeyPath ) 
		) {
		
			// Generate keypair
			$keypair = Crypt::createKeypair();
			
			\OC_FileProxy::$enabled = false;
			
			// Save public key
			$this->view->file_put_contents( $this->publicKeyPath, $keypair['publicKey'] );
			
			// Encrypt private key with user pwd as passphrase
			$encryptedPrivateKey = Crypt::symmetricEncryptFileContent( $keypair['privateKey'], $passphrase );
			
			// Save private key
			$this->view->file_put_contents( $this->privateKeyPath, $encryptedPrivateKey );
			
			\OC_FileProxy::$enabled = true;

            // create database configuration
            $sql = 'INSERT INTO `*PREFIX*encryption` (`uid`,`mode`,`recovery`) VALUES (?,?,?)';
            $args = array( $this->userId, 'server-side', 0);
            $query = \OCP\DB::prepare( $sql );
            $query->execute( $args );
		}
		
		return true;
	
	}
	
	/**
	 * @brief Check whether pwd recovery is enabled for a given user
	 * @return bool
	 * @note If records are not being returned, check for a hidden space 
	 *       at the start of the uid in db
	 */
	public function recoveryEnabled() {
	
		$sql = 'SELECT 
				recovery 
			FROM 
				`*PREFIX*encryption` 
			WHERE 
				uid = ?';
				
		$args = array( $this->userId );

		$query = \OCP\DB::prepare( $sql );
		
		$result = $query->execute( $args );
		
		// Set default in case no records found
		$recoveryEnabled = 0;
		
		while( $row = $result->fetchRow() ) {
		
			$recoveryEnabled = $row['recovery'];
			
		}
		
		return $recoveryEnabled;
	
	}
	
	/**
	 * @brief Enable / disable pwd recovery for a given user
	 * @param bool $enabled Whether to enable or disable recovery
	 * @return bool
	 */
	public function setRecovery( $enabled ) {
	
		$sql = 'UPDATE 
				*PREFIX*encryption 
			SET 
				recovery = ? 
			WHERE 
				uid = ?';
		
		// Ensure value is an integer
		$enabled = intval( $enabled );
		
		$args = array( $enabled, $this->userId );

		$query = \OCP\DB::prepare( $sql );
		
		if ( $query->execute( $args ) ) {
		
			return true;
			
		} else {
		
			return false;
			
		}
		
	}
	
	/**
	 * @brief Find all files and their encryption status within a directory
	 * @param string $directory The path of the parent directory to search
	 * @return mixed false if 0 found, array on success. Keys: name, path
	 
	 * @note $directory needs to be a path relative to OC data dir. e.g.
	 *       /admin/files NOT /backup OR /home/www/oc/data/admin/files
	 */
	public function findEncFiles( $directory ) {
		
		// Disable proxy - we don't want files to be decrypted before
		// we handle them
		\OC_FileProxy::$enabled = false;
		
		$found = array( 'plain' => array(), 'encrypted' => array(), 'legacy' => array() );
		
		if ( 
			$this->view->is_dir( $directory ) 
			&& $handle = $this->view->opendir( $directory ) 
		) {
		
			while ( false !== ( $file = readdir( $handle ) ) ) {
				
				if (
				$file != "." 
				&& $file != ".."
				) {
					
					$filePath = $directory . '/' . $this->view->getRelativePath( '/' . $file );
					$relPath = $this->stripUserFilesPath( $filePath );
					
					// If the path is a directory, search 
					// its contents
					if ( $this->view->is_dir( $filePath ) ) { 
						
						$this->findEncFiles( $filePath );
					
					// If the path is a file, determine 
					// its encryption status
					} elseif ( $this->view->is_file( $filePath ) ) {
						
						// Disable proxies again, some-
						// where they got re-enabled :/
						\OC_FileProxy::$enabled = false;
						
						$data = $this->view->file_get_contents( $filePath );
						
						// If the file is encrypted
						// NOTE: If the userId is 
						// empty or not set, file will 
						// detected as plain
						// NOTE: This is inefficient;
						// scanning every file like this
						// will eat server resources :(
						if ( 
							Keymanager::getFileKey( $this->view, $this->userId, $relPath )
							&& Crypt::isCatfileContent( $data )
						) {
						
							$found['encrypted'][] = array( 'name' => $file, 'path' => $filePath );
						
						// If the file uses old 
						// encryption system
						} elseif (  Crypt::isLegacyEncryptedContent( $this->tail( $filePath, 3 ), $relPath ) ) {
							
							$found['legacy'][] = array( 'name' => $file, 'path' => $filePath );
							
						// If the file is not encrypted
						} else {
						
							$found['plain'][] = array( 'name' => $file, 'path' => $relPath );
						
						}
					
					}
					
				}
				
			}
			
			\OC_FileProxy::$enabled = true;
			
			if ( empty( $found ) ) {
			
				return false;
			
			} else {
				
				return $found;
			
			}
		
		}
		
		\OC_FileProxy::$enabled = true;
		
		return false;

	}
	
        /**
         * @brief Fetch the last lines of a file efficiently
         * @note Safe to use on large files; does not read entire file to memory
         * @note Derivative of http://tekkie.flashbit.net/php/tail-functionality-in-php
         */
	public function tail( $filename, $numLines ) {
		
		\OC_FileProxy::$enabled = false;
		
		$text = '';
		$pos = -1;
		$handle = $this->view->fopen( $filename, 'r' );

		while ( $numLines > 0 ) {
		
			--$pos;

			if( fseek( $handle, $pos, SEEK_END ) !== 0 ) {
			
				rewind( $handle );
				$numLines = 0;
				
			} elseif ( fgetc( $handle ) === "\n" ) {
			
				--$numLines;
				
			}

			$block_size = ( -$pos ) % 8192;
			if ( $block_size === 0 || $numLines === 0 ) {
			
				$text = fread( $handle, ( $block_size === 0 ? 8192 : $block_size ) ) . $text;
				
			}
		}

		fclose( $handle );
		
		\OC_FileProxy::$enabled = true;
		
		return $text;
	}
	
    /**
     * @brief Check if a given path identifies an encrypted file
     * @return true / false
     */
	public function isEncryptedPath( $path ) {
	
		// Disable encryption proxy so data retreived is in its 
		// original form
		\OC_FileProxy::$enabled = false;
	
		$data = $this->view->file_get_contents( $path );
		
		\OC_FileProxy::$enabled = true;
		
		return Crypt::isCatfileContent( $data );
	
	}

    /**
     * @brief get the file size of the unencrypted file
     *
     * @param $path absolute path
     * @return true / false if file is encrypted
     */

    public function getFileSize($path) {
        $result = 0;

        // Disable encryption proxy to prevent recursive calls
        $proxyStatus = \OC_FileProxy::$enabled;
        \OC_FileProxy::$enabled = false;

        // Reformat path for use with OC_FSV
        $pathSplit = explode( '/', $path );
        $pathRelative = implode( '/', array_slice( $pathSplit, 3 ) );

        if ($pathSplit[2] == 'files' && $this->view->file_exists($path) && $this->isEncryptedPath($path)) {

            // get the size from filesystem
            $fullPath = $this->view->getLocalFile($path);
            $size = filesize($fullPath);

            // calculate last chunk nr
            $lastChunckNr = floor($size / 8192);

            // open stream
            $stream = fopen('crypt://' . $pathRelative, "r");

            if(is_resource($stream)) {
                // calculate last chunk position
                $lastChunckPos = ($lastChunckNr * 8192);

                // seek to end
                fseek($stream, $lastChunckPos);

                // get the content of the last chunk
                $lastChunkContent = fread($stream, 8192);

                // calc the real file size with the size of the last chunk
                $realSize = (($lastChunckNr * 6126) + strlen($lastChunkContent));

                // store file size
                $result = $realSize;
            }
        }

        \OC_FileProxy::$enabled = $proxyStatus;

        return $result;
    }
    /**
     * @brief fix the file size of the encrypted file
     *
     * @param $path absolute path
     * @return true / false if file is encrypted
     */

    public function fixFileSize($path) {
        $result = false;

        // Disable encryption proxy to prevent recursive calls
        $proxyStatus = \OC_FileProxy::$enabled;
        \OC_FileProxy::$enabled = false;

        $realSize = $this->getFileSize($path);
        if($realSize > 0) {
            $cached = $this->view->getFileInfo($path);
            $cached['encrypted'] = 1;

            // set the size
            $cached['unencrypted_size'] = $realSize;

            // put file info
            $this->view->putFileInfo( $path, $cached );

            $result = true;
        }

        \OC_FileProxy::$enabled = $proxyStatus;

        return $result;
    }

	/**
	 * @brief Format a path to be relative to the /user/files/ directory
	 */
	public function stripUserFilesPath( $path ) {
	
		$trimmed = ltrim( $path, '/' );
		$split = explode( '/', $trimmed );
		$sliced = array_slice( $split, 2 );
		$relPath = implode( '/', $sliced );
		
		return $relPath;
	
	}
	
	/**
	 * @brief Format a shared path to be relative to the /user/files/ directory
	 * @note Expects a path like /uid/files/Shared/filepath
	 */
	public function stripSharedFilePath( $path ) {
	
		$trimmed = ltrim( $path, '/' );
		$split = explode( '/', $trimmed );
		$sliced = array_slice( $split, 3 );
		$relPath = implode( '/', $sliced );
		
		return $relPath;
	
	}
	
	public function isSharedPath( $path ) {
	
		$trimmed = ltrim( $path, '/' );
		$split = explode( '/', $trimmed );
		
		if ( $split[2] == "Shared" ) {
		
			return true;
		
		} else {
		
			return false;
		
		}
	
	}
	
	/**
	 * @brief Encrypt all files in a directory
	 * @param string $publicKey the public key to encrypt files with
	 * @param string $dirPath the directory whose files will be encrypted
	 * @note Encryption is recursive
	 */
	public function encryptAll( $publicKey, $dirPath, $legacyPassphrase = null, $newPassphrase = null ) {
		
		if ( $found = $this->findEncFiles( $dirPath ) ) {
		
			// Disable proxy to prevent file being encrypted twice
			\OC_FileProxy::$enabled = false;
		
			// Encrypt unencrypted files
			foreach ( $found['plain'] as $plainFile ) {
				
				//relative to data/<user>/file
				$relPath = $plainFile['path'];
				
				//relative to /data
				$rawPath = $this->userId . '/files/' .  $plainFile['path'];
				
				// Open plain file handle for binary reading
				$plainHandle1 = $this->view->fopen( $rawPath, 'rb' );
				
				// 2nd handle for moving plain file - view->rename() doesn't work, this is a workaround
				$plainHandle2 = $this->view->fopen( $rawPath . '.plaintmp', 'wb' );
				
				// Move plain file to a temporary location
				stream_copy_to_stream( $plainHandle1, $plainHandle2 );
				
				// Close access to original file
// 				$this->view->fclose( $plainHandle1 ); // not implemented in view{}
				
				// Delete original plain file so we can rename enc file later
				$this->view->unlink( $rawPath );
				
				// Open enc file handle for binary writing, with same filename as original plain file
				$encHandle = fopen( 'crypt://' . $relPath, 'wb' );
				
				// Save data from plain stream to new encrypted file via enc stream
				// NOTE: Stream{} will be invoked for handling 
				// the encryption, and should handle all keys 
				// and their generation etc. automatically
				$size = stream_copy_to_stream( $plainHandle2, $encHandle );
				
				// Delete temporary plain copy of file
				$this->view->unlink( $rawPath . '.plaintmp' );
				
				// Add the file to the cache
				\OC\Files\Filesystem::putFileInfo( $plainFile['path'], array( 'encrypted'=>true, 'size' => $size ), '' );
			
			}
			
			// Encrypt legacy encrypted files
			if ( 
				! empty( $legacyPassphrase ) 
				&& ! empty( $newPassphrase ) 
			) {
			
				foreach ( $found['legacy'] as $legacyFile ) {
				
					// Fetch data from file
					$legacyData = $this->view->file_get_contents( $legacyFile['path'] );
				
					// Recrypt data, generate catfile
					$recrypted = Crypt::legacyKeyRecryptKeyfile( $legacyData, $legacyPassphrase, $publicKey, $newPassphrase );
					
					$relPath = $legacyFile['path'];
					$rawPath = $this->userId . '/files/' .  $plainFile['path'];
					
					// Save keyfile
					Keymanager::setFileKey( $this->view, $relPath, $this->userId, $recrypted['key'] );
					
					// Overwrite the existing file with the encrypted one
					$this->view->file_put_contents( $rawPath, $recrypted['data'] );
					
					$size = strlen( $recrypted['data'] );
					
					// Add the file to the cache
					\OC\Files\Filesystem::putFileInfo( $rawPath, array( 'encrypted'=>true, 'size' => $size ), '' );
				
				}
				
			}
			
			\OC_FileProxy::$enabled = true;
			
			// If files were found, return true
			return true;
		
		} else {
		
			// If no files were found, return false
			return false;
			
		}
		
	}
	
	/**
	 * @brief Return important encryption related paths
	 * @param string $pathName Name of the directory to return the path of
	 * @return string path
	 */
	public function getPath( $pathName ) {
	
		switch ( $pathName ) {
			
			case 'publicKeyDir':
			
				return $this->publicKeyDir;
				
				break;
				
			case 'encryptionDir':
			
				return $this->encryptionDir;
				
				break;
				
			case 'keyfilesPath':
			
				return $this->keyfilesPath;
				
				break;
				
			case 'publicKeyPath':
			
				return $this->publicKeyPath;
				
				break;
				
			case 'privateKeyPath':
			
				return $this->privateKeyPath;
				
				break;
			
		}
		
	}
	
	/**
	 * @brief get path of a file.
	 * @param $fileId id of the file
	 * @return path of the file
	 */
	public static function fileIdToPath( $fileId ) {
	
		$query = \OC_DB::prepare( 'SELECT `path`'
				.' FROM `*PREFIX*filecache`'
				.' WHERE `fileid` = ?' );
				
		$result = $query->execute( array( $fileId ) );
		
		$row = $result->fetchRow();
		
		return substr( $row['path'], 5 );
	
	}
	
	/**
	 * @brief Filter an array of UIDs to return only ones ready for sharing
	 * @param array $unfilteredUsers users to be checked for sharing readiness
	 * @return multi-dimensional array. keys: ready, unready
	 */
	public function filterShareReadyUsers( $unfilteredUsers ) {
	
		// This array will collect the filtered IDs
		$readyIds = $unreadyIds = array();
	
		// Loop through users and create array of UIDs that need new keyfiles
		foreach ( $unfilteredUsers as $user ) {
		
			$util = new Util( $this->view, $user );
				
			// Check that the user is encryption capable, or is the
			// public system user 'ownCloud' (for public shares)
			if ( 
				$util->ready() 
				or $user == 'owncloud'
			) {
			
				// Construct array of ready UIDs for Keymanager{}
				$readyIds[] = $user;
				
			} else {
				
				// Construct array of unready UIDs for Keymanager{}
				$unreadyIds[] = $user;
				
				// Log warning; we can't do necessary setup here
				// because we don't have the user passphrase
				\OC_Log::write( 'Encryption library', '"'.$user.'" is not setup for encryption', \OC_Log::WARN );
		
			}
		
		}
		
		return array ( 
			'ready' => $readyIds
			, 'unready' => $unreadyIds
		);
		
	}
		
	/**
	 * @brief Decrypt a keyfile without knowing how it was encrypted
	 * @param string $filePath
	 * @param string $fileOwner
	 * @param string $privateKey
	 * @note Checks whether file was encrypted with openssl_seal or 
	 *       openssl_encrypt, and decrypts accrdingly
	 * @note This was used when 2 types of encryption for keyfiles was used, 
	 *       but now we've switched to exclusively using openssl_seal()
	 */
	public function decryptUnknownKeyfile( $filePath, $fileOwner, $privateKey ) {

		// Get the encrypted keyfile
		// NOTE: the keyfile format depends on how it was encrypted! At
		// this stage we don't know how it was encrypted
		$encKeyfile = Keymanager::getFileKey( $this->view, $this->userId, $filePath );
		
		// We need to decrypt the keyfile
		// Has the file been shared yet?
		if ( 
			$this->userId == $fileOwner
			&& ! Keymanager::getShareKey( $this->view, $this->userId, $filePath ) // NOTE: we can't use isShared() here because it's a post share hook so it always returns true
		) {
		
			// The file has no shareKey, and its keyfile must be 
			// decrypted conventionally
			$plainKeyfile = Crypt::keyDecrypt( $encKeyfile, $privateKey );
			
		
		} else {
			
			// The file has a shareKey and must use it for decryption
			$shareKey = Keymanager::getShareKey( $this->view, $this->userId, $filePath );
		
			$plainKeyfile = Crypt::multiKeyDecrypt( $encKeyfile, $shareKey, $privateKey );
			
		}
		
		return $plainKeyfile;

	}
	
	/**
	 * @brief Encrypt keyfile to multiple users
	 * @param array $users list of users which should be able to access the file
	 * @param string $filePath path of the file to be shared
	 */
	public function setSharedFileKeyfiles( Session $session, array $users, $filePath ) {
	
		// Make sure users are capable of sharing
		$filteredUids = $this->filterShareReadyUsers( $users );
		
// 		trigger_error( print_r($filteredUids, 1) );
		
		if ( ! empty( $filteredUids['unready'] ) ) {
		
			// Notify user of unready userDir
			// TODO: Move this out of here; it belongs somewhere else
			\OCP\JSON::error();
			
		}
		
		// Get public keys for each user, ready for generating sharekeys
		$userPubKeys = Keymanager::getPublicKeys( $this->view, $filteredUids['ready'] );

		\OC_FileProxy::$enabled = false;

		// Get the current users's private key for decrypting existing keyfile
		$privateKey = $session->getPrivateKey();
		
		$fileOwner = \OC\Files\Filesystem::getOwner( $filePath );
		
		// Decrypt keyfile
		$plainKeyfile = $this->decryptUnknownKeyfile( $filePath, $fileOwner, $privateKey );
		
		// Re-enc keyfile to (additional) sharekeys
		$multiEncKey = Crypt::multiKeyEncrypt( $plainKeyfile, $userPubKeys );
		
		// Save the recrypted key to it's owner's keyfiles directory
		// Save new sharekeys to all necessary user directory
		// TODO: Reuse the keyfile, it it exists, instead of making a new one
		if ( 
			! Keymanager::setFileKey( $this->view, $filePath, $fileOwner, $multiEncKey['data'] )
			|| ! Keymanager::setShareKeys( $this->view, $filePath, $multiEncKey['keys'] ) 
		) {

			trigger_error( "SET Share keys failed" );

		}

		// Delete existing keyfile
		// Do this last to ensure file is recoverable in case of error
		// Keymanager::deleteFileKey( $this->view, $this->userId, $params['fileTarget'] );
	
		\OC_FileProxy::$enabled = true;

		return true;
	}
	
	/**
	 * @brief Find, sanitise and format users sharing a file
	 * @note This wraps other methods into a portable bundle
	 */
	public function getSharingUsersArray( $sharingEnabled, $filePath, $currentUserId = false ) {

		// Check if key recovery is enabled
		$recoveryEnabled = $this->recoveryEnabled();
		
		// Make sure that a share key is generated for the owner too
		list($owner, $ownerPath) = $this->getUidAndFilename($filePath);

		if ( $sharingEnabled ) {
		
			// Find out who, if anyone, is sharing the file
			$userIds = \OCP\Share::getUsersSharingFile( $ownerPath, $owner,true, true, true );
		
		}
		
		// If recovery is enabled, add the 
		// Admin UID to list of users to share to
		if ( $recoveryEnabled ) {
		
			// FIXME: Create a separate admin user purely for recovery, and create method in util for fetching this id from DB?
			$adminUid = 'recoveryAdmin';
		
			$userIds[] = $adminUid;
			
		}

        // add current user if given
        if($currentUserId != false) {
            $userIds[] = $currentUserId;
        }

		// Remove duplicate UIDs
		$uniqueUserIds = array_unique ( $userIds );
		
		return $uniqueUserIds;

	}
		
	/**
	 * @brief get uid of the owners of the file and the path to the file
	 * @param $path Path of the file to check
	 * @note $shareFilePath must be relative to data/UID/files. Files 
	 *       relative to /Shared are also acceptable
	 * @return array
	 */
	public function getUidAndFilename( $path ) {

		$fileOwnerUid = \OC\Files\Filesystem::getOwner( $path );
		
		// Check that UID is valid
		if ( ! \OCP\User::userExists( $fileOwnerUid ) ) {
		
			throw new \Exception( 'Could not find owner (UID = "' . var_export( $fileOwnerUid, 1 ) . '") of file "' . $path . '"' );
			
		}

		// NOTE: Bah, this dependency should be elsewhere
		\OC\Files\Filesystem::initMountPoints( $fileOwnerUid );
		
		// If the file owner is the currently logged in user
		if ( $fileOwnerUid == $this->userId ) {
		
			// Assume the path supplied is correct
			$filename = $path;
			
		} else {
		
			$info = \OC\Files\Filesystem::getFileInfo( $path );
			$ownerView = new \OC\Files\View( '/' . $fileOwnerUid . '/files' );
			
			// Fetch real file path from DB
			$filename = $ownerView->getPath( $info['fileid'] ); // TODO: Check that this returns a path without including the user data dir
		
		}
		
		// Make path relative for use by $view
		$relpath = $fileOwnerUid . '/' . $this->fileFolderName . '/' . $filename;
		
		// Check that the filename we're using is working
		if ( $this->view->file_exists( $relpath ) ) {
		
			return array ( $fileOwnerUid, $filename );
			
		} else {
		
			return false;
			
		}
		
	}

	/**
	 * @brief geo recursively through a dir and collect all files and sub files.
	 * @param type $dir relative to the users files folder
	 * @return array with list of files relative to the users files folder
	 */
	public function getAllFiles($dir) {
		$result = array();

        $content = $this->view->getDirectoryContent($this->userFilesDir.$dir);

        // handling for re shared folders
        $path_split = explode( '/', $dir );
        $shared = '';
        if($path_split[1] === 'Shared') {
            $shared = '/Shared';
        }

		foreach ($content as $c) {
			if ($c['type'] === "dir" ) {
                $result = array_merge($result, $this->getAllFiles($shared.substr($c['path'],5)));
			} else {
                $result[] = $shared.substr($c['path'], 5);
			}
		}
		return $result;
	}

}