Completed
Push — stable12 ( c7e4bd...b91394 )
by
unknown
32:05 queued 21:31
created
apps/dav/lib/CardDAV/AddressBookRoot.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@
 block discarded – undo
30 30
 
31 31
 	/**
32 32
 	 * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
-	 * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
33
+	 * @param CardDavBackend $carddavBackend
34 34
 	 * @param string $principalPrefix
35 35
 	 */
36 36
 	public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
Please login to merge, or discard this patch.
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -25,46 +25,46 @@
 block discarded – undo
25 25
 
26 26
 class AddressBookRoot extends \Sabre\CardDAV\AddressBookRoot {
27 27
 
28
-	/** @var IL10N */
29
-	protected $l10n;
28
+    /** @var IL10N */
29
+    protected $l10n;
30 30
 
31
-	/**
32
-	 * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
-	 * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
34
-	 * @param string $principalPrefix
35
-	 */
36
-	public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
37
-		parent::__construct($principalBackend, $carddavBackend, $principalPrefix);
38
-		$this->l10n = \OC::$server->getL10N('dav');
39
-	}
31
+    /**
32
+     * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
+     * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
34
+     * @param string $principalPrefix
35
+     */
36
+    public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
37
+        parent::__construct($principalBackend, $carddavBackend, $principalPrefix);
38
+        $this->l10n = \OC::$server->getL10N('dav');
39
+    }
40 40
 
41
-	/**
42
-	 * This method returns a node for a principal.
43
-	 *
44
-	 * The passed array contains principal information, and is guaranteed to
45
-	 * at least contain a uri item. Other properties may or may not be
46
-	 * supplied by the authentication backend.
47
-	 *
48
-	 * @param array $principal
49
-	 * @return \Sabre\DAV\INode
50
-	 */
51
-	function getChildForPrincipal(array $principal) {
41
+    /**
42
+     * This method returns a node for a principal.
43
+     *
44
+     * The passed array contains principal information, and is guaranteed to
45
+     * at least contain a uri item. Other properties may or may not be
46
+     * supplied by the authentication backend.
47
+     *
48
+     * @param array $principal
49
+     * @return \Sabre\DAV\INode
50
+     */
51
+    function getChildForPrincipal(array $principal) {
52 52
 
53
-		return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->l10n);
53
+        return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->l10n);
54 54
 
55
-	}
55
+    }
56 56
 
57
-	function getName() {
57
+    function getName() {
58 58
 
59
-		if ($this->principalPrefix === 'principals') {
60
-			return parent::getName();
61
-		}
62
-		// Grabbing all the components of the principal path.
63
-		$parts = explode('/', $this->principalPrefix);
59
+        if ($this->principalPrefix === 'principals') {
60
+            return parent::getName();
61
+        }
62
+        // Grabbing all the components of the principal path.
63
+        $parts = explode('/', $this->principalPrefix);
64 64
 
65
-		// We are only interested in the second part.
66
-		return $parts[1];
65
+        // We are only interested in the second part.
66
+        return $parts[1];
67 67
 
68
-	}
68
+    }
69 69
 
70 70
 }
Please login to merge, or discard this patch.
lib/private/Share20/DefaultShareProvider.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -770,7 +770,7 @@
 block discarded – undo
770 770
 
771 771
 	/**
772 772
 	 * @param Share[] $shares
773
-	 * @param $userId
773
+	 * @param string $userId
774 774
 	 * @return Share[] The updates shares if no update is found for a share return the original
775 775
 	 */
776 776
 	private function resolveGroupShares($shares, $userId) {
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
 			->orderBy('id');
289 289
 
290 290
 		$cursor = $qb->execute();
291
-		while($data = $cursor->fetch()) {
291
+		while ($data = $cursor->fetch()) {
292 292
 			$children[] = $this->createShare($data);
293 293
 		}
294 294
 		$cursor->closeCursor();
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 			$user = $this->userManager->get($recipient);
334 334
 
335 335
 			if (is_null($group)) {
336
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
336
+				throw new ProviderException('Group "'.$share->getSharedWith().'" does not exist');
337 337
 			}
338 338
 
339 339
 			if (!$group->inGroup($user)) {
@@ -493,7 +493,7 @@  discard block
 block discarded – undo
493 493
 			);
494 494
 		}
495 495
 
496
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
496
+		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497 497
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498 498
 
499 499
 		$qb->orderBy('id');
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
 
550 550
 		$cursor = $qb->execute();
551 551
 		$shares = [];
552
-		while($data = $cursor->fetch()) {
552
+		while ($data = $cursor->fetch()) {
553 553
 			$shares[] = $this->createShare($data);
554 554
 		}
555 555
 		$cursor->closeCursor();
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
 			->execute();
629 629
 
630 630
 		$shares = [];
631
-		while($data = $cursor->fetch()) {
631
+		while ($data = $cursor->fetch()) {
632 632
 			$shares[] = $this->createShare($data);
633 633
 		}
634 634
 		$cursor->closeCursor();
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
 
700 700
 			$cursor = $qb->execute();
701 701
 
702
-			while($data = $cursor->fetch()) {
702
+			while ($data = $cursor->fetch()) {
703 703
 				if ($this->isAccessibleResult($data)) {
704 704
 					$shares[] = $this->createShare($data);
705 705
 				}
@@ -714,7 +714,7 @@  discard block
 block discarded – undo
714 714
 			$shares2 = [];
715 715
 
716 716
 			$start = 0;
717
-			while(true) {
717
+			while (true) {
718 718
 				$groups = array_slice($allGroups, $start, 100);
719 719
 				$start += 100;
720 720
 
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
 					));
758 758
 
759 759
 				$cursor = $qb->execute();
760
-				while($data = $cursor->fetch()) {
760
+				while ($data = $cursor->fetch()) {
761 761
 					if ($offset > 0) {
762 762
 						$offset--;
763 763
 						continue;
@@ -826,14 +826,14 @@  discard block
 block discarded – undo
826 826
 	 */
827 827
 	private function createShare($data) {
828 828
 		$share = new Share($this->rootFolder, $this->userManager);
829
-		$share->setId((int)$data['id'])
830
-			->setShareType((int)$data['share_type'])
831
-			->setPermissions((int)$data['permissions'])
829
+		$share->setId((int) $data['id'])
830
+			->setShareType((int) $data['share_type'])
831
+			->setPermissions((int) $data['permissions'])
832 832
 			->setTarget($data['file_target'])
833
-			->setMailSend((bool)$data['mail_send']);
833
+			->setMailSend((bool) $data['mail_send']);
834 834
 
835 835
 		$shareTime = new \DateTime();
836
-		$shareTime->setTimestamp((int)$data['stime']);
836
+		$shareTime->setTimestamp((int) $data['stime']);
837 837
 		$share->setShareTime($shareTime);
838 838
 
839 839
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
@@ -848,7 +848,7 @@  discard block
 block discarded – undo
848 848
 		$share->setSharedBy($data['uid_initiator']);
849 849
 		$share->setShareOwner($data['uid_owner']);
850 850
 
851
-		$share->setNodeId((int)$data['file_source']);
851
+		$share->setNodeId((int) $data['file_source']);
852 852
 		$share->setNodeType($data['item_type']);
853 853
 
854 854
 		if ($data['expiration'] !== null) {
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
 		if (isset($data['f_permissions'])) {
860 860
 			$entryData = $data;
861 861
 			$entryData['permissions'] = $entryData['f_permissions'];
862
-			$entryData['parent'] = $entryData['f_parent'];;
862
+			$entryData['parent'] = $entryData['f_parent']; ;
863 863
 			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864 864
 				\OC::$server->getMimeTypeLoader()));
865 865
 		}
@@ -878,7 +878,7 @@  discard block
 block discarded – undo
878 878
 		$result = [];
879 879
 
880 880
 		$start = 0;
881
-		while(true) {
881
+		while (true) {
882 882
 			/** @var Share[] $shareSlice */
883 883
 			$shareSlice = array_slice($shares, $start, 100);
884 884
 			$start += 100;
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
 			$shareMap = [];
894 894
 
895 895
 			foreach ($shareSlice as $share) {
896
-				$ids[] = (int)$share->getId();
896
+				$ids[] = (int) $share->getId();
897 897
 				$shareMap[$share->getId()] = $share;
898 898
 			}
899 899
 
@@ -910,8 +910,8 @@  discard block
 block discarded – undo
910 910
 
911 911
 			$stmt = $query->execute();
912 912
 
913
-			while($data = $stmt->fetch()) {
914
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
913
+			while ($data = $stmt->fetch()) {
914
+				$shareMap[$data['parent']]->setPermissions((int) $data['permissions']);
915 915
 				$shareMap[$data['parent']]->setTarget($data['file_target']);
916 916
 			}
917 917
 
@@ -1008,8 +1008,8 @@  discard block
 block discarded – undo
1008 1008
 
1009 1009
 		$cursor = $qb->execute();
1010 1010
 		$ids = [];
1011
-		while($row = $cursor->fetch()) {
1012
-			$ids[] = (int)$row['id'];
1011
+		while ($row = $cursor->fetch()) {
1012
+			$ids[] = (int) $row['id'];
1013 1013
 		}
1014 1014
 		$cursor->closeCursor();
1015 1015
 
@@ -1051,8 +1051,8 @@  discard block
 block discarded – undo
1051 1051
 
1052 1052
 		$cursor = $qb->execute();
1053 1053
 		$ids = [];
1054
-		while($row = $cursor->fetch()) {
1055
-			$ids[] = (int)$row['id'];
1054
+		while ($row = $cursor->fetch()) {
1055
+			$ids[] = (int) $row['id'];
1056 1056
 		}
1057 1057
 		$cursor->closeCursor();
1058 1058
 
@@ -1106,8 +1106,8 @@  discard block
 block discarded – undo
1106 1106
 
1107 1107
 		$users = [];
1108 1108
 		$link = false;
1109
-		while($row = $cursor->fetch()) {
1110
-			$type = (int)$row['share_type'];
1109
+		while ($row = $cursor->fetch()) {
1110
+			$type = (int) $row['share_type'];
1111 1111
 			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1112 1112
 				$uid = $row['share_with'];
1113 1113
 				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
Please login to merge, or discard this patch.
Indentation   +1103 added lines, -1103 removed lines patch added patch discarded remove patch
@@ -46,1140 +46,1140 @@
 block discarded – undo
46 46
  */
47 47
 class DefaultShareProvider implements IShareProvider {
48 48
 
49
-	// Special share type for user modified group shares
50
-	const SHARE_TYPE_USERGROUP = 2;
51
-
52
-	/** @var IDBConnection */
53
-	private $dbConn;
54
-
55
-	/** @var IUserManager */
56
-	private $userManager;
57
-
58
-	/** @var IGroupManager */
59
-	private $groupManager;
60
-
61
-	/** @var IRootFolder */
62
-	private $rootFolder;
63
-
64
-	/**
65
-	 * DefaultShareProvider constructor.
66
-	 *
67
-	 * @param IDBConnection $connection
68
-	 * @param IUserManager $userManager
69
-	 * @param IGroupManager $groupManager
70
-	 * @param IRootFolder $rootFolder
71
-	 */
72
-	public function __construct(
73
-			IDBConnection $connection,
74
-			IUserManager $userManager,
75
-			IGroupManager $groupManager,
76
-			IRootFolder $rootFolder) {
77
-		$this->dbConn = $connection;
78
-		$this->userManager = $userManager;
79
-		$this->groupManager = $groupManager;
80
-		$this->rootFolder = $rootFolder;
81
-	}
82
-
83
-	/**
84
-	 * Return the identifier of this provider.
85
-	 *
86
-	 * @return string Containing only [a-zA-Z0-9]
87
-	 */
88
-	public function identifier() {
89
-		return 'ocinternal';
90
-	}
91
-
92
-	/**
93
-	 * Share a path
94
-	 *
95
-	 * @param \OCP\Share\IShare $share
96
-	 * @return \OCP\Share\IShare The share object
97
-	 * @throws ShareNotFound
98
-	 * @throws \Exception
99
-	 */
100
-	public function create(\OCP\Share\IShare $share) {
101
-		$qb = $this->dbConn->getQueryBuilder();
102
-
103
-		$qb->insert('share');
104
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
105
-
106
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
107
-			//Set the UID of the user we share with
108
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
109
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
110
-			//Set the GID of the group we share with
111
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
112
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
113
-			//Set the token of the share
114
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
115
-
116
-			//If a password is set store it
117
-			if ($share->getPassword() !== null) {
118
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
119
-			}
120
-
121
-			//If an expiration date is set store it
122
-			if ($share->getExpirationDate() !== null) {
123
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
124
-			}
125
-
126
-			if (method_exists($share, 'getParent')) {
127
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
128
-			}
129
-		} else {
130
-			throw new \Exception('invalid share type!');
131
-		}
132
-
133
-		// Set what is shares
134
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
135
-		if ($share->getNode() instanceof \OCP\Files\File) {
136
-			$qb->setParameter('itemType', 'file');
137
-		} else {
138
-			$qb->setParameter('itemType', 'folder');
139
-		}
140
-
141
-		// Set the file id
142
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
143
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
144
-
145
-		// set the permissions
146
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
147
-
148
-		// Set who created this share
149
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
150
-
151
-		// Set who is the owner of this file/folder (and this the owner of the share)
152
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
153
-
154
-		// Set the file target
155
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
156
-
157
-		// Set the time this share was created
158
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
159
-
160
-		// insert the data and fetch the id of the share
161
-		$this->dbConn->beginTransaction();
162
-		$qb->execute();
163
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
164
-
165
-		// Now fetch the inserted share and create a complete share object
166
-		$qb = $this->dbConn->getQueryBuilder();
167
-		$qb->select('*')
168
-			->from('share')
169
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
170
-
171
-		$cursor = $qb->execute();
172
-		$data = $cursor->fetch();
173
-		$this->dbConn->commit();
174
-		$cursor->closeCursor();
175
-
176
-		if ($data === false) {
177
-			throw new ShareNotFound();
178
-		}
179
-
180
-		$share = $this->createShare($data);
181
-		return $share;
182
-	}
183
-
184
-	/**
185
-	 * Update a share
186
-	 *
187
-	 * @param \OCP\Share\IShare $share
188
-	 * @return \OCP\Share\IShare The share object
189
-	 */
190
-	public function update(\OCP\Share\IShare $share) {
191
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
192
-			/*
49
+    // Special share type for user modified group shares
50
+    const SHARE_TYPE_USERGROUP = 2;
51
+
52
+    /** @var IDBConnection */
53
+    private $dbConn;
54
+
55
+    /** @var IUserManager */
56
+    private $userManager;
57
+
58
+    /** @var IGroupManager */
59
+    private $groupManager;
60
+
61
+    /** @var IRootFolder */
62
+    private $rootFolder;
63
+
64
+    /**
65
+     * DefaultShareProvider constructor.
66
+     *
67
+     * @param IDBConnection $connection
68
+     * @param IUserManager $userManager
69
+     * @param IGroupManager $groupManager
70
+     * @param IRootFolder $rootFolder
71
+     */
72
+    public function __construct(
73
+            IDBConnection $connection,
74
+            IUserManager $userManager,
75
+            IGroupManager $groupManager,
76
+            IRootFolder $rootFolder) {
77
+        $this->dbConn = $connection;
78
+        $this->userManager = $userManager;
79
+        $this->groupManager = $groupManager;
80
+        $this->rootFolder = $rootFolder;
81
+    }
82
+
83
+    /**
84
+     * Return the identifier of this provider.
85
+     *
86
+     * @return string Containing only [a-zA-Z0-9]
87
+     */
88
+    public function identifier() {
89
+        return 'ocinternal';
90
+    }
91
+
92
+    /**
93
+     * Share a path
94
+     *
95
+     * @param \OCP\Share\IShare $share
96
+     * @return \OCP\Share\IShare The share object
97
+     * @throws ShareNotFound
98
+     * @throws \Exception
99
+     */
100
+    public function create(\OCP\Share\IShare $share) {
101
+        $qb = $this->dbConn->getQueryBuilder();
102
+
103
+        $qb->insert('share');
104
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
105
+
106
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
107
+            //Set the UID of the user we share with
108
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
109
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
110
+            //Set the GID of the group we share with
111
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
112
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
113
+            //Set the token of the share
114
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
115
+
116
+            //If a password is set store it
117
+            if ($share->getPassword() !== null) {
118
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
119
+            }
120
+
121
+            //If an expiration date is set store it
122
+            if ($share->getExpirationDate() !== null) {
123
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
124
+            }
125
+
126
+            if (method_exists($share, 'getParent')) {
127
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
128
+            }
129
+        } else {
130
+            throw new \Exception('invalid share type!');
131
+        }
132
+
133
+        // Set what is shares
134
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
135
+        if ($share->getNode() instanceof \OCP\Files\File) {
136
+            $qb->setParameter('itemType', 'file');
137
+        } else {
138
+            $qb->setParameter('itemType', 'folder');
139
+        }
140
+
141
+        // Set the file id
142
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
143
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
144
+
145
+        // set the permissions
146
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
147
+
148
+        // Set who created this share
149
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
150
+
151
+        // Set who is the owner of this file/folder (and this the owner of the share)
152
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
153
+
154
+        // Set the file target
155
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
156
+
157
+        // Set the time this share was created
158
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
159
+
160
+        // insert the data and fetch the id of the share
161
+        $this->dbConn->beginTransaction();
162
+        $qb->execute();
163
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
164
+
165
+        // Now fetch the inserted share and create a complete share object
166
+        $qb = $this->dbConn->getQueryBuilder();
167
+        $qb->select('*')
168
+            ->from('share')
169
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
170
+
171
+        $cursor = $qb->execute();
172
+        $data = $cursor->fetch();
173
+        $this->dbConn->commit();
174
+        $cursor->closeCursor();
175
+
176
+        if ($data === false) {
177
+            throw new ShareNotFound();
178
+        }
179
+
180
+        $share = $this->createShare($data);
181
+        return $share;
182
+    }
183
+
184
+    /**
185
+     * Update a share
186
+     *
187
+     * @param \OCP\Share\IShare $share
188
+     * @return \OCP\Share\IShare The share object
189
+     */
190
+    public function update(\OCP\Share\IShare $share) {
191
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
192
+            /*
193 193
 			 * We allow updating the recipient on user shares.
194 194
 			 */
195
-			$qb = $this->dbConn->getQueryBuilder();
196
-			$qb->update('share')
197
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
198
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
199
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
200
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
201
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
202
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
203
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
204
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
205
-				->execute();
206
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
207
-			$qb = $this->dbConn->getQueryBuilder();
208
-			$qb->update('share')
209
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
210
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
211
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
212
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
213
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
214
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
215
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
216
-				->execute();
217
-
218
-			/*
195
+            $qb = $this->dbConn->getQueryBuilder();
196
+            $qb->update('share')
197
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
198
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
199
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
200
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
201
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
202
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
203
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
204
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
205
+                ->execute();
206
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
207
+            $qb = $this->dbConn->getQueryBuilder();
208
+            $qb->update('share')
209
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
210
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
211
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
212
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
213
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
214
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
215
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
216
+                ->execute();
217
+
218
+            /*
219 219
 			 * Update all user defined group shares
220 220
 			 */
221
-			$qb = $this->dbConn->getQueryBuilder();
222
-			$qb->update('share')
223
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
224
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
225
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
226
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
227
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
228
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
229
-				->execute();
230
-
231
-			/*
221
+            $qb = $this->dbConn->getQueryBuilder();
222
+            $qb->update('share')
223
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
224
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
225
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
226
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
227
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
228
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
229
+                ->execute();
230
+
231
+            /*
232 232
 			 * Now update the permissions for all children that have not set it to 0
233 233
 			 */
234
-			$qb = $this->dbConn->getQueryBuilder();
235
-			$qb->update('share')
236
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
237
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
238
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
239
-				->execute();
240
-
241
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
242
-			$qb = $this->dbConn->getQueryBuilder();
243
-			$qb->update('share')
244
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
245
-				->set('password', $qb->createNamedParameter($share->getPassword()))
246
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
247
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
248
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
249
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
250
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
251
-				->set('token', $qb->createNamedParameter($share->getToken()))
252
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
253
-				->execute();
254
-		}
255
-
256
-		return $share;
257
-	}
258
-
259
-	/**
260
-	 * Get all children of this share
261
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
262
-	 *
263
-	 * @param \OCP\Share\IShare $parent
264
-	 * @return \OCP\Share\IShare[]
265
-	 */
266
-	public function getChildren(\OCP\Share\IShare $parent) {
267
-		$children = [];
268
-
269
-		$qb = $this->dbConn->getQueryBuilder();
270
-		$qb->select('*')
271
-			->from('share')
272
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
273
-			->andWhere(
274
-				$qb->expr()->in(
275
-					'share_type',
276
-					$qb->createNamedParameter([
277
-						\OCP\Share::SHARE_TYPE_USER,
278
-						\OCP\Share::SHARE_TYPE_GROUP,
279
-						\OCP\Share::SHARE_TYPE_LINK,
280
-					], IQueryBuilder::PARAM_INT_ARRAY)
281
-				)
282
-			)
283
-			->andWhere($qb->expr()->orX(
284
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
285
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
286
-			))
287
-			->orderBy('id');
288
-
289
-		$cursor = $qb->execute();
290
-		while($data = $cursor->fetch()) {
291
-			$children[] = $this->createShare($data);
292
-		}
293
-		$cursor->closeCursor();
294
-
295
-		return $children;
296
-	}
297
-
298
-	/**
299
-	 * Delete a share
300
-	 *
301
-	 * @param \OCP\Share\IShare $share
302
-	 */
303
-	public function delete(\OCP\Share\IShare $share) {
304
-		$qb = $this->dbConn->getQueryBuilder();
305
-		$qb->delete('share')
306
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
307
-
308
-		/*
234
+            $qb = $this->dbConn->getQueryBuilder();
235
+            $qb->update('share')
236
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
237
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
238
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
239
+                ->execute();
240
+
241
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
242
+            $qb = $this->dbConn->getQueryBuilder();
243
+            $qb->update('share')
244
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
245
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
246
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
247
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
248
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
249
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
250
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
251
+                ->set('token', $qb->createNamedParameter($share->getToken()))
252
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
253
+                ->execute();
254
+        }
255
+
256
+        return $share;
257
+    }
258
+
259
+    /**
260
+     * Get all children of this share
261
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
262
+     *
263
+     * @param \OCP\Share\IShare $parent
264
+     * @return \OCP\Share\IShare[]
265
+     */
266
+    public function getChildren(\OCP\Share\IShare $parent) {
267
+        $children = [];
268
+
269
+        $qb = $this->dbConn->getQueryBuilder();
270
+        $qb->select('*')
271
+            ->from('share')
272
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
273
+            ->andWhere(
274
+                $qb->expr()->in(
275
+                    'share_type',
276
+                    $qb->createNamedParameter([
277
+                        \OCP\Share::SHARE_TYPE_USER,
278
+                        \OCP\Share::SHARE_TYPE_GROUP,
279
+                        \OCP\Share::SHARE_TYPE_LINK,
280
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
281
+                )
282
+            )
283
+            ->andWhere($qb->expr()->orX(
284
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
285
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
286
+            ))
287
+            ->orderBy('id');
288
+
289
+        $cursor = $qb->execute();
290
+        while($data = $cursor->fetch()) {
291
+            $children[] = $this->createShare($data);
292
+        }
293
+        $cursor->closeCursor();
294
+
295
+        return $children;
296
+    }
297
+
298
+    /**
299
+     * Delete a share
300
+     *
301
+     * @param \OCP\Share\IShare $share
302
+     */
303
+    public function delete(\OCP\Share\IShare $share) {
304
+        $qb = $this->dbConn->getQueryBuilder();
305
+        $qb->delete('share')
306
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
307
+
308
+        /*
309 309
 		 * If the share is a group share delete all possible
310 310
 		 * user defined groups shares.
311 311
 		 */
312
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
313
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
314
-		}
315
-
316
-		$qb->execute();
317
-	}
318
-
319
-	/**
320
-	 * Unshare a share from the recipient. If this is a group share
321
-	 * this means we need a special entry in the share db.
322
-	 *
323
-	 * @param \OCP\Share\IShare $share
324
-	 * @param string $recipient UserId of recipient
325
-	 * @throws BackendError
326
-	 * @throws ProviderException
327
-	 */
328
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
329
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
330
-
331
-			$group = $this->groupManager->get($share->getSharedWith());
332
-			$user = $this->userManager->get($recipient);
333
-
334
-			if (is_null($group)) {
335
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
336
-			}
337
-
338
-			if (!$group->inGroup($user)) {
339
-				throw new ProviderException('Recipient not in receiving group');
340
-			}
341
-
342
-			// Try to fetch user specific share
343
-			$qb = $this->dbConn->getQueryBuilder();
344
-			$stmt = $qb->select('*')
345
-				->from('share')
346
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
347
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
348
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
349
-				->andWhere($qb->expr()->orX(
350
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
351
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
352
-				))
353
-				->execute();
354
-
355
-			$data = $stmt->fetch();
356
-
357
-			/*
312
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
313
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
314
+        }
315
+
316
+        $qb->execute();
317
+    }
318
+
319
+    /**
320
+     * Unshare a share from the recipient. If this is a group share
321
+     * this means we need a special entry in the share db.
322
+     *
323
+     * @param \OCP\Share\IShare $share
324
+     * @param string $recipient UserId of recipient
325
+     * @throws BackendError
326
+     * @throws ProviderException
327
+     */
328
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
329
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
330
+
331
+            $group = $this->groupManager->get($share->getSharedWith());
332
+            $user = $this->userManager->get($recipient);
333
+
334
+            if (is_null($group)) {
335
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
336
+            }
337
+
338
+            if (!$group->inGroup($user)) {
339
+                throw new ProviderException('Recipient not in receiving group');
340
+            }
341
+
342
+            // Try to fetch user specific share
343
+            $qb = $this->dbConn->getQueryBuilder();
344
+            $stmt = $qb->select('*')
345
+                ->from('share')
346
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
347
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
348
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
349
+                ->andWhere($qb->expr()->orX(
350
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
351
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
352
+                ))
353
+                ->execute();
354
+
355
+            $data = $stmt->fetch();
356
+
357
+            /*
358 358
 			 * Check if there already is a user specific group share.
359 359
 			 * If there is update it (if required).
360 360
 			 */
361
-			if ($data === false) {
362
-				$qb = $this->dbConn->getQueryBuilder();
363
-
364
-				$type = $share->getNodeType();
365
-
366
-				//Insert new share
367
-				$qb->insert('share')
368
-					->values([
369
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
370
-						'share_with' => $qb->createNamedParameter($recipient),
371
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
372
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
373
-						'parent' => $qb->createNamedParameter($share->getId()),
374
-						'item_type' => $qb->createNamedParameter($type),
375
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
376
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
377
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
378
-						'permissions' => $qb->createNamedParameter(0),
379
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
380
-					])->execute();
381
-
382
-			} else if ($data['permissions'] !== 0) {
383
-
384
-				// Update existing usergroup share
385
-				$qb = $this->dbConn->getQueryBuilder();
386
-				$qb->update('share')
387
-					->set('permissions', $qb->createNamedParameter(0))
388
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
389
-					->execute();
390
-			}
391
-
392
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
393
-
394
-			if ($share->getSharedWith() !== $recipient) {
395
-				throw new ProviderException('Recipient does not match');
396
-			}
397
-
398
-			// We can just delete user and link shares
399
-			$this->delete($share);
400
-		} else {
401
-			throw new ProviderException('Invalid shareType');
402
-		}
403
-	}
404
-
405
-	/**
406
-	 * @inheritdoc
407
-	 */
408
-	public function move(\OCP\Share\IShare $share, $recipient) {
409
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
410
-			// Just update the target
411
-			$qb = $this->dbConn->getQueryBuilder();
412
-			$qb->update('share')
413
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
414
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
415
-				->execute();
416
-
417
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
418
-
419
-			// Check if there is a usergroup share
420
-			$qb = $this->dbConn->getQueryBuilder();
421
-			$stmt = $qb->select('id')
422
-				->from('share')
423
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
424
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
425
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
426
-				->andWhere($qb->expr()->orX(
427
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
428
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
429
-				))
430
-				->setMaxResults(1)
431
-				->execute();
432
-
433
-			$data = $stmt->fetch();
434
-			$stmt->closeCursor();
435
-
436
-			if ($data === false) {
437
-				// No usergroup share yet. Create one.
438
-				$qb = $this->dbConn->getQueryBuilder();
439
-				$qb->insert('share')
440
-					->values([
441
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
442
-						'share_with' => $qb->createNamedParameter($recipient),
443
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
444
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
445
-						'parent' => $qb->createNamedParameter($share->getId()),
446
-						'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
447
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
448
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
450
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
451
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
452
-					])->execute();
453
-			} else {
454
-				// Already a usergroup share. Update it.
455
-				$qb = $this->dbConn->getQueryBuilder();
456
-				$qb->update('share')
457
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
458
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
459
-					->execute();
460
-			}
461
-		}
462
-
463
-		return $share;
464
-	}
465
-
466
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
467
-		$qb = $this->dbConn->getQueryBuilder();
468
-		$qb->select('*')
469
-			->from('share', 's')
470
-			->andWhere($qb->expr()->orX(
471
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
472
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
473
-			));
474
-
475
-		$qb->andWhere($qb->expr()->orX(
476
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
477
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
478
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
479
-		));
480
-
481
-		/**
482
-		 * Reshares for this user are shares where they are the owner.
483
-		 */
484
-		if ($reshares === false) {
485
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
486
-		} else {
487
-			$qb->andWhere(
488
-				$qb->expr()->orX(
489
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
490
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
491
-				)
492
-			);
493
-		}
494
-
495
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
496
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
497
-
498
-		$qb->orderBy('id');
499
-
500
-		$cursor = $qb->execute();
501
-		$shares = [];
502
-		while ($data = $cursor->fetch()) {
503
-			$shares[$data['fileid']][] = $this->createShare($data);
504
-		}
505
-		$cursor->closeCursor();
506
-
507
-		return $shares;
508
-	}
509
-
510
-	/**
511
-	 * @inheritdoc
512
-	 */
513
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
514
-		$qb = $this->dbConn->getQueryBuilder();
515
-		$qb->select('*')
516
-			->from('share')
517
-			->andWhere($qb->expr()->orX(
518
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
519
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
520
-			));
521
-
522
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
523
-
524
-		/**
525
-		 * Reshares for this user are shares where they are the owner.
526
-		 */
527
-		if ($reshares === false) {
528
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
529
-		} else {
530
-			$qb->andWhere(
531
-				$qb->expr()->orX(
532
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
533
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
534
-				)
535
-			);
536
-		}
537
-
538
-		if ($node !== null) {
539
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
540
-		}
541
-
542
-		if ($limit !== -1) {
543
-			$qb->setMaxResults($limit);
544
-		}
545
-
546
-		$qb->setFirstResult($offset);
547
-		$qb->orderBy('id');
548
-
549
-		$cursor = $qb->execute();
550
-		$shares = [];
551
-		while($data = $cursor->fetch()) {
552
-			$shares[] = $this->createShare($data);
553
-		}
554
-		$cursor->closeCursor();
555
-
556
-		return $shares;
557
-	}
558
-
559
-	/**
560
-	 * @inheritdoc
561
-	 */
562
-	public function getShareById($id, $recipientId = null) {
563
-		$qb = $this->dbConn->getQueryBuilder();
564
-
565
-		$qb->select('*')
566
-			->from('share')
567
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
568
-			->andWhere(
569
-				$qb->expr()->in(
570
-					'share_type',
571
-					$qb->createNamedParameter([
572
-						\OCP\Share::SHARE_TYPE_USER,
573
-						\OCP\Share::SHARE_TYPE_GROUP,
574
-						\OCP\Share::SHARE_TYPE_LINK,
575
-					], IQueryBuilder::PARAM_INT_ARRAY)
576
-				)
577
-			)
578
-			->andWhere($qb->expr()->orX(
579
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
580
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
581
-			));
582
-
583
-		$cursor = $qb->execute();
584
-		$data = $cursor->fetch();
585
-		$cursor->closeCursor();
586
-
587
-		if ($data === false) {
588
-			throw new ShareNotFound();
589
-		}
590
-
591
-		try {
592
-			$share = $this->createShare($data);
593
-		} catch (InvalidShare $e) {
594
-			throw new ShareNotFound();
595
-		}
596
-
597
-		// If the recipient is set for a group share resolve to that user
598
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
599
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
600
-		}
601
-
602
-		return $share;
603
-	}
604
-
605
-	/**
606
-	 * Get shares for a given path
607
-	 *
608
-	 * @param \OCP\Files\Node $path
609
-	 * @return \OCP\Share\IShare[]
610
-	 */
611
-	public function getSharesByPath(Node $path) {
612
-		$qb = $this->dbConn->getQueryBuilder();
613
-
614
-		$cursor = $qb->select('*')
615
-			->from('share')
616
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
617
-			->andWhere(
618
-				$qb->expr()->orX(
619
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
620
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
621
-				)
622
-			)
623
-			->andWhere($qb->expr()->orX(
624
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
625
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
626
-			))
627
-			->execute();
628
-
629
-		$shares = [];
630
-		while($data = $cursor->fetch()) {
631
-			$shares[] = $this->createShare($data);
632
-		}
633
-		$cursor->closeCursor();
634
-
635
-		return $shares;
636
-	}
637
-
638
-	/**
639
-	 * Returns whether the given database result can be interpreted as
640
-	 * a share with accessible file (not trashed, not deleted)
641
-	 */
642
-	private function isAccessibleResult($data) {
643
-		// exclude shares leading to deleted file entries
644
-		if ($data['fileid'] === null) {
645
-			return false;
646
-		}
647
-
648
-		// exclude shares leading to trashbin on home storages
649
-		$pathSections = explode('/', $data['path'], 2);
650
-		// FIXME: would not detect rare md5'd home storage case properly
651
-		if ($pathSections[0] !== 'files'
652
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
653
-			return false;
654
-		}
655
-		return true;
656
-	}
657
-
658
-	/**
659
-	 * @inheritdoc
660
-	 */
661
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
662
-		/** @var Share[] $shares */
663
-		$shares = [];
664
-
665
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
666
-			//Get shares directly with this user
667
-			$qb = $this->dbConn->getQueryBuilder();
668
-			$qb->select('s.*',
669
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
670
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
671
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
672
-			)
673
-				->selectAlias('st.id', 'storage_string_id')
674
-				->from('share', 's')
675
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
676
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
677
-
678
-			// Order by id
679
-			$qb->orderBy('s.id');
680
-
681
-			// Set limit and offset
682
-			if ($limit !== -1) {
683
-				$qb->setMaxResults($limit);
684
-			}
685
-			$qb->setFirstResult($offset);
686
-
687
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
688
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
689
-				->andWhere($qb->expr()->orX(
690
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
691
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
692
-				));
693
-
694
-			// Filter by node if provided
695
-			if ($node !== null) {
696
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
697
-			}
698
-
699
-			$cursor = $qb->execute();
700
-
701
-			while($data = $cursor->fetch()) {
702
-				if ($this->isAccessibleResult($data)) {
703
-					$shares[] = $this->createShare($data);
704
-				}
705
-			}
706
-			$cursor->closeCursor();
707
-
708
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
709
-			$user = $this->userManager->get($userId);
710
-			$allGroups = $this->groupManager->getUserGroups($user);
711
-
712
-			/** @var Share[] $shares2 */
713
-			$shares2 = [];
714
-
715
-			$start = 0;
716
-			while(true) {
717
-				$groups = array_slice($allGroups, $start, 100);
718
-				$start += 100;
719
-
720
-				if ($groups === []) {
721
-					break;
722
-				}
723
-
724
-				$qb = $this->dbConn->getQueryBuilder();
725
-				$qb->select('s.*',
726
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
727
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
728
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
729
-				)
730
-					->selectAlias('st.id', 'storage_string_id')
731
-					->from('share', 's')
732
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
733
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
734
-					->orderBy('s.id')
735
-					->setFirstResult(0);
736
-
737
-				if ($limit !== -1) {
738
-					$qb->setMaxResults($limit - count($shares));
739
-				}
740
-
741
-				// Filter by node if provided
742
-				if ($node !== null) {
743
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
744
-				}
745
-
746
-
747
-				$groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
748
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
749
-
750
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
751
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
752
-						$groups,
753
-						IQueryBuilder::PARAM_STR_ARRAY
754
-					)))
755
-					->andWhere($qb->expr()->orX(
756
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
757
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
758
-					));
759
-
760
-				$cursor = $qb->execute();
761
-				while($data = $cursor->fetch()) {
762
-					if ($offset > 0) {
763
-						$offset--;
764
-						continue;
765
-					}
766
-
767
-					if ($this->isAccessibleResult($data)) {
768
-						$shares2[] = $this->createShare($data);
769
-					}
770
-				}
771
-				$cursor->closeCursor();
772
-			}
773
-
774
-			/*
361
+            if ($data === false) {
362
+                $qb = $this->dbConn->getQueryBuilder();
363
+
364
+                $type = $share->getNodeType();
365
+
366
+                //Insert new share
367
+                $qb->insert('share')
368
+                    ->values([
369
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
370
+                        'share_with' => $qb->createNamedParameter($recipient),
371
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
372
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
373
+                        'parent' => $qb->createNamedParameter($share->getId()),
374
+                        'item_type' => $qb->createNamedParameter($type),
375
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
376
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
377
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
378
+                        'permissions' => $qb->createNamedParameter(0),
379
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
380
+                    ])->execute();
381
+
382
+            } else if ($data['permissions'] !== 0) {
383
+
384
+                // Update existing usergroup share
385
+                $qb = $this->dbConn->getQueryBuilder();
386
+                $qb->update('share')
387
+                    ->set('permissions', $qb->createNamedParameter(0))
388
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
389
+                    ->execute();
390
+            }
391
+
392
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
393
+
394
+            if ($share->getSharedWith() !== $recipient) {
395
+                throw new ProviderException('Recipient does not match');
396
+            }
397
+
398
+            // We can just delete user and link shares
399
+            $this->delete($share);
400
+        } else {
401
+            throw new ProviderException('Invalid shareType');
402
+        }
403
+    }
404
+
405
+    /**
406
+     * @inheritdoc
407
+     */
408
+    public function move(\OCP\Share\IShare $share, $recipient) {
409
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
410
+            // Just update the target
411
+            $qb = $this->dbConn->getQueryBuilder();
412
+            $qb->update('share')
413
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
414
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
415
+                ->execute();
416
+
417
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
418
+
419
+            // Check if there is a usergroup share
420
+            $qb = $this->dbConn->getQueryBuilder();
421
+            $stmt = $qb->select('id')
422
+                ->from('share')
423
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
424
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
425
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
426
+                ->andWhere($qb->expr()->orX(
427
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
428
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
429
+                ))
430
+                ->setMaxResults(1)
431
+                ->execute();
432
+
433
+            $data = $stmt->fetch();
434
+            $stmt->closeCursor();
435
+
436
+            if ($data === false) {
437
+                // No usergroup share yet. Create one.
438
+                $qb = $this->dbConn->getQueryBuilder();
439
+                $qb->insert('share')
440
+                    ->values([
441
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
442
+                        'share_with' => $qb->createNamedParameter($recipient),
443
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
444
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
445
+                        'parent' => $qb->createNamedParameter($share->getId()),
446
+                        'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
447
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
448
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
450
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
451
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
452
+                    ])->execute();
453
+            } else {
454
+                // Already a usergroup share. Update it.
455
+                $qb = $this->dbConn->getQueryBuilder();
456
+                $qb->update('share')
457
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
458
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
459
+                    ->execute();
460
+            }
461
+        }
462
+
463
+        return $share;
464
+    }
465
+
466
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
467
+        $qb = $this->dbConn->getQueryBuilder();
468
+        $qb->select('*')
469
+            ->from('share', 's')
470
+            ->andWhere($qb->expr()->orX(
471
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
472
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
473
+            ));
474
+
475
+        $qb->andWhere($qb->expr()->orX(
476
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
477
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
478
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
479
+        ));
480
+
481
+        /**
482
+         * Reshares for this user are shares where they are the owner.
483
+         */
484
+        if ($reshares === false) {
485
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
486
+        } else {
487
+            $qb->andWhere(
488
+                $qb->expr()->orX(
489
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
490
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
491
+                )
492
+            );
493
+        }
494
+
495
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
496
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
497
+
498
+        $qb->orderBy('id');
499
+
500
+        $cursor = $qb->execute();
501
+        $shares = [];
502
+        while ($data = $cursor->fetch()) {
503
+            $shares[$data['fileid']][] = $this->createShare($data);
504
+        }
505
+        $cursor->closeCursor();
506
+
507
+        return $shares;
508
+    }
509
+
510
+    /**
511
+     * @inheritdoc
512
+     */
513
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
514
+        $qb = $this->dbConn->getQueryBuilder();
515
+        $qb->select('*')
516
+            ->from('share')
517
+            ->andWhere($qb->expr()->orX(
518
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
519
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
520
+            ));
521
+
522
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
523
+
524
+        /**
525
+         * Reshares for this user are shares where they are the owner.
526
+         */
527
+        if ($reshares === false) {
528
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
529
+        } else {
530
+            $qb->andWhere(
531
+                $qb->expr()->orX(
532
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
533
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
534
+                )
535
+            );
536
+        }
537
+
538
+        if ($node !== null) {
539
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
540
+        }
541
+
542
+        if ($limit !== -1) {
543
+            $qb->setMaxResults($limit);
544
+        }
545
+
546
+        $qb->setFirstResult($offset);
547
+        $qb->orderBy('id');
548
+
549
+        $cursor = $qb->execute();
550
+        $shares = [];
551
+        while($data = $cursor->fetch()) {
552
+            $shares[] = $this->createShare($data);
553
+        }
554
+        $cursor->closeCursor();
555
+
556
+        return $shares;
557
+    }
558
+
559
+    /**
560
+     * @inheritdoc
561
+     */
562
+    public function getShareById($id, $recipientId = null) {
563
+        $qb = $this->dbConn->getQueryBuilder();
564
+
565
+        $qb->select('*')
566
+            ->from('share')
567
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
568
+            ->andWhere(
569
+                $qb->expr()->in(
570
+                    'share_type',
571
+                    $qb->createNamedParameter([
572
+                        \OCP\Share::SHARE_TYPE_USER,
573
+                        \OCP\Share::SHARE_TYPE_GROUP,
574
+                        \OCP\Share::SHARE_TYPE_LINK,
575
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
576
+                )
577
+            )
578
+            ->andWhere($qb->expr()->orX(
579
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
580
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
581
+            ));
582
+
583
+        $cursor = $qb->execute();
584
+        $data = $cursor->fetch();
585
+        $cursor->closeCursor();
586
+
587
+        if ($data === false) {
588
+            throw new ShareNotFound();
589
+        }
590
+
591
+        try {
592
+            $share = $this->createShare($data);
593
+        } catch (InvalidShare $e) {
594
+            throw new ShareNotFound();
595
+        }
596
+
597
+        // If the recipient is set for a group share resolve to that user
598
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
599
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
600
+        }
601
+
602
+        return $share;
603
+    }
604
+
605
+    /**
606
+     * Get shares for a given path
607
+     *
608
+     * @param \OCP\Files\Node $path
609
+     * @return \OCP\Share\IShare[]
610
+     */
611
+    public function getSharesByPath(Node $path) {
612
+        $qb = $this->dbConn->getQueryBuilder();
613
+
614
+        $cursor = $qb->select('*')
615
+            ->from('share')
616
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
617
+            ->andWhere(
618
+                $qb->expr()->orX(
619
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
620
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
621
+                )
622
+            )
623
+            ->andWhere($qb->expr()->orX(
624
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
625
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
626
+            ))
627
+            ->execute();
628
+
629
+        $shares = [];
630
+        while($data = $cursor->fetch()) {
631
+            $shares[] = $this->createShare($data);
632
+        }
633
+        $cursor->closeCursor();
634
+
635
+        return $shares;
636
+    }
637
+
638
+    /**
639
+     * Returns whether the given database result can be interpreted as
640
+     * a share with accessible file (not trashed, not deleted)
641
+     */
642
+    private function isAccessibleResult($data) {
643
+        // exclude shares leading to deleted file entries
644
+        if ($data['fileid'] === null) {
645
+            return false;
646
+        }
647
+
648
+        // exclude shares leading to trashbin on home storages
649
+        $pathSections = explode('/', $data['path'], 2);
650
+        // FIXME: would not detect rare md5'd home storage case properly
651
+        if ($pathSections[0] !== 'files'
652
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
653
+            return false;
654
+        }
655
+        return true;
656
+    }
657
+
658
+    /**
659
+     * @inheritdoc
660
+     */
661
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
662
+        /** @var Share[] $shares */
663
+        $shares = [];
664
+
665
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
666
+            //Get shares directly with this user
667
+            $qb = $this->dbConn->getQueryBuilder();
668
+            $qb->select('s.*',
669
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
670
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
671
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
672
+            )
673
+                ->selectAlias('st.id', 'storage_string_id')
674
+                ->from('share', 's')
675
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
676
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
677
+
678
+            // Order by id
679
+            $qb->orderBy('s.id');
680
+
681
+            // Set limit and offset
682
+            if ($limit !== -1) {
683
+                $qb->setMaxResults($limit);
684
+            }
685
+            $qb->setFirstResult($offset);
686
+
687
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
688
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
689
+                ->andWhere($qb->expr()->orX(
690
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
691
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
692
+                ));
693
+
694
+            // Filter by node if provided
695
+            if ($node !== null) {
696
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
697
+            }
698
+
699
+            $cursor = $qb->execute();
700
+
701
+            while($data = $cursor->fetch()) {
702
+                if ($this->isAccessibleResult($data)) {
703
+                    $shares[] = $this->createShare($data);
704
+                }
705
+            }
706
+            $cursor->closeCursor();
707
+
708
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
709
+            $user = $this->userManager->get($userId);
710
+            $allGroups = $this->groupManager->getUserGroups($user);
711
+
712
+            /** @var Share[] $shares2 */
713
+            $shares2 = [];
714
+
715
+            $start = 0;
716
+            while(true) {
717
+                $groups = array_slice($allGroups, $start, 100);
718
+                $start += 100;
719
+
720
+                if ($groups === []) {
721
+                    break;
722
+                }
723
+
724
+                $qb = $this->dbConn->getQueryBuilder();
725
+                $qb->select('s.*',
726
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
727
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
728
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
729
+                )
730
+                    ->selectAlias('st.id', 'storage_string_id')
731
+                    ->from('share', 's')
732
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
733
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
734
+                    ->orderBy('s.id')
735
+                    ->setFirstResult(0);
736
+
737
+                if ($limit !== -1) {
738
+                    $qb->setMaxResults($limit - count($shares));
739
+                }
740
+
741
+                // Filter by node if provided
742
+                if ($node !== null) {
743
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
744
+                }
745
+
746
+
747
+                $groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
748
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
749
+
750
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
751
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
752
+                        $groups,
753
+                        IQueryBuilder::PARAM_STR_ARRAY
754
+                    )))
755
+                    ->andWhere($qb->expr()->orX(
756
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
757
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
758
+                    ));
759
+
760
+                $cursor = $qb->execute();
761
+                while($data = $cursor->fetch()) {
762
+                    if ($offset > 0) {
763
+                        $offset--;
764
+                        continue;
765
+                    }
766
+
767
+                    if ($this->isAccessibleResult($data)) {
768
+                        $shares2[] = $this->createShare($data);
769
+                    }
770
+                }
771
+                $cursor->closeCursor();
772
+            }
773
+
774
+            /*
775 775
  			 * Resolve all group shares to user specific shares
776 776
  			 */
777
-			$shares = $this->resolveGroupShares($shares2, $userId);
778
-		} else {
779
-			throw new BackendError('Invalid backend');
780
-		}
781
-
782
-
783
-		return $shares;
784
-	}
785
-
786
-	/**
787
-	 * Get a share by token
788
-	 *
789
-	 * @param string $token
790
-	 * @return \OCP\Share\IShare
791
-	 * @throws ShareNotFound
792
-	 */
793
-	public function getShareByToken($token) {
794
-		$qb = $this->dbConn->getQueryBuilder();
795
-
796
-		$cursor = $qb->select('*')
797
-			->from('share')
798
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
799
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
800
-			->andWhere($qb->expr()->orX(
801
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
802
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
803
-			))
804
-			->execute();
805
-
806
-		$data = $cursor->fetch();
807
-
808
-		if ($data === false) {
809
-			throw new ShareNotFound();
810
-		}
811
-
812
-		try {
813
-			$share = $this->createShare($data);
814
-		} catch (InvalidShare $e) {
815
-			throw new ShareNotFound();
816
-		}
817
-
818
-		return $share;
819
-	}
820
-
821
-	/**
822
-	 * Create a share object from an database row
823
-	 *
824
-	 * @param mixed[] $data
825
-	 * @return \OCP\Share\IShare
826
-	 * @throws InvalidShare
827
-	 */
828
-	private function createShare($data) {
829
-		$share = new Share($this->rootFolder, $this->userManager);
830
-		$share->setId((int)$data['id'])
831
-			->setShareType((int)$data['share_type'])
832
-			->setPermissions((int)$data['permissions'])
833
-			->setTarget($data['file_target'])
834
-			->setMailSend((bool)$data['mail_send']);
835
-
836
-		$shareTime = new \DateTime();
837
-		$shareTime->setTimestamp((int)$data['stime']);
838
-		$share->setShareTime($shareTime);
839
-
840
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
841
-			$share->setSharedWith($data['share_with']);
842
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
843
-			$share->setSharedWith($data['share_with']);
844
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
845
-			$share->setPassword($data['password']);
846
-			$share->setToken($data['token']);
847
-		}
848
-
849
-		$share->setSharedBy($data['uid_initiator']);
850
-		$share->setShareOwner($data['uid_owner']);
851
-
852
-		$share->setNodeId((int)$data['file_source']);
853
-		$share->setNodeType($data['item_type']);
854
-
855
-		if ($data['expiration'] !== null) {
856
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
857
-			$share->setExpirationDate($expiration);
858
-		}
859
-
860
-		if (isset($data['f_permissions'])) {
861
-			$entryData = $data;
862
-			$entryData['permissions'] = $entryData['f_permissions'];
863
-			$entryData['parent'] = $entryData['f_parent'];;
864
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
865
-				\OC::$server->getMimeTypeLoader()));
866
-		}
867
-
868
-		$share->setProviderId($this->identifier());
869
-
870
-		return $share;
871
-	}
872
-
873
-	/**
874
-	 * @param Share[] $shares
875
-	 * @param $userId
876
-	 * @return Share[] The updates shares if no update is found for a share return the original
877
-	 */
878
-	private function resolveGroupShares($shares, $userId) {
879
-		$result = [];
880
-
881
-		$start = 0;
882
-		while(true) {
883
-			/** @var Share[] $shareSlice */
884
-			$shareSlice = array_slice($shares, $start, 100);
885
-			$start += 100;
886
-
887
-			if ($shareSlice === []) {
888
-				break;
889
-			}
890
-
891
-			/** @var int[] $ids */
892
-			$ids = [];
893
-			/** @var Share[] $shareMap */
894
-			$shareMap = [];
895
-
896
-			foreach ($shareSlice as $share) {
897
-				$ids[] = (int)$share->getId();
898
-				$shareMap[$share->getId()] = $share;
899
-			}
900
-
901
-			$qb = $this->dbConn->getQueryBuilder();
902
-
903
-			$query = $qb->select('*')
904
-				->from('share')
905
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
906
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
907
-				->andWhere($qb->expr()->orX(
908
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
909
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
910
-				));
911
-
912
-			$stmt = $query->execute();
913
-
914
-			while($data = $stmt->fetch()) {
915
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
916
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
917
-			}
918
-
919
-			$stmt->closeCursor();
920
-
921
-			foreach ($shareMap as $share) {
922
-				$result[] = $share;
923
-			}
924
-		}
925
-
926
-		return $result;
927
-	}
928
-
929
-	/**
930
-	 * A user is deleted from the system
931
-	 * So clean up the relevant shares.
932
-	 *
933
-	 * @param string $uid
934
-	 * @param int $shareType
935
-	 */
936
-	public function userDeleted($uid, $shareType) {
937
-		$qb = $this->dbConn->getQueryBuilder();
938
-
939
-		$qb->delete('share');
940
-
941
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
942
-			/*
777
+            $shares = $this->resolveGroupShares($shares2, $userId);
778
+        } else {
779
+            throw new BackendError('Invalid backend');
780
+        }
781
+
782
+
783
+        return $shares;
784
+    }
785
+
786
+    /**
787
+     * Get a share by token
788
+     *
789
+     * @param string $token
790
+     * @return \OCP\Share\IShare
791
+     * @throws ShareNotFound
792
+     */
793
+    public function getShareByToken($token) {
794
+        $qb = $this->dbConn->getQueryBuilder();
795
+
796
+        $cursor = $qb->select('*')
797
+            ->from('share')
798
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
799
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
800
+            ->andWhere($qb->expr()->orX(
801
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
802
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
803
+            ))
804
+            ->execute();
805
+
806
+        $data = $cursor->fetch();
807
+
808
+        if ($data === false) {
809
+            throw new ShareNotFound();
810
+        }
811
+
812
+        try {
813
+            $share = $this->createShare($data);
814
+        } catch (InvalidShare $e) {
815
+            throw new ShareNotFound();
816
+        }
817
+
818
+        return $share;
819
+    }
820
+
821
+    /**
822
+     * Create a share object from an database row
823
+     *
824
+     * @param mixed[] $data
825
+     * @return \OCP\Share\IShare
826
+     * @throws InvalidShare
827
+     */
828
+    private function createShare($data) {
829
+        $share = new Share($this->rootFolder, $this->userManager);
830
+        $share->setId((int)$data['id'])
831
+            ->setShareType((int)$data['share_type'])
832
+            ->setPermissions((int)$data['permissions'])
833
+            ->setTarget($data['file_target'])
834
+            ->setMailSend((bool)$data['mail_send']);
835
+
836
+        $shareTime = new \DateTime();
837
+        $shareTime->setTimestamp((int)$data['stime']);
838
+        $share->setShareTime($shareTime);
839
+
840
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
841
+            $share->setSharedWith($data['share_with']);
842
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
843
+            $share->setSharedWith($data['share_with']);
844
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
845
+            $share->setPassword($data['password']);
846
+            $share->setToken($data['token']);
847
+        }
848
+
849
+        $share->setSharedBy($data['uid_initiator']);
850
+        $share->setShareOwner($data['uid_owner']);
851
+
852
+        $share->setNodeId((int)$data['file_source']);
853
+        $share->setNodeType($data['item_type']);
854
+
855
+        if ($data['expiration'] !== null) {
856
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
857
+            $share->setExpirationDate($expiration);
858
+        }
859
+
860
+        if (isset($data['f_permissions'])) {
861
+            $entryData = $data;
862
+            $entryData['permissions'] = $entryData['f_permissions'];
863
+            $entryData['parent'] = $entryData['f_parent'];;
864
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
865
+                \OC::$server->getMimeTypeLoader()));
866
+        }
867
+
868
+        $share->setProviderId($this->identifier());
869
+
870
+        return $share;
871
+    }
872
+
873
+    /**
874
+     * @param Share[] $shares
875
+     * @param $userId
876
+     * @return Share[] The updates shares if no update is found for a share return the original
877
+     */
878
+    private function resolveGroupShares($shares, $userId) {
879
+        $result = [];
880
+
881
+        $start = 0;
882
+        while(true) {
883
+            /** @var Share[] $shareSlice */
884
+            $shareSlice = array_slice($shares, $start, 100);
885
+            $start += 100;
886
+
887
+            if ($shareSlice === []) {
888
+                break;
889
+            }
890
+
891
+            /** @var int[] $ids */
892
+            $ids = [];
893
+            /** @var Share[] $shareMap */
894
+            $shareMap = [];
895
+
896
+            foreach ($shareSlice as $share) {
897
+                $ids[] = (int)$share->getId();
898
+                $shareMap[$share->getId()] = $share;
899
+            }
900
+
901
+            $qb = $this->dbConn->getQueryBuilder();
902
+
903
+            $query = $qb->select('*')
904
+                ->from('share')
905
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
906
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
907
+                ->andWhere($qb->expr()->orX(
908
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
909
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
910
+                ));
911
+
912
+            $stmt = $query->execute();
913
+
914
+            while($data = $stmt->fetch()) {
915
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
916
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
917
+            }
918
+
919
+            $stmt->closeCursor();
920
+
921
+            foreach ($shareMap as $share) {
922
+                $result[] = $share;
923
+            }
924
+        }
925
+
926
+        return $result;
927
+    }
928
+
929
+    /**
930
+     * A user is deleted from the system
931
+     * So clean up the relevant shares.
932
+     *
933
+     * @param string $uid
934
+     * @param int $shareType
935
+     */
936
+    public function userDeleted($uid, $shareType) {
937
+        $qb = $this->dbConn->getQueryBuilder();
938
+
939
+        $qb->delete('share');
940
+
941
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
942
+            /*
943 943
 			 * Delete all user shares that are owned by this user
944 944
 			 * or that are received by this user
945 945
 			 */
946 946
 
947
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
947
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
948 948
 
949
-			$qb->andWhere(
950
-				$qb->expr()->orX(
951
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
952
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
953
-				)
954
-			);
955
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
956
-			/*
949
+            $qb->andWhere(
950
+                $qb->expr()->orX(
951
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
952
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
953
+                )
954
+            );
955
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
956
+            /*
957 957
 			 * Delete all group shares that are owned by this user
958 958
 			 * Or special user group shares that are received by this user
959 959
 			 */
960
-			$qb->where(
961
-				$qb->expr()->andX(
962
-					$qb->expr()->orX(
963
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
964
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
965
-					),
966
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
967
-				)
968
-			);
969
-
970
-			$qb->orWhere(
971
-				$qb->expr()->andX(
972
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
973
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
974
-				)
975
-			);
976
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
977
-			/*
960
+            $qb->where(
961
+                $qb->expr()->andX(
962
+                    $qb->expr()->orX(
963
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
964
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
965
+                    ),
966
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
967
+                )
968
+            );
969
+
970
+            $qb->orWhere(
971
+                $qb->expr()->andX(
972
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
973
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
974
+                )
975
+            );
976
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
977
+            /*
978 978
 			 * Delete all link shares owned by this user.
979 979
 			 * And all link shares initiated by this user (until #22327 is in)
980 980
 			 */
981
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
982
-
983
-			$qb->andWhere(
984
-				$qb->expr()->orX(
985
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
986
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
987
-				)
988
-			);
989
-		}
990
-
991
-		$qb->execute();
992
-	}
993
-
994
-	/**
995
-	 * Delete all shares received by this group. As well as any custom group
996
-	 * shares for group members.
997
-	 *
998
-	 * @param string $gid
999
-	 */
1000
-	public function groupDeleted($gid) {
1001
-		/*
981
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
982
+
983
+            $qb->andWhere(
984
+                $qb->expr()->orX(
985
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
986
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
987
+                )
988
+            );
989
+        }
990
+
991
+        $qb->execute();
992
+    }
993
+
994
+    /**
995
+     * Delete all shares received by this group. As well as any custom group
996
+     * shares for group members.
997
+     *
998
+     * @param string $gid
999
+     */
1000
+    public function groupDeleted($gid) {
1001
+        /*
1002 1002
 		 * First delete all custom group shares for group members
1003 1003
 		 */
1004
-		$qb = $this->dbConn->getQueryBuilder();
1005
-		$qb->select('id')
1006
-			->from('share')
1007
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1008
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1009
-
1010
-		$cursor = $qb->execute();
1011
-		$ids = [];
1012
-		while($row = $cursor->fetch()) {
1013
-			$ids[] = (int)$row['id'];
1014
-		}
1015
-		$cursor->closeCursor();
1016
-
1017
-		if (!empty($ids)) {
1018
-			$chunks = array_chunk($ids, 100);
1019
-			foreach ($chunks as $chunk) {
1020
-				$qb->delete('share')
1021
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1022
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1023
-				$qb->execute();
1024
-			}
1025
-		}
1026
-
1027
-		/*
1004
+        $qb = $this->dbConn->getQueryBuilder();
1005
+        $qb->select('id')
1006
+            ->from('share')
1007
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1008
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1009
+
1010
+        $cursor = $qb->execute();
1011
+        $ids = [];
1012
+        while($row = $cursor->fetch()) {
1013
+            $ids[] = (int)$row['id'];
1014
+        }
1015
+        $cursor->closeCursor();
1016
+
1017
+        if (!empty($ids)) {
1018
+            $chunks = array_chunk($ids, 100);
1019
+            foreach ($chunks as $chunk) {
1020
+                $qb->delete('share')
1021
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1022
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1023
+                $qb->execute();
1024
+            }
1025
+        }
1026
+
1027
+        /*
1028 1028
 		 * Now delete all the group shares
1029 1029
 		 */
1030
-		$qb = $this->dbConn->getQueryBuilder();
1031
-		$qb->delete('share')
1032
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1033
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1034
-		$qb->execute();
1035
-	}
1036
-
1037
-	/**
1038
-	 * Delete custom group shares to this group for this user
1039
-	 *
1040
-	 * @param string $uid
1041
-	 * @param string $gid
1042
-	 */
1043
-	public function userDeletedFromGroup($uid, $gid) {
1044
-		/*
1030
+        $qb = $this->dbConn->getQueryBuilder();
1031
+        $qb->delete('share')
1032
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1033
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1034
+        $qb->execute();
1035
+    }
1036
+
1037
+    /**
1038
+     * Delete custom group shares to this group for this user
1039
+     *
1040
+     * @param string $uid
1041
+     * @param string $gid
1042
+     */
1043
+    public function userDeletedFromGroup($uid, $gid) {
1044
+        /*
1045 1045
 		 * Get all group shares
1046 1046
 		 */
1047
-		$qb = $this->dbConn->getQueryBuilder();
1048
-		$qb->select('id')
1049
-			->from('share')
1050
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1051
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1052
-
1053
-		$cursor = $qb->execute();
1054
-		$ids = [];
1055
-		while($row = $cursor->fetch()) {
1056
-			$ids[] = (int)$row['id'];
1057
-		}
1058
-		$cursor->closeCursor();
1059
-
1060
-		if (!empty($ids)) {
1061
-			$chunks = array_chunk($ids, 100);
1062
-			foreach ($chunks as $chunk) {
1063
-				/*
1047
+        $qb = $this->dbConn->getQueryBuilder();
1048
+        $qb->select('id')
1049
+            ->from('share')
1050
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1051
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1052
+
1053
+        $cursor = $qb->execute();
1054
+        $ids = [];
1055
+        while($row = $cursor->fetch()) {
1056
+            $ids[] = (int)$row['id'];
1057
+        }
1058
+        $cursor->closeCursor();
1059
+
1060
+        if (!empty($ids)) {
1061
+            $chunks = array_chunk($ids, 100);
1062
+            foreach ($chunks as $chunk) {
1063
+                /*
1064 1064
 				 * Delete all special shares wit this users for the found group shares
1065 1065
 				 */
1066
-				$qb->delete('share')
1067
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1068
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1069
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1070
-				$qb->execute();
1071
-			}
1072
-		}
1073
-	}
1074
-
1075
-	/**
1076
-	 * @inheritdoc
1077
-	 */
1078
-	public function getAccessList($nodes, $currentAccess) {
1079
-		$ids = [];
1080
-		foreach ($nodes as $node) {
1081
-			$ids[] = $node->getId();
1082
-		}
1083
-
1084
-		$qb = $this->dbConn->getQueryBuilder();
1085
-
1086
-		$or = $qb->expr()->orX(
1087
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1088
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1089
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1090
-		);
1091
-
1092
-		if ($currentAccess) {
1093
-			$or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1094
-		}
1095
-
1096
-		$qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1097
-			->from('share')
1098
-			->where(
1099
-				$or
1100
-			)
1101
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1102
-			->andWhere($qb->expr()->orX(
1103
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1104
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1105
-			));
1106
-		$cursor = $qb->execute();
1107
-
1108
-		$users = [];
1109
-		$link = false;
1110
-		while($row = $cursor->fetch()) {
1111
-			$type = (int)$row['share_type'];
1112
-			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1113
-				$uid = $row['share_with'];
1114
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1115
-				$users[$uid][$row['id']] = $row;
1116
-			} else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1117
-				$gid = $row['share_with'];
1118
-				$group = $this->groupManager->get($gid);
1119
-
1120
-				if ($group === null) {
1121
-					continue;
1122
-				}
1123
-
1124
-				$userList = $group->getUsers();
1125
-				foreach ($userList as $user) {
1126
-					$uid = $user->getUID();
1127
-					$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1128
-					$users[$uid][$row['id']] = $row;
1129
-				}
1130
-			} else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1131
-				$link = true;
1132
-			} else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1133
-				$uid = $row['share_with'];
1134
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1135
-				$users[$uid][$row['id']] = $row;
1136
-			}
1137
-		}
1138
-		$cursor->closeCursor();
1139
-
1140
-		if ($currentAccess === true) {
1141
-			$users = array_map([$this, 'filterSharesOfUser'], $users);
1142
-			$users = array_filter($users);
1143
-		} else {
1144
-			$users = array_keys($users);
1145
-		}
1146
-
1147
-		return ['users' => $users, 'public' => $link];
1148
-	}
1149
-
1150
-	/**
1151
-	 * For each user the path with the fewest slashes is returned
1152
-	 * @param array $shares
1153
-	 * @return array
1154
-	 */
1155
-	protected function filterSharesOfUser(array $shares) {
1156
-		// Group shares when the user has a share exception
1157
-		foreach ($shares as $id => $share) {
1158
-			$type = (int) $share['share_type'];
1159
-			$permissions = (int) $share['permissions'];
1160
-
1161
-			if ($type === self::SHARE_TYPE_USERGROUP) {
1162
-				unset($shares[$share['parent']]);
1163
-
1164
-				if ($permissions === 0) {
1165
-					unset($shares[$id]);
1166
-				}
1167
-			}
1168
-		}
1169
-
1170
-		$best = [];
1171
-		$bestDepth = 0;
1172
-		foreach ($shares as $id => $share) {
1173
-			$depth = substr_count($share['file_target'], '/');
1174
-			if (empty($best) || $depth < $bestDepth) {
1175
-				$bestDepth = $depth;
1176
-				$best = [
1177
-					'node_id' => $share['file_source'],
1178
-					'node_path' => $share['file_target'],
1179
-				];
1180
-			}
1181
-		}
1182
-
1183
-		return $best;
1184
-	}
1066
+                $qb->delete('share')
1067
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1068
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1069
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1070
+                $qb->execute();
1071
+            }
1072
+        }
1073
+    }
1074
+
1075
+    /**
1076
+     * @inheritdoc
1077
+     */
1078
+    public function getAccessList($nodes, $currentAccess) {
1079
+        $ids = [];
1080
+        foreach ($nodes as $node) {
1081
+            $ids[] = $node->getId();
1082
+        }
1083
+
1084
+        $qb = $this->dbConn->getQueryBuilder();
1085
+
1086
+        $or = $qb->expr()->orX(
1087
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1088
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1089
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1090
+        );
1091
+
1092
+        if ($currentAccess) {
1093
+            $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1094
+        }
1095
+
1096
+        $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1097
+            ->from('share')
1098
+            ->where(
1099
+                $or
1100
+            )
1101
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1102
+            ->andWhere($qb->expr()->orX(
1103
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1104
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1105
+            ));
1106
+        $cursor = $qb->execute();
1107
+
1108
+        $users = [];
1109
+        $link = false;
1110
+        while($row = $cursor->fetch()) {
1111
+            $type = (int)$row['share_type'];
1112
+            if ($type === \OCP\Share::SHARE_TYPE_USER) {
1113
+                $uid = $row['share_with'];
1114
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1115
+                $users[$uid][$row['id']] = $row;
1116
+            } else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1117
+                $gid = $row['share_with'];
1118
+                $group = $this->groupManager->get($gid);
1119
+
1120
+                if ($group === null) {
1121
+                    continue;
1122
+                }
1123
+
1124
+                $userList = $group->getUsers();
1125
+                foreach ($userList as $user) {
1126
+                    $uid = $user->getUID();
1127
+                    $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1128
+                    $users[$uid][$row['id']] = $row;
1129
+                }
1130
+            } else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1131
+                $link = true;
1132
+            } else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1133
+                $uid = $row['share_with'];
1134
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1135
+                $users[$uid][$row['id']] = $row;
1136
+            }
1137
+        }
1138
+        $cursor->closeCursor();
1139
+
1140
+        if ($currentAccess === true) {
1141
+            $users = array_map([$this, 'filterSharesOfUser'], $users);
1142
+            $users = array_filter($users);
1143
+        } else {
1144
+            $users = array_keys($users);
1145
+        }
1146
+
1147
+        return ['users' => $users, 'public' => $link];
1148
+    }
1149
+
1150
+    /**
1151
+     * For each user the path with the fewest slashes is returned
1152
+     * @param array $shares
1153
+     * @return array
1154
+     */
1155
+    protected function filterSharesOfUser(array $shares) {
1156
+        // Group shares when the user has a share exception
1157
+        foreach ($shares as $id => $share) {
1158
+            $type = (int) $share['share_type'];
1159
+            $permissions = (int) $share['permissions'];
1160
+
1161
+            if ($type === self::SHARE_TYPE_USERGROUP) {
1162
+                unset($shares[$share['parent']]);
1163
+
1164
+                if ($permissions === 0) {
1165
+                    unset($shares[$id]);
1166
+                }
1167
+            }
1168
+        }
1169
+
1170
+        $best = [];
1171
+        $bestDepth = 0;
1172
+        foreach ($shares as $id => $share) {
1173
+            $depth = substr_count($share['file_target'], '/');
1174
+            if (empty($best) || $depth < $bestDepth) {
1175
+                $bestDepth = $depth;
1176
+                $best = [
1177
+                    'node_id' => $share['file_source'],
1178
+                    'node_path' => $share['file_target'],
1179
+                ];
1180
+            }
1181
+        }
1182
+
1183
+        return $best;
1184
+    }
1185 1185
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/ShareTypeList.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@
 block discarded – undo
61 61
 	 * The deserialize method is called during xml parsing.
62 62
 	 *
63 63
 	 * @param Reader $reader
64
-	 * @return mixed
64
+	 * @return null|ShareTypeList
65 65
 	 */
66 66
 	static function xmlDeserialize(Reader $reader) {
67 67
 		$shareTypes = [];
Please login to merge, or discard this patch.
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -32,61 +32,61 @@
 block discarded – undo
32 32
  * This property contains multiple "share-type" elements, each containing a share type.
33 33
  */
34 34
 class ShareTypeList implements Element {
35
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
35
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
36 36
 
37
-	/**
38
-	 * Share types
39
-	 *
40
-	 * @var int[]
41
-	 */
42
-	private $shareTypes;
37
+    /**
38
+     * Share types
39
+     *
40
+     * @var int[]
41
+     */
42
+    private $shareTypes;
43 43
 
44
-	/**
45
-	 * @param int[] $shareTypes
46
-	 */
47
-	public function __construct($shareTypes) {
48
-		$this->shareTypes = $shareTypes;
49
-	}
44
+    /**
45
+     * @param int[] $shareTypes
46
+     */
47
+    public function __construct($shareTypes) {
48
+        $this->shareTypes = $shareTypes;
49
+    }
50 50
 
51
-	/**
52
-	 * Returns the share types
53
-	 *
54
-	 * @return int[]
55
-	 */
56
-	public function getShareTypes() {
57
-		return $this->shareTypes;
58
-	}
51
+    /**
52
+     * Returns the share types
53
+     *
54
+     * @return int[]
55
+     */
56
+    public function getShareTypes() {
57
+        return $this->shareTypes;
58
+    }
59 59
 
60
-	/**
61
-	 * The deserialize method is called during xml parsing.
62
-	 *
63
-	 * @param Reader $reader
64
-	 * @return mixed
65
-	 */
66
-	static function xmlDeserialize(Reader $reader) {
67
-		$shareTypes = [];
60
+    /**
61
+     * The deserialize method is called during xml parsing.
62
+     *
63
+     * @param Reader $reader
64
+     * @return mixed
65
+     */
66
+    static function xmlDeserialize(Reader $reader) {
67
+        $shareTypes = [];
68 68
 
69
-		$tree = $reader->parseInnerTree();
70
-		if ($tree === null) {
71
-			return null;
72
-		}
73
-		foreach ($tree as $elem) {
74
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
-				$shareTypes[] = (int)$elem['value'];
76
-			}
77
-		}
78
-		return new self($shareTypes);
79
-	}
69
+        $tree = $reader->parseInnerTree();
70
+        if ($tree === null) {
71
+            return null;
72
+        }
73
+        foreach ($tree as $elem) {
74
+            if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
+                $shareTypes[] = (int)$elem['value'];
76
+            }
77
+        }
78
+        return new self($shareTypes);
79
+    }
80 80
 
81
-	/**
82
-	 * The xmlSerialize metod is called during xml writing.
83
-	 *
84
-	 * @param Writer $writer
85
-	 * @return void
86
-	 */
87
-	function xmlSerialize(Writer $writer) {
88
-		foreach ($this->shareTypes as $shareType) {
89
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
90
-		}
91
-	}
81
+    /**
82
+     * The xmlSerialize metod is called during xml writing.
83
+     *
84
+     * @param Writer $writer
85
+     * @return void
86
+     */
87
+    function xmlSerialize(Writer $writer) {
88
+        foreach ($this->shareTypes as $shareType) {
89
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
90
+        }
91
+    }
92 92
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -71,8 +71,8 @@  discard block
 block discarded – undo
71 71
 			return null;
72 72
 		}
73 73
 		foreach ($tree as $elem) {
74
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
-				$shareTypes[] = (int)$elem['value'];
74
+			if ($elem['name'] === '{'.self::NS_OWNCLOUD.'}share-type') {
75
+				$shareTypes[] = (int) $elem['value'];
76 76
 			}
77 77
 		}
78 78
 		return new self($shareTypes);
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 	 */
87 87
 	function xmlSerialize(Writer $writer) {
88 88
 		foreach ($this->shareTypes as $shareType) {
89
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
89
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}share-type', $shareType);
90 90
 		}
91 91
 	}
92 92
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/TagList.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@
 block discarded – undo
80 80
 	 * the next element.
81 81
 	 *
82 82
 	 * @param Reader $reader
83
-	 * @return mixed
83
+	 * @return null|TagList
84 84
 	 */
85 85
 	static function xmlDeserialize(Reader $reader) {
86 86
 		$tags = [];
Please login to merge, or discard this patch.
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -34,92 +34,92 @@
 block discarded – undo
34 34
  * This property contains multiple "tag" elements, each containing a tag name.
35 35
  */
36 36
 class TagList implements Element {
37
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
37
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
38 38
 
39
-	/**
40
-	 * tags
41
-	 *
42
-	 * @var array
43
-	 */
44
-	private $tags;
39
+    /**
40
+     * tags
41
+     *
42
+     * @var array
43
+     */
44
+    private $tags;
45 45
 
46
-	/**
47
-	 * @param array $tags
48
-	 */
49
-	public function __construct(array $tags) {
50
-		$this->tags = $tags;
51
-	}
46
+    /**
47
+     * @param array $tags
48
+     */
49
+    public function __construct(array $tags) {
50
+        $this->tags = $tags;
51
+    }
52 52
 
53
-	/**
54
-	 * Returns the tags
55
-	 *
56
-	 * @return array
57
-	 */
58
-	public function getTags() {
53
+    /**
54
+     * Returns the tags
55
+     *
56
+     * @return array
57
+     */
58
+    public function getTags() {
59 59
 
60
-		return $this->tags;
60
+        return $this->tags;
61 61
 
62
-	}
62
+    }
63 63
 
64
-	/**
65
-	 * The deserialize method is called during xml parsing.
66
-	 *
67
-	 * This method is called statictly, this is because in theory this method
68
-	 * may be used as a type of constructor, or factory method.
69
-	 *
70
-	 * Often you want to return an instance of the current class, but you are
71
-	 * free to return other data as well.
72
-	 *
73
-	 * You are responsible for advancing the reader to the next element. Not
74
-	 * doing anything will result in a never-ending loop.
75
-	 *
76
-	 * If you just want to skip parsing for this element altogether, you can
77
-	 * just call $reader->next();
78
-	 *
79
-	 * $reader->parseInnerTree() will parse the entire sub-tree, and advance to
80
-	 * the next element.
81
-	 *
82
-	 * @param Reader $reader
83
-	 * @return mixed
84
-	 */
85
-	static function xmlDeserialize(Reader $reader) {
86
-		$tags = [];
64
+    /**
65
+     * The deserialize method is called during xml parsing.
66
+     *
67
+     * This method is called statictly, this is because in theory this method
68
+     * may be used as a type of constructor, or factory method.
69
+     *
70
+     * Often you want to return an instance of the current class, but you are
71
+     * free to return other data as well.
72
+     *
73
+     * You are responsible for advancing the reader to the next element. Not
74
+     * doing anything will result in a never-ending loop.
75
+     *
76
+     * If you just want to skip parsing for this element altogether, you can
77
+     * just call $reader->next();
78
+     *
79
+     * $reader->parseInnerTree() will parse the entire sub-tree, and advance to
80
+     * the next element.
81
+     *
82
+     * @param Reader $reader
83
+     * @return mixed
84
+     */
85
+    static function xmlDeserialize(Reader $reader) {
86
+        $tags = [];
87 87
 
88
-		$tree = $reader->parseInnerTree();
89
-		if ($tree === null) {
90
-			return null;
91
-		}
92
-		foreach ($tree as $elem) {
93
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
94
-				$tags[] = $elem['value'];
95
-			}
96
-		}
97
-		return new self($tags);
98
-	}
88
+        $tree = $reader->parseInnerTree();
89
+        if ($tree === null) {
90
+            return null;
91
+        }
92
+        foreach ($tree as $elem) {
93
+            if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
94
+                $tags[] = $elem['value'];
95
+            }
96
+        }
97
+        return new self($tags);
98
+    }
99 99
 
100
-	/**
101
-	 * The xmlSerialize metod is called during xml writing.
102
-	 *
103
-	 * Use the $writer argument to write its own xml serialization.
104
-	 *
105
-	 * An important note: do _not_ create a parent element. Any element
106
-	 * implementing XmlSerializble should only ever write what's considered
107
-	 * its 'inner xml'.
108
-	 *
109
-	 * The parent of the current element is responsible for writing a
110
-	 * containing element.
111
-	 *
112
-	 * This allows serializers to be re-used for different element names.
113
-	 *
114
-	 * If you are opening new elements, you must also close them again.
115
-	 *
116
-	 * @param Writer $writer
117
-	 * @return void
118
-	 */
119
-	function xmlSerialize(Writer $writer) {
100
+    /**
101
+     * The xmlSerialize metod is called during xml writing.
102
+     *
103
+     * Use the $writer argument to write its own xml serialization.
104
+     *
105
+     * An important note: do _not_ create a parent element. Any element
106
+     * implementing XmlSerializble should only ever write what's considered
107
+     * its 'inner xml'.
108
+     *
109
+     * The parent of the current element is responsible for writing a
110
+     * containing element.
111
+     *
112
+     * This allows serializers to be re-used for different element names.
113
+     *
114
+     * If you are opening new elements, you must also close them again.
115
+     *
116
+     * @param Writer $writer
117
+     * @return void
118
+     */
119
+    function xmlSerialize(Writer $writer) {
120 120
 
121
-		foreach ($this->tags as $tag) {
122
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
123
-		}
124
-	}
121
+        foreach ($this->tags as $tag) {
122
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
123
+        }
124
+    }
125 125
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 			return null;
91 91
 		}
92 92
 		foreach ($tree as $elem) {
93
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
93
+			if ($elem['name'] === '{'.self::NS_OWNCLOUD.'}tag') {
94 94
 				$tags[] = $elem['value'];
95 95
 			}
96 96
 		}
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
 	function xmlSerialize(Writer $writer) {
120 120
 
121 121
 		foreach ($this->tags as $tag) {
122
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
122
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}tag', $tag);
123 123
 		}
124 124
 	}
125 125
 }
Please login to merge, or discard this patch.
lib/private/L10N/Factory.php 3 patches
Doc Comments   +5 added lines patch added patch discarded remove patch
@@ -318,6 +318,11 @@
 block discarded – undo
318 318
 	 */
319 319
 	// FIXME This method is only public, until OC_L10N does not need it anymore,
320 320
 	// FIXME This is also the reason, why it is not in the public interface
321
+
322
+	/**
323
+	 * @param string $app
324
+	 * @param string $lang
325
+	 */
321 326
 	public function getL10nFilesForApp($app, $lang) {
322 327
 		$languageFiles = [];
323 328
 
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -131,9 +131,9 @@  discard block
 block discarded – undo
131 131
 		 *
132 132
 		 * @link https://github.com/owncloud/core/issues/21955
133 133
 		 */
134
-		if($this->config->getSystemValue('installed', false)) {
135
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
136
-			if(!is_null($userId)) {
134
+		if ($this->config->getSystemValue('installed', false)) {
135
+			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null;
136
+			if (!is_null($userId)) {
137 137
 				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
138 138
 			} else {
139 139
 				$userLang = null;
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 		// merge with translations from theme
203 203
 		$theme = $this->config->getSystemValue('theme');
204 204
 		if (!empty($theme)) {
205
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
205
+			$themeDir = $this->serverRoot.'/themes/'.$theme.substr($dir, strlen($this->serverRoot));
206 206
 
207 207
 			if (is_dir($themeDir)) {
208 208
 				$files = scandir($themeDir);
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
 	 */
298 298
 	private function isSubDirectory($sub, $parent) {
299 299
 		// Check whether $sub contains no ".."
300
-		if(strpos($sub, '..') !== false) {
300
+		if (strpos($sub, '..') !== false) {
301 301
 			return false;
302 302
 		}
303 303
 
@@ -322,12 +322,12 @@  discard block
 block discarded – undo
322 322
 		$languageFiles = [];
323 323
 
324 324
 		$i18nDir = $this->findL10nDir($app);
325
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
325
+		$transFile = strip_tags($i18nDir).strip_tags($lang).'.json';
326 326
 
327
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
328
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
329
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
330
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
327
+		if (($this->isSubDirectory($transFile, $this->serverRoot.'/core/l10n/')
328
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/lib/l10n/')
329
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/settings/l10n/')
330
+				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app).'/l10n/')
331 331
 			)
332 332
 			&& file_exists($transFile)) {
333 333
 			// load the translations file
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
 		// merge with translations from theme
338 338
 		$theme = $this->config->getSystemValue('theme');
339 339
 		if (!empty($theme)) {
340
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
340
+			$transFile = $this->serverRoot.'/themes/'.$theme.substr($transFile, strlen($this->serverRoot));
341 341
 			if (file_exists($transFile)) {
342 342
 				$languageFiles[] = $transFile;
343 343
 			}
@@ -354,14 +354,14 @@  discard block
 block discarded – undo
354 354
 	 */
355 355
 	protected function findL10nDir($app = null) {
356 356
 		if (in_array($app, ['core', 'lib', 'settings'])) {
357
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
358
-				return $this->serverRoot . '/' . $app . '/l10n/';
357
+			if (file_exists($this->serverRoot.'/'.$app.'/l10n/')) {
358
+				return $this->serverRoot.'/'.$app.'/l10n/';
359 359
 			}
360 360
 		} else if ($app && \OC_App::getAppPath($app) !== false) {
361 361
 			// Check if the app is in the app folder
362
-			return \OC_App::getAppPath($app) . '/l10n/';
362
+			return \OC_App::getAppPath($app).'/l10n/';
363 363
 		}
364
-		return $this->serverRoot . '/core/l10n/';
364
+		return $this->serverRoot.'/core/l10n/';
365 365
 	}
366 366
 
367 367
 
@@ -378,15 +378,15 @@  discard block
 block discarded – undo
378 378
 			return $this->pluralFunctions[$string];
379 379
 		}
380 380
 
381
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
381
+		if (preg_match('/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
382 382
 			// sanitize
383
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
384
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
383
+			$nplurals = preg_replace('/[^0-9]/', '', $matches[1]);
384
+			$plural = preg_replace('#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2]);
385 385
 
386 386
 			$body = str_replace(
387
-				array( 'plural', 'n', '$n$plurals', ),
388
-				array( '$plural', '$n', '$nplurals', ),
389
-				'nplurals='. $nplurals . '; plural=' . $plural
387
+				array('plural', 'n', '$n$plurals',),
388
+				array('$plural', '$n', '$nplurals',),
389
+				'nplurals='.$nplurals.'; plural='.$plural
390 390
 			);
391 391
 
392 392
 			// add parents
@@ -394,9 +394,9 @@  discard block
 block discarded – undo
394 394
 			$body .= ';';
395 395
 			$res = '';
396 396
 			$p = 0;
397
-			for($i = 0; $i < strlen($body); $i++) {
397
+			for ($i = 0; $i < strlen($body); $i++) {
398 398
 				$ch = $body[$i];
399
-				switch ( $ch ) {
399
+				switch ($ch) {
400 400
 					case '?':
401 401
 						$res .= ' ? (';
402 402
 						$p++;
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
 						$res .= ') : (';
406 406
 						break;
407 407
 					case ';':
408
-						$res .= str_repeat( ')', $p ) . ';';
408
+						$res .= str_repeat(')', $p).';';
409 409
 						$p = 0;
410 410
 						break;
411 411
 					default:
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 				}
414 414
 			}
415 415
 
416
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
416
+			$body = $res.'return ($plural>=$nplurals?$nplurals-1:$plural);';
417 417
 			$function = create_function('$n', $body);
418 418
 			$this->pluralFunctions[$string] = $function;
419 419
 			return $function;
Please login to merge, or discard this patch.
Indentation   +380 added lines, -380 removed lines patch added patch discarded remove patch
@@ -40,384 +40,384 @@
 block discarded – undo
40 40
  */
41 41
 class Factory implements IFactory {
42 42
 
43
-	/** @var string */
44
-	protected $requestLanguage = '';
45
-
46
-	/**
47
-	 * cached instances
48
-	 * @var array Structure: Lang => App => \OCP\IL10N
49
-	 */
50
-	protected $instances = [];
51
-
52
-	/**
53
-	 * @var array Structure: App => string[]
54
-	 */
55
-	protected $availableLanguages = [];
56
-
57
-	/**
58
-	 * @var array Structure: string => callable
59
-	 */
60
-	protected $pluralFunctions = [];
61
-
62
-	/** @var IConfig */
63
-	protected $config;
64
-
65
-	/** @var IRequest */
66
-	protected $request;
67
-
68
-	/** @var IUserSession */
69
-	protected $userSession;
70
-
71
-	/** @var string */
72
-	protected $serverRoot;
73
-
74
-	/**
75
-	 * @param IConfig $config
76
-	 * @param IRequest $request
77
-	 * @param IUserSession $userSession
78
-	 * @param string $serverRoot
79
-	 */
80
-	public function __construct(IConfig $config,
81
-								IRequest $request,
82
-								IUserSession $userSession,
83
-								$serverRoot) {
84
-		$this->config = $config;
85
-		$this->request = $request;
86
-		$this->userSession = $userSession;
87
-		$this->serverRoot = $serverRoot;
88
-	}
89
-
90
-	/**
91
-	 * Get a language instance
92
-	 *
93
-	 * @param string $app
94
-	 * @param string|null $lang
95
-	 * @return \OCP\IL10N
96
-	 */
97
-	public function get($app, $lang = null) {
98
-		$app = \OC_App::cleanAppId($app);
99
-		if ($lang !== null) {
100
-			$lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
101
-		}
102
-
103
-		$forceLang = $this->config->getSystemValue('force_language', false);
104
-		if (is_string($forceLang)) {
105
-			$lang = $forceLang;
106
-		}
107
-
108
-		if ($lang === null || !$this->languageExists($app, $lang)) {
109
-			$lang = $this->findLanguage($app);
110
-		}
111
-
112
-		if (!isset($this->instances[$lang][$app])) {
113
-			$this->instances[$lang][$app] = new L10N(
114
-				$this, $app, $lang,
115
-				$this->getL10nFilesForApp($app, $lang)
116
-			);
117
-		}
118
-
119
-		return $this->instances[$lang][$app];
120
-	}
121
-
122
-	/**
123
-	 * Find the best language
124
-	 *
125
-	 * @param string|null $app App id or null for core
126
-	 * @return string language If nothing works it returns 'en'
127
-	 */
128
-	public function findLanguage($app = null) {
129
-		$forceLang = $this->config->getSystemValue('force_language', false);
130
-		if (is_string($forceLang)) {
131
-			$this->requestLanguage = $forceLang;
132
-		}
133
-
134
-		if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
135
-			return $this->requestLanguage;
136
-		}
137
-
138
-		/**
139
-		 * At this point Nextcloud might not yet be installed and thus the lookup
140
-		 * in the preferences table might fail. For this reason we need to check
141
-		 * whether the instance has already been installed
142
-		 *
143
-		 * @link https://github.com/owncloud/core/issues/21955
144
-		 */
145
-		if($this->config->getSystemValue('installed', false)) {
146
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
147
-			if(!is_null($userId)) {
148
-				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
149
-			} else {
150
-				$userLang = null;
151
-			}
152
-		} else {
153
-			$userId = null;
154
-			$userLang = null;
155
-		}
156
-
157
-		if ($userLang) {
158
-			$this->requestLanguage = $userLang;
159
-			if ($this->languageExists($app, $userLang)) {
160
-				return $userLang;
161
-			}
162
-		}
163
-
164
-		try {
165
-			// Try to get the language from the Request
166
-			$lang = $this->getLanguageFromRequest($app);
167
-			if ($userId !== null && $app === null && !$userLang) {
168
-				$this->config->setUserValue($userId, 'core', 'lang', $lang);
169
-			}
170
-			return $lang;
171
-		} catch (LanguageNotFoundException $e) {
172
-			// Finding language from request failed fall back to default language
173
-			$defaultLanguage = $this->config->getSystemValue('default_language', false);
174
-			if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
175
-				return $defaultLanguage;
176
-			}
177
-		}
178
-
179
-		// We could not find any language so fall back to english
180
-		return 'en';
181
-	}
182
-
183
-	/**
184
-	 * Find all available languages for an app
185
-	 *
186
-	 * @param string|null $app App id or null for core
187
-	 * @return array an array of available languages
188
-	 */
189
-	public function findAvailableLanguages($app = null) {
190
-		$key = $app;
191
-		if ($key === null) {
192
-			$key = 'null';
193
-		}
194
-
195
-		// also works with null as key
196
-		if (!empty($this->availableLanguages[$key])) {
197
-			return $this->availableLanguages[$key];
198
-		}
199
-
200
-		$available = ['en']; //english is always available
201
-		$dir = $this->findL10nDir($app);
202
-		if (is_dir($dir)) {
203
-			$files = scandir($dir);
204
-			if ($files !== false) {
205
-				foreach ($files as $file) {
206
-					if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
207
-						$available[] = substr($file, 0, -5);
208
-					}
209
-				}
210
-			}
211
-		}
212
-
213
-		// merge with translations from theme
214
-		$theme = $this->config->getSystemValue('theme');
215
-		if (!empty($theme)) {
216
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
217
-
218
-			if (is_dir($themeDir)) {
219
-				$files = scandir($themeDir);
220
-				if ($files !== false) {
221
-					foreach ($files as $file) {
222
-						if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
223
-							$available[] = substr($file, 0, -5);
224
-						}
225
-					}
226
-				}
227
-			}
228
-		}
229
-
230
-		$this->availableLanguages[$key] = $available;
231
-		return $available;
232
-	}
233
-
234
-	/**
235
-	 * @param string|null $app App id or null for core
236
-	 * @param string $lang
237
-	 * @return bool
238
-	 */
239
-	public function languageExists($app, $lang) {
240
-		if ($lang === 'en') {//english is always available
241
-			return true;
242
-		}
243
-
244
-		$languages = $this->findAvailableLanguages($app);
245
-		return array_search($lang, $languages) !== false;
246
-	}
247
-
248
-	/**
249
-	 * @param string|null $app
250
-	 * @return string
251
-	 * @throws LanguageNotFoundException
252
-	 */
253
-	private function getLanguageFromRequest($app) {
254
-		$header = $this->request->getHeader('ACCEPT_LANGUAGE');
255
-		if ($header) {
256
-			$available = $this->findAvailableLanguages($app);
257
-
258
-			// E.g. make sure that 'de' is before 'de_DE'.
259
-			sort($available);
260
-
261
-			$preferences = preg_split('/,\s*/', strtolower($header));
262
-			foreach ($preferences as $preference) {
263
-				list($preferred_language) = explode(';', $preference);
264
-				$preferred_language = str_replace('-', '_', $preferred_language);
265
-
266
-				foreach ($available as $available_language) {
267
-					if ($preferred_language === strtolower($available_language)) {
268
-						return $available_language;
269
-					}
270
-				}
271
-
272
-				// Fallback from de_De to de
273
-				foreach ($available as $available_language) {
274
-					if (substr($preferred_language, 0, 2) === $available_language) {
275
-						return $available_language;
276
-					}
277
-				}
278
-			}
279
-		}
280
-
281
-		throw new LanguageNotFoundException();
282
-	}
283
-
284
-	/**
285
-	 * Checks if $sub is a subdirectory of $parent
286
-	 *
287
-	 * @param string $sub
288
-	 * @param string $parent
289
-	 * @return bool
290
-	 */
291
-	private function isSubDirectory($sub, $parent) {
292
-		// Check whether $sub contains no ".."
293
-		if(strpos($sub, '..') !== false) {
294
-			return false;
295
-		}
296
-
297
-		// Check whether $sub is a subdirectory of $parent
298
-		if (strpos($sub, $parent) === 0) {
299
-			return true;
300
-		}
301
-
302
-		return false;
303
-	}
304
-
305
-	/**
306
-	 * Get a list of language files that should be loaded
307
-	 *
308
-	 * @param string $app
309
-	 * @param string $lang
310
-	 * @return string[]
311
-	 */
312
-	// FIXME This method is only public, until OC_L10N does not need it anymore,
313
-	// FIXME This is also the reason, why it is not in the public interface
314
-	public function getL10nFilesForApp($app, $lang) {
315
-		$languageFiles = [];
316
-
317
-		$i18nDir = $this->findL10nDir($app);
318
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
319
-
320
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
321
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
322
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
323
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
324
-			)
325
-			&& file_exists($transFile)) {
326
-			// load the translations file
327
-			$languageFiles[] = $transFile;
328
-		}
329
-
330
-		// merge with translations from theme
331
-		$theme = $this->config->getSystemValue('theme');
332
-		if (!empty($theme)) {
333
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
334
-			if (file_exists($transFile)) {
335
-				$languageFiles[] = $transFile;
336
-			}
337
-		}
338
-
339
-		return $languageFiles;
340
-	}
341
-
342
-	/**
343
-	 * find the l10n directory
344
-	 *
345
-	 * @param string $app App id or empty string for core
346
-	 * @return string directory
347
-	 */
348
-	protected function findL10nDir($app = null) {
349
-		if (in_array($app, ['core', 'lib', 'settings'])) {
350
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
351
-				return $this->serverRoot . '/' . $app . '/l10n/';
352
-			}
353
-		} else if ($app && \OC_App::getAppPath($app) !== false) {
354
-			// Check if the app is in the app folder
355
-			return \OC_App::getAppPath($app) . '/l10n/';
356
-		}
357
-		return $this->serverRoot . '/core/l10n/';
358
-	}
359
-
360
-
361
-	/**
362
-	 * Creates a function from the plural string
363
-	 *
364
-	 * Parts of the code is copied from Habari:
365
-	 * https://github.com/habari/system/blob/master/classes/locale.php
366
-	 * @param string $string
367
-	 * @return string
368
-	 */
369
-	public function createPluralFunction($string) {
370
-		if (isset($this->pluralFunctions[$string])) {
371
-			return $this->pluralFunctions[$string];
372
-		}
373
-
374
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
375
-			// sanitize
376
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
377
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
378
-
379
-			$body = str_replace(
380
-				array( 'plural', 'n', '$n$plurals', ),
381
-				array( '$plural', '$n', '$nplurals', ),
382
-				'nplurals='. $nplurals . '; plural=' . $plural
383
-			);
384
-
385
-			// add parents
386
-			// important since PHP's ternary evaluates from left to right
387
-			$body .= ';';
388
-			$res = '';
389
-			$p = 0;
390
-			for($i = 0; $i < strlen($body); $i++) {
391
-				$ch = $body[$i];
392
-				switch ( $ch ) {
393
-					case '?':
394
-						$res .= ' ? (';
395
-						$p++;
396
-						break;
397
-					case ':':
398
-						$res .= ') : (';
399
-						break;
400
-					case ';':
401
-						$res .= str_repeat( ')', $p ) . ';';
402
-						$p = 0;
403
-						break;
404
-					default:
405
-						$res .= $ch;
406
-				}
407
-			}
408
-
409
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
410
-			$function = create_function('$n', $body);
411
-			$this->pluralFunctions[$string] = $function;
412
-			return $function;
413
-		} else {
414
-			// default: one plural form for all cases but n==1 (english)
415
-			$function = create_function(
416
-				'$n',
417
-				'$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
418
-			);
419
-			$this->pluralFunctions[$string] = $function;
420
-			return $function;
421
-		}
422
-	}
43
+    /** @var string */
44
+    protected $requestLanguage = '';
45
+
46
+    /**
47
+     * cached instances
48
+     * @var array Structure: Lang => App => \OCP\IL10N
49
+     */
50
+    protected $instances = [];
51
+
52
+    /**
53
+     * @var array Structure: App => string[]
54
+     */
55
+    protected $availableLanguages = [];
56
+
57
+    /**
58
+     * @var array Structure: string => callable
59
+     */
60
+    protected $pluralFunctions = [];
61
+
62
+    /** @var IConfig */
63
+    protected $config;
64
+
65
+    /** @var IRequest */
66
+    protected $request;
67
+
68
+    /** @var IUserSession */
69
+    protected $userSession;
70
+
71
+    /** @var string */
72
+    protected $serverRoot;
73
+
74
+    /**
75
+     * @param IConfig $config
76
+     * @param IRequest $request
77
+     * @param IUserSession $userSession
78
+     * @param string $serverRoot
79
+     */
80
+    public function __construct(IConfig $config,
81
+                                IRequest $request,
82
+                                IUserSession $userSession,
83
+                                $serverRoot) {
84
+        $this->config = $config;
85
+        $this->request = $request;
86
+        $this->userSession = $userSession;
87
+        $this->serverRoot = $serverRoot;
88
+    }
89
+
90
+    /**
91
+     * Get a language instance
92
+     *
93
+     * @param string $app
94
+     * @param string|null $lang
95
+     * @return \OCP\IL10N
96
+     */
97
+    public function get($app, $lang = null) {
98
+        $app = \OC_App::cleanAppId($app);
99
+        if ($lang !== null) {
100
+            $lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
101
+        }
102
+
103
+        $forceLang = $this->config->getSystemValue('force_language', false);
104
+        if (is_string($forceLang)) {
105
+            $lang = $forceLang;
106
+        }
107
+
108
+        if ($lang === null || !$this->languageExists($app, $lang)) {
109
+            $lang = $this->findLanguage($app);
110
+        }
111
+
112
+        if (!isset($this->instances[$lang][$app])) {
113
+            $this->instances[$lang][$app] = new L10N(
114
+                $this, $app, $lang,
115
+                $this->getL10nFilesForApp($app, $lang)
116
+            );
117
+        }
118
+
119
+        return $this->instances[$lang][$app];
120
+    }
121
+
122
+    /**
123
+     * Find the best language
124
+     *
125
+     * @param string|null $app App id or null for core
126
+     * @return string language If nothing works it returns 'en'
127
+     */
128
+    public function findLanguage($app = null) {
129
+        $forceLang = $this->config->getSystemValue('force_language', false);
130
+        if (is_string($forceLang)) {
131
+            $this->requestLanguage = $forceLang;
132
+        }
133
+
134
+        if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
135
+            return $this->requestLanguage;
136
+        }
137
+
138
+        /**
139
+         * At this point Nextcloud might not yet be installed and thus the lookup
140
+         * in the preferences table might fail. For this reason we need to check
141
+         * whether the instance has already been installed
142
+         *
143
+         * @link https://github.com/owncloud/core/issues/21955
144
+         */
145
+        if($this->config->getSystemValue('installed', false)) {
146
+            $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
147
+            if(!is_null($userId)) {
148
+                $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
149
+            } else {
150
+                $userLang = null;
151
+            }
152
+        } else {
153
+            $userId = null;
154
+            $userLang = null;
155
+        }
156
+
157
+        if ($userLang) {
158
+            $this->requestLanguage = $userLang;
159
+            if ($this->languageExists($app, $userLang)) {
160
+                return $userLang;
161
+            }
162
+        }
163
+
164
+        try {
165
+            // Try to get the language from the Request
166
+            $lang = $this->getLanguageFromRequest($app);
167
+            if ($userId !== null && $app === null && !$userLang) {
168
+                $this->config->setUserValue($userId, 'core', 'lang', $lang);
169
+            }
170
+            return $lang;
171
+        } catch (LanguageNotFoundException $e) {
172
+            // Finding language from request failed fall back to default language
173
+            $defaultLanguage = $this->config->getSystemValue('default_language', false);
174
+            if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
175
+                return $defaultLanguage;
176
+            }
177
+        }
178
+
179
+        // We could not find any language so fall back to english
180
+        return 'en';
181
+    }
182
+
183
+    /**
184
+     * Find all available languages for an app
185
+     *
186
+     * @param string|null $app App id or null for core
187
+     * @return array an array of available languages
188
+     */
189
+    public function findAvailableLanguages($app = null) {
190
+        $key = $app;
191
+        if ($key === null) {
192
+            $key = 'null';
193
+        }
194
+
195
+        // also works with null as key
196
+        if (!empty($this->availableLanguages[$key])) {
197
+            return $this->availableLanguages[$key];
198
+        }
199
+
200
+        $available = ['en']; //english is always available
201
+        $dir = $this->findL10nDir($app);
202
+        if (is_dir($dir)) {
203
+            $files = scandir($dir);
204
+            if ($files !== false) {
205
+                foreach ($files as $file) {
206
+                    if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
207
+                        $available[] = substr($file, 0, -5);
208
+                    }
209
+                }
210
+            }
211
+        }
212
+
213
+        // merge with translations from theme
214
+        $theme = $this->config->getSystemValue('theme');
215
+        if (!empty($theme)) {
216
+            $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
217
+
218
+            if (is_dir($themeDir)) {
219
+                $files = scandir($themeDir);
220
+                if ($files !== false) {
221
+                    foreach ($files as $file) {
222
+                        if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
223
+                            $available[] = substr($file, 0, -5);
224
+                        }
225
+                    }
226
+                }
227
+            }
228
+        }
229
+
230
+        $this->availableLanguages[$key] = $available;
231
+        return $available;
232
+    }
233
+
234
+    /**
235
+     * @param string|null $app App id or null for core
236
+     * @param string $lang
237
+     * @return bool
238
+     */
239
+    public function languageExists($app, $lang) {
240
+        if ($lang === 'en') {//english is always available
241
+            return true;
242
+        }
243
+
244
+        $languages = $this->findAvailableLanguages($app);
245
+        return array_search($lang, $languages) !== false;
246
+    }
247
+
248
+    /**
249
+     * @param string|null $app
250
+     * @return string
251
+     * @throws LanguageNotFoundException
252
+     */
253
+    private function getLanguageFromRequest($app) {
254
+        $header = $this->request->getHeader('ACCEPT_LANGUAGE');
255
+        if ($header) {
256
+            $available = $this->findAvailableLanguages($app);
257
+
258
+            // E.g. make sure that 'de' is before 'de_DE'.
259
+            sort($available);
260
+
261
+            $preferences = preg_split('/,\s*/', strtolower($header));
262
+            foreach ($preferences as $preference) {
263
+                list($preferred_language) = explode(';', $preference);
264
+                $preferred_language = str_replace('-', '_', $preferred_language);
265
+
266
+                foreach ($available as $available_language) {
267
+                    if ($preferred_language === strtolower($available_language)) {
268
+                        return $available_language;
269
+                    }
270
+                }
271
+
272
+                // Fallback from de_De to de
273
+                foreach ($available as $available_language) {
274
+                    if (substr($preferred_language, 0, 2) === $available_language) {
275
+                        return $available_language;
276
+                    }
277
+                }
278
+            }
279
+        }
280
+
281
+        throw new LanguageNotFoundException();
282
+    }
283
+
284
+    /**
285
+     * Checks if $sub is a subdirectory of $parent
286
+     *
287
+     * @param string $sub
288
+     * @param string $parent
289
+     * @return bool
290
+     */
291
+    private function isSubDirectory($sub, $parent) {
292
+        // Check whether $sub contains no ".."
293
+        if(strpos($sub, '..') !== false) {
294
+            return false;
295
+        }
296
+
297
+        // Check whether $sub is a subdirectory of $parent
298
+        if (strpos($sub, $parent) === 0) {
299
+            return true;
300
+        }
301
+
302
+        return false;
303
+    }
304
+
305
+    /**
306
+     * Get a list of language files that should be loaded
307
+     *
308
+     * @param string $app
309
+     * @param string $lang
310
+     * @return string[]
311
+     */
312
+    // FIXME This method is only public, until OC_L10N does not need it anymore,
313
+    // FIXME This is also the reason, why it is not in the public interface
314
+    public function getL10nFilesForApp($app, $lang) {
315
+        $languageFiles = [];
316
+
317
+        $i18nDir = $this->findL10nDir($app);
318
+        $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
319
+
320
+        if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
321
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
322
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
323
+                || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
324
+            )
325
+            && file_exists($transFile)) {
326
+            // load the translations file
327
+            $languageFiles[] = $transFile;
328
+        }
329
+
330
+        // merge with translations from theme
331
+        $theme = $this->config->getSystemValue('theme');
332
+        if (!empty($theme)) {
333
+            $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
334
+            if (file_exists($transFile)) {
335
+                $languageFiles[] = $transFile;
336
+            }
337
+        }
338
+
339
+        return $languageFiles;
340
+    }
341
+
342
+    /**
343
+     * find the l10n directory
344
+     *
345
+     * @param string $app App id or empty string for core
346
+     * @return string directory
347
+     */
348
+    protected function findL10nDir($app = null) {
349
+        if (in_array($app, ['core', 'lib', 'settings'])) {
350
+            if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
351
+                return $this->serverRoot . '/' . $app . '/l10n/';
352
+            }
353
+        } else if ($app && \OC_App::getAppPath($app) !== false) {
354
+            // Check if the app is in the app folder
355
+            return \OC_App::getAppPath($app) . '/l10n/';
356
+        }
357
+        return $this->serverRoot . '/core/l10n/';
358
+    }
359
+
360
+
361
+    /**
362
+     * Creates a function from the plural string
363
+     *
364
+     * Parts of the code is copied from Habari:
365
+     * https://github.com/habari/system/blob/master/classes/locale.php
366
+     * @param string $string
367
+     * @return string
368
+     */
369
+    public function createPluralFunction($string) {
370
+        if (isset($this->pluralFunctions[$string])) {
371
+            return $this->pluralFunctions[$string];
372
+        }
373
+
374
+        if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
375
+            // sanitize
376
+            $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
377
+            $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
378
+
379
+            $body = str_replace(
380
+                array( 'plural', 'n', '$n$plurals', ),
381
+                array( '$plural', '$n', '$nplurals', ),
382
+                'nplurals='. $nplurals . '; plural=' . $plural
383
+            );
384
+
385
+            // add parents
386
+            // important since PHP's ternary evaluates from left to right
387
+            $body .= ';';
388
+            $res = '';
389
+            $p = 0;
390
+            for($i = 0; $i < strlen($body); $i++) {
391
+                $ch = $body[$i];
392
+                switch ( $ch ) {
393
+                    case '?':
394
+                        $res .= ' ? (';
395
+                        $p++;
396
+                        break;
397
+                    case ':':
398
+                        $res .= ') : (';
399
+                        break;
400
+                    case ';':
401
+                        $res .= str_repeat( ')', $p ) . ';';
402
+                        $p = 0;
403
+                        break;
404
+                    default:
405
+                        $res .= $ch;
406
+                }
407
+            }
408
+
409
+            $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
410
+            $function = create_function('$n', $body);
411
+            $this->pluralFunctions[$string] = $function;
412
+            return $function;
413
+        } else {
414
+            // default: one plural form for all cases but n==1 (english)
415
+            $function = create_function(
416
+                '$n',
417
+                '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
418
+            );
419
+            $this->pluralFunctions[$string] = $function;
420
+            return $function;
421
+        }
422
+    }
423 423
 }
Please login to merge, or discard this patch.
lib/private/Files/Filesystem.php 3 patches
Doc Comments   +31 added lines, -2 removed lines patch added patch discarded remove patch
@@ -360,6 +360,9 @@  discard block
 block discarded – undo
360 360
 		}
361 361
 	}
362 362
 
363
+	/**
364
+	 * @param string $root
365
+	 */
363 366
 	static public function init($user, $root) {
364 367
 		if (self::$defaultInstance) {
365 368
 			return false;
@@ -528,7 +531,7 @@  discard block
 block discarded – undo
528 531
 	/**
529 532
 	 * mount an \OC\Files\Storage\Storage in our virtual filesystem
530 533
 	 *
531
-	 * @param \OC\Files\Storage\Storage|string $class
534
+	 * @param string $class
532 535
 	 * @param array $arguments
533 536
 	 * @param string $mountpoint
534 537
 	 */
@@ -660,6 +663,9 @@  discard block
 block discarded – undo
660 663
 		return self::$defaultInstance->is_dir($path);
661 664
 	}
662 665
 
666
+	/**
667
+	 * @param string $path
668
+	 */
663 669
 	static public function is_file($path) {
664 670
 		return self::$defaultInstance->is_file($path);
665 671
 	}
@@ -672,6 +678,9 @@  discard block
 block discarded – undo
672 678
 		return self::$defaultInstance->filetype($path);
673 679
 	}
674 680
 
681
+	/**
682
+	 * @param string $path
683
+	 */
675 684
 	static public function filesize($path) {
676 685
 		return self::$defaultInstance->filesize($path);
677 686
 	}
@@ -684,6 +693,9 @@  discard block
 block discarded – undo
684 693
 		return self::$defaultInstance->isCreatable($path);
685 694
 	}
686 695
 
696
+	/**
697
+	 * @param string $path
698
+	 */
687 699
 	static public function isReadable($path) {
688 700
 		return self::$defaultInstance->isReadable($path);
689 701
 	}
@@ -696,6 +708,9 @@  discard block
 block discarded – undo
696 708
 		return self::$defaultInstance->isDeletable($path);
697 709
 	}
698 710
 
711
+	/**
712
+	 * @param string $path
713
+	 */
699 714
 	static public function isSharable($path) {
700 715
 		return self::$defaultInstance->isSharable($path);
701 716
 	}
@@ -704,6 +719,9 @@  discard block
 block discarded – undo
704 719
 		return self::$defaultInstance->file_exists($path);
705 720
 	}
706 721
 
722
+	/**
723
+	 * @param string $path
724
+	 */
707 725
 	static public function filemtime($path) {
708 726
 		return self::$defaultInstance->filemtime($path);
709 727
 	}
@@ -713,6 +731,7 @@  discard block
 block discarded – undo
713 731
 	}
714 732
 
715 733
 	/**
734
+	 * @param string $path
716 735
 	 * @return string
717 736
 	 */
718 737
 	static public function file_get_contents($path) {
@@ -735,6 +754,10 @@  discard block
 block discarded – undo
735 754
 		return self::$defaultInstance->copy($path1, $path2);
736 755
 	}
737 756
 
757
+	/**
758
+	 * @param string $path
759
+	 * @param string $mode
760
+	 */
738 761
 	static public function fopen($path, $mode) {
739 762
 		return self::$defaultInstance->fopen($path, $mode);
740 763
 	}
@@ -750,6 +773,9 @@  discard block
 block discarded – undo
750 773
 		return self::$defaultInstance->fromTmpFile($tmpFile, $path);
751 774
 	}
752 775
 
776
+	/**
777
+	 * @param string $path
778
+	 */
753 779
 	static public function getMimeType($path) {
754 780
 		return self::$defaultInstance->getMimeType($path);
755 781
 	}
@@ -762,6 +788,9 @@  discard block
 block discarded – undo
762 788
 		return self::$defaultInstance->free_space($path);
763 789
 	}
764 790
 
791
+	/**
792
+	 * @param string $query
793
+	 */
765 794
 	static public function search($query) {
766 795
 		return self::$defaultInstance->search($query);
767 796
 	}
@@ -870,7 +899,7 @@  discard block
 block discarded – undo
870 899
 	 * @param string $path
871 900
 	 * @param boolean $includeMountPoints whether to add mountpoint sizes,
872 901
 	 * defaults to true
873
-	 * @return \OC\Files\FileInfo|bool False if file does not exist
902
+	 * @return \OCP\Files\FileInfo|null False if file does not exist
874 903
 	 */
875 904
 	public static function getFileInfo($path, $includeMountPoints = true) {
876 905
 		return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -409,17 +409,17 @@  discard block
 block discarded – undo
409 409
 		$userObject = $userManager->get($user);
410 410
 
411 411
 		if (is_null($userObject)) {
412
-			\OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
412
+			\OCP\Util::writeLog('files', ' Backends provided no user object for '.$user, \OCP\Util::ERROR);
413 413
 			// reset flag, this will make it possible to rethrow the exception if called again
414 414
 			unset(self::$usersSetup[$user]);
415
-			throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
415
+			throw new \OC\User\NoUserException('Backends provided no user object for '.$user);
416 416
 		}
417 417
 
418 418
 		$realUid = $userObject->getUID();
419 419
 		// workaround in case of different casings
420 420
 		if ($user !== $realUid) {
421 421
 			$stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
422
-			\OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "' . $realUid . '" got "' . $user . '". Stack: ' . $stack, \OCP\Util::WARN);
422
+			\OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "'.$realUid.'" got "'.$user.'". Stack: '.$stack, \OCP\Util::WARN);
423 423
 			$user = $realUid;
424 424
 
425 425
 			// again with the correct casing
@@ -453,11 +453,11 @@  discard block
 block discarded – undo
453 453
 		} else {
454 454
 			self::getMountManager()->addMount(new MountPoint(
455 455
 				new NullStorage([]),
456
-				'/' . $user
456
+				'/'.$user
457 457
 			));
458 458
 			self::getMountManager()->addMount(new MountPoint(
459 459
 				new NullStorage([]),
460
-				'/' . $user . '/files'
460
+				'/'.$user.'/files'
461 461
 			));
462 462
 		}
463 463
 		\OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
@@ -472,7 +472,7 @@  discard block
 block discarded – undo
472 472
 	private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
473 473
 		if (!self::$listeningForProviders) {
474 474
 			self::$listeningForProviders = true;
475
-			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
475
+			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function(IMountProvider $provider) use ($userManager) {
476 476
 				foreach (Filesystem::$usersSetup as $user => $setup) {
477 477
 					$userObject = $userManager->get($user);
478 478
 					if ($userObject) {
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
 	 * @return string
568 568
 	 */
569 569
 	static public function getLocalPath($path) {
570
-		$datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
570
+		$datadir = \OC_User::getHome(\OC_User::getUser()).'/files';
571 571
 		$newpath = $path;
572 572
 		if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
573 573
 			$newpath = substr($path, strlen($datadir));
@@ -584,7 +584,7 @@  discard block
 block discarded – undo
584 584
 	static public function isValidPath($path) {
585 585
 		$path = self::normalizePath($path);
586 586
 		if (!$path || $path[0] !== '/') {
587
-			$path = '/' . $path;
587
+			$path = '/'.$path;
588 588
 		}
589 589
 		if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
590 590
 			return false;
@@ -813,7 +813,7 @@  discard block
 block discarded – undo
813 813
 		 *        conversion should get removed as soon as all existing
814 814
 		 *        function calls have been fixed.
815 815
 		 */
816
-		$path = (string)$path;
816
+		$path = (string) $path;
817 817
 
818 818
 		$cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
819 819
 
@@ -835,7 +835,7 @@  discard block
 block discarded – undo
835 835
 
836 836
 		//add leading slash
837 837
 		if ($path[0] !== '/') {
838
-			$path = '/' . $path;
838
+			$path = '/'.$path;
839 839
 		}
840 840
 
841 841
 		// remove '/./'
Please login to merge, or discard this patch.
Indentation   +861 added lines, -861 removed lines patch added patch discarded remove patch
@@ -70,865 +70,865 @@
 block discarded – undo
70 70
 
71 71
 class Filesystem {
72 72
 
73
-	/**
74
-	 * @var Mount\Manager $mounts
75
-	 */
76
-	private static $mounts;
77
-
78
-	public static $loaded = false;
79
-	/**
80
-	 * @var \OC\Files\View $defaultInstance
81
-	 */
82
-	static private $defaultInstance;
83
-
84
-	static private $usersSetup = array();
85
-
86
-	static private $normalizedPathCache = null;
87
-
88
-	static private $listeningForProviders = false;
89
-
90
-	/**
91
-	 * classname which used for hooks handling
92
-	 * used as signalclass in OC_Hooks::emit()
93
-	 */
94
-	const CLASSNAME = 'OC_Filesystem';
95
-
96
-	/**
97
-	 * signalname emitted before file renaming
98
-	 *
99
-	 * @param string $oldpath
100
-	 * @param string $newpath
101
-	 */
102
-	const signal_rename = 'rename';
103
-
104
-	/**
105
-	 * signal emitted after file renaming
106
-	 *
107
-	 * @param string $oldpath
108
-	 * @param string $newpath
109
-	 */
110
-	const signal_post_rename = 'post_rename';
111
-
112
-	/**
113
-	 * signal emitted before file/dir creation
114
-	 *
115
-	 * @param string $path
116
-	 * @param bool $run changing this flag to false in hook handler will cancel event
117
-	 */
118
-	const signal_create = 'create';
119
-
120
-	/**
121
-	 * signal emitted after file/dir creation
122
-	 *
123
-	 * @param string $path
124
-	 * @param bool $run changing this flag to false in hook handler will cancel event
125
-	 */
126
-	const signal_post_create = 'post_create';
127
-
128
-	/**
129
-	 * signal emits before file/dir copy
130
-	 *
131
-	 * @param string $oldpath
132
-	 * @param string $newpath
133
-	 * @param bool $run changing this flag to false in hook handler will cancel event
134
-	 */
135
-	const signal_copy = 'copy';
136
-
137
-	/**
138
-	 * signal emits after file/dir copy
139
-	 *
140
-	 * @param string $oldpath
141
-	 * @param string $newpath
142
-	 */
143
-	const signal_post_copy = 'post_copy';
144
-
145
-	/**
146
-	 * signal emits before file/dir save
147
-	 *
148
-	 * @param string $path
149
-	 * @param bool $run changing this flag to false in hook handler will cancel event
150
-	 */
151
-	const signal_write = 'write';
152
-
153
-	/**
154
-	 * signal emits after file/dir save
155
-	 *
156
-	 * @param string $path
157
-	 */
158
-	const signal_post_write = 'post_write';
159
-
160
-	/**
161
-	 * signal emitted before file/dir update
162
-	 *
163
-	 * @param string $path
164
-	 * @param bool $run changing this flag to false in hook handler will cancel event
165
-	 */
166
-	const signal_update = 'update';
167
-
168
-	/**
169
-	 * signal emitted after file/dir update
170
-	 *
171
-	 * @param string $path
172
-	 * @param bool $run changing this flag to false in hook handler will cancel event
173
-	 */
174
-	const signal_post_update = 'post_update';
175
-
176
-	/**
177
-	 * signal emits when reading file/dir
178
-	 *
179
-	 * @param string $path
180
-	 */
181
-	const signal_read = 'read';
182
-
183
-	/**
184
-	 * signal emits when removing file/dir
185
-	 *
186
-	 * @param string $path
187
-	 */
188
-	const signal_delete = 'delete';
189
-
190
-	/**
191
-	 * parameters definitions for signals
192
-	 */
193
-	const signal_param_path = 'path';
194
-	const signal_param_oldpath = 'oldpath';
195
-	const signal_param_newpath = 'newpath';
196
-
197
-	/**
198
-	 * run - changing this flag to false in hook handler will cancel event
199
-	 */
200
-	const signal_param_run = 'run';
201
-
202
-	const signal_create_mount = 'create_mount';
203
-	const signal_delete_mount = 'delete_mount';
204
-	const signal_param_mount_type = 'mounttype';
205
-	const signal_param_users = 'users';
206
-
207
-	/**
208
-	 * @var \OC\Files\Storage\StorageFactory $loader
209
-	 */
210
-	private static $loader;
211
-
212
-	/** @var bool */
213
-	private static $logWarningWhenAddingStorageWrapper = true;
214
-
215
-	/**
216
-	 * @param bool $shouldLog
217
-	 * @return bool previous value
218
-	 * @internal
219
-	 */
220
-	public static function logWarningWhenAddingStorageWrapper($shouldLog) {
221
-		$previousValue = self::$logWarningWhenAddingStorageWrapper;
222
-		self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
223
-		return $previousValue;
224
-	}
225
-
226
-	/**
227
-	 * @param string $wrapperName
228
-	 * @param callable $wrapper
229
-	 * @param int $priority
230
-	 */
231
-	public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
232
-		if (self::$logWarningWhenAddingStorageWrapper) {
233
-			\OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
234
-				'wrapper' => $wrapperName,
235
-				'app' => 'filesystem',
236
-			]);
237
-		}
238
-
239
-		$mounts = self::getMountManager()->getAll();
240
-		if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
241
-			// do not re-wrap if storage with this name already existed
242
-			return;
243
-		}
244
-	}
245
-
246
-	/**
247
-	 * Returns the storage factory
248
-	 *
249
-	 * @return \OCP\Files\Storage\IStorageFactory
250
-	 */
251
-	public static function getLoader() {
252
-		if (!self::$loader) {
253
-			self::$loader = new StorageFactory();
254
-		}
255
-		return self::$loader;
256
-	}
257
-
258
-	/**
259
-	 * Returns the mount manager
260
-	 *
261
-	 * @return \OC\Files\Mount\Manager
262
-	 */
263
-	public static function getMountManager($user = '') {
264
-		if (!self::$mounts) {
265
-			\OC_Util::setupFS($user);
266
-		}
267
-		return self::$mounts;
268
-	}
269
-
270
-	/**
271
-	 * get the mountpoint of the storage object for a path
272
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
273
-	 * returned mountpoint is relative to the absolute root of the filesystem
274
-	 * and doesn't take the chroot into account )
275
-	 *
276
-	 * @param string $path
277
-	 * @return string
278
-	 */
279
-	static public function getMountPoint($path) {
280
-		if (!self::$mounts) {
281
-			\OC_Util::setupFS();
282
-		}
283
-		$mount = self::$mounts->find($path);
284
-		if ($mount) {
285
-			return $mount->getMountPoint();
286
-		} else {
287
-			return '';
288
-		}
289
-	}
290
-
291
-	/**
292
-	 * get a list of all mount points in a directory
293
-	 *
294
-	 * @param string $path
295
-	 * @return string[]
296
-	 */
297
-	static public function getMountPoints($path) {
298
-		if (!self::$mounts) {
299
-			\OC_Util::setupFS();
300
-		}
301
-		$result = array();
302
-		$mounts = self::$mounts->findIn($path);
303
-		foreach ($mounts as $mount) {
304
-			$result[] = $mount->getMountPoint();
305
-		}
306
-		return $result;
307
-	}
308
-
309
-	/**
310
-	 * get the storage mounted at $mountPoint
311
-	 *
312
-	 * @param string $mountPoint
313
-	 * @return \OC\Files\Storage\Storage
314
-	 */
315
-	public static function getStorage($mountPoint) {
316
-		if (!self::$mounts) {
317
-			\OC_Util::setupFS();
318
-		}
319
-		$mount = self::$mounts->find($mountPoint);
320
-		return $mount->getStorage();
321
-	}
322
-
323
-	/**
324
-	 * @param string $id
325
-	 * @return Mount\MountPoint[]
326
-	 */
327
-	public static function getMountByStorageId($id) {
328
-		if (!self::$mounts) {
329
-			\OC_Util::setupFS();
330
-		}
331
-		return self::$mounts->findByStorageId($id);
332
-	}
333
-
334
-	/**
335
-	 * @param int $id
336
-	 * @return Mount\MountPoint[]
337
-	 */
338
-	public static function getMountByNumericId($id) {
339
-		if (!self::$mounts) {
340
-			\OC_Util::setupFS();
341
-		}
342
-		return self::$mounts->findByNumericId($id);
343
-	}
344
-
345
-	/**
346
-	 * resolve a path to a storage and internal path
347
-	 *
348
-	 * @param string $path
349
-	 * @return array an array consisting of the storage and the internal path
350
-	 */
351
-	static public function resolvePath($path) {
352
-		if (!self::$mounts) {
353
-			\OC_Util::setupFS();
354
-		}
355
-		$mount = self::$mounts->find($path);
356
-		if ($mount) {
357
-			return array($mount->getStorage(), rtrim($mount->getInternalPath($path), '/'));
358
-		} else {
359
-			return array(null, null);
360
-		}
361
-	}
362
-
363
-	static public function init($user, $root) {
364
-		if (self::$defaultInstance) {
365
-			return false;
366
-		}
367
-		self::getLoader();
368
-		self::$defaultInstance = new View($root);
369
-
370
-		if (!self::$mounts) {
371
-			self::$mounts = \OC::$server->getMountManager();
372
-		}
373
-
374
-		//load custom mount config
375
-		self::initMountPoints($user);
376
-
377
-		self::$loaded = true;
378
-
379
-		return true;
380
-	}
381
-
382
-	static public function initMountManager() {
383
-		if (!self::$mounts) {
384
-			self::$mounts = \OC::$server->getMountManager();
385
-		}
386
-	}
387
-
388
-	/**
389
-	 * Initialize system and personal mount points for a user
390
-	 *
391
-	 * @param string $user
392
-	 * @throws \OC\User\NoUserException if the user is not available
393
-	 */
394
-	public static function initMountPoints($user = '') {
395
-		if ($user == '') {
396
-			$user = \OC_User::getUser();
397
-		}
398
-		if ($user === null || $user === false || $user === '') {
399
-			throw new \OC\User\NoUserException('Attempted to initialize mount points for null user and no user in session');
400
-		}
401
-
402
-		if (isset(self::$usersSetup[$user])) {
403
-			return;
404
-		}
405
-
406
-		self::$usersSetup[$user] = true;
407
-
408
-		$userManager = \OC::$server->getUserManager();
409
-		$userObject = $userManager->get($user);
410
-
411
-		if (is_null($userObject)) {
412
-			\OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
413
-			// reset flag, this will make it possible to rethrow the exception if called again
414
-			unset(self::$usersSetup[$user]);
415
-			throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
416
-		}
417
-
418
-		$realUid = $userObject->getUID();
419
-		// workaround in case of different casings
420
-		if ($user !== $realUid) {
421
-			$stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
422
-			\OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "' . $realUid . '" got "' . $user . '". Stack: ' . $stack, \OCP\Util::WARN);
423
-			$user = $realUid;
424
-
425
-			// again with the correct casing
426
-			if (isset(self::$usersSetup[$user])) {
427
-				return;
428
-			}
429
-
430
-			self::$usersSetup[$user] = true;
431
-		}
432
-
433
-		if (\OC::$server->getLockdownManager()->canAccessFilesystem()) {
434
-			/** @var \OC\Files\Config\MountProviderCollection $mountConfigManager */
435
-			$mountConfigManager = \OC::$server->getMountProviderCollection();
436
-
437
-			// home mounts are handled seperate since we need to ensure this is mounted before we call the other mount providers
438
-			$homeMount = $mountConfigManager->getHomeMountForUser($userObject);
439
-
440
-			self::getMountManager()->addMount($homeMount);
441
-
442
-			\OC\Files\Filesystem::getStorage($user);
443
-
444
-			// Chance to mount for other storages
445
-			if ($userObject) {
446
-				$mounts = $mountConfigManager->addMountForUser($userObject, self::getMountManager());
447
-				$mounts[] = $homeMount;
448
-				$mountConfigManager->registerMounts($userObject, $mounts);
449
-			}
450
-
451
-			self::listenForNewMountProviders($mountConfigManager, $userManager);
452
-		} else {
453
-			self::getMountManager()->addMount(new MountPoint(
454
-				new NullStorage([]),
455
-				'/' . $user
456
-			));
457
-			self::getMountManager()->addMount(new MountPoint(
458
-				new NullStorage([]),
459
-				'/' . $user . '/files'
460
-			));
461
-		}
462
-		\OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
463
-	}
464
-
465
-	/**
466
-	 * Get mounts from mount providers that are registered after setup
467
-	 *
468
-	 * @param MountProviderCollection $mountConfigManager
469
-	 * @param IUserManager $userManager
470
-	 */
471
-	private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
472
-		if (!self::$listeningForProviders) {
473
-			self::$listeningForProviders = true;
474
-			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
475
-				foreach (Filesystem::$usersSetup as $user => $setup) {
476
-					$userObject = $userManager->get($user);
477
-					if ($userObject) {
478
-						$mounts = $provider->getMountsForUser($userObject, Filesystem::getLoader());
479
-						array_walk($mounts, array(self::$mounts, 'addMount'));
480
-					}
481
-				}
482
-			});
483
-		}
484
-	}
485
-
486
-	/**
487
-	 * get the default filesystem view
488
-	 *
489
-	 * @return View
490
-	 */
491
-	static public function getView() {
492
-		return self::$defaultInstance;
493
-	}
494
-
495
-	/**
496
-	 * tear down the filesystem, removing all storage providers
497
-	 */
498
-	static public function tearDown() {
499
-		self::clearMounts();
500
-		self::$defaultInstance = null;
501
-	}
502
-
503
-	/**
504
-	 * get the relative path of the root data directory for the current user
505
-	 *
506
-	 * @return string
507
-	 *
508
-	 * Returns path like /admin/files
509
-	 */
510
-	static public function getRoot() {
511
-		if (!self::$defaultInstance) {
512
-			return null;
513
-		}
514
-		return self::$defaultInstance->getRoot();
515
-	}
516
-
517
-	/**
518
-	 * clear all mounts and storage backends
519
-	 */
520
-	public static function clearMounts() {
521
-		if (self::$mounts) {
522
-			self::$usersSetup = array();
523
-			self::$mounts->clear();
524
-		}
525
-	}
526
-
527
-	/**
528
-	 * mount an \OC\Files\Storage\Storage in our virtual filesystem
529
-	 *
530
-	 * @param \OC\Files\Storage\Storage|string $class
531
-	 * @param array $arguments
532
-	 * @param string $mountpoint
533
-	 */
534
-	static public function mount($class, $arguments, $mountpoint) {
535
-		if (!self::$mounts) {
536
-			\OC_Util::setupFS();
537
-		}
538
-		$mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
539
-		self::$mounts->addMount($mount);
540
-	}
541
-
542
-	/**
543
-	 * return the path to a local version of the file
544
-	 * we need this because we can't know if a file is stored local or not from
545
-	 * outside the filestorage and for some purposes a local file is needed
546
-	 *
547
-	 * @param string $path
548
-	 * @return string
549
-	 */
550
-	static public function getLocalFile($path) {
551
-		return self::$defaultInstance->getLocalFile($path);
552
-	}
553
-
554
-	/**
555
-	 * @param string $path
556
-	 * @return string
557
-	 */
558
-	static public function getLocalFolder($path) {
559
-		return self::$defaultInstance->getLocalFolder($path);
560
-	}
561
-
562
-	/**
563
-	 * return path to file which reflects one visible in browser
564
-	 *
565
-	 * @param string $path
566
-	 * @return string
567
-	 */
568
-	static public function getLocalPath($path) {
569
-		$datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
570
-		$newpath = $path;
571
-		if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
572
-			$newpath = substr($path, strlen($datadir));
573
-		}
574
-		return $newpath;
575
-	}
576
-
577
-	/**
578
-	 * check if the requested path is valid
579
-	 *
580
-	 * @param string $path
581
-	 * @return bool
582
-	 */
583
-	static public function isValidPath($path) {
584
-		$path = self::normalizePath($path);
585
-		if (!$path || $path[0] !== '/') {
586
-			$path = '/' . $path;
587
-		}
588
-		if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
589
-			return false;
590
-		}
591
-		return true;
592
-	}
593
-
594
-	/**
595
-	 * checks if a file is blacklisted for storage in the filesystem
596
-	 * Listens to write and rename hooks
597
-	 *
598
-	 * @param array $data from hook
599
-	 */
600
-	static public function isBlacklisted($data) {
601
-		if (isset($data['path'])) {
602
-			$path = $data['path'];
603
-		} else if (isset($data['newpath'])) {
604
-			$path = $data['newpath'];
605
-		}
606
-		if (isset($path)) {
607
-			if (self::isFileBlacklisted($path)) {
608
-				$data['run'] = false;
609
-			}
610
-		}
611
-	}
612
-
613
-	/**
614
-	 * @param string $filename
615
-	 * @return bool
616
-	 */
617
-	static public function isFileBlacklisted($filename) {
618
-		$filename = self::normalizePath($filename);
619
-
620
-		$blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess'));
621
-		$filename = strtolower(basename($filename));
622
-		return in_array($filename, $blacklist);
623
-	}
624
-
625
-	/**
626
-	 * check if the directory should be ignored when scanning
627
-	 * NOTE: the special directories . and .. would cause never ending recursion
628
-	 *
629
-	 * @param String $dir
630
-	 * @return boolean
631
-	 */
632
-	static public function isIgnoredDir($dir) {
633
-		if ($dir === '.' || $dir === '..') {
634
-			return true;
635
-		}
636
-		return false;
637
-	}
638
-
639
-	/**
640
-	 * following functions are equivalent to their php builtin equivalents for arguments/return values.
641
-	 */
642
-	static public function mkdir($path) {
643
-		return self::$defaultInstance->mkdir($path);
644
-	}
645
-
646
-	static public function rmdir($path) {
647
-		return self::$defaultInstance->rmdir($path);
648
-	}
649
-
650
-	static public function opendir($path) {
651
-		return self::$defaultInstance->opendir($path);
652
-	}
653
-
654
-	static public function readdir($path) {
655
-		return self::$defaultInstance->readdir($path);
656
-	}
657
-
658
-	static public function is_dir($path) {
659
-		return self::$defaultInstance->is_dir($path);
660
-	}
661
-
662
-	static public function is_file($path) {
663
-		return self::$defaultInstance->is_file($path);
664
-	}
665
-
666
-	static public function stat($path) {
667
-		return self::$defaultInstance->stat($path);
668
-	}
669
-
670
-	static public function filetype($path) {
671
-		return self::$defaultInstance->filetype($path);
672
-	}
673
-
674
-	static public function filesize($path) {
675
-		return self::$defaultInstance->filesize($path);
676
-	}
677
-
678
-	static public function readfile($path) {
679
-		return self::$defaultInstance->readfile($path);
680
-	}
681
-
682
-	static public function isCreatable($path) {
683
-		return self::$defaultInstance->isCreatable($path);
684
-	}
685
-
686
-	static public function isReadable($path) {
687
-		return self::$defaultInstance->isReadable($path);
688
-	}
689
-
690
-	static public function isUpdatable($path) {
691
-		return self::$defaultInstance->isUpdatable($path);
692
-	}
693
-
694
-	static public function isDeletable($path) {
695
-		return self::$defaultInstance->isDeletable($path);
696
-	}
697
-
698
-	static public function isSharable($path) {
699
-		return self::$defaultInstance->isSharable($path);
700
-	}
701
-
702
-	static public function file_exists($path) {
703
-		return self::$defaultInstance->file_exists($path);
704
-	}
705
-
706
-	static public function filemtime($path) {
707
-		return self::$defaultInstance->filemtime($path);
708
-	}
709
-
710
-	static public function touch($path, $mtime = null) {
711
-		return self::$defaultInstance->touch($path, $mtime);
712
-	}
713
-
714
-	/**
715
-	 * @return string
716
-	 */
717
-	static public function file_get_contents($path) {
718
-		return self::$defaultInstance->file_get_contents($path);
719
-	}
720
-
721
-	static public function file_put_contents($path, $data) {
722
-		return self::$defaultInstance->file_put_contents($path, $data);
723
-	}
724
-
725
-	static public function unlink($path) {
726
-		return self::$defaultInstance->unlink($path);
727
-	}
728
-
729
-	static public function rename($path1, $path2) {
730
-		return self::$defaultInstance->rename($path1, $path2);
731
-	}
732
-
733
-	static public function copy($path1, $path2) {
734
-		return self::$defaultInstance->copy($path1, $path2);
735
-	}
736
-
737
-	static public function fopen($path, $mode) {
738
-		return self::$defaultInstance->fopen($path, $mode);
739
-	}
740
-
741
-	/**
742
-	 * @return string
743
-	 */
744
-	static public function toTmpFile($path) {
745
-		return self::$defaultInstance->toTmpFile($path);
746
-	}
747
-
748
-	static public function fromTmpFile($tmpFile, $path) {
749
-		return self::$defaultInstance->fromTmpFile($tmpFile, $path);
750
-	}
751
-
752
-	static public function getMimeType($path) {
753
-		return self::$defaultInstance->getMimeType($path);
754
-	}
755
-
756
-	static public function hash($type, $path, $raw = false) {
757
-		return self::$defaultInstance->hash($type, $path, $raw);
758
-	}
759
-
760
-	static public function free_space($path = '/') {
761
-		return self::$defaultInstance->free_space($path);
762
-	}
763
-
764
-	static public function search($query) {
765
-		return self::$defaultInstance->search($query);
766
-	}
767
-
768
-	/**
769
-	 * @param string $query
770
-	 */
771
-	static public function searchByMime($query) {
772
-		return self::$defaultInstance->searchByMime($query);
773
-	}
774
-
775
-	/**
776
-	 * @param string|int $tag name or tag id
777
-	 * @param string $userId owner of the tags
778
-	 * @return FileInfo[] array or file info
779
-	 */
780
-	static public function searchByTag($tag, $userId) {
781
-		return self::$defaultInstance->searchByTag($tag, $userId);
782
-	}
783
-
784
-	/**
785
-	 * check if a file or folder has been updated since $time
786
-	 *
787
-	 * @param string $path
788
-	 * @param int $time
789
-	 * @return bool
790
-	 */
791
-	static public function hasUpdated($path, $time) {
792
-		return self::$defaultInstance->hasUpdated($path, $time);
793
-	}
794
-
795
-	/**
796
-	 * Fix common problems with a file path
797
-	 *
798
-	 * @param string $path
799
-	 * @param bool $stripTrailingSlash whether to strip the trailing slash
800
-	 * @param bool $isAbsolutePath whether the given path is absolute
801
-	 * @param bool $keepUnicode true to disable unicode normalization
802
-	 * @return string
803
-	 */
804
-	public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
805
-		if (is_null(self::$normalizedPathCache)) {
806
-			self::$normalizedPathCache = new CappedMemoryCache();
807
-		}
808
-
809
-		/**
810
-		 * FIXME: This is a workaround for existing classes and files which call
811
-		 *        this function with another type than a valid string. This
812
-		 *        conversion should get removed as soon as all existing
813
-		 *        function calls have been fixed.
814
-		 */
815
-		$path = (string)$path;
816
-
817
-		$cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
818
-
819
-		if (isset(self::$normalizedPathCache[$cacheKey])) {
820
-			return self::$normalizedPathCache[$cacheKey];
821
-		}
822
-
823
-		if ($path == '') {
824
-			return '/';
825
-		}
826
-
827
-		//normalize unicode if possible
828
-		if (!$keepUnicode) {
829
-			$path = \OC_Util::normalizeUnicode($path);
830
-		}
831
-
832
-		//no windows style slashes
833
-		$path = str_replace('\\', '/', $path);
834
-
835
-		//add leading slash
836
-		if ($path[0] !== '/') {
837
-			$path = '/' . $path;
838
-		}
839
-
840
-		// remove '/./'
841
-		// ugly, but str_replace() can't replace them all in one go
842
-		// as the replacement itself is part of the search string
843
-		// which will only be found during the next iteration
844
-		while (strpos($path, '/./') !== false) {
845
-			$path = str_replace('/./', '/', $path);
846
-		}
847
-		// remove sequences of slashes
848
-		$path = preg_replace('#/{2,}#', '/', $path);
849
-
850
-		//remove trailing slash
851
-		if ($stripTrailingSlash and strlen($path) > 1 and substr($path, -1, 1) === '/') {
852
-			$path = substr($path, 0, -1);
853
-		}
854
-
855
-		// remove trailing '/.'
856
-		if (substr($path, -2) == '/.') {
857
-			$path = substr($path, 0, -2);
858
-		}
859
-
860
-		$normalizedPath = $path;
861
-		self::$normalizedPathCache[$cacheKey] = $normalizedPath;
862
-
863
-		return $normalizedPath;
864
-	}
865
-
866
-	/**
867
-	 * get the filesystem info
868
-	 *
869
-	 * @param string $path
870
-	 * @param boolean $includeMountPoints whether to add mountpoint sizes,
871
-	 * defaults to true
872
-	 * @return \OC\Files\FileInfo|bool False if file does not exist
873
-	 */
874
-	public static function getFileInfo($path, $includeMountPoints = true) {
875
-		return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
876
-	}
877
-
878
-	/**
879
-	 * change file metadata
880
-	 *
881
-	 * @param string $path
882
-	 * @param array $data
883
-	 * @return int
884
-	 *
885
-	 * returns the fileid of the updated file
886
-	 */
887
-	public static function putFileInfo($path, $data) {
888
-		return self::$defaultInstance->putFileInfo($path, $data);
889
-	}
890
-
891
-	/**
892
-	 * get the content of a directory
893
-	 *
894
-	 * @param string $directory path under datadirectory
895
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
896
-	 * @return \OC\Files\FileInfo[]
897
-	 */
898
-	public static function getDirectoryContent($directory, $mimetype_filter = '') {
899
-		return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
900
-	}
901
-
902
-	/**
903
-	 * Get the path of a file by id
904
-	 *
905
-	 * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
906
-	 *
907
-	 * @param int $id
908
-	 * @throws NotFoundException
909
-	 * @return string
910
-	 */
911
-	public static function getPath($id) {
912
-		return self::$defaultInstance->getPath($id);
913
-	}
914
-
915
-	/**
916
-	 * Get the owner for a file or folder
917
-	 *
918
-	 * @param string $path
919
-	 * @return string
920
-	 */
921
-	public static function getOwner($path) {
922
-		return self::$defaultInstance->getOwner($path);
923
-	}
924
-
925
-	/**
926
-	 * get the ETag for a file or folder
927
-	 *
928
-	 * @param string $path
929
-	 * @return string
930
-	 */
931
-	static public function getETag($path) {
932
-		return self::$defaultInstance->getETag($path);
933
-	}
73
+    /**
74
+     * @var Mount\Manager $mounts
75
+     */
76
+    private static $mounts;
77
+
78
+    public static $loaded = false;
79
+    /**
80
+     * @var \OC\Files\View $defaultInstance
81
+     */
82
+    static private $defaultInstance;
83
+
84
+    static private $usersSetup = array();
85
+
86
+    static private $normalizedPathCache = null;
87
+
88
+    static private $listeningForProviders = false;
89
+
90
+    /**
91
+     * classname which used for hooks handling
92
+     * used as signalclass in OC_Hooks::emit()
93
+     */
94
+    const CLASSNAME = 'OC_Filesystem';
95
+
96
+    /**
97
+     * signalname emitted before file renaming
98
+     *
99
+     * @param string $oldpath
100
+     * @param string $newpath
101
+     */
102
+    const signal_rename = 'rename';
103
+
104
+    /**
105
+     * signal emitted after file renaming
106
+     *
107
+     * @param string $oldpath
108
+     * @param string $newpath
109
+     */
110
+    const signal_post_rename = 'post_rename';
111
+
112
+    /**
113
+     * signal emitted before file/dir creation
114
+     *
115
+     * @param string $path
116
+     * @param bool $run changing this flag to false in hook handler will cancel event
117
+     */
118
+    const signal_create = 'create';
119
+
120
+    /**
121
+     * signal emitted after file/dir creation
122
+     *
123
+     * @param string $path
124
+     * @param bool $run changing this flag to false in hook handler will cancel event
125
+     */
126
+    const signal_post_create = 'post_create';
127
+
128
+    /**
129
+     * signal emits before file/dir copy
130
+     *
131
+     * @param string $oldpath
132
+     * @param string $newpath
133
+     * @param bool $run changing this flag to false in hook handler will cancel event
134
+     */
135
+    const signal_copy = 'copy';
136
+
137
+    /**
138
+     * signal emits after file/dir copy
139
+     *
140
+     * @param string $oldpath
141
+     * @param string $newpath
142
+     */
143
+    const signal_post_copy = 'post_copy';
144
+
145
+    /**
146
+     * signal emits before file/dir save
147
+     *
148
+     * @param string $path
149
+     * @param bool $run changing this flag to false in hook handler will cancel event
150
+     */
151
+    const signal_write = 'write';
152
+
153
+    /**
154
+     * signal emits after file/dir save
155
+     *
156
+     * @param string $path
157
+     */
158
+    const signal_post_write = 'post_write';
159
+
160
+    /**
161
+     * signal emitted before file/dir update
162
+     *
163
+     * @param string $path
164
+     * @param bool $run changing this flag to false in hook handler will cancel event
165
+     */
166
+    const signal_update = 'update';
167
+
168
+    /**
169
+     * signal emitted after file/dir update
170
+     *
171
+     * @param string $path
172
+     * @param bool $run changing this flag to false in hook handler will cancel event
173
+     */
174
+    const signal_post_update = 'post_update';
175
+
176
+    /**
177
+     * signal emits when reading file/dir
178
+     *
179
+     * @param string $path
180
+     */
181
+    const signal_read = 'read';
182
+
183
+    /**
184
+     * signal emits when removing file/dir
185
+     *
186
+     * @param string $path
187
+     */
188
+    const signal_delete = 'delete';
189
+
190
+    /**
191
+     * parameters definitions for signals
192
+     */
193
+    const signal_param_path = 'path';
194
+    const signal_param_oldpath = 'oldpath';
195
+    const signal_param_newpath = 'newpath';
196
+
197
+    /**
198
+     * run - changing this flag to false in hook handler will cancel event
199
+     */
200
+    const signal_param_run = 'run';
201
+
202
+    const signal_create_mount = 'create_mount';
203
+    const signal_delete_mount = 'delete_mount';
204
+    const signal_param_mount_type = 'mounttype';
205
+    const signal_param_users = 'users';
206
+
207
+    /**
208
+     * @var \OC\Files\Storage\StorageFactory $loader
209
+     */
210
+    private static $loader;
211
+
212
+    /** @var bool */
213
+    private static $logWarningWhenAddingStorageWrapper = true;
214
+
215
+    /**
216
+     * @param bool $shouldLog
217
+     * @return bool previous value
218
+     * @internal
219
+     */
220
+    public static function logWarningWhenAddingStorageWrapper($shouldLog) {
221
+        $previousValue = self::$logWarningWhenAddingStorageWrapper;
222
+        self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
223
+        return $previousValue;
224
+    }
225
+
226
+    /**
227
+     * @param string $wrapperName
228
+     * @param callable $wrapper
229
+     * @param int $priority
230
+     */
231
+    public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
232
+        if (self::$logWarningWhenAddingStorageWrapper) {
233
+            \OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
234
+                'wrapper' => $wrapperName,
235
+                'app' => 'filesystem',
236
+            ]);
237
+        }
238
+
239
+        $mounts = self::getMountManager()->getAll();
240
+        if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
241
+            // do not re-wrap if storage with this name already existed
242
+            return;
243
+        }
244
+    }
245
+
246
+    /**
247
+     * Returns the storage factory
248
+     *
249
+     * @return \OCP\Files\Storage\IStorageFactory
250
+     */
251
+    public static function getLoader() {
252
+        if (!self::$loader) {
253
+            self::$loader = new StorageFactory();
254
+        }
255
+        return self::$loader;
256
+    }
257
+
258
+    /**
259
+     * Returns the mount manager
260
+     *
261
+     * @return \OC\Files\Mount\Manager
262
+     */
263
+    public static function getMountManager($user = '') {
264
+        if (!self::$mounts) {
265
+            \OC_Util::setupFS($user);
266
+        }
267
+        return self::$mounts;
268
+    }
269
+
270
+    /**
271
+     * get the mountpoint of the storage object for a path
272
+     * ( note: because a storage is not always mounted inside the fakeroot, the
273
+     * returned mountpoint is relative to the absolute root of the filesystem
274
+     * and doesn't take the chroot into account )
275
+     *
276
+     * @param string $path
277
+     * @return string
278
+     */
279
+    static public function getMountPoint($path) {
280
+        if (!self::$mounts) {
281
+            \OC_Util::setupFS();
282
+        }
283
+        $mount = self::$mounts->find($path);
284
+        if ($mount) {
285
+            return $mount->getMountPoint();
286
+        } else {
287
+            return '';
288
+        }
289
+    }
290
+
291
+    /**
292
+     * get a list of all mount points in a directory
293
+     *
294
+     * @param string $path
295
+     * @return string[]
296
+     */
297
+    static public function getMountPoints($path) {
298
+        if (!self::$mounts) {
299
+            \OC_Util::setupFS();
300
+        }
301
+        $result = array();
302
+        $mounts = self::$mounts->findIn($path);
303
+        foreach ($mounts as $mount) {
304
+            $result[] = $mount->getMountPoint();
305
+        }
306
+        return $result;
307
+    }
308
+
309
+    /**
310
+     * get the storage mounted at $mountPoint
311
+     *
312
+     * @param string $mountPoint
313
+     * @return \OC\Files\Storage\Storage
314
+     */
315
+    public static function getStorage($mountPoint) {
316
+        if (!self::$mounts) {
317
+            \OC_Util::setupFS();
318
+        }
319
+        $mount = self::$mounts->find($mountPoint);
320
+        return $mount->getStorage();
321
+    }
322
+
323
+    /**
324
+     * @param string $id
325
+     * @return Mount\MountPoint[]
326
+     */
327
+    public static function getMountByStorageId($id) {
328
+        if (!self::$mounts) {
329
+            \OC_Util::setupFS();
330
+        }
331
+        return self::$mounts->findByStorageId($id);
332
+    }
333
+
334
+    /**
335
+     * @param int $id
336
+     * @return Mount\MountPoint[]
337
+     */
338
+    public static function getMountByNumericId($id) {
339
+        if (!self::$mounts) {
340
+            \OC_Util::setupFS();
341
+        }
342
+        return self::$mounts->findByNumericId($id);
343
+    }
344
+
345
+    /**
346
+     * resolve a path to a storage and internal path
347
+     *
348
+     * @param string $path
349
+     * @return array an array consisting of the storage and the internal path
350
+     */
351
+    static public function resolvePath($path) {
352
+        if (!self::$mounts) {
353
+            \OC_Util::setupFS();
354
+        }
355
+        $mount = self::$mounts->find($path);
356
+        if ($mount) {
357
+            return array($mount->getStorage(), rtrim($mount->getInternalPath($path), '/'));
358
+        } else {
359
+            return array(null, null);
360
+        }
361
+    }
362
+
363
+    static public function init($user, $root) {
364
+        if (self::$defaultInstance) {
365
+            return false;
366
+        }
367
+        self::getLoader();
368
+        self::$defaultInstance = new View($root);
369
+
370
+        if (!self::$mounts) {
371
+            self::$mounts = \OC::$server->getMountManager();
372
+        }
373
+
374
+        //load custom mount config
375
+        self::initMountPoints($user);
376
+
377
+        self::$loaded = true;
378
+
379
+        return true;
380
+    }
381
+
382
+    static public function initMountManager() {
383
+        if (!self::$mounts) {
384
+            self::$mounts = \OC::$server->getMountManager();
385
+        }
386
+    }
387
+
388
+    /**
389
+     * Initialize system and personal mount points for a user
390
+     *
391
+     * @param string $user
392
+     * @throws \OC\User\NoUserException if the user is not available
393
+     */
394
+    public static function initMountPoints($user = '') {
395
+        if ($user == '') {
396
+            $user = \OC_User::getUser();
397
+        }
398
+        if ($user === null || $user === false || $user === '') {
399
+            throw new \OC\User\NoUserException('Attempted to initialize mount points for null user and no user in session');
400
+        }
401
+
402
+        if (isset(self::$usersSetup[$user])) {
403
+            return;
404
+        }
405
+
406
+        self::$usersSetup[$user] = true;
407
+
408
+        $userManager = \OC::$server->getUserManager();
409
+        $userObject = $userManager->get($user);
410
+
411
+        if (is_null($userObject)) {
412
+            \OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
413
+            // reset flag, this will make it possible to rethrow the exception if called again
414
+            unset(self::$usersSetup[$user]);
415
+            throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
416
+        }
417
+
418
+        $realUid = $userObject->getUID();
419
+        // workaround in case of different casings
420
+        if ($user !== $realUid) {
421
+            $stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
422
+            \OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "' . $realUid . '" got "' . $user . '". Stack: ' . $stack, \OCP\Util::WARN);
423
+            $user = $realUid;
424
+
425
+            // again with the correct casing
426
+            if (isset(self::$usersSetup[$user])) {
427
+                return;
428
+            }
429
+
430
+            self::$usersSetup[$user] = true;
431
+        }
432
+
433
+        if (\OC::$server->getLockdownManager()->canAccessFilesystem()) {
434
+            /** @var \OC\Files\Config\MountProviderCollection $mountConfigManager */
435
+            $mountConfigManager = \OC::$server->getMountProviderCollection();
436
+
437
+            // home mounts are handled seperate since we need to ensure this is mounted before we call the other mount providers
438
+            $homeMount = $mountConfigManager->getHomeMountForUser($userObject);
439
+
440
+            self::getMountManager()->addMount($homeMount);
441
+
442
+            \OC\Files\Filesystem::getStorage($user);
443
+
444
+            // Chance to mount for other storages
445
+            if ($userObject) {
446
+                $mounts = $mountConfigManager->addMountForUser($userObject, self::getMountManager());
447
+                $mounts[] = $homeMount;
448
+                $mountConfigManager->registerMounts($userObject, $mounts);
449
+            }
450
+
451
+            self::listenForNewMountProviders($mountConfigManager, $userManager);
452
+        } else {
453
+            self::getMountManager()->addMount(new MountPoint(
454
+                new NullStorage([]),
455
+                '/' . $user
456
+            ));
457
+            self::getMountManager()->addMount(new MountPoint(
458
+                new NullStorage([]),
459
+                '/' . $user . '/files'
460
+            ));
461
+        }
462
+        \OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
463
+    }
464
+
465
+    /**
466
+     * Get mounts from mount providers that are registered after setup
467
+     *
468
+     * @param MountProviderCollection $mountConfigManager
469
+     * @param IUserManager $userManager
470
+     */
471
+    private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
472
+        if (!self::$listeningForProviders) {
473
+            self::$listeningForProviders = true;
474
+            $mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
475
+                foreach (Filesystem::$usersSetup as $user => $setup) {
476
+                    $userObject = $userManager->get($user);
477
+                    if ($userObject) {
478
+                        $mounts = $provider->getMountsForUser($userObject, Filesystem::getLoader());
479
+                        array_walk($mounts, array(self::$mounts, 'addMount'));
480
+                    }
481
+                }
482
+            });
483
+        }
484
+    }
485
+
486
+    /**
487
+     * get the default filesystem view
488
+     *
489
+     * @return View
490
+     */
491
+    static public function getView() {
492
+        return self::$defaultInstance;
493
+    }
494
+
495
+    /**
496
+     * tear down the filesystem, removing all storage providers
497
+     */
498
+    static public function tearDown() {
499
+        self::clearMounts();
500
+        self::$defaultInstance = null;
501
+    }
502
+
503
+    /**
504
+     * get the relative path of the root data directory for the current user
505
+     *
506
+     * @return string
507
+     *
508
+     * Returns path like /admin/files
509
+     */
510
+    static public function getRoot() {
511
+        if (!self::$defaultInstance) {
512
+            return null;
513
+        }
514
+        return self::$defaultInstance->getRoot();
515
+    }
516
+
517
+    /**
518
+     * clear all mounts and storage backends
519
+     */
520
+    public static function clearMounts() {
521
+        if (self::$mounts) {
522
+            self::$usersSetup = array();
523
+            self::$mounts->clear();
524
+        }
525
+    }
526
+
527
+    /**
528
+     * mount an \OC\Files\Storage\Storage in our virtual filesystem
529
+     *
530
+     * @param \OC\Files\Storage\Storage|string $class
531
+     * @param array $arguments
532
+     * @param string $mountpoint
533
+     */
534
+    static public function mount($class, $arguments, $mountpoint) {
535
+        if (!self::$mounts) {
536
+            \OC_Util::setupFS();
537
+        }
538
+        $mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
539
+        self::$mounts->addMount($mount);
540
+    }
541
+
542
+    /**
543
+     * return the path to a local version of the file
544
+     * we need this because we can't know if a file is stored local or not from
545
+     * outside the filestorage and for some purposes a local file is needed
546
+     *
547
+     * @param string $path
548
+     * @return string
549
+     */
550
+    static public function getLocalFile($path) {
551
+        return self::$defaultInstance->getLocalFile($path);
552
+    }
553
+
554
+    /**
555
+     * @param string $path
556
+     * @return string
557
+     */
558
+    static public function getLocalFolder($path) {
559
+        return self::$defaultInstance->getLocalFolder($path);
560
+    }
561
+
562
+    /**
563
+     * return path to file which reflects one visible in browser
564
+     *
565
+     * @param string $path
566
+     * @return string
567
+     */
568
+    static public function getLocalPath($path) {
569
+        $datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
570
+        $newpath = $path;
571
+        if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
572
+            $newpath = substr($path, strlen($datadir));
573
+        }
574
+        return $newpath;
575
+    }
576
+
577
+    /**
578
+     * check if the requested path is valid
579
+     *
580
+     * @param string $path
581
+     * @return bool
582
+     */
583
+    static public function isValidPath($path) {
584
+        $path = self::normalizePath($path);
585
+        if (!$path || $path[0] !== '/') {
586
+            $path = '/' . $path;
587
+        }
588
+        if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
589
+            return false;
590
+        }
591
+        return true;
592
+    }
593
+
594
+    /**
595
+     * checks if a file is blacklisted for storage in the filesystem
596
+     * Listens to write and rename hooks
597
+     *
598
+     * @param array $data from hook
599
+     */
600
+    static public function isBlacklisted($data) {
601
+        if (isset($data['path'])) {
602
+            $path = $data['path'];
603
+        } else if (isset($data['newpath'])) {
604
+            $path = $data['newpath'];
605
+        }
606
+        if (isset($path)) {
607
+            if (self::isFileBlacklisted($path)) {
608
+                $data['run'] = false;
609
+            }
610
+        }
611
+    }
612
+
613
+    /**
614
+     * @param string $filename
615
+     * @return bool
616
+     */
617
+    static public function isFileBlacklisted($filename) {
618
+        $filename = self::normalizePath($filename);
619
+
620
+        $blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess'));
621
+        $filename = strtolower(basename($filename));
622
+        return in_array($filename, $blacklist);
623
+    }
624
+
625
+    /**
626
+     * check if the directory should be ignored when scanning
627
+     * NOTE: the special directories . and .. would cause never ending recursion
628
+     *
629
+     * @param String $dir
630
+     * @return boolean
631
+     */
632
+    static public function isIgnoredDir($dir) {
633
+        if ($dir === '.' || $dir === '..') {
634
+            return true;
635
+        }
636
+        return false;
637
+    }
638
+
639
+    /**
640
+     * following functions are equivalent to their php builtin equivalents for arguments/return values.
641
+     */
642
+    static public function mkdir($path) {
643
+        return self::$defaultInstance->mkdir($path);
644
+    }
645
+
646
+    static public function rmdir($path) {
647
+        return self::$defaultInstance->rmdir($path);
648
+    }
649
+
650
+    static public function opendir($path) {
651
+        return self::$defaultInstance->opendir($path);
652
+    }
653
+
654
+    static public function readdir($path) {
655
+        return self::$defaultInstance->readdir($path);
656
+    }
657
+
658
+    static public function is_dir($path) {
659
+        return self::$defaultInstance->is_dir($path);
660
+    }
661
+
662
+    static public function is_file($path) {
663
+        return self::$defaultInstance->is_file($path);
664
+    }
665
+
666
+    static public function stat($path) {
667
+        return self::$defaultInstance->stat($path);
668
+    }
669
+
670
+    static public function filetype($path) {
671
+        return self::$defaultInstance->filetype($path);
672
+    }
673
+
674
+    static public function filesize($path) {
675
+        return self::$defaultInstance->filesize($path);
676
+    }
677
+
678
+    static public function readfile($path) {
679
+        return self::$defaultInstance->readfile($path);
680
+    }
681
+
682
+    static public function isCreatable($path) {
683
+        return self::$defaultInstance->isCreatable($path);
684
+    }
685
+
686
+    static public function isReadable($path) {
687
+        return self::$defaultInstance->isReadable($path);
688
+    }
689
+
690
+    static public function isUpdatable($path) {
691
+        return self::$defaultInstance->isUpdatable($path);
692
+    }
693
+
694
+    static public function isDeletable($path) {
695
+        return self::$defaultInstance->isDeletable($path);
696
+    }
697
+
698
+    static public function isSharable($path) {
699
+        return self::$defaultInstance->isSharable($path);
700
+    }
701
+
702
+    static public function file_exists($path) {
703
+        return self::$defaultInstance->file_exists($path);
704
+    }
705
+
706
+    static public function filemtime($path) {
707
+        return self::$defaultInstance->filemtime($path);
708
+    }
709
+
710
+    static public function touch($path, $mtime = null) {
711
+        return self::$defaultInstance->touch($path, $mtime);
712
+    }
713
+
714
+    /**
715
+     * @return string
716
+     */
717
+    static public function file_get_contents($path) {
718
+        return self::$defaultInstance->file_get_contents($path);
719
+    }
720
+
721
+    static public function file_put_contents($path, $data) {
722
+        return self::$defaultInstance->file_put_contents($path, $data);
723
+    }
724
+
725
+    static public function unlink($path) {
726
+        return self::$defaultInstance->unlink($path);
727
+    }
728
+
729
+    static public function rename($path1, $path2) {
730
+        return self::$defaultInstance->rename($path1, $path2);
731
+    }
732
+
733
+    static public function copy($path1, $path2) {
734
+        return self::$defaultInstance->copy($path1, $path2);
735
+    }
736
+
737
+    static public function fopen($path, $mode) {
738
+        return self::$defaultInstance->fopen($path, $mode);
739
+    }
740
+
741
+    /**
742
+     * @return string
743
+     */
744
+    static public function toTmpFile($path) {
745
+        return self::$defaultInstance->toTmpFile($path);
746
+    }
747
+
748
+    static public function fromTmpFile($tmpFile, $path) {
749
+        return self::$defaultInstance->fromTmpFile($tmpFile, $path);
750
+    }
751
+
752
+    static public function getMimeType($path) {
753
+        return self::$defaultInstance->getMimeType($path);
754
+    }
755
+
756
+    static public function hash($type, $path, $raw = false) {
757
+        return self::$defaultInstance->hash($type, $path, $raw);
758
+    }
759
+
760
+    static public function free_space($path = '/') {
761
+        return self::$defaultInstance->free_space($path);
762
+    }
763
+
764
+    static public function search($query) {
765
+        return self::$defaultInstance->search($query);
766
+    }
767
+
768
+    /**
769
+     * @param string $query
770
+     */
771
+    static public function searchByMime($query) {
772
+        return self::$defaultInstance->searchByMime($query);
773
+    }
774
+
775
+    /**
776
+     * @param string|int $tag name or tag id
777
+     * @param string $userId owner of the tags
778
+     * @return FileInfo[] array or file info
779
+     */
780
+    static public function searchByTag($tag, $userId) {
781
+        return self::$defaultInstance->searchByTag($tag, $userId);
782
+    }
783
+
784
+    /**
785
+     * check if a file or folder has been updated since $time
786
+     *
787
+     * @param string $path
788
+     * @param int $time
789
+     * @return bool
790
+     */
791
+    static public function hasUpdated($path, $time) {
792
+        return self::$defaultInstance->hasUpdated($path, $time);
793
+    }
794
+
795
+    /**
796
+     * Fix common problems with a file path
797
+     *
798
+     * @param string $path
799
+     * @param bool $stripTrailingSlash whether to strip the trailing slash
800
+     * @param bool $isAbsolutePath whether the given path is absolute
801
+     * @param bool $keepUnicode true to disable unicode normalization
802
+     * @return string
803
+     */
804
+    public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
805
+        if (is_null(self::$normalizedPathCache)) {
806
+            self::$normalizedPathCache = new CappedMemoryCache();
807
+        }
808
+
809
+        /**
810
+         * FIXME: This is a workaround for existing classes and files which call
811
+         *        this function with another type than a valid string. This
812
+         *        conversion should get removed as soon as all existing
813
+         *        function calls have been fixed.
814
+         */
815
+        $path = (string)$path;
816
+
817
+        $cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
818
+
819
+        if (isset(self::$normalizedPathCache[$cacheKey])) {
820
+            return self::$normalizedPathCache[$cacheKey];
821
+        }
822
+
823
+        if ($path == '') {
824
+            return '/';
825
+        }
826
+
827
+        //normalize unicode if possible
828
+        if (!$keepUnicode) {
829
+            $path = \OC_Util::normalizeUnicode($path);
830
+        }
831
+
832
+        //no windows style slashes
833
+        $path = str_replace('\\', '/', $path);
834
+
835
+        //add leading slash
836
+        if ($path[0] !== '/') {
837
+            $path = '/' . $path;
838
+        }
839
+
840
+        // remove '/./'
841
+        // ugly, but str_replace() can't replace them all in one go
842
+        // as the replacement itself is part of the search string
843
+        // which will only be found during the next iteration
844
+        while (strpos($path, '/./') !== false) {
845
+            $path = str_replace('/./', '/', $path);
846
+        }
847
+        // remove sequences of slashes
848
+        $path = preg_replace('#/{2,}#', '/', $path);
849
+
850
+        //remove trailing slash
851
+        if ($stripTrailingSlash and strlen($path) > 1 and substr($path, -1, 1) === '/') {
852
+            $path = substr($path, 0, -1);
853
+        }
854
+
855
+        // remove trailing '/.'
856
+        if (substr($path, -2) == '/.') {
857
+            $path = substr($path, 0, -2);
858
+        }
859
+
860
+        $normalizedPath = $path;
861
+        self::$normalizedPathCache[$cacheKey] = $normalizedPath;
862
+
863
+        return $normalizedPath;
864
+    }
865
+
866
+    /**
867
+     * get the filesystem info
868
+     *
869
+     * @param string $path
870
+     * @param boolean $includeMountPoints whether to add mountpoint sizes,
871
+     * defaults to true
872
+     * @return \OC\Files\FileInfo|bool False if file does not exist
873
+     */
874
+    public static function getFileInfo($path, $includeMountPoints = true) {
875
+        return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
876
+    }
877
+
878
+    /**
879
+     * change file metadata
880
+     *
881
+     * @param string $path
882
+     * @param array $data
883
+     * @return int
884
+     *
885
+     * returns the fileid of the updated file
886
+     */
887
+    public static function putFileInfo($path, $data) {
888
+        return self::$defaultInstance->putFileInfo($path, $data);
889
+    }
890
+
891
+    /**
892
+     * get the content of a directory
893
+     *
894
+     * @param string $directory path under datadirectory
895
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
896
+     * @return \OC\Files\FileInfo[]
897
+     */
898
+    public static function getDirectoryContent($directory, $mimetype_filter = '') {
899
+        return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
900
+    }
901
+
902
+    /**
903
+     * Get the path of a file by id
904
+     *
905
+     * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
906
+     *
907
+     * @param int $id
908
+     * @throws NotFoundException
909
+     * @return string
910
+     */
911
+    public static function getPath($id) {
912
+        return self::$defaultInstance->getPath($id);
913
+    }
914
+
915
+    /**
916
+     * Get the owner for a file or folder
917
+     *
918
+     * @param string $path
919
+     * @return string
920
+     */
921
+    public static function getOwner($path) {
922
+        return self::$defaultInstance->getOwner($path);
923
+    }
924
+
925
+    /**
926
+     * get the ETag for a file or folder
927
+     *
928
+     * @param string $path
929
+     * @return string
930
+     */
931
+    static public function getETag($path) {
932
+        return self::$defaultInstance->getETag($path);
933
+    }
934 934
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Encryption.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -984,7 +984,7 @@  discard block
 block discarded – undo
984 984
 	/**
985 985
 	 * check if path points to a files version
986 986
 	 *
987
-	 * @param $path
987
+	 * @param string $path
988 988
 	 * @return bool
989 989
 	 */
990 990
 	protected function isVersion($path) {
@@ -995,7 +995,7 @@  discard block
 block discarded – undo
995 995
 	/**
996 996
 	 * check if the given storage should be encrypted or not
997 997
 	 *
998
-	 * @param $path
998
+	 * @param string $path
999 999
 	 * @return bool
1000 1000
 	 */
1001 1001
 	protected function shouldEncrypt($path) {
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -368,8 +368,8 @@  discard block
 block discarded – undo
368 368
 		// check if the file is stored in the array cache, this means that we
369 369
 		// copy a file over to the versions folder, in this case we don't want to
370 370
 		// decrypt it
371
-		if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
372
-			$this->arrayCache->remove('encryption_copy_version_' . $path);
371
+		if ($this->arrayCache->hasKey('encryption_copy_version_'.$path)) {
372
+			$this->arrayCache->remove('encryption_copy_version_'.$path);
373 373
 			return $this->storage->fopen($path, $mode);
374 374
 		}
375 375
 
@@ -439,8 +439,8 @@  discard block
 block discarded – undo
439 439
 					}
440 440
 				}
441 441
 			} catch (ModuleDoesNotExistsException $e) {
442
-				$this->logger->warning('Encryption module "' . $encryptionModuleId .
443
-					'" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
442
+				$this->logger->warning('Encryption module "'.$encryptionModuleId.
443
+					'" not found, file will be stored unencrypted ('.$e->getMessage().')');
444 444
 			}
445 445
 
446 446
 			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
@@ -492,7 +492,7 @@  discard block
 block discarded – undo
492 492
 				try {
493 493
 					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
494 494
 				} catch (\Exception $e) {
495
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
495
+					$this->logger->error('Couldn\'t re-calculate unencrypted size for '.$path);
496 496
 					$this->logger->logException($e);
497 497
 				}
498 498
 				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
@@ -521,7 +521,7 @@  discard block
 block discarded – undo
521 521
 
522 522
 		// if we couldn't open the file we return the old unencrypted size
523 523
 		if (!is_resource($stream)) {
524
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
524
+			$this->logger->error('Could not open '.$path.'. Recalculation of unencrypted size aborted.');
525 525
 			return $unencryptedSize;
526 526
 		}
527 527
 
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
 		// next highest is end of chunks, one subtracted is last one
547 547
 		// we have to read the last chunk, we can't just calculate it (because of padding etc)
548 548
 
549
-		$lastChunkNr = ceil($size/ $blockSize)-1;
549
+		$lastChunkNr = ceil($size / $blockSize) - 1;
550 550
 		// calculate last chunk position
551 551
 		$lastChunkPos = ($lastChunkNr * $blockSize);
552 552
 		// try to fseek to the last chunk, if it fails we have to read the whole file
@@ -554,16 +554,16 @@  discard block
 block discarded – undo
554 554
 			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
555 555
 		}
556 556
 
557
-		$lastChunkContentEncrypted='';
557
+		$lastChunkContentEncrypted = '';
558 558
 		$count = $blockSize;
559 559
 
560 560
 		while ($count > 0) {
561
-			$data=fread($stream, $blockSize);
562
-			$count=strlen($data);
561
+			$data = fread($stream, $blockSize);
562
+			$count = strlen($data);
563 563
 			$lastChunkContentEncrypted .= $data;
564
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
564
+			if (strlen($lastChunkContentEncrypted) > $blockSize) {
565 565
 				$newUnencryptedSize += $unencryptedBlockSize;
566
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
566
+				$lastChunkContentEncrypted = substr($lastChunkContentEncrypted, $blockSize);
567 567
 			}
568 568
 		}
569 569
 
@@ -571,8 +571,8 @@  discard block
 block discarded – undo
571 571
 
572 572
 		// we have to decrypt the last chunk to get it actual size
573 573
 		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
574
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
575
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
574
+		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr.'end');
575
+		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr.'end');
576 576
 
577 577
 		// calc the real file size with the size of the last chunk
578 578
 		$newUnencryptedSize += strlen($decryptedLastChunk);
@@ -653,9 +653,9 @@  discard block
 block discarded – undo
653 653
 	private function updateEncryptedVersion(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
654 654
 		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath) ? 1 : 0;
655 655
 		$cacheInformation = [
656
-			'encrypted' => (bool)$isEncrypted,
656
+			'encrypted' => (bool) $isEncrypted,
657 657
 		];
658
-		if($isEncrypted === 1) {
658
+		if ($isEncrypted === 1) {
659 659
 			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
660 660
 
661 661
 			// In case of a move operation from an unencrypted to an encrypted
@@ -663,7 +663,7 @@  discard block
 block discarded – undo
663 663
 			// correct value would be "1". Thus we manually set the value to "1"
664 664
 			// for those cases.
665 665
 			// See also https://github.com/owncloud/core/issues/23078
666
-			if($encryptedVersion === 0) {
666
+			if ($encryptedVersion === 0) {
667 667
 				$encryptedVersion = 1;
668 668
 			}
669 669
 
@@ -699,9 +699,9 @@  discard block
 block discarded – undo
699 699
 			// remember that we try to create a version so that we can detect it during
700 700
 			// fopen($sourceInternalPath) and by-pass the encryption in order to
701 701
 			// create a 1:1 copy of the file
702
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
702
+			$this->arrayCache->set('encryption_copy_version_'.$sourceInternalPath, true);
703 703
 			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
704
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
704
+			$this->arrayCache->remove('encryption_copy_version_'.$sourceInternalPath);
705 705
 			if ($result) {
706 706
 				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
707 707
 				// make sure that we update the unencrypted size for the version
@@ -721,7 +721,7 @@  discard block
 block discarded – undo
721 721
 		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
722 722
 		if (count($mount) === 1) {
723 723
 			$mountPoint = $mount[0]->getMountPoint();
724
-			$source = $mountPoint . '/' . $sourceInternalPath;
724
+			$source = $mountPoint.'/'.$sourceInternalPath;
725 725
 			$target = $this->getFullPath($targetInternalPath);
726 726
 			$this->copyKeys($source, $target);
727 727
 		} else {
@@ -734,7 +734,7 @@  discard block
 block discarded – undo
734 734
 			if (is_resource($dh)) {
735 735
 				while ($result and ($file = readdir($dh)) !== false) {
736 736
 					if (!Filesystem::isIgnoredDir($file)) {
737
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
737
+						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath.'/'.$file, $targetInternalPath.'/'.$file, false, $isRename);
738 738
 					}
739 739
 				}
740 740
 			}
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
 				fclose($target);
751 751
 				throw $e;
752 752
 			}
753
-			if($result) {
753
+			if ($result) {
754 754
 				if ($preserveMtime) {
755 755
 					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
756 756
 				}
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
 				$this->getCache()->remove($targetInternalPath);
763 763
 			}
764 764
 		}
765
-		return (bool)$result;
765
+		return (bool) $result;
766 766
 
767 767
 	}
768 768
 
@@ -833,7 +833,7 @@  discard block
 block discarded – undo
833 833
 	 * @return string full path including mount point
834 834
 	 */
835 835
 	protected function getFullPath($path) {
836
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
836
+		return Filesystem::normalizePath($this->mountPoint.'/'.$path);
837 837
 	}
838 838
 
839 839
 	/**
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
 				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
890 890
 
891 891
 				// +1 to not start with an ':' which would result in empty element at the beginning
892
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
892
+				$exploded = explode(':', substr($header, strlen(Util::HEADER_START) + 1));
893 893
 
894 894
 				$element = array_shift($exploded);
895 895
 				while ($element !== Util::HEADER_END) {
@@ -950,7 +950,7 @@  discard block
 block discarded – undo
950 950
 			try {
951 951
 				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
952 952
 			} catch (ModuleDoesNotExistsException $e) {
953
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
953
+				$this->logger->critical('Encryption module defined in "'.$path.'" not loaded!');
954 954
 				throw $e;
955 955
 			}
956 956
 		}
Please login to merge, or discard this patch.
Indentation   +974 added lines, -974 removed lines patch added patch discarded remove patch
@@ -46,979 +46,979 @@
 block discarded – undo
46 46
 
47 47
 class Encryption extends Wrapper {
48 48
 
49
-	use LocalTempFileTrait;
50
-
51
-	/** @var string */
52
-	private $mountPoint;
53
-
54
-	/** @var \OC\Encryption\Util */
55
-	private $util;
56
-
57
-	/** @var \OCP\Encryption\IManager */
58
-	private $encryptionManager;
59
-
60
-	/** @var \OCP\ILogger */
61
-	private $logger;
62
-
63
-	/** @var string */
64
-	private $uid;
65
-
66
-	/** @var array */
67
-	protected $unencryptedSize;
68
-
69
-	/** @var \OCP\Encryption\IFile */
70
-	private $fileHelper;
71
-
72
-	/** @var IMountPoint */
73
-	private $mount;
74
-
75
-	/** @var IStorage */
76
-	private $keyStorage;
77
-
78
-	/** @var Update */
79
-	private $update;
80
-
81
-	/** @var Manager */
82
-	private $mountManager;
83
-
84
-	/** @var array remember for which path we execute the repair step to avoid recursions */
85
-	private $fixUnencryptedSizeOf = array();
86
-
87
-	/** @var  ArrayCache */
88
-	private $arrayCache;
89
-
90
-	/**
91
-	 * @param array $parameters
92
-	 * @param IManager $encryptionManager
93
-	 * @param Util $util
94
-	 * @param ILogger $logger
95
-	 * @param IFile $fileHelper
96
-	 * @param string $uid
97
-	 * @param IStorage $keyStorage
98
-	 * @param Update $update
99
-	 * @param Manager $mountManager
100
-	 * @param ArrayCache $arrayCache
101
-	 */
102
-	public function __construct(
103
-			$parameters,
104
-			IManager $encryptionManager = null,
105
-			Util $util = null,
106
-			ILogger $logger = null,
107
-			IFile $fileHelper = null,
108
-			$uid = null,
109
-			IStorage $keyStorage = null,
110
-			Update $update = null,
111
-			Manager $mountManager = null,
112
-			ArrayCache $arrayCache = null
113
-		) {
114
-
115
-		$this->mountPoint = $parameters['mountPoint'];
116
-		$this->mount = $parameters['mount'];
117
-		$this->encryptionManager = $encryptionManager;
118
-		$this->util = $util;
119
-		$this->logger = $logger;
120
-		$this->uid = $uid;
121
-		$this->fileHelper = $fileHelper;
122
-		$this->keyStorage = $keyStorage;
123
-		$this->unencryptedSize = array();
124
-		$this->update = $update;
125
-		$this->mountManager = $mountManager;
126
-		$this->arrayCache = $arrayCache;
127
-		parent::__construct($parameters);
128
-	}
129
-
130
-	/**
131
-	 * see http://php.net/manual/en/function.filesize.php
132
-	 * The result for filesize when called on a folder is required to be 0
133
-	 *
134
-	 * @param string $path
135
-	 * @return int
136
-	 */
137
-	public function filesize($path) {
138
-		$fullPath = $this->getFullPath($path);
139
-
140
-		/** @var CacheEntry $info */
141
-		$info = $this->getCache()->get($path);
142
-		if (isset($this->unencryptedSize[$fullPath])) {
143
-			$size = $this->unencryptedSize[$fullPath];
144
-			// update file cache
145
-			if ($info instanceof ICacheEntry) {
146
-				$info = $info->getData();
147
-				$info['encrypted'] = $info['encryptedVersion'];
148
-			} else {
149
-				if (!is_array($info)) {
150
-					$info = [];
151
-				}
152
-				$info['encrypted'] = true;
153
-			}
154
-
155
-			$info['size'] = $size;
156
-			$this->getCache()->put($path, $info);
157
-
158
-			return $size;
159
-		}
160
-
161
-		if (isset($info['fileid']) && $info['encrypted']) {
162
-			return $this->verifyUnencryptedSize($path, $info['size']);
163
-		}
164
-
165
-		return $this->storage->filesize($path);
166
-	}
167
-
168
-	/**
169
-	 * @param string $path
170
-	 * @return array
171
-	 */
172
-	public function getMetaData($path) {
173
-		$data = $this->storage->getMetaData($path);
174
-		if (is_null($data)) {
175
-			return null;
176
-		}
177
-		$fullPath = $this->getFullPath($path);
178
-		$info = $this->getCache()->get($path);
179
-
180
-		if (isset($this->unencryptedSize[$fullPath])) {
181
-			$data['encrypted'] = true;
182
-			$data['size'] = $this->unencryptedSize[$fullPath];
183
-		} else {
184
-			if (isset($info['fileid']) && $info['encrypted']) {
185
-				$data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
186
-				$data['encrypted'] = true;
187
-			}
188
-		}
189
-
190
-		if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
191
-			$data['encryptedVersion'] = $info['encryptedVersion'];
192
-		}
193
-
194
-		return $data;
195
-	}
196
-
197
-	/**
198
-	 * see http://php.net/manual/en/function.file_get_contents.php
199
-	 *
200
-	 * @param string $path
201
-	 * @return string
202
-	 */
203
-	public function file_get_contents($path) {
204
-
205
-		$encryptionModule = $this->getEncryptionModule($path);
206
-
207
-		if ($encryptionModule) {
208
-			$handle = $this->fopen($path, "r");
209
-			if (!$handle) {
210
-				return false;
211
-			}
212
-			$data = stream_get_contents($handle);
213
-			fclose($handle);
214
-			return $data;
215
-		}
216
-		return $this->storage->file_get_contents($path);
217
-	}
218
-
219
-	/**
220
-	 * see http://php.net/manual/en/function.file_put_contents.php
221
-	 *
222
-	 * @param string $path
223
-	 * @param string $data
224
-	 * @return bool
225
-	 */
226
-	public function file_put_contents($path, $data) {
227
-		// file put content will always be translated to a stream write
228
-		$handle = $this->fopen($path, 'w');
229
-		if (is_resource($handle)) {
230
-			$written = fwrite($handle, $data);
231
-			fclose($handle);
232
-			return $written;
233
-		}
234
-
235
-		return false;
236
-	}
237
-
238
-	/**
239
-	 * see http://php.net/manual/en/function.unlink.php
240
-	 *
241
-	 * @param string $path
242
-	 * @return bool
243
-	 */
244
-	public function unlink($path) {
245
-		$fullPath = $this->getFullPath($path);
246
-		if ($this->util->isExcluded($fullPath)) {
247
-			return $this->storage->unlink($path);
248
-		}
249
-
250
-		$encryptionModule = $this->getEncryptionModule($path);
251
-		if ($encryptionModule) {
252
-			$this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
253
-		}
254
-
255
-		return $this->storage->unlink($path);
256
-	}
257
-
258
-	/**
259
-	 * see http://php.net/manual/en/function.rename.php
260
-	 *
261
-	 * @param string $path1
262
-	 * @param string $path2
263
-	 * @return bool
264
-	 */
265
-	public function rename($path1, $path2) {
266
-
267
-		$result = $this->storage->rename($path1, $path2);
268
-
269
-		if ($result &&
270
-			// versions always use the keys from the original file, so we can skip
271
-			// this step for versions
272
-			$this->isVersion($path2) === false &&
273
-			$this->encryptionManager->isEnabled()) {
274
-			$source = $this->getFullPath($path1);
275
-			if (!$this->util->isExcluded($source)) {
276
-				$target = $this->getFullPath($path2);
277
-				if (isset($this->unencryptedSize[$source])) {
278
-					$this->unencryptedSize[$target] = $this->unencryptedSize[$source];
279
-				}
280
-				$this->keyStorage->renameKeys($source, $target);
281
-				$module = $this->getEncryptionModule($path2);
282
-				if ($module) {
283
-					$module->update($target, $this->uid, []);
284
-				}
285
-			}
286
-		}
287
-
288
-		return $result;
289
-	}
290
-
291
-	/**
292
-	 * see http://php.net/manual/en/function.rmdir.php
293
-	 *
294
-	 * @param string $path
295
-	 * @return bool
296
-	 */
297
-	public function rmdir($path) {
298
-		$result = $this->storage->rmdir($path);
299
-		$fullPath = $this->getFullPath($path);
300
-		if ($result &&
301
-			$this->util->isExcluded($fullPath) === false &&
302
-			$this->encryptionManager->isEnabled()
303
-		) {
304
-			$this->keyStorage->deleteAllFileKeys($fullPath);
305
-		}
306
-
307
-		return $result;
308
-	}
309
-
310
-	/**
311
-	 * check if a file can be read
312
-	 *
313
-	 * @param string $path
314
-	 * @return bool
315
-	 */
316
-	public function isReadable($path) {
317
-
318
-		$isReadable = true;
319
-
320
-		$metaData = $this->getMetaData($path);
321
-		if (
322
-			!$this->is_dir($path) &&
323
-			isset($metaData['encrypted']) &&
324
-			$metaData['encrypted'] === true
325
-		) {
326
-			$fullPath = $this->getFullPath($path);
327
-			$module = $this->getEncryptionModule($path);
328
-			$isReadable = $module->isReadable($fullPath, $this->uid);
329
-		}
330
-
331
-		return $this->storage->isReadable($path) && $isReadable;
332
-	}
333
-
334
-	/**
335
-	 * see http://php.net/manual/en/function.copy.php
336
-	 *
337
-	 * @param string $path1
338
-	 * @param string $path2
339
-	 * @return bool
340
-	 */
341
-	public function copy($path1, $path2) {
342
-
343
-		$source = $this->getFullPath($path1);
344
-
345
-		if ($this->util->isExcluded($source)) {
346
-			return $this->storage->copy($path1, $path2);
347
-		}
348
-
349
-		// need to stream copy file by file in case we copy between a encrypted
350
-		// and a unencrypted storage
351
-		$this->unlink($path2);
352
-		$result = $this->copyFromStorage($this, $path1, $path2);
353
-
354
-		return $result;
355
-	}
356
-
357
-	/**
358
-	 * see http://php.net/manual/en/function.fopen.php
359
-	 *
360
-	 * @param string $path
361
-	 * @param string $mode
362
-	 * @return resource|bool
363
-	 * @throws GenericEncryptionException
364
-	 * @throws ModuleDoesNotExistsException
365
-	 */
366
-	public function fopen($path, $mode) {
367
-
368
-		// check if the file is stored in the array cache, this means that we
369
-		// copy a file over to the versions folder, in this case we don't want to
370
-		// decrypt it
371
-		if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
372
-			$this->arrayCache->remove('encryption_copy_version_' . $path);
373
-			return $this->storage->fopen($path, $mode);
374
-		}
375
-
376
-		$encryptionEnabled = $this->encryptionManager->isEnabled();
377
-		$shouldEncrypt = false;
378
-		$encryptionModule = null;
379
-		$header = $this->getHeader($path);
380
-		$signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
381
-		$fullPath = $this->getFullPath($path);
382
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
383
-
384
-		if ($this->util->isExcluded($fullPath) === false) {
385
-
386
-			$size = $unencryptedSize = 0;
387
-			$realFile = $this->util->stripPartialFileExtension($path);
388
-			$targetExists = $this->file_exists($realFile) || $this->file_exists($path);
389
-			$targetIsEncrypted = false;
390
-			if ($targetExists) {
391
-				// in case the file exists we require the explicit module as
392
-				// specified in the file header - otherwise we need to fail hard to
393
-				// prevent data loss on client side
394
-				if (!empty($encryptionModuleId)) {
395
-					$targetIsEncrypted = true;
396
-					$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
397
-				}
398
-
399
-				if ($this->file_exists($path)) {
400
-					$size = $this->storage->filesize($path);
401
-					$unencryptedSize = $this->filesize($path);
402
-				} else {
403
-					$size = $unencryptedSize = 0;
404
-				}
405
-			}
406
-
407
-			try {
408
-
409
-				if (
410
-					$mode === 'w'
411
-					|| $mode === 'w+'
412
-					|| $mode === 'wb'
413
-					|| $mode === 'wb+'
414
-				) {
415
-					// don't overwrite encrypted files if encryption is not enabled
416
-					if ($targetIsEncrypted && $encryptionEnabled === false) {
417
-						throw new GenericEncryptionException('Tried to access encrypted file but encryption is not enabled');
418
-					}
419
-					if ($encryptionEnabled) {
420
-						// if $encryptionModuleId is empty, the default module will be used
421
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
422
-						$shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
423
-						$signed = true;
424
-					}
425
-				} else {
426
-					$info = $this->getCache()->get($path);
427
-					// only get encryption module if we found one in the header
428
-					// or if file should be encrypted according to the file cache
429
-					if (!empty($encryptionModuleId)) {
430
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
431
-						$shouldEncrypt = true;
432
-					} else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
433
-						// we come from a old installation. No header and/or no module defined
434
-						// but the file is encrypted. In this case we need to use the
435
-						// OC_DEFAULT_MODULE to read the file
436
-						$encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
437
-						$shouldEncrypt = true;
438
-						$targetIsEncrypted = true;
439
-					}
440
-				}
441
-			} catch (ModuleDoesNotExistsException $e) {
442
-				$this->logger->warning('Encryption module "' . $encryptionModuleId .
443
-					'" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
444
-			}
445
-
446
-			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
447
-			if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
448
-				if (!$targetExists || !$targetIsEncrypted) {
449
-					$shouldEncrypt = false;
450
-				}
451
-			}
452
-
453
-			if ($shouldEncrypt === true && $encryptionModule !== null) {
454
-				$headerSize = $this->getHeaderSize($path);
455
-				$source = $this->storage->fopen($path, $mode);
456
-				if (!is_resource($source)) {
457
-					return false;
458
-				}
459
-				$handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
460
-					$this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
461
-					$size, $unencryptedSize, $headerSize, $signed);
462
-				return $handle;
463
-			}
464
-
465
-		}
466
-
467
-		return $this->storage->fopen($path, $mode);
468
-	}
469
-
470
-
471
-	/**
472
-	 * perform some plausibility checks if the the unencrypted size is correct.
473
-	 * If not, we calculate the correct unencrypted size and return it
474
-	 *
475
-	 * @param string $path internal path relative to the storage root
476
-	 * @param int $unencryptedSize size of the unencrypted file
477
-	 *
478
-	 * @return int unencrypted size
479
-	 */
480
-	protected function verifyUnencryptedSize($path, $unencryptedSize) {
481
-
482
-		$size = $this->storage->filesize($path);
483
-		$result = $unencryptedSize;
484
-
485
-		if ($unencryptedSize < 0 ||
486
-			($size > 0 && $unencryptedSize === $size)
487
-		) {
488
-			// check if we already calculate the unencrypted size for the
489
-			// given path to avoid recursions
490
-			if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
491
-				$this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
492
-				try {
493
-					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
494
-				} catch (\Exception $e) {
495
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
496
-					$this->logger->logException($e);
497
-				}
498
-				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
499
-			}
500
-		}
501
-
502
-		return $result;
503
-	}
504
-
505
-	/**
506
-	 * calculate the unencrypted size
507
-	 *
508
-	 * @param string $path internal path relative to the storage root
509
-	 * @param int $size size of the physical file
510
-	 * @param int $unencryptedSize size of the unencrypted file
511
-	 *
512
-	 * @return int calculated unencrypted size
513
-	 */
514
-	protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
515
-
516
-		$headerSize = $this->getHeaderSize($path);
517
-		$header = $this->getHeader($path);
518
-		$encryptionModule = $this->getEncryptionModule($path);
519
-
520
-		$stream = $this->storage->fopen($path, 'r');
521
-
522
-		// if we couldn't open the file we return the old unencrypted size
523
-		if (!is_resource($stream)) {
524
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
525
-			return $unencryptedSize;
526
-		}
527
-
528
-		$newUnencryptedSize = 0;
529
-		$size -= $headerSize;
530
-		$blockSize = $this->util->getBlockSize();
531
-
532
-		// if a header exists we skip it
533
-		if ($headerSize > 0) {
534
-			fread($stream, $headerSize);
535
-		}
536
-
537
-		// fast path, else the calculation for $lastChunkNr is bogus
538
-		if ($size === 0) {
539
-			return 0;
540
-		}
541
-
542
-		$signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
543
-		$unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
544
-
545
-		// calculate last chunk nr
546
-		// next highest is end of chunks, one subtracted is last one
547
-		// we have to read the last chunk, we can't just calculate it (because of padding etc)
548
-
549
-		$lastChunkNr = ceil($size/ $blockSize)-1;
550
-		// calculate last chunk position
551
-		$lastChunkPos = ($lastChunkNr * $blockSize);
552
-		// try to fseek to the last chunk, if it fails we have to read the whole file
553
-		if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
554
-			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
555
-		}
556
-
557
-		$lastChunkContentEncrypted='';
558
-		$count = $blockSize;
559
-
560
-		while ($count > 0) {
561
-			$data=fread($stream, $blockSize);
562
-			$count=strlen($data);
563
-			$lastChunkContentEncrypted .= $data;
564
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
565
-				$newUnencryptedSize += $unencryptedBlockSize;
566
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
567
-			}
568
-		}
569
-
570
-		fclose($stream);
571
-
572
-		// we have to decrypt the last chunk to get it actual size
573
-		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
574
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
575
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
576
-
577
-		// calc the real file size with the size of the last chunk
578
-		$newUnencryptedSize += strlen($decryptedLastChunk);
579
-
580
-		$this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
581
-
582
-		// write to cache if applicable
583
-		$cache = $this->storage->getCache();
584
-		if ($cache) {
585
-			$entry = $cache->get($path);
586
-			$cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
587
-		}
588
-
589
-		return $newUnencryptedSize;
590
-	}
591
-
592
-	/**
593
-	 * @param Storage $sourceStorage
594
-	 * @param string $sourceInternalPath
595
-	 * @param string $targetInternalPath
596
-	 * @param bool $preserveMtime
597
-	 * @return bool
598
-	 */
599
-	public function moveFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
600
-		if ($sourceStorage === $this) {
601
-			return $this->rename($sourceInternalPath, $targetInternalPath);
602
-		}
603
-
604
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
605
-		// - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
606
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
607
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
608
-		// - remove $this->copyBetweenStorage
609
-
610
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
611
-			return false;
612
-		}
613
-
614
-		$result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
615
-		if ($result) {
616
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
617
-				$result &= $sourceStorage->rmdir($sourceInternalPath);
618
-			} else {
619
-				$result &= $sourceStorage->unlink($sourceInternalPath);
620
-			}
621
-		}
622
-		return $result;
623
-	}
624
-
625
-
626
-	/**
627
-	 * @param Storage $sourceStorage
628
-	 * @param string $sourceInternalPath
629
-	 * @param string $targetInternalPath
630
-	 * @param bool $preserveMtime
631
-	 * @param bool $isRename
632
-	 * @return bool
633
-	 */
634
-	public function copyFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
635
-
636
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
637
-		// - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
638
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
639
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
640
-		// - remove $this->copyBetweenStorage
641
-
642
-		return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
643
-	}
644
-
645
-	/**
646
-	 * Update the encrypted cache version in the database
647
-	 *
648
-	 * @param Storage $sourceStorage
649
-	 * @param string $sourceInternalPath
650
-	 * @param string $targetInternalPath
651
-	 * @param bool $isRename
652
-	 */
653
-	private function updateEncryptedVersion(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
654
-		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath) ? 1 : 0;
655
-		$cacheInformation = [
656
-			'encrypted' => (bool)$isEncrypted,
657
-		];
658
-		if($isEncrypted === 1) {
659
-			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
660
-
661
-			// In case of a move operation from an unencrypted to an encrypted
662
-			// storage the old encrypted version would stay with "0" while the
663
-			// correct value would be "1". Thus we manually set the value to "1"
664
-			// for those cases.
665
-			// See also https://github.com/owncloud/core/issues/23078
666
-			if($encryptedVersion === 0) {
667
-				$encryptedVersion = 1;
668
-			}
669
-
670
-			$cacheInformation['encryptedVersion'] = $encryptedVersion;
671
-		}
672
-
673
-		// in case of a rename we need to manipulate the source cache because
674
-		// this information will be kept for the new target
675
-		if ($isRename) {
676
-			$sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
677
-		} else {
678
-			$this->getCache()->put($targetInternalPath, $cacheInformation);
679
-		}
680
-	}
681
-
682
-	/**
683
-	 * copy file between two storages
684
-	 *
685
-	 * @param Storage $sourceStorage
686
-	 * @param string $sourceInternalPath
687
-	 * @param string $targetInternalPath
688
-	 * @param bool $preserveMtime
689
-	 * @param bool $isRename
690
-	 * @return bool
691
-	 * @throws \Exception
692
-	 */
693
-	private function copyBetweenStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
694
-
695
-		// for versions we have nothing to do, because versions should always use the
696
-		// key from the original file. Just create a 1:1 copy and done
697
-		if ($this->isVersion($targetInternalPath) ||
698
-			$this->isVersion($sourceInternalPath)) {
699
-			// remember that we try to create a version so that we can detect it during
700
-			// fopen($sourceInternalPath) and by-pass the encryption in order to
701
-			// create a 1:1 copy of the file
702
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
703
-			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
704
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
705
-			if ($result) {
706
-				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
707
-				// make sure that we update the unencrypted size for the version
708
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
709
-					$this->updateUnencryptedSize(
710
-						$this->getFullPath($targetInternalPath),
711
-						$info['size']
712
-					);
713
-				}
714
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
715
-			}
716
-			return $result;
717
-		}
718
-
719
-		// first copy the keys that we reuse the existing file key on the target location
720
-		// and don't create a new one which would break versions for example.
721
-		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
722
-		if (count($mount) === 1) {
723
-			$mountPoint = $mount[0]->getMountPoint();
724
-			$source = $mountPoint . '/' . $sourceInternalPath;
725
-			$target = $this->getFullPath($targetInternalPath);
726
-			$this->copyKeys($source, $target);
727
-		} else {
728
-			$this->logger->error('Could not find mount point, can\'t keep encryption keys');
729
-		}
730
-
731
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
732
-			$dh = $sourceStorage->opendir($sourceInternalPath);
733
-			$result = $this->mkdir($targetInternalPath);
734
-			if (is_resource($dh)) {
735
-				while ($result and ($file = readdir($dh)) !== false) {
736
-					if (!Filesystem::isIgnoredDir($file)) {
737
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
738
-					}
739
-				}
740
-			}
741
-		} else {
742
-			try {
743
-				$source = $sourceStorage->fopen($sourceInternalPath, 'r');
744
-				$target = $this->fopen($targetInternalPath, 'w');
745
-				list(, $result) = \OC_Helper::streamCopy($source, $target);
746
-				fclose($source);
747
-				fclose($target);
748
-			} catch (\Exception $e) {
749
-				fclose($source);
750
-				fclose($target);
751
-				throw $e;
752
-			}
753
-			if($result) {
754
-				if ($preserveMtime) {
755
-					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
756
-				}
757
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
758
-			} else {
759
-				// delete partially written target file
760
-				$this->unlink($targetInternalPath);
761
-				// delete cache entry that was created by fopen
762
-				$this->getCache()->remove($targetInternalPath);
763
-			}
764
-		}
765
-		return (bool)$result;
766
-
767
-	}
768
-
769
-	/**
770
-	 * get the path to a local version of the file.
771
-	 * The local version of the file can be temporary and doesn't have to be persistent across requests
772
-	 *
773
-	 * @param string $path
774
-	 * @return string
775
-	 */
776
-	public function getLocalFile($path) {
777
-		if ($this->encryptionManager->isEnabled()) {
778
-			$cachedFile = $this->getCachedFile($path);
779
-			if (is_string($cachedFile)) {
780
-				return $cachedFile;
781
-			}
782
-		}
783
-		return $this->storage->getLocalFile($path);
784
-	}
785
-
786
-	/**
787
-	 * Returns the wrapped storage's value for isLocal()
788
-	 *
789
-	 * @return bool wrapped storage's isLocal() value
790
-	 */
791
-	public function isLocal() {
792
-		if ($this->encryptionManager->isEnabled()) {
793
-			return false;
794
-		}
795
-		return $this->storage->isLocal();
796
-	}
797
-
798
-	/**
799
-	 * see http://php.net/manual/en/function.stat.php
800
-	 * only the following keys are required in the result: size and mtime
801
-	 *
802
-	 * @param string $path
803
-	 * @return array
804
-	 */
805
-	public function stat($path) {
806
-		$stat = $this->storage->stat($path);
807
-		$fileSize = $this->filesize($path);
808
-		$stat['size'] = $fileSize;
809
-		$stat[7] = $fileSize;
810
-		return $stat;
811
-	}
812
-
813
-	/**
814
-	 * see http://php.net/manual/en/function.hash.php
815
-	 *
816
-	 * @param string $type
817
-	 * @param string $path
818
-	 * @param bool $raw
819
-	 * @return string
820
-	 */
821
-	public function hash($type, $path, $raw = false) {
822
-		$fh = $this->fopen($path, 'rb');
823
-		$ctx = hash_init($type);
824
-		hash_update_stream($ctx, $fh);
825
-		fclose($fh);
826
-		return hash_final($ctx, $raw);
827
-	}
828
-
829
-	/**
830
-	 * return full path, including mount point
831
-	 *
832
-	 * @param string $path relative to mount point
833
-	 * @return string full path including mount point
834
-	 */
835
-	protected function getFullPath($path) {
836
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
837
-	}
838
-
839
-	/**
840
-	 * read first block of encrypted file, typically this will contain the
841
-	 * encryption header
842
-	 *
843
-	 * @param string $path
844
-	 * @return string
845
-	 */
846
-	protected function readFirstBlock($path) {
847
-		$firstBlock = '';
848
-		if ($this->storage->file_exists($path)) {
849
-			$handle = $this->storage->fopen($path, 'r');
850
-			$firstBlock = fread($handle, $this->util->getHeaderSize());
851
-			fclose($handle);
852
-		}
853
-		return $firstBlock;
854
-	}
855
-
856
-	/**
857
-	 * return header size of given file
858
-	 *
859
-	 * @param string $path
860
-	 * @return int
861
-	 */
862
-	protected function getHeaderSize($path) {
863
-		$headerSize = 0;
864
-		$realFile = $this->util->stripPartialFileExtension($path);
865
-		if ($this->storage->file_exists($realFile)) {
866
-			$path = $realFile;
867
-		}
868
-		$firstBlock = $this->readFirstBlock($path);
869
-
870
-		if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
871
-			$headerSize = $this->util->getHeaderSize();
872
-		}
873
-
874
-		return $headerSize;
875
-	}
876
-
877
-	/**
878
-	 * parse raw header to array
879
-	 *
880
-	 * @param string $rawHeader
881
-	 * @return array
882
-	 */
883
-	protected function parseRawHeader($rawHeader) {
884
-		$result = array();
885
-		if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
886
-			$header = $rawHeader;
887
-			$endAt = strpos($header, Util::HEADER_END);
888
-			if ($endAt !== false) {
889
-				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
890
-
891
-				// +1 to not start with an ':' which would result in empty element at the beginning
892
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
893
-
894
-				$element = array_shift($exploded);
895
-				while ($element !== Util::HEADER_END) {
896
-					$result[$element] = array_shift($exploded);
897
-					$element = array_shift($exploded);
898
-				}
899
-			}
900
-		}
901
-
902
-		return $result;
903
-	}
904
-
905
-	/**
906
-	 * read header from file
907
-	 *
908
-	 * @param string $path
909
-	 * @return array
910
-	 */
911
-	protected function getHeader($path) {
912
-		$realFile = $this->util->stripPartialFileExtension($path);
913
-		$exists = $this->storage->file_exists($realFile);
914
-		if ($exists) {
915
-			$path = $realFile;
916
-		}
917
-
918
-		$firstBlock = $this->readFirstBlock($path);
919
-		$result = $this->parseRawHeader($firstBlock);
920
-
921
-		// if the header doesn't contain a encryption module we check if it is a
922
-		// legacy file. If true, we add the default encryption module
923
-		if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
924
-			if (!empty($result)) {
925
-				$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
926
-			} else if ($exists) {
927
-				// if the header was empty we have to check first if it is a encrypted file at all
928
-				// We would do query to filecache only if we know that entry in filecache exists
929
-				$info = $this->getCache()->get($path);
930
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
931
-					$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
932
-				}
933
-			}
934
-		}
935
-
936
-		return $result;
937
-	}
938
-
939
-	/**
940
-	 * read encryption module needed to read/write the file located at $path
941
-	 *
942
-	 * @param string $path
943
-	 * @return null|\OCP\Encryption\IEncryptionModule
944
-	 * @throws ModuleDoesNotExistsException
945
-	 * @throws \Exception
946
-	 */
947
-	protected function getEncryptionModule($path) {
948
-		$encryptionModule = null;
949
-		$header = $this->getHeader($path);
950
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
951
-		if (!empty($encryptionModuleId)) {
952
-			try {
953
-				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
954
-			} catch (ModuleDoesNotExistsException $e) {
955
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
956
-				throw $e;
957
-			}
958
-		}
959
-
960
-		return $encryptionModule;
961
-	}
962
-
963
-	/**
964
-	 * @param string $path
965
-	 * @param int $unencryptedSize
966
-	 */
967
-	public function updateUnencryptedSize($path, $unencryptedSize) {
968
-		$this->unencryptedSize[$path] = $unencryptedSize;
969
-	}
970
-
971
-	/**
972
-	 * copy keys to new location
973
-	 *
974
-	 * @param string $source path relative to data/
975
-	 * @param string $target path relative to data/
976
-	 * @return bool
977
-	 */
978
-	protected function copyKeys($source, $target) {
979
-		if (!$this->util->isExcluded($source)) {
980
-			return $this->keyStorage->copyKeys($source, $target);
981
-		}
982
-
983
-		return false;
984
-	}
985
-
986
-	/**
987
-	 * check if path points to a files version
988
-	 *
989
-	 * @param $path
990
-	 * @return bool
991
-	 */
992
-	protected function isVersion($path) {
993
-		$normalized = Filesystem::normalizePath($path);
994
-		return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
995
-	}
996
-
997
-	/**
998
-	 * check if the given storage should be encrypted or not
999
-	 *
1000
-	 * @param $path
1001
-	 * @return bool
1002
-	 */
1003
-	protected function shouldEncrypt($path) {
1004
-		$fullPath = $this->getFullPath($path);
1005
-		$mountPointConfig = $this->mount->getOption('encrypt', true);
1006
-		if ($mountPointConfig === false) {
1007
-			return false;
1008
-		}
1009
-
1010
-		try {
1011
-			$encryptionModule = $this->getEncryptionModule($fullPath);
1012
-		} catch (ModuleDoesNotExistsException $e) {
1013
-			return false;
1014
-		}
1015
-
1016
-		if ($encryptionModule === null) {
1017
-			$encryptionModule = $this->encryptionManager->getEncryptionModule();
1018
-		}
1019
-
1020
-		return $encryptionModule->shouldEncrypt($fullPath);
1021
-
1022
-	}
49
+    use LocalTempFileTrait;
50
+
51
+    /** @var string */
52
+    private $mountPoint;
53
+
54
+    /** @var \OC\Encryption\Util */
55
+    private $util;
56
+
57
+    /** @var \OCP\Encryption\IManager */
58
+    private $encryptionManager;
59
+
60
+    /** @var \OCP\ILogger */
61
+    private $logger;
62
+
63
+    /** @var string */
64
+    private $uid;
65
+
66
+    /** @var array */
67
+    protected $unencryptedSize;
68
+
69
+    /** @var \OCP\Encryption\IFile */
70
+    private $fileHelper;
71
+
72
+    /** @var IMountPoint */
73
+    private $mount;
74
+
75
+    /** @var IStorage */
76
+    private $keyStorage;
77
+
78
+    /** @var Update */
79
+    private $update;
80
+
81
+    /** @var Manager */
82
+    private $mountManager;
83
+
84
+    /** @var array remember for which path we execute the repair step to avoid recursions */
85
+    private $fixUnencryptedSizeOf = array();
86
+
87
+    /** @var  ArrayCache */
88
+    private $arrayCache;
89
+
90
+    /**
91
+     * @param array $parameters
92
+     * @param IManager $encryptionManager
93
+     * @param Util $util
94
+     * @param ILogger $logger
95
+     * @param IFile $fileHelper
96
+     * @param string $uid
97
+     * @param IStorage $keyStorage
98
+     * @param Update $update
99
+     * @param Manager $mountManager
100
+     * @param ArrayCache $arrayCache
101
+     */
102
+    public function __construct(
103
+            $parameters,
104
+            IManager $encryptionManager = null,
105
+            Util $util = null,
106
+            ILogger $logger = null,
107
+            IFile $fileHelper = null,
108
+            $uid = null,
109
+            IStorage $keyStorage = null,
110
+            Update $update = null,
111
+            Manager $mountManager = null,
112
+            ArrayCache $arrayCache = null
113
+        ) {
114
+
115
+        $this->mountPoint = $parameters['mountPoint'];
116
+        $this->mount = $parameters['mount'];
117
+        $this->encryptionManager = $encryptionManager;
118
+        $this->util = $util;
119
+        $this->logger = $logger;
120
+        $this->uid = $uid;
121
+        $this->fileHelper = $fileHelper;
122
+        $this->keyStorage = $keyStorage;
123
+        $this->unencryptedSize = array();
124
+        $this->update = $update;
125
+        $this->mountManager = $mountManager;
126
+        $this->arrayCache = $arrayCache;
127
+        parent::__construct($parameters);
128
+    }
129
+
130
+    /**
131
+     * see http://php.net/manual/en/function.filesize.php
132
+     * The result for filesize when called on a folder is required to be 0
133
+     *
134
+     * @param string $path
135
+     * @return int
136
+     */
137
+    public function filesize($path) {
138
+        $fullPath = $this->getFullPath($path);
139
+
140
+        /** @var CacheEntry $info */
141
+        $info = $this->getCache()->get($path);
142
+        if (isset($this->unencryptedSize[$fullPath])) {
143
+            $size = $this->unencryptedSize[$fullPath];
144
+            // update file cache
145
+            if ($info instanceof ICacheEntry) {
146
+                $info = $info->getData();
147
+                $info['encrypted'] = $info['encryptedVersion'];
148
+            } else {
149
+                if (!is_array($info)) {
150
+                    $info = [];
151
+                }
152
+                $info['encrypted'] = true;
153
+            }
154
+
155
+            $info['size'] = $size;
156
+            $this->getCache()->put($path, $info);
157
+
158
+            return $size;
159
+        }
160
+
161
+        if (isset($info['fileid']) && $info['encrypted']) {
162
+            return $this->verifyUnencryptedSize($path, $info['size']);
163
+        }
164
+
165
+        return $this->storage->filesize($path);
166
+    }
167
+
168
+    /**
169
+     * @param string $path
170
+     * @return array
171
+     */
172
+    public function getMetaData($path) {
173
+        $data = $this->storage->getMetaData($path);
174
+        if (is_null($data)) {
175
+            return null;
176
+        }
177
+        $fullPath = $this->getFullPath($path);
178
+        $info = $this->getCache()->get($path);
179
+
180
+        if (isset($this->unencryptedSize[$fullPath])) {
181
+            $data['encrypted'] = true;
182
+            $data['size'] = $this->unencryptedSize[$fullPath];
183
+        } else {
184
+            if (isset($info['fileid']) && $info['encrypted']) {
185
+                $data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
186
+                $data['encrypted'] = true;
187
+            }
188
+        }
189
+
190
+        if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
191
+            $data['encryptedVersion'] = $info['encryptedVersion'];
192
+        }
193
+
194
+        return $data;
195
+    }
196
+
197
+    /**
198
+     * see http://php.net/manual/en/function.file_get_contents.php
199
+     *
200
+     * @param string $path
201
+     * @return string
202
+     */
203
+    public function file_get_contents($path) {
204
+
205
+        $encryptionModule = $this->getEncryptionModule($path);
206
+
207
+        if ($encryptionModule) {
208
+            $handle = $this->fopen($path, "r");
209
+            if (!$handle) {
210
+                return false;
211
+            }
212
+            $data = stream_get_contents($handle);
213
+            fclose($handle);
214
+            return $data;
215
+        }
216
+        return $this->storage->file_get_contents($path);
217
+    }
218
+
219
+    /**
220
+     * see http://php.net/manual/en/function.file_put_contents.php
221
+     *
222
+     * @param string $path
223
+     * @param string $data
224
+     * @return bool
225
+     */
226
+    public function file_put_contents($path, $data) {
227
+        // file put content will always be translated to a stream write
228
+        $handle = $this->fopen($path, 'w');
229
+        if (is_resource($handle)) {
230
+            $written = fwrite($handle, $data);
231
+            fclose($handle);
232
+            return $written;
233
+        }
234
+
235
+        return false;
236
+    }
237
+
238
+    /**
239
+     * see http://php.net/manual/en/function.unlink.php
240
+     *
241
+     * @param string $path
242
+     * @return bool
243
+     */
244
+    public function unlink($path) {
245
+        $fullPath = $this->getFullPath($path);
246
+        if ($this->util->isExcluded($fullPath)) {
247
+            return $this->storage->unlink($path);
248
+        }
249
+
250
+        $encryptionModule = $this->getEncryptionModule($path);
251
+        if ($encryptionModule) {
252
+            $this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
253
+        }
254
+
255
+        return $this->storage->unlink($path);
256
+    }
257
+
258
+    /**
259
+     * see http://php.net/manual/en/function.rename.php
260
+     *
261
+     * @param string $path1
262
+     * @param string $path2
263
+     * @return bool
264
+     */
265
+    public function rename($path1, $path2) {
266
+
267
+        $result = $this->storage->rename($path1, $path2);
268
+
269
+        if ($result &&
270
+            // versions always use the keys from the original file, so we can skip
271
+            // this step for versions
272
+            $this->isVersion($path2) === false &&
273
+            $this->encryptionManager->isEnabled()) {
274
+            $source = $this->getFullPath($path1);
275
+            if (!$this->util->isExcluded($source)) {
276
+                $target = $this->getFullPath($path2);
277
+                if (isset($this->unencryptedSize[$source])) {
278
+                    $this->unencryptedSize[$target] = $this->unencryptedSize[$source];
279
+                }
280
+                $this->keyStorage->renameKeys($source, $target);
281
+                $module = $this->getEncryptionModule($path2);
282
+                if ($module) {
283
+                    $module->update($target, $this->uid, []);
284
+                }
285
+            }
286
+        }
287
+
288
+        return $result;
289
+    }
290
+
291
+    /**
292
+     * see http://php.net/manual/en/function.rmdir.php
293
+     *
294
+     * @param string $path
295
+     * @return bool
296
+     */
297
+    public function rmdir($path) {
298
+        $result = $this->storage->rmdir($path);
299
+        $fullPath = $this->getFullPath($path);
300
+        if ($result &&
301
+            $this->util->isExcluded($fullPath) === false &&
302
+            $this->encryptionManager->isEnabled()
303
+        ) {
304
+            $this->keyStorage->deleteAllFileKeys($fullPath);
305
+        }
306
+
307
+        return $result;
308
+    }
309
+
310
+    /**
311
+     * check if a file can be read
312
+     *
313
+     * @param string $path
314
+     * @return bool
315
+     */
316
+    public function isReadable($path) {
317
+
318
+        $isReadable = true;
319
+
320
+        $metaData = $this->getMetaData($path);
321
+        if (
322
+            !$this->is_dir($path) &&
323
+            isset($metaData['encrypted']) &&
324
+            $metaData['encrypted'] === true
325
+        ) {
326
+            $fullPath = $this->getFullPath($path);
327
+            $module = $this->getEncryptionModule($path);
328
+            $isReadable = $module->isReadable($fullPath, $this->uid);
329
+        }
330
+
331
+        return $this->storage->isReadable($path) && $isReadable;
332
+    }
333
+
334
+    /**
335
+     * see http://php.net/manual/en/function.copy.php
336
+     *
337
+     * @param string $path1
338
+     * @param string $path2
339
+     * @return bool
340
+     */
341
+    public function copy($path1, $path2) {
342
+
343
+        $source = $this->getFullPath($path1);
344
+
345
+        if ($this->util->isExcluded($source)) {
346
+            return $this->storage->copy($path1, $path2);
347
+        }
348
+
349
+        // need to stream copy file by file in case we copy between a encrypted
350
+        // and a unencrypted storage
351
+        $this->unlink($path2);
352
+        $result = $this->copyFromStorage($this, $path1, $path2);
353
+
354
+        return $result;
355
+    }
356
+
357
+    /**
358
+     * see http://php.net/manual/en/function.fopen.php
359
+     *
360
+     * @param string $path
361
+     * @param string $mode
362
+     * @return resource|bool
363
+     * @throws GenericEncryptionException
364
+     * @throws ModuleDoesNotExistsException
365
+     */
366
+    public function fopen($path, $mode) {
367
+
368
+        // check if the file is stored in the array cache, this means that we
369
+        // copy a file over to the versions folder, in this case we don't want to
370
+        // decrypt it
371
+        if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
372
+            $this->arrayCache->remove('encryption_copy_version_' . $path);
373
+            return $this->storage->fopen($path, $mode);
374
+        }
375
+
376
+        $encryptionEnabled = $this->encryptionManager->isEnabled();
377
+        $shouldEncrypt = false;
378
+        $encryptionModule = null;
379
+        $header = $this->getHeader($path);
380
+        $signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
381
+        $fullPath = $this->getFullPath($path);
382
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
383
+
384
+        if ($this->util->isExcluded($fullPath) === false) {
385
+
386
+            $size = $unencryptedSize = 0;
387
+            $realFile = $this->util->stripPartialFileExtension($path);
388
+            $targetExists = $this->file_exists($realFile) || $this->file_exists($path);
389
+            $targetIsEncrypted = false;
390
+            if ($targetExists) {
391
+                // in case the file exists we require the explicit module as
392
+                // specified in the file header - otherwise we need to fail hard to
393
+                // prevent data loss on client side
394
+                if (!empty($encryptionModuleId)) {
395
+                    $targetIsEncrypted = true;
396
+                    $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
397
+                }
398
+
399
+                if ($this->file_exists($path)) {
400
+                    $size = $this->storage->filesize($path);
401
+                    $unencryptedSize = $this->filesize($path);
402
+                } else {
403
+                    $size = $unencryptedSize = 0;
404
+                }
405
+            }
406
+
407
+            try {
408
+
409
+                if (
410
+                    $mode === 'w'
411
+                    || $mode === 'w+'
412
+                    || $mode === 'wb'
413
+                    || $mode === 'wb+'
414
+                ) {
415
+                    // don't overwrite encrypted files if encryption is not enabled
416
+                    if ($targetIsEncrypted && $encryptionEnabled === false) {
417
+                        throw new GenericEncryptionException('Tried to access encrypted file but encryption is not enabled');
418
+                    }
419
+                    if ($encryptionEnabled) {
420
+                        // if $encryptionModuleId is empty, the default module will be used
421
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
422
+                        $shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
423
+                        $signed = true;
424
+                    }
425
+                } else {
426
+                    $info = $this->getCache()->get($path);
427
+                    // only get encryption module if we found one in the header
428
+                    // or if file should be encrypted according to the file cache
429
+                    if (!empty($encryptionModuleId)) {
430
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
431
+                        $shouldEncrypt = true;
432
+                    } else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
433
+                        // we come from a old installation. No header and/or no module defined
434
+                        // but the file is encrypted. In this case we need to use the
435
+                        // OC_DEFAULT_MODULE to read the file
436
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
437
+                        $shouldEncrypt = true;
438
+                        $targetIsEncrypted = true;
439
+                    }
440
+                }
441
+            } catch (ModuleDoesNotExistsException $e) {
442
+                $this->logger->warning('Encryption module "' . $encryptionModuleId .
443
+                    '" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
444
+            }
445
+
446
+            // encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
447
+            if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
448
+                if (!$targetExists || !$targetIsEncrypted) {
449
+                    $shouldEncrypt = false;
450
+                }
451
+            }
452
+
453
+            if ($shouldEncrypt === true && $encryptionModule !== null) {
454
+                $headerSize = $this->getHeaderSize($path);
455
+                $source = $this->storage->fopen($path, $mode);
456
+                if (!is_resource($source)) {
457
+                    return false;
458
+                }
459
+                $handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
460
+                    $this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
461
+                    $size, $unencryptedSize, $headerSize, $signed);
462
+                return $handle;
463
+            }
464
+
465
+        }
466
+
467
+        return $this->storage->fopen($path, $mode);
468
+    }
469
+
470
+
471
+    /**
472
+     * perform some plausibility checks if the the unencrypted size is correct.
473
+     * If not, we calculate the correct unencrypted size and return it
474
+     *
475
+     * @param string $path internal path relative to the storage root
476
+     * @param int $unencryptedSize size of the unencrypted file
477
+     *
478
+     * @return int unencrypted size
479
+     */
480
+    protected function verifyUnencryptedSize($path, $unencryptedSize) {
481
+
482
+        $size = $this->storage->filesize($path);
483
+        $result = $unencryptedSize;
484
+
485
+        if ($unencryptedSize < 0 ||
486
+            ($size > 0 && $unencryptedSize === $size)
487
+        ) {
488
+            // check if we already calculate the unencrypted size for the
489
+            // given path to avoid recursions
490
+            if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
491
+                $this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
492
+                try {
493
+                    $result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
494
+                } catch (\Exception $e) {
495
+                    $this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
496
+                    $this->logger->logException($e);
497
+                }
498
+                unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
499
+            }
500
+        }
501
+
502
+        return $result;
503
+    }
504
+
505
+    /**
506
+     * calculate the unencrypted size
507
+     *
508
+     * @param string $path internal path relative to the storage root
509
+     * @param int $size size of the physical file
510
+     * @param int $unencryptedSize size of the unencrypted file
511
+     *
512
+     * @return int calculated unencrypted size
513
+     */
514
+    protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
515
+
516
+        $headerSize = $this->getHeaderSize($path);
517
+        $header = $this->getHeader($path);
518
+        $encryptionModule = $this->getEncryptionModule($path);
519
+
520
+        $stream = $this->storage->fopen($path, 'r');
521
+
522
+        // if we couldn't open the file we return the old unencrypted size
523
+        if (!is_resource($stream)) {
524
+            $this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
525
+            return $unencryptedSize;
526
+        }
527
+
528
+        $newUnencryptedSize = 0;
529
+        $size -= $headerSize;
530
+        $blockSize = $this->util->getBlockSize();
531
+
532
+        // if a header exists we skip it
533
+        if ($headerSize > 0) {
534
+            fread($stream, $headerSize);
535
+        }
536
+
537
+        // fast path, else the calculation for $lastChunkNr is bogus
538
+        if ($size === 0) {
539
+            return 0;
540
+        }
541
+
542
+        $signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
543
+        $unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
544
+
545
+        // calculate last chunk nr
546
+        // next highest is end of chunks, one subtracted is last one
547
+        // we have to read the last chunk, we can't just calculate it (because of padding etc)
548
+
549
+        $lastChunkNr = ceil($size/ $blockSize)-1;
550
+        // calculate last chunk position
551
+        $lastChunkPos = ($lastChunkNr * $blockSize);
552
+        // try to fseek to the last chunk, if it fails we have to read the whole file
553
+        if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
554
+            $newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
555
+        }
556
+
557
+        $lastChunkContentEncrypted='';
558
+        $count = $blockSize;
559
+
560
+        while ($count > 0) {
561
+            $data=fread($stream, $blockSize);
562
+            $count=strlen($data);
563
+            $lastChunkContentEncrypted .= $data;
564
+            if(strlen($lastChunkContentEncrypted) > $blockSize) {
565
+                $newUnencryptedSize += $unencryptedBlockSize;
566
+                $lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
567
+            }
568
+        }
569
+
570
+        fclose($stream);
571
+
572
+        // we have to decrypt the last chunk to get it actual size
573
+        $encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
574
+        $decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
575
+        $decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
576
+
577
+        // calc the real file size with the size of the last chunk
578
+        $newUnencryptedSize += strlen($decryptedLastChunk);
579
+
580
+        $this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
581
+
582
+        // write to cache if applicable
583
+        $cache = $this->storage->getCache();
584
+        if ($cache) {
585
+            $entry = $cache->get($path);
586
+            $cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
587
+        }
588
+
589
+        return $newUnencryptedSize;
590
+    }
591
+
592
+    /**
593
+     * @param Storage $sourceStorage
594
+     * @param string $sourceInternalPath
595
+     * @param string $targetInternalPath
596
+     * @param bool $preserveMtime
597
+     * @return bool
598
+     */
599
+    public function moveFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
600
+        if ($sourceStorage === $this) {
601
+            return $this->rename($sourceInternalPath, $targetInternalPath);
602
+        }
603
+
604
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
605
+        // - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
606
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
607
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
608
+        // - remove $this->copyBetweenStorage
609
+
610
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
611
+            return false;
612
+        }
613
+
614
+        $result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
615
+        if ($result) {
616
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
617
+                $result &= $sourceStorage->rmdir($sourceInternalPath);
618
+            } else {
619
+                $result &= $sourceStorage->unlink($sourceInternalPath);
620
+            }
621
+        }
622
+        return $result;
623
+    }
624
+
625
+
626
+    /**
627
+     * @param Storage $sourceStorage
628
+     * @param string $sourceInternalPath
629
+     * @param string $targetInternalPath
630
+     * @param bool $preserveMtime
631
+     * @param bool $isRename
632
+     * @return bool
633
+     */
634
+    public function copyFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
635
+
636
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
637
+        // - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
638
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
639
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
640
+        // - remove $this->copyBetweenStorage
641
+
642
+        return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
643
+    }
644
+
645
+    /**
646
+     * Update the encrypted cache version in the database
647
+     *
648
+     * @param Storage $sourceStorage
649
+     * @param string $sourceInternalPath
650
+     * @param string $targetInternalPath
651
+     * @param bool $isRename
652
+     */
653
+    private function updateEncryptedVersion(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
654
+        $isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath) ? 1 : 0;
655
+        $cacheInformation = [
656
+            'encrypted' => (bool)$isEncrypted,
657
+        ];
658
+        if($isEncrypted === 1) {
659
+            $encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
660
+
661
+            // In case of a move operation from an unencrypted to an encrypted
662
+            // storage the old encrypted version would stay with "0" while the
663
+            // correct value would be "1". Thus we manually set the value to "1"
664
+            // for those cases.
665
+            // See also https://github.com/owncloud/core/issues/23078
666
+            if($encryptedVersion === 0) {
667
+                $encryptedVersion = 1;
668
+            }
669
+
670
+            $cacheInformation['encryptedVersion'] = $encryptedVersion;
671
+        }
672
+
673
+        // in case of a rename we need to manipulate the source cache because
674
+        // this information will be kept for the new target
675
+        if ($isRename) {
676
+            $sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
677
+        } else {
678
+            $this->getCache()->put($targetInternalPath, $cacheInformation);
679
+        }
680
+    }
681
+
682
+    /**
683
+     * copy file between two storages
684
+     *
685
+     * @param Storage $sourceStorage
686
+     * @param string $sourceInternalPath
687
+     * @param string $targetInternalPath
688
+     * @param bool $preserveMtime
689
+     * @param bool $isRename
690
+     * @return bool
691
+     * @throws \Exception
692
+     */
693
+    private function copyBetweenStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
694
+
695
+        // for versions we have nothing to do, because versions should always use the
696
+        // key from the original file. Just create a 1:1 copy and done
697
+        if ($this->isVersion($targetInternalPath) ||
698
+            $this->isVersion($sourceInternalPath)) {
699
+            // remember that we try to create a version so that we can detect it during
700
+            // fopen($sourceInternalPath) and by-pass the encryption in order to
701
+            // create a 1:1 copy of the file
702
+            $this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
703
+            $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
704
+            $this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
705
+            if ($result) {
706
+                $info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
707
+                // make sure that we update the unencrypted size for the version
708
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
709
+                    $this->updateUnencryptedSize(
710
+                        $this->getFullPath($targetInternalPath),
711
+                        $info['size']
712
+                    );
713
+                }
714
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
715
+            }
716
+            return $result;
717
+        }
718
+
719
+        // first copy the keys that we reuse the existing file key on the target location
720
+        // and don't create a new one which would break versions for example.
721
+        $mount = $this->mountManager->findByStorageId($sourceStorage->getId());
722
+        if (count($mount) === 1) {
723
+            $mountPoint = $mount[0]->getMountPoint();
724
+            $source = $mountPoint . '/' . $sourceInternalPath;
725
+            $target = $this->getFullPath($targetInternalPath);
726
+            $this->copyKeys($source, $target);
727
+        } else {
728
+            $this->logger->error('Could not find mount point, can\'t keep encryption keys');
729
+        }
730
+
731
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
732
+            $dh = $sourceStorage->opendir($sourceInternalPath);
733
+            $result = $this->mkdir($targetInternalPath);
734
+            if (is_resource($dh)) {
735
+                while ($result and ($file = readdir($dh)) !== false) {
736
+                    if (!Filesystem::isIgnoredDir($file)) {
737
+                        $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
738
+                    }
739
+                }
740
+            }
741
+        } else {
742
+            try {
743
+                $source = $sourceStorage->fopen($sourceInternalPath, 'r');
744
+                $target = $this->fopen($targetInternalPath, 'w');
745
+                list(, $result) = \OC_Helper::streamCopy($source, $target);
746
+                fclose($source);
747
+                fclose($target);
748
+            } catch (\Exception $e) {
749
+                fclose($source);
750
+                fclose($target);
751
+                throw $e;
752
+            }
753
+            if($result) {
754
+                if ($preserveMtime) {
755
+                    $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
756
+                }
757
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
758
+            } else {
759
+                // delete partially written target file
760
+                $this->unlink($targetInternalPath);
761
+                // delete cache entry that was created by fopen
762
+                $this->getCache()->remove($targetInternalPath);
763
+            }
764
+        }
765
+        return (bool)$result;
766
+
767
+    }
768
+
769
+    /**
770
+     * get the path to a local version of the file.
771
+     * The local version of the file can be temporary and doesn't have to be persistent across requests
772
+     *
773
+     * @param string $path
774
+     * @return string
775
+     */
776
+    public function getLocalFile($path) {
777
+        if ($this->encryptionManager->isEnabled()) {
778
+            $cachedFile = $this->getCachedFile($path);
779
+            if (is_string($cachedFile)) {
780
+                return $cachedFile;
781
+            }
782
+        }
783
+        return $this->storage->getLocalFile($path);
784
+    }
785
+
786
+    /**
787
+     * Returns the wrapped storage's value for isLocal()
788
+     *
789
+     * @return bool wrapped storage's isLocal() value
790
+     */
791
+    public function isLocal() {
792
+        if ($this->encryptionManager->isEnabled()) {
793
+            return false;
794
+        }
795
+        return $this->storage->isLocal();
796
+    }
797
+
798
+    /**
799
+     * see http://php.net/manual/en/function.stat.php
800
+     * only the following keys are required in the result: size and mtime
801
+     *
802
+     * @param string $path
803
+     * @return array
804
+     */
805
+    public function stat($path) {
806
+        $stat = $this->storage->stat($path);
807
+        $fileSize = $this->filesize($path);
808
+        $stat['size'] = $fileSize;
809
+        $stat[7] = $fileSize;
810
+        return $stat;
811
+    }
812
+
813
+    /**
814
+     * see http://php.net/manual/en/function.hash.php
815
+     *
816
+     * @param string $type
817
+     * @param string $path
818
+     * @param bool $raw
819
+     * @return string
820
+     */
821
+    public function hash($type, $path, $raw = false) {
822
+        $fh = $this->fopen($path, 'rb');
823
+        $ctx = hash_init($type);
824
+        hash_update_stream($ctx, $fh);
825
+        fclose($fh);
826
+        return hash_final($ctx, $raw);
827
+    }
828
+
829
+    /**
830
+     * return full path, including mount point
831
+     *
832
+     * @param string $path relative to mount point
833
+     * @return string full path including mount point
834
+     */
835
+    protected function getFullPath($path) {
836
+        return Filesystem::normalizePath($this->mountPoint . '/' . $path);
837
+    }
838
+
839
+    /**
840
+     * read first block of encrypted file, typically this will contain the
841
+     * encryption header
842
+     *
843
+     * @param string $path
844
+     * @return string
845
+     */
846
+    protected function readFirstBlock($path) {
847
+        $firstBlock = '';
848
+        if ($this->storage->file_exists($path)) {
849
+            $handle = $this->storage->fopen($path, 'r');
850
+            $firstBlock = fread($handle, $this->util->getHeaderSize());
851
+            fclose($handle);
852
+        }
853
+        return $firstBlock;
854
+    }
855
+
856
+    /**
857
+     * return header size of given file
858
+     *
859
+     * @param string $path
860
+     * @return int
861
+     */
862
+    protected function getHeaderSize($path) {
863
+        $headerSize = 0;
864
+        $realFile = $this->util->stripPartialFileExtension($path);
865
+        if ($this->storage->file_exists($realFile)) {
866
+            $path = $realFile;
867
+        }
868
+        $firstBlock = $this->readFirstBlock($path);
869
+
870
+        if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
871
+            $headerSize = $this->util->getHeaderSize();
872
+        }
873
+
874
+        return $headerSize;
875
+    }
876
+
877
+    /**
878
+     * parse raw header to array
879
+     *
880
+     * @param string $rawHeader
881
+     * @return array
882
+     */
883
+    protected function parseRawHeader($rawHeader) {
884
+        $result = array();
885
+        if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
886
+            $header = $rawHeader;
887
+            $endAt = strpos($header, Util::HEADER_END);
888
+            if ($endAt !== false) {
889
+                $header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
890
+
891
+                // +1 to not start with an ':' which would result in empty element at the beginning
892
+                $exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
893
+
894
+                $element = array_shift($exploded);
895
+                while ($element !== Util::HEADER_END) {
896
+                    $result[$element] = array_shift($exploded);
897
+                    $element = array_shift($exploded);
898
+                }
899
+            }
900
+        }
901
+
902
+        return $result;
903
+    }
904
+
905
+    /**
906
+     * read header from file
907
+     *
908
+     * @param string $path
909
+     * @return array
910
+     */
911
+    protected function getHeader($path) {
912
+        $realFile = $this->util->stripPartialFileExtension($path);
913
+        $exists = $this->storage->file_exists($realFile);
914
+        if ($exists) {
915
+            $path = $realFile;
916
+        }
917
+
918
+        $firstBlock = $this->readFirstBlock($path);
919
+        $result = $this->parseRawHeader($firstBlock);
920
+
921
+        // if the header doesn't contain a encryption module we check if it is a
922
+        // legacy file. If true, we add the default encryption module
923
+        if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
924
+            if (!empty($result)) {
925
+                $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
926
+            } else if ($exists) {
927
+                // if the header was empty we have to check first if it is a encrypted file at all
928
+                // We would do query to filecache only if we know that entry in filecache exists
929
+                $info = $this->getCache()->get($path);
930
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
931
+                    $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
932
+                }
933
+            }
934
+        }
935
+
936
+        return $result;
937
+    }
938
+
939
+    /**
940
+     * read encryption module needed to read/write the file located at $path
941
+     *
942
+     * @param string $path
943
+     * @return null|\OCP\Encryption\IEncryptionModule
944
+     * @throws ModuleDoesNotExistsException
945
+     * @throws \Exception
946
+     */
947
+    protected function getEncryptionModule($path) {
948
+        $encryptionModule = null;
949
+        $header = $this->getHeader($path);
950
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
951
+        if (!empty($encryptionModuleId)) {
952
+            try {
953
+                $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
954
+            } catch (ModuleDoesNotExistsException $e) {
955
+                $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
956
+                throw $e;
957
+            }
958
+        }
959
+
960
+        return $encryptionModule;
961
+    }
962
+
963
+    /**
964
+     * @param string $path
965
+     * @param int $unencryptedSize
966
+     */
967
+    public function updateUnencryptedSize($path, $unencryptedSize) {
968
+        $this->unencryptedSize[$path] = $unencryptedSize;
969
+    }
970
+
971
+    /**
972
+     * copy keys to new location
973
+     *
974
+     * @param string $source path relative to data/
975
+     * @param string $target path relative to data/
976
+     * @return bool
977
+     */
978
+    protected function copyKeys($source, $target) {
979
+        if (!$this->util->isExcluded($source)) {
980
+            return $this->keyStorage->copyKeys($source, $target);
981
+        }
982
+
983
+        return false;
984
+    }
985
+
986
+    /**
987
+     * check if path points to a files version
988
+     *
989
+     * @param $path
990
+     * @return bool
991
+     */
992
+    protected function isVersion($path) {
993
+        $normalized = Filesystem::normalizePath($path);
994
+        return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
995
+    }
996
+
997
+    /**
998
+     * check if the given storage should be encrypted or not
999
+     *
1000
+     * @param $path
1001
+     * @return bool
1002
+     */
1003
+    protected function shouldEncrypt($path) {
1004
+        $fullPath = $this->getFullPath($path);
1005
+        $mountPointConfig = $this->mount->getOption('encrypt', true);
1006
+        if ($mountPointConfig === false) {
1007
+            return false;
1008
+        }
1009
+
1010
+        try {
1011
+            $encryptionModule = $this->getEncryptionModule($fullPath);
1012
+        } catch (ModuleDoesNotExistsException $e) {
1013
+            return false;
1014
+        }
1015
+
1016
+        if ($encryptionModule === null) {
1017
+            $encryptionModule = $this->encryptionManager->getEncryptionModule();
1018
+        }
1019
+
1020
+        return $encryptionModule->shouldEncrypt($fullPath);
1021
+
1022
+    }
1023 1023
 
1024 1024
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/Dropbox.php 3 patches
Doc Comments   +6 added lines patch added patch discarded remove patch
@@ -76,6 +76,9 @@  discard block
 block discarded – undo
76 76
 		return false;
77 77
 	}
78 78
 
79
+	/**
80
+	 * @param string $path
81
+	 */
79 82
 	private function setMetaData($path, $metaData) {
80 83
 		$this->metaData[ltrim($path, '/')] = $metaData;
81 84
 	}
@@ -316,6 +319,9 @@  discard block
 block discarded – undo
316 319
 		return false;
317 320
 	}
318 321
 
322
+	/**
323
+	 * @param string $path
324
+	 */
319 325
 	public function writeBack($tmpFile, $path) {
320 326
 		$handle = fopen($tmpFile, 'r');
321 327
 		try {
Please login to merge, or discard this patch.
Indentation   +290 added lines, -290 removed lines patch added patch discarded remove patch
@@ -40,317 +40,317 @@
 block discarded – undo
40 40
 
41 41
 class Dropbox extends \OC\Files\Storage\Common {
42 42
 
43
-	private $dropbox;
44
-	private $root;
45
-	private $id;
46
-	private $metaData = array();
47
-	private $oauth;
43
+    private $dropbox;
44
+    private $root;
45
+    private $id;
46
+    private $metaData = array();
47
+    private $oauth;
48 48
 
49
-	public function __construct($params) {
50
-		if (isset($params['configured']) && $params['configured'] == 'true'
51
-			&& isset($params['app_key'])
52
-			&& isset($params['app_secret'])
53
-			&& isset($params['token'])
54
-			&& isset($params['token_secret'])
55
-		) {
56
-			$this->root = isset($params['root']) ? $params['root'] : '';
57
-			$this->id = 'dropbox::'.$params['app_key'] . $params['token']. '/' . $this->root;
58
-			$this->oauth = new \Dropbox_OAuth_Curl($params['app_key'], $params['app_secret']);
59
-			$this->oauth->setToken($params['token'], $params['token_secret']);
60
-			// note: Dropbox_API connection is lazy
61
-			$this->dropbox = new \Dropbox_API($this->oauth, 'auto');
62
-		} else {
63
-			throw new \Exception('Creating Dropbox storage failed');
64
-		}
65
-	}
49
+    public function __construct($params) {
50
+        if (isset($params['configured']) && $params['configured'] == 'true'
51
+            && isset($params['app_key'])
52
+            && isset($params['app_secret'])
53
+            && isset($params['token'])
54
+            && isset($params['token_secret'])
55
+        ) {
56
+            $this->root = isset($params['root']) ? $params['root'] : '';
57
+            $this->id = 'dropbox::'.$params['app_key'] . $params['token']. '/' . $this->root;
58
+            $this->oauth = new \Dropbox_OAuth_Curl($params['app_key'], $params['app_secret']);
59
+            $this->oauth->setToken($params['token'], $params['token_secret']);
60
+            // note: Dropbox_API connection is lazy
61
+            $this->dropbox = new \Dropbox_API($this->oauth, 'auto');
62
+        } else {
63
+            throw new \Exception('Creating Dropbox storage failed');
64
+        }
65
+    }
66 66
 
67
-	/**
68
-	 * @param string $path
69
-	 */
70
-	private function deleteMetaData($path) {
71
-		$path = ltrim($this->root.$path, '/');
72
-		if (isset($this->metaData[$path])) {
73
-			unset($this->metaData[$path]);
74
-			return true;
75
-		}
76
-		return false;
77
-	}
67
+    /**
68
+     * @param string $path
69
+     */
70
+    private function deleteMetaData($path) {
71
+        $path = ltrim($this->root.$path, '/');
72
+        if (isset($this->metaData[$path])) {
73
+            unset($this->metaData[$path]);
74
+            return true;
75
+        }
76
+        return false;
77
+    }
78 78
 
79
-	private function setMetaData($path, $metaData) {
80
-		$this->metaData[ltrim($path, '/')] = $metaData;
81
-	}
79
+    private function setMetaData($path, $metaData) {
80
+        $this->metaData[ltrim($path, '/')] = $metaData;
81
+    }
82 82
 
83
-	/**
84
-	 * Returns the path's metadata
85
-	 * @param string $path path for which to return the metadata
86
-	 * @param bool $list if true, also return the directory's contents
87
-	 * @return mixed directory contents if $list is true, file metadata if $list is
88
-	 * false, null if the file doesn't exist or "false" if the operation failed
89
-	 */
90
-	private function getDropBoxMetaData($path, $list = false) {
91
-		$path = ltrim($this->root.$path, '/');
92
-		if ( ! $list && isset($this->metaData[$path])) {
93
-			return $this->metaData[$path];
94
-		} else {
95
-			if ($list) {
96
-				try {
97
-					$response = $this->dropbox->getMetaData($path);
98
-				} catch (\Dropbox_Exception_Forbidden $e) {
99
-					throw new StorageNotAvailableException('Dropbox API rate limit exceeded', StorageNotAvailableException::STATUS_ERROR, $e);
100
-				} catch (\Exception $exception) {
101
-					\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
102
-					return false;
103
-				}
104
-				$contents = array();
105
-				if ($response && isset($response['contents'])) {
106
-					// Cache folder's contents
107
-					foreach ($response['contents'] as $file) {
108
-						if (!isset($file['is_deleted']) || !$file['is_deleted']) {
109
-							$this->setMetaData($path.'/'.basename($file['path']), $file);
110
-							$contents[] = $file;
111
-						}
112
-					}
113
-					unset($response['contents']);
114
-				}
115
-				if (!isset($response['is_deleted']) || !$response['is_deleted']) {
116
-					$this->setMetaData($path, $response);
117
-				}
118
-				// Return contents of folder only
119
-				return $contents;
120
-			} else {
121
-				try {
122
-					$requestPath = $path;
123
-					if ($path === '.') {
124
-						$requestPath = '';
125
-					}
83
+    /**
84
+     * Returns the path's metadata
85
+     * @param string $path path for which to return the metadata
86
+     * @param bool $list if true, also return the directory's contents
87
+     * @return mixed directory contents if $list is true, file metadata if $list is
88
+     * false, null if the file doesn't exist or "false" if the operation failed
89
+     */
90
+    private function getDropBoxMetaData($path, $list = false) {
91
+        $path = ltrim($this->root.$path, '/');
92
+        if ( ! $list && isset($this->metaData[$path])) {
93
+            return $this->metaData[$path];
94
+        } else {
95
+            if ($list) {
96
+                try {
97
+                    $response = $this->dropbox->getMetaData($path);
98
+                } catch (\Dropbox_Exception_Forbidden $e) {
99
+                    throw new StorageNotAvailableException('Dropbox API rate limit exceeded', StorageNotAvailableException::STATUS_ERROR, $e);
100
+                } catch (\Exception $exception) {
101
+                    \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
102
+                    return false;
103
+                }
104
+                $contents = array();
105
+                if ($response && isset($response['contents'])) {
106
+                    // Cache folder's contents
107
+                    foreach ($response['contents'] as $file) {
108
+                        if (!isset($file['is_deleted']) || !$file['is_deleted']) {
109
+                            $this->setMetaData($path.'/'.basename($file['path']), $file);
110
+                            $contents[] = $file;
111
+                        }
112
+                    }
113
+                    unset($response['contents']);
114
+                }
115
+                if (!isset($response['is_deleted']) || !$response['is_deleted']) {
116
+                    $this->setMetaData($path, $response);
117
+                }
118
+                // Return contents of folder only
119
+                return $contents;
120
+            } else {
121
+                try {
122
+                    $requestPath = $path;
123
+                    if ($path === '.') {
124
+                        $requestPath = '';
125
+                    }
126 126
 
127
-					$response = $this->dropbox->getMetaData($requestPath, 'false');
128
-					if (!isset($response['is_deleted']) || !$response['is_deleted']) {
129
-						$this->setMetaData($path, $response);
130
-						return $response;
131
-					}
132
-					return null;
133
-				} catch (\Dropbox_Exception_Forbidden $e) {
134
-					throw new StorageNotAvailableException('Dropbox API rate limit exceeded', StorageNotAvailableException::STATUS_ERROR, $e);
135
-				} catch (\Exception $exception) {
136
-					if ($exception instanceof \Dropbox_Exception_NotFound) {
137
-						// don't log, might be a file_exist check
138
-						return false;
139
-					}
140
-					\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
141
-					return false;
142
-				}
143
-			}
144
-		}
145
-	}
127
+                    $response = $this->dropbox->getMetaData($requestPath, 'false');
128
+                    if (!isset($response['is_deleted']) || !$response['is_deleted']) {
129
+                        $this->setMetaData($path, $response);
130
+                        return $response;
131
+                    }
132
+                    return null;
133
+                } catch (\Dropbox_Exception_Forbidden $e) {
134
+                    throw new StorageNotAvailableException('Dropbox API rate limit exceeded', StorageNotAvailableException::STATUS_ERROR, $e);
135
+                } catch (\Exception $exception) {
136
+                    if ($exception instanceof \Dropbox_Exception_NotFound) {
137
+                        // don't log, might be a file_exist check
138
+                        return false;
139
+                    }
140
+                    \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
141
+                    return false;
142
+                }
143
+            }
144
+        }
145
+    }
146 146
 
147
-	public function getId(){
148
-		return $this->id;
149
-	}
147
+    public function getId(){
148
+        return $this->id;
149
+    }
150 150
 
151
-	public function mkdir($path) {
152
-		$path = $this->root.$path;
153
-		try {
154
-			$this->dropbox->createFolder($path);
155
-			return true;
156
-		} catch (\Exception $exception) {
157
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
158
-			return false;
159
-		}
160
-	}
151
+    public function mkdir($path) {
152
+        $path = $this->root.$path;
153
+        try {
154
+            $this->dropbox->createFolder($path);
155
+            return true;
156
+        } catch (\Exception $exception) {
157
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
158
+            return false;
159
+        }
160
+    }
161 161
 
162
-	public function rmdir($path) {
163
-		return $this->unlink($path);
164
-	}
162
+    public function rmdir($path) {
163
+        return $this->unlink($path);
164
+    }
165 165
 
166
-	public function opendir($path) {
167
-		$contents = $this->getDropBoxMetaData($path, true);
168
-		if ($contents !== false) {
169
-			$files = array();
170
-			foreach ($contents as $file) {
171
-				$files[] = basename($file['path']);
172
-			}
173
-			return IteratorDirectory::wrap($files);
174
-		}
175
-		return false;
176
-	}
166
+    public function opendir($path) {
167
+        $contents = $this->getDropBoxMetaData($path, true);
168
+        if ($contents !== false) {
169
+            $files = array();
170
+            foreach ($contents as $file) {
171
+                $files[] = basename($file['path']);
172
+            }
173
+            return IteratorDirectory::wrap($files);
174
+        }
175
+        return false;
176
+    }
177 177
 
178
-	public function stat($path) {
179
-		$metaData = $this->getDropBoxMetaData($path);
180
-		if ($metaData) {
181
-			$stat['size'] = $metaData['bytes'];
182
-			$stat['atime'] = time();
183
-			$stat['mtime'] = (isset($metaData['modified'])) ? strtotime($metaData['modified']) : time();
184
-			return $stat;
185
-		}
186
-		return false;
187
-	}
178
+    public function stat($path) {
179
+        $metaData = $this->getDropBoxMetaData($path);
180
+        if ($metaData) {
181
+            $stat['size'] = $metaData['bytes'];
182
+            $stat['atime'] = time();
183
+            $stat['mtime'] = (isset($metaData['modified'])) ? strtotime($metaData['modified']) : time();
184
+            return $stat;
185
+        }
186
+        return false;
187
+    }
188 188
 
189
-	public function filetype($path) {
190
-		if ($path == '' || $path == '/') {
191
-			return 'dir';
192
-		} else {
193
-			$metaData = $this->getDropBoxMetaData($path);
194
-			if ($metaData) {
195
-				if ($metaData['is_dir'] == 'true') {
196
-					return 'dir';
197
-				} else {
198
-					return 'file';
199
-				}
200
-			}
201
-		}
202
-		return false;
203
-	}
189
+    public function filetype($path) {
190
+        if ($path == '' || $path == '/') {
191
+            return 'dir';
192
+        } else {
193
+            $metaData = $this->getDropBoxMetaData($path);
194
+            if ($metaData) {
195
+                if ($metaData['is_dir'] == 'true') {
196
+                    return 'dir';
197
+                } else {
198
+                    return 'file';
199
+                }
200
+            }
201
+        }
202
+        return false;
203
+    }
204 204
 
205
-	public function file_exists($path) {
206
-		if ($path == '' || $path == '/') {
207
-			return true;
208
-		}
209
-		if ($this->getDropBoxMetaData($path)) {
210
-			return true;
211
-		}
212
-		return false;
213
-	}
205
+    public function file_exists($path) {
206
+        if ($path == '' || $path == '/') {
207
+            return true;
208
+        }
209
+        if ($this->getDropBoxMetaData($path)) {
210
+            return true;
211
+        }
212
+        return false;
213
+    }
214 214
 
215
-	public function unlink($path) {
216
-		try {
217
-			$this->dropbox->delete($this->root.$path);
218
-			$this->deleteMetaData($path);
219
-			return true;
220
-		} catch (\Exception $exception) {
221
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
222
-			return false;
223
-		}
224
-	}
215
+    public function unlink($path) {
216
+        try {
217
+            $this->dropbox->delete($this->root.$path);
218
+            $this->deleteMetaData($path);
219
+            return true;
220
+        } catch (\Exception $exception) {
221
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
222
+            return false;
223
+        }
224
+    }
225 225
 
226
-	public function rename($path1, $path2) {
227
-		try {
228
-			// overwrite if target file exists and is not a directory
229
-			$destMetaData = $this->getDropBoxMetaData($path2);
230
-			if (isset($destMetaData) && $destMetaData !== false && !$destMetaData['is_dir']) {
231
-				$this->unlink($path2);
232
-			}
233
-			$this->dropbox->move($this->root.$path1, $this->root.$path2);
234
-			$this->deleteMetaData($path1);
235
-			return true;
236
-		} catch (\Exception $exception) {
237
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
238
-			return false;
239
-		}
240
-	}
226
+    public function rename($path1, $path2) {
227
+        try {
228
+            // overwrite if target file exists and is not a directory
229
+            $destMetaData = $this->getDropBoxMetaData($path2);
230
+            if (isset($destMetaData) && $destMetaData !== false && !$destMetaData['is_dir']) {
231
+                $this->unlink($path2);
232
+            }
233
+            $this->dropbox->move($this->root.$path1, $this->root.$path2);
234
+            $this->deleteMetaData($path1);
235
+            return true;
236
+        } catch (\Exception $exception) {
237
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
238
+            return false;
239
+        }
240
+    }
241 241
 
242
-	public function copy($path1, $path2) {
243
-		$path1 = $this->root.$path1;
244
-		$path2 = $this->root.$path2;
245
-		try {
246
-			$this->dropbox->copy($path1, $path2);
247
-			return true;
248
-		} catch (\Exception $exception) {
249
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
250
-			return false;
251
-		}
252
-	}
242
+    public function copy($path1, $path2) {
243
+        $path1 = $this->root.$path1;
244
+        $path2 = $this->root.$path2;
245
+        try {
246
+            $this->dropbox->copy($path1, $path2);
247
+            return true;
248
+        } catch (\Exception $exception) {
249
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
250
+            return false;
251
+        }
252
+    }
253 253
 
254
-	public function fopen($path, $mode) {
255
-		$path = $this->root.$path;
256
-		switch ($mode) {
257
-			case 'r':
258
-			case 'rb':
259
-				try {
260
-					// slashes need to stay
261
-					$encodedPath = str_replace('%2F', '/', rawurlencode(trim($path, '/')));
262
-					$downloadUrl = 'https://api-content.dropbox.com/1/files/auto/' . $encodedPath;
263
-					$headers = $this->oauth->getOAuthHeader($downloadUrl, [], 'GET');
254
+    public function fopen($path, $mode) {
255
+        $path = $this->root.$path;
256
+        switch ($mode) {
257
+            case 'r':
258
+            case 'rb':
259
+                try {
260
+                    // slashes need to stay
261
+                    $encodedPath = str_replace('%2F', '/', rawurlencode(trim($path, '/')));
262
+                    $downloadUrl = 'https://api-content.dropbox.com/1/files/auto/' . $encodedPath;
263
+                    $headers = $this->oauth->getOAuthHeader($downloadUrl, [], 'GET');
264 264
 
265
-					$client = \OC::$server->getHTTPClientService()->newClient();
266
-					try {
267
-						$response = $client->get($downloadUrl, [
268
-							'headers' => $headers,
269
-							'stream' => true,
270
-						]);
271
-					} catch (RequestException $e) {
272
-						if (!is_null($e->getResponse())) {
273
-							if ($e->getResponse()->getStatusCode() === 404) {
274
-								return false;
275
-							} else {
276
-								throw $e;
277
-							}
278
-						} else {
279
-							throw $e;
280
-						}
281
-					}
265
+                    $client = \OC::$server->getHTTPClientService()->newClient();
266
+                    try {
267
+                        $response = $client->get($downloadUrl, [
268
+                            'headers' => $headers,
269
+                            'stream' => true,
270
+                        ]);
271
+                    } catch (RequestException $e) {
272
+                        if (!is_null($e->getResponse())) {
273
+                            if ($e->getResponse()->getStatusCode() === 404) {
274
+                                return false;
275
+                            } else {
276
+                                throw $e;
277
+                            }
278
+                        } else {
279
+                            throw $e;
280
+                        }
281
+                    }
282 282
 
283
-					$handle = $response->getBody();
284
-					return RetryWrapper::wrap($handle);
285
-				} catch (\Exception $exception) {
286
-					\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
287
-					return false;
288
-				}
289
-			case 'w':
290
-			case 'wb':
291
-			case 'a':
292
-			case 'ab':
293
-			case 'r+':
294
-			case 'w+':
295
-			case 'wb+':
296
-			case 'a+':
297
-			case 'x':
298
-			case 'x+':
299
-			case 'c':
300
-			case 'c+':
301
-				if (strrpos($path, '.') !== false) {
302
-					$ext = substr($path, strrpos($path, '.'));
303
-				} else {
304
-					$ext = '';
305
-				}
306
-				$tmpFile = \OCP\Files::tmpFile($ext);
307
-				if ($this->file_exists($path)) {
308
-					$source = $this->fopen($path, 'r');
309
-					file_put_contents($tmpFile, $source);
310
-				}
311
-			$handle = fopen($tmpFile, $mode);
312
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
313
-				$this->writeBack($tmpFile, $path);
314
-			});
315
-		}
316
-		return false;
317
-	}
283
+                    $handle = $response->getBody();
284
+                    return RetryWrapper::wrap($handle);
285
+                } catch (\Exception $exception) {
286
+                    \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
287
+                    return false;
288
+                }
289
+            case 'w':
290
+            case 'wb':
291
+            case 'a':
292
+            case 'ab':
293
+            case 'r+':
294
+            case 'w+':
295
+            case 'wb+':
296
+            case 'a+':
297
+            case 'x':
298
+            case 'x+':
299
+            case 'c':
300
+            case 'c+':
301
+                if (strrpos($path, '.') !== false) {
302
+                    $ext = substr($path, strrpos($path, '.'));
303
+                } else {
304
+                    $ext = '';
305
+                }
306
+                $tmpFile = \OCP\Files::tmpFile($ext);
307
+                if ($this->file_exists($path)) {
308
+                    $source = $this->fopen($path, 'r');
309
+                    file_put_contents($tmpFile, $source);
310
+                }
311
+            $handle = fopen($tmpFile, $mode);
312
+            return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
313
+                $this->writeBack($tmpFile, $path);
314
+            });
315
+        }
316
+        return false;
317
+    }
318 318
 
319
-	public function writeBack($tmpFile, $path) {
320
-		$handle = fopen($tmpFile, 'r');
321
-		try {
322
-			$this->dropbox->putFile($path, $handle);
323
-			unlink($tmpFile);
324
-			$this->deleteMetaData($path);
325
-		} catch (\Exception $exception) {
326
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
327
-		}
328
-	}
319
+    public function writeBack($tmpFile, $path) {
320
+        $handle = fopen($tmpFile, 'r');
321
+        try {
322
+            $this->dropbox->putFile($path, $handle);
323
+            unlink($tmpFile);
324
+            $this->deleteMetaData($path);
325
+        } catch (\Exception $exception) {
326
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
327
+        }
328
+    }
329 329
 
330
-	public function free_space($path) {
331
-		try {
332
-			$info = $this->dropbox->getAccountInfo();
333
-			return $info['quota_info']['quota'] - $info['quota_info']['normal'];
334
-		} catch (\Exception $exception) {
335
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
336
-			return false;
337
-		}
338
-	}
330
+    public function free_space($path) {
331
+        try {
332
+            $info = $this->dropbox->getAccountInfo();
333
+            return $info['quota_info']['quota'] - $info['quota_info']['normal'];
334
+        } catch (\Exception $exception) {
335
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
336
+            return false;
337
+        }
338
+    }
339 339
 
340
-	public function touch($path, $mtime = null) {
341
-		if ($this->file_exists($path)) {
342
-			return false;
343
-		} else {
344
-			$this->file_put_contents($path, '');
345
-		}
346
-		return true;
347
-	}
340
+    public function touch($path, $mtime = null) {
341
+        if ($this->file_exists($path)) {
342
+            return false;
343
+        } else {
344
+            $this->file_put_contents($path, '');
345
+        }
346
+        return true;
347
+    }
348 348
 
349
-	/**
350
-	 * check if curl is installed
351
-	 */
352
-	public static function checkDependencies() {
353
-		return true;
354
-	}
349
+    /**
350
+     * check if curl is installed
351
+     */
352
+    public static function checkDependencies() {
353
+        return true;
354
+    }
355 355
 
356 356
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
 use Icewind\Streams\RetryWrapper;
37 37
 use OCP\Files\StorageNotAvailableException;
38 38
 
39
-require_once __DIR__ . '/../../../3rdparty/Dropbox/autoload.php';
39
+require_once __DIR__.'/../../../3rdparty/Dropbox/autoload.php';
40 40
 
41 41
 class Dropbox extends \OC\Files\Storage\Common {
42 42
 
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
 			&& isset($params['token_secret'])
55 55
 		) {
56 56
 			$this->root = isset($params['root']) ? $params['root'] : '';
57
-			$this->id = 'dropbox::'.$params['app_key'] . $params['token']. '/' . $this->root;
57
+			$this->id = 'dropbox::'.$params['app_key'].$params['token'].'/'.$this->root;
58 58
 			$this->oauth = new \Dropbox_OAuth_Curl($params['app_key'], $params['app_secret']);
59 59
 			$this->oauth->setToken($params['token'], $params['token_secret']);
60 60
 			// note: Dropbox_API connection is lazy
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	 */
90 90
 	private function getDropBoxMetaData($path, $list = false) {
91 91
 		$path = ltrim($this->root.$path, '/');
92
-		if ( ! $list && isset($this->metaData[$path])) {
92
+		if (!$list && isset($this->metaData[$path])) {
93 93
 			return $this->metaData[$path];
94 94
 		} else {
95 95
 			if ($list) {
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 		}
145 145
 	}
146 146
 
147
-	public function getId(){
147
+	public function getId() {
148 148
 		return $this->id;
149 149
 	}
150 150
 
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
 				try {
260 260
 					// slashes need to stay
261 261
 					$encodedPath = str_replace('%2F', '/', rawurlencode(trim($path, '/')));
262
-					$downloadUrl = 'https://api-content.dropbox.com/1/files/auto/' . $encodedPath;
262
+					$downloadUrl = 'https://api-content.dropbox.com/1/files/auto/'.$encodedPath;
263 263
 					$headers = $this->oauth->getOAuthHeader($downloadUrl, [], 'GET');
264 264
 
265 265
 					$client = \OC::$server->getHTTPClientService()->newClient();
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
 					file_put_contents($tmpFile, $source);
310 310
 				}
311 311
 			$handle = fopen($tmpFile, $mode);
312
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
312
+			return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
313 313
 				$this->writeBack($tmpFile, $path);
314 314
 			});
315 315
 		}
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/Google.php 3 patches
Doc Comments   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 	 *
217 217
 	 * @param \Google_Service_Drive_DriveFile
218 218
 	 *
219
-	 * @return true if the file is a Google Doc file, false otherwise
219
+	 * @return boolean if the file is a Google Doc file, false otherwise
220 220
 	 */
221 221
 	private function isGoogleDocFile($file) {
222 222
 		return $this->getGoogleDocExtension($file->getMimeType()) !== '';
@@ -505,6 +505,9 @@  discard block
 block discarded – undo
505 505
 		}
506 506
 	}
507 507
 
508
+	/**
509
+	 * @param string $path
510
+	 */
508 511
 	public function writeBack($tmpFile, $path) {
509 512
 		$parentFolder = $this->getDriveFile(dirname($path));
510 513
 		if ($parentFolder) {
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 				if (isset($this->driveFiles[$path])) {
124 124
 					$parentId = $this->driveFiles[$path]->getId();
125 125
 				} else {
126
-					$q = "title='" . str_replace("'","\\'", $name) . "' and '" . str_replace("'","\\'", $parentId) . "' in parents and trashed = false";
126
+					$q = "title='".str_replace("'", "\\'", $name)."' and '".str_replace("'", "\\'", $parentId)."' in parents and trashed = false";
127 127
 					$result = $this->service->files->listFiles(array('q' => $q))->getItems();
128 128
 					if (!empty($result)) {
129 129
 						// Google Drive allows files with the same name, Nextcloud doesn't
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
 				if ($result) {
237 237
 					$this->setDriveFile($path, $result);
238 238
 				}
239
-				return (bool)$result;
239
+				return (bool) $result;
240 240
 			}
241 241
 		}
242 242
 		return false;
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 		}
249 249
 		if (trim($path, '/') === '') {
250 250
 			$dir = $this->opendir($path);
251
-			if(is_resource($dir)) {
251
+			if (is_resource($dir)) {
252 252
 				while (($file = readdir($dir)) !== false) {
253 253
 					if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
254 254
 						if (!$this->unlink($path.'/'.$file)) {
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
 				if ($pageToken !== true) {
277 277
 					$params['pageToken'] = $pageToken;
278 278
 				}
279
-				$params['q'] = "'" . str_replace("'","\\'", $folder->getId()) . "' in parents and trashed = false";
279
+				$params['q'] = "'".str_replace("'", "\\'", $folder->getId())."' in parents and trashed = false";
280 280
 				$children = $this->service->files->listFiles($params);
281 281
 				foreach ($children->getItems() as $child) {
282 282
 					$name = $child->getTitle();
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
 	}
370 370
 
371 371
 	public function file_exists($path) {
372
-		return (bool)$this->getDriveFile($path);
372
+		return (bool) $this->getDriveFile($path);
373 373
 	}
374 374
 
375 375
 	public function unlink($path) {
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
 			if ($result) {
380 380
 				$this->setDriveFile($path, false);
381 381
 			}
382
-			return (bool)$result;
382
+			return (bool) $result;
383 383
 		} else {
384 384
 			return false;
385 385
 		}
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
 					}
428 428
 				}
429 429
 			}
430
-			return (bool)$result;
430
+			return (bool) $result;
431 431
 		} else {
432 432
 			return false;
433 433
 		}
@@ -462,10 +462,10 @@  discard block
 block discarded – undo
462 462
 							$response = $client->get($downloadUrl, [
463 463
 								'headers' => $httpRequest->getRequestHeaders(),
464 464
 								'stream' => true,
465
-								'verify' => realpath(__DIR__ . '/../../../3rdparty/google-api-php-client/src/Google/IO/cacerts.pem'),
465
+								'verify' => realpath(__DIR__.'/../../../3rdparty/google-api-php-client/src/Google/IO/cacerts.pem'),
466 466
 							]);
467 467
 						} catch (RequestException $e) {
468
-							if(!is_null($e->getResponse())) {
468
+							if (!is_null($e->getResponse())) {
469 469
 								if ($e->getResponse()->getStatusCode() === 404) {
470 470
 									return false;
471 471
 								} else {
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
 					file_put_contents($tmpFile, $source);
500 500
 				}
501 501
 				$handle = fopen($tmpFile, $mode);
502
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
502
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
503 503
 					$this->writeBack($tmpFile, $path);
504 504
 				});
505 505
 		}
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
 		if ($result) {
642 642
 			$this->setDriveFile($path, $result);
643 643
 		}
644
-		return (bool)$result;
644
+		return (bool) $result;
645 645
 	}
646 646
 
647 647
 	public function test() {
@@ -668,7 +668,7 @@  discard block
 block discarded – undo
668 668
 					'includeSubscribed' => true,
669 669
 				);
670 670
 				if (isset($startChangeId)) {
671
-					$startChangeId = (int)$startChangeId;
671
+					$startChangeId = (int) $startChangeId;
672 672
 					$largestChangeId = $startChangeId;
673 673
 					$params['startChangeId'] = $startChangeId + 1;
674 674
 				} else {
Please login to merge, or discard this patch.
Indentation   +676 added lines, -676 removed lines patch added patch discarded remove patch
@@ -41,352 +41,352 @@  discard block
 block discarded – undo
41 41
 use Icewind\Streams\RetryWrapper;
42 42
 
43 43
 set_include_path(get_include_path().PATH_SEPARATOR.
44
-	\OC_App::getAppPath('files_external').'/3rdparty/google-api-php-client/src');
44
+    \OC_App::getAppPath('files_external').'/3rdparty/google-api-php-client/src');
45 45
 require_once 'Google/autoload.php';
46 46
 
47 47
 class Google extends \OC\Files\Storage\Common {
48 48
 
49
-	private $client;
50
-	private $id;
51
-	private $service;
52
-	private $driveFiles;
53
-
54
-	// Google Doc mimetypes
55
-	const FOLDER = 'application/vnd.google-apps.folder';
56
-	const DOCUMENT = 'application/vnd.google-apps.document';
57
-	const SPREADSHEET = 'application/vnd.google-apps.spreadsheet';
58
-	const DRAWING = 'application/vnd.google-apps.drawing';
59
-	const PRESENTATION = 'application/vnd.google-apps.presentation';
60
-	const MAP = 'application/vnd.google-apps.map';
61
-
62
-	public function __construct($params) {
63
-		if (isset($params['configured']) && $params['configured'] === 'true'
64
-			&& isset($params['client_id']) && isset($params['client_secret'])
65
-			&& isset($params['token'])
66
-		) {
67
-			$this->client = new \Google_Client();
68
-			$this->client->setClientId($params['client_id']);
69
-			$this->client->setClientSecret($params['client_secret']);
70
-			$this->client->setScopes(array('https://www.googleapis.com/auth/drive'));
71
-			$this->client->setAccessToken($params['token']);
72
-			// if curl isn't available we're likely to run into
73
-			// https://github.com/google/google-api-php-client/issues/59
74
-			// - disable gzip to avoid it.
75
-			if (!function_exists('curl_version') || !function_exists('curl_exec')) {
76
-				$this->client->setClassConfig("Google_Http_Request", "disable_gzip", true);
77
-			}
78
-			// note: API connection is lazy
79
-			$this->service = new \Google_Service_Drive($this->client);
80
-			$token = json_decode($params['token'], true);
81
-			$this->id = 'google::'.substr($params['client_id'], 0, 30).$token['created'];
82
-		} else {
83
-			throw new \Exception('Creating Google storage failed');
84
-		}
85
-	}
86
-
87
-	public function getId() {
88
-		return $this->id;
89
-	}
90
-
91
-	/**
92
-	 * Get the Google_Service_Drive_DriveFile object for the specified path.
93
-	 * Returns false on failure.
94
-	 * @param string $path
95
-	 * @return \Google_Service_Drive_DriveFile|false
96
-	 */
97
-	private function getDriveFile($path) {
98
-		// Remove leading and trailing slashes
99
-		$path = trim($path, '/');
100
-		if ($path === '.') {
101
-			$path = '';
102
-		}
103
-		if (isset($this->driveFiles[$path])) {
104
-			return $this->driveFiles[$path];
105
-		} else if ($path === '') {
106
-			$root = $this->service->files->get('root');
107
-			$this->driveFiles[$path] = $root;
108
-			return $root;
109
-		} else {
110
-			// Google Drive SDK does not have methods for retrieving files by path
111
-			// Instead we must find the id of the parent folder of the file
112
-			$parentId = $this->getDriveFile('')->getId();
113
-			$folderNames = explode('/', $path);
114
-			$path = '';
115
-			// Loop through each folder of this path to get to the file
116
-			foreach ($folderNames as $name) {
117
-				// Reconstruct path from beginning
118
-				if ($path === '') {
119
-					$path .= $name;
120
-				} else {
121
-					$path .= '/'.$name;
122
-				}
123
-				if (isset($this->driveFiles[$path])) {
124
-					$parentId = $this->driveFiles[$path]->getId();
125
-				} else {
126
-					$q = "title='" . str_replace("'","\\'", $name) . "' and '" . str_replace("'","\\'", $parentId) . "' in parents and trashed = false";
127
-					$result = $this->service->files->listFiles(array('q' => $q))->getItems();
128
-					if (!empty($result)) {
129
-						// Google Drive allows files with the same name, Nextcloud doesn't
130
-						if (count($result) > 1) {
131
-							$this->onDuplicateFileDetected($path);
132
-							return false;
133
-						} else {
134
-							$file = current($result);
135
-							$this->driveFiles[$path] = $file;
136
-							$parentId = $file->getId();
137
-						}
138
-					} else {
139
-						// Google Docs have no extension in their title, so try without extension
140
-						$pos = strrpos($path, '.');
141
-						if ($pos !== false) {
142
-							$pathWithoutExt = substr($path, 0, $pos);
143
-							$file = $this->getDriveFile($pathWithoutExt);
144
-							if ($file && $this->isGoogleDocFile($file)) {
145
-								// Switch cached Google_Service_Drive_DriveFile to the correct index
146
-								unset($this->driveFiles[$pathWithoutExt]);
147
-								$this->driveFiles[$path] = $file;
148
-								$parentId = $file->getId();
149
-							} else {
150
-								return false;
151
-							}
152
-						} else {
153
-							return false;
154
-						}
155
-					}
156
-				}
157
-			}
158
-			return $this->driveFiles[$path];
159
-		}
160
-	}
161
-
162
-	/**
163
-	 * Set the Google_Service_Drive_DriveFile object in the cache
164
-	 * @param string $path
165
-	 * @param \Google_Service_Drive_DriveFile|false $file
166
-	 */
167
-	private function setDriveFile($path, $file) {
168
-		$path = trim($path, '/');
169
-		$this->driveFiles[$path] = $file;
170
-		if ($file === false) {
171
-			// Remove all children
172
-			$len = strlen($path);
173
-			foreach ($this->driveFiles as $key => $file) {
174
-				if (substr($key, 0, $len) === $path) {
175
-					unset($this->driveFiles[$key]);
176
-				}
177
-			}
178
-		}
179
-	}
180
-
181
-	/**
182
-	 * Write a log message to inform about duplicate file names
183
-	 * @param string $path
184
-	 */
185
-	private function onDuplicateFileDetected($path) {
186
-		$about = $this->service->about->get();
187
-		$user = $about->getName();
188
-		\OCP\Util::writeLog('files_external',
189
-			'Ignoring duplicate file name: '.$path.' on Google Drive for Google user: '.$user,
190
-			\OCP\Util::INFO
191
-		);
192
-	}
193
-
194
-	/**
195
-	 * Generate file extension for a Google Doc, choosing Open Document formats for download
196
-	 * @param string $mimetype
197
-	 * @return string
198
-	 */
199
-	private function getGoogleDocExtension($mimetype) {
200
-		if ($mimetype === self::DOCUMENT) {
201
-			return 'odt';
202
-		} else if ($mimetype === self::SPREADSHEET) {
203
-			return 'ods';
204
-		} else if ($mimetype === self::DRAWING) {
205
-			return 'jpg';
206
-		} else if ($mimetype === self::PRESENTATION) {
207
-			// Download as .odp is not available
208
-			return 'pdf';
209
-		} else {
210
-			return '';
211
-		}
212
-	}
213
-
214
-	/**
215
-	 * Returns whether the given drive file is a Google Doc file
216
-	 *
217
-	 * @param \Google_Service_Drive_DriveFile
218
-	 *
219
-	 * @return true if the file is a Google Doc file, false otherwise
220
-	 */
221
-	private function isGoogleDocFile($file) {
222
-		return $this->getGoogleDocExtension($file->getMimeType()) !== '';
223
-	}
224
-
225
-	public function mkdir($path) {
226
-		if (!$this->is_dir($path)) {
227
-			$parentFolder = $this->getDriveFile(dirname($path));
228
-			if ($parentFolder) {
229
-				$folder = new \Google_Service_Drive_DriveFile();
230
-				$folder->setTitle(basename($path));
231
-				$folder->setMimeType(self::FOLDER);
232
-				$parent = new \Google_Service_Drive_ParentReference();
233
-				$parent->setId($parentFolder->getId());
234
-				$folder->setParents(array($parent));
235
-				$result = $this->service->files->insert($folder);
236
-				if ($result) {
237
-					$this->setDriveFile($path, $result);
238
-				}
239
-				return (bool)$result;
240
-			}
241
-		}
242
-		return false;
243
-	}
244
-
245
-	public function rmdir($path) {
246
-		if (!$this->isDeletable($path)) {
247
-			return false;
248
-		}
249
-		if (trim($path, '/') === '') {
250
-			$dir = $this->opendir($path);
251
-			if(is_resource($dir)) {
252
-				while (($file = readdir($dir)) !== false) {
253
-					if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
254
-						if (!$this->unlink($path.'/'.$file)) {
255
-							return false;
256
-						}
257
-					}
258
-				}
259
-				closedir($dir);
260
-			}
261
-			$this->driveFiles = array();
262
-			return true;
263
-		} else {
264
-			return $this->unlink($path);
265
-		}
266
-	}
267
-
268
-	public function opendir($path) {
269
-		$folder = $this->getDriveFile($path);
270
-		if ($folder) {
271
-			$files = array();
272
-			$duplicates = array();
273
-			$pageToken = true;
274
-			while ($pageToken) {
275
-				$params = array();
276
-				if ($pageToken !== true) {
277
-					$params['pageToken'] = $pageToken;
278
-				}
279
-				$params['q'] = "'" . str_replace("'","\\'", $folder->getId()) . "' in parents and trashed = false";
280
-				$children = $this->service->files->listFiles($params);
281
-				foreach ($children->getItems() as $child) {
282
-					$name = $child->getTitle();
283
-					// Check if this is a Google Doc i.e. no extension in name
284
-					$extension = $child->getFileExtension();
285
-					if (empty($extension)) {
286
-						if ($child->getMimeType() === self::MAP) {
287
-							continue; // No method known to transfer map files, ignore it
288
-						} else if ($child->getMimeType() !== self::FOLDER) {
289
-							$name .= '.'.$this->getGoogleDocExtension($child->getMimeType());
290
-						}
291
-					}
292
-					if ($path === '') {
293
-						$filepath = $name;
294
-					} else {
295
-						$filepath = $path.'/'.$name;
296
-					}
297
-					// Google Drive allows files with the same name, Nextcloud doesn't
298
-					// Prevent opendir() from returning any duplicate files
299
-					$key = array_search($name, $files);
300
-					if ($key !== false || isset($duplicates[$filepath])) {
301
-						if (!isset($duplicates[$filepath])) {
302
-							$duplicates[$filepath] = true;
303
-							$this->setDriveFile($filepath, false);
304
-							unset($files[$key]);
305
-							$this->onDuplicateFileDetected($filepath);
306
-						}
307
-					} else {
308
-						// Cache the Google_Service_Drive_DriveFile for future use
309
-						$this->setDriveFile($filepath, $child);
310
-						$files[] = $name;
311
-					}
312
-				}
313
-				$pageToken = $children->getNextPageToken();
314
-			}
315
-			return IteratorDirectory::wrap($files);
316
-		} else {
317
-			return false;
318
-		}
319
-	}
320
-
321
-	public function stat($path) {
322
-		$file = $this->getDriveFile($path);
323
-		if ($file) {
324
-			$stat = array();
325
-			if ($this->filetype($path) === 'dir') {
326
-				$stat['size'] = 0;
327
-			} else {
328
-				// Check if this is a Google Doc
329
-				if ($this->isGoogleDocFile($file)) {
330
-					// Return unknown file size
331
-					$stat['size'] = \OCP\Files\FileInfo::SPACE_UNKNOWN;
332
-				} else {
333
-					$stat['size'] = $file->getFileSize();
334
-				}
335
-			}
336
-			$stat['atime'] = strtotime($file->getLastViewedByMeDate());
337
-			$stat['mtime'] = strtotime($file->getModifiedDate());
338
-			$stat['ctime'] = strtotime($file->getCreatedDate());
339
-			return $stat;
340
-		} else {
341
-			return false;
342
-		}
343
-	}
344
-
345
-	public function filetype($path) {
346
-		if ($path === '') {
347
-			return 'dir';
348
-		} else {
349
-			$file = $this->getDriveFile($path);
350
-			if ($file) {
351
-				if ($file->getMimeType() === self::FOLDER) {
352
-					return 'dir';
353
-				} else {
354
-					return 'file';
355
-				}
356
-			} else {
357
-				return false;
358
-			}
359
-		}
360
-	}
361
-
362
-	public function isUpdatable($path) {
363
-		$file = $this->getDriveFile($path);
364
-		if ($file) {
365
-			return $file->getEditable();
366
-		} else {
367
-			return false;
368
-		}
369
-	}
370
-
371
-	public function file_exists($path) {
372
-		return (bool)$this->getDriveFile($path);
373
-	}
374
-
375
-	public function unlink($path) {
376
-		$file = $this->getDriveFile($path);
377
-		if ($file) {
378
-			$result = $this->service->files->trash($file->getId());
379
-			if ($result) {
380
-				$this->setDriveFile($path, false);
381
-			}
382
-			return (bool)$result;
383
-		} else {
384
-			return false;
385
-		}
386
-	}
387
-
388
-	public function rename($path1, $path2) {
389
-		// Avoid duplicate files with the same name
49
+    private $client;
50
+    private $id;
51
+    private $service;
52
+    private $driveFiles;
53
+
54
+    // Google Doc mimetypes
55
+    const FOLDER = 'application/vnd.google-apps.folder';
56
+    const DOCUMENT = 'application/vnd.google-apps.document';
57
+    const SPREADSHEET = 'application/vnd.google-apps.spreadsheet';
58
+    const DRAWING = 'application/vnd.google-apps.drawing';
59
+    const PRESENTATION = 'application/vnd.google-apps.presentation';
60
+    const MAP = 'application/vnd.google-apps.map';
61
+
62
+    public function __construct($params) {
63
+        if (isset($params['configured']) && $params['configured'] === 'true'
64
+            && isset($params['client_id']) && isset($params['client_secret'])
65
+            && isset($params['token'])
66
+        ) {
67
+            $this->client = new \Google_Client();
68
+            $this->client->setClientId($params['client_id']);
69
+            $this->client->setClientSecret($params['client_secret']);
70
+            $this->client->setScopes(array('https://www.googleapis.com/auth/drive'));
71
+            $this->client->setAccessToken($params['token']);
72
+            // if curl isn't available we're likely to run into
73
+            // https://github.com/google/google-api-php-client/issues/59
74
+            // - disable gzip to avoid it.
75
+            if (!function_exists('curl_version') || !function_exists('curl_exec')) {
76
+                $this->client->setClassConfig("Google_Http_Request", "disable_gzip", true);
77
+            }
78
+            // note: API connection is lazy
79
+            $this->service = new \Google_Service_Drive($this->client);
80
+            $token = json_decode($params['token'], true);
81
+            $this->id = 'google::'.substr($params['client_id'], 0, 30).$token['created'];
82
+        } else {
83
+            throw new \Exception('Creating Google storage failed');
84
+        }
85
+    }
86
+
87
+    public function getId() {
88
+        return $this->id;
89
+    }
90
+
91
+    /**
92
+     * Get the Google_Service_Drive_DriveFile object for the specified path.
93
+     * Returns false on failure.
94
+     * @param string $path
95
+     * @return \Google_Service_Drive_DriveFile|false
96
+     */
97
+    private function getDriveFile($path) {
98
+        // Remove leading and trailing slashes
99
+        $path = trim($path, '/');
100
+        if ($path === '.') {
101
+            $path = '';
102
+        }
103
+        if (isset($this->driveFiles[$path])) {
104
+            return $this->driveFiles[$path];
105
+        } else if ($path === '') {
106
+            $root = $this->service->files->get('root');
107
+            $this->driveFiles[$path] = $root;
108
+            return $root;
109
+        } else {
110
+            // Google Drive SDK does not have methods for retrieving files by path
111
+            // Instead we must find the id of the parent folder of the file
112
+            $parentId = $this->getDriveFile('')->getId();
113
+            $folderNames = explode('/', $path);
114
+            $path = '';
115
+            // Loop through each folder of this path to get to the file
116
+            foreach ($folderNames as $name) {
117
+                // Reconstruct path from beginning
118
+                if ($path === '') {
119
+                    $path .= $name;
120
+                } else {
121
+                    $path .= '/'.$name;
122
+                }
123
+                if (isset($this->driveFiles[$path])) {
124
+                    $parentId = $this->driveFiles[$path]->getId();
125
+                } else {
126
+                    $q = "title='" . str_replace("'","\\'", $name) . "' and '" . str_replace("'","\\'", $parentId) . "' in parents and trashed = false";
127
+                    $result = $this->service->files->listFiles(array('q' => $q))->getItems();
128
+                    if (!empty($result)) {
129
+                        // Google Drive allows files with the same name, Nextcloud doesn't
130
+                        if (count($result) > 1) {
131
+                            $this->onDuplicateFileDetected($path);
132
+                            return false;
133
+                        } else {
134
+                            $file = current($result);
135
+                            $this->driveFiles[$path] = $file;
136
+                            $parentId = $file->getId();
137
+                        }
138
+                    } else {
139
+                        // Google Docs have no extension in their title, so try without extension
140
+                        $pos = strrpos($path, '.');
141
+                        if ($pos !== false) {
142
+                            $pathWithoutExt = substr($path, 0, $pos);
143
+                            $file = $this->getDriveFile($pathWithoutExt);
144
+                            if ($file && $this->isGoogleDocFile($file)) {
145
+                                // Switch cached Google_Service_Drive_DriveFile to the correct index
146
+                                unset($this->driveFiles[$pathWithoutExt]);
147
+                                $this->driveFiles[$path] = $file;
148
+                                $parentId = $file->getId();
149
+                            } else {
150
+                                return false;
151
+                            }
152
+                        } else {
153
+                            return false;
154
+                        }
155
+                    }
156
+                }
157
+            }
158
+            return $this->driveFiles[$path];
159
+        }
160
+    }
161
+
162
+    /**
163
+     * Set the Google_Service_Drive_DriveFile object in the cache
164
+     * @param string $path
165
+     * @param \Google_Service_Drive_DriveFile|false $file
166
+     */
167
+    private function setDriveFile($path, $file) {
168
+        $path = trim($path, '/');
169
+        $this->driveFiles[$path] = $file;
170
+        if ($file === false) {
171
+            // Remove all children
172
+            $len = strlen($path);
173
+            foreach ($this->driveFiles as $key => $file) {
174
+                if (substr($key, 0, $len) === $path) {
175
+                    unset($this->driveFiles[$key]);
176
+                }
177
+            }
178
+        }
179
+    }
180
+
181
+    /**
182
+     * Write a log message to inform about duplicate file names
183
+     * @param string $path
184
+     */
185
+    private function onDuplicateFileDetected($path) {
186
+        $about = $this->service->about->get();
187
+        $user = $about->getName();
188
+        \OCP\Util::writeLog('files_external',
189
+            'Ignoring duplicate file name: '.$path.' on Google Drive for Google user: '.$user,
190
+            \OCP\Util::INFO
191
+        );
192
+    }
193
+
194
+    /**
195
+     * Generate file extension for a Google Doc, choosing Open Document formats for download
196
+     * @param string $mimetype
197
+     * @return string
198
+     */
199
+    private function getGoogleDocExtension($mimetype) {
200
+        if ($mimetype === self::DOCUMENT) {
201
+            return 'odt';
202
+        } else if ($mimetype === self::SPREADSHEET) {
203
+            return 'ods';
204
+        } else if ($mimetype === self::DRAWING) {
205
+            return 'jpg';
206
+        } else if ($mimetype === self::PRESENTATION) {
207
+            // Download as .odp is not available
208
+            return 'pdf';
209
+        } else {
210
+            return '';
211
+        }
212
+    }
213
+
214
+    /**
215
+     * Returns whether the given drive file is a Google Doc file
216
+     *
217
+     * @param \Google_Service_Drive_DriveFile
218
+     *
219
+     * @return true if the file is a Google Doc file, false otherwise
220
+     */
221
+    private function isGoogleDocFile($file) {
222
+        return $this->getGoogleDocExtension($file->getMimeType()) !== '';
223
+    }
224
+
225
+    public function mkdir($path) {
226
+        if (!$this->is_dir($path)) {
227
+            $parentFolder = $this->getDriveFile(dirname($path));
228
+            if ($parentFolder) {
229
+                $folder = new \Google_Service_Drive_DriveFile();
230
+                $folder->setTitle(basename($path));
231
+                $folder->setMimeType(self::FOLDER);
232
+                $parent = new \Google_Service_Drive_ParentReference();
233
+                $parent->setId($parentFolder->getId());
234
+                $folder->setParents(array($parent));
235
+                $result = $this->service->files->insert($folder);
236
+                if ($result) {
237
+                    $this->setDriveFile($path, $result);
238
+                }
239
+                return (bool)$result;
240
+            }
241
+        }
242
+        return false;
243
+    }
244
+
245
+    public function rmdir($path) {
246
+        if (!$this->isDeletable($path)) {
247
+            return false;
248
+        }
249
+        if (trim($path, '/') === '') {
250
+            $dir = $this->opendir($path);
251
+            if(is_resource($dir)) {
252
+                while (($file = readdir($dir)) !== false) {
253
+                    if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
254
+                        if (!$this->unlink($path.'/'.$file)) {
255
+                            return false;
256
+                        }
257
+                    }
258
+                }
259
+                closedir($dir);
260
+            }
261
+            $this->driveFiles = array();
262
+            return true;
263
+        } else {
264
+            return $this->unlink($path);
265
+        }
266
+    }
267
+
268
+    public function opendir($path) {
269
+        $folder = $this->getDriveFile($path);
270
+        if ($folder) {
271
+            $files = array();
272
+            $duplicates = array();
273
+            $pageToken = true;
274
+            while ($pageToken) {
275
+                $params = array();
276
+                if ($pageToken !== true) {
277
+                    $params['pageToken'] = $pageToken;
278
+                }
279
+                $params['q'] = "'" . str_replace("'","\\'", $folder->getId()) . "' in parents and trashed = false";
280
+                $children = $this->service->files->listFiles($params);
281
+                foreach ($children->getItems() as $child) {
282
+                    $name = $child->getTitle();
283
+                    // Check if this is a Google Doc i.e. no extension in name
284
+                    $extension = $child->getFileExtension();
285
+                    if (empty($extension)) {
286
+                        if ($child->getMimeType() === self::MAP) {
287
+                            continue; // No method known to transfer map files, ignore it
288
+                        } else if ($child->getMimeType() !== self::FOLDER) {
289
+                            $name .= '.'.$this->getGoogleDocExtension($child->getMimeType());
290
+                        }
291
+                    }
292
+                    if ($path === '') {
293
+                        $filepath = $name;
294
+                    } else {
295
+                        $filepath = $path.'/'.$name;
296
+                    }
297
+                    // Google Drive allows files with the same name, Nextcloud doesn't
298
+                    // Prevent opendir() from returning any duplicate files
299
+                    $key = array_search($name, $files);
300
+                    if ($key !== false || isset($duplicates[$filepath])) {
301
+                        if (!isset($duplicates[$filepath])) {
302
+                            $duplicates[$filepath] = true;
303
+                            $this->setDriveFile($filepath, false);
304
+                            unset($files[$key]);
305
+                            $this->onDuplicateFileDetected($filepath);
306
+                        }
307
+                    } else {
308
+                        // Cache the Google_Service_Drive_DriveFile for future use
309
+                        $this->setDriveFile($filepath, $child);
310
+                        $files[] = $name;
311
+                    }
312
+                }
313
+                $pageToken = $children->getNextPageToken();
314
+            }
315
+            return IteratorDirectory::wrap($files);
316
+        } else {
317
+            return false;
318
+        }
319
+    }
320
+
321
+    public function stat($path) {
322
+        $file = $this->getDriveFile($path);
323
+        if ($file) {
324
+            $stat = array();
325
+            if ($this->filetype($path) === 'dir') {
326
+                $stat['size'] = 0;
327
+            } else {
328
+                // Check if this is a Google Doc
329
+                if ($this->isGoogleDocFile($file)) {
330
+                    // Return unknown file size
331
+                    $stat['size'] = \OCP\Files\FileInfo::SPACE_UNKNOWN;
332
+                } else {
333
+                    $stat['size'] = $file->getFileSize();
334
+                }
335
+            }
336
+            $stat['atime'] = strtotime($file->getLastViewedByMeDate());
337
+            $stat['mtime'] = strtotime($file->getModifiedDate());
338
+            $stat['ctime'] = strtotime($file->getCreatedDate());
339
+            return $stat;
340
+        } else {
341
+            return false;
342
+        }
343
+    }
344
+
345
+    public function filetype($path) {
346
+        if ($path === '') {
347
+            return 'dir';
348
+        } else {
349
+            $file = $this->getDriveFile($path);
350
+            if ($file) {
351
+                if ($file->getMimeType() === self::FOLDER) {
352
+                    return 'dir';
353
+                } else {
354
+                    return 'file';
355
+                }
356
+            } else {
357
+                return false;
358
+            }
359
+        }
360
+    }
361
+
362
+    public function isUpdatable($path) {
363
+        $file = $this->getDriveFile($path);
364
+        if ($file) {
365
+            return $file->getEditable();
366
+        } else {
367
+            return false;
368
+        }
369
+    }
370
+
371
+    public function file_exists($path) {
372
+        return (bool)$this->getDriveFile($path);
373
+    }
374
+
375
+    public function unlink($path) {
376
+        $file = $this->getDriveFile($path);
377
+        if ($file) {
378
+            $result = $this->service->files->trash($file->getId());
379
+            if ($result) {
380
+                $this->setDriveFile($path, false);
381
+            }
382
+            return (bool)$result;
383
+        } else {
384
+            return false;
385
+        }
386
+    }
387
+
388
+    public function rename($path1, $path2) {
389
+        // Avoid duplicate files with the same name
390 390
                 $testRegex = '/^.+\.ocTransferId\d+\.part$/';
391 391
                 if (preg_match($testRegex, $path1)) {
392 392
                         if ($this->is_file($path2)) {
@@ -399,339 +399,339 @@  discard block
 block discarded – undo
399 399
                         }
400 400
                 }
401 401
 		
402
-		$file = $this->getDriveFile($path1);
403
-		if ($file) {
404
-			$newFile = $this->getDriveFile($path2);
405
-			if (dirname($path1) === dirname($path2)) {
406
-				if ($newFile) {
407
-					// rename to the name of the target file, could be an office file without extension
408
-					$file->setTitle($newFile->getTitle());
409
-				} else {
410
-					$file->setTitle(basename(($path2)));
411
-				}
412
-			} else {
413
-				// Change file parent
414
-				$parentFolder2 = $this->getDriveFile(dirname($path2));
415
-				if ($parentFolder2) {
416
-					$parent = new \Google_Service_Drive_ParentReference();
417
-					$parent->setId($parentFolder2->getId());
418
-					$file->setParents(array($parent));
419
-				} else {
420
-					return false;
421
-				}
422
-			}
423
-			// We need to get the object for the existing file with the same
424
-			// name (if there is one) before we do the patch. If oldfile
425
-			// exists and is a directory we have to delete it before we
426
-			// do the rename too.
427
-			$oldfile = $this->getDriveFile($path2);
428
-			if ($oldfile && $this->is_dir($path2)) {
429
-				$this->rmdir($path2);
430
-				$oldfile = false;
431
-			}
432
-			$result = $this->service->files->patch($file->getId(), $file);
433
-			if ($result) {
434
-				$this->setDriveFile($path1, false);
435
-				$this->setDriveFile($path2, $result);
436
-				if ($oldfile && $newFile) {
437
-					// only delete if they have a different id (same id can happen for part files)
438
-					if ($newFile->getId() !== $oldfile->getId()) {
439
-						$this->service->files->delete($oldfile->getId());
440
-					}
441
-				}
442
-			}
443
-			return (bool)$result;
444
-		} else {
445
-			return false;
446
-		}
447
-	}
448
-
449
-	public function fopen($path, $mode) {
450
-		$pos = strrpos($path, '.');
451
-		if ($pos !== false) {
452
-			$ext = substr($path, $pos);
453
-		} else {
454
-			$ext = '';
455
-		}
456
-		switch ($mode) {
457
-			case 'r':
458
-			case 'rb':
459
-				$file = $this->getDriveFile($path);
460
-				if ($file) {
461
-					$exportLinks = $file->getExportLinks();
462
-					$mimetype = $this->getMimeType($path);
463
-					$downloadUrl = null;
464
-					if ($exportLinks && isset($exportLinks[$mimetype])) {
465
-						$downloadUrl = $exportLinks[$mimetype];
466
-					} else {
467
-						$downloadUrl = $file->getDownloadUrl();
468
-					}
469
-					if (isset($downloadUrl)) {
470
-						$request = new \Google_Http_Request($downloadUrl, 'GET', null, null);
471
-						$httpRequest = $this->client->getAuth()->sign($request);
472
-						// the library's service doesn't support streaming, so we use Guzzle instead
473
-						$client = \OC::$server->getHTTPClientService()->newClient();
474
-						try {
475
-							$response = $client->get($downloadUrl, [
476
-								'headers' => $httpRequest->getRequestHeaders(),
477
-								'stream' => true,
478
-								'verify' => realpath(__DIR__ . '/../../../3rdparty/google-api-php-client/src/Google/IO/cacerts.pem'),
479
-							]);
480
-						} catch (RequestException $e) {
481
-							if(!is_null($e->getResponse())) {
482
-								if ($e->getResponse()->getStatusCode() === 404) {
483
-									return false;
484
-								} else {
485
-									throw $e;
486
-								}
487
-							} else {
488
-								throw $e;
489
-							}
490
-						}
491
-
492
-						$handle = $response->getBody();
493
-						return RetryWrapper::wrap($handle);
494
-					}
495
-				}
496
-				return false;
497
-			case 'w':
498
-			case 'wb':
499
-			case 'a':
500
-			case 'ab':
501
-			case 'r+':
502
-			case 'w+':
503
-			case 'wb+':
504
-			case 'a+':
505
-			case 'x':
506
-			case 'x+':
507
-			case 'c':
508
-			case 'c+':
509
-				$tmpFile = \OCP\Files::tmpFile($ext);
510
-				if ($this->file_exists($path)) {
511
-					$source = $this->fopen($path, 'rb');
512
-					file_put_contents($tmpFile, $source);
513
-				}
514
-				$handle = fopen($tmpFile, $mode);
515
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
516
-					$this->writeBack($tmpFile, $path);
517
-				});
518
-		}
519
-	}
520
-
521
-	public function writeBack($tmpFile, $path) {
522
-		$parentFolder = $this->getDriveFile(dirname($path));
523
-		if ($parentFolder) {
524
-			$mimetype = \OC::$server->getMimeTypeDetector()->detect($tmpFile);
525
-			$params = array(
526
-				'mimeType' => $mimetype,
527
-				'uploadType' => 'media'
528
-			);
529
-			$result = false;
530
-
531
-			$chunkSizeBytes = 10 * 1024 * 1024;
532
-
533
-			$useChunking = false;
534
-			$size = filesize($tmpFile);
535
-			if ($size > $chunkSizeBytes) {
536
-				$useChunking = true;
537
-			} else {
538
-				$params['data'] = file_get_contents($tmpFile);
539
-			}
540
-
541
-			if ($this->file_exists($path)) {
542
-				$file = $this->getDriveFile($path);
543
-				$this->client->setDefer($useChunking);
544
-				$request = $this->service->files->update($file->getId(), $file, $params);
545
-			} else {
546
-				$file = new \Google_Service_Drive_DriveFile();
547
-				$file->setTitle(basename($path));
548
-				$file->setMimeType($mimetype);
549
-				$parent = new \Google_Service_Drive_ParentReference();
550
-				$parent->setId($parentFolder->getId());
551
-				$file->setParents(array($parent));
552
-				$this->client->setDefer($useChunking);
553
-				$request = $this->service->files->insert($file, $params);
554
-			}
555
-
556
-			if ($useChunking) {
557
-				// Create a media file upload to represent our upload process.
558
-				$media = new \Google_Http_MediaFileUpload(
559
-					$this->client,
560
-					$request,
561
-					'text/plain',
562
-					null,
563
-					true,
564
-					$chunkSizeBytes
565
-				);
566
-				$media->setFileSize($size);
567
-
568
-				// Upload the various chunks. $status will be false until the process is
569
-				// complete.
570
-				$status = false;
571
-				$handle = fopen($tmpFile, 'rb');
572
-				while (!$status && !feof($handle)) {
573
-					$chunk = fread($handle, $chunkSizeBytes);
574
-					$status = $media->nextChunk($chunk);
575
-				}
576
-
577
-				// The final value of $status will be the data from the API for the object
578
-				// that has been uploaded.
579
-				$result = false;
580
-				if ($status !== false) {
581
-					$result = $status;
582
-				}
583
-
584
-				fclose($handle);
585
-			} else {
586
-				$result = $request;
587
-			}
588
-
589
-			// Reset to the client to execute requests immediately in the future.
590
-			$this->client->setDefer(false);
591
-
592
-			if ($result) {
593
-				$this->setDriveFile($path, $result);
594
-			}
595
-		}
596
-	}
597
-
598
-	public function getMimeType($path) {
599
-		$file = $this->getDriveFile($path);
600
-		if ($file) {
601
-			$mimetype = $file->getMimeType();
602
-			// Convert Google Doc mimetypes, choosing Open Document formats for download
603
-			if ($mimetype === self::FOLDER) {
604
-				return 'httpd/unix-directory';
605
-			} else if ($mimetype === self::DOCUMENT) {
606
-				return 'application/vnd.oasis.opendocument.text';
607
-			} else if ($mimetype === self::SPREADSHEET) {
608
-				return 'application/x-vnd.oasis.opendocument.spreadsheet';
609
-			} else if ($mimetype === self::DRAWING) {
610
-				return 'image/jpeg';
611
-			} else if ($mimetype === self::PRESENTATION) {
612
-				// Download as .odp is not available
613
-				return 'application/pdf';
614
-			} else {
615
-				// use extension-based detection, could be an encrypted file
616
-				return parent::getMimeType($path);
617
-			}
618
-		} else {
619
-			return false;
620
-		}
621
-	}
622
-
623
-	public function free_space($path) {
624
-		$about = $this->service->about->get();
625
-		return $about->getQuotaBytesTotal() - $about->getQuotaBytesUsed();
626
-	}
627
-
628
-	public function touch($path, $mtime = null) {
629
-		$file = $this->getDriveFile($path);
630
-		$result = false;
631
-		if ($file) {
632
-			if (isset($mtime)) {
633
-				// This is just RFC3339, but frustratingly, GDrive's API *requires*
634
-				// the fractions portion be present, while no handy PHP constant
635
-				// for RFC3339 or ISO8601 includes it. So we do it ourselves.
636
-				$file->setModifiedDate(date('Y-m-d\TH:i:s.uP', $mtime));
637
-				$result = $this->service->files->patch($file->getId(), $file, array(
638
-					'setModifiedDate' => true,
639
-				));
640
-			} else {
641
-				$result = $this->service->files->touch($file->getId());
642
-			}
643
-		} else {
644
-			$parentFolder = $this->getDriveFile(dirname($path));
645
-			if ($parentFolder) {
646
-				$file = new \Google_Service_Drive_DriveFile();
647
-				$file->setTitle(basename($path));
648
-				$parent = new \Google_Service_Drive_ParentReference();
649
-				$parent->setId($parentFolder->getId());
650
-				$file->setParents(array($parent));
651
-				$result = $this->service->files->insert($file);
652
-			}
653
-		}
654
-		if ($result) {
655
-			$this->setDriveFile($path, $result);
656
-		}
657
-		return (bool)$result;
658
-	}
659
-
660
-	public function test() {
661
-		if ($this->free_space('')) {
662
-			return true;
663
-		}
664
-		return false;
665
-	}
666
-
667
-	public function hasUpdated($path, $time) {
668
-		$appConfig = \OC::$server->getAppConfig();
669
-		if ($this->is_file($path)) {
670
-			return parent::hasUpdated($path, $time);
671
-		} else {
672
-			// Google Drive doesn't change modified times of folders when files inside are updated
673
-			// Instead we use the Changes API to see if folders have been updated, and it's a pain
674
-			$folder = $this->getDriveFile($path);
675
-			if ($folder) {
676
-				$result = false;
677
-				$folderId = $folder->getId();
678
-				$startChangeId = $appConfig->getValue('files_external', $this->getId().'cId');
679
-				$params = array(
680
-					'includeDeleted' => true,
681
-					'includeSubscribed' => true,
682
-				);
683
-				if (isset($startChangeId)) {
684
-					$startChangeId = (int)$startChangeId;
685
-					$largestChangeId = $startChangeId;
686
-					$params['startChangeId'] = $startChangeId + 1;
687
-				} else {
688
-					$largestChangeId = 0;
689
-				}
690
-				$pageToken = true;
691
-				while ($pageToken) {
692
-					if ($pageToken !== true) {
693
-						$params['pageToken'] = $pageToken;
694
-					}
695
-					$changes = $this->service->changes->listChanges($params);
696
-					if ($largestChangeId === 0 || $largestChangeId === $startChangeId) {
697
-						$largestChangeId = $changes->getLargestChangeId();
698
-					}
699
-					if (isset($startChangeId)) {
700
-						// Check if a file in this folder has been updated
701
-						// There is no way to filter by folder at the API level...
702
-						foreach ($changes->getItems() as $change) {
703
-							$file = $change->getFile();
704
-							if ($file) {
705
-								foreach ($file->getParents() as $parent) {
706
-									if ($parent->getId() === $folderId) {
707
-										$result = true;
708
-									// Check if there are changes in different folders
709
-									} else if ($change->getId() <= $largestChangeId) {
710
-										// Decrement id so this change is fetched when called again
711
-										$largestChangeId = $change->getId();
712
-										$largestChangeId--;
713
-									}
714
-								}
715
-							}
716
-						}
717
-						$pageToken = $changes->getNextPageToken();
718
-					} else {
719
-						// Assuming the initial scan just occurred and changes are negligible
720
-						break;
721
-					}
722
-				}
723
-				$appConfig->setValue('files_external', $this->getId().'cId', $largestChangeId);
724
-				return $result;
725
-			}
726
-		}
727
-		return false;
728
-	}
729
-
730
-	/**
731
-	 * check if curl is installed
732
-	 */
733
-	public static function checkDependencies() {
734
-		return true;
735
-	}
402
+        $file = $this->getDriveFile($path1);
403
+        if ($file) {
404
+            $newFile = $this->getDriveFile($path2);
405
+            if (dirname($path1) === dirname($path2)) {
406
+                if ($newFile) {
407
+                    // rename to the name of the target file, could be an office file without extension
408
+                    $file->setTitle($newFile->getTitle());
409
+                } else {
410
+                    $file->setTitle(basename(($path2)));
411
+                }
412
+            } else {
413
+                // Change file parent
414
+                $parentFolder2 = $this->getDriveFile(dirname($path2));
415
+                if ($parentFolder2) {
416
+                    $parent = new \Google_Service_Drive_ParentReference();
417
+                    $parent->setId($parentFolder2->getId());
418
+                    $file->setParents(array($parent));
419
+                } else {
420
+                    return false;
421
+                }
422
+            }
423
+            // We need to get the object for the existing file with the same
424
+            // name (if there is one) before we do the patch. If oldfile
425
+            // exists and is a directory we have to delete it before we
426
+            // do the rename too.
427
+            $oldfile = $this->getDriveFile($path2);
428
+            if ($oldfile && $this->is_dir($path2)) {
429
+                $this->rmdir($path2);
430
+                $oldfile = false;
431
+            }
432
+            $result = $this->service->files->patch($file->getId(), $file);
433
+            if ($result) {
434
+                $this->setDriveFile($path1, false);
435
+                $this->setDriveFile($path2, $result);
436
+                if ($oldfile && $newFile) {
437
+                    // only delete if they have a different id (same id can happen for part files)
438
+                    if ($newFile->getId() !== $oldfile->getId()) {
439
+                        $this->service->files->delete($oldfile->getId());
440
+                    }
441
+                }
442
+            }
443
+            return (bool)$result;
444
+        } else {
445
+            return false;
446
+        }
447
+    }
448
+
449
+    public function fopen($path, $mode) {
450
+        $pos = strrpos($path, '.');
451
+        if ($pos !== false) {
452
+            $ext = substr($path, $pos);
453
+        } else {
454
+            $ext = '';
455
+        }
456
+        switch ($mode) {
457
+            case 'r':
458
+            case 'rb':
459
+                $file = $this->getDriveFile($path);
460
+                if ($file) {
461
+                    $exportLinks = $file->getExportLinks();
462
+                    $mimetype = $this->getMimeType($path);
463
+                    $downloadUrl = null;
464
+                    if ($exportLinks && isset($exportLinks[$mimetype])) {
465
+                        $downloadUrl = $exportLinks[$mimetype];
466
+                    } else {
467
+                        $downloadUrl = $file->getDownloadUrl();
468
+                    }
469
+                    if (isset($downloadUrl)) {
470
+                        $request = new \Google_Http_Request($downloadUrl, 'GET', null, null);
471
+                        $httpRequest = $this->client->getAuth()->sign($request);
472
+                        // the library's service doesn't support streaming, so we use Guzzle instead
473
+                        $client = \OC::$server->getHTTPClientService()->newClient();
474
+                        try {
475
+                            $response = $client->get($downloadUrl, [
476
+                                'headers' => $httpRequest->getRequestHeaders(),
477
+                                'stream' => true,
478
+                                'verify' => realpath(__DIR__ . '/../../../3rdparty/google-api-php-client/src/Google/IO/cacerts.pem'),
479
+                            ]);
480
+                        } catch (RequestException $e) {
481
+                            if(!is_null($e->getResponse())) {
482
+                                if ($e->getResponse()->getStatusCode() === 404) {
483
+                                    return false;
484
+                                } else {
485
+                                    throw $e;
486
+                                }
487
+                            } else {
488
+                                throw $e;
489
+                            }
490
+                        }
491
+
492
+                        $handle = $response->getBody();
493
+                        return RetryWrapper::wrap($handle);
494
+                    }
495
+                }
496
+                return false;
497
+            case 'w':
498
+            case 'wb':
499
+            case 'a':
500
+            case 'ab':
501
+            case 'r+':
502
+            case 'w+':
503
+            case 'wb+':
504
+            case 'a+':
505
+            case 'x':
506
+            case 'x+':
507
+            case 'c':
508
+            case 'c+':
509
+                $tmpFile = \OCP\Files::tmpFile($ext);
510
+                if ($this->file_exists($path)) {
511
+                    $source = $this->fopen($path, 'rb');
512
+                    file_put_contents($tmpFile, $source);
513
+                }
514
+                $handle = fopen($tmpFile, $mode);
515
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
516
+                    $this->writeBack($tmpFile, $path);
517
+                });
518
+        }
519
+    }
520
+
521
+    public function writeBack($tmpFile, $path) {
522
+        $parentFolder = $this->getDriveFile(dirname($path));
523
+        if ($parentFolder) {
524
+            $mimetype = \OC::$server->getMimeTypeDetector()->detect($tmpFile);
525
+            $params = array(
526
+                'mimeType' => $mimetype,
527
+                'uploadType' => 'media'
528
+            );
529
+            $result = false;
530
+
531
+            $chunkSizeBytes = 10 * 1024 * 1024;
532
+
533
+            $useChunking = false;
534
+            $size = filesize($tmpFile);
535
+            if ($size > $chunkSizeBytes) {
536
+                $useChunking = true;
537
+            } else {
538
+                $params['data'] = file_get_contents($tmpFile);
539
+            }
540
+
541
+            if ($this->file_exists($path)) {
542
+                $file = $this->getDriveFile($path);
543
+                $this->client->setDefer($useChunking);
544
+                $request = $this->service->files->update($file->getId(), $file, $params);
545
+            } else {
546
+                $file = new \Google_Service_Drive_DriveFile();
547
+                $file->setTitle(basename($path));
548
+                $file->setMimeType($mimetype);
549
+                $parent = new \Google_Service_Drive_ParentReference();
550
+                $parent->setId($parentFolder->getId());
551
+                $file->setParents(array($parent));
552
+                $this->client->setDefer($useChunking);
553
+                $request = $this->service->files->insert($file, $params);
554
+            }
555
+
556
+            if ($useChunking) {
557
+                // Create a media file upload to represent our upload process.
558
+                $media = new \Google_Http_MediaFileUpload(
559
+                    $this->client,
560
+                    $request,
561
+                    'text/plain',
562
+                    null,
563
+                    true,
564
+                    $chunkSizeBytes
565
+                );
566
+                $media->setFileSize($size);
567
+
568
+                // Upload the various chunks. $status will be false until the process is
569
+                // complete.
570
+                $status = false;
571
+                $handle = fopen($tmpFile, 'rb');
572
+                while (!$status && !feof($handle)) {
573
+                    $chunk = fread($handle, $chunkSizeBytes);
574
+                    $status = $media->nextChunk($chunk);
575
+                }
576
+
577
+                // The final value of $status will be the data from the API for the object
578
+                // that has been uploaded.
579
+                $result = false;
580
+                if ($status !== false) {
581
+                    $result = $status;
582
+                }
583
+
584
+                fclose($handle);
585
+            } else {
586
+                $result = $request;
587
+            }
588
+
589
+            // Reset to the client to execute requests immediately in the future.
590
+            $this->client->setDefer(false);
591
+
592
+            if ($result) {
593
+                $this->setDriveFile($path, $result);
594
+            }
595
+        }
596
+    }
597
+
598
+    public function getMimeType($path) {
599
+        $file = $this->getDriveFile($path);
600
+        if ($file) {
601
+            $mimetype = $file->getMimeType();
602
+            // Convert Google Doc mimetypes, choosing Open Document formats for download
603
+            if ($mimetype === self::FOLDER) {
604
+                return 'httpd/unix-directory';
605
+            } else if ($mimetype === self::DOCUMENT) {
606
+                return 'application/vnd.oasis.opendocument.text';
607
+            } else if ($mimetype === self::SPREADSHEET) {
608
+                return 'application/x-vnd.oasis.opendocument.spreadsheet';
609
+            } else if ($mimetype === self::DRAWING) {
610
+                return 'image/jpeg';
611
+            } else if ($mimetype === self::PRESENTATION) {
612
+                // Download as .odp is not available
613
+                return 'application/pdf';
614
+            } else {
615
+                // use extension-based detection, could be an encrypted file
616
+                return parent::getMimeType($path);
617
+            }
618
+        } else {
619
+            return false;
620
+        }
621
+    }
622
+
623
+    public function free_space($path) {
624
+        $about = $this->service->about->get();
625
+        return $about->getQuotaBytesTotal() - $about->getQuotaBytesUsed();
626
+    }
627
+
628
+    public function touch($path, $mtime = null) {
629
+        $file = $this->getDriveFile($path);
630
+        $result = false;
631
+        if ($file) {
632
+            if (isset($mtime)) {
633
+                // This is just RFC3339, but frustratingly, GDrive's API *requires*
634
+                // the fractions portion be present, while no handy PHP constant
635
+                // for RFC3339 or ISO8601 includes it. So we do it ourselves.
636
+                $file->setModifiedDate(date('Y-m-d\TH:i:s.uP', $mtime));
637
+                $result = $this->service->files->patch($file->getId(), $file, array(
638
+                    'setModifiedDate' => true,
639
+                ));
640
+            } else {
641
+                $result = $this->service->files->touch($file->getId());
642
+            }
643
+        } else {
644
+            $parentFolder = $this->getDriveFile(dirname($path));
645
+            if ($parentFolder) {
646
+                $file = new \Google_Service_Drive_DriveFile();
647
+                $file->setTitle(basename($path));
648
+                $parent = new \Google_Service_Drive_ParentReference();
649
+                $parent->setId($parentFolder->getId());
650
+                $file->setParents(array($parent));
651
+                $result = $this->service->files->insert($file);
652
+            }
653
+        }
654
+        if ($result) {
655
+            $this->setDriveFile($path, $result);
656
+        }
657
+        return (bool)$result;
658
+    }
659
+
660
+    public function test() {
661
+        if ($this->free_space('')) {
662
+            return true;
663
+        }
664
+        return false;
665
+    }
666
+
667
+    public function hasUpdated($path, $time) {
668
+        $appConfig = \OC::$server->getAppConfig();
669
+        if ($this->is_file($path)) {
670
+            return parent::hasUpdated($path, $time);
671
+        } else {
672
+            // Google Drive doesn't change modified times of folders when files inside are updated
673
+            // Instead we use the Changes API to see if folders have been updated, and it's a pain
674
+            $folder = $this->getDriveFile($path);
675
+            if ($folder) {
676
+                $result = false;
677
+                $folderId = $folder->getId();
678
+                $startChangeId = $appConfig->getValue('files_external', $this->getId().'cId');
679
+                $params = array(
680
+                    'includeDeleted' => true,
681
+                    'includeSubscribed' => true,
682
+                );
683
+                if (isset($startChangeId)) {
684
+                    $startChangeId = (int)$startChangeId;
685
+                    $largestChangeId = $startChangeId;
686
+                    $params['startChangeId'] = $startChangeId + 1;
687
+                } else {
688
+                    $largestChangeId = 0;
689
+                }
690
+                $pageToken = true;
691
+                while ($pageToken) {
692
+                    if ($pageToken !== true) {
693
+                        $params['pageToken'] = $pageToken;
694
+                    }
695
+                    $changes = $this->service->changes->listChanges($params);
696
+                    if ($largestChangeId === 0 || $largestChangeId === $startChangeId) {
697
+                        $largestChangeId = $changes->getLargestChangeId();
698
+                    }
699
+                    if (isset($startChangeId)) {
700
+                        // Check if a file in this folder has been updated
701
+                        // There is no way to filter by folder at the API level...
702
+                        foreach ($changes->getItems() as $change) {
703
+                            $file = $change->getFile();
704
+                            if ($file) {
705
+                                foreach ($file->getParents() as $parent) {
706
+                                    if ($parent->getId() === $folderId) {
707
+                                        $result = true;
708
+                                    // Check if there are changes in different folders
709
+                                    } else if ($change->getId() <= $largestChangeId) {
710
+                                        // Decrement id so this change is fetched when called again
711
+                                        $largestChangeId = $change->getId();
712
+                                        $largestChangeId--;
713
+                                    }
714
+                                }
715
+                            }
716
+                        }
717
+                        $pageToken = $changes->getNextPageToken();
718
+                    } else {
719
+                        // Assuming the initial scan just occurred and changes are negligible
720
+                        break;
721
+                    }
722
+                }
723
+                $appConfig->setValue('files_external', $this->getId().'cId', $largestChangeId);
724
+                return $result;
725
+            }
726
+        }
727
+        return false;
728
+    }
729
+
730
+    /**
731
+     * check if curl is installed
732
+     */
733
+    public static function checkDependencies() {
734
+        return true;
735
+    }
736 736
 
737 737
 }
Please login to merge, or discard this patch.