Completed
Pull Request — master (#9224)
by Jan-Christoph
28:56 queued 04:45
created
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   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
 			->orderBy('id');
288 288
 
289 289
 		$cursor = $qb->execute();
290
-		while($data = $cursor->fetch()) {
290
+		while ($data = $cursor->fetch()) {
291 291
 			$children[] = $this->createShare($data);
292 292
 		}
293 293
 		$cursor->closeCursor();
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
 			$user = $this->userManager->get($recipient);
333 333
 
334 334
 			if (is_null($group)) {
335
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
335
+				throw new ProviderException('Group "'.$share->getSharedWith().'" does not exist');
336 336
 			}
337 337
 
338 338
 			if (!$group->inGroup($user)) {
@@ -492,7 +492,7 @@  discard block
 block discarded – undo
492 492
 			);
493 493
 		}
494 494
 
495
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
495
+		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
496 496
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
497 497
 
498 498
 		$qb->orderBy('id');
@@ -548,7 +548,7 @@  discard block
 block discarded – undo
548 548
 
549 549
 		$cursor = $qb->execute();
550 550
 		$shares = [];
551
-		while($data = $cursor->fetch()) {
551
+		while ($data = $cursor->fetch()) {
552 552
 			$shares[] = $this->createShare($data);
553 553
 		}
554 554
 		$cursor->closeCursor();
@@ -627,7 +627,7 @@  discard block
 block discarded – undo
627 627
 			->execute();
628 628
 
629 629
 		$shares = [];
630
-		while($data = $cursor->fetch()) {
630
+		while ($data = $cursor->fetch()) {
631 631
 			$shares[] = $this->createShare($data);
632 632
 		}
633 633
 		$cursor->closeCursor();
@@ -698,7 +698,7 @@  discard block
 block discarded – undo
698 698
 
699 699
 			$cursor = $qb->execute();
700 700
 
701
-			while($data = $cursor->fetch()) {
701
+			while ($data = $cursor->fetch()) {
702 702
 				if ($this->isAccessibleResult($data)) {
703 703
 					$shares[] = $this->createShare($data);
704 704
 				}
@@ -713,7 +713,7 @@  discard block
 block discarded – undo
713 713
 			$shares2 = [];
714 714
 
715 715
 			$start = 0;
716
-			while(true) {
716
+			while (true) {
717 717
 				$groups = array_slice($allGroups, $start, 100);
718 718
 				$start += 100;
719 719
 
@@ -758,7 +758,7 @@  discard block
 block discarded – undo
758 758
 					));
759 759
 
760 760
 				$cursor = $qb->execute();
761
-				while($data = $cursor->fetch()) {
761
+				while ($data = $cursor->fetch()) {
762 762
 					if ($offset > 0) {
763 763
 						$offset--;
764 764
 						continue;
@@ -827,14 +827,14 @@  discard block
 block discarded – undo
827 827
 	 */
828 828
 	private function createShare($data) {
829 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'])
830
+		$share->setId((int) $data['id'])
831
+			->setShareType((int) $data['share_type'])
832
+			->setPermissions((int) $data['permissions'])
833 833
 			->setTarget($data['file_target'])
834
-			->setMailSend((bool)$data['mail_send']);
834
+			->setMailSend((bool) $data['mail_send']);
835 835
 
836 836
 		$shareTime = new \DateTime();
837
-		$shareTime->setTimestamp((int)$data['stime']);
837
+		$shareTime->setTimestamp((int) $data['stime']);
838 838
 		$share->setShareTime($shareTime);
839 839
 
840 840
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
@@ -849,7 +849,7 @@  discard block
 block discarded – undo
849 849
 		$share->setSharedBy($data['uid_initiator']);
850 850
 		$share->setShareOwner($data['uid_owner']);
851 851
 
852
-		$share->setNodeId((int)$data['file_source']);
852
+		$share->setNodeId((int) $data['file_source']);
853 853
 		$share->setNodeType($data['item_type']);
854 854
 
855 855
 		if ($data['expiration'] !== null) {
@@ -879,7 +879,7 @@  discard block
 block discarded – undo
879 879
 		$result = [];
880 880
 
881 881
 		$start = 0;
882
-		while(true) {
882
+		while (true) {
883 883
 			/** @var Share[] $shareSlice */
884 884
 			$shareSlice = array_slice($shares, $start, 100);
885 885
 			$start += 100;
@@ -894,7 +894,7 @@  discard block
 block discarded – undo
894 894
 			$shareMap = [];
895 895
 
896 896
 			foreach ($shareSlice as $share) {
897
-				$ids[] = (int)$share->getId();
897
+				$ids[] = (int) $share->getId();
898 898
 				$shareMap[$share->getId()] = $share;
899 899
 			}
900 900
 
@@ -911,8 +911,8 @@  discard block
 block discarded – undo
911 911
 
912 912
 			$stmt = $query->execute();
913 913
 
914
-			while($data = $stmt->fetch()) {
915
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
914
+			while ($data = $stmt->fetch()) {
915
+				$shareMap[$data['parent']]->setPermissions((int) $data['permissions']);
916 916
 				$shareMap[$data['parent']]->setTarget($data['file_target']);
917 917
 			}
918 918
 
@@ -1009,8 +1009,8 @@  discard block
 block discarded – undo
1009 1009
 
1010 1010
 		$cursor = $qb->execute();
1011 1011
 		$ids = [];
1012
-		while($row = $cursor->fetch()) {
1013
-			$ids[] = (int)$row['id'];
1012
+		while ($row = $cursor->fetch()) {
1013
+			$ids[] = (int) $row['id'];
1014 1014
 		}
1015 1015
 		$cursor->closeCursor();
1016 1016
 
@@ -1052,8 +1052,8 @@  discard block
 block discarded – undo
1052 1052
 
1053 1053
 		$cursor = $qb->execute();
1054 1054
 		$ids = [];
1055
-		while($row = $cursor->fetch()) {
1056
-			$ids[] = (int)$row['id'];
1055
+		while ($row = $cursor->fetch()) {
1056
+			$ids[] = (int) $row['id'];
1057 1057
 		}
1058 1058
 		$cursor->closeCursor();
1059 1059
 
@@ -1107,8 +1107,8 @@  discard block
 block discarded – undo
1107 1107
 
1108 1108
 		$users = [];
1109 1109
 		$link = false;
1110
-		while($row = $cursor->fetch()) {
1111
-			$type = (int)$row['share_type'];
1110
+		while ($row = $cursor->fetch()) {
1111
+			$type = (int) $row['share_type'];
1112 1112
 			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1113 1113
 				$uid = $row['share_with'];
1114 1114
 				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
Please login to merge, or discard this patch.
Indentation   +1106 added lines, -1106 removed lines patch added patch discarded remove patch
@@ -52,1143 +52,1143 @@
 block discarded – undo
52 52
  */
53 53
 class DefaultShareProvider implements IShareProvider {
54 54
 
55
-	// Special share type for user modified group shares
56
-	const SHARE_TYPE_USERGROUP = 2;
57
-
58
-	/** @var IDBConnection */
59
-	private $dbConn;
60
-
61
-	/** @var IUserManager */
62
-	private $userManager;
63
-
64
-	/** @var IGroupManager */
65
-	private $groupManager;
66
-
67
-	/** @var IRootFolder */
68
-	private $rootFolder;
69
-
70
-	/**
71
-	 * DefaultShareProvider constructor.
72
-	 *
73
-	 * @param IDBConnection $connection
74
-	 * @param IUserManager $userManager
75
-	 * @param IGroupManager $groupManager
76
-	 * @param IRootFolder $rootFolder
77
-	 */
78
-	public function __construct(
79
-			IDBConnection $connection,
80
-			IUserManager $userManager,
81
-			IGroupManager $groupManager,
82
-			IRootFolder $rootFolder) {
83
-		$this->dbConn = $connection;
84
-		$this->userManager = $userManager;
85
-		$this->groupManager = $groupManager;
86
-		$this->rootFolder = $rootFolder;
87
-	}
88
-
89
-	/**
90
-	 * Return the identifier of this provider.
91
-	 *
92
-	 * @return string Containing only [a-zA-Z0-9]
93
-	 */
94
-	public function identifier() {
95
-		return 'ocinternal';
96
-	}
97
-
98
-	/**
99
-	 * Share a path
100
-	 *
101
-	 * @param \OCP\Share\IShare $share
102
-	 * @return \OCP\Share\IShare The share object
103
-	 * @throws ShareNotFound
104
-	 * @throws \Exception
105
-	 */
106
-	public function create(\OCP\Share\IShare $share) {
107
-		$qb = $this->dbConn->getQueryBuilder();
108
-
109
-		$qb->insert('share');
110
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
111
-
112
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
113
-			//Set the UID of the user we share with
114
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
115
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
116
-			//Set the GID of the group we share with
117
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
118
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
119
-			//Set the token of the share
120
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
121
-
122
-			//If a password is set store it
123
-			if ($share->getPassword() !== null) {
124
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
125
-			}
126
-
127
-			//If an expiration date is set store it
128
-			if ($share->getExpirationDate() !== null) {
129
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
130
-			}
131
-
132
-			if (method_exists($share, 'getParent')) {
133
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
134
-			}
135
-		} else {
136
-			throw new \Exception('invalid share type!');
137
-		}
138
-
139
-		// Set what is shares
140
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
141
-		if ($share->getNode() instanceof \OCP\Files\File) {
142
-			$qb->setParameter('itemType', 'file');
143
-		} else {
144
-			$qb->setParameter('itemType', 'folder');
145
-		}
146
-
147
-		// Set the file id
148
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
149
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
150
-
151
-		// set the permissions
152
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
153
-
154
-		// Set who created this share
155
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
156
-
157
-		// Set who is the owner of this file/folder (and this the owner of the share)
158
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
159
-
160
-		// Set the file target
161
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
162
-
163
-		// Set the time this share was created
164
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
165
-
166
-		// insert the data and fetch the id of the share
167
-		$this->dbConn->beginTransaction();
168
-		$qb->execute();
169
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
170
-
171
-		// Now fetch the inserted share and create a complete share object
172
-		$qb = $this->dbConn->getQueryBuilder();
173
-		$qb->select('*')
174
-			->from('share')
175
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
176
-
177
-		$cursor = $qb->execute();
178
-		$data = $cursor->fetch();
179
-		$this->dbConn->commit();
180
-		$cursor->closeCursor();
181
-
182
-		if ($data === false) {
183
-			throw new ShareNotFound();
184
-		}
185
-
186
-		$mailSendValue = $share->getMailSend();
187
-		$data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
188
-
189
-		$share = $this->createShare($data);
190
-		return $share;
191
-	}
192
-
193
-	/**
194
-	 * Update a share
195
-	 *
196
-	 * @param \OCP\Share\IShare $share
197
-	 * @return \OCP\Share\IShare The share object
198
-	 */
199
-	public function update(\OCP\Share\IShare $share) {
200
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
201
-			/*
55
+    // Special share type for user modified group shares
56
+    const SHARE_TYPE_USERGROUP = 2;
57
+
58
+    /** @var IDBConnection */
59
+    private $dbConn;
60
+
61
+    /** @var IUserManager */
62
+    private $userManager;
63
+
64
+    /** @var IGroupManager */
65
+    private $groupManager;
66
+
67
+    /** @var IRootFolder */
68
+    private $rootFolder;
69
+
70
+    /**
71
+     * DefaultShareProvider constructor.
72
+     *
73
+     * @param IDBConnection $connection
74
+     * @param IUserManager $userManager
75
+     * @param IGroupManager $groupManager
76
+     * @param IRootFolder $rootFolder
77
+     */
78
+    public function __construct(
79
+            IDBConnection $connection,
80
+            IUserManager $userManager,
81
+            IGroupManager $groupManager,
82
+            IRootFolder $rootFolder) {
83
+        $this->dbConn = $connection;
84
+        $this->userManager = $userManager;
85
+        $this->groupManager = $groupManager;
86
+        $this->rootFolder = $rootFolder;
87
+    }
88
+
89
+    /**
90
+     * Return the identifier of this provider.
91
+     *
92
+     * @return string Containing only [a-zA-Z0-9]
93
+     */
94
+    public function identifier() {
95
+        return 'ocinternal';
96
+    }
97
+
98
+    /**
99
+     * Share a path
100
+     *
101
+     * @param \OCP\Share\IShare $share
102
+     * @return \OCP\Share\IShare The share object
103
+     * @throws ShareNotFound
104
+     * @throws \Exception
105
+     */
106
+    public function create(\OCP\Share\IShare $share) {
107
+        $qb = $this->dbConn->getQueryBuilder();
108
+
109
+        $qb->insert('share');
110
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
111
+
112
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
113
+            //Set the UID of the user we share with
114
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
115
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
116
+            //Set the GID of the group we share with
117
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
118
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
119
+            //Set the token of the share
120
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
121
+
122
+            //If a password is set store it
123
+            if ($share->getPassword() !== null) {
124
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
125
+            }
126
+
127
+            //If an expiration date is set store it
128
+            if ($share->getExpirationDate() !== null) {
129
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
130
+            }
131
+
132
+            if (method_exists($share, 'getParent')) {
133
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
134
+            }
135
+        } else {
136
+            throw new \Exception('invalid share type!');
137
+        }
138
+
139
+        // Set what is shares
140
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
141
+        if ($share->getNode() instanceof \OCP\Files\File) {
142
+            $qb->setParameter('itemType', 'file');
143
+        } else {
144
+            $qb->setParameter('itemType', 'folder');
145
+        }
146
+
147
+        // Set the file id
148
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
149
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
150
+
151
+        // set the permissions
152
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
153
+
154
+        // Set who created this share
155
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
156
+
157
+        // Set who is the owner of this file/folder (and this the owner of the share)
158
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
159
+
160
+        // Set the file target
161
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
162
+
163
+        // Set the time this share was created
164
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
165
+
166
+        // insert the data and fetch the id of the share
167
+        $this->dbConn->beginTransaction();
168
+        $qb->execute();
169
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
170
+
171
+        // Now fetch the inserted share and create a complete share object
172
+        $qb = $this->dbConn->getQueryBuilder();
173
+        $qb->select('*')
174
+            ->from('share')
175
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
176
+
177
+        $cursor = $qb->execute();
178
+        $data = $cursor->fetch();
179
+        $this->dbConn->commit();
180
+        $cursor->closeCursor();
181
+
182
+        if ($data === false) {
183
+            throw new ShareNotFound();
184
+        }
185
+
186
+        $mailSendValue = $share->getMailSend();
187
+        $data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
188
+
189
+        $share = $this->createShare($data);
190
+        return $share;
191
+    }
192
+
193
+    /**
194
+     * Update a share
195
+     *
196
+     * @param \OCP\Share\IShare $share
197
+     * @return \OCP\Share\IShare The share object
198
+     */
199
+    public function update(\OCP\Share\IShare $share) {
200
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
201
+            /*
202 202
 			 * We allow updating the recipient on user shares.
203 203
 			 */
204
-			$qb = $this->dbConn->getQueryBuilder();
205
-			$qb->update('share')
206
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
207
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
208
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
209
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
210
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
211
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
212
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
213
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
214
-				->execute();
215
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
216
-			$qb = $this->dbConn->getQueryBuilder();
217
-			$qb->update('share')
218
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
219
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
220
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
221
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
222
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
223
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
224
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
225
-				->execute();
226
-
227
-			/*
204
+            $qb = $this->dbConn->getQueryBuilder();
205
+            $qb->update('share')
206
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
207
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
208
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
209
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
210
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
211
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
212
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
213
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
214
+                ->execute();
215
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
216
+            $qb = $this->dbConn->getQueryBuilder();
217
+            $qb->update('share')
218
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
219
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
220
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
221
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
222
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
223
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
224
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
225
+                ->execute();
226
+
227
+            /*
228 228
 			 * Update all user defined group shares
229 229
 			 */
230
-			$qb = $this->dbConn->getQueryBuilder();
231
-			$qb->update('share')
232
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
233
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
234
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
235
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
236
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
237
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
238
-				->execute();
239
-
240
-			/*
230
+            $qb = $this->dbConn->getQueryBuilder();
231
+            $qb->update('share')
232
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
233
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
234
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
235
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
236
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
237
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
238
+                ->execute();
239
+
240
+            /*
241 241
 			 * Now update the permissions for all children that have not set it to 0
242 242
 			 */
243
-			$qb = $this->dbConn->getQueryBuilder();
244
-			$qb->update('share')
245
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
246
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
247
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
248
-				->execute();
249
-
250
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
251
-			$qb = $this->dbConn->getQueryBuilder();
252
-			$qb->update('share')
253
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
254
-				->set('password', $qb->createNamedParameter($share->getPassword()))
255
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
256
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
257
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
258
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
259
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
260
-				->set('token', $qb->createNamedParameter($share->getToken()))
261
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
262
-				->execute();
263
-		}
264
-
265
-		return $share;
266
-	}
267
-
268
-	/**
269
-	 * Get all children of this share
270
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
271
-	 *
272
-	 * @param \OCP\Share\IShare $parent
273
-	 * @return \OCP\Share\IShare[]
274
-	 */
275
-	public function getChildren(\OCP\Share\IShare $parent) {
276
-		$children = [];
277
-
278
-		$qb = $this->dbConn->getQueryBuilder();
279
-		$qb->select('*')
280
-			->from('share')
281
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
282
-			->andWhere(
283
-				$qb->expr()->in(
284
-					'share_type',
285
-					$qb->createNamedParameter([
286
-						\OCP\Share::SHARE_TYPE_USER,
287
-						\OCP\Share::SHARE_TYPE_GROUP,
288
-						\OCP\Share::SHARE_TYPE_LINK,
289
-					], IQueryBuilder::PARAM_INT_ARRAY)
290
-				)
291
-			)
292
-			->andWhere($qb->expr()->orX(
293
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
294
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
295
-			))
296
-			->orderBy('id');
297
-
298
-		$cursor = $qb->execute();
299
-		while($data = $cursor->fetch()) {
300
-			$children[] = $this->createShare($data);
301
-		}
302
-		$cursor->closeCursor();
303
-
304
-		return $children;
305
-	}
306
-
307
-	/**
308
-	 * Delete a share
309
-	 *
310
-	 * @param \OCP\Share\IShare $share
311
-	 */
312
-	public function delete(\OCP\Share\IShare $share) {
313
-		$qb = $this->dbConn->getQueryBuilder();
314
-		$qb->delete('share')
315
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
316
-
317
-		/*
243
+            $qb = $this->dbConn->getQueryBuilder();
244
+            $qb->update('share')
245
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
246
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
247
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
248
+                ->execute();
249
+
250
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
251
+            $qb = $this->dbConn->getQueryBuilder();
252
+            $qb->update('share')
253
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
254
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
255
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
256
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
257
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
258
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
259
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
260
+                ->set('token', $qb->createNamedParameter($share->getToken()))
261
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
262
+                ->execute();
263
+        }
264
+
265
+        return $share;
266
+    }
267
+
268
+    /**
269
+     * Get all children of this share
270
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
271
+     *
272
+     * @param \OCP\Share\IShare $parent
273
+     * @return \OCP\Share\IShare[]
274
+     */
275
+    public function getChildren(\OCP\Share\IShare $parent) {
276
+        $children = [];
277
+
278
+        $qb = $this->dbConn->getQueryBuilder();
279
+        $qb->select('*')
280
+            ->from('share')
281
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
282
+            ->andWhere(
283
+                $qb->expr()->in(
284
+                    'share_type',
285
+                    $qb->createNamedParameter([
286
+                        \OCP\Share::SHARE_TYPE_USER,
287
+                        \OCP\Share::SHARE_TYPE_GROUP,
288
+                        \OCP\Share::SHARE_TYPE_LINK,
289
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
290
+                )
291
+            )
292
+            ->andWhere($qb->expr()->orX(
293
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
294
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
295
+            ))
296
+            ->orderBy('id');
297
+
298
+        $cursor = $qb->execute();
299
+        while($data = $cursor->fetch()) {
300
+            $children[] = $this->createShare($data);
301
+        }
302
+        $cursor->closeCursor();
303
+
304
+        return $children;
305
+    }
306
+
307
+    /**
308
+     * Delete a share
309
+     *
310
+     * @param \OCP\Share\IShare $share
311
+     */
312
+    public function delete(\OCP\Share\IShare $share) {
313
+        $qb = $this->dbConn->getQueryBuilder();
314
+        $qb->delete('share')
315
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
316
+
317
+        /*
318 318
 		 * If the share is a group share delete all possible
319 319
 		 * user defined groups shares.
320 320
 		 */
321
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
322
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
323
-		}
324
-
325
-		$qb->execute();
326
-	}
327
-
328
-	/**
329
-	 * Unshare a share from the recipient. If this is a group share
330
-	 * this means we need a special entry in the share db.
331
-	 *
332
-	 * @param \OCP\Share\IShare $share
333
-	 * @param string $recipient UserId of recipient
334
-	 * @throws BackendError
335
-	 * @throws ProviderException
336
-	 */
337
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
338
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
339
-
340
-			$group = $this->groupManager->get($share->getSharedWith());
341
-			$user = $this->userManager->get($recipient);
342
-
343
-			if (is_null($group)) {
344
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
345
-			}
346
-
347
-			if (!$group->inGroup($user)) {
348
-				throw new ProviderException('Recipient not in receiving group');
349
-			}
350
-
351
-			// Try to fetch user specific share
352
-			$qb = $this->dbConn->getQueryBuilder();
353
-			$stmt = $qb->select('*')
354
-				->from('share')
355
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
356
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
357
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
358
-				->andWhere($qb->expr()->orX(
359
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
360
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
361
-				))
362
-				->execute();
363
-
364
-			$data = $stmt->fetch();
365
-
366
-			/*
321
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
322
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
323
+        }
324
+
325
+        $qb->execute();
326
+    }
327
+
328
+    /**
329
+     * Unshare a share from the recipient. If this is a group share
330
+     * this means we need a special entry in the share db.
331
+     *
332
+     * @param \OCP\Share\IShare $share
333
+     * @param string $recipient UserId of recipient
334
+     * @throws BackendError
335
+     * @throws ProviderException
336
+     */
337
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
338
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
339
+
340
+            $group = $this->groupManager->get($share->getSharedWith());
341
+            $user = $this->userManager->get($recipient);
342
+
343
+            if (is_null($group)) {
344
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
345
+            }
346
+
347
+            if (!$group->inGroup($user)) {
348
+                throw new ProviderException('Recipient not in receiving group');
349
+            }
350
+
351
+            // Try to fetch user specific share
352
+            $qb = $this->dbConn->getQueryBuilder();
353
+            $stmt = $qb->select('*')
354
+                ->from('share')
355
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
356
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
357
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
358
+                ->andWhere($qb->expr()->orX(
359
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
360
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
361
+                ))
362
+                ->execute();
363
+
364
+            $data = $stmt->fetch();
365
+
366
+            /*
367 367
 			 * Check if there already is a user specific group share.
368 368
 			 * If there is update it (if required).
369 369
 			 */
370
-			if ($data === false) {
371
-				$qb = $this->dbConn->getQueryBuilder();
372
-
373
-				$type = $share->getNodeType();
374
-
375
-				//Insert new share
376
-				$qb->insert('share')
377
-					->values([
378
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
379
-						'share_with' => $qb->createNamedParameter($recipient),
380
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
381
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
382
-						'parent' => $qb->createNamedParameter($share->getId()),
383
-						'item_type' => $qb->createNamedParameter($type),
384
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
385
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
386
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
387
-						'permissions' => $qb->createNamedParameter(0),
388
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
389
-					])->execute();
390
-
391
-			} else if ($data['permissions'] !== 0) {
392
-
393
-				// Update existing usergroup share
394
-				$qb = $this->dbConn->getQueryBuilder();
395
-				$qb->update('share')
396
-					->set('permissions', $qb->createNamedParameter(0))
397
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
398
-					->execute();
399
-			}
400
-
401
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
402
-
403
-			if ($share->getSharedWith() !== $recipient) {
404
-				throw new ProviderException('Recipient does not match');
405
-			}
406
-
407
-			// We can just delete user and link shares
408
-			$this->delete($share);
409
-		} else {
410
-			throw new ProviderException('Invalid shareType');
411
-		}
412
-	}
413
-
414
-	/**
415
-	 * @inheritdoc
416
-	 */
417
-	public function move(\OCP\Share\IShare $share, $recipient) {
418
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
419
-			// Just update the target
420
-			$qb = $this->dbConn->getQueryBuilder();
421
-			$qb->update('share')
422
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
423
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
424
-				->execute();
425
-
426
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
427
-
428
-			// Check if there is a usergroup share
429
-			$qb = $this->dbConn->getQueryBuilder();
430
-			$stmt = $qb->select('id')
431
-				->from('share')
432
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
433
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
434
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
435
-				->andWhere($qb->expr()->orX(
436
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
437
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
438
-				))
439
-				->setMaxResults(1)
440
-				->execute();
441
-
442
-			$data = $stmt->fetch();
443
-			$stmt->closeCursor();
444
-
445
-			if ($data === false) {
446
-				// No usergroup share yet. Create one.
447
-				$qb = $this->dbConn->getQueryBuilder();
448
-				$qb->insert('share')
449
-					->values([
450
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
451
-						'share_with' => $qb->createNamedParameter($recipient),
452
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
453
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
454
-						'parent' => $qb->createNamedParameter($share->getId()),
455
-						'item_type' => $qb->createNamedParameter($share->getNodeType()),
456
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
457
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
458
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
459
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
460
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
461
-					])->execute();
462
-			} else {
463
-				// Already a usergroup share. Update it.
464
-				$qb = $this->dbConn->getQueryBuilder();
465
-				$qb->update('share')
466
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
467
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
468
-					->execute();
469
-			}
470
-		}
471
-
472
-		return $share;
473
-	}
474
-
475
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
476
-		$qb = $this->dbConn->getQueryBuilder();
477
-		$qb->select('*')
478
-			->from('share', 's')
479
-			->andWhere($qb->expr()->orX(
480
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
481
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
482
-			));
483
-
484
-		$qb->andWhere($qb->expr()->orX(
485
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
486
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
487
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
488
-		));
489
-
490
-		/**
491
-		 * Reshares for this user are shares where they are the owner.
492
-		 */
493
-		if ($reshares === false) {
494
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
495
-		} else {
496
-			$qb->andWhere(
497
-				$qb->expr()->orX(
498
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
499
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
500
-				)
501
-			);
502
-		}
503
-
504
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
505
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
506
-
507
-		$qb->orderBy('id');
508
-
509
-		$cursor = $qb->execute();
510
-		$shares = [];
511
-		while ($data = $cursor->fetch()) {
512
-			$shares[$data['fileid']][] = $this->createShare($data);
513
-		}
514
-		$cursor->closeCursor();
515
-
516
-		return $shares;
517
-	}
518
-
519
-	/**
520
-	 * @inheritdoc
521
-	 */
522
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
523
-		$qb = $this->dbConn->getQueryBuilder();
524
-		$qb->select('*')
525
-			->from('share')
526
-			->andWhere($qb->expr()->orX(
527
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
528
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
529
-			));
530
-
531
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
532
-
533
-		/**
534
-		 * Reshares for this user are shares where they are the owner.
535
-		 */
536
-		if ($reshares === false) {
537
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
538
-		} else {
539
-			$qb->andWhere(
540
-				$qb->expr()->orX(
541
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
542
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
543
-				)
544
-			);
545
-		}
546
-
547
-		if ($node !== null) {
548
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
549
-		}
550
-
551
-		if ($limit !== -1) {
552
-			$qb->setMaxResults($limit);
553
-		}
554
-
555
-		$qb->setFirstResult($offset);
556
-		$qb->orderBy('id');
557
-
558
-		$cursor = $qb->execute();
559
-		$shares = [];
560
-		while($data = $cursor->fetch()) {
561
-			$shares[] = $this->createShare($data);
562
-		}
563
-		$cursor->closeCursor();
564
-
565
-		return $shares;
566
-	}
567
-
568
-	/**
569
-	 * @inheritdoc
570
-	 */
571
-	public function getShareById($id, $recipientId = null) {
572
-		$qb = $this->dbConn->getQueryBuilder();
573
-
574
-		$qb->select('*')
575
-			->from('share')
576
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
577
-			->andWhere(
578
-				$qb->expr()->in(
579
-					'share_type',
580
-					$qb->createNamedParameter([
581
-						\OCP\Share::SHARE_TYPE_USER,
582
-						\OCP\Share::SHARE_TYPE_GROUP,
583
-						\OCP\Share::SHARE_TYPE_LINK,
584
-					], IQueryBuilder::PARAM_INT_ARRAY)
585
-				)
586
-			)
587
-			->andWhere($qb->expr()->orX(
588
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
589
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
590
-			));
591
-
592
-		$cursor = $qb->execute();
593
-		$data = $cursor->fetch();
594
-		$cursor->closeCursor();
595
-
596
-		if ($data === false) {
597
-			throw new ShareNotFound();
598
-		}
599
-
600
-		try {
601
-			$share = $this->createShare($data);
602
-		} catch (InvalidShare $e) {
603
-			throw new ShareNotFound();
604
-		}
605
-
606
-		// If the recipient is set for a group share resolve to that user
607
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
608
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
609
-		}
610
-
611
-		return $share;
612
-	}
613
-
614
-	/**
615
-	 * Get shares for a given path
616
-	 *
617
-	 * @param \OCP\Files\Node $path
618
-	 * @return \OCP\Share\IShare[]
619
-	 */
620
-	public function getSharesByPath(Node $path) {
621
-		$qb = $this->dbConn->getQueryBuilder();
622
-
623
-		$cursor = $qb->select('*')
624
-			->from('share')
625
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
626
-			->andWhere(
627
-				$qb->expr()->orX(
628
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
629
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
630
-				)
631
-			)
632
-			->andWhere($qb->expr()->orX(
633
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
634
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
635
-			))
636
-			->execute();
637
-
638
-		$shares = [];
639
-		while($data = $cursor->fetch()) {
640
-			$shares[] = $this->createShare($data);
641
-		}
642
-		$cursor->closeCursor();
643
-
644
-		return $shares;
645
-	}
646
-
647
-	/**
648
-	 * Returns whether the given database result can be interpreted as
649
-	 * a share with accessible file (not trashed, not deleted)
650
-	 */
651
-	private function isAccessibleResult($data) {
652
-		// exclude shares leading to deleted file entries
653
-		if ($data['fileid'] === null) {
654
-			return false;
655
-		}
656
-
657
-		// exclude shares leading to trashbin on home storages
658
-		$pathSections = explode('/', $data['path'], 2);
659
-		// FIXME: would not detect rare md5'd home storage case properly
660
-		if ($pathSections[0] !== 'files'
661
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
662
-			return false;
663
-		}
664
-		return true;
665
-	}
666
-
667
-	/**
668
-	 * @inheritdoc
669
-	 */
670
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
671
-		/** @var Share[] $shares */
672
-		$shares = [];
673
-
674
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
675
-			//Get shares directly with this user
676
-			$qb = $this->dbConn->getQueryBuilder();
677
-			$qb->select('s.*',
678
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
679
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
680
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
681
-			)
682
-				->selectAlias('st.id', 'storage_string_id')
683
-				->from('share', 's')
684
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
685
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
686
-
687
-			// Order by id
688
-			$qb->orderBy('s.id');
689
-
690
-			// Set limit and offset
691
-			if ($limit !== -1) {
692
-				$qb->setMaxResults($limit);
693
-			}
694
-			$qb->setFirstResult($offset);
695
-
696
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
697
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
698
-				->andWhere($qb->expr()->orX(
699
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
700
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
701
-				));
702
-
703
-			// Filter by node if provided
704
-			if ($node !== null) {
705
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
706
-			}
707
-
708
-			$cursor = $qb->execute();
709
-
710
-			while($data = $cursor->fetch()) {
711
-				if ($this->isAccessibleResult($data)) {
712
-					$shares[] = $this->createShare($data);
713
-				}
714
-			}
715
-			$cursor->closeCursor();
716
-
717
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
718
-			$user = $this->userManager->get($userId);
719
-			$allGroups = $this->groupManager->getUserGroups($user);
720
-
721
-			/** @var Share[] $shares2 */
722
-			$shares2 = [];
723
-
724
-			$start = 0;
725
-			while(true) {
726
-				$groups = array_slice($allGroups, $start, 100);
727
-				$start += 100;
728
-
729
-				if ($groups === []) {
730
-					break;
731
-				}
732
-
733
-				$qb = $this->dbConn->getQueryBuilder();
734
-				$qb->select('s.*',
735
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
736
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
737
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
738
-				)
739
-					->selectAlias('st.id', 'storage_string_id')
740
-					->from('share', 's')
741
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
742
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
743
-					->orderBy('s.id')
744
-					->setFirstResult(0);
745
-
746
-				if ($limit !== -1) {
747
-					$qb->setMaxResults($limit - count($shares));
748
-				}
749
-
750
-				// Filter by node if provided
751
-				if ($node !== null) {
752
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
753
-				}
754
-
755
-
756
-				$groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
757
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
758
-
759
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
760
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
761
-						$groups,
762
-						IQueryBuilder::PARAM_STR_ARRAY
763
-					)))
764
-					->andWhere($qb->expr()->orX(
765
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
766
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
767
-					));
768
-
769
-				$cursor = $qb->execute();
770
-				while($data = $cursor->fetch()) {
771
-					if ($offset > 0) {
772
-						$offset--;
773
-						continue;
774
-					}
775
-
776
-					if ($this->isAccessibleResult($data)) {
777
-						$shares2[] = $this->createShare($data);
778
-					}
779
-				}
780
-				$cursor->closeCursor();
781
-			}
782
-
783
-			/*
370
+            if ($data === false) {
371
+                $qb = $this->dbConn->getQueryBuilder();
372
+
373
+                $type = $share->getNodeType();
374
+
375
+                //Insert new share
376
+                $qb->insert('share')
377
+                    ->values([
378
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
379
+                        'share_with' => $qb->createNamedParameter($recipient),
380
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
381
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
382
+                        'parent' => $qb->createNamedParameter($share->getId()),
383
+                        'item_type' => $qb->createNamedParameter($type),
384
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
385
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
386
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
387
+                        'permissions' => $qb->createNamedParameter(0),
388
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
389
+                    ])->execute();
390
+
391
+            } else if ($data['permissions'] !== 0) {
392
+
393
+                // Update existing usergroup share
394
+                $qb = $this->dbConn->getQueryBuilder();
395
+                $qb->update('share')
396
+                    ->set('permissions', $qb->createNamedParameter(0))
397
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
398
+                    ->execute();
399
+            }
400
+
401
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
402
+
403
+            if ($share->getSharedWith() !== $recipient) {
404
+                throw new ProviderException('Recipient does not match');
405
+            }
406
+
407
+            // We can just delete user and link shares
408
+            $this->delete($share);
409
+        } else {
410
+            throw new ProviderException('Invalid shareType');
411
+        }
412
+    }
413
+
414
+    /**
415
+     * @inheritdoc
416
+     */
417
+    public function move(\OCP\Share\IShare $share, $recipient) {
418
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
419
+            // Just update the target
420
+            $qb = $this->dbConn->getQueryBuilder();
421
+            $qb->update('share')
422
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
423
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
424
+                ->execute();
425
+
426
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
427
+
428
+            // Check if there is a usergroup share
429
+            $qb = $this->dbConn->getQueryBuilder();
430
+            $stmt = $qb->select('id')
431
+                ->from('share')
432
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
433
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
434
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
435
+                ->andWhere($qb->expr()->orX(
436
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
437
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
438
+                ))
439
+                ->setMaxResults(1)
440
+                ->execute();
441
+
442
+            $data = $stmt->fetch();
443
+            $stmt->closeCursor();
444
+
445
+            if ($data === false) {
446
+                // No usergroup share yet. Create one.
447
+                $qb = $this->dbConn->getQueryBuilder();
448
+                $qb->insert('share')
449
+                    ->values([
450
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
451
+                        'share_with' => $qb->createNamedParameter($recipient),
452
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
453
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
454
+                        'parent' => $qb->createNamedParameter($share->getId()),
455
+                        'item_type' => $qb->createNamedParameter($share->getNodeType()),
456
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
457
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
458
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
459
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
460
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
461
+                    ])->execute();
462
+            } else {
463
+                // Already a usergroup share. Update it.
464
+                $qb = $this->dbConn->getQueryBuilder();
465
+                $qb->update('share')
466
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
467
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
468
+                    ->execute();
469
+            }
470
+        }
471
+
472
+        return $share;
473
+    }
474
+
475
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
476
+        $qb = $this->dbConn->getQueryBuilder();
477
+        $qb->select('*')
478
+            ->from('share', 's')
479
+            ->andWhere($qb->expr()->orX(
480
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
481
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
482
+            ));
483
+
484
+        $qb->andWhere($qb->expr()->orX(
485
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
486
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
487
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
488
+        ));
489
+
490
+        /**
491
+         * Reshares for this user are shares where they are the owner.
492
+         */
493
+        if ($reshares === false) {
494
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
495
+        } else {
496
+            $qb->andWhere(
497
+                $qb->expr()->orX(
498
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
499
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
500
+                )
501
+            );
502
+        }
503
+
504
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
505
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
506
+
507
+        $qb->orderBy('id');
508
+
509
+        $cursor = $qb->execute();
510
+        $shares = [];
511
+        while ($data = $cursor->fetch()) {
512
+            $shares[$data['fileid']][] = $this->createShare($data);
513
+        }
514
+        $cursor->closeCursor();
515
+
516
+        return $shares;
517
+    }
518
+
519
+    /**
520
+     * @inheritdoc
521
+     */
522
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
523
+        $qb = $this->dbConn->getQueryBuilder();
524
+        $qb->select('*')
525
+            ->from('share')
526
+            ->andWhere($qb->expr()->orX(
527
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
528
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
529
+            ));
530
+
531
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
532
+
533
+        /**
534
+         * Reshares for this user are shares where they are the owner.
535
+         */
536
+        if ($reshares === false) {
537
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
538
+        } else {
539
+            $qb->andWhere(
540
+                $qb->expr()->orX(
541
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
542
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
543
+                )
544
+            );
545
+        }
546
+
547
+        if ($node !== null) {
548
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
549
+        }
550
+
551
+        if ($limit !== -1) {
552
+            $qb->setMaxResults($limit);
553
+        }
554
+
555
+        $qb->setFirstResult($offset);
556
+        $qb->orderBy('id');
557
+
558
+        $cursor = $qb->execute();
559
+        $shares = [];
560
+        while($data = $cursor->fetch()) {
561
+            $shares[] = $this->createShare($data);
562
+        }
563
+        $cursor->closeCursor();
564
+
565
+        return $shares;
566
+    }
567
+
568
+    /**
569
+     * @inheritdoc
570
+     */
571
+    public function getShareById($id, $recipientId = null) {
572
+        $qb = $this->dbConn->getQueryBuilder();
573
+
574
+        $qb->select('*')
575
+            ->from('share')
576
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
577
+            ->andWhere(
578
+                $qb->expr()->in(
579
+                    'share_type',
580
+                    $qb->createNamedParameter([
581
+                        \OCP\Share::SHARE_TYPE_USER,
582
+                        \OCP\Share::SHARE_TYPE_GROUP,
583
+                        \OCP\Share::SHARE_TYPE_LINK,
584
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
585
+                )
586
+            )
587
+            ->andWhere($qb->expr()->orX(
588
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
589
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
590
+            ));
591
+
592
+        $cursor = $qb->execute();
593
+        $data = $cursor->fetch();
594
+        $cursor->closeCursor();
595
+
596
+        if ($data === false) {
597
+            throw new ShareNotFound();
598
+        }
599
+
600
+        try {
601
+            $share = $this->createShare($data);
602
+        } catch (InvalidShare $e) {
603
+            throw new ShareNotFound();
604
+        }
605
+
606
+        // If the recipient is set for a group share resolve to that user
607
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
608
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
609
+        }
610
+
611
+        return $share;
612
+    }
613
+
614
+    /**
615
+     * Get shares for a given path
616
+     *
617
+     * @param \OCP\Files\Node $path
618
+     * @return \OCP\Share\IShare[]
619
+     */
620
+    public function getSharesByPath(Node $path) {
621
+        $qb = $this->dbConn->getQueryBuilder();
622
+
623
+        $cursor = $qb->select('*')
624
+            ->from('share')
625
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
626
+            ->andWhere(
627
+                $qb->expr()->orX(
628
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
629
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
630
+                )
631
+            )
632
+            ->andWhere($qb->expr()->orX(
633
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
634
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
635
+            ))
636
+            ->execute();
637
+
638
+        $shares = [];
639
+        while($data = $cursor->fetch()) {
640
+            $shares[] = $this->createShare($data);
641
+        }
642
+        $cursor->closeCursor();
643
+
644
+        return $shares;
645
+    }
646
+
647
+    /**
648
+     * Returns whether the given database result can be interpreted as
649
+     * a share with accessible file (not trashed, not deleted)
650
+     */
651
+    private function isAccessibleResult($data) {
652
+        // exclude shares leading to deleted file entries
653
+        if ($data['fileid'] === null) {
654
+            return false;
655
+        }
656
+
657
+        // exclude shares leading to trashbin on home storages
658
+        $pathSections = explode('/', $data['path'], 2);
659
+        // FIXME: would not detect rare md5'd home storage case properly
660
+        if ($pathSections[0] !== 'files'
661
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
662
+            return false;
663
+        }
664
+        return true;
665
+    }
666
+
667
+    /**
668
+     * @inheritdoc
669
+     */
670
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
671
+        /** @var Share[] $shares */
672
+        $shares = [];
673
+
674
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
675
+            //Get shares directly with this user
676
+            $qb = $this->dbConn->getQueryBuilder();
677
+            $qb->select('s.*',
678
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
679
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
680
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
681
+            )
682
+                ->selectAlias('st.id', 'storage_string_id')
683
+                ->from('share', 's')
684
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
685
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
686
+
687
+            // Order by id
688
+            $qb->orderBy('s.id');
689
+
690
+            // Set limit and offset
691
+            if ($limit !== -1) {
692
+                $qb->setMaxResults($limit);
693
+            }
694
+            $qb->setFirstResult($offset);
695
+
696
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
697
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
698
+                ->andWhere($qb->expr()->orX(
699
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
700
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
701
+                ));
702
+
703
+            // Filter by node if provided
704
+            if ($node !== null) {
705
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
706
+            }
707
+
708
+            $cursor = $qb->execute();
709
+
710
+            while($data = $cursor->fetch()) {
711
+                if ($this->isAccessibleResult($data)) {
712
+                    $shares[] = $this->createShare($data);
713
+                }
714
+            }
715
+            $cursor->closeCursor();
716
+
717
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
718
+            $user = $this->userManager->get($userId);
719
+            $allGroups = $this->groupManager->getUserGroups($user);
720
+
721
+            /** @var Share[] $shares2 */
722
+            $shares2 = [];
723
+
724
+            $start = 0;
725
+            while(true) {
726
+                $groups = array_slice($allGroups, $start, 100);
727
+                $start += 100;
728
+
729
+                if ($groups === []) {
730
+                    break;
731
+                }
732
+
733
+                $qb = $this->dbConn->getQueryBuilder();
734
+                $qb->select('s.*',
735
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
736
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
737
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
738
+                )
739
+                    ->selectAlias('st.id', 'storage_string_id')
740
+                    ->from('share', 's')
741
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
742
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
743
+                    ->orderBy('s.id')
744
+                    ->setFirstResult(0);
745
+
746
+                if ($limit !== -1) {
747
+                    $qb->setMaxResults($limit - count($shares));
748
+                }
749
+
750
+                // Filter by node if provided
751
+                if ($node !== null) {
752
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
753
+                }
754
+
755
+
756
+                $groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
757
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
758
+
759
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
760
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
761
+                        $groups,
762
+                        IQueryBuilder::PARAM_STR_ARRAY
763
+                    )))
764
+                    ->andWhere($qb->expr()->orX(
765
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
766
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
767
+                    ));
768
+
769
+                $cursor = $qb->execute();
770
+                while($data = $cursor->fetch()) {
771
+                    if ($offset > 0) {
772
+                        $offset--;
773
+                        continue;
774
+                    }
775
+
776
+                    if ($this->isAccessibleResult($data)) {
777
+                        $shares2[] = $this->createShare($data);
778
+                    }
779
+                }
780
+                $cursor->closeCursor();
781
+            }
782
+
783
+            /*
784 784
  			 * Resolve all group shares to user specific shares
785 785
  			 */
786
-			$shares = $this->resolveGroupShares($shares2, $userId);
787
-		} else {
788
-			throw new BackendError('Invalid backend');
789
-		}
790
-
791
-
792
-		return $shares;
793
-	}
794
-
795
-	/**
796
-	 * Get a share by token
797
-	 *
798
-	 * @param string $token
799
-	 * @return \OCP\Share\IShare
800
-	 * @throws ShareNotFound
801
-	 */
802
-	public function getShareByToken($token) {
803
-		$qb = $this->dbConn->getQueryBuilder();
804
-
805
-		$cursor = $qb->select('*')
806
-			->from('share')
807
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
808
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
809
-			->andWhere($qb->expr()->orX(
810
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
811
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
812
-			))
813
-			->execute();
814
-
815
-		$data = $cursor->fetch();
816
-
817
-		if ($data === false) {
818
-			throw new ShareNotFound();
819
-		}
820
-
821
-		try {
822
-			$share = $this->createShare($data);
823
-		} catch (InvalidShare $e) {
824
-			throw new ShareNotFound();
825
-		}
826
-
827
-		return $share;
828
-	}
829
-
830
-	/**
831
-	 * Create a share object from an database row
832
-	 *
833
-	 * @param mixed[] $data
834
-	 * @return \OCP\Share\IShare
835
-	 * @throws InvalidShare
836
-	 */
837
-	private function createShare($data) {
838
-		$share = new Share($this->rootFolder, $this->userManager);
839
-		$share->setId((int)$data['id'])
840
-			->setShareType((int)$data['share_type'])
841
-			->setPermissions((int)$data['permissions'])
842
-			->setTarget($data['file_target'])
843
-			->setMailSend((bool)$data['mail_send']);
844
-
845
-		$shareTime = new \DateTime();
846
-		$shareTime->setTimestamp((int)$data['stime']);
847
-		$share->setShareTime($shareTime);
848
-
849
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
850
-			$share->setSharedWith($data['share_with']);
851
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
852
-			$share->setSharedWith($data['share_with']);
853
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
854
-			$share->setPassword($data['password']);
855
-			$share->setToken($data['token']);
856
-		}
857
-
858
-		$share->setSharedBy($data['uid_initiator']);
859
-		$share->setShareOwner($data['uid_owner']);
860
-
861
-		$share->setNodeId((int)$data['file_source']);
862
-		$share->setNodeType($data['item_type']);
863
-
864
-		if ($data['expiration'] !== null) {
865
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
866
-			$share->setExpirationDate($expiration);
867
-		}
868
-
869
-		if (isset($data['f_permissions'])) {
870
-			$entryData = $data;
871
-			$entryData['permissions'] = $entryData['f_permissions'];
872
-			$entryData['parent'] = $entryData['f_parent'];
873
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
874
-				\OC::$server->getMimeTypeLoader()));
875
-		}
876
-
877
-		$share->setProviderId($this->identifier());
878
-
879
-		return $share;
880
-	}
881
-
882
-	/**
883
-	 * @param Share[] $shares
884
-	 * @param $userId
885
-	 * @return Share[] The updates shares if no update is found for a share return the original
886
-	 */
887
-	private function resolveGroupShares($shares, $userId) {
888
-		$result = [];
889
-
890
-		$start = 0;
891
-		while(true) {
892
-			/** @var Share[] $shareSlice */
893
-			$shareSlice = array_slice($shares, $start, 100);
894
-			$start += 100;
895
-
896
-			if ($shareSlice === []) {
897
-				break;
898
-			}
899
-
900
-			/** @var int[] $ids */
901
-			$ids = [];
902
-			/** @var Share[] $shareMap */
903
-			$shareMap = [];
904
-
905
-			foreach ($shareSlice as $share) {
906
-				$ids[] = (int)$share->getId();
907
-				$shareMap[$share->getId()] = $share;
908
-			}
909
-
910
-			$qb = $this->dbConn->getQueryBuilder();
911
-
912
-			$query = $qb->select('*')
913
-				->from('share')
914
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
915
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
916
-				->andWhere($qb->expr()->orX(
917
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
918
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
919
-				));
920
-
921
-			$stmt = $query->execute();
922
-
923
-			while($data = $stmt->fetch()) {
924
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
925
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
926
-			}
927
-
928
-			$stmt->closeCursor();
929
-
930
-			foreach ($shareMap as $share) {
931
-				$result[] = $share;
932
-			}
933
-		}
934
-
935
-		return $result;
936
-	}
937
-
938
-	/**
939
-	 * A user is deleted from the system
940
-	 * So clean up the relevant shares.
941
-	 *
942
-	 * @param string $uid
943
-	 * @param int $shareType
944
-	 */
945
-	public function userDeleted($uid, $shareType) {
946
-		$qb = $this->dbConn->getQueryBuilder();
947
-
948
-		$qb->delete('share');
949
-
950
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
951
-			/*
786
+            $shares = $this->resolveGroupShares($shares2, $userId);
787
+        } else {
788
+            throw new BackendError('Invalid backend');
789
+        }
790
+
791
+
792
+        return $shares;
793
+    }
794
+
795
+    /**
796
+     * Get a share by token
797
+     *
798
+     * @param string $token
799
+     * @return \OCP\Share\IShare
800
+     * @throws ShareNotFound
801
+     */
802
+    public function getShareByToken($token) {
803
+        $qb = $this->dbConn->getQueryBuilder();
804
+
805
+        $cursor = $qb->select('*')
806
+            ->from('share')
807
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
808
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
809
+            ->andWhere($qb->expr()->orX(
810
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
811
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
812
+            ))
813
+            ->execute();
814
+
815
+        $data = $cursor->fetch();
816
+
817
+        if ($data === false) {
818
+            throw new ShareNotFound();
819
+        }
820
+
821
+        try {
822
+            $share = $this->createShare($data);
823
+        } catch (InvalidShare $e) {
824
+            throw new ShareNotFound();
825
+        }
826
+
827
+        return $share;
828
+    }
829
+
830
+    /**
831
+     * Create a share object from an database row
832
+     *
833
+     * @param mixed[] $data
834
+     * @return \OCP\Share\IShare
835
+     * @throws InvalidShare
836
+     */
837
+    private function createShare($data) {
838
+        $share = new Share($this->rootFolder, $this->userManager);
839
+        $share->setId((int)$data['id'])
840
+            ->setShareType((int)$data['share_type'])
841
+            ->setPermissions((int)$data['permissions'])
842
+            ->setTarget($data['file_target'])
843
+            ->setMailSend((bool)$data['mail_send']);
844
+
845
+        $shareTime = new \DateTime();
846
+        $shareTime->setTimestamp((int)$data['stime']);
847
+        $share->setShareTime($shareTime);
848
+
849
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
850
+            $share->setSharedWith($data['share_with']);
851
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
852
+            $share->setSharedWith($data['share_with']);
853
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
854
+            $share->setPassword($data['password']);
855
+            $share->setToken($data['token']);
856
+        }
857
+
858
+        $share->setSharedBy($data['uid_initiator']);
859
+        $share->setShareOwner($data['uid_owner']);
860
+
861
+        $share->setNodeId((int)$data['file_source']);
862
+        $share->setNodeType($data['item_type']);
863
+
864
+        if ($data['expiration'] !== null) {
865
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
866
+            $share->setExpirationDate($expiration);
867
+        }
868
+
869
+        if (isset($data['f_permissions'])) {
870
+            $entryData = $data;
871
+            $entryData['permissions'] = $entryData['f_permissions'];
872
+            $entryData['parent'] = $entryData['f_parent'];
873
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
874
+                \OC::$server->getMimeTypeLoader()));
875
+        }
876
+
877
+        $share->setProviderId($this->identifier());
878
+
879
+        return $share;
880
+    }
881
+
882
+    /**
883
+     * @param Share[] $shares
884
+     * @param $userId
885
+     * @return Share[] The updates shares if no update is found for a share return the original
886
+     */
887
+    private function resolveGroupShares($shares, $userId) {
888
+        $result = [];
889
+
890
+        $start = 0;
891
+        while(true) {
892
+            /** @var Share[] $shareSlice */
893
+            $shareSlice = array_slice($shares, $start, 100);
894
+            $start += 100;
895
+
896
+            if ($shareSlice === []) {
897
+                break;
898
+            }
899
+
900
+            /** @var int[] $ids */
901
+            $ids = [];
902
+            /** @var Share[] $shareMap */
903
+            $shareMap = [];
904
+
905
+            foreach ($shareSlice as $share) {
906
+                $ids[] = (int)$share->getId();
907
+                $shareMap[$share->getId()] = $share;
908
+            }
909
+
910
+            $qb = $this->dbConn->getQueryBuilder();
911
+
912
+            $query = $qb->select('*')
913
+                ->from('share')
914
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
915
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
916
+                ->andWhere($qb->expr()->orX(
917
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
918
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
919
+                ));
920
+
921
+            $stmt = $query->execute();
922
+
923
+            while($data = $stmt->fetch()) {
924
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
925
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
926
+            }
927
+
928
+            $stmt->closeCursor();
929
+
930
+            foreach ($shareMap as $share) {
931
+                $result[] = $share;
932
+            }
933
+        }
934
+
935
+        return $result;
936
+    }
937
+
938
+    /**
939
+     * A user is deleted from the system
940
+     * So clean up the relevant shares.
941
+     *
942
+     * @param string $uid
943
+     * @param int $shareType
944
+     */
945
+    public function userDeleted($uid, $shareType) {
946
+        $qb = $this->dbConn->getQueryBuilder();
947
+
948
+        $qb->delete('share');
949
+
950
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
951
+            /*
952 952
 			 * Delete all user shares that are owned by this user
953 953
 			 * or that are received by this user
954 954
 			 */
955 955
 
956
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
956
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
957 957
 
958
-			$qb->andWhere(
959
-				$qb->expr()->orX(
960
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
961
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
962
-				)
963
-			);
964
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
965
-			/*
958
+            $qb->andWhere(
959
+                $qb->expr()->orX(
960
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
961
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
962
+                )
963
+            );
964
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
965
+            /*
966 966
 			 * Delete all group shares that are owned by this user
967 967
 			 * Or special user group shares that are received by this user
968 968
 			 */
969
-			$qb->where(
970
-				$qb->expr()->andX(
971
-					$qb->expr()->orX(
972
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
973
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
974
-					),
975
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
976
-				)
977
-			);
978
-
979
-			$qb->orWhere(
980
-				$qb->expr()->andX(
981
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
982
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
983
-				)
984
-			);
985
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
986
-			/*
969
+            $qb->where(
970
+                $qb->expr()->andX(
971
+                    $qb->expr()->orX(
972
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
973
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
974
+                    ),
975
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
976
+                )
977
+            );
978
+
979
+            $qb->orWhere(
980
+                $qb->expr()->andX(
981
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
982
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
983
+                )
984
+            );
985
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
986
+            /*
987 987
 			 * Delete all link shares owned by this user.
988 988
 			 * And all link shares initiated by this user (until #22327 is in)
989 989
 			 */
990
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
991
-
992
-			$qb->andWhere(
993
-				$qb->expr()->orX(
994
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
995
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
996
-				)
997
-			);
998
-		}
999
-
1000
-		$qb->execute();
1001
-	}
1002
-
1003
-	/**
1004
-	 * Delete all shares received by this group. As well as any custom group
1005
-	 * shares for group members.
1006
-	 *
1007
-	 * @param string $gid
1008
-	 */
1009
-	public function groupDeleted($gid) {
1010
-		/*
990
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
991
+
992
+            $qb->andWhere(
993
+                $qb->expr()->orX(
994
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
995
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
996
+                )
997
+            );
998
+        }
999
+
1000
+        $qb->execute();
1001
+    }
1002
+
1003
+    /**
1004
+     * Delete all shares received by this group. As well as any custom group
1005
+     * shares for group members.
1006
+     *
1007
+     * @param string $gid
1008
+     */
1009
+    public function groupDeleted($gid) {
1010
+        /*
1011 1011
 		 * First delete all custom group shares for group members
1012 1012
 		 */
1013
-		$qb = $this->dbConn->getQueryBuilder();
1014
-		$qb->select('id')
1015
-			->from('share')
1016
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1017
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1018
-
1019
-		$cursor = $qb->execute();
1020
-		$ids = [];
1021
-		while($row = $cursor->fetch()) {
1022
-			$ids[] = (int)$row['id'];
1023
-		}
1024
-		$cursor->closeCursor();
1025
-
1026
-		if (!empty($ids)) {
1027
-			$chunks = array_chunk($ids, 100);
1028
-			foreach ($chunks as $chunk) {
1029
-				$qb->delete('share')
1030
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1031
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1032
-				$qb->execute();
1033
-			}
1034
-		}
1035
-
1036
-		/*
1013
+        $qb = $this->dbConn->getQueryBuilder();
1014
+        $qb->select('id')
1015
+            ->from('share')
1016
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1017
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1018
+
1019
+        $cursor = $qb->execute();
1020
+        $ids = [];
1021
+        while($row = $cursor->fetch()) {
1022
+            $ids[] = (int)$row['id'];
1023
+        }
1024
+        $cursor->closeCursor();
1025
+
1026
+        if (!empty($ids)) {
1027
+            $chunks = array_chunk($ids, 100);
1028
+            foreach ($chunks as $chunk) {
1029
+                $qb->delete('share')
1030
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1031
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1032
+                $qb->execute();
1033
+            }
1034
+        }
1035
+
1036
+        /*
1037 1037
 		 * Now delete all the group shares
1038 1038
 		 */
1039
-		$qb = $this->dbConn->getQueryBuilder();
1040
-		$qb->delete('share')
1041
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1042
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1043
-		$qb->execute();
1044
-	}
1045
-
1046
-	/**
1047
-	 * Delete custom group shares to this group for this user
1048
-	 *
1049
-	 * @param string $uid
1050
-	 * @param string $gid
1051
-	 */
1052
-	public function userDeletedFromGroup($uid, $gid) {
1053
-		/*
1039
+        $qb = $this->dbConn->getQueryBuilder();
1040
+        $qb->delete('share')
1041
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1042
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1043
+        $qb->execute();
1044
+    }
1045
+
1046
+    /**
1047
+     * Delete custom group shares to this group for this user
1048
+     *
1049
+     * @param string $uid
1050
+     * @param string $gid
1051
+     */
1052
+    public function userDeletedFromGroup($uid, $gid) {
1053
+        /*
1054 1054
 		 * Get all group shares
1055 1055
 		 */
1056
-		$qb = $this->dbConn->getQueryBuilder();
1057
-		$qb->select('id')
1058
-			->from('share')
1059
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1060
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1061
-
1062
-		$cursor = $qb->execute();
1063
-		$ids = [];
1064
-		while($row = $cursor->fetch()) {
1065
-			$ids[] = (int)$row['id'];
1066
-		}
1067
-		$cursor->closeCursor();
1068
-
1069
-		if (!empty($ids)) {
1070
-			$chunks = array_chunk($ids, 100);
1071
-			foreach ($chunks as $chunk) {
1072
-				/*
1056
+        $qb = $this->dbConn->getQueryBuilder();
1057
+        $qb->select('id')
1058
+            ->from('share')
1059
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1060
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1061
+
1062
+        $cursor = $qb->execute();
1063
+        $ids = [];
1064
+        while($row = $cursor->fetch()) {
1065
+            $ids[] = (int)$row['id'];
1066
+        }
1067
+        $cursor->closeCursor();
1068
+
1069
+        if (!empty($ids)) {
1070
+            $chunks = array_chunk($ids, 100);
1071
+            foreach ($chunks as $chunk) {
1072
+                /*
1073 1073
 				 * Delete all special shares wit this users for the found group shares
1074 1074
 				 */
1075
-				$qb->delete('share')
1076
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1077
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1078
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1079
-				$qb->execute();
1080
-			}
1081
-		}
1082
-	}
1083
-
1084
-	/**
1085
-	 * @inheritdoc
1086
-	 */
1087
-	public function getAccessList($nodes, $currentAccess) {
1088
-		$ids = [];
1089
-		foreach ($nodes as $node) {
1090
-			$ids[] = $node->getId();
1091
-		}
1092
-
1093
-		$qb = $this->dbConn->getQueryBuilder();
1094
-
1095
-		$or = $qb->expr()->orX(
1096
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1097
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1098
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1099
-		);
1100
-
1101
-		if ($currentAccess) {
1102
-			$or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1103
-		}
1104
-
1105
-		$qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1106
-			->from('share')
1107
-			->where(
1108
-				$or
1109
-			)
1110
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1111
-			->andWhere($qb->expr()->orX(
1112
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1113
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1114
-			));
1115
-		$cursor = $qb->execute();
1116
-
1117
-		$users = [];
1118
-		$link = false;
1119
-		while($row = $cursor->fetch()) {
1120
-			$type = (int)$row['share_type'];
1121
-			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1122
-				$uid = $row['share_with'];
1123
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1124
-				$users[$uid][$row['id']] = $row;
1125
-			} else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1126
-				$gid = $row['share_with'];
1127
-				$group = $this->groupManager->get($gid);
1128
-
1129
-				if ($group === null) {
1130
-					continue;
1131
-				}
1132
-
1133
-				$userList = $group->getUsers();
1134
-				foreach ($userList as $user) {
1135
-					$uid = $user->getUID();
1136
-					$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1137
-					$users[$uid][$row['id']] = $row;
1138
-				}
1139
-			} else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1140
-				$link = true;
1141
-			} else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1142
-				$uid = $row['share_with'];
1143
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1144
-				$users[$uid][$row['id']] = $row;
1145
-			}
1146
-		}
1147
-		$cursor->closeCursor();
1148
-
1149
-		if ($currentAccess === true) {
1150
-			$users = array_map([$this, 'filterSharesOfUser'], $users);
1151
-			$users = array_filter($users);
1152
-		} else {
1153
-			$users = array_keys($users);
1154
-		}
1155
-
1156
-		return ['users' => $users, 'public' => $link];
1157
-	}
1158
-
1159
-	/**
1160
-	 * For each user the path with the fewest slashes is returned
1161
-	 * @param array $shares
1162
-	 * @return array
1163
-	 */
1164
-	protected function filterSharesOfUser(array $shares) {
1165
-		// Group shares when the user has a share exception
1166
-		foreach ($shares as $id => $share) {
1167
-			$type = (int) $share['share_type'];
1168
-			$permissions = (int) $share['permissions'];
1169
-
1170
-			if ($type === self::SHARE_TYPE_USERGROUP) {
1171
-				unset($shares[$share['parent']]);
1172
-
1173
-				if ($permissions === 0) {
1174
-					unset($shares[$id]);
1175
-				}
1176
-			}
1177
-		}
1178
-
1179
-		$best = [];
1180
-		$bestDepth = 0;
1181
-		foreach ($shares as $id => $share) {
1182
-			$depth = substr_count($share['file_target'], '/');
1183
-			if (empty($best) || $depth < $bestDepth) {
1184
-				$bestDepth = $depth;
1185
-				$best = [
1186
-					'node_id' => $share['file_source'],
1187
-					'node_path' => $share['file_target'],
1188
-				];
1189
-			}
1190
-		}
1191
-
1192
-		return $best;
1193
-	}
1075
+                $qb->delete('share')
1076
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1077
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1078
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1079
+                $qb->execute();
1080
+            }
1081
+        }
1082
+    }
1083
+
1084
+    /**
1085
+     * @inheritdoc
1086
+     */
1087
+    public function getAccessList($nodes, $currentAccess) {
1088
+        $ids = [];
1089
+        foreach ($nodes as $node) {
1090
+            $ids[] = $node->getId();
1091
+        }
1092
+
1093
+        $qb = $this->dbConn->getQueryBuilder();
1094
+
1095
+        $or = $qb->expr()->orX(
1096
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1097
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1098
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1099
+        );
1100
+
1101
+        if ($currentAccess) {
1102
+            $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1103
+        }
1104
+
1105
+        $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1106
+            ->from('share')
1107
+            ->where(
1108
+                $or
1109
+            )
1110
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1111
+            ->andWhere($qb->expr()->orX(
1112
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1113
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1114
+            ));
1115
+        $cursor = $qb->execute();
1116
+
1117
+        $users = [];
1118
+        $link = false;
1119
+        while($row = $cursor->fetch()) {
1120
+            $type = (int)$row['share_type'];
1121
+            if ($type === \OCP\Share::SHARE_TYPE_USER) {
1122
+                $uid = $row['share_with'];
1123
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1124
+                $users[$uid][$row['id']] = $row;
1125
+            } else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1126
+                $gid = $row['share_with'];
1127
+                $group = $this->groupManager->get($gid);
1128
+
1129
+                if ($group === null) {
1130
+                    continue;
1131
+                }
1132
+
1133
+                $userList = $group->getUsers();
1134
+                foreach ($userList as $user) {
1135
+                    $uid = $user->getUID();
1136
+                    $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1137
+                    $users[$uid][$row['id']] = $row;
1138
+                }
1139
+            } else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1140
+                $link = true;
1141
+            } else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1142
+                $uid = $row['share_with'];
1143
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1144
+                $users[$uid][$row['id']] = $row;
1145
+            }
1146
+        }
1147
+        $cursor->closeCursor();
1148
+
1149
+        if ($currentAccess === true) {
1150
+            $users = array_map([$this, 'filterSharesOfUser'], $users);
1151
+            $users = array_filter($users);
1152
+        } else {
1153
+            $users = array_keys($users);
1154
+        }
1155
+
1156
+        return ['users' => $users, 'public' => $link];
1157
+    }
1158
+
1159
+    /**
1160
+     * For each user the path with the fewest slashes is returned
1161
+     * @param array $shares
1162
+     * @return array
1163
+     */
1164
+    protected function filterSharesOfUser(array $shares) {
1165
+        // Group shares when the user has a share exception
1166
+        foreach ($shares as $id => $share) {
1167
+            $type = (int) $share['share_type'];
1168
+            $permissions = (int) $share['permissions'];
1169
+
1170
+            if ($type === self::SHARE_TYPE_USERGROUP) {
1171
+                unset($shares[$share['parent']]);
1172
+
1173
+                if ($permissions === 0) {
1174
+                    unset($shares[$id]);
1175
+                }
1176
+            }
1177
+        }
1178
+
1179
+        $best = [];
1180
+        $bestDepth = 0;
1181
+        foreach ($shares as $id => $share) {
1182
+            $depth = substr_count($share['file_target'], '/');
1183
+            if (empty($best) || $depth < $bestDepth) {
1184
+                $bestDepth = $depth;
1185
+                $best = [
1186
+                    'node_id' => $share['file_source'],
1187
+                    'node_path' => $share['file_target'],
1188
+                ];
1189
+            }
1190
+        }
1191
+
1192
+        return $best;
1193
+    }
1194 1194
 }
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.
Indentation   +401 added lines, -401 removed lines patch added patch discarded remove patch
@@ -40,405 +40,405 @@
 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
-		if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
130
-			return $this->requestLanguage;
131
-		}
132
-
133
-		/**
134
-		 * At this point Nextcloud might not yet be installed and thus the lookup
135
-		 * in the preferences table might fail. For this reason we need to check
136
-		 * whether the instance has already been installed
137
-		 *
138
-		 * @link https://github.com/owncloud/core/issues/21955
139
-		 */
140
-		if($this->config->getSystemValue('installed', false)) {
141
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
142
-			if(!is_null($userId)) {
143
-				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
144
-			} else {
145
-				$userLang = null;
146
-			}
147
-		} else {
148
-			$userId = null;
149
-			$userLang = null;
150
-		}
151
-
152
-		if ($userLang) {
153
-			$this->requestLanguage = $userLang;
154
-			if ($this->languageExists($app, $userLang)) {
155
-				return $userLang;
156
-			}
157
-		}
158
-
159
-		try {
160
-			// Try to get the language from the Request
161
-			$lang = $this->getLanguageFromRequest($app);
162
-			if ($userId !== null && $app === null && !$userLang) {
163
-				$this->config->setUserValue($userId, 'core', 'lang', $lang);
164
-			}
165
-			return $lang;
166
-		} catch (LanguageNotFoundException $e) {
167
-			// Finding language from request failed fall back to default language
168
-			$defaultLanguage = $this->config->getSystemValue('default_language', false);
169
-			if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
170
-				return $defaultLanguage;
171
-			}
172
-		}
173
-
174
-		// We could not find any language so fall back to english
175
-		return 'en';
176
-	}
177
-
178
-	/**
179
-	 * Find all available languages for an app
180
-	 *
181
-	 * @param string|null $app App id or null for core
182
-	 * @return array an array of available languages
183
-	 */
184
-	public function findAvailableLanguages($app = null) {
185
-		$key = $app;
186
-		if ($key === null) {
187
-			$key = 'null';
188
-		}
189
-
190
-		// also works with null as key
191
-		if (!empty($this->availableLanguages[$key])) {
192
-			return $this->availableLanguages[$key];
193
-		}
194
-
195
-		$available = ['en']; //english is always available
196
-		$dir = $this->findL10nDir($app);
197
-		if (is_dir($dir)) {
198
-			$files = scandir($dir);
199
-			if ($files !== false) {
200
-				foreach ($files as $file) {
201
-					if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
202
-						$available[] = substr($file, 0, -5);
203
-					}
204
-				}
205
-			}
206
-		}
207
-
208
-		// merge with translations from theme
209
-		$theme = $this->config->getSystemValue('theme');
210
-		if (!empty($theme)) {
211
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
212
-
213
-			if (is_dir($themeDir)) {
214
-				$files = scandir($themeDir);
215
-				if ($files !== false) {
216
-					foreach ($files as $file) {
217
-						if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
218
-							$available[] = substr($file, 0, -5);
219
-						}
220
-					}
221
-				}
222
-			}
223
-		}
224
-
225
-		$this->availableLanguages[$key] = $available;
226
-		return $available;
227
-	}
228
-
229
-	/**
230
-	 * @param string|null $app App id or null for core
231
-	 * @param string $lang
232
-	 * @return bool
233
-	 */
234
-	public function languageExists($app, $lang) {
235
-		if ($lang === 'en') {//english is always available
236
-			return true;
237
-		}
238
-
239
-		$languages = $this->findAvailableLanguages($app);
240
-		return array_search($lang, $languages) !== false;
241
-	}
242
-
243
-	/**
244
-	 * @param string|null $app
245
-	 * @return string
246
-	 * @throws LanguageNotFoundException
247
-	 */
248
-	private function getLanguageFromRequest($app) {
249
-		$header = $this->request->getHeader('ACCEPT_LANGUAGE');
250
-		if ($header !== '') {
251
-			$available = $this->findAvailableLanguages($app);
252
-
253
-			// E.g. make sure that 'de' is before 'de_DE'.
254
-			sort($available);
255
-
256
-			$preferences = preg_split('/,\s*/', strtolower($header));
257
-			foreach ($preferences as $preference) {
258
-				list($preferred_language) = explode(';', $preference);
259
-				$preferred_language = str_replace('-', '_', $preferred_language);
260
-
261
-				foreach ($available as $available_language) {
262
-					if ($preferred_language === strtolower($available_language)) {
263
-						return $this->respectDefaultLanguage($app, $available_language);
264
-					}
265
-				}
266
-
267
-				// Fallback from de_De to de
268
-				foreach ($available as $available_language) {
269
-					if (substr($preferred_language, 0, 2) === $available_language) {
270
-						return $available_language;
271
-					}
272
-				}
273
-			}
274
-		}
275
-
276
-		throw new LanguageNotFoundException();
277
-	}
278
-
279
-	/**
280
-	 * if default language is set to de_DE (formal German) this should be
281
-	 * preferred to 'de' (non-formal German) if possible
282
-	 *
283
-	 * @param string|null $app
284
-	 * @param string $lang
285
-	 * @return string
286
-	 */
287
-	protected function respectDefaultLanguage($app, $lang) {
288
-		$result = $lang;
289
-		$defaultLanguage = $this->config->getSystemValue('default_language', false);
290
-
291
-		// use formal version of german ("Sie" instead of "Du") if the default
292
-		// language is set to 'de_DE' if possible
293
-		if (is_string($defaultLanguage) &&
294
-			strtolower($lang) === 'de' &&
295
-			strtolower($defaultLanguage) === 'de_de' &&
296
-			$this->languageExists($app, 'de_DE')
297
-		) {
298
-			$result = 'de_DE';
299
-		}
300
-
301
-		return $result;
302
-	}
303
-
304
-	/**
305
-	 * Checks if $sub is a subdirectory of $parent
306
-	 *
307
-	 * @param string $sub
308
-	 * @param string $parent
309
-	 * @return bool
310
-	 */
311
-	private function isSubDirectory($sub, $parent) {
312
-		// Check whether $sub contains no ".."
313
-		if(strpos($sub, '..') !== false) {
314
-			return false;
315
-		}
316
-
317
-		// Check whether $sub is a subdirectory of $parent
318
-		if (strpos($sub, $parent) === 0) {
319
-			return true;
320
-		}
321
-
322
-		return false;
323
-	}
324
-
325
-	/**
326
-	 * Get a list of language files that should be loaded
327
-	 *
328
-	 * @param string $app
329
-	 * @param string $lang
330
-	 * @return string[]
331
-	 */
332
-	// FIXME This method is only public, until OC_L10N does not need it anymore,
333
-	// FIXME This is also the reason, why it is not in the public interface
334
-	public function getL10nFilesForApp($app, $lang) {
335
-		$languageFiles = [];
336
-
337
-		$i18nDir = $this->findL10nDir($app);
338
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
339
-
340
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
341
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
342
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
343
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
344
-			)
345
-			&& file_exists($transFile)) {
346
-			// load the translations file
347
-			$languageFiles[] = $transFile;
348
-		}
349
-
350
-		// merge with translations from theme
351
-		$theme = $this->config->getSystemValue('theme');
352
-		if (!empty($theme)) {
353
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
354
-			if (file_exists($transFile)) {
355
-				$languageFiles[] = $transFile;
356
-			}
357
-		}
358
-
359
-		return $languageFiles;
360
-	}
361
-
362
-	/**
363
-	 * find the l10n directory
364
-	 *
365
-	 * @param string $app App id or empty string for core
366
-	 * @return string directory
367
-	 */
368
-	protected function findL10nDir($app = null) {
369
-		if (in_array($app, ['core', 'lib', 'settings'])) {
370
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
371
-				return $this->serverRoot . '/' . $app . '/l10n/';
372
-			}
373
-		} else if ($app && \OC_App::getAppPath($app) !== false) {
374
-			// Check if the app is in the app folder
375
-			return \OC_App::getAppPath($app) . '/l10n/';
376
-		}
377
-		return $this->serverRoot . '/core/l10n/';
378
-	}
379
-
380
-
381
-	/**
382
-	 * Creates a function from the plural string
383
-	 *
384
-	 * Parts of the code is copied from Habari:
385
-	 * https://github.com/habari/system/blob/master/classes/locale.php
386
-	 * @param string $string
387
-	 * @return string
388
-	 */
389
-	public function createPluralFunction($string) {
390
-		if (isset($this->pluralFunctions[$string])) {
391
-			return $this->pluralFunctions[$string];
392
-		}
393
-
394
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
395
-			// sanitize
396
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
397
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
398
-
399
-			$body = str_replace(
400
-				array( 'plural', 'n', '$n$plurals', ),
401
-				array( '$plural', '$n', '$nplurals', ),
402
-				'nplurals='. $nplurals . '; plural=' . $plural
403
-			);
404
-
405
-			// add parents
406
-			// important since PHP's ternary evaluates from left to right
407
-			$body .= ';';
408
-			$res = '';
409
-			$p = 0;
410
-			$length = strlen($body);
411
-			for($i = 0; $i < $length; $i++) {
412
-				$ch = $body[$i];
413
-				switch ( $ch ) {
414
-					case '?':
415
-						$res .= ' ? (';
416
-						$p++;
417
-						break;
418
-					case ':':
419
-						$res .= ') : (';
420
-						break;
421
-					case ';':
422
-						$res .= str_repeat( ')', $p ) . ';';
423
-						$p = 0;
424
-						break;
425
-					default:
426
-						$res .= $ch;
427
-				}
428
-			}
429
-
430
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
431
-			$function = create_function('$n', $body);
432
-			$this->pluralFunctions[$string] = $function;
433
-			return $function;
434
-		} else {
435
-			// default: one plural form for all cases but n==1 (english)
436
-			$function = create_function(
437
-				'$n',
438
-				'$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
439
-			);
440
-			$this->pluralFunctions[$string] = $function;
441
-			return $function;
442
-		}
443
-	}
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
+        if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
130
+            return $this->requestLanguage;
131
+        }
132
+
133
+        /**
134
+         * At this point Nextcloud might not yet be installed and thus the lookup
135
+         * in the preferences table might fail. For this reason we need to check
136
+         * whether the instance has already been installed
137
+         *
138
+         * @link https://github.com/owncloud/core/issues/21955
139
+         */
140
+        if($this->config->getSystemValue('installed', false)) {
141
+            $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
142
+            if(!is_null($userId)) {
143
+                $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
144
+            } else {
145
+                $userLang = null;
146
+            }
147
+        } else {
148
+            $userId = null;
149
+            $userLang = null;
150
+        }
151
+
152
+        if ($userLang) {
153
+            $this->requestLanguage = $userLang;
154
+            if ($this->languageExists($app, $userLang)) {
155
+                return $userLang;
156
+            }
157
+        }
158
+
159
+        try {
160
+            // Try to get the language from the Request
161
+            $lang = $this->getLanguageFromRequest($app);
162
+            if ($userId !== null && $app === null && !$userLang) {
163
+                $this->config->setUserValue($userId, 'core', 'lang', $lang);
164
+            }
165
+            return $lang;
166
+        } catch (LanguageNotFoundException $e) {
167
+            // Finding language from request failed fall back to default language
168
+            $defaultLanguage = $this->config->getSystemValue('default_language', false);
169
+            if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
170
+                return $defaultLanguage;
171
+            }
172
+        }
173
+
174
+        // We could not find any language so fall back to english
175
+        return 'en';
176
+    }
177
+
178
+    /**
179
+     * Find all available languages for an app
180
+     *
181
+     * @param string|null $app App id or null for core
182
+     * @return array an array of available languages
183
+     */
184
+    public function findAvailableLanguages($app = null) {
185
+        $key = $app;
186
+        if ($key === null) {
187
+            $key = 'null';
188
+        }
189
+
190
+        // also works with null as key
191
+        if (!empty($this->availableLanguages[$key])) {
192
+            return $this->availableLanguages[$key];
193
+        }
194
+
195
+        $available = ['en']; //english is always available
196
+        $dir = $this->findL10nDir($app);
197
+        if (is_dir($dir)) {
198
+            $files = scandir($dir);
199
+            if ($files !== false) {
200
+                foreach ($files as $file) {
201
+                    if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
202
+                        $available[] = substr($file, 0, -5);
203
+                    }
204
+                }
205
+            }
206
+        }
207
+
208
+        // merge with translations from theme
209
+        $theme = $this->config->getSystemValue('theme');
210
+        if (!empty($theme)) {
211
+            $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
212
+
213
+            if (is_dir($themeDir)) {
214
+                $files = scandir($themeDir);
215
+                if ($files !== false) {
216
+                    foreach ($files as $file) {
217
+                        if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
218
+                            $available[] = substr($file, 0, -5);
219
+                        }
220
+                    }
221
+                }
222
+            }
223
+        }
224
+
225
+        $this->availableLanguages[$key] = $available;
226
+        return $available;
227
+    }
228
+
229
+    /**
230
+     * @param string|null $app App id or null for core
231
+     * @param string $lang
232
+     * @return bool
233
+     */
234
+    public function languageExists($app, $lang) {
235
+        if ($lang === 'en') {//english is always available
236
+            return true;
237
+        }
238
+
239
+        $languages = $this->findAvailableLanguages($app);
240
+        return array_search($lang, $languages) !== false;
241
+    }
242
+
243
+    /**
244
+     * @param string|null $app
245
+     * @return string
246
+     * @throws LanguageNotFoundException
247
+     */
248
+    private function getLanguageFromRequest($app) {
249
+        $header = $this->request->getHeader('ACCEPT_LANGUAGE');
250
+        if ($header !== '') {
251
+            $available = $this->findAvailableLanguages($app);
252
+
253
+            // E.g. make sure that 'de' is before 'de_DE'.
254
+            sort($available);
255
+
256
+            $preferences = preg_split('/,\s*/', strtolower($header));
257
+            foreach ($preferences as $preference) {
258
+                list($preferred_language) = explode(';', $preference);
259
+                $preferred_language = str_replace('-', '_', $preferred_language);
260
+
261
+                foreach ($available as $available_language) {
262
+                    if ($preferred_language === strtolower($available_language)) {
263
+                        return $this->respectDefaultLanguage($app, $available_language);
264
+                    }
265
+                }
266
+
267
+                // Fallback from de_De to de
268
+                foreach ($available as $available_language) {
269
+                    if (substr($preferred_language, 0, 2) === $available_language) {
270
+                        return $available_language;
271
+                    }
272
+                }
273
+            }
274
+        }
275
+
276
+        throw new LanguageNotFoundException();
277
+    }
278
+
279
+    /**
280
+     * if default language is set to de_DE (formal German) this should be
281
+     * preferred to 'de' (non-formal German) if possible
282
+     *
283
+     * @param string|null $app
284
+     * @param string $lang
285
+     * @return string
286
+     */
287
+    protected function respectDefaultLanguage($app, $lang) {
288
+        $result = $lang;
289
+        $defaultLanguage = $this->config->getSystemValue('default_language', false);
290
+
291
+        // use formal version of german ("Sie" instead of "Du") if the default
292
+        // language is set to 'de_DE' if possible
293
+        if (is_string($defaultLanguage) &&
294
+            strtolower($lang) === 'de' &&
295
+            strtolower($defaultLanguage) === 'de_de' &&
296
+            $this->languageExists($app, 'de_DE')
297
+        ) {
298
+            $result = 'de_DE';
299
+        }
300
+
301
+        return $result;
302
+    }
303
+
304
+    /**
305
+     * Checks if $sub is a subdirectory of $parent
306
+     *
307
+     * @param string $sub
308
+     * @param string $parent
309
+     * @return bool
310
+     */
311
+    private function isSubDirectory($sub, $parent) {
312
+        // Check whether $sub contains no ".."
313
+        if(strpos($sub, '..') !== false) {
314
+            return false;
315
+        }
316
+
317
+        // Check whether $sub is a subdirectory of $parent
318
+        if (strpos($sub, $parent) === 0) {
319
+            return true;
320
+        }
321
+
322
+        return false;
323
+    }
324
+
325
+    /**
326
+     * Get a list of language files that should be loaded
327
+     *
328
+     * @param string $app
329
+     * @param string $lang
330
+     * @return string[]
331
+     */
332
+    // FIXME This method is only public, until OC_L10N does not need it anymore,
333
+    // FIXME This is also the reason, why it is not in the public interface
334
+    public function getL10nFilesForApp($app, $lang) {
335
+        $languageFiles = [];
336
+
337
+        $i18nDir = $this->findL10nDir($app);
338
+        $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
339
+
340
+        if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
341
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
342
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
343
+                || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
344
+            )
345
+            && file_exists($transFile)) {
346
+            // load the translations file
347
+            $languageFiles[] = $transFile;
348
+        }
349
+
350
+        // merge with translations from theme
351
+        $theme = $this->config->getSystemValue('theme');
352
+        if (!empty($theme)) {
353
+            $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
354
+            if (file_exists($transFile)) {
355
+                $languageFiles[] = $transFile;
356
+            }
357
+        }
358
+
359
+        return $languageFiles;
360
+    }
361
+
362
+    /**
363
+     * find the l10n directory
364
+     *
365
+     * @param string $app App id or empty string for core
366
+     * @return string directory
367
+     */
368
+    protected function findL10nDir($app = null) {
369
+        if (in_array($app, ['core', 'lib', 'settings'])) {
370
+            if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
371
+                return $this->serverRoot . '/' . $app . '/l10n/';
372
+            }
373
+        } else if ($app && \OC_App::getAppPath($app) !== false) {
374
+            // Check if the app is in the app folder
375
+            return \OC_App::getAppPath($app) . '/l10n/';
376
+        }
377
+        return $this->serverRoot . '/core/l10n/';
378
+    }
379
+
380
+
381
+    /**
382
+     * Creates a function from the plural string
383
+     *
384
+     * Parts of the code is copied from Habari:
385
+     * https://github.com/habari/system/blob/master/classes/locale.php
386
+     * @param string $string
387
+     * @return string
388
+     */
389
+    public function createPluralFunction($string) {
390
+        if (isset($this->pluralFunctions[$string])) {
391
+            return $this->pluralFunctions[$string];
392
+        }
393
+
394
+        if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
395
+            // sanitize
396
+            $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
397
+            $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
398
+
399
+            $body = str_replace(
400
+                array( 'plural', 'n', '$n$plurals', ),
401
+                array( '$plural', '$n', '$nplurals', ),
402
+                'nplurals='. $nplurals . '; plural=' . $plural
403
+            );
404
+
405
+            // add parents
406
+            // important since PHP's ternary evaluates from left to right
407
+            $body .= ';';
408
+            $res = '';
409
+            $p = 0;
410
+            $length = strlen($body);
411
+            for($i = 0; $i < $length; $i++) {
412
+                $ch = $body[$i];
413
+                switch ( $ch ) {
414
+                    case '?':
415
+                        $res .= ' ? (';
416
+                        $p++;
417
+                        break;
418
+                    case ':':
419
+                        $res .= ') : (';
420
+                        break;
421
+                    case ';':
422
+                        $res .= str_repeat( ')', $p ) . ';';
423
+                        $p = 0;
424
+                        break;
425
+                    default:
426
+                        $res .= $ch;
427
+                }
428
+            }
429
+
430
+            $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
431
+            $function = create_function('$n', $body);
432
+            $this->pluralFunctions[$string] = $function;
433
+            return $function;
434
+        } else {
435
+            // default: one plural form for all cases but n==1 (english)
436
+            $function = create_function(
437
+                '$n',
438
+                '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
439
+            );
440
+            $this->pluralFunctions[$string] = $function;
441
+            return $function;
442
+        }
443
+    }
444 444
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -137,9 +137,9 @@  discard block
 block discarded – undo
137 137
 		 *
138 138
 		 * @link https://github.com/owncloud/core/issues/21955
139 139
 		 */
140
-		if($this->config->getSystemValue('installed', false)) {
141
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
142
-			if(!is_null($userId)) {
140
+		if ($this->config->getSystemValue('installed', false)) {
141
+			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null;
142
+			if (!is_null($userId)) {
143 143
 				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
144 144
 			} else {
145 145
 				$userLang = null;
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
 		// merge with translations from theme
209 209
 		$theme = $this->config->getSystemValue('theme');
210 210
 		if (!empty($theme)) {
211
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
211
+			$themeDir = $this->serverRoot.'/themes/'.$theme.substr($dir, strlen($this->serverRoot));
212 212
 
213 213
 			if (is_dir($themeDir)) {
214 214
 				$files = scandir($themeDir);
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
 	 */
311 311
 	private function isSubDirectory($sub, $parent) {
312 312
 		// Check whether $sub contains no ".."
313
-		if(strpos($sub, '..') !== false) {
313
+		if (strpos($sub, '..') !== false) {
314 314
 			return false;
315 315
 		}
316 316
 
@@ -335,12 +335,12 @@  discard block
 block discarded – undo
335 335
 		$languageFiles = [];
336 336
 
337 337
 		$i18nDir = $this->findL10nDir($app);
338
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
338
+		$transFile = strip_tags($i18nDir).strip_tags($lang).'.json';
339 339
 
340
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
341
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
342
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
343
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
340
+		if (($this->isSubDirectory($transFile, $this->serverRoot.'/core/l10n/')
341
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/lib/l10n/')
342
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/settings/l10n/')
343
+				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app).'/l10n/')
344 344
 			)
345 345
 			&& file_exists($transFile)) {
346 346
 			// load the translations file
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
 		// merge with translations from theme
351 351
 		$theme = $this->config->getSystemValue('theme');
352 352
 		if (!empty($theme)) {
353
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
353
+			$transFile = $this->serverRoot.'/themes/'.$theme.substr($transFile, strlen($this->serverRoot));
354 354
 			if (file_exists($transFile)) {
355 355
 				$languageFiles[] = $transFile;
356 356
 			}
@@ -367,14 +367,14 @@  discard block
 block discarded – undo
367 367
 	 */
368 368
 	protected function findL10nDir($app = null) {
369 369
 		if (in_array($app, ['core', 'lib', 'settings'])) {
370
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
371
-				return $this->serverRoot . '/' . $app . '/l10n/';
370
+			if (file_exists($this->serverRoot.'/'.$app.'/l10n/')) {
371
+				return $this->serverRoot.'/'.$app.'/l10n/';
372 372
 			}
373 373
 		} else if ($app && \OC_App::getAppPath($app) !== false) {
374 374
 			// Check if the app is in the app folder
375
-			return \OC_App::getAppPath($app) . '/l10n/';
375
+			return \OC_App::getAppPath($app).'/l10n/';
376 376
 		}
377
-		return $this->serverRoot . '/core/l10n/';
377
+		return $this->serverRoot.'/core/l10n/';
378 378
 	}
379 379
 
380 380
 
@@ -391,15 +391,15 @@  discard block
 block discarded – undo
391 391
 			return $this->pluralFunctions[$string];
392 392
 		}
393 393
 
394
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
394
+		if (preg_match('/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
395 395
 			// sanitize
396
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
397
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
396
+			$nplurals = preg_replace('/[^0-9]/', '', $matches[1]);
397
+			$plural = preg_replace('#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2]);
398 398
 
399 399
 			$body = str_replace(
400
-				array( 'plural', 'n', '$n$plurals', ),
401
-				array( '$plural', '$n', '$nplurals', ),
402
-				'nplurals='. $nplurals . '; plural=' . $plural
400
+				array('plural', 'n', '$n$plurals',),
401
+				array('$plural', '$n', '$nplurals',),
402
+				'nplurals='.$nplurals.'; plural='.$plural
403 403
 			);
404 404
 
405 405
 			// add parents
@@ -408,9 +408,9 @@  discard block
 block discarded – undo
408 408
 			$res = '';
409 409
 			$p = 0;
410 410
 			$length = strlen($body);
411
-			for($i = 0; $i < $length; $i++) {
411
+			for ($i = 0; $i < $length; $i++) {
412 412
 				$ch = $body[$i];
413
-				switch ( $ch ) {
413
+				switch ($ch) {
414 414
 					case '?':
415 415
 						$res .= ' ? (';
416 416
 						$p++;
@@ -419,7 +419,7 @@  discard block
 block discarded – undo
419 419
 						$res .= ') : (';
420 420
 						break;
421 421
 					case ';':
422
-						$res .= str_repeat( ')', $p ) . ';';
422
+						$res .= str_repeat(')', $p).';';
423 423
 						$p = 0;
424 424
 						break;
425 425
 					default:
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
 				}
428 428
 			}
429 429
 
430
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
430
+			$body = $res.'return ($plural>=$nplurals?$nplurals-1:$plural);';
431 431
 			$function = create_function('$n', $body);
432 432
 			$this->pluralFunctions[$string] = $function;
433 433
 			return $function;
Please login to merge, or discard this patch.
lib/private/Setup/MySQL.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -101,7 +101,7 @@
 block discarded – undo
101 101
 	}
102 102
 
103 103
 	/**
104
-	 * @param $username
104
+	 * @param string $username
105 105
 	 * @param IDBConnection $connection
106 106
 	 * @return array
107 107
 	 */
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -52,7 +52,7 @@  discard block
 block discarded – undo
52 52
 		$this->createDatabase($connection);
53 53
 
54 54
 		//fill the database if needed
55
-		$query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
55
+		$query = 'select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
56 56
 		$connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
57 57
 	}
58 58
 
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 	 * @param \OC\DB\Connection $connection
61 61
 	 */
62 62
 	private function createDatabase($connection) {
63
-		try{
63
+		try {
64 64
 			$name = $this->dbName;
65 65
 			$user = $this->dbUser;
66 66
 			//we can't use OC_DB functions here because we need to connect as the administrative user.
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
 
79 79
 		try {
80 80
 			//this query will fail if there aren't the right permissions, ignore the error
81
-			$query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
81
+			$query = "GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
82 82
 			$connection->executeUpdate($query);
83 83
 		} catch (\Exception $ex) {
84 84
 			$this->logger->logException($ex, [
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 	 * @throws \OC\DatabaseSetupException
95 95
 	 */
96 96
 	private function createDBUser($connection) {
97
-		try{
97
+		try {
98 98
 			$name = $this->dbUser;
99 99
 			$password = $this->dbPassword;
100 100
 			// we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 			$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
105 105
 			$connection->executeUpdate($query);
106 106
 		}
107
-		catch (\Exception $ex){
107
+		catch (\Exception $ex) {
108 108
 			$this->logger->logException($ex, [
109 109
 				'message' => 'Database user creation failed.',
110 110
 				'level' => \OCP\Util::ERROR,
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 			//we don't have a dbuser specified in config
127 127
 			if ($this->dbUser !== $oldUser) {
128 128
 				//add prefix to the admin username to prevent collisions
129
-				$adminUser = substr('oc_' . $username, 0, 16);
129
+				$adminUser = substr('oc_'.$username, 0, 16);
130 130
 
131 131
 				$i = 1;
132 132
 				while (true) {
@@ -143,15 +143,15 @@  discard block
 block discarded – undo
143 143
 							$this->dbUser = $adminUser;
144 144
 
145 145
 							//create a random password so we don't need to store the admin password in the config file
146
-							$this->dbPassword =  $this->random->generate(30);
146
+							$this->dbPassword = $this->random->generate(30);
147 147
 
148 148
 							$this->createDBUser($connection);
149 149
 
150 150
 							break;
151 151
 						} else {
152 152
 							//repeat with different username
153
-							$length = strlen((string)$i);
154
-							$adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
153
+							$length = strlen((string) $i);
154
+							$adminUser = substr('oc_'.$username, 0, 16 - $length).$i;
155 155
 							$i++;
156 156
 						}
157 157
 					} else {
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -103,8 +103,7 @@
 block discarded – undo
103 103
 			$connection->executeUpdate($query);
104 104
 			$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
105 105
 			$connection->executeUpdate($query);
106
-		}
107
-		catch (\Exception $ex){
106
+		} catch (\Exception $ex){
108 107
 			$this->logger->logException($ex, [
109 108
 				'message' => 'Database user creation failed.',
110 109
 				'level' => \OCP\Util::ERROR,
Please login to merge, or discard this patch.
Indentation   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -33,143 +33,143 @@
 block discarded – undo
33 33
 use OCP\IDBConnection;
34 34
 
35 35
 class MySQL extends AbstractDatabase {
36
-	public $dbprettyname = 'MySQL/MariaDB';
37
-
38
-	public function setupDatabase($username) {
39
-		//check if the database user has admin right
40
-		$connection = $this->connect(['dbname' => null]);
41
-
42
-		// detect mb4
43
-		$tools = new MySqlTools();
44
-		if ($tools->supports4ByteCharset($connection)) {
45
-			$this->config->setValue('mysql.utf8mb4', true);
46
-			$connection = $this->connect(['dbname' => null]);
47
-		}
48
-
49
-		$this->createSpecificUser($username, $connection);
50
-
51
-		//create the database
52
-		$this->createDatabase($connection);
53
-
54
-		//fill the database if needed
55
-		$query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
56
-		$connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
57
-	}
58
-
59
-	/**
60
-	 * @param \OC\DB\Connection $connection
61
-	 */
62
-	private function createDatabase($connection) {
63
-		try{
64
-			$name = $this->dbName;
65
-			$user = $this->dbUser;
66
-			//we can't use OC_DB functions here because we need to connect as the administrative user.
67
-			$characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
68
-			$query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
69
-			$connection->executeUpdate($query);
70
-		} catch (\Exception $ex) {
71
-			$this->logger->logException($ex, [
72
-				'message' => 'Database creation failed.',
73
-				'level' => \OCP\Util::ERROR,
74
-				'app' => 'mysql.setup',
75
-			]);
76
-			return;
77
-		}
78
-
79
-		try {
80
-			//this query will fail if there aren't the right permissions, ignore the error
81
-			$query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
82
-			$connection->executeUpdate($query);
83
-		} catch (\Exception $ex) {
84
-			$this->logger->logException($ex, [
85
-				'message' => 'Could not automatically grant privileges, this can be ignored if database user already had privileges.',
86
-				'level' => \OCP\Util::DEBUG,
87
-				'app' => 'mysql.setup',
88
-			]);
89
-		}
90
-	}
91
-
92
-	/**
93
-	 * @param IDBConnection $connection
94
-	 * @throws \OC\DatabaseSetupException
95
-	 */
96
-	private function createDBUser($connection) {
97
-		try{
98
-			$name = $this->dbUser;
99
-			$password = $this->dbPassword;
100
-			// we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
101
-			// the anonymous user would take precedence when there is one.
102
-			$query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
103
-			$connection->executeUpdate($query);
104
-			$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
105
-			$connection->executeUpdate($query);
106
-		}
107
-		catch (\Exception $ex){
108
-			$this->logger->logException($ex, [
109
-				'message' => 'Database user creation failed.',
110
-				'level' => \OCP\Util::ERROR,
111
-				'app' => 'mysql.setup',
112
-			]);
113
-		}
114
-	}
115
-
116
-	/**
117
-	 * @param $username
118
-	 * @param IDBConnection $connection
119
-	 * @return array
120
-	 */
121
-	private function createSpecificUser($username, $connection) {
122
-		try {
123
-			//user already specified in config
124
-			$oldUser = $this->config->getValue('dbuser', false);
125
-
126
-			//we don't have a dbuser specified in config
127
-			if ($this->dbUser !== $oldUser) {
128
-				//add prefix to the admin username to prevent collisions
129
-				$adminUser = substr('oc_' . $username, 0, 16);
130
-
131
-				$i = 1;
132
-				while (true) {
133
-					//this should be enough to check for admin rights in mysql
134
-					$query = 'SELECT user FROM mysql.user WHERE user=?';
135
-					$result = $connection->executeQuery($query, [$adminUser]);
136
-
137
-					//current dbuser has admin rights
138
-					if ($result) {
139
-						$data = $result->fetchAll();
140
-						//new dbuser does not exist
141
-						if (count($data) === 0) {
142
-							//use the admin login data for the new database user
143
-							$this->dbUser = $adminUser;
144
-
145
-							//create a random password so we don't need to store the admin password in the config file
146
-							$this->dbPassword =  $this->random->generate(30);
147
-
148
-							$this->createDBUser($connection);
149
-
150
-							break;
151
-						} else {
152
-							//repeat with different username
153
-							$length = strlen((string)$i);
154
-							$adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
155
-							$i++;
156
-						}
157
-					} else {
158
-						break;
159
-					}
160
-				}
161
-			}
162
-		} catch (\Exception $ex) {
163
-			$this->logger->logException($ex, [
164
-				'message' => 'Can not create a new MySQL user, will continue with the provided user.',
165
-				'level' => \OCP\Util::INFO,
166
-				'app' => 'mysql.setup',
167
-			]);
168
-		}
169
-
170
-		$this->config->setValues([
171
-			'dbuser' => $this->dbUser,
172
-			'dbpassword' => $this->dbPassword,
173
-		]);
174
-	}
36
+    public $dbprettyname = 'MySQL/MariaDB';
37
+
38
+    public function setupDatabase($username) {
39
+        //check if the database user has admin right
40
+        $connection = $this->connect(['dbname' => null]);
41
+
42
+        // detect mb4
43
+        $tools = new MySqlTools();
44
+        if ($tools->supports4ByteCharset($connection)) {
45
+            $this->config->setValue('mysql.utf8mb4', true);
46
+            $connection = $this->connect(['dbname' => null]);
47
+        }
48
+
49
+        $this->createSpecificUser($username, $connection);
50
+
51
+        //create the database
52
+        $this->createDatabase($connection);
53
+
54
+        //fill the database if needed
55
+        $query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
56
+        $connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
57
+    }
58
+
59
+    /**
60
+     * @param \OC\DB\Connection $connection
61
+     */
62
+    private function createDatabase($connection) {
63
+        try{
64
+            $name = $this->dbName;
65
+            $user = $this->dbUser;
66
+            //we can't use OC_DB functions here because we need to connect as the administrative user.
67
+            $characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
68
+            $query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
69
+            $connection->executeUpdate($query);
70
+        } catch (\Exception $ex) {
71
+            $this->logger->logException($ex, [
72
+                'message' => 'Database creation failed.',
73
+                'level' => \OCP\Util::ERROR,
74
+                'app' => 'mysql.setup',
75
+            ]);
76
+            return;
77
+        }
78
+
79
+        try {
80
+            //this query will fail if there aren't the right permissions, ignore the error
81
+            $query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
82
+            $connection->executeUpdate($query);
83
+        } catch (\Exception $ex) {
84
+            $this->logger->logException($ex, [
85
+                'message' => 'Could not automatically grant privileges, this can be ignored if database user already had privileges.',
86
+                'level' => \OCP\Util::DEBUG,
87
+                'app' => 'mysql.setup',
88
+            ]);
89
+        }
90
+    }
91
+
92
+    /**
93
+     * @param IDBConnection $connection
94
+     * @throws \OC\DatabaseSetupException
95
+     */
96
+    private function createDBUser($connection) {
97
+        try{
98
+            $name = $this->dbUser;
99
+            $password = $this->dbPassword;
100
+            // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
101
+            // the anonymous user would take precedence when there is one.
102
+            $query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
103
+            $connection->executeUpdate($query);
104
+            $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
105
+            $connection->executeUpdate($query);
106
+        }
107
+        catch (\Exception $ex){
108
+            $this->logger->logException($ex, [
109
+                'message' => 'Database user creation failed.',
110
+                'level' => \OCP\Util::ERROR,
111
+                'app' => 'mysql.setup',
112
+            ]);
113
+        }
114
+    }
115
+
116
+    /**
117
+     * @param $username
118
+     * @param IDBConnection $connection
119
+     * @return array
120
+     */
121
+    private function createSpecificUser($username, $connection) {
122
+        try {
123
+            //user already specified in config
124
+            $oldUser = $this->config->getValue('dbuser', false);
125
+
126
+            //we don't have a dbuser specified in config
127
+            if ($this->dbUser !== $oldUser) {
128
+                //add prefix to the admin username to prevent collisions
129
+                $adminUser = substr('oc_' . $username, 0, 16);
130
+
131
+                $i = 1;
132
+                while (true) {
133
+                    //this should be enough to check for admin rights in mysql
134
+                    $query = 'SELECT user FROM mysql.user WHERE user=?';
135
+                    $result = $connection->executeQuery($query, [$adminUser]);
136
+
137
+                    //current dbuser has admin rights
138
+                    if ($result) {
139
+                        $data = $result->fetchAll();
140
+                        //new dbuser does not exist
141
+                        if (count($data) === 0) {
142
+                            //use the admin login data for the new database user
143
+                            $this->dbUser = $adminUser;
144
+
145
+                            //create a random password so we don't need to store the admin password in the config file
146
+                            $this->dbPassword =  $this->random->generate(30);
147
+
148
+                            $this->createDBUser($connection);
149
+
150
+                            break;
151
+                        } else {
152
+                            //repeat with different username
153
+                            $length = strlen((string)$i);
154
+                            $adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
155
+                            $i++;
156
+                        }
157
+                    } else {
158
+                        break;
159
+                    }
160
+                }
161
+            }
162
+        } catch (\Exception $ex) {
163
+            $this->logger->logException($ex, [
164
+                'message' => 'Can not create a new MySQL user, will continue with the provided user.',
165
+                'level' => \OCP\Util::INFO,
166
+                'app' => 'mysql.setup',
167
+            ]);
168
+        }
169
+
170
+        $this->config->setValues([
171
+            'dbuser' => $this->dbUser,
172
+            'dbpassword' => $this->dbPassword,
173
+        ]);
174
+    }
175 175
 }
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   +853 added lines, -853 removed lines patch added patch discarded remove patch
@@ -69,857 +69,857 @@
 block discarded – undo
69 69
 
70 70
 class Filesystem {
71 71
 
72
-	/**
73
-	 * @var Mount\Manager $mounts
74
-	 */
75
-	private static $mounts;
76
-
77
-	public static $loaded = false;
78
-	/**
79
-	 * @var \OC\Files\View $defaultInstance
80
-	 */
81
-	static private $defaultInstance;
82
-
83
-	static private $usersSetup = array();
84
-
85
-	static private $normalizedPathCache = null;
86
-
87
-	static private $listeningForProviders = false;
88
-
89
-	/**
90
-	 * classname which used for hooks handling
91
-	 * used as signalclass in OC_Hooks::emit()
92
-	 */
93
-	const CLASSNAME = 'OC_Filesystem';
94
-
95
-	/**
96
-	 * signalname emitted before file renaming
97
-	 *
98
-	 * @param string $oldpath
99
-	 * @param string $newpath
100
-	 */
101
-	const signal_rename = 'rename';
102
-
103
-	/**
104
-	 * signal emitted after file renaming
105
-	 *
106
-	 * @param string $oldpath
107
-	 * @param string $newpath
108
-	 */
109
-	const signal_post_rename = 'post_rename';
110
-
111
-	/**
112
-	 * signal emitted before file/dir creation
113
-	 *
114
-	 * @param string $path
115
-	 * @param bool $run changing this flag to false in hook handler will cancel event
116
-	 */
117
-	const signal_create = 'create';
118
-
119
-	/**
120
-	 * signal emitted after file/dir creation
121
-	 *
122
-	 * @param string $path
123
-	 * @param bool $run changing this flag to false in hook handler will cancel event
124
-	 */
125
-	const signal_post_create = 'post_create';
126
-
127
-	/**
128
-	 * signal emits before file/dir copy
129
-	 *
130
-	 * @param string $oldpath
131
-	 * @param string $newpath
132
-	 * @param bool $run changing this flag to false in hook handler will cancel event
133
-	 */
134
-	const signal_copy = 'copy';
135
-
136
-	/**
137
-	 * signal emits after file/dir copy
138
-	 *
139
-	 * @param string $oldpath
140
-	 * @param string $newpath
141
-	 */
142
-	const signal_post_copy = 'post_copy';
143
-
144
-	/**
145
-	 * signal emits before file/dir save
146
-	 *
147
-	 * @param string $path
148
-	 * @param bool $run changing this flag to false in hook handler will cancel event
149
-	 */
150
-	const signal_write = 'write';
151
-
152
-	/**
153
-	 * signal emits after file/dir save
154
-	 *
155
-	 * @param string $path
156
-	 */
157
-	const signal_post_write = 'post_write';
158
-
159
-	/**
160
-	 * signal emitted before file/dir update
161
-	 *
162
-	 * @param string $path
163
-	 * @param bool $run changing this flag to false in hook handler will cancel event
164
-	 */
165
-	const signal_update = 'update';
166
-
167
-	/**
168
-	 * signal emitted after file/dir update
169
-	 *
170
-	 * @param string $path
171
-	 * @param bool $run changing this flag to false in hook handler will cancel event
172
-	 */
173
-	const signal_post_update = 'post_update';
174
-
175
-	/**
176
-	 * signal emits when reading file/dir
177
-	 *
178
-	 * @param string $path
179
-	 */
180
-	const signal_read = 'read';
181
-
182
-	/**
183
-	 * signal emits when removing file/dir
184
-	 *
185
-	 * @param string $path
186
-	 */
187
-	const signal_delete = 'delete';
188
-
189
-	/**
190
-	 * parameters definitions for signals
191
-	 */
192
-	const signal_param_path = 'path';
193
-	const signal_param_oldpath = 'oldpath';
194
-	const signal_param_newpath = 'newpath';
195
-
196
-	/**
197
-	 * run - changing this flag to false in hook handler will cancel event
198
-	 */
199
-	const signal_param_run = 'run';
200
-
201
-	const signal_create_mount = 'create_mount';
202
-	const signal_delete_mount = 'delete_mount';
203
-	const signal_param_mount_type = 'mounttype';
204
-	const signal_param_users = 'users';
205
-
206
-	/**
207
-	 * @var \OC\Files\Storage\StorageFactory $loader
208
-	 */
209
-	private static $loader;
210
-
211
-	/** @var bool */
212
-	private static $logWarningWhenAddingStorageWrapper = true;
213
-
214
-	/**
215
-	 * @param bool $shouldLog
216
-	 * @return bool previous value
217
-	 * @internal
218
-	 */
219
-	public static function logWarningWhenAddingStorageWrapper($shouldLog) {
220
-		$previousValue = self::$logWarningWhenAddingStorageWrapper;
221
-		self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
222
-		return $previousValue;
223
-	}
224
-
225
-	/**
226
-	 * @param string $wrapperName
227
-	 * @param callable $wrapper
228
-	 * @param int $priority
229
-	 */
230
-	public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
231
-		if (self::$logWarningWhenAddingStorageWrapper) {
232
-			\OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
233
-				'wrapper' => $wrapperName,
234
-				'app' => 'filesystem',
235
-			]);
236
-		}
237
-
238
-		$mounts = self::getMountManager()->getAll();
239
-		if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
240
-			// do not re-wrap if storage with this name already existed
241
-			return;
242
-		}
243
-	}
244
-
245
-	/**
246
-	 * Returns the storage factory
247
-	 *
248
-	 * @return \OCP\Files\Storage\IStorageFactory
249
-	 */
250
-	public static function getLoader() {
251
-		if (!self::$loader) {
252
-			self::$loader = new StorageFactory();
253
-		}
254
-		return self::$loader;
255
-	}
256
-
257
-	/**
258
-	 * Returns the mount manager
259
-	 *
260
-	 * @return \OC\Files\Mount\Manager
261
-	 */
262
-	public static function getMountManager($user = '') {
263
-		if (!self::$mounts) {
264
-			\OC_Util::setupFS($user);
265
-		}
266
-		return self::$mounts;
267
-	}
268
-
269
-	/**
270
-	 * get the mountpoint of the storage object for a path
271
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
272
-	 * returned mountpoint is relative to the absolute root of the filesystem
273
-	 * and doesn't take the chroot into account )
274
-	 *
275
-	 * @param string $path
276
-	 * @return string
277
-	 */
278
-	static public function getMountPoint($path) {
279
-		if (!self::$mounts) {
280
-			\OC_Util::setupFS();
281
-		}
282
-		$mount = self::$mounts->find($path);
283
-		if ($mount) {
284
-			return $mount->getMountPoint();
285
-		} else {
286
-			return '';
287
-		}
288
-	}
289
-
290
-	/**
291
-	 * get a list of all mount points in a directory
292
-	 *
293
-	 * @param string $path
294
-	 * @return string[]
295
-	 */
296
-	static public function getMountPoints($path) {
297
-		if (!self::$mounts) {
298
-			\OC_Util::setupFS();
299
-		}
300
-		$result = array();
301
-		$mounts = self::$mounts->findIn($path);
302
-		foreach ($mounts as $mount) {
303
-			$result[] = $mount->getMountPoint();
304
-		}
305
-		return $result;
306
-	}
307
-
308
-	/**
309
-	 * get the storage mounted at $mountPoint
310
-	 *
311
-	 * @param string $mountPoint
312
-	 * @return \OC\Files\Storage\Storage
313
-	 */
314
-	public static function getStorage($mountPoint) {
315
-		if (!self::$mounts) {
316
-			\OC_Util::setupFS();
317
-		}
318
-		$mount = self::$mounts->find($mountPoint);
319
-		return $mount->getStorage();
320
-	}
321
-
322
-	/**
323
-	 * @param string $id
324
-	 * @return Mount\MountPoint[]
325
-	 */
326
-	public static function getMountByStorageId($id) {
327
-		if (!self::$mounts) {
328
-			\OC_Util::setupFS();
329
-		}
330
-		return self::$mounts->findByStorageId($id);
331
-	}
332
-
333
-	/**
334
-	 * @param int $id
335
-	 * @return Mount\MountPoint[]
336
-	 */
337
-	public static function getMountByNumericId($id) {
338
-		if (!self::$mounts) {
339
-			\OC_Util::setupFS();
340
-		}
341
-		return self::$mounts->findByNumericId($id);
342
-	}
343
-
344
-	/**
345
-	 * resolve a path to a storage and internal path
346
-	 *
347
-	 * @param string $path
348
-	 * @return array an array consisting of the storage and the internal path
349
-	 */
350
-	static public function resolvePath($path) {
351
-		if (!self::$mounts) {
352
-			\OC_Util::setupFS();
353
-		}
354
-		$mount = self::$mounts->find($path);
355
-		if ($mount) {
356
-			return array($mount->getStorage(), rtrim($mount->getInternalPath($path), '/'));
357
-		} else {
358
-			return array(null, null);
359
-		}
360
-	}
361
-
362
-	static public function init($user, $root) {
363
-		if (self::$defaultInstance) {
364
-			return false;
365
-		}
366
-		self::getLoader();
367
-		self::$defaultInstance = new View($root);
368
-
369
-		if (!self::$mounts) {
370
-			self::$mounts = \OC::$server->getMountManager();
371
-		}
372
-
373
-		//load custom mount config
374
-		self::initMountPoints($user);
375
-
376
-		self::$loaded = true;
377
-
378
-		return true;
379
-	}
380
-
381
-	static public function initMountManager() {
382
-		if (!self::$mounts) {
383
-			self::$mounts = \OC::$server->getMountManager();
384
-		}
385
-	}
386
-
387
-	/**
388
-	 * Initialize system and personal mount points for a user
389
-	 *
390
-	 * @param string $user
391
-	 * @throws \OC\User\NoUserException if the user is not available
392
-	 */
393
-	public static function initMountPoints($user = '') {
394
-		if ($user == '') {
395
-			$user = \OC_User::getUser();
396
-		}
397
-		if ($user === null || $user === false || $user === '') {
398
-			throw new \OC\User\NoUserException('Attempted to initialize mount points for null user and no user in session');
399
-		}
400
-
401
-		if (isset(self::$usersSetup[$user])) {
402
-			return;
403
-		}
404
-
405
-		self::$usersSetup[$user] = true;
406
-
407
-		$userManager = \OC::$server->getUserManager();
408
-		$userObject = $userManager->get($user);
409
-
410
-		if (is_null($userObject)) {
411
-			\OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
412
-			// reset flag, this will make it possible to rethrow the exception if called again
413
-			unset(self::$usersSetup[$user]);
414
-			throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
415
-		}
416
-
417
-		$realUid = $userObject->getUID();
418
-		// workaround in case of different casings
419
-		if ($user !== $realUid) {
420
-			$stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
421
-			\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
-			$user = $realUid;
423
-
424
-			// again with the correct casing
425
-			if (isset(self::$usersSetup[$user])) {
426
-				return;
427
-			}
428
-
429
-			self::$usersSetup[$user] = true;
430
-		}
431
-
432
-		if (\OC::$server->getLockdownManager()->canAccessFilesystem()) {
433
-			/** @var \OC\Files\Config\MountProviderCollection $mountConfigManager */
434
-			$mountConfigManager = \OC::$server->getMountProviderCollection();
435
-
436
-			// home mounts are handled seperate since we need to ensure this is mounted before we call the other mount providers
437
-			$homeMount = $mountConfigManager->getHomeMountForUser($userObject);
438
-
439
-			self::getMountManager()->addMount($homeMount);
440
-
441
-			\OC\Files\Filesystem::getStorage($user);
442
-
443
-			// Chance to mount for other storages
444
-			if ($userObject) {
445
-				$mounts = $mountConfigManager->addMountForUser($userObject, self::getMountManager());
446
-				$mounts[] = $homeMount;
447
-				$mountConfigManager->registerMounts($userObject, $mounts);
448
-			}
449
-
450
-			self::listenForNewMountProviders($mountConfigManager, $userManager);
451
-		} else {
452
-			self::getMountManager()->addMount(new MountPoint(
453
-				new NullStorage([]),
454
-				'/' . $user
455
-			));
456
-			self::getMountManager()->addMount(new MountPoint(
457
-				new NullStorage([]),
458
-				'/' . $user . '/files'
459
-			));
460
-		}
461
-		\OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
462
-	}
463
-
464
-	/**
465
-	 * Get mounts from mount providers that are registered after setup
466
-	 *
467
-	 * @param MountProviderCollection $mountConfigManager
468
-	 * @param IUserManager $userManager
469
-	 */
470
-	private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
471
-		if (!self::$listeningForProviders) {
472
-			self::$listeningForProviders = true;
473
-			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
474
-				foreach (Filesystem::$usersSetup as $user => $setup) {
475
-					$userObject = $userManager->get($user);
476
-					if ($userObject) {
477
-						$mounts = $provider->getMountsForUser($userObject, Filesystem::getLoader());
478
-						array_walk($mounts, array(self::$mounts, 'addMount'));
479
-					}
480
-				}
481
-			});
482
-		}
483
-	}
484
-
485
-	/**
486
-	 * get the default filesystem view
487
-	 *
488
-	 * @return View
489
-	 */
490
-	static public function getView() {
491
-		return self::$defaultInstance;
492
-	}
493
-
494
-	/**
495
-	 * tear down the filesystem, removing all storage providers
496
-	 */
497
-	static public function tearDown() {
498
-		self::clearMounts();
499
-		self::$defaultInstance = null;
500
-	}
501
-
502
-	/**
503
-	 * get the relative path of the root data directory for the current user
504
-	 *
505
-	 * @return string
506
-	 *
507
-	 * Returns path like /admin/files
508
-	 */
509
-	static public function getRoot() {
510
-		if (!self::$defaultInstance) {
511
-			return null;
512
-		}
513
-		return self::$defaultInstance->getRoot();
514
-	}
515
-
516
-	/**
517
-	 * clear all mounts and storage backends
518
-	 */
519
-	public static function clearMounts() {
520
-		if (self::$mounts) {
521
-			self::$usersSetup = array();
522
-			self::$mounts->clear();
523
-		}
524
-	}
525
-
526
-	/**
527
-	 * mount an \OC\Files\Storage\Storage in our virtual filesystem
528
-	 *
529
-	 * @param \OC\Files\Storage\Storage|string $class
530
-	 * @param array $arguments
531
-	 * @param string $mountpoint
532
-	 */
533
-	static public function mount($class, $arguments, $mountpoint) {
534
-		if (!self::$mounts) {
535
-			\OC_Util::setupFS();
536
-		}
537
-		$mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
538
-		self::$mounts->addMount($mount);
539
-	}
540
-
541
-	/**
542
-	 * return the path to a local version of the file
543
-	 * we need this because we can't know if a file is stored local or not from
544
-	 * outside the filestorage and for some purposes a local file is needed
545
-	 *
546
-	 * @param string $path
547
-	 * @return string
548
-	 */
549
-	static public function getLocalFile($path) {
550
-		return self::$defaultInstance->getLocalFile($path);
551
-	}
552
-
553
-	/**
554
-	 * @param string $path
555
-	 * @return string
556
-	 */
557
-	static public function getLocalFolder($path) {
558
-		return self::$defaultInstance->getLocalFolder($path);
559
-	}
560
-
561
-	/**
562
-	 * return path to file which reflects one visible in browser
563
-	 *
564
-	 * @param string $path
565
-	 * @return string
566
-	 */
567
-	static public function getLocalPath($path) {
568
-		$datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
569
-		$newpath = $path;
570
-		if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
571
-			$newpath = substr($path, strlen($datadir));
572
-		}
573
-		return $newpath;
574
-	}
575
-
576
-	/**
577
-	 * check if the requested path is valid
578
-	 *
579
-	 * @param string $path
580
-	 * @return bool
581
-	 */
582
-	static public function isValidPath($path) {
583
-		$path = self::normalizePath($path);
584
-		if (!$path || $path[0] !== '/') {
585
-			$path = '/' . $path;
586
-		}
587
-		if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
588
-			return false;
589
-		}
590
-		return true;
591
-	}
592
-
593
-	/**
594
-	 * checks if a file is blacklisted for storage in the filesystem
595
-	 * Listens to write and rename hooks
596
-	 *
597
-	 * @param array $data from hook
598
-	 */
599
-	static public function isBlacklisted($data) {
600
-		if (isset($data['path'])) {
601
-			$path = $data['path'];
602
-		} else if (isset($data['newpath'])) {
603
-			$path = $data['newpath'];
604
-		}
605
-		if (isset($path)) {
606
-			if (self::isFileBlacklisted($path)) {
607
-				$data['run'] = false;
608
-			}
609
-		}
610
-	}
611
-
612
-	/**
613
-	 * @param string $filename
614
-	 * @return bool
615
-	 */
616
-	static public function isFileBlacklisted($filename) {
617
-		$filename = self::normalizePath($filename);
618
-
619
-		$blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess'));
620
-		$filename = strtolower(basename($filename));
621
-		return in_array($filename, $blacklist);
622
-	}
623
-
624
-	/**
625
-	 * check if the directory should be ignored when scanning
626
-	 * NOTE: the special directories . and .. would cause never ending recursion
627
-	 *
628
-	 * @param String $dir
629
-	 * @return boolean
630
-	 */
631
-	static public function isIgnoredDir($dir) {
632
-		if ($dir === '.' || $dir === '..') {
633
-			return true;
634
-		}
635
-		return false;
636
-	}
637
-
638
-	/**
639
-	 * following functions are equivalent to their php builtin equivalents for arguments/return values.
640
-	 */
641
-	static public function mkdir($path) {
642
-		return self::$defaultInstance->mkdir($path);
643
-	}
644
-
645
-	static public function rmdir($path) {
646
-		return self::$defaultInstance->rmdir($path);
647
-	}
648
-
649
-	static public function is_dir($path) {
650
-		return self::$defaultInstance->is_dir($path);
651
-	}
652
-
653
-	static public function is_file($path) {
654
-		return self::$defaultInstance->is_file($path);
655
-	}
656
-
657
-	static public function stat($path) {
658
-		return self::$defaultInstance->stat($path);
659
-	}
660
-
661
-	static public function filetype($path) {
662
-		return self::$defaultInstance->filetype($path);
663
-	}
664
-
665
-	static public function filesize($path) {
666
-		return self::$defaultInstance->filesize($path);
667
-	}
668
-
669
-	static public function readfile($path) {
670
-		return self::$defaultInstance->readfile($path);
671
-	}
672
-
673
-	static public function isCreatable($path) {
674
-		return self::$defaultInstance->isCreatable($path);
675
-	}
676
-
677
-	static public function isReadable($path) {
678
-		return self::$defaultInstance->isReadable($path);
679
-	}
680
-
681
-	static public function isUpdatable($path) {
682
-		return self::$defaultInstance->isUpdatable($path);
683
-	}
684
-
685
-	static public function isDeletable($path) {
686
-		return self::$defaultInstance->isDeletable($path);
687
-	}
688
-
689
-	static public function isSharable($path) {
690
-		return self::$defaultInstance->isSharable($path);
691
-	}
692
-
693
-	static public function file_exists($path) {
694
-		return self::$defaultInstance->file_exists($path);
695
-	}
696
-
697
-	static public function filemtime($path) {
698
-		return self::$defaultInstance->filemtime($path);
699
-	}
700
-
701
-	static public function touch($path, $mtime = null) {
702
-		return self::$defaultInstance->touch($path, $mtime);
703
-	}
704
-
705
-	/**
706
-	 * @return string
707
-	 */
708
-	static public function file_get_contents($path) {
709
-		return self::$defaultInstance->file_get_contents($path);
710
-	}
711
-
712
-	static public function file_put_contents($path, $data) {
713
-		return self::$defaultInstance->file_put_contents($path, $data);
714
-	}
715
-
716
-	static public function unlink($path) {
717
-		return self::$defaultInstance->unlink($path);
718
-	}
719
-
720
-	static public function rename($path1, $path2) {
721
-		return self::$defaultInstance->rename($path1, $path2);
722
-	}
723
-
724
-	static public function copy($path1, $path2) {
725
-		return self::$defaultInstance->copy($path1, $path2);
726
-	}
727
-
728
-	static public function fopen($path, $mode) {
729
-		return self::$defaultInstance->fopen($path, $mode);
730
-	}
731
-
732
-	/**
733
-	 * @return string
734
-	 */
735
-	static public function toTmpFile($path) {
736
-		return self::$defaultInstance->toTmpFile($path);
737
-	}
738
-
739
-	static public function fromTmpFile($tmpFile, $path) {
740
-		return self::$defaultInstance->fromTmpFile($tmpFile, $path);
741
-	}
742
-
743
-	static public function getMimeType($path) {
744
-		return self::$defaultInstance->getMimeType($path);
745
-	}
746
-
747
-	static public function hash($type, $path, $raw = false) {
748
-		return self::$defaultInstance->hash($type, $path, $raw);
749
-	}
750
-
751
-	static public function free_space($path = '/') {
752
-		return self::$defaultInstance->free_space($path);
753
-	}
754
-
755
-	static public function search($query) {
756
-		return self::$defaultInstance->search($query);
757
-	}
758
-
759
-	/**
760
-	 * @param string $query
761
-	 */
762
-	static public function searchByMime($query) {
763
-		return self::$defaultInstance->searchByMime($query);
764
-	}
765
-
766
-	/**
767
-	 * @param string|int $tag name or tag id
768
-	 * @param string $userId owner of the tags
769
-	 * @return FileInfo[] array or file info
770
-	 */
771
-	static public function searchByTag($tag, $userId) {
772
-		return self::$defaultInstance->searchByTag($tag, $userId);
773
-	}
774
-
775
-	/**
776
-	 * check if a file or folder has been updated since $time
777
-	 *
778
-	 * @param string $path
779
-	 * @param int $time
780
-	 * @return bool
781
-	 */
782
-	static public function hasUpdated($path, $time) {
783
-		return self::$defaultInstance->hasUpdated($path, $time);
784
-	}
785
-
786
-	/**
787
-	 * Fix common problems with a file path
788
-	 *
789
-	 * @param string $path
790
-	 * @param bool $stripTrailingSlash whether to strip the trailing slash
791
-	 * @param bool $isAbsolutePath whether the given path is absolute
792
-	 * @param bool $keepUnicode true to disable unicode normalization
793
-	 * @return string
794
-	 */
795
-	public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
796
-		if (is_null(self::$normalizedPathCache)) {
797
-			self::$normalizedPathCache = new CappedMemoryCache(2048);
798
-		}
799
-
800
-		/**
801
-		 * FIXME: This is a workaround for existing classes and files which call
802
-		 *        this function with another type than a valid string. This
803
-		 *        conversion should get removed as soon as all existing
804
-		 *        function calls have been fixed.
805
-		 */
806
-		$path = (string)$path;
807
-
808
-		$cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
809
-
810
-		if (isset(self::$normalizedPathCache[$cacheKey])) {
811
-			return self::$normalizedPathCache[$cacheKey];
812
-		}
813
-
814
-		if ($path == '') {
815
-			return '/';
816
-		}
817
-
818
-		//normalize unicode if possible
819
-		if (!$keepUnicode) {
820
-			$path = \OC_Util::normalizeUnicode($path);
821
-		}
822
-
823
-		//no windows style slashes
824
-		$path = str_replace('\\', '/', $path);
825
-
826
-		//add leading slash
827
-		if ($path[0] !== '/') {
828
-			$path = '/' . $path;
829
-		}
830
-
831
-		// remove '/./'
832
-		// ugly, but str_replace() can't replace them all in one go
833
-		// as the replacement itself is part of the search string
834
-		// which will only be found during the next iteration
835
-		while (strpos($path, '/./') !== false) {
836
-			$path = str_replace('/./', '/', $path);
837
-		}
838
-		// remove sequences of slashes
839
-		$path = preg_replace('#/{2,}#', '/', $path);
840
-
841
-		//remove trailing slash
842
-		if ($stripTrailingSlash and strlen($path) > 1) {
843
-			$path = rtrim($path, '/');
844
-		}
845
-
846
-		// remove trailing '/.'
847
-		if (substr($path, -2) == '/.') {
848
-			$path = substr($path, 0, -2);
849
-		}
850
-
851
-		$normalizedPath = $path;
852
-		self::$normalizedPathCache[$cacheKey] = $normalizedPath;
853
-
854
-		return $normalizedPath;
855
-	}
856
-
857
-	/**
858
-	 * get the filesystem info
859
-	 *
860
-	 * @param string $path
861
-	 * @param boolean $includeMountPoints whether to add mountpoint sizes,
862
-	 * defaults to true
863
-	 * @return \OC\Files\FileInfo|bool False if file does not exist
864
-	 */
865
-	public static function getFileInfo($path, $includeMountPoints = true) {
866
-		return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
867
-	}
868
-
869
-	/**
870
-	 * change file metadata
871
-	 *
872
-	 * @param string $path
873
-	 * @param array $data
874
-	 * @return int
875
-	 *
876
-	 * returns the fileid of the updated file
877
-	 */
878
-	public static function putFileInfo($path, $data) {
879
-		return self::$defaultInstance->putFileInfo($path, $data);
880
-	}
881
-
882
-	/**
883
-	 * get the content of a directory
884
-	 *
885
-	 * @param string $directory path under datadirectory
886
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
887
-	 * @return \OC\Files\FileInfo[]
888
-	 */
889
-	public static function getDirectoryContent($directory, $mimetype_filter = '') {
890
-		return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
891
-	}
892
-
893
-	/**
894
-	 * Get the path of a file by id
895
-	 *
896
-	 * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
897
-	 *
898
-	 * @param int $id
899
-	 * @throws NotFoundException
900
-	 * @return string
901
-	 */
902
-	public static function getPath($id) {
903
-		return self::$defaultInstance->getPath($id);
904
-	}
905
-
906
-	/**
907
-	 * Get the owner for a file or folder
908
-	 *
909
-	 * @param string $path
910
-	 * @return string
911
-	 */
912
-	public static function getOwner($path) {
913
-		return self::$defaultInstance->getOwner($path);
914
-	}
915
-
916
-	/**
917
-	 * get the ETag for a file or folder
918
-	 *
919
-	 * @param string $path
920
-	 * @return string
921
-	 */
922
-	static public function getETag($path) {
923
-		return self::$defaultInstance->getETag($path);
924
-	}
72
+    /**
73
+     * @var Mount\Manager $mounts
74
+     */
75
+    private static $mounts;
76
+
77
+    public static $loaded = false;
78
+    /**
79
+     * @var \OC\Files\View $defaultInstance
80
+     */
81
+    static private $defaultInstance;
82
+
83
+    static private $usersSetup = array();
84
+
85
+    static private $normalizedPathCache = null;
86
+
87
+    static private $listeningForProviders = false;
88
+
89
+    /**
90
+     * classname which used for hooks handling
91
+     * used as signalclass in OC_Hooks::emit()
92
+     */
93
+    const CLASSNAME = 'OC_Filesystem';
94
+
95
+    /**
96
+     * signalname emitted before file renaming
97
+     *
98
+     * @param string $oldpath
99
+     * @param string $newpath
100
+     */
101
+    const signal_rename = 'rename';
102
+
103
+    /**
104
+     * signal emitted after file renaming
105
+     *
106
+     * @param string $oldpath
107
+     * @param string $newpath
108
+     */
109
+    const signal_post_rename = 'post_rename';
110
+
111
+    /**
112
+     * signal emitted before file/dir creation
113
+     *
114
+     * @param string $path
115
+     * @param bool $run changing this flag to false in hook handler will cancel event
116
+     */
117
+    const signal_create = 'create';
118
+
119
+    /**
120
+     * signal emitted after file/dir creation
121
+     *
122
+     * @param string $path
123
+     * @param bool $run changing this flag to false in hook handler will cancel event
124
+     */
125
+    const signal_post_create = 'post_create';
126
+
127
+    /**
128
+     * signal emits before file/dir copy
129
+     *
130
+     * @param string $oldpath
131
+     * @param string $newpath
132
+     * @param bool $run changing this flag to false in hook handler will cancel event
133
+     */
134
+    const signal_copy = 'copy';
135
+
136
+    /**
137
+     * signal emits after file/dir copy
138
+     *
139
+     * @param string $oldpath
140
+     * @param string $newpath
141
+     */
142
+    const signal_post_copy = 'post_copy';
143
+
144
+    /**
145
+     * signal emits before file/dir save
146
+     *
147
+     * @param string $path
148
+     * @param bool $run changing this flag to false in hook handler will cancel event
149
+     */
150
+    const signal_write = 'write';
151
+
152
+    /**
153
+     * signal emits after file/dir save
154
+     *
155
+     * @param string $path
156
+     */
157
+    const signal_post_write = 'post_write';
158
+
159
+    /**
160
+     * signal emitted before file/dir update
161
+     *
162
+     * @param string $path
163
+     * @param bool $run changing this flag to false in hook handler will cancel event
164
+     */
165
+    const signal_update = 'update';
166
+
167
+    /**
168
+     * signal emitted after file/dir update
169
+     *
170
+     * @param string $path
171
+     * @param bool $run changing this flag to false in hook handler will cancel event
172
+     */
173
+    const signal_post_update = 'post_update';
174
+
175
+    /**
176
+     * signal emits when reading file/dir
177
+     *
178
+     * @param string $path
179
+     */
180
+    const signal_read = 'read';
181
+
182
+    /**
183
+     * signal emits when removing file/dir
184
+     *
185
+     * @param string $path
186
+     */
187
+    const signal_delete = 'delete';
188
+
189
+    /**
190
+     * parameters definitions for signals
191
+     */
192
+    const signal_param_path = 'path';
193
+    const signal_param_oldpath = 'oldpath';
194
+    const signal_param_newpath = 'newpath';
195
+
196
+    /**
197
+     * run - changing this flag to false in hook handler will cancel event
198
+     */
199
+    const signal_param_run = 'run';
200
+
201
+    const signal_create_mount = 'create_mount';
202
+    const signal_delete_mount = 'delete_mount';
203
+    const signal_param_mount_type = 'mounttype';
204
+    const signal_param_users = 'users';
205
+
206
+    /**
207
+     * @var \OC\Files\Storage\StorageFactory $loader
208
+     */
209
+    private static $loader;
210
+
211
+    /** @var bool */
212
+    private static $logWarningWhenAddingStorageWrapper = true;
213
+
214
+    /**
215
+     * @param bool $shouldLog
216
+     * @return bool previous value
217
+     * @internal
218
+     */
219
+    public static function logWarningWhenAddingStorageWrapper($shouldLog) {
220
+        $previousValue = self::$logWarningWhenAddingStorageWrapper;
221
+        self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
222
+        return $previousValue;
223
+    }
224
+
225
+    /**
226
+     * @param string $wrapperName
227
+     * @param callable $wrapper
228
+     * @param int $priority
229
+     */
230
+    public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
231
+        if (self::$logWarningWhenAddingStorageWrapper) {
232
+            \OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
233
+                'wrapper' => $wrapperName,
234
+                'app' => 'filesystem',
235
+            ]);
236
+        }
237
+
238
+        $mounts = self::getMountManager()->getAll();
239
+        if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
240
+            // do not re-wrap if storage with this name already existed
241
+            return;
242
+        }
243
+    }
244
+
245
+    /**
246
+     * Returns the storage factory
247
+     *
248
+     * @return \OCP\Files\Storage\IStorageFactory
249
+     */
250
+    public static function getLoader() {
251
+        if (!self::$loader) {
252
+            self::$loader = new StorageFactory();
253
+        }
254
+        return self::$loader;
255
+    }
256
+
257
+    /**
258
+     * Returns the mount manager
259
+     *
260
+     * @return \OC\Files\Mount\Manager
261
+     */
262
+    public static function getMountManager($user = '') {
263
+        if (!self::$mounts) {
264
+            \OC_Util::setupFS($user);
265
+        }
266
+        return self::$mounts;
267
+    }
268
+
269
+    /**
270
+     * get the mountpoint of the storage object for a path
271
+     * ( note: because a storage is not always mounted inside the fakeroot, the
272
+     * returned mountpoint is relative to the absolute root of the filesystem
273
+     * and doesn't take the chroot into account )
274
+     *
275
+     * @param string $path
276
+     * @return string
277
+     */
278
+    static public function getMountPoint($path) {
279
+        if (!self::$mounts) {
280
+            \OC_Util::setupFS();
281
+        }
282
+        $mount = self::$mounts->find($path);
283
+        if ($mount) {
284
+            return $mount->getMountPoint();
285
+        } else {
286
+            return '';
287
+        }
288
+    }
289
+
290
+    /**
291
+     * get a list of all mount points in a directory
292
+     *
293
+     * @param string $path
294
+     * @return string[]
295
+     */
296
+    static public function getMountPoints($path) {
297
+        if (!self::$mounts) {
298
+            \OC_Util::setupFS();
299
+        }
300
+        $result = array();
301
+        $mounts = self::$mounts->findIn($path);
302
+        foreach ($mounts as $mount) {
303
+            $result[] = $mount->getMountPoint();
304
+        }
305
+        return $result;
306
+    }
307
+
308
+    /**
309
+     * get the storage mounted at $mountPoint
310
+     *
311
+     * @param string $mountPoint
312
+     * @return \OC\Files\Storage\Storage
313
+     */
314
+    public static function getStorage($mountPoint) {
315
+        if (!self::$mounts) {
316
+            \OC_Util::setupFS();
317
+        }
318
+        $mount = self::$mounts->find($mountPoint);
319
+        return $mount->getStorage();
320
+    }
321
+
322
+    /**
323
+     * @param string $id
324
+     * @return Mount\MountPoint[]
325
+     */
326
+    public static function getMountByStorageId($id) {
327
+        if (!self::$mounts) {
328
+            \OC_Util::setupFS();
329
+        }
330
+        return self::$mounts->findByStorageId($id);
331
+    }
332
+
333
+    /**
334
+     * @param int $id
335
+     * @return Mount\MountPoint[]
336
+     */
337
+    public static function getMountByNumericId($id) {
338
+        if (!self::$mounts) {
339
+            \OC_Util::setupFS();
340
+        }
341
+        return self::$mounts->findByNumericId($id);
342
+    }
343
+
344
+    /**
345
+     * resolve a path to a storage and internal path
346
+     *
347
+     * @param string $path
348
+     * @return array an array consisting of the storage and the internal path
349
+     */
350
+    static public function resolvePath($path) {
351
+        if (!self::$mounts) {
352
+            \OC_Util::setupFS();
353
+        }
354
+        $mount = self::$mounts->find($path);
355
+        if ($mount) {
356
+            return array($mount->getStorage(), rtrim($mount->getInternalPath($path), '/'));
357
+        } else {
358
+            return array(null, null);
359
+        }
360
+    }
361
+
362
+    static public function init($user, $root) {
363
+        if (self::$defaultInstance) {
364
+            return false;
365
+        }
366
+        self::getLoader();
367
+        self::$defaultInstance = new View($root);
368
+
369
+        if (!self::$mounts) {
370
+            self::$mounts = \OC::$server->getMountManager();
371
+        }
372
+
373
+        //load custom mount config
374
+        self::initMountPoints($user);
375
+
376
+        self::$loaded = true;
377
+
378
+        return true;
379
+    }
380
+
381
+    static public function initMountManager() {
382
+        if (!self::$mounts) {
383
+            self::$mounts = \OC::$server->getMountManager();
384
+        }
385
+    }
386
+
387
+    /**
388
+     * Initialize system and personal mount points for a user
389
+     *
390
+     * @param string $user
391
+     * @throws \OC\User\NoUserException if the user is not available
392
+     */
393
+    public static function initMountPoints($user = '') {
394
+        if ($user == '') {
395
+            $user = \OC_User::getUser();
396
+        }
397
+        if ($user === null || $user === false || $user === '') {
398
+            throw new \OC\User\NoUserException('Attempted to initialize mount points for null user and no user in session');
399
+        }
400
+
401
+        if (isset(self::$usersSetup[$user])) {
402
+            return;
403
+        }
404
+
405
+        self::$usersSetup[$user] = true;
406
+
407
+        $userManager = \OC::$server->getUserManager();
408
+        $userObject = $userManager->get($user);
409
+
410
+        if (is_null($userObject)) {
411
+            \OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
412
+            // reset flag, this will make it possible to rethrow the exception if called again
413
+            unset(self::$usersSetup[$user]);
414
+            throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
415
+        }
416
+
417
+        $realUid = $userObject->getUID();
418
+        // workaround in case of different casings
419
+        if ($user !== $realUid) {
420
+            $stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
421
+            \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
+            $user = $realUid;
423
+
424
+            // again with the correct casing
425
+            if (isset(self::$usersSetup[$user])) {
426
+                return;
427
+            }
428
+
429
+            self::$usersSetup[$user] = true;
430
+        }
431
+
432
+        if (\OC::$server->getLockdownManager()->canAccessFilesystem()) {
433
+            /** @var \OC\Files\Config\MountProviderCollection $mountConfigManager */
434
+            $mountConfigManager = \OC::$server->getMountProviderCollection();
435
+
436
+            // home mounts are handled seperate since we need to ensure this is mounted before we call the other mount providers
437
+            $homeMount = $mountConfigManager->getHomeMountForUser($userObject);
438
+
439
+            self::getMountManager()->addMount($homeMount);
440
+
441
+            \OC\Files\Filesystem::getStorage($user);
442
+
443
+            // Chance to mount for other storages
444
+            if ($userObject) {
445
+                $mounts = $mountConfigManager->addMountForUser($userObject, self::getMountManager());
446
+                $mounts[] = $homeMount;
447
+                $mountConfigManager->registerMounts($userObject, $mounts);
448
+            }
449
+
450
+            self::listenForNewMountProviders($mountConfigManager, $userManager);
451
+        } else {
452
+            self::getMountManager()->addMount(new MountPoint(
453
+                new NullStorage([]),
454
+                '/' . $user
455
+            ));
456
+            self::getMountManager()->addMount(new MountPoint(
457
+                new NullStorage([]),
458
+                '/' . $user . '/files'
459
+            ));
460
+        }
461
+        \OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
462
+    }
463
+
464
+    /**
465
+     * Get mounts from mount providers that are registered after setup
466
+     *
467
+     * @param MountProviderCollection $mountConfigManager
468
+     * @param IUserManager $userManager
469
+     */
470
+    private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
471
+        if (!self::$listeningForProviders) {
472
+            self::$listeningForProviders = true;
473
+            $mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
474
+                foreach (Filesystem::$usersSetup as $user => $setup) {
475
+                    $userObject = $userManager->get($user);
476
+                    if ($userObject) {
477
+                        $mounts = $provider->getMountsForUser($userObject, Filesystem::getLoader());
478
+                        array_walk($mounts, array(self::$mounts, 'addMount'));
479
+                    }
480
+                }
481
+            });
482
+        }
483
+    }
484
+
485
+    /**
486
+     * get the default filesystem view
487
+     *
488
+     * @return View
489
+     */
490
+    static public function getView() {
491
+        return self::$defaultInstance;
492
+    }
493
+
494
+    /**
495
+     * tear down the filesystem, removing all storage providers
496
+     */
497
+    static public function tearDown() {
498
+        self::clearMounts();
499
+        self::$defaultInstance = null;
500
+    }
501
+
502
+    /**
503
+     * get the relative path of the root data directory for the current user
504
+     *
505
+     * @return string
506
+     *
507
+     * Returns path like /admin/files
508
+     */
509
+    static public function getRoot() {
510
+        if (!self::$defaultInstance) {
511
+            return null;
512
+        }
513
+        return self::$defaultInstance->getRoot();
514
+    }
515
+
516
+    /**
517
+     * clear all mounts and storage backends
518
+     */
519
+    public static function clearMounts() {
520
+        if (self::$mounts) {
521
+            self::$usersSetup = array();
522
+            self::$mounts->clear();
523
+        }
524
+    }
525
+
526
+    /**
527
+     * mount an \OC\Files\Storage\Storage in our virtual filesystem
528
+     *
529
+     * @param \OC\Files\Storage\Storage|string $class
530
+     * @param array $arguments
531
+     * @param string $mountpoint
532
+     */
533
+    static public function mount($class, $arguments, $mountpoint) {
534
+        if (!self::$mounts) {
535
+            \OC_Util::setupFS();
536
+        }
537
+        $mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
538
+        self::$mounts->addMount($mount);
539
+    }
540
+
541
+    /**
542
+     * return the path to a local version of the file
543
+     * we need this because we can't know if a file is stored local or not from
544
+     * outside the filestorage and for some purposes a local file is needed
545
+     *
546
+     * @param string $path
547
+     * @return string
548
+     */
549
+    static public function getLocalFile($path) {
550
+        return self::$defaultInstance->getLocalFile($path);
551
+    }
552
+
553
+    /**
554
+     * @param string $path
555
+     * @return string
556
+     */
557
+    static public function getLocalFolder($path) {
558
+        return self::$defaultInstance->getLocalFolder($path);
559
+    }
560
+
561
+    /**
562
+     * return path to file which reflects one visible in browser
563
+     *
564
+     * @param string $path
565
+     * @return string
566
+     */
567
+    static public function getLocalPath($path) {
568
+        $datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
569
+        $newpath = $path;
570
+        if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
571
+            $newpath = substr($path, strlen($datadir));
572
+        }
573
+        return $newpath;
574
+    }
575
+
576
+    /**
577
+     * check if the requested path is valid
578
+     *
579
+     * @param string $path
580
+     * @return bool
581
+     */
582
+    static public function isValidPath($path) {
583
+        $path = self::normalizePath($path);
584
+        if (!$path || $path[0] !== '/') {
585
+            $path = '/' . $path;
586
+        }
587
+        if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
588
+            return false;
589
+        }
590
+        return true;
591
+    }
592
+
593
+    /**
594
+     * checks if a file is blacklisted for storage in the filesystem
595
+     * Listens to write and rename hooks
596
+     *
597
+     * @param array $data from hook
598
+     */
599
+    static public function isBlacklisted($data) {
600
+        if (isset($data['path'])) {
601
+            $path = $data['path'];
602
+        } else if (isset($data['newpath'])) {
603
+            $path = $data['newpath'];
604
+        }
605
+        if (isset($path)) {
606
+            if (self::isFileBlacklisted($path)) {
607
+                $data['run'] = false;
608
+            }
609
+        }
610
+    }
611
+
612
+    /**
613
+     * @param string $filename
614
+     * @return bool
615
+     */
616
+    static public function isFileBlacklisted($filename) {
617
+        $filename = self::normalizePath($filename);
618
+
619
+        $blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess'));
620
+        $filename = strtolower(basename($filename));
621
+        return in_array($filename, $blacklist);
622
+    }
623
+
624
+    /**
625
+     * check if the directory should be ignored when scanning
626
+     * NOTE: the special directories . and .. would cause never ending recursion
627
+     *
628
+     * @param String $dir
629
+     * @return boolean
630
+     */
631
+    static public function isIgnoredDir($dir) {
632
+        if ($dir === '.' || $dir === '..') {
633
+            return true;
634
+        }
635
+        return false;
636
+    }
637
+
638
+    /**
639
+     * following functions are equivalent to their php builtin equivalents for arguments/return values.
640
+     */
641
+    static public function mkdir($path) {
642
+        return self::$defaultInstance->mkdir($path);
643
+    }
644
+
645
+    static public function rmdir($path) {
646
+        return self::$defaultInstance->rmdir($path);
647
+    }
648
+
649
+    static public function is_dir($path) {
650
+        return self::$defaultInstance->is_dir($path);
651
+    }
652
+
653
+    static public function is_file($path) {
654
+        return self::$defaultInstance->is_file($path);
655
+    }
656
+
657
+    static public function stat($path) {
658
+        return self::$defaultInstance->stat($path);
659
+    }
660
+
661
+    static public function filetype($path) {
662
+        return self::$defaultInstance->filetype($path);
663
+    }
664
+
665
+    static public function filesize($path) {
666
+        return self::$defaultInstance->filesize($path);
667
+    }
668
+
669
+    static public function readfile($path) {
670
+        return self::$defaultInstance->readfile($path);
671
+    }
672
+
673
+    static public function isCreatable($path) {
674
+        return self::$defaultInstance->isCreatable($path);
675
+    }
676
+
677
+    static public function isReadable($path) {
678
+        return self::$defaultInstance->isReadable($path);
679
+    }
680
+
681
+    static public function isUpdatable($path) {
682
+        return self::$defaultInstance->isUpdatable($path);
683
+    }
684
+
685
+    static public function isDeletable($path) {
686
+        return self::$defaultInstance->isDeletable($path);
687
+    }
688
+
689
+    static public function isSharable($path) {
690
+        return self::$defaultInstance->isSharable($path);
691
+    }
692
+
693
+    static public function file_exists($path) {
694
+        return self::$defaultInstance->file_exists($path);
695
+    }
696
+
697
+    static public function filemtime($path) {
698
+        return self::$defaultInstance->filemtime($path);
699
+    }
700
+
701
+    static public function touch($path, $mtime = null) {
702
+        return self::$defaultInstance->touch($path, $mtime);
703
+    }
704
+
705
+    /**
706
+     * @return string
707
+     */
708
+    static public function file_get_contents($path) {
709
+        return self::$defaultInstance->file_get_contents($path);
710
+    }
711
+
712
+    static public function file_put_contents($path, $data) {
713
+        return self::$defaultInstance->file_put_contents($path, $data);
714
+    }
715
+
716
+    static public function unlink($path) {
717
+        return self::$defaultInstance->unlink($path);
718
+    }
719
+
720
+    static public function rename($path1, $path2) {
721
+        return self::$defaultInstance->rename($path1, $path2);
722
+    }
723
+
724
+    static public function copy($path1, $path2) {
725
+        return self::$defaultInstance->copy($path1, $path2);
726
+    }
727
+
728
+    static public function fopen($path, $mode) {
729
+        return self::$defaultInstance->fopen($path, $mode);
730
+    }
731
+
732
+    /**
733
+     * @return string
734
+     */
735
+    static public function toTmpFile($path) {
736
+        return self::$defaultInstance->toTmpFile($path);
737
+    }
738
+
739
+    static public function fromTmpFile($tmpFile, $path) {
740
+        return self::$defaultInstance->fromTmpFile($tmpFile, $path);
741
+    }
742
+
743
+    static public function getMimeType($path) {
744
+        return self::$defaultInstance->getMimeType($path);
745
+    }
746
+
747
+    static public function hash($type, $path, $raw = false) {
748
+        return self::$defaultInstance->hash($type, $path, $raw);
749
+    }
750
+
751
+    static public function free_space($path = '/') {
752
+        return self::$defaultInstance->free_space($path);
753
+    }
754
+
755
+    static public function search($query) {
756
+        return self::$defaultInstance->search($query);
757
+    }
758
+
759
+    /**
760
+     * @param string $query
761
+     */
762
+    static public function searchByMime($query) {
763
+        return self::$defaultInstance->searchByMime($query);
764
+    }
765
+
766
+    /**
767
+     * @param string|int $tag name or tag id
768
+     * @param string $userId owner of the tags
769
+     * @return FileInfo[] array or file info
770
+     */
771
+    static public function searchByTag($tag, $userId) {
772
+        return self::$defaultInstance->searchByTag($tag, $userId);
773
+    }
774
+
775
+    /**
776
+     * check if a file or folder has been updated since $time
777
+     *
778
+     * @param string $path
779
+     * @param int $time
780
+     * @return bool
781
+     */
782
+    static public function hasUpdated($path, $time) {
783
+        return self::$defaultInstance->hasUpdated($path, $time);
784
+    }
785
+
786
+    /**
787
+     * Fix common problems with a file path
788
+     *
789
+     * @param string $path
790
+     * @param bool $stripTrailingSlash whether to strip the trailing slash
791
+     * @param bool $isAbsolutePath whether the given path is absolute
792
+     * @param bool $keepUnicode true to disable unicode normalization
793
+     * @return string
794
+     */
795
+    public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
796
+        if (is_null(self::$normalizedPathCache)) {
797
+            self::$normalizedPathCache = new CappedMemoryCache(2048);
798
+        }
799
+
800
+        /**
801
+         * FIXME: This is a workaround for existing classes and files which call
802
+         *        this function with another type than a valid string. This
803
+         *        conversion should get removed as soon as all existing
804
+         *        function calls have been fixed.
805
+         */
806
+        $path = (string)$path;
807
+
808
+        $cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
809
+
810
+        if (isset(self::$normalizedPathCache[$cacheKey])) {
811
+            return self::$normalizedPathCache[$cacheKey];
812
+        }
813
+
814
+        if ($path == '') {
815
+            return '/';
816
+        }
817
+
818
+        //normalize unicode if possible
819
+        if (!$keepUnicode) {
820
+            $path = \OC_Util::normalizeUnicode($path);
821
+        }
822
+
823
+        //no windows style slashes
824
+        $path = str_replace('\\', '/', $path);
825
+
826
+        //add leading slash
827
+        if ($path[0] !== '/') {
828
+            $path = '/' . $path;
829
+        }
830
+
831
+        // remove '/./'
832
+        // ugly, but str_replace() can't replace them all in one go
833
+        // as the replacement itself is part of the search string
834
+        // which will only be found during the next iteration
835
+        while (strpos($path, '/./') !== false) {
836
+            $path = str_replace('/./', '/', $path);
837
+        }
838
+        // remove sequences of slashes
839
+        $path = preg_replace('#/{2,}#', '/', $path);
840
+
841
+        //remove trailing slash
842
+        if ($stripTrailingSlash and strlen($path) > 1) {
843
+            $path = rtrim($path, '/');
844
+        }
845
+
846
+        // remove trailing '/.'
847
+        if (substr($path, -2) == '/.') {
848
+            $path = substr($path, 0, -2);
849
+        }
850
+
851
+        $normalizedPath = $path;
852
+        self::$normalizedPathCache[$cacheKey] = $normalizedPath;
853
+
854
+        return $normalizedPath;
855
+    }
856
+
857
+    /**
858
+     * get the filesystem info
859
+     *
860
+     * @param string $path
861
+     * @param boolean $includeMountPoints whether to add mountpoint sizes,
862
+     * defaults to true
863
+     * @return \OC\Files\FileInfo|bool False if file does not exist
864
+     */
865
+    public static function getFileInfo($path, $includeMountPoints = true) {
866
+        return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
867
+    }
868
+
869
+    /**
870
+     * change file metadata
871
+     *
872
+     * @param string $path
873
+     * @param array $data
874
+     * @return int
875
+     *
876
+     * returns the fileid of the updated file
877
+     */
878
+    public static function putFileInfo($path, $data) {
879
+        return self::$defaultInstance->putFileInfo($path, $data);
880
+    }
881
+
882
+    /**
883
+     * get the content of a directory
884
+     *
885
+     * @param string $directory path under datadirectory
886
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
887
+     * @return \OC\Files\FileInfo[]
888
+     */
889
+    public static function getDirectoryContent($directory, $mimetype_filter = '') {
890
+        return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
891
+    }
892
+
893
+    /**
894
+     * Get the path of a file by id
895
+     *
896
+     * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
897
+     *
898
+     * @param int $id
899
+     * @throws NotFoundException
900
+     * @return string
901
+     */
902
+    public static function getPath($id) {
903
+        return self::$defaultInstance->getPath($id);
904
+    }
905
+
906
+    /**
907
+     * Get the owner for a file or folder
908
+     *
909
+     * @param string $path
910
+     * @return string
911
+     */
912
+    public static function getOwner($path) {
913
+        return self::$defaultInstance->getOwner($path);
914
+    }
915
+
916
+    /**
917
+     * get the ETag for a file or folder
918
+     *
919
+     * @param string $path
920
+     * @return string
921
+     */
922
+    static public function getETag($path) {
923
+        return self::$defaultInstance->getETag($path);
924
+    }
925 925
 }
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.
Indentation   +976 added lines, -976 removed lines patch added patch discarded remove patch
@@ -48,981 +48,981 @@
 block discarded – undo
48 48
 
49 49
 class Encryption extends Wrapper {
50 50
 
51
-	use LocalTempFileTrait;
52
-
53
-	/** @var string */
54
-	private $mountPoint;
55
-
56
-	/** @var \OC\Encryption\Util */
57
-	private $util;
58
-
59
-	/** @var \OCP\Encryption\IManager */
60
-	private $encryptionManager;
61
-
62
-	/** @var \OCP\ILogger */
63
-	private $logger;
64
-
65
-	/** @var string */
66
-	private $uid;
67
-
68
-	/** @var array */
69
-	protected $unencryptedSize;
70
-
71
-	/** @var \OCP\Encryption\IFile */
72
-	private $fileHelper;
73
-
74
-	/** @var IMountPoint */
75
-	private $mount;
76
-
77
-	/** @var IStorage */
78
-	private $keyStorage;
79
-
80
-	/** @var Update */
81
-	private $update;
82
-
83
-	/** @var Manager */
84
-	private $mountManager;
85
-
86
-	/** @var array remember for which path we execute the repair step to avoid recursions */
87
-	private $fixUnencryptedSizeOf = array();
88
-
89
-	/** @var  ArrayCache */
90
-	private $arrayCache;
91
-
92
-	/**
93
-	 * @param array $parameters
94
-	 * @param IManager $encryptionManager
95
-	 * @param Util $util
96
-	 * @param ILogger $logger
97
-	 * @param IFile $fileHelper
98
-	 * @param string $uid
99
-	 * @param IStorage $keyStorage
100
-	 * @param Update $update
101
-	 * @param Manager $mountManager
102
-	 * @param ArrayCache $arrayCache
103
-	 */
104
-	public function __construct(
105
-			$parameters,
106
-			IManager $encryptionManager = null,
107
-			Util $util = null,
108
-			ILogger $logger = null,
109
-			IFile $fileHelper = null,
110
-			$uid = null,
111
-			IStorage $keyStorage = null,
112
-			Update $update = null,
113
-			Manager $mountManager = null,
114
-			ArrayCache $arrayCache = null
115
-		) {
116
-
117
-		$this->mountPoint = $parameters['mountPoint'];
118
-		$this->mount = $parameters['mount'];
119
-		$this->encryptionManager = $encryptionManager;
120
-		$this->util = $util;
121
-		$this->logger = $logger;
122
-		$this->uid = $uid;
123
-		$this->fileHelper = $fileHelper;
124
-		$this->keyStorage = $keyStorage;
125
-		$this->unencryptedSize = array();
126
-		$this->update = $update;
127
-		$this->mountManager = $mountManager;
128
-		$this->arrayCache = $arrayCache;
129
-		parent::__construct($parameters);
130
-	}
131
-
132
-	/**
133
-	 * see http://php.net/manual/en/function.filesize.php
134
-	 * The result for filesize when called on a folder is required to be 0
135
-	 *
136
-	 * @param string $path
137
-	 * @return int
138
-	 */
139
-	public function filesize($path) {
140
-		$fullPath = $this->getFullPath($path);
141
-
142
-		/** @var CacheEntry $info */
143
-		$info = $this->getCache()->get($path);
144
-		if (isset($this->unencryptedSize[$fullPath])) {
145
-			$size = $this->unencryptedSize[$fullPath];
146
-			// update file cache
147
-			if ($info instanceof ICacheEntry) {
148
-				$info = $info->getData();
149
-				$info['encrypted'] = $info['encryptedVersion'];
150
-			} else {
151
-				if (!is_array($info)) {
152
-					$info = [];
153
-				}
154
-				$info['encrypted'] = true;
155
-			}
156
-
157
-			$info['size'] = $size;
158
-			$this->getCache()->put($path, $info);
159
-
160
-			return $size;
161
-		}
162
-
163
-		if (isset($info['fileid']) && $info['encrypted']) {
164
-			return $this->verifyUnencryptedSize($path, $info['size']);
165
-		}
166
-
167
-		return $this->storage->filesize($path);
168
-	}
169
-
170
-	/**
171
-	 * @param string $path
172
-	 * @return array
173
-	 */
174
-	public function getMetaData($path) {
175
-		$data = $this->storage->getMetaData($path);
176
-		if (is_null($data)) {
177
-			return null;
178
-		}
179
-		$fullPath = $this->getFullPath($path);
180
-		$info = $this->getCache()->get($path);
181
-
182
-		if (isset($this->unencryptedSize[$fullPath])) {
183
-			$data['encrypted'] = true;
184
-			$data['size'] = $this->unencryptedSize[$fullPath];
185
-		} else {
186
-			if (isset($info['fileid']) && $info['encrypted']) {
187
-				$data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
188
-				$data['encrypted'] = true;
189
-			}
190
-		}
191
-
192
-		if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
193
-			$data['encryptedVersion'] = $info['encryptedVersion'];
194
-		}
195
-
196
-		return $data;
197
-	}
198
-
199
-	/**
200
-	 * see http://php.net/manual/en/function.file_get_contents.php
201
-	 *
202
-	 * @param string $path
203
-	 * @return string
204
-	 */
205
-	public function file_get_contents($path) {
206
-
207
-		$encryptionModule = $this->getEncryptionModule($path);
208
-
209
-		if ($encryptionModule) {
210
-			$handle = $this->fopen($path, "r");
211
-			if (!$handle) {
212
-				return false;
213
-			}
214
-			$data = stream_get_contents($handle);
215
-			fclose($handle);
216
-			return $data;
217
-		}
218
-		return $this->storage->file_get_contents($path);
219
-	}
220
-
221
-	/**
222
-	 * see http://php.net/manual/en/function.file_put_contents.php
223
-	 *
224
-	 * @param string $path
225
-	 * @param string $data
226
-	 * @return bool
227
-	 */
228
-	public function file_put_contents($path, $data) {
229
-		// file put content will always be translated to a stream write
230
-		$handle = $this->fopen($path, 'w');
231
-		if (is_resource($handle)) {
232
-			$written = fwrite($handle, $data);
233
-			fclose($handle);
234
-			return $written;
235
-		}
236
-
237
-		return false;
238
-	}
239
-
240
-	/**
241
-	 * see http://php.net/manual/en/function.unlink.php
242
-	 *
243
-	 * @param string $path
244
-	 * @return bool
245
-	 */
246
-	public function unlink($path) {
247
-		$fullPath = $this->getFullPath($path);
248
-		if ($this->util->isExcluded($fullPath)) {
249
-			return $this->storage->unlink($path);
250
-		}
251
-
252
-		$encryptionModule = $this->getEncryptionModule($path);
253
-		if ($encryptionModule) {
254
-			$this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
255
-		}
256
-
257
-		return $this->storage->unlink($path);
258
-	}
259
-
260
-	/**
261
-	 * see http://php.net/manual/en/function.rename.php
262
-	 *
263
-	 * @param string $path1
264
-	 * @param string $path2
265
-	 * @return bool
266
-	 */
267
-	public function rename($path1, $path2) {
268
-
269
-		$result = $this->storage->rename($path1, $path2);
270
-
271
-		if ($result &&
272
-			// versions always use the keys from the original file, so we can skip
273
-			// this step for versions
274
-			$this->isVersion($path2) === false &&
275
-			$this->encryptionManager->isEnabled()) {
276
-			$source = $this->getFullPath($path1);
277
-			if (!$this->util->isExcluded($source)) {
278
-				$target = $this->getFullPath($path2);
279
-				if (isset($this->unencryptedSize[$source])) {
280
-					$this->unencryptedSize[$target] = $this->unencryptedSize[$source];
281
-				}
282
-				$this->keyStorage->renameKeys($source, $target);
283
-				$module = $this->getEncryptionModule($path2);
284
-				if ($module) {
285
-					$module->update($target, $this->uid, []);
286
-				}
287
-			}
288
-		}
289
-
290
-		return $result;
291
-	}
292
-
293
-	/**
294
-	 * see http://php.net/manual/en/function.rmdir.php
295
-	 *
296
-	 * @param string $path
297
-	 * @return bool
298
-	 */
299
-	public function rmdir($path) {
300
-		$result = $this->storage->rmdir($path);
301
-		$fullPath = $this->getFullPath($path);
302
-		if ($result &&
303
-			$this->util->isExcluded($fullPath) === false &&
304
-			$this->encryptionManager->isEnabled()
305
-		) {
306
-			$this->keyStorage->deleteAllFileKeys($fullPath);
307
-		}
308
-
309
-		return $result;
310
-	}
311
-
312
-	/**
313
-	 * check if a file can be read
314
-	 *
315
-	 * @param string $path
316
-	 * @return bool
317
-	 */
318
-	public function isReadable($path) {
319
-
320
-		$isReadable = true;
321
-
322
-		$metaData = $this->getMetaData($path);
323
-		if (
324
-			!$this->is_dir($path) &&
325
-			isset($metaData['encrypted']) &&
326
-			$metaData['encrypted'] === true
327
-		) {
328
-			$fullPath = $this->getFullPath($path);
329
-			$module = $this->getEncryptionModule($path);
330
-			$isReadable = $module->isReadable($fullPath, $this->uid);
331
-		}
332
-
333
-		return $this->storage->isReadable($path) && $isReadable;
334
-	}
335
-
336
-	/**
337
-	 * see http://php.net/manual/en/function.copy.php
338
-	 *
339
-	 * @param string $path1
340
-	 * @param string $path2
341
-	 * @return bool
342
-	 */
343
-	public function copy($path1, $path2) {
344
-
345
-		$source = $this->getFullPath($path1);
346
-
347
-		if ($this->util->isExcluded($source)) {
348
-			return $this->storage->copy($path1, $path2);
349
-		}
350
-
351
-		// need to stream copy file by file in case we copy between a encrypted
352
-		// and a unencrypted storage
353
-		$this->unlink($path2);
354
-		return $this->copyFromStorage($this, $path1, $path2);
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';
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->logException($e, [
443
-					'message' => 'Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted',
444
-					'level' => \OCP\Util::WARN,
445
-					'app' => 'core',
446
-				]);
447
-			}
448
-
449
-			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
450
-			if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
451
-				if (!$targetExists || !$targetIsEncrypted) {
452
-					$shouldEncrypt = false;
453
-				}
454
-			}
455
-
456
-			if ($shouldEncrypt === true && $encryptionModule !== null) {
457
-				$headerSize = $this->getHeaderSize($path);
458
-				$source = $this->storage->fopen($path, $mode);
459
-				if (!is_resource($source)) {
460
-					return false;
461
-				}
462
-				$handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
463
-					$this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
464
-					$size, $unencryptedSize, $headerSize, $signed);
465
-				return $handle;
466
-			}
467
-
468
-		}
469
-
470
-		return $this->storage->fopen($path, $mode);
471
-	}
472
-
473
-
474
-	/**
475
-	 * perform some plausibility checks if the the unencrypted size is correct.
476
-	 * If not, we calculate the correct unencrypted size and return it
477
-	 *
478
-	 * @param string $path internal path relative to the storage root
479
-	 * @param int $unencryptedSize size of the unencrypted file
480
-	 *
481
-	 * @return int unencrypted size
482
-	 */
483
-	protected function verifyUnencryptedSize($path, $unencryptedSize) {
484
-
485
-		$size = $this->storage->filesize($path);
486
-		$result = $unencryptedSize;
487
-
488
-		if ($unencryptedSize < 0 ||
489
-			($size > 0 && $unencryptedSize === $size)
490
-		) {
491
-			// check if we already calculate the unencrypted size for the
492
-			// given path to avoid recursions
493
-			if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
494
-				$this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
495
-				try {
496
-					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
497
-				} catch (\Exception $e) {
498
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
499
-					$this->logger->logException($e);
500
-				}
501
-				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
502
-			}
503
-		}
504
-
505
-		return $result;
506
-	}
507
-
508
-	/**
509
-	 * calculate the unencrypted size
510
-	 *
511
-	 * @param string $path internal path relative to the storage root
512
-	 * @param int $size size of the physical file
513
-	 * @param int $unencryptedSize size of the unencrypted file
514
-	 *
515
-	 * @return int calculated unencrypted size
516
-	 */
517
-	protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
518
-
519
-		$headerSize = $this->getHeaderSize($path);
520
-		$header = $this->getHeader($path);
521
-		$encryptionModule = $this->getEncryptionModule($path);
522
-
523
-		$stream = $this->storage->fopen($path, 'r');
524
-
525
-		// if we couldn't open the file we return the old unencrypted size
526
-		if (!is_resource($stream)) {
527
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
528
-			return $unencryptedSize;
529
-		}
530
-
531
-		$newUnencryptedSize = 0;
532
-		$size -= $headerSize;
533
-		$blockSize = $this->util->getBlockSize();
534
-
535
-		// if a header exists we skip it
536
-		if ($headerSize > 0) {
537
-			fread($stream, $headerSize);
538
-		}
539
-
540
-		// fast path, else the calculation for $lastChunkNr is bogus
541
-		if ($size === 0) {
542
-			return 0;
543
-		}
544
-
545
-		$signed = isset($header['signed']) && $header['signed'] === 'true';
546
-		$unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
547
-
548
-		// calculate last chunk nr
549
-		// next highest is end of chunks, one subtracted is last one
550
-		// we have to read the last chunk, we can't just calculate it (because of padding etc)
551
-
552
-		$lastChunkNr = ceil($size/ $blockSize)-1;
553
-		// calculate last chunk position
554
-		$lastChunkPos = ($lastChunkNr * $blockSize);
555
-		// try to fseek to the last chunk, if it fails we have to read the whole file
556
-		if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
557
-			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
558
-		}
559
-
560
-		$lastChunkContentEncrypted='';
561
-		$count = $blockSize;
562
-
563
-		while ($count > 0) {
564
-			$data=fread($stream, $blockSize);
565
-			$count=strlen($data);
566
-			$lastChunkContentEncrypted .= $data;
567
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
568
-				$newUnencryptedSize += $unencryptedBlockSize;
569
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
570
-			}
571
-		}
572
-
573
-		fclose($stream);
574
-
575
-		// we have to decrypt the last chunk to get it actual size
576
-		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
577
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
578
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
579
-
580
-		// calc the real file size with the size of the last chunk
581
-		$newUnencryptedSize += strlen($decryptedLastChunk);
582
-
583
-		$this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
584
-
585
-		// write to cache if applicable
586
-		$cache = $this->storage->getCache();
587
-		if ($cache) {
588
-			$entry = $cache->get($path);
589
-			$cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
590
-		}
591
-
592
-		return $newUnencryptedSize;
593
-	}
594
-
595
-	/**
596
-	 * @param Storage\IStorage $sourceStorage
597
-	 * @param string $sourceInternalPath
598
-	 * @param string $targetInternalPath
599
-	 * @param bool $preserveMtime
600
-	 * @return bool
601
-	 */
602
-	public function moveFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
603
-		if ($sourceStorage === $this) {
604
-			return $this->rename($sourceInternalPath, $targetInternalPath);
605
-		}
606
-
607
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
608
-		// - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
609
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
610
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
611
-		// - remove $this->copyBetweenStorage
612
-
613
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
614
-			return false;
615
-		}
616
-
617
-		$result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
618
-		if ($result) {
619
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
620
-				$result &= $sourceStorage->rmdir($sourceInternalPath);
621
-			} else {
622
-				$result &= $sourceStorage->unlink($sourceInternalPath);
623
-			}
624
-		}
625
-		return $result;
626
-	}
627
-
628
-
629
-	/**
630
-	 * @param Storage\IStorage $sourceStorage
631
-	 * @param string $sourceInternalPath
632
-	 * @param string $targetInternalPath
633
-	 * @param bool $preserveMtime
634
-	 * @param bool $isRename
635
-	 * @return bool
636
-	 */
637
-	public function copyFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
638
-
639
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
640
-		// - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
641
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
642
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
643
-		// - remove $this->copyBetweenStorage
644
-
645
-		return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
646
-	}
647
-
648
-	/**
649
-	 * Update the encrypted cache version in the database
650
-	 *
651
-	 * @param Storage\IStorage $sourceStorage
652
-	 * @param string $sourceInternalPath
653
-	 * @param string $targetInternalPath
654
-	 * @param bool $isRename
655
-	 * @param bool $keepEncryptionVersion
656
-	 */
657
-	private function updateEncryptedVersion(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, $keepEncryptionVersion) {
658
-		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
659
-		$cacheInformation = [
660
-			'encrypted' => $isEncrypted,
661
-		];
662
-		if($isEncrypted) {
663
-			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
664
-
665
-			// In case of a move operation from an unencrypted to an encrypted
666
-			// storage the old encrypted version would stay with "0" while the
667
-			// correct value would be "1". Thus we manually set the value to "1"
668
-			// for those cases.
669
-			// See also https://github.com/owncloud/core/issues/23078
670
-			if($encryptedVersion === 0 || !$keepEncryptionVersion) {
671
-				$encryptedVersion = 1;
672
-			}
673
-
674
-			$cacheInformation['encryptedVersion'] = $encryptedVersion;
675
-		}
676
-
677
-		// in case of a rename we need to manipulate the source cache because
678
-		// this information will be kept for the new target
679
-		if ($isRename) {
680
-			$sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
681
-		} else {
682
-			$this->getCache()->put($targetInternalPath, $cacheInformation);
683
-		}
684
-	}
685
-
686
-	/**
687
-	 * copy file between two storages
688
-	 *
689
-	 * @param Storage\IStorage $sourceStorage
690
-	 * @param string $sourceInternalPath
691
-	 * @param string $targetInternalPath
692
-	 * @param bool $preserveMtime
693
-	 * @param bool $isRename
694
-	 * @return bool
695
-	 * @throws \Exception
696
-	 */
697
-	private function copyBetweenStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
698
-
699
-		// for versions we have nothing to do, because versions should always use the
700
-		// key from the original file. Just create a 1:1 copy and done
701
-		if ($this->isVersion($targetInternalPath) ||
702
-			$this->isVersion($sourceInternalPath)) {
703
-			// remember that we try to create a version so that we can detect it during
704
-			// fopen($sourceInternalPath) and by-pass the encryption in order to
705
-			// create a 1:1 copy of the file
706
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
707
-			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
708
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
709
-			if ($result) {
710
-				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
711
-				// make sure that we update the unencrypted size for the version
712
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
713
-					$this->updateUnencryptedSize(
714
-						$this->getFullPath($targetInternalPath),
715
-						$info['size']
716
-					);
717
-				}
718
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
719
-			}
720
-			return $result;
721
-		}
722
-
723
-		// first copy the keys that we reuse the existing file key on the target location
724
-		// and don't create a new one which would break versions for example.
725
-		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
726
-		if (count($mount) === 1) {
727
-			$mountPoint = $mount[0]->getMountPoint();
728
-			$source = $mountPoint . '/' . $sourceInternalPath;
729
-			$target = $this->getFullPath($targetInternalPath);
730
-			$this->copyKeys($source, $target);
731
-		} else {
732
-			$this->logger->error('Could not find mount point, can\'t keep encryption keys');
733
-		}
734
-
735
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
736
-			$dh = $sourceStorage->opendir($sourceInternalPath);
737
-			$result = $this->mkdir($targetInternalPath);
738
-			if (is_resource($dh)) {
739
-				while ($result and ($file = readdir($dh)) !== false) {
740
-					if (!Filesystem::isIgnoredDir($file)) {
741
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
742
-					}
743
-				}
744
-			}
745
-		} else {
746
-			try {
747
-				$source = $sourceStorage->fopen($sourceInternalPath, 'r');
748
-				$target = $this->fopen($targetInternalPath, 'w');
749
-				list(, $result) = \OC_Helper::streamCopy($source, $target);
750
-				fclose($source);
751
-				fclose($target);
752
-			} catch (\Exception $e) {
753
-				fclose($source);
754
-				fclose($target);
755
-				throw $e;
756
-			}
757
-			if($result) {
758
-				if ($preserveMtime) {
759
-					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
760
-				}
761
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
762
-			} else {
763
-				// delete partially written target file
764
-				$this->unlink($targetInternalPath);
765
-				// delete cache entry that was created by fopen
766
-				$this->getCache()->remove($targetInternalPath);
767
-			}
768
-		}
769
-		return (bool)$result;
770
-
771
-	}
772
-
773
-	/**
774
-	 * get the path to a local version of the file.
775
-	 * The local version of the file can be temporary and doesn't have to be persistent across requests
776
-	 *
777
-	 * @param string $path
778
-	 * @return string
779
-	 */
780
-	public function getLocalFile($path) {
781
-		if ($this->encryptionManager->isEnabled()) {
782
-			$cachedFile = $this->getCachedFile($path);
783
-			if (is_string($cachedFile)) {
784
-				return $cachedFile;
785
-			}
786
-		}
787
-		return $this->storage->getLocalFile($path);
788
-	}
789
-
790
-	/**
791
-	 * Returns the wrapped storage's value for isLocal()
792
-	 *
793
-	 * @return bool wrapped storage's isLocal() value
794
-	 */
795
-	public function isLocal() {
796
-		if ($this->encryptionManager->isEnabled()) {
797
-			return false;
798
-		}
799
-		return $this->storage->isLocal();
800
-	}
801
-
802
-	/**
803
-	 * see http://php.net/manual/en/function.stat.php
804
-	 * only the following keys are required in the result: size and mtime
805
-	 *
806
-	 * @param string $path
807
-	 * @return array
808
-	 */
809
-	public function stat($path) {
810
-		$stat = $this->storage->stat($path);
811
-		$fileSize = $this->filesize($path);
812
-		$stat['size'] = $fileSize;
813
-		$stat[7] = $fileSize;
814
-		return $stat;
815
-	}
816
-
817
-	/**
818
-	 * see http://php.net/manual/en/function.hash.php
819
-	 *
820
-	 * @param string $type
821
-	 * @param string $path
822
-	 * @param bool $raw
823
-	 * @return string
824
-	 */
825
-	public function hash($type, $path, $raw = false) {
826
-		$fh = $this->fopen($path, 'rb');
827
-		$ctx = hash_init($type);
828
-		hash_update_stream($ctx, $fh);
829
-		fclose($fh);
830
-		return hash_final($ctx, $raw);
831
-	}
832
-
833
-	/**
834
-	 * return full path, including mount point
835
-	 *
836
-	 * @param string $path relative to mount point
837
-	 * @return string full path including mount point
838
-	 */
839
-	protected function getFullPath($path) {
840
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
841
-	}
842
-
843
-	/**
844
-	 * read first block of encrypted file, typically this will contain the
845
-	 * encryption header
846
-	 *
847
-	 * @param string $path
848
-	 * @return string
849
-	 */
850
-	protected function readFirstBlock($path) {
851
-		$firstBlock = '';
852
-		if ($this->storage->file_exists($path)) {
853
-			$handle = $this->storage->fopen($path, 'r');
854
-			$firstBlock = fread($handle, $this->util->getHeaderSize());
855
-			fclose($handle);
856
-		}
857
-		return $firstBlock;
858
-	}
859
-
860
-	/**
861
-	 * return header size of given file
862
-	 *
863
-	 * @param string $path
864
-	 * @return int
865
-	 */
866
-	protected function getHeaderSize($path) {
867
-		$headerSize = 0;
868
-		$realFile = $this->util->stripPartialFileExtension($path);
869
-		if ($this->storage->file_exists($realFile)) {
870
-			$path = $realFile;
871
-		}
872
-		$firstBlock = $this->readFirstBlock($path);
873
-
874
-		if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
875
-			$headerSize = $this->util->getHeaderSize();
876
-		}
877
-
878
-		return $headerSize;
879
-	}
880
-
881
-	/**
882
-	 * parse raw header to array
883
-	 *
884
-	 * @param string $rawHeader
885
-	 * @return array
886
-	 */
887
-	protected function parseRawHeader($rawHeader) {
888
-		$result = array();
889
-		if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
890
-			$header = $rawHeader;
891
-			$endAt = strpos($header, Util::HEADER_END);
892
-			if ($endAt !== false) {
893
-				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
894
-
895
-				// +1 to not start with an ':' which would result in empty element at the beginning
896
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
897
-
898
-				$element = array_shift($exploded);
899
-				while ($element !== Util::HEADER_END) {
900
-					$result[$element] = array_shift($exploded);
901
-					$element = array_shift($exploded);
902
-				}
903
-			}
904
-		}
905
-
906
-		return $result;
907
-	}
908
-
909
-	/**
910
-	 * read header from file
911
-	 *
912
-	 * @param string $path
913
-	 * @return array
914
-	 */
915
-	protected function getHeader($path) {
916
-		$realFile = $this->util->stripPartialFileExtension($path);
917
-		$exists = $this->storage->file_exists($realFile);
918
-		if ($exists) {
919
-			$path = $realFile;
920
-		}
921
-
922
-		$firstBlock = $this->readFirstBlock($path);
923
-		$result = $this->parseRawHeader($firstBlock);
924
-
925
-		// if the header doesn't contain a encryption module we check if it is a
926
-		// legacy file. If true, we add the default encryption module
927
-		if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
928
-			if (!empty($result)) {
929
-				$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
930
-			} else if ($exists) {
931
-				// if the header was empty we have to check first if it is a encrypted file at all
932
-				// We would do query to filecache only if we know that entry in filecache exists
933
-				$info = $this->getCache()->get($path);
934
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
935
-					$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
936
-				}
937
-			}
938
-		}
939
-
940
-		return $result;
941
-	}
942
-
943
-	/**
944
-	 * read encryption module needed to read/write the file located at $path
945
-	 *
946
-	 * @param string $path
947
-	 * @return null|\OCP\Encryption\IEncryptionModule
948
-	 * @throws ModuleDoesNotExistsException
949
-	 * @throws \Exception
950
-	 */
951
-	protected function getEncryptionModule($path) {
952
-		$encryptionModule = null;
953
-		$header = $this->getHeader($path);
954
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
955
-		if (!empty($encryptionModuleId)) {
956
-			try {
957
-				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
958
-			} catch (ModuleDoesNotExistsException $e) {
959
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
960
-				throw $e;
961
-			}
962
-		}
963
-
964
-		return $encryptionModule;
965
-	}
966
-
967
-	/**
968
-	 * @param string $path
969
-	 * @param int $unencryptedSize
970
-	 */
971
-	public function updateUnencryptedSize($path, $unencryptedSize) {
972
-		$this->unencryptedSize[$path] = $unencryptedSize;
973
-	}
974
-
975
-	/**
976
-	 * copy keys to new location
977
-	 *
978
-	 * @param string $source path relative to data/
979
-	 * @param string $target path relative to data/
980
-	 * @return bool
981
-	 */
982
-	protected function copyKeys($source, $target) {
983
-		if (!$this->util->isExcluded($source)) {
984
-			return $this->keyStorage->copyKeys($source, $target);
985
-		}
986
-
987
-		return false;
988
-	}
989
-
990
-	/**
991
-	 * check if path points to a files version
992
-	 *
993
-	 * @param $path
994
-	 * @return bool
995
-	 */
996
-	protected function isVersion($path) {
997
-		$normalized = Filesystem::normalizePath($path);
998
-		return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
999
-	}
1000
-
1001
-	/**
1002
-	 * check if the given storage should be encrypted or not
1003
-	 *
1004
-	 * @param $path
1005
-	 * @return bool
1006
-	 */
1007
-	protected function shouldEncrypt($path) {
1008
-		$fullPath = $this->getFullPath($path);
1009
-		$mountPointConfig = $this->mount->getOption('encrypt', true);
1010
-		if ($mountPointConfig === false) {
1011
-			return false;
1012
-		}
1013
-
1014
-		try {
1015
-			$encryptionModule = $this->getEncryptionModule($fullPath);
1016
-		} catch (ModuleDoesNotExistsException $e) {
1017
-			return false;
1018
-		}
1019
-
1020
-		if ($encryptionModule === null) {
1021
-			$encryptionModule = $this->encryptionManager->getEncryptionModule();
1022
-		}
1023
-
1024
-		return $encryptionModule->shouldEncrypt($fullPath);
1025
-
1026
-	}
51
+    use LocalTempFileTrait;
52
+
53
+    /** @var string */
54
+    private $mountPoint;
55
+
56
+    /** @var \OC\Encryption\Util */
57
+    private $util;
58
+
59
+    /** @var \OCP\Encryption\IManager */
60
+    private $encryptionManager;
61
+
62
+    /** @var \OCP\ILogger */
63
+    private $logger;
64
+
65
+    /** @var string */
66
+    private $uid;
67
+
68
+    /** @var array */
69
+    protected $unencryptedSize;
70
+
71
+    /** @var \OCP\Encryption\IFile */
72
+    private $fileHelper;
73
+
74
+    /** @var IMountPoint */
75
+    private $mount;
76
+
77
+    /** @var IStorage */
78
+    private $keyStorage;
79
+
80
+    /** @var Update */
81
+    private $update;
82
+
83
+    /** @var Manager */
84
+    private $mountManager;
85
+
86
+    /** @var array remember for which path we execute the repair step to avoid recursions */
87
+    private $fixUnencryptedSizeOf = array();
88
+
89
+    /** @var  ArrayCache */
90
+    private $arrayCache;
91
+
92
+    /**
93
+     * @param array $parameters
94
+     * @param IManager $encryptionManager
95
+     * @param Util $util
96
+     * @param ILogger $logger
97
+     * @param IFile $fileHelper
98
+     * @param string $uid
99
+     * @param IStorage $keyStorage
100
+     * @param Update $update
101
+     * @param Manager $mountManager
102
+     * @param ArrayCache $arrayCache
103
+     */
104
+    public function __construct(
105
+            $parameters,
106
+            IManager $encryptionManager = null,
107
+            Util $util = null,
108
+            ILogger $logger = null,
109
+            IFile $fileHelper = null,
110
+            $uid = null,
111
+            IStorage $keyStorage = null,
112
+            Update $update = null,
113
+            Manager $mountManager = null,
114
+            ArrayCache $arrayCache = null
115
+        ) {
116
+
117
+        $this->mountPoint = $parameters['mountPoint'];
118
+        $this->mount = $parameters['mount'];
119
+        $this->encryptionManager = $encryptionManager;
120
+        $this->util = $util;
121
+        $this->logger = $logger;
122
+        $this->uid = $uid;
123
+        $this->fileHelper = $fileHelper;
124
+        $this->keyStorage = $keyStorage;
125
+        $this->unencryptedSize = array();
126
+        $this->update = $update;
127
+        $this->mountManager = $mountManager;
128
+        $this->arrayCache = $arrayCache;
129
+        parent::__construct($parameters);
130
+    }
131
+
132
+    /**
133
+     * see http://php.net/manual/en/function.filesize.php
134
+     * The result for filesize when called on a folder is required to be 0
135
+     *
136
+     * @param string $path
137
+     * @return int
138
+     */
139
+    public function filesize($path) {
140
+        $fullPath = $this->getFullPath($path);
141
+
142
+        /** @var CacheEntry $info */
143
+        $info = $this->getCache()->get($path);
144
+        if (isset($this->unencryptedSize[$fullPath])) {
145
+            $size = $this->unencryptedSize[$fullPath];
146
+            // update file cache
147
+            if ($info instanceof ICacheEntry) {
148
+                $info = $info->getData();
149
+                $info['encrypted'] = $info['encryptedVersion'];
150
+            } else {
151
+                if (!is_array($info)) {
152
+                    $info = [];
153
+                }
154
+                $info['encrypted'] = true;
155
+            }
156
+
157
+            $info['size'] = $size;
158
+            $this->getCache()->put($path, $info);
159
+
160
+            return $size;
161
+        }
162
+
163
+        if (isset($info['fileid']) && $info['encrypted']) {
164
+            return $this->verifyUnencryptedSize($path, $info['size']);
165
+        }
166
+
167
+        return $this->storage->filesize($path);
168
+    }
169
+
170
+    /**
171
+     * @param string $path
172
+     * @return array
173
+     */
174
+    public function getMetaData($path) {
175
+        $data = $this->storage->getMetaData($path);
176
+        if (is_null($data)) {
177
+            return null;
178
+        }
179
+        $fullPath = $this->getFullPath($path);
180
+        $info = $this->getCache()->get($path);
181
+
182
+        if (isset($this->unencryptedSize[$fullPath])) {
183
+            $data['encrypted'] = true;
184
+            $data['size'] = $this->unencryptedSize[$fullPath];
185
+        } else {
186
+            if (isset($info['fileid']) && $info['encrypted']) {
187
+                $data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
188
+                $data['encrypted'] = true;
189
+            }
190
+        }
191
+
192
+        if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
193
+            $data['encryptedVersion'] = $info['encryptedVersion'];
194
+        }
195
+
196
+        return $data;
197
+    }
198
+
199
+    /**
200
+     * see http://php.net/manual/en/function.file_get_contents.php
201
+     *
202
+     * @param string $path
203
+     * @return string
204
+     */
205
+    public function file_get_contents($path) {
206
+
207
+        $encryptionModule = $this->getEncryptionModule($path);
208
+
209
+        if ($encryptionModule) {
210
+            $handle = $this->fopen($path, "r");
211
+            if (!$handle) {
212
+                return false;
213
+            }
214
+            $data = stream_get_contents($handle);
215
+            fclose($handle);
216
+            return $data;
217
+        }
218
+        return $this->storage->file_get_contents($path);
219
+    }
220
+
221
+    /**
222
+     * see http://php.net/manual/en/function.file_put_contents.php
223
+     *
224
+     * @param string $path
225
+     * @param string $data
226
+     * @return bool
227
+     */
228
+    public function file_put_contents($path, $data) {
229
+        // file put content will always be translated to a stream write
230
+        $handle = $this->fopen($path, 'w');
231
+        if (is_resource($handle)) {
232
+            $written = fwrite($handle, $data);
233
+            fclose($handle);
234
+            return $written;
235
+        }
236
+
237
+        return false;
238
+    }
239
+
240
+    /**
241
+     * see http://php.net/manual/en/function.unlink.php
242
+     *
243
+     * @param string $path
244
+     * @return bool
245
+     */
246
+    public function unlink($path) {
247
+        $fullPath = $this->getFullPath($path);
248
+        if ($this->util->isExcluded($fullPath)) {
249
+            return $this->storage->unlink($path);
250
+        }
251
+
252
+        $encryptionModule = $this->getEncryptionModule($path);
253
+        if ($encryptionModule) {
254
+            $this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
255
+        }
256
+
257
+        return $this->storage->unlink($path);
258
+    }
259
+
260
+    /**
261
+     * see http://php.net/manual/en/function.rename.php
262
+     *
263
+     * @param string $path1
264
+     * @param string $path2
265
+     * @return bool
266
+     */
267
+    public function rename($path1, $path2) {
268
+
269
+        $result = $this->storage->rename($path1, $path2);
270
+
271
+        if ($result &&
272
+            // versions always use the keys from the original file, so we can skip
273
+            // this step for versions
274
+            $this->isVersion($path2) === false &&
275
+            $this->encryptionManager->isEnabled()) {
276
+            $source = $this->getFullPath($path1);
277
+            if (!$this->util->isExcluded($source)) {
278
+                $target = $this->getFullPath($path2);
279
+                if (isset($this->unencryptedSize[$source])) {
280
+                    $this->unencryptedSize[$target] = $this->unencryptedSize[$source];
281
+                }
282
+                $this->keyStorage->renameKeys($source, $target);
283
+                $module = $this->getEncryptionModule($path2);
284
+                if ($module) {
285
+                    $module->update($target, $this->uid, []);
286
+                }
287
+            }
288
+        }
289
+
290
+        return $result;
291
+    }
292
+
293
+    /**
294
+     * see http://php.net/manual/en/function.rmdir.php
295
+     *
296
+     * @param string $path
297
+     * @return bool
298
+     */
299
+    public function rmdir($path) {
300
+        $result = $this->storage->rmdir($path);
301
+        $fullPath = $this->getFullPath($path);
302
+        if ($result &&
303
+            $this->util->isExcluded($fullPath) === false &&
304
+            $this->encryptionManager->isEnabled()
305
+        ) {
306
+            $this->keyStorage->deleteAllFileKeys($fullPath);
307
+        }
308
+
309
+        return $result;
310
+    }
311
+
312
+    /**
313
+     * check if a file can be read
314
+     *
315
+     * @param string $path
316
+     * @return bool
317
+     */
318
+    public function isReadable($path) {
319
+
320
+        $isReadable = true;
321
+
322
+        $metaData = $this->getMetaData($path);
323
+        if (
324
+            !$this->is_dir($path) &&
325
+            isset($metaData['encrypted']) &&
326
+            $metaData['encrypted'] === true
327
+        ) {
328
+            $fullPath = $this->getFullPath($path);
329
+            $module = $this->getEncryptionModule($path);
330
+            $isReadable = $module->isReadable($fullPath, $this->uid);
331
+        }
332
+
333
+        return $this->storage->isReadable($path) && $isReadable;
334
+    }
335
+
336
+    /**
337
+     * see http://php.net/manual/en/function.copy.php
338
+     *
339
+     * @param string $path1
340
+     * @param string $path2
341
+     * @return bool
342
+     */
343
+    public function copy($path1, $path2) {
344
+
345
+        $source = $this->getFullPath($path1);
346
+
347
+        if ($this->util->isExcluded($source)) {
348
+            return $this->storage->copy($path1, $path2);
349
+        }
350
+
351
+        // need to stream copy file by file in case we copy between a encrypted
352
+        // and a unencrypted storage
353
+        $this->unlink($path2);
354
+        return $this->copyFromStorage($this, $path1, $path2);
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';
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->logException($e, [
443
+                    'message' => 'Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted',
444
+                    'level' => \OCP\Util::WARN,
445
+                    'app' => 'core',
446
+                ]);
447
+            }
448
+
449
+            // encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
450
+            if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
451
+                if (!$targetExists || !$targetIsEncrypted) {
452
+                    $shouldEncrypt = false;
453
+                }
454
+            }
455
+
456
+            if ($shouldEncrypt === true && $encryptionModule !== null) {
457
+                $headerSize = $this->getHeaderSize($path);
458
+                $source = $this->storage->fopen($path, $mode);
459
+                if (!is_resource($source)) {
460
+                    return false;
461
+                }
462
+                $handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
463
+                    $this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
464
+                    $size, $unencryptedSize, $headerSize, $signed);
465
+                return $handle;
466
+            }
467
+
468
+        }
469
+
470
+        return $this->storage->fopen($path, $mode);
471
+    }
472
+
473
+
474
+    /**
475
+     * perform some plausibility checks if the the unencrypted size is correct.
476
+     * If not, we calculate the correct unencrypted size and return it
477
+     *
478
+     * @param string $path internal path relative to the storage root
479
+     * @param int $unencryptedSize size of the unencrypted file
480
+     *
481
+     * @return int unencrypted size
482
+     */
483
+    protected function verifyUnencryptedSize($path, $unencryptedSize) {
484
+
485
+        $size = $this->storage->filesize($path);
486
+        $result = $unencryptedSize;
487
+
488
+        if ($unencryptedSize < 0 ||
489
+            ($size > 0 && $unencryptedSize === $size)
490
+        ) {
491
+            // check if we already calculate the unencrypted size for the
492
+            // given path to avoid recursions
493
+            if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
494
+                $this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
495
+                try {
496
+                    $result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
497
+                } catch (\Exception $e) {
498
+                    $this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
499
+                    $this->logger->logException($e);
500
+                }
501
+                unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
502
+            }
503
+        }
504
+
505
+        return $result;
506
+    }
507
+
508
+    /**
509
+     * calculate the unencrypted size
510
+     *
511
+     * @param string $path internal path relative to the storage root
512
+     * @param int $size size of the physical file
513
+     * @param int $unencryptedSize size of the unencrypted file
514
+     *
515
+     * @return int calculated unencrypted size
516
+     */
517
+    protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
518
+
519
+        $headerSize = $this->getHeaderSize($path);
520
+        $header = $this->getHeader($path);
521
+        $encryptionModule = $this->getEncryptionModule($path);
522
+
523
+        $stream = $this->storage->fopen($path, 'r');
524
+
525
+        // if we couldn't open the file we return the old unencrypted size
526
+        if (!is_resource($stream)) {
527
+            $this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
528
+            return $unencryptedSize;
529
+        }
530
+
531
+        $newUnencryptedSize = 0;
532
+        $size -= $headerSize;
533
+        $blockSize = $this->util->getBlockSize();
534
+
535
+        // if a header exists we skip it
536
+        if ($headerSize > 0) {
537
+            fread($stream, $headerSize);
538
+        }
539
+
540
+        // fast path, else the calculation for $lastChunkNr is bogus
541
+        if ($size === 0) {
542
+            return 0;
543
+        }
544
+
545
+        $signed = isset($header['signed']) && $header['signed'] === 'true';
546
+        $unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
547
+
548
+        // calculate last chunk nr
549
+        // next highest is end of chunks, one subtracted is last one
550
+        // we have to read the last chunk, we can't just calculate it (because of padding etc)
551
+
552
+        $lastChunkNr = ceil($size/ $blockSize)-1;
553
+        // calculate last chunk position
554
+        $lastChunkPos = ($lastChunkNr * $blockSize);
555
+        // try to fseek to the last chunk, if it fails we have to read the whole file
556
+        if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
557
+            $newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
558
+        }
559
+
560
+        $lastChunkContentEncrypted='';
561
+        $count = $blockSize;
562
+
563
+        while ($count > 0) {
564
+            $data=fread($stream, $blockSize);
565
+            $count=strlen($data);
566
+            $lastChunkContentEncrypted .= $data;
567
+            if(strlen($lastChunkContentEncrypted) > $blockSize) {
568
+                $newUnencryptedSize += $unencryptedBlockSize;
569
+                $lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
570
+            }
571
+        }
572
+
573
+        fclose($stream);
574
+
575
+        // we have to decrypt the last chunk to get it actual size
576
+        $encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
577
+        $decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
578
+        $decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
579
+
580
+        // calc the real file size with the size of the last chunk
581
+        $newUnencryptedSize += strlen($decryptedLastChunk);
582
+
583
+        $this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
584
+
585
+        // write to cache if applicable
586
+        $cache = $this->storage->getCache();
587
+        if ($cache) {
588
+            $entry = $cache->get($path);
589
+            $cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
590
+        }
591
+
592
+        return $newUnencryptedSize;
593
+    }
594
+
595
+    /**
596
+     * @param Storage\IStorage $sourceStorage
597
+     * @param string $sourceInternalPath
598
+     * @param string $targetInternalPath
599
+     * @param bool $preserveMtime
600
+     * @return bool
601
+     */
602
+    public function moveFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
603
+        if ($sourceStorage === $this) {
604
+            return $this->rename($sourceInternalPath, $targetInternalPath);
605
+        }
606
+
607
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
608
+        // - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
609
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
610
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
611
+        // - remove $this->copyBetweenStorage
612
+
613
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
614
+            return false;
615
+        }
616
+
617
+        $result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
618
+        if ($result) {
619
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
620
+                $result &= $sourceStorage->rmdir($sourceInternalPath);
621
+            } else {
622
+                $result &= $sourceStorage->unlink($sourceInternalPath);
623
+            }
624
+        }
625
+        return $result;
626
+    }
627
+
628
+
629
+    /**
630
+     * @param Storage\IStorage $sourceStorage
631
+     * @param string $sourceInternalPath
632
+     * @param string $targetInternalPath
633
+     * @param bool $preserveMtime
634
+     * @param bool $isRename
635
+     * @return bool
636
+     */
637
+    public function copyFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
638
+
639
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
640
+        // - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
641
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
642
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
643
+        // - remove $this->copyBetweenStorage
644
+
645
+        return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
646
+    }
647
+
648
+    /**
649
+     * Update the encrypted cache version in the database
650
+     *
651
+     * @param Storage\IStorage $sourceStorage
652
+     * @param string $sourceInternalPath
653
+     * @param string $targetInternalPath
654
+     * @param bool $isRename
655
+     * @param bool $keepEncryptionVersion
656
+     */
657
+    private function updateEncryptedVersion(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, $keepEncryptionVersion) {
658
+        $isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
659
+        $cacheInformation = [
660
+            'encrypted' => $isEncrypted,
661
+        ];
662
+        if($isEncrypted) {
663
+            $encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
664
+
665
+            // In case of a move operation from an unencrypted to an encrypted
666
+            // storage the old encrypted version would stay with "0" while the
667
+            // correct value would be "1". Thus we manually set the value to "1"
668
+            // for those cases.
669
+            // See also https://github.com/owncloud/core/issues/23078
670
+            if($encryptedVersion === 0 || !$keepEncryptionVersion) {
671
+                $encryptedVersion = 1;
672
+            }
673
+
674
+            $cacheInformation['encryptedVersion'] = $encryptedVersion;
675
+        }
676
+
677
+        // in case of a rename we need to manipulate the source cache because
678
+        // this information will be kept for the new target
679
+        if ($isRename) {
680
+            $sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
681
+        } else {
682
+            $this->getCache()->put($targetInternalPath, $cacheInformation);
683
+        }
684
+    }
685
+
686
+    /**
687
+     * copy file between two storages
688
+     *
689
+     * @param Storage\IStorage $sourceStorage
690
+     * @param string $sourceInternalPath
691
+     * @param string $targetInternalPath
692
+     * @param bool $preserveMtime
693
+     * @param bool $isRename
694
+     * @return bool
695
+     * @throws \Exception
696
+     */
697
+    private function copyBetweenStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
698
+
699
+        // for versions we have nothing to do, because versions should always use the
700
+        // key from the original file. Just create a 1:1 copy and done
701
+        if ($this->isVersion($targetInternalPath) ||
702
+            $this->isVersion($sourceInternalPath)) {
703
+            // remember that we try to create a version so that we can detect it during
704
+            // fopen($sourceInternalPath) and by-pass the encryption in order to
705
+            // create a 1:1 copy of the file
706
+            $this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
707
+            $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
708
+            $this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
709
+            if ($result) {
710
+                $info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
711
+                // make sure that we update the unencrypted size for the version
712
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
713
+                    $this->updateUnencryptedSize(
714
+                        $this->getFullPath($targetInternalPath),
715
+                        $info['size']
716
+                    );
717
+                }
718
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
719
+            }
720
+            return $result;
721
+        }
722
+
723
+        // first copy the keys that we reuse the existing file key on the target location
724
+        // and don't create a new one which would break versions for example.
725
+        $mount = $this->mountManager->findByStorageId($sourceStorage->getId());
726
+        if (count($mount) === 1) {
727
+            $mountPoint = $mount[0]->getMountPoint();
728
+            $source = $mountPoint . '/' . $sourceInternalPath;
729
+            $target = $this->getFullPath($targetInternalPath);
730
+            $this->copyKeys($source, $target);
731
+        } else {
732
+            $this->logger->error('Could not find mount point, can\'t keep encryption keys');
733
+        }
734
+
735
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
736
+            $dh = $sourceStorage->opendir($sourceInternalPath);
737
+            $result = $this->mkdir($targetInternalPath);
738
+            if (is_resource($dh)) {
739
+                while ($result and ($file = readdir($dh)) !== false) {
740
+                    if (!Filesystem::isIgnoredDir($file)) {
741
+                        $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
742
+                    }
743
+                }
744
+            }
745
+        } else {
746
+            try {
747
+                $source = $sourceStorage->fopen($sourceInternalPath, 'r');
748
+                $target = $this->fopen($targetInternalPath, 'w');
749
+                list(, $result) = \OC_Helper::streamCopy($source, $target);
750
+                fclose($source);
751
+                fclose($target);
752
+            } catch (\Exception $e) {
753
+                fclose($source);
754
+                fclose($target);
755
+                throw $e;
756
+            }
757
+            if($result) {
758
+                if ($preserveMtime) {
759
+                    $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
760
+                }
761
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
762
+            } else {
763
+                // delete partially written target file
764
+                $this->unlink($targetInternalPath);
765
+                // delete cache entry that was created by fopen
766
+                $this->getCache()->remove($targetInternalPath);
767
+            }
768
+        }
769
+        return (bool)$result;
770
+
771
+    }
772
+
773
+    /**
774
+     * get the path to a local version of the file.
775
+     * The local version of the file can be temporary and doesn't have to be persistent across requests
776
+     *
777
+     * @param string $path
778
+     * @return string
779
+     */
780
+    public function getLocalFile($path) {
781
+        if ($this->encryptionManager->isEnabled()) {
782
+            $cachedFile = $this->getCachedFile($path);
783
+            if (is_string($cachedFile)) {
784
+                return $cachedFile;
785
+            }
786
+        }
787
+        return $this->storage->getLocalFile($path);
788
+    }
789
+
790
+    /**
791
+     * Returns the wrapped storage's value for isLocal()
792
+     *
793
+     * @return bool wrapped storage's isLocal() value
794
+     */
795
+    public function isLocal() {
796
+        if ($this->encryptionManager->isEnabled()) {
797
+            return false;
798
+        }
799
+        return $this->storage->isLocal();
800
+    }
801
+
802
+    /**
803
+     * see http://php.net/manual/en/function.stat.php
804
+     * only the following keys are required in the result: size and mtime
805
+     *
806
+     * @param string $path
807
+     * @return array
808
+     */
809
+    public function stat($path) {
810
+        $stat = $this->storage->stat($path);
811
+        $fileSize = $this->filesize($path);
812
+        $stat['size'] = $fileSize;
813
+        $stat[7] = $fileSize;
814
+        return $stat;
815
+    }
816
+
817
+    /**
818
+     * see http://php.net/manual/en/function.hash.php
819
+     *
820
+     * @param string $type
821
+     * @param string $path
822
+     * @param bool $raw
823
+     * @return string
824
+     */
825
+    public function hash($type, $path, $raw = false) {
826
+        $fh = $this->fopen($path, 'rb');
827
+        $ctx = hash_init($type);
828
+        hash_update_stream($ctx, $fh);
829
+        fclose($fh);
830
+        return hash_final($ctx, $raw);
831
+    }
832
+
833
+    /**
834
+     * return full path, including mount point
835
+     *
836
+     * @param string $path relative to mount point
837
+     * @return string full path including mount point
838
+     */
839
+    protected function getFullPath($path) {
840
+        return Filesystem::normalizePath($this->mountPoint . '/' . $path);
841
+    }
842
+
843
+    /**
844
+     * read first block of encrypted file, typically this will contain the
845
+     * encryption header
846
+     *
847
+     * @param string $path
848
+     * @return string
849
+     */
850
+    protected function readFirstBlock($path) {
851
+        $firstBlock = '';
852
+        if ($this->storage->file_exists($path)) {
853
+            $handle = $this->storage->fopen($path, 'r');
854
+            $firstBlock = fread($handle, $this->util->getHeaderSize());
855
+            fclose($handle);
856
+        }
857
+        return $firstBlock;
858
+    }
859
+
860
+    /**
861
+     * return header size of given file
862
+     *
863
+     * @param string $path
864
+     * @return int
865
+     */
866
+    protected function getHeaderSize($path) {
867
+        $headerSize = 0;
868
+        $realFile = $this->util->stripPartialFileExtension($path);
869
+        if ($this->storage->file_exists($realFile)) {
870
+            $path = $realFile;
871
+        }
872
+        $firstBlock = $this->readFirstBlock($path);
873
+
874
+        if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
875
+            $headerSize = $this->util->getHeaderSize();
876
+        }
877
+
878
+        return $headerSize;
879
+    }
880
+
881
+    /**
882
+     * parse raw header to array
883
+     *
884
+     * @param string $rawHeader
885
+     * @return array
886
+     */
887
+    protected function parseRawHeader($rawHeader) {
888
+        $result = array();
889
+        if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
890
+            $header = $rawHeader;
891
+            $endAt = strpos($header, Util::HEADER_END);
892
+            if ($endAt !== false) {
893
+                $header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
894
+
895
+                // +1 to not start with an ':' which would result in empty element at the beginning
896
+                $exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
897
+
898
+                $element = array_shift($exploded);
899
+                while ($element !== Util::HEADER_END) {
900
+                    $result[$element] = array_shift($exploded);
901
+                    $element = array_shift($exploded);
902
+                }
903
+            }
904
+        }
905
+
906
+        return $result;
907
+    }
908
+
909
+    /**
910
+     * read header from file
911
+     *
912
+     * @param string $path
913
+     * @return array
914
+     */
915
+    protected function getHeader($path) {
916
+        $realFile = $this->util->stripPartialFileExtension($path);
917
+        $exists = $this->storage->file_exists($realFile);
918
+        if ($exists) {
919
+            $path = $realFile;
920
+        }
921
+
922
+        $firstBlock = $this->readFirstBlock($path);
923
+        $result = $this->parseRawHeader($firstBlock);
924
+
925
+        // if the header doesn't contain a encryption module we check if it is a
926
+        // legacy file. If true, we add the default encryption module
927
+        if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
928
+            if (!empty($result)) {
929
+                $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
930
+            } else if ($exists) {
931
+                // if the header was empty we have to check first if it is a encrypted file at all
932
+                // We would do query to filecache only if we know that entry in filecache exists
933
+                $info = $this->getCache()->get($path);
934
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
935
+                    $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
936
+                }
937
+            }
938
+        }
939
+
940
+        return $result;
941
+    }
942
+
943
+    /**
944
+     * read encryption module needed to read/write the file located at $path
945
+     *
946
+     * @param string $path
947
+     * @return null|\OCP\Encryption\IEncryptionModule
948
+     * @throws ModuleDoesNotExistsException
949
+     * @throws \Exception
950
+     */
951
+    protected function getEncryptionModule($path) {
952
+        $encryptionModule = null;
953
+        $header = $this->getHeader($path);
954
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
955
+        if (!empty($encryptionModuleId)) {
956
+            try {
957
+                $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
958
+            } catch (ModuleDoesNotExistsException $e) {
959
+                $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
960
+                throw $e;
961
+            }
962
+        }
963
+
964
+        return $encryptionModule;
965
+    }
966
+
967
+    /**
968
+     * @param string $path
969
+     * @param int $unencryptedSize
970
+     */
971
+    public function updateUnencryptedSize($path, $unencryptedSize) {
972
+        $this->unencryptedSize[$path] = $unencryptedSize;
973
+    }
974
+
975
+    /**
976
+     * copy keys to new location
977
+     *
978
+     * @param string $source path relative to data/
979
+     * @param string $target path relative to data/
980
+     * @return bool
981
+     */
982
+    protected function copyKeys($source, $target) {
983
+        if (!$this->util->isExcluded($source)) {
984
+            return $this->keyStorage->copyKeys($source, $target);
985
+        }
986
+
987
+        return false;
988
+    }
989
+
990
+    /**
991
+     * check if path points to a files version
992
+     *
993
+     * @param $path
994
+     * @return bool
995
+     */
996
+    protected function isVersion($path) {
997
+        $normalized = Filesystem::normalizePath($path);
998
+        return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
999
+    }
1000
+
1001
+    /**
1002
+     * check if the given storage should be encrypted or not
1003
+     *
1004
+     * @param $path
1005
+     * @return bool
1006
+     */
1007
+    protected function shouldEncrypt($path) {
1008
+        $fullPath = $this->getFullPath($path);
1009
+        $mountPointConfig = $this->mount->getOption('encrypt', true);
1010
+        if ($mountPointConfig === false) {
1011
+            return false;
1012
+        }
1013
+
1014
+        try {
1015
+            $encryptionModule = $this->getEncryptionModule($fullPath);
1016
+        } catch (ModuleDoesNotExistsException $e) {
1017
+            return false;
1018
+        }
1019
+
1020
+        if ($encryptionModule === null) {
1021
+            $encryptionModule = $this->encryptionManager->getEncryptionModule();
1022
+        }
1023
+
1024
+        return $encryptionModule->shouldEncrypt($fullPath);
1025
+
1026
+    }
1027 1027
 
1028 1028
 }
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 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
 
@@ -440,7 +440,7 @@  discard block
 block discarded – undo
440 440
 				}
441 441
 			} catch (ModuleDoesNotExistsException $e) {
442 442
 				$this->logger->logException($e, [
443
-					'message' => 'Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted',
443
+					'message' => 'Encryption module "'.$encryptionModuleId.'" not found, file will be stored unencrypted',
444 444
 					'level' => \OCP\Util::WARN,
445 445
 					'app' => 'core',
446 446
 				]);
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
 				try {
496 496
 					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
497 497
 				} catch (\Exception $e) {
498
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
498
+					$this->logger->error('Couldn\'t re-calculate unencrypted size for '.$path);
499 499
 					$this->logger->logException($e);
500 500
 				}
501 501
 				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
@@ -524,7 +524,7 @@  discard block
 block discarded – undo
524 524
 
525 525
 		// if we couldn't open the file we return the old unencrypted size
526 526
 		if (!is_resource($stream)) {
527
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
527
+			$this->logger->error('Could not open '.$path.'. Recalculation of unencrypted size aborted.');
528 528
 			return $unencryptedSize;
529 529
 		}
530 530
 
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
 		// next highest is end of chunks, one subtracted is last one
550 550
 		// we have to read the last chunk, we can't just calculate it (because of padding etc)
551 551
 
552
-		$lastChunkNr = ceil($size/ $blockSize)-1;
552
+		$lastChunkNr = ceil($size / $blockSize) - 1;
553 553
 		// calculate last chunk position
554 554
 		$lastChunkPos = ($lastChunkNr * $blockSize);
555 555
 		// try to fseek to the last chunk, if it fails we have to read the whole file
@@ -557,16 +557,16 @@  discard block
 block discarded – undo
557 557
 			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
558 558
 		}
559 559
 
560
-		$lastChunkContentEncrypted='';
560
+		$lastChunkContentEncrypted = '';
561 561
 		$count = $blockSize;
562 562
 
563 563
 		while ($count > 0) {
564
-			$data=fread($stream, $blockSize);
565
-			$count=strlen($data);
564
+			$data = fread($stream, $blockSize);
565
+			$count = strlen($data);
566 566
 			$lastChunkContentEncrypted .= $data;
567
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
567
+			if (strlen($lastChunkContentEncrypted) > $blockSize) {
568 568
 				$newUnencryptedSize += $unencryptedBlockSize;
569
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
569
+				$lastChunkContentEncrypted = substr($lastChunkContentEncrypted, $blockSize);
570 570
 			}
571 571
 		}
572 572
 
@@ -574,8 +574,8 @@  discard block
 block discarded – undo
574 574
 
575 575
 		// we have to decrypt the last chunk to get it actual size
576 576
 		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
577
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
578
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
577
+		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr.'end');
578
+		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr.'end');
579 579
 
580 580
 		// calc the real file size with the size of the last chunk
581 581
 		$newUnencryptedSize += strlen($decryptedLastChunk);
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
 		$cacheInformation = [
660 660
 			'encrypted' => $isEncrypted,
661 661
 		];
662
-		if($isEncrypted) {
662
+		if ($isEncrypted) {
663 663
 			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
664 664
 
665 665
 			// In case of a move operation from an unencrypted to an encrypted
@@ -667,7 +667,7 @@  discard block
 block discarded – undo
667 667
 			// correct value would be "1". Thus we manually set the value to "1"
668 668
 			// for those cases.
669 669
 			// See also https://github.com/owncloud/core/issues/23078
670
-			if($encryptedVersion === 0 || !$keepEncryptionVersion) {
670
+			if ($encryptedVersion === 0 || !$keepEncryptionVersion) {
671 671
 				$encryptedVersion = 1;
672 672
 			}
673 673
 
@@ -703,9 +703,9 @@  discard block
 block discarded – undo
703 703
 			// remember that we try to create a version so that we can detect it during
704 704
 			// fopen($sourceInternalPath) and by-pass the encryption in order to
705 705
 			// create a 1:1 copy of the file
706
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
706
+			$this->arrayCache->set('encryption_copy_version_'.$sourceInternalPath, true);
707 707
 			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
708
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
708
+			$this->arrayCache->remove('encryption_copy_version_'.$sourceInternalPath);
709 709
 			if ($result) {
710 710
 				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
711 711
 				// make sure that we update the unencrypted size for the version
@@ -725,7 +725,7 @@  discard block
 block discarded – undo
725 725
 		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
726 726
 		if (count($mount) === 1) {
727 727
 			$mountPoint = $mount[0]->getMountPoint();
728
-			$source = $mountPoint . '/' . $sourceInternalPath;
728
+			$source = $mountPoint.'/'.$sourceInternalPath;
729 729
 			$target = $this->getFullPath($targetInternalPath);
730 730
 			$this->copyKeys($source, $target);
731 731
 		} else {
@@ -738,7 +738,7 @@  discard block
 block discarded – undo
738 738
 			if (is_resource($dh)) {
739 739
 				while ($result and ($file = readdir($dh)) !== false) {
740 740
 					if (!Filesystem::isIgnoredDir($file)) {
741
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
741
+						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath.'/'.$file, $targetInternalPath.'/'.$file, false, $isRename);
742 742
 					}
743 743
 				}
744 744
 			}
@@ -754,7 +754,7 @@  discard block
 block discarded – undo
754 754
 				fclose($target);
755 755
 				throw $e;
756 756
 			}
757
-			if($result) {
757
+			if ($result) {
758 758
 				if ($preserveMtime) {
759 759
 					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
760 760
 				}
@@ -766,7 +766,7 @@  discard block
 block discarded – undo
766 766
 				$this->getCache()->remove($targetInternalPath);
767 767
 			}
768 768
 		}
769
-		return (bool)$result;
769
+		return (bool) $result;
770 770
 
771 771
 	}
772 772
 
@@ -837,7 +837,7 @@  discard block
 block discarded – undo
837 837
 	 * @return string full path including mount point
838 838
 	 */
839 839
 	protected function getFullPath($path) {
840
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
840
+		return Filesystem::normalizePath($this->mountPoint.'/'.$path);
841 841
 	}
842 842
 
843 843
 	/**
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
 				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
894 894
 
895 895
 				// +1 to not start with an ':' which would result in empty element at the beginning
896
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
896
+				$exploded = explode(':', substr($header, strlen(Util::HEADER_START) + 1));
897 897
 
898 898
 				$element = array_shift($exploded);
899 899
 				while ($element !== Util::HEADER_END) {
@@ -956,7 +956,7 @@  discard block
 block discarded – undo
956 956
 			try {
957 957
 				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
958 958
 			} catch (ModuleDoesNotExistsException $e) {
959
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
959
+				$this->logger->critical('Encryption module defined in "'.$path.'" not loaded!');
960 960
 				throw $e;
961 961
 			}
962 962
 		}
Please login to merge, or discard this patch.
lib/private/Files/ObjectStore/ObjectStoreStorage.php 3 patches
Doc Comments   +6 added lines patch added patch discarded remove patch
@@ -162,6 +162,9 @@  discard block
 block discarded – undo
162 162
 		return true;
163 163
 	}
164 164
 
165
+	/**
166
+	 * @param string $path
167
+	 */
165 168
 	private function rmObjects($path) {
166 169
 		$children = $this->getCache()->getFolderContents($path);
167 170
 		foreach ($children as $child) {
@@ -364,6 +367,9 @@  discard block
 block discarded – undo
364 367
 		return true;
365 368
 	}
366 369
 
370
+	/**
371
+	 * @param string $path
372
+	 */
367 373
 	public function writeBack($tmpFile, $path) {
368 374
 		$stat = $this->stat($path);
369 375
 		if (empty($stat)) {
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -55,9 +55,9 @@  discard block
 block discarded – undo
55 55
 			throw new \Exception('missing IObjectStore instance');
56 56
 		}
57 57
 		if (isset($params['storageid'])) {
58
-			$this->id = 'object::store:' . $params['storageid'];
58
+			$this->id = 'object::store:'.$params['storageid'];
59 59
 		} else {
60
-			$this->id = 'object::store:' . $this->objectStore->getStorageId();
60
+			$this->id = 'object::store:'.$this->objectStore->getStorageId();
61 61
 		}
62 62
 		if (isset($params['objectPrefix'])) {
63 63
 			$this->objectPrefix = $params['objectPrefix'];
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 				if ($ex->getCode() !== 404) {
192 192
 					$this->logger->logException($ex, [
193 193
 						'app' => 'objectstore',
194
-						'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
194
+						'message' => 'Could not delete object '.$this->getURN($stat['fileid']).' for '.$path,
195 195
 					]);
196 196
 					return false;
197 197
 				}
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 	 */
224 224
 	protected function getURN($fileId) {
225 225
 		if (is_numeric($fileId)) {
226
-			return $this->objectPrefix . $fileId;
226
+			return $this->objectPrefix.$fileId;
227 227
 		}
228 228
 		return null;
229 229
 	}
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
 					} catch (\Exception $ex) {
278 278
 						$this->logger->logException($ex, [
279 279
 							'app' => 'objectstore',
280
-							'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
280
+							'message' => 'Count not get object '.$this->getURN($stat['fileid']).' for file '.$path,
281 281
 						]);
282 282
 						return false;
283 283
 					}
@@ -290,7 +290,7 @@  discard block
 block discarded – undo
290 290
 			case 'wb+':
291 291
 				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
292 292
 				$handle = fopen($tmpFile, $mode);
293
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
293
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
294 294
 					$this->writeBack($tmpFile, $path);
295 295
 				});
296 296
 			case 'a':
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
 					file_put_contents($tmpFile, $source);
308 308
 				}
309 309
 				$handle = fopen($tmpFile, $mode);
310
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
310
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
311 311
 					$this->writeBack($tmpFile, $path);
312 312
 				});
313 313
 		}
@@ -316,7 +316,7 @@  discard block
 block discarded – undo
316 316
 
317 317
 	public function file_exists($path) {
318 318
 		$path = $this->normalizePath($path);
319
-		return (bool)$this->stat($path);
319
+		return (bool) $this->stat($path);
320 320
 	}
321 321
 
322 322
 	public function rename($source, $target) {
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
 			} catch (\Exception $ex) {
374 374
 				$this->logger->logException($ex, [
375 375
 					'app' => 'objectstore',
376
-					'message' => 'Could not create object for ' . $path,
376
+					'message' => 'Could not create object for '.$path,
377 377
 				]);
378 378
 				throw $ex;
379 379
 			}
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 			$this->getCache()->remove($path);
414 414
 			$this->logger->logException($ex, [
415 415
 				'app' => 'objectstore',
416
-				'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
416
+				'message' => 'Could not create object '.$this->getURN($fileId).' for '.$path,
417 417
 			]);
418 418
 			throw $ex; // make this bubble up
419 419
 		}
Please login to merge, or discard this patch.
Indentation   +402 added lines, -402 removed lines patch added patch discarded remove patch
@@ -31,406 +31,406 @@
 block discarded – undo
31 31
 use OCP\Files\ObjectStore\IObjectStore;
32 32
 
33 33
 class ObjectStoreStorage extends \OC\Files\Storage\Common {
34
-	/**
35
-	 * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
36
-	 */
37
-	protected $objectStore;
38
-	/**
39
-	 * @var string $id
40
-	 */
41
-	protected $id;
42
-	/**
43
-	 * @var \OC\User\User $user
44
-	 */
45
-	protected $user;
46
-
47
-	private $objectPrefix = 'urn:oid:';
48
-
49
-	private $logger;
50
-
51
-	public function __construct($params) {
52
-		if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
53
-			$this->objectStore = $params['objectstore'];
54
-		} else {
55
-			throw new \Exception('missing IObjectStore instance');
56
-		}
57
-		if (isset($params['storageid'])) {
58
-			$this->id = 'object::store:' . $params['storageid'];
59
-		} else {
60
-			$this->id = 'object::store:' . $this->objectStore->getStorageId();
61
-		}
62
-		if (isset($params['objectPrefix'])) {
63
-			$this->objectPrefix = $params['objectPrefix'];
64
-		}
65
-		//initialize cache with root directory in cache
66
-		if (!$this->is_dir('/')) {
67
-			$this->mkdir('/');
68
-		}
69
-
70
-		$this->logger = \OC::$server->getLogger();
71
-	}
72
-
73
-	public function mkdir($path) {
74
-		$path = $this->normalizePath($path);
75
-
76
-		if ($this->file_exists($path)) {
77
-			return false;
78
-		}
79
-
80
-		$mTime = time();
81
-		$data = [
82
-			'mimetype' => 'httpd/unix-directory',
83
-			'size' => 0,
84
-			'mtime' => $mTime,
85
-			'storage_mtime' => $mTime,
86
-			'permissions' => \OCP\Constants::PERMISSION_ALL,
87
-		];
88
-		if ($path === '') {
89
-			//create root on the fly
90
-			$data['etag'] = $this->getETag('');
91
-			$this->getCache()->put('', $data);
92
-			return true;
93
-		} else {
94
-			// if parent does not exist, create it
95
-			$parent = $this->normalizePath(dirname($path));
96
-			$parentType = $this->filetype($parent);
97
-			if ($parentType === false) {
98
-				if (!$this->mkdir($parent)) {
99
-					// something went wrong
100
-					return false;
101
-				}
102
-			} else if ($parentType === 'file') {
103
-				// parent is a file
104
-				return false;
105
-			}
106
-			// finally create the new dir
107
-			$mTime = time(); // update mtime
108
-			$data['mtime'] = $mTime;
109
-			$data['storage_mtime'] = $mTime;
110
-			$data['etag'] = $this->getETag($path);
111
-			$this->getCache()->put($path, $data);
112
-			return true;
113
-		}
114
-	}
115
-
116
-	/**
117
-	 * @param string $path
118
-	 * @return string
119
-	 */
120
-	private function normalizePath($path) {
121
-		$path = trim($path, '/');
122
-		//FIXME why do we sometimes get a path like 'files//username'?
123
-		$path = str_replace('//', '/', $path);
124
-
125
-		// dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
126
-		if (!$path || $path === '.') {
127
-			$path = '';
128
-		}
129
-
130
-		return $path;
131
-	}
132
-
133
-	/**
134
-	 * Object Stores use a NoopScanner because metadata is directly stored in
135
-	 * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
136
-	 *
137
-	 * @param string $path
138
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
139
-	 * @return \OC\Files\ObjectStore\NoopScanner
140
-	 */
141
-	public function getScanner($path = '', $storage = null) {
142
-		if (!$storage) {
143
-			$storage = $this;
144
-		}
145
-		if (!isset($this->scanner)) {
146
-			$this->scanner = new NoopScanner($storage);
147
-		}
148
-		return $this->scanner;
149
-	}
150
-
151
-	public function getId() {
152
-		return $this->id;
153
-	}
154
-
155
-	public function rmdir($path) {
156
-		$path = $this->normalizePath($path);
157
-
158
-		if (!$this->is_dir($path)) {
159
-			return false;
160
-		}
161
-
162
-		$this->rmObjects($path);
163
-
164
-		$this->getCache()->remove($path);
165
-
166
-		return true;
167
-	}
168
-
169
-	private function rmObjects($path) {
170
-		$children = $this->getCache()->getFolderContents($path);
171
-		foreach ($children as $child) {
172
-			if ($child['mimetype'] === 'httpd/unix-directory') {
173
-				$this->rmObjects($child['path']);
174
-			} else {
175
-				$this->unlink($child['path']);
176
-			}
177
-		}
178
-	}
179
-
180
-	public function unlink($path) {
181
-		$path = $this->normalizePath($path);
182
-		$stat = $this->stat($path);
183
-
184
-		if ($stat && isset($stat['fileid'])) {
185
-			if ($stat['mimetype'] === 'httpd/unix-directory') {
186
-				return $this->rmdir($path);
187
-			}
188
-			try {
189
-				$this->objectStore->deleteObject($this->getURN($stat['fileid']));
190
-			} catch (\Exception $ex) {
191
-				if ($ex->getCode() !== 404) {
192
-					$this->logger->logException($ex, [
193
-						'app' => 'objectstore',
194
-						'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
195
-					]);
196
-					return false;
197
-				}
198
-				//removing from cache is ok as it does not exist in the objectstore anyway
199
-			}
200
-			$this->getCache()->remove($path);
201
-			return true;
202
-		}
203
-		return false;
204
-	}
205
-
206
-	public function stat($path) {
207
-		$path = $this->normalizePath($path);
208
-		$cacheEntry = $this->getCache()->get($path);
209
-		if ($cacheEntry instanceof CacheEntry) {
210
-			return $cacheEntry->getData();
211
-		} else {
212
-			return false;
213
-		}
214
-	}
215
-
216
-	/**
217
-	 * Override this method if you need a different unique resource identifier for your object storage implementation.
218
-	 * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
219
-	 * You may need a mapping table to store your URN if it cannot be generated from the fileid.
220
-	 *
221
-	 * @param int $fileId the fileid
222
-	 * @return null|string the unified resource name used to identify the object
223
-	 */
224
-	protected function getURN($fileId) {
225
-		if (is_numeric($fileId)) {
226
-			return $this->objectPrefix . $fileId;
227
-		}
228
-		return null;
229
-	}
230
-
231
-	public function opendir($path) {
232
-		$path = $this->normalizePath($path);
233
-
234
-		try {
235
-			$files = array();
236
-			$folderContents = $this->getCache()->getFolderContents($path);
237
-			foreach ($folderContents as $file) {
238
-				$files[] = $file['name'];
239
-			}
240
-
241
-			return IteratorDirectory::wrap($files);
242
-		} catch (\Exception $e) {
243
-			$this->logger->logException($e);
244
-			return false;
245
-		}
246
-	}
247
-
248
-	public function filetype($path) {
249
-		$path = $this->normalizePath($path);
250
-		$stat = $this->stat($path);
251
-		if ($stat) {
252
-			if ($stat['mimetype'] === 'httpd/unix-directory') {
253
-				return 'dir';
254
-			}
255
-			return 'file';
256
-		} else {
257
-			return false;
258
-		}
259
-	}
260
-
261
-	public function fopen($path, $mode) {
262
-		$path = $this->normalizePath($path);
263
-
264
-		if (strrpos($path, '.') !== false) {
265
-			$ext = substr($path, strrpos($path, '.'));
266
-		} else {
267
-			$ext = '';
268
-		}
269
-
270
-		switch ($mode) {
271
-			case 'r':
272
-			case 'rb':
273
-				$stat = $this->stat($path);
274
-				if (is_array($stat)) {
275
-					try {
276
-						return $this->objectStore->readObject($this->getURN($stat['fileid']));
277
-					} catch (\Exception $ex) {
278
-						$this->logger->logException($ex, [
279
-							'app' => 'objectstore',
280
-							'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
281
-						]);
282
-						return false;
283
-					}
284
-				} else {
285
-					return false;
286
-				}
287
-			case 'w':
288
-			case 'wb':
289
-			case 'w+':
290
-			case 'wb+':
291
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
292
-				$handle = fopen($tmpFile, $mode);
293
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
294
-					$this->writeBack($tmpFile, $path);
295
-				});
296
-			case 'a':
297
-			case 'ab':
298
-			case 'r+':
299
-			case 'a+':
300
-			case 'x':
301
-			case 'x+':
302
-			case 'c':
303
-			case 'c+':
304
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
305
-				if ($this->file_exists($path)) {
306
-					$source = $this->fopen($path, 'r');
307
-					file_put_contents($tmpFile, $source);
308
-				}
309
-				$handle = fopen($tmpFile, $mode);
310
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
311
-					$this->writeBack($tmpFile, $path);
312
-				});
313
-		}
314
-		return false;
315
-	}
316
-
317
-	public function file_exists($path) {
318
-		$path = $this->normalizePath($path);
319
-		return (bool)$this->stat($path);
320
-	}
321
-
322
-	public function rename($source, $target) {
323
-		$source = $this->normalizePath($source);
324
-		$target = $this->normalizePath($target);
325
-		$this->remove($target);
326
-		$this->getCache()->move($source, $target);
327
-		$this->touch(dirname($target));
328
-		return true;
329
-	}
330
-
331
-	public function getMimeType($path) {
332
-		$path = $this->normalizePath($path);
333
-		$stat = $this->stat($path);
334
-		if (is_array($stat)) {
335
-			return $stat['mimetype'];
336
-		} else {
337
-			return false;
338
-		}
339
-	}
340
-
341
-	public function touch($path, $mtime = null) {
342
-		if (is_null($mtime)) {
343
-			$mtime = time();
344
-		}
345
-
346
-		$path = $this->normalizePath($path);
347
-		$dirName = dirname($path);
348
-		$parentExists = $this->is_dir($dirName);
349
-		if (!$parentExists) {
350
-			return false;
351
-		}
352
-
353
-		$stat = $this->stat($path);
354
-		if (is_array($stat)) {
355
-			// update existing mtime in db
356
-			$stat['mtime'] = $mtime;
357
-			$this->getCache()->update($stat['fileid'], $stat);
358
-		} else {
359
-			try {
360
-				//create a empty file, need to have at least on char to make it
361
-				// work with all object storage implementations
362
-				$this->file_put_contents($path, ' ');
363
-				$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
364
-				$stat = array(
365
-					'etag' => $this->getETag($path),
366
-					'mimetype' => $mimeType,
367
-					'size' => 0,
368
-					'mtime' => $mtime,
369
-					'storage_mtime' => $mtime,
370
-					'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
371
-				);
372
-				$this->getCache()->put($path, $stat);
373
-			} catch (\Exception $ex) {
374
-				$this->logger->logException($ex, [
375
-					'app' => 'objectstore',
376
-					'message' => 'Could not create object for ' . $path,
377
-				]);
378
-				throw $ex;
379
-			}
380
-		}
381
-		return true;
382
-	}
383
-
384
-	public function writeBack($tmpFile, $path) {
385
-		$stat = $this->stat($path);
386
-		if (empty($stat)) {
387
-			// create new file
388
-			$stat = array(
389
-				'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
390
-			);
391
-		}
392
-		// update stat with new data
393
-		$mTime = time();
394
-		$stat['size'] = filesize($tmpFile);
395
-		$stat['mtime'] = $mTime;
396
-		$stat['storage_mtime'] = $mTime;
397
-
398
-		// run path based detection first, to use file extension because $tmpFile is only a random string
399
-		$mimetypeDetector = \OC::$server->getMimeTypeDetector();
400
-		$mimetype = $mimetypeDetector->detectPath($path);
401
-		if ($mimetype === 'application/octet-stream') {
402
-			$mimetype = $mimetypeDetector->detect($tmpFile);
403
-		}
404
-
405
-		$stat['mimetype'] = $mimetype;
406
-		$stat['etag'] = $this->getETag($path);
407
-
408
-		$fileId = $this->getCache()->put($path, $stat);
409
-		try {
410
-			//upload to object storage
411
-			$this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
412
-		} catch (\Exception $ex) {
413
-			$this->getCache()->remove($path);
414
-			$this->logger->logException($ex, [
415
-				'app' => 'objectstore',
416
-				'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
417
-			]);
418
-			throw $ex; // make this bubble up
419
-		}
420
-	}
421
-
422
-	/**
423
-	 * external changes are not supported, exclusive access to the object storage is assumed
424
-	 *
425
-	 * @param string $path
426
-	 * @param int $time
427
-	 * @return false
428
-	 */
429
-	public function hasUpdated($path, $time) {
430
-		return false;
431
-	}
432
-
433
-	public function needsPartFile() {
434
-		return false;
435
-	}
34
+    /**
35
+     * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
36
+     */
37
+    protected $objectStore;
38
+    /**
39
+     * @var string $id
40
+     */
41
+    protected $id;
42
+    /**
43
+     * @var \OC\User\User $user
44
+     */
45
+    protected $user;
46
+
47
+    private $objectPrefix = 'urn:oid:';
48
+
49
+    private $logger;
50
+
51
+    public function __construct($params) {
52
+        if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
53
+            $this->objectStore = $params['objectstore'];
54
+        } else {
55
+            throw new \Exception('missing IObjectStore instance');
56
+        }
57
+        if (isset($params['storageid'])) {
58
+            $this->id = 'object::store:' . $params['storageid'];
59
+        } else {
60
+            $this->id = 'object::store:' . $this->objectStore->getStorageId();
61
+        }
62
+        if (isset($params['objectPrefix'])) {
63
+            $this->objectPrefix = $params['objectPrefix'];
64
+        }
65
+        //initialize cache with root directory in cache
66
+        if (!$this->is_dir('/')) {
67
+            $this->mkdir('/');
68
+        }
69
+
70
+        $this->logger = \OC::$server->getLogger();
71
+    }
72
+
73
+    public function mkdir($path) {
74
+        $path = $this->normalizePath($path);
75
+
76
+        if ($this->file_exists($path)) {
77
+            return false;
78
+        }
79
+
80
+        $mTime = time();
81
+        $data = [
82
+            'mimetype' => 'httpd/unix-directory',
83
+            'size' => 0,
84
+            'mtime' => $mTime,
85
+            'storage_mtime' => $mTime,
86
+            'permissions' => \OCP\Constants::PERMISSION_ALL,
87
+        ];
88
+        if ($path === '') {
89
+            //create root on the fly
90
+            $data['etag'] = $this->getETag('');
91
+            $this->getCache()->put('', $data);
92
+            return true;
93
+        } else {
94
+            // if parent does not exist, create it
95
+            $parent = $this->normalizePath(dirname($path));
96
+            $parentType = $this->filetype($parent);
97
+            if ($parentType === false) {
98
+                if (!$this->mkdir($parent)) {
99
+                    // something went wrong
100
+                    return false;
101
+                }
102
+            } else if ($parentType === 'file') {
103
+                // parent is a file
104
+                return false;
105
+            }
106
+            // finally create the new dir
107
+            $mTime = time(); // update mtime
108
+            $data['mtime'] = $mTime;
109
+            $data['storage_mtime'] = $mTime;
110
+            $data['etag'] = $this->getETag($path);
111
+            $this->getCache()->put($path, $data);
112
+            return true;
113
+        }
114
+    }
115
+
116
+    /**
117
+     * @param string $path
118
+     * @return string
119
+     */
120
+    private function normalizePath($path) {
121
+        $path = trim($path, '/');
122
+        //FIXME why do we sometimes get a path like 'files//username'?
123
+        $path = str_replace('//', '/', $path);
124
+
125
+        // dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
126
+        if (!$path || $path === '.') {
127
+            $path = '';
128
+        }
129
+
130
+        return $path;
131
+    }
132
+
133
+    /**
134
+     * Object Stores use a NoopScanner because metadata is directly stored in
135
+     * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
136
+     *
137
+     * @param string $path
138
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
139
+     * @return \OC\Files\ObjectStore\NoopScanner
140
+     */
141
+    public function getScanner($path = '', $storage = null) {
142
+        if (!$storage) {
143
+            $storage = $this;
144
+        }
145
+        if (!isset($this->scanner)) {
146
+            $this->scanner = new NoopScanner($storage);
147
+        }
148
+        return $this->scanner;
149
+    }
150
+
151
+    public function getId() {
152
+        return $this->id;
153
+    }
154
+
155
+    public function rmdir($path) {
156
+        $path = $this->normalizePath($path);
157
+
158
+        if (!$this->is_dir($path)) {
159
+            return false;
160
+        }
161
+
162
+        $this->rmObjects($path);
163
+
164
+        $this->getCache()->remove($path);
165
+
166
+        return true;
167
+    }
168
+
169
+    private function rmObjects($path) {
170
+        $children = $this->getCache()->getFolderContents($path);
171
+        foreach ($children as $child) {
172
+            if ($child['mimetype'] === 'httpd/unix-directory') {
173
+                $this->rmObjects($child['path']);
174
+            } else {
175
+                $this->unlink($child['path']);
176
+            }
177
+        }
178
+    }
179
+
180
+    public function unlink($path) {
181
+        $path = $this->normalizePath($path);
182
+        $stat = $this->stat($path);
183
+
184
+        if ($stat && isset($stat['fileid'])) {
185
+            if ($stat['mimetype'] === 'httpd/unix-directory') {
186
+                return $this->rmdir($path);
187
+            }
188
+            try {
189
+                $this->objectStore->deleteObject($this->getURN($stat['fileid']));
190
+            } catch (\Exception $ex) {
191
+                if ($ex->getCode() !== 404) {
192
+                    $this->logger->logException($ex, [
193
+                        'app' => 'objectstore',
194
+                        'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
195
+                    ]);
196
+                    return false;
197
+                }
198
+                //removing from cache is ok as it does not exist in the objectstore anyway
199
+            }
200
+            $this->getCache()->remove($path);
201
+            return true;
202
+        }
203
+        return false;
204
+    }
205
+
206
+    public function stat($path) {
207
+        $path = $this->normalizePath($path);
208
+        $cacheEntry = $this->getCache()->get($path);
209
+        if ($cacheEntry instanceof CacheEntry) {
210
+            return $cacheEntry->getData();
211
+        } else {
212
+            return false;
213
+        }
214
+    }
215
+
216
+    /**
217
+     * Override this method if you need a different unique resource identifier for your object storage implementation.
218
+     * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
219
+     * You may need a mapping table to store your URN if it cannot be generated from the fileid.
220
+     *
221
+     * @param int $fileId the fileid
222
+     * @return null|string the unified resource name used to identify the object
223
+     */
224
+    protected function getURN($fileId) {
225
+        if (is_numeric($fileId)) {
226
+            return $this->objectPrefix . $fileId;
227
+        }
228
+        return null;
229
+    }
230
+
231
+    public function opendir($path) {
232
+        $path = $this->normalizePath($path);
233
+
234
+        try {
235
+            $files = array();
236
+            $folderContents = $this->getCache()->getFolderContents($path);
237
+            foreach ($folderContents as $file) {
238
+                $files[] = $file['name'];
239
+            }
240
+
241
+            return IteratorDirectory::wrap($files);
242
+        } catch (\Exception $e) {
243
+            $this->logger->logException($e);
244
+            return false;
245
+        }
246
+    }
247
+
248
+    public function filetype($path) {
249
+        $path = $this->normalizePath($path);
250
+        $stat = $this->stat($path);
251
+        if ($stat) {
252
+            if ($stat['mimetype'] === 'httpd/unix-directory') {
253
+                return 'dir';
254
+            }
255
+            return 'file';
256
+        } else {
257
+            return false;
258
+        }
259
+    }
260
+
261
+    public function fopen($path, $mode) {
262
+        $path = $this->normalizePath($path);
263
+
264
+        if (strrpos($path, '.') !== false) {
265
+            $ext = substr($path, strrpos($path, '.'));
266
+        } else {
267
+            $ext = '';
268
+        }
269
+
270
+        switch ($mode) {
271
+            case 'r':
272
+            case 'rb':
273
+                $stat = $this->stat($path);
274
+                if (is_array($stat)) {
275
+                    try {
276
+                        return $this->objectStore->readObject($this->getURN($stat['fileid']));
277
+                    } catch (\Exception $ex) {
278
+                        $this->logger->logException($ex, [
279
+                            'app' => 'objectstore',
280
+                            'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
281
+                        ]);
282
+                        return false;
283
+                    }
284
+                } else {
285
+                    return false;
286
+                }
287
+            case 'w':
288
+            case 'wb':
289
+            case 'w+':
290
+            case 'wb+':
291
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
292
+                $handle = fopen($tmpFile, $mode);
293
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
294
+                    $this->writeBack($tmpFile, $path);
295
+                });
296
+            case 'a':
297
+            case 'ab':
298
+            case 'r+':
299
+            case 'a+':
300
+            case 'x':
301
+            case 'x+':
302
+            case 'c':
303
+            case 'c+':
304
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
305
+                if ($this->file_exists($path)) {
306
+                    $source = $this->fopen($path, 'r');
307
+                    file_put_contents($tmpFile, $source);
308
+                }
309
+                $handle = fopen($tmpFile, $mode);
310
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
311
+                    $this->writeBack($tmpFile, $path);
312
+                });
313
+        }
314
+        return false;
315
+    }
316
+
317
+    public function file_exists($path) {
318
+        $path = $this->normalizePath($path);
319
+        return (bool)$this->stat($path);
320
+    }
321
+
322
+    public function rename($source, $target) {
323
+        $source = $this->normalizePath($source);
324
+        $target = $this->normalizePath($target);
325
+        $this->remove($target);
326
+        $this->getCache()->move($source, $target);
327
+        $this->touch(dirname($target));
328
+        return true;
329
+    }
330
+
331
+    public function getMimeType($path) {
332
+        $path = $this->normalizePath($path);
333
+        $stat = $this->stat($path);
334
+        if (is_array($stat)) {
335
+            return $stat['mimetype'];
336
+        } else {
337
+            return false;
338
+        }
339
+    }
340
+
341
+    public function touch($path, $mtime = null) {
342
+        if (is_null($mtime)) {
343
+            $mtime = time();
344
+        }
345
+
346
+        $path = $this->normalizePath($path);
347
+        $dirName = dirname($path);
348
+        $parentExists = $this->is_dir($dirName);
349
+        if (!$parentExists) {
350
+            return false;
351
+        }
352
+
353
+        $stat = $this->stat($path);
354
+        if (is_array($stat)) {
355
+            // update existing mtime in db
356
+            $stat['mtime'] = $mtime;
357
+            $this->getCache()->update($stat['fileid'], $stat);
358
+        } else {
359
+            try {
360
+                //create a empty file, need to have at least on char to make it
361
+                // work with all object storage implementations
362
+                $this->file_put_contents($path, ' ');
363
+                $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
364
+                $stat = array(
365
+                    'etag' => $this->getETag($path),
366
+                    'mimetype' => $mimeType,
367
+                    'size' => 0,
368
+                    'mtime' => $mtime,
369
+                    'storage_mtime' => $mtime,
370
+                    'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
371
+                );
372
+                $this->getCache()->put($path, $stat);
373
+            } catch (\Exception $ex) {
374
+                $this->logger->logException($ex, [
375
+                    'app' => 'objectstore',
376
+                    'message' => 'Could not create object for ' . $path,
377
+                ]);
378
+                throw $ex;
379
+            }
380
+        }
381
+        return true;
382
+    }
383
+
384
+    public function writeBack($tmpFile, $path) {
385
+        $stat = $this->stat($path);
386
+        if (empty($stat)) {
387
+            // create new file
388
+            $stat = array(
389
+                'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
390
+            );
391
+        }
392
+        // update stat with new data
393
+        $mTime = time();
394
+        $stat['size'] = filesize($tmpFile);
395
+        $stat['mtime'] = $mTime;
396
+        $stat['storage_mtime'] = $mTime;
397
+
398
+        // run path based detection first, to use file extension because $tmpFile is only a random string
399
+        $mimetypeDetector = \OC::$server->getMimeTypeDetector();
400
+        $mimetype = $mimetypeDetector->detectPath($path);
401
+        if ($mimetype === 'application/octet-stream') {
402
+            $mimetype = $mimetypeDetector->detect($tmpFile);
403
+        }
404
+
405
+        $stat['mimetype'] = $mimetype;
406
+        $stat['etag'] = $this->getETag($path);
407
+
408
+        $fileId = $this->getCache()->put($path, $stat);
409
+        try {
410
+            //upload to object storage
411
+            $this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
412
+        } catch (\Exception $ex) {
413
+            $this->getCache()->remove($path);
414
+            $this->logger->logException($ex, [
415
+                'app' => 'objectstore',
416
+                'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
417
+            ]);
418
+            throw $ex; // make this bubble up
419
+        }
420
+    }
421
+
422
+    /**
423
+     * external changes are not supported, exclusive access to the object storage is assumed
424
+     *
425
+     * @param string $path
426
+     * @param int $time
427
+     * @return false
428
+     */
429
+    public function hasUpdated($path, $time) {
430
+        return false;
431
+    }
432
+
433
+    public function needsPartFile() {
434
+        return false;
435
+    }
436 436
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Notify/SMBNotifyHandler.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -102,7 +102,7 @@
 block discarded – undo
102 102
 
103 103
 	/**
104 104
 	 * @param \Icewind\SMB\Change $change
105
-	 * @return IChange|null
105
+	 * @return null|Change
106 106
 	 */
107 107
 	private function mapChange(\Icewind\SMB\Change $change) {
108 108
 		$path = $this->relativePath($change->getPath());
Please login to merge, or discard this patch.
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -29,122 +29,122 @@
 block discarded – undo
29 29
 use OCP\Files\Notify\INotifyHandler;
30 30
 
31 31
 class SMBNotifyHandler implements INotifyHandler {
32
-	/**
33
-	 * @var \Icewind\SMB\INotifyHandler
34
-	 */
35
-	private $shareNotifyHandler;
32
+    /**
33
+     * @var \Icewind\SMB\INotifyHandler
34
+     */
35
+    private $shareNotifyHandler;
36 36
 
37
-	/**
38
-	 * @var string
39
-	 */
40
-	private $root;
37
+    /**
38
+     * @var string
39
+     */
40
+    private $root;
41 41
 
42
-	private $oldRenamePath = null;
42
+    private $oldRenamePath = null;
43 43
 
44
-	/**
45
-	 * SMBNotifyHandler constructor.
46
-	 *
47
-	 * @param \Icewind\SMB\INotifyHandler $shareNotifyHandler
48
-	 * @param string $root
49
-	 */
50
-	public function __construct(\Icewind\SMB\INotifyHandler $shareNotifyHandler, $root) {
51
-		$this->shareNotifyHandler = $shareNotifyHandler;
52
-		$this->root = $root;
53
-	}
44
+    /**
45
+     * SMBNotifyHandler constructor.
46
+     *
47
+     * @param \Icewind\SMB\INotifyHandler $shareNotifyHandler
48
+     * @param string $root
49
+     */
50
+    public function __construct(\Icewind\SMB\INotifyHandler $shareNotifyHandler, $root) {
51
+        $this->shareNotifyHandler = $shareNotifyHandler;
52
+        $this->root = $root;
53
+    }
54 54
 
55
-	private function relativePath($fullPath) {
56
-		if ($fullPath === $this->root) {
57
-			return '';
58
-		} else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
59
-			return substr($fullPath, strlen($this->root));
60
-		} else {
61
-			return null;
62
-		}
63
-	}
55
+    private function relativePath($fullPath) {
56
+        if ($fullPath === $this->root) {
57
+            return '';
58
+        } else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
59
+            return substr($fullPath, strlen($this->root));
60
+        } else {
61
+            return null;
62
+        }
63
+    }
64 64
 
65
-	public function listen(callable $callback) {
66
-		$oldRenamePath = null;
67
-		$this->shareNotifyHandler->listen(function (\Icewind\SMB\Change $shareChange) use ($callback) {
68
-			$change = $this->mapChange($shareChange);
69
-			if (!is_null($change)) {
70
-				return $callback($change);
71
-			} else {
72
-				return true;
73
-			}
74
-		});
75
-	}
65
+    public function listen(callable $callback) {
66
+        $oldRenamePath = null;
67
+        $this->shareNotifyHandler->listen(function (\Icewind\SMB\Change $shareChange) use ($callback) {
68
+            $change = $this->mapChange($shareChange);
69
+            if (!is_null($change)) {
70
+                return $callback($change);
71
+            } else {
72
+                return true;
73
+            }
74
+        });
75
+    }
76 76
 
77
-	/**
78
-	 * Get all changes detected since the start of the notify process or the last call to getChanges
79
-	 *
80
-	 * @return IChange[]
81
-	 */
82
-	public function getChanges() {
83
-		$shareChanges = $this->shareNotifyHandler->getChanges();
84
-		$changes = [];
85
-		foreach ($shareChanges as $shareChange) {
86
-			$change = $this->mapChange($shareChange);
87
-			if ($change) {
88
-				$changes[] = $change;
89
-			}
90
-		}
91
-		return $changes;
92
-	}
77
+    /**
78
+     * Get all changes detected since the start of the notify process or the last call to getChanges
79
+     *
80
+     * @return IChange[]
81
+     */
82
+    public function getChanges() {
83
+        $shareChanges = $this->shareNotifyHandler->getChanges();
84
+        $changes = [];
85
+        foreach ($shareChanges as $shareChange) {
86
+            $change = $this->mapChange($shareChange);
87
+            if ($change) {
88
+                $changes[] = $change;
89
+            }
90
+        }
91
+        return $changes;
92
+    }
93 93
 
94
-	/**
95
-	 * Stop listening for changes
96
-	 *
97
-	 * Note that any pending changes will be discarded
98
-	 */
99
-	public function stop() {
100
-		$this->shareNotifyHandler->stop();
101
-	}
94
+    /**
95
+     * Stop listening for changes
96
+     *
97
+     * Note that any pending changes will be discarded
98
+     */
99
+    public function stop() {
100
+        $this->shareNotifyHandler->stop();
101
+    }
102 102
 
103
-	/**
104
-	 * @param \Icewind\SMB\Change $change
105
-	 * @return IChange|null
106
-	 */
107
-	private function mapChange(\Icewind\SMB\Change $change) {
108
-		$path = $this->relativePath($change->getPath());
109
-		if (is_null($path)) {
110
-			return null;
111
-		}
112
-		if ($change->getCode() === \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_OLD) {
113
-			$this->oldRenamePath = $path;
114
-			return null;
115
-		}
116
-		$type = $this->mapNotifyType($change->getCode());
117
-		if (is_null($type)) {
118
-			return null;
119
-		}
120
-		if ($type === IChange::RENAMED) {
121
-			if (!is_null($this->oldRenamePath)) {
122
-				$result = new RenameChange($type, $this->oldRenamePath, $path);
123
-				$this->oldRenamePath = null;
124
-			} else {
125
-				$result = null;
126
-			}
127
-		} else {
128
-			$result = new Change($type, $path);
129
-		}
130
-		return $result;
131
-	}
103
+    /**
104
+     * @param \Icewind\SMB\Change $change
105
+     * @return IChange|null
106
+     */
107
+    private function mapChange(\Icewind\SMB\Change $change) {
108
+        $path = $this->relativePath($change->getPath());
109
+        if (is_null($path)) {
110
+            return null;
111
+        }
112
+        if ($change->getCode() === \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_OLD) {
113
+            $this->oldRenamePath = $path;
114
+            return null;
115
+        }
116
+        $type = $this->mapNotifyType($change->getCode());
117
+        if (is_null($type)) {
118
+            return null;
119
+        }
120
+        if ($type === IChange::RENAMED) {
121
+            if (!is_null($this->oldRenamePath)) {
122
+                $result = new RenameChange($type, $this->oldRenamePath, $path);
123
+                $this->oldRenamePath = null;
124
+            } else {
125
+                $result = null;
126
+            }
127
+        } else {
128
+            $result = new Change($type, $path);
129
+        }
130
+        return $result;
131
+    }
132 132
 
133
-	private function mapNotifyType($smbType) {
134
-		switch ($smbType) {
135
-			case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED:
136
-				return IChange::ADDED;
137
-			case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED:
138
-				return IChange::REMOVED;
139
-			case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED:
140
-			case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED_STREAM:
141
-			case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED_STREAM:
142
-			case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED_STREAM:
143
-				return IChange::MODIFIED;
144
-			case \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_NEW:
145
-				return IChange::RENAMED;
146
-			default:
147
-				return null;
148
-		}
149
-	}
133
+    private function mapNotifyType($smbType) {
134
+        switch ($smbType) {
135
+            case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED:
136
+                return IChange::ADDED;
137
+            case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED:
138
+                return IChange::REMOVED;
139
+            case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED:
140
+            case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED_STREAM:
141
+            case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED_STREAM:
142
+            case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED_STREAM:
143
+                return IChange::MODIFIED;
144
+            case \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_NEW:
145
+                return IChange::RENAMED;
146
+            default:
147
+                return null;
148
+        }
149
+    }
150 150
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -64,7 +64,7 @@
 block discarded – undo
64 64
 
65 65
 	public function listen(callable $callback) {
66 66
 		$oldRenamePath = null;
67
-		$this->shareNotifyHandler->listen(function (\Icewind\SMB\Change $shareChange) use ($callback) {
67
+		$this->shareNotifyHandler->listen(function(\Icewind\SMB\Change $shareChange) use ($callback) {
68 68
 			$change = $this->mapChange($shareChange);
69 69
 			if (!is_null($change)) {
70 70
 				return $callback($change);
Please login to merge, or discard this patch.