Completed
Pull Request — master (#9895)
by Björn
43:43 queued 13:05
created
lib/public/Settings/IIconSection.php 2 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -33,6 +33,7 @@
 block discarded – undo
33 33
 	 *
34 34
 	 * @returns string
35 35
 	 * @since 12
36
+	 * @return string
36 37
 	 */
37 38
 	public function getIcon();
38 39
 }
Please login to merge, or discard this patch.
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -27,12 +27,12 @@
 block discarded – undo
27 27
  * @since 12
28 28
  */
29 29
 interface IIconSection extends ISection {
30
-	/**
31
-	 * returns the relative path to an 16*16 icon describing the section.
32
-	 * e.g. '/core/img/places/files.svg'
33
-	 *
34
-	 * @returns string
35
-	 * @since 12
36
-	 */
37
-	public function getIcon();
30
+    /**
31
+     * returns the relative path to an 16*16 icon describing the section.
32
+     * e.g. '/core/img/places/files.svg'
33
+     *
34
+     * @returns string
35
+     * @since 12
36
+     */
37
+    public function getIcon();
38 38
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/FTP.php 4 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -139,6 +139,9 @@
 block discarded – undo
139 139
 		return false;
140 140
 	}
141 141
 
142
+	/**
143
+	 * @param string $path
144
+	 */
142 145
 	public function writeBack($tmpFile, $path) {
143 146
 		$this->uploadFile($tmpFile, $path);
144 147
 		unlink($tmpFile);
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -93,8 +93,7 @@
 block discarded – undo
93 93
 	public function unlink($path) {
94 94
 		if ($this->is_dir($path)) {
95 95
 			return $this->rmdir($path);
96
-		}
97
-		else {
96
+		} else {
98 97
 			$url = $this->constructUrl($path);
99 98
 			$result = unlink($url);
100 99
 			clearstatcache(true, $url);
Please login to merge, or discard this patch.
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -38,122 +38,122 @@
 block discarded – undo
38 38
 use Icewind\Streams\RetryWrapper;
39 39
 
40 40
 class FTP extends StreamWrapper{
41
-	private $password;
42
-	private $user;
43
-	private $host;
44
-	private $secure;
45
-	private $root;
41
+    private $password;
42
+    private $user;
43
+    private $host;
44
+    private $secure;
45
+    private $root;
46 46
 
47
-	private static $tempFiles=array();
47
+    private static $tempFiles=array();
48 48
 
49
-	public function __construct($params) {
50
-		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
51
-			$this->host=$params['host'];
52
-			$this->user=$params['user'];
53
-			$this->password=$params['password'];
54
-			if (isset($params['secure'])) {
55
-				$this->secure = $params['secure'];
56
-			} else {
57
-				$this->secure = false;
58
-			}
59
-			$this->root=isset($params['root'])?$params['root']:'/';
60
-			if ( ! $this->root || $this->root[0]!=='/') {
61
-				$this->root='/'.$this->root;
62
-			}
63
-			if (substr($this->root, -1) !== '/') {
64
-				$this->root .= '/';
65
-			}
66
-		} else {
67
-			throw new \Exception('Creating FTP storage failed');
68
-		}
49
+    public function __construct($params) {
50
+        if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
51
+            $this->host=$params['host'];
52
+            $this->user=$params['user'];
53
+            $this->password=$params['password'];
54
+            if (isset($params['secure'])) {
55
+                $this->secure = $params['secure'];
56
+            } else {
57
+                $this->secure = false;
58
+            }
59
+            $this->root=isset($params['root'])?$params['root']:'/';
60
+            if ( ! $this->root || $this->root[0]!=='/') {
61
+                $this->root='/'.$this->root;
62
+            }
63
+            if (substr($this->root, -1) !== '/') {
64
+                $this->root .= '/';
65
+            }
66
+        } else {
67
+            throw new \Exception('Creating FTP storage failed');
68
+        }
69 69
 		
70
-	}
70
+    }
71 71
 
72
-	public function getId(){
73
-		return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
74
-	}
72
+    public function getId(){
73
+        return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
74
+    }
75 75
 
76
-	/**
77
-	 * construct the ftp url
78
-	 * @param string $path
79
-	 * @return string
80
-	 */
81
-	public function constructUrl($path) {
82
-		$url='ftp';
83
-		if ($this->secure) {
84
-			$url.='s';
85
-		}
86
-		$url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
87
-		return $url;
88
-	}
76
+    /**
77
+     * construct the ftp url
78
+     * @param string $path
79
+     * @return string
80
+     */
81
+    public function constructUrl($path) {
82
+        $url='ftp';
83
+        if ($this->secure) {
84
+            $url.='s';
85
+        }
86
+        $url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
87
+        return $url;
88
+    }
89 89
 
90
-	/**
91
-	 * Unlinks file or directory
92
-	 * @param string $path
93
-	 */
94
-	public function unlink($path) {
95
-		if ($this->is_dir($path)) {
96
-			return $this->rmdir($path);
97
-		}
98
-		else {
99
-			$url = $this->constructUrl($path);
100
-			$result = unlink($url);
101
-			clearstatcache(true, $url);
102
-			return $result;
103
-		}
104
-	}
105
-	public function fopen($path,$mode) {
106
-		switch($mode) {
107
-			case 'r':
108
-			case 'rb':
109
-			case 'w':
110
-			case 'wb':
111
-			case 'a':
112
-			case 'ab':
113
-				//these are supported by the wrapper
114
-				$context = stream_context_create(array('ftp' => array('overwrite' => true)));
115
-				$handle = fopen($this->constructUrl($path), $mode, false, $context);
116
-				return RetryWrapper::wrap($handle);
117
-			case 'r+':
118
-			case 'w+':
119
-			case 'wb+':
120
-			case 'a+':
121
-			case 'x':
122
-			case 'x+':
123
-			case 'c':
124
-			case 'c+':
125
-				//emulate these
126
-				if (strrpos($path, '.')!==false) {
127
-					$ext=substr($path, strrpos($path, '.'));
128
-				} else {
129
-					$ext='';
130
-				}
131
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile();
132
-				if ($this->file_exists($path)) {
133
-					$this->getFile($path, $tmpFile);
134
-				}
135
-				$handle = fopen($tmpFile, $mode);
136
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
137
-					$this->writeBack($tmpFile, $path);
138
-				});
139
-		}
140
-		return false;
141
-	}
90
+    /**
91
+     * Unlinks file or directory
92
+     * @param string $path
93
+     */
94
+    public function unlink($path) {
95
+        if ($this->is_dir($path)) {
96
+            return $this->rmdir($path);
97
+        }
98
+        else {
99
+            $url = $this->constructUrl($path);
100
+            $result = unlink($url);
101
+            clearstatcache(true, $url);
102
+            return $result;
103
+        }
104
+    }
105
+    public function fopen($path,$mode) {
106
+        switch($mode) {
107
+            case 'r':
108
+            case 'rb':
109
+            case 'w':
110
+            case 'wb':
111
+            case 'a':
112
+            case 'ab':
113
+                //these are supported by the wrapper
114
+                $context = stream_context_create(array('ftp' => array('overwrite' => true)));
115
+                $handle = fopen($this->constructUrl($path), $mode, false, $context);
116
+                return RetryWrapper::wrap($handle);
117
+            case 'r+':
118
+            case 'w+':
119
+            case 'wb+':
120
+            case 'a+':
121
+            case 'x':
122
+            case 'x+':
123
+            case 'c':
124
+            case 'c+':
125
+                //emulate these
126
+                if (strrpos($path, '.')!==false) {
127
+                    $ext=substr($path, strrpos($path, '.'));
128
+                } else {
129
+                    $ext='';
130
+                }
131
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile();
132
+                if ($this->file_exists($path)) {
133
+                    $this->getFile($path, $tmpFile);
134
+                }
135
+                $handle = fopen($tmpFile, $mode);
136
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
137
+                    $this->writeBack($tmpFile, $path);
138
+                });
139
+        }
140
+        return false;
141
+    }
142 142
 
143
-	public function writeBack($tmpFile, $path) {
144
-		$this->uploadFile($tmpFile, $path);
145
-		unlink($tmpFile);
146
-	}
143
+    public function writeBack($tmpFile, $path) {
144
+        $this->uploadFile($tmpFile, $path);
145
+        unlink($tmpFile);
146
+    }
147 147
 
148
-	/**
149
-	 * check if php-ftp is installed
150
-	 */
151
-	public static function checkDependencies() {
152
-		if (function_exists('ftp_login')) {
153
-			return true;
154
-		} else {
155
-			return array('ftp');
156
-		}
157
-	}
148
+    /**
149
+     * check if php-ftp is installed
150
+     */
151
+    public static function checkDependencies() {
152
+        if (function_exists('ftp_login')) {
153
+            return true;
154
+        } else {
155
+            return array('ftp');
156
+        }
157
+    }
158 158
 
159 159
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -37,28 +37,28 @@  discard block
 block discarded – undo
37 37
 use Icewind\Streams\CallbackWrapper;
38 38
 use Icewind\Streams\RetryWrapper;
39 39
 
40
-class FTP extends StreamWrapper{
40
+class FTP extends StreamWrapper {
41 41
 	private $password;
42 42
 	private $user;
43 43
 	private $host;
44 44
 	private $secure;
45 45
 	private $root;
46 46
 
47
-	private static $tempFiles=array();
47
+	private static $tempFiles = array();
48 48
 
49 49
 	public function __construct($params) {
50 50
 		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
51
-			$this->host=$params['host'];
52
-			$this->user=$params['user'];
53
-			$this->password=$params['password'];
51
+			$this->host = $params['host'];
52
+			$this->user = $params['user'];
53
+			$this->password = $params['password'];
54 54
 			if (isset($params['secure'])) {
55 55
 				$this->secure = $params['secure'];
56 56
 			} else {
57 57
 				$this->secure = false;
58 58
 			}
59
-			$this->root=isset($params['root'])?$params['root']:'/';
60
-			if ( ! $this->root || $this->root[0]!=='/') {
61
-				$this->root='/'.$this->root;
59
+			$this->root = isset($params['root']) ? $params['root'] : '/';
60
+			if (!$this->root || $this->root[0] !== '/') {
61
+				$this->root = '/'.$this->root;
62 62
 			}
63 63
 			if (substr($this->root, -1) !== '/') {
64 64
 				$this->root .= '/';
@@ -69,8 +69,8 @@  discard block
 block discarded – undo
69 69
 		
70 70
 	}
71 71
 
72
-	public function getId(){
73
-		return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
72
+	public function getId() {
73
+		return 'ftp::'.$this->user.'@'.$this->host.'/'.$this->root;
74 74
 	}
75 75
 
76 76
 	/**
@@ -79,11 +79,11 @@  discard block
 block discarded – undo
79 79
 	 * @return string
80 80
 	 */
81 81
 	public function constructUrl($path) {
82
-		$url='ftp';
82
+		$url = 'ftp';
83 83
 		if ($this->secure) {
84
-			$url.='s';
84
+			$url .= 's';
85 85
 		}
86
-		$url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
86
+		$url .= '://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
87 87
 		return $url;
88 88
 	}
89 89
 
@@ -102,8 +102,8 @@  discard block
 block discarded – undo
102 102
 			return $result;
103 103
 		}
104 104
 	}
105
-	public function fopen($path,$mode) {
106
-		switch($mode) {
105
+	public function fopen($path, $mode) {
106
+		switch ($mode) {
107 107
 			case 'r':
108 108
 			case 'rb':
109 109
 			case 'w':
@@ -123,17 +123,17 @@  discard block
 block discarded – undo
123 123
 			case 'c':
124 124
 			case 'c+':
125 125
 				//emulate these
126
-				if (strrpos($path, '.')!==false) {
127
-					$ext=substr($path, strrpos($path, '.'));
126
+				if (strrpos($path, '.') !== false) {
127
+					$ext = substr($path, strrpos($path, '.'));
128 128
 				} else {
129
-					$ext='';
129
+					$ext = '';
130 130
 				}
131 131
 				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile();
132 132
 				if ($this->file_exists($path)) {
133 133
 					$this->getFile($path, $tmpFile);
134 134
 				}
135 135
 				$handle = fopen($tmpFile, $mode);
136
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
136
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
137 137
 					$this->writeBack($tmpFile, $path);
138 138
 				});
139 139
 		}
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareController.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -597,7 +597,7 @@
 block discarded – undo
597 597
 	 * publish activity
598 598
 	 *
599 599
 	 * @param string $subject
600
-	 * @param array $parameters
600
+	 * @param string[] $parameters
601 601
 	 * @param string $affectedUser
602 602
 	 * @param int $fileId
603 603
 	 * @param string $filePath
Please login to merge, or discard this patch.
Indentation   +596 added lines, -596 removed lines patch added patch discarded remove patch
@@ -70,604 +70,604 @@
 block discarded – undo
70 70
  */
71 71
 class ShareController extends Controller {
72 72
 
73
-	/** @var IConfig */
74
-	protected $config;
75
-	/** @var IURLGenerator */
76
-	protected $urlGenerator;
77
-	/** @var IUserManager */
78
-	protected $userManager;
79
-	/** @var ILogger */
80
-	protected $logger;
81
-	/** @var \OCP\Activity\IManager */
82
-	protected $activityManager;
83
-	/** @var \OCP\Share\IManager */
84
-	protected $shareManager;
85
-	/** @var ISession */
86
-	protected $session;
87
-	/** @var IPreview */
88
-	protected $previewManager;
89
-	/** @var IRootFolder */
90
-	protected $rootFolder;
91
-	/** @var FederatedShareProvider */
92
-	protected $federatedShareProvider;
93
-	/** @var EventDispatcherInterface */
94
-	protected $eventDispatcher;
95
-	/** @var IL10N */
96
-	protected $l10n;
97
-	/** @var Defaults */
98
-	protected $defaults;
99
-
100
-	/**
101
-	 * @param string $appName
102
-	 * @param IRequest $request
103
-	 * @param IConfig $config
104
-	 * @param IURLGenerator $urlGenerator
105
-	 * @param IUserManager $userManager
106
-	 * @param ILogger $logger
107
-	 * @param \OCP\Activity\IManager $activityManager
108
-	 * @param \OCP\Share\IManager $shareManager
109
-	 * @param ISession $session
110
-	 * @param IPreview $previewManager
111
-	 * @param IRootFolder $rootFolder
112
-	 * @param FederatedShareProvider $federatedShareProvider
113
-	 * @param EventDispatcherInterface $eventDispatcher
114
-	 * @param IL10N $l10n
115
-	 * @param Defaults $defaults
116
-	 */
117
-	public function __construct($appName,
118
-								IRequest $request,
119
-								IConfig $config,
120
-								IURLGenerator $urlGenerator,
121
-								IUserManager $userManager,
122
-								ILogger $logger,
123
-								\OCP\Activity\IManager $activityManager,
124
-								\OCP\Share\IManager $shareManager,
125
-								ISession $session,
126
-								IPreview $previewManager,
127
-								IRootFolder $rootFolder,
128
-								FederatedShareProvider $federatedShareProvider,
129
-								EventDispatcherInterface $eventDispatcher,
130
-								IL10N $l10n,
131
-								Defaults $defaults) {
132
-		parent::__construct($appName, $request);
133
-
134
-		$this->config = $config;
135
-		$this->urlGenerator = $urlGenerator;
136
-		$this->userManager = $userManager;
137
-		$this->logger = $logger;
138
-		$this->activityManager = $activityManager;
139
-		$this->shareManager = $shareManager;
140
-		$this->session = $session;
141
-		$this->previewManager = $previewManager;
142
-		$this->rootFolder = $rootFolder;
143
-		$this->federatedShareProvider = $federatedShareProvider;
144
-		$this->eventDispatcher = $eventDispatcher;
145
-		$this->l10n = $l10n;
146
-		$this->defaults = $defaults;
147
-	}
148
-
149
-	/**
150
-	 * @PublicPage
151
-	 * @NoCSRFRequired
152
-	 *
153
-	 * @param string $token
154
-	 * @return TemplateResponse|RedirectResponse
155
-	 */
156
-	public function showAuthenticate($token) {
157
-		$share = $this->shareManager->getShareByToken($token);
158
-
159
-		if($this->linkShareAuth($share)) {
160
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
161
-		}
162
-
163
-		return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
164
-	}
165
-
166
-	/**
167
-	 * @PublicPage
168
-	 * @UseSession
169
-	 * @BruteForceProtection(action=publicLinkAuth)
170
-	 *
171
-	 * Authenticates against password-protected shares
172
-	 * @param string $token
173
-	 * @param string $redirect
174
-	 * @param string $password
175
-	 * @return RedirectResponse|TemplateResponse|NotFoundResponse
176
-	 */
177
-	public function authenticate($token, $redirect, $password = '') {
178
-
179
-		// Check whether share exists
180
-		try {
181
-			$share = $this->shareManager->getShareByToken($token);
182
-		} catch (ShareNotFound $e) {
183
-			return new NotFoundResponse();
184
-		}
185
-
186
-		$authenticate = $this->linkShareAuth($share, $password);
187
-
188
-		// if download was requested before auth, redirect to download
189
-		if ($authenticate === true && $redirect === 'download') {
190
-			return new RedirectResponse($this->urlGenerator->linkToRoute(
191
-				'files_sharing.sharecontroller.downloadShare',
192
-				array('token' => $token))
193
-			);
194
-		} else if ($authenticate === true) {
195
-			return new RedirectResponse($this->urlGenerator->linkToRoute(
196
-				'files_sharing.sharecontroller.showShare',
197
-				array('token' => $token))
198
-			);
199
-		}
200
-
201
-		$response = new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
202
-		$response->throttle();
203
-		return $response;
204
-	}
205
-
206
-	/**
207
-	 * Authenticate a link item with the given password.
208
-	 * Or use the session if no password is provided.
209
-	 *
210
-	 * This is a modified version of Helper::authenticate
211
-	 * TODO: Try to merge back eventually with Helper::authenticate
212
-	 *
213
-	 * @param \OCP\Share\IShare $share
214
-	 * @param string|null $password
215
-	 * @return bool
216
-	 */
217
-	private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
218
-		if ($password !== null) {
219
-			if ($this->shareManager->checkPassword($share, $password)) {
220
-				$this->session->regenerateId();
221
-				$this->session->set('public_link_authenticated', (string)$share->getId());
222
-			} else {
223
-				$this->emitAccessShareHook($share, 403, 'Wrong password');
224
-				return false;
225
-			}
226
-		} else {
227
-			// not authenticated ?
228
-			if ( ! $this->session->exists('public_link_authenticated')
229
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
230
-				return false;
231
-			}
232
-		}
233
-		return true;
234
-	}
235
-
236
-	/**
237
-	 * throws hooks when a share is attempted to be accessed
238
-	 *
239
-	 * @param \OCP\Share\IShare|string $share the Share instance if available,
240
-	 * otherwise token
241
-	 * @param int $errorCode
242
-	 * @param string $errorMessage
243
-	 * @throws \OC\HintException
244
-	 * @throws \OC\ServerNotAvailableException
245
-	 */
246
-	protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
247
-		$itemType = $itemSource = $uidOwner = '';
248
-		$token = $share;
249
-		$exception = null;
250
-		if($share instanceof \OCP\Share\IShare) {
251
-			try {
252
-				$token = $share->getToken();
253
-				$uidOwner = $share->getSharedBy();
254
-				$itemType = $share->getNodeType();
255
-				$itemSource = $share->getNodeId();
256
-			} catch (\Exception $e) {
257
-				// we log what we know and pass on the exception afterwards
258
-				$exception = $e;
259
-			}
260
-		}
261
-		\OC_Hook::emit(Share::class, 'share_link_access', [
262
-			'itemType' => $itemType,
263
-			'itemSource' => $itemSource,
264
-			'uidOwner' => $uidOwner,
265
-			'token' => $token,
266
-			'errorCode' => $errorCode,
267
-			'errorMessage' => $errorMessage,
268
-		]);
269
-		if(!is_null($exception)) {
270
-			throw $exception;
271
-		}
272
-	}
273
-
274
-	/**
275
-	 * Validate the permissions of the share
276
-	 *
277
-	 * @param Share\IShare $share
278
-	 * @return bool
279
-	 */
280
-	private function validateShare(\OCP\Share\IShare $share) {
281
-		return $share->getNode()->isReadable() && $share->getNode()->isShareable();
282
-	}
283
-
284
-	/**
285
-	 * @PublicPage
286
-	 * @NoCSRFRequired
287
-	 *
288
-	 * @param string $token
289
-	 * @param string $path
290
-	 * @return TemplateResponse|RedirectResponse|NotFoundResponse
291
-	 * @throws NotFoundException
292
-	 * @throws \Exception
293
-	 */
294
-	public function showShare($token, $path = '') {
295
-		\OC_User::setIncognitoMode(true);
296
-
297
-		// Check whether share exists
298
-		try {
299
-			$share = $this->shareManager->getShareByToken($token);
300
-		} catch (ShareNotFound $e) {
301
-			$this->emitAccessShareHook($token, 404, 'Share not found');
302
-			return new NotFoundResponse();
303
-		}
304
-
305
-		// Share is password protected - check whether the user is permitted to access the share
306
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
307
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
308
-				array('token' => $token, 'redirect' => 'preview')));
309
-		}
310
-
311
-		if (!$this->validateShare($share)) {
312
-			throw new NotFoundException();
313
-		}
314
-		// We can't get the path of a file share
315
-		try {
316
-			if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
317
-				$this->emitAccessShareHook($share, 404, 'Share not found');
318
-				throw new NotFoundException();
319
-			}
320
-		} catch (\Exception $e) {
321
-			$this->emitAccessShareHook($share, 404, 'Share not found');
322
-			throw $e;
323
-		}
324
-
325
-		$shareTmpl = [];
326
-		$shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
327
-		$shareTmpl['owner'] = $share->getShareOwner();
328
-		$shareTmpl['filename'] = $share->getNode()->getName();
329
-		$shareTmpl['directory_path'] = $share->getTarget();
330
-		$shareTmpl['mimetype'] = $share->getNode()->getMimetype();
331
-		$shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
332
-		$shareTmpl['dirToken'] = $token;
333
-		$shareTmpl['sharingToken'] = $token;
334
-		$shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
335
-		$shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
336
-		$shareTmpl['dir'] = '';
337
-		$shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
338
-		$shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
339
-
340
-		// Show file list
341
-		$hideFileList = false;
342
-		if ($share->getNode() instanceof \OCP\Files\Folder) {
343
-			/** @var \OCP\Files\Folder $rootFolder */
344
-			$rootFolder = $share->getNode();
345
-
346
-			try {
347
-				$folderNode = $rootFolder->get($path);
348
-			} catch (\OCP\Files\NotFoundException $e) {
349
-				$this->emitAccessShareHook($share, 404, 'Share not found');
350
-				throw new NotFoundException();
351
-			}
352
-
353
-			$shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
354
-
355
-			/*
73
+    /** @var IConfig */
74
+    protected $config;
75
+    /** @var IURLGenerator */
76
+    protected $urlGenerator;
77
+    /** @var IUserManager */
78
+    protected $userManager;
79
+    /** @var ILogger */
80
+    protected $logger;
81
+    /** @var \OCP\Activity\IManager */
82
+    protected $activityManager;
83
+    /** @var \OCP\Share\IManager */
84
+    protected $shareManager;
85
+    /** @var ISession */
86
+    protected $session;
87
+    /** @var IPreview */
88
+    protected $previewManager;
89
+    /** @var IRootFolder */
90
+    protected $rootFolder;
91
+    /** @var FederatedShareProvider */
92
+    protected $federatedShareProvider;
93
+    /** @var EventDispatcherInterface */
94
+    protected $eventDispatcher;
95
+    /** @var IL10N */
96
+    protected $l10n;
97
+    /** @var Defaults */
98
+    protected $defaults;
99
+
100
+    /**
101
+     * @param string $appName
102
+     * @param IRequest $request
103
+     * @param IConfig $config
104
+     * @param IURLGenerator $urlGenerator
105
+     * @param IUserManager $userManager
106
+     * @param ILogger $logger
107
+     * @param \OCP\Activity\IManager $activityManager
108
+     * @param \OCP\Share\IManager $shareManager
109
+     * @param ISession $session
110
+     * @param IPreview $previewManager
111
+     * @param IRootFolder $rootFolder
112
+     * @param FederatedShareProvider $federatedShareProvider
113
+     * @param EventDispatcherInterface $eventDispatcher
114
+     * @param IL10N $l10n
115
+     * @param Defaults $defaults
116
+     */
117
+    public function __construct($appName,
118
+                                IRequest $request,
119
+                                IConfig $config,
120
+                                IURLGenerator $urlGenerator,
121
+                                IUserManager $userManager,
122
+                                ILogger $logger,
123
+                                \OCP\Activity\IManager $activityManager,
124
+                                \OCP\Share\IManager $shareManager,
125
+                                ISession $session,
126
+                                IPreview $previewManager,
127
+                                IRootFolder $rootFolder,
128
+                                FederatedShareProvider $federatedShareProvider,
129
+                                EventDispatcherInterface $eventDispatcher,
130
+                                IL10N $l10n,
131
+                                Defaults $defaults) {
132
+        parent::__construct($appName, $request);
133
+
134
+        $this->config = $config;
135
+        $this->urlGenerator = $urlGenerator;
136
+        $this->userManager = $userManager;
137
+        $this->logger = $logger;
138
+        $this->activityManager = $activityManager;
139
+        $this->shareManager = $shareManager;
140
+        $this->session = $session;
141
+        $this->previewManager = $previewManager;
142
+        $this->rootFolder = $rootFolder;
143
+        $this->federatedShareProvider = $federatedShareProvider;
144
+        $this->eventDispatcher = $eventDispatcher;
145
+        $this->l10n = $l10n;
146
+        $this->defaults = $defaults;
147
+    }
148
+
149
+    /**
150
+     * @PublicPage
151
+     * @NoCSRFRequired
152
+     *
153
+     * @param string $token
154
+     * @return TemplateResponse|RedirectResponse
155
+     */
156
+    public function showAuthenticate($token) {
157
+        $share = $this->shareManager->getShareByToken($token);
158
+
159
+        if($this->linkShareAuth($share)) {
160
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
161
+        }
162
+
163
+        return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
164
+    }
165
+
166
+    /**
167
+     * @PublicPage
168
+     * @UseSession
169
+     * @BruteForceProtection(action=publicLinkAuth)
170
+     *
171
+     * Authenticates against password-protected shares
172
+     * @param string $token
173
+     * @param string $redirect
174
+     * @param string $password
175
+     * @return RedirectResponse|TemplateResponse|NotFoundResponse
176
+     */
177
+    public function authenticate($token, $redirect, $password = '') {
178
+
179
+        // Check whether share exists
180
+        try {
181
+            $share = $this->shareManager->getShareByToken($token);
182
+        } catch (ShareNotFound $e) {
183
+            return new NotFoundResponse();
184
+        }
185
+
186
+        $authenticate = $this->linkShareAuth($share, $password);
187
+
188
+        // if download was requested before auth, redirect to download
189
+        if ($authenticate === true && $redirect === 'download') {
190
+            return new RedirectResponse($this->urlGenerator->linkToRoute(
191
+                'files_sharing.sharecontroller.downloadShare',
192
+                array('token' => $token))
193
+            );
194
+        } else if ($authenticate === true) {
195
+            return new RedirectResponse($this->urlGenerator->linkToRoute(
196
+                'files_sharing.sharecontroller.showShare',
197
+                array('token' => $token))
198
+            );
199
+        }
200
+
201
+        $response = new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
202
+        $response->throttle();
203
+        return $response;
204
+    }
205
+
206
+    /**
207
+     * Authenticate a link item with the given password.
208
+     * Or use the session if no password is provided.
209
+     *
210
+     * This is a modified version of Helper::authenticate
211
+     * TODO: Try to merge back eventually with Helper::authenticate
212
+     *
213
+     * @param \OCP\Share\IShare $share
214
+     * @param string|null $password
215
+     * @return bool
216
+     */
217
+    private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
218
+        if ($password !== null) {
219
+            if ($this->shareManager->checkPassword($share, $password)) {
220
+                $this->session->regenerateId();
221
+                $this->session->set('public_link_authenticated', (string)$share->getId());
222
+            } else {
223
+                $this->emitAccessShareHook($share, 403, 'Wrong password');
224
+                return false;
225
+            }
226
+        } else {
227
+            // not authenticated ?
228
+            if ( ! $this->session->exists('public_link_authenticated')
229
+                || $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
230
+                return false;
231
+            }
232
+        }
233
+        return true;
234
+    }
235
+
236
+    /**
237
+     * throws hooks when a share is attempted to be accessed
238
+     *
239
+     * @param \OCP\Share\IShare|string $share the Share instance if available,
240
+     * otherwise token
241
+     * @param int $errorCode
242
+     * @param string $errorMessage
243
+     * @throws \OC\HintException
244
+     * @throws \OC\ServerNotAvailableException
245
+     */
246
+    protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
247
+        $itemType = $itemSource = $uidOwner = '';
248
+        $token = $share;
249
+        $exception = null;
250
+        if($share instanceof \OCP\Share\IShare) {
251
+            try {
252
+                $token = $share->getToken();
253
+                $uidOwner = $share->getSharedBy();
254
+                $itemType = $share->getNodeType();
255
+                $itemSource = $share->getNodeId();
256
+            } catch (\Exception $e) {
257
+                // we log what we know and pass on the exception afterwards
258
+                $exception = $e;
259
+            }
260
+        }
261
+        \OC_Hook::emit(Share::class, 'share_link_access', [
262
+            'itemType' => $itemType,
263
+            'itemSource' => $itemSource,
264
+            'uidOwner' => $uidOwner,
265
+            'token' => $token,
266
+            'errorCode' => $errorCode,
267
+            'errorMessage' => $errorMessage,
268
+        ]);
269
+        if(!is_null($exception)) {
270
+            throw $exception;
271
+        }
272
+    }
273
+
274
+    /**
275
+     * Validate the permissions of the share
276
+     *
277
+     * @param Share\IShare $share
278
+     * @return bool
279
+     */
280
+    private function validateShare(\OCP\Share\IShare $share) {
281
+        return $share->getNode()->isReadable() && $share->getNode()->isShareable();
282
+    }
283
+
284
+    /**
285
+     * @PublicPage
286
+     * @NoCSRFRequired
287
+     *
288
+     * @param string $token
289
+     * @param string $path
290
+     * @return TemplateResponse|RedirectResponse|NotFoundResponse
291
+     * @throws NotFoundException
292
+     * @throws \Exception
293
+     */
294
+    public function showShare($token, $path = '') {
295
+        \OC_User::setIncognitoMode(true);
296
+
297
+        // Check whether share exists
298
+        try {
299
+            $share = $this->shareManager->getShareByToken($token);
300
+        } catch (ShareNotFound $e) {
301
+            $this->emitAccessShareHook($token, 404, 'Share not found');
302
+            return new NotFoundResponse();
303
+        }
304
+
305
+        // Share is password protected - check whether the user is permitted to access the share
306
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
307
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
308
+                array('token' => $token, 'redirect' => 'preview')));
309
+        }
310
+
311
+        if (!$this->validateShare($share)) {
312
+            throw new NotFoundException();
313
+        }
314
+        // We can't get the path of a file share
315
+        try {
316
+            if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
317
+                $this->emitAccessShareHook($share, 404, 'Share not found');
318
+                throw new NotFoundException();
319
+            }
320
+        } catch (\Exception $e) {
321
+            $this->emitAccessShareHook($share, 404, 'Share not found');
322
+            throw $e;
323
+        }
324
+
325
+        $shareTmpl = [];
326
+        $shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
327
+        $shareTmpl['owner'] = $share->getShareOwner();
328
+        $shareTmpl['filename'] = $share->getNode()->getName();
329
+        $shareTmpl['directory_path'] = $share->getTarget();
330
+        $shareTmpl['mimetype'] = $share->getNode()->getMimetype();
331
+        $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
332
+        $shareTmpl['dirToken'] = $token;
333
+        $shareTmpl['sharingToken'] = $token;
334
+        $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
335
+        $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
336
+        $shareTmpl['dir'] = '';
337
+        $shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
338
+        $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
339
+
340
+        // Show file list
341
+        $hideFileList = false;
342
+        if ($share->getNode() instanceof \OCP\Files\Folder) {
343
+            /** @var \OCP\Files\Folder $rootFolder */
344
+            $rootFolder = $share->getNode();
345
+
346
+            try {
347
+                $folderNode = $rootFolder->get($path);
348
+            } catch (\OCP\Files\NotFoundException $e) {
349
+                $this->emitAccessShareHook($share, 404, 'Share not found');
350
+                throw new NotFoundException();
351
+            }
352
+
353
+            $shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
354
+
355
+            /*
356 356
 			 * The OC_Util methods require a view. This just uses the node API
357 357
 			 */
358
-			$freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
359
-			if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
360
-				$freeSpace = max($freeSpace, 0);
361
-			} else {
362
-				$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
363
-			}
364
-
365
-			$hideFileList = !($share->getPermissions() & \OCP\Constants::PERMISSION_READ);
366
-			$maxUploadFilesize = $freeSpace;
367
-
368
-			$folder = new Template('files', 'list', '');
369
-			$folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
370
-			$folder->assign('dirToken', $token);
371
-			$folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
372
-			$folder->assign('isPublic', true);
373
-			$folder->assign('hideFileList', $hideFileList);
374
-			$folder->assign('publicUploadEnabled', 'no');
375
-			$folder->assign('uploadMaxFilesize', $maxUploadFilesize);
376
-			$folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
377
-			$folder->assign('freeSpace', $freeSpace);
378
-			$folder->assign('usedSpacePercent', 0);
379
-			$folder->assign('trash', false);
380
-			$shareTmpl['folder'] = $folder->fetchPage();
381
-		}
382
-
383
-		$shareTmpl['hideFileList'] = $hideFileList;
384
-		$shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
385
-		$shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
386
-		$shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
387
-		$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
388
-		$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
389
-		$shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
390
-		$shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
391
-		$shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
392
-		$shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
393
-		$ogPreview = '';
394
-		if ($shareTmpl['previewSupported']) {
395
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
396
-				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
397
-			$ogPreview = $shareTmpl['previewImage'];
398
-
399
-			// We just have direct previews for image files
400
-			if ($share->getNode()->getMimePart() === 'image') {
401
-				$shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $token]);
402
-
403
-				$ogPreview = $shareTmpl['previewURL'];
404
-
405
-				//Whatapp is kind of picky about their size requirements
406
-				if ($this->request->isUserAgent(['/^WhatsApp/'])) {
407
-					$ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
408
-						't' => $token,
409
-						'x' => 256,
410
-						'y' => 256,
411
-						'a' => true,
412
-					]);
413
-				}
414
-			}
415
-		} else {
416
-			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
417
-			$ogPreview = $shareTmpl['previewImage'];
418
-		}
419
-
420
-		// Load files we need
421
-		\OCP\Util::addScript('files', 'file-upload');
422
-		\OCP\Util::addStyle('files_sharing', 'publicView');
423
-		\OCP\Util::addScript('files_sharing', 'public');
424
-		\OCP\Util::addScript('files', 'fileactions');
425
-		\OCP\Util::addScript('files', 'fileactionsmenu');
426
-		\OCP\Util::addScript('files', 'jquery.fileupload');
427
-		\OCP\Util::addScript('files_sharing', 'files_drop');
428
-
429
-		if (isset($shareTmpl['folder'])) {
430
-			// JS required for folders
431
-			\OCP\Util::addStyle('files', 'merged');
432
-			\OCP\Util::addScript('files', 'filesummary');
433
-			\OCP\Util::addScript('files', 'breadcrumb');
434
-			\OCP\Util::addScript('files', 'fileinfomodel');
435
-			\OCP\Util::addScript('files', 'newfilemenu');
436
-			\OCP\Util::addScript('files', 'files');
437
-			\OCP\Util::addScript('files', 'filelist');
438
-			\OCP\Util::addScript('files', 'keyboardshortcuts');
439
-		}
440
-
441
-		// OpenGraph Support: http://ogp.me/
442
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
443
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
444
-		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
445
-		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
446
-		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
447
-		\OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
448
-
449
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
450
-
451
-		$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
452
-		$csp->addAllowedFrameDomain('\'self\'');
453
-
454
-		$response = new PublicTemplateResponse($this->appName, 'public', $shareTmpl);
455
-		$response->setHeaderTitle($shareTmpl['filename']);
456
-		$response->setHeaderDetails($this->l10n->t('shared by %s', [$shareTmpl['displayName']]));
457
-		$response->setHeaderActions([
458
-			new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download-white', $shareTmpl['downloadURL'], 0),
459
-			new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']),
460
-			new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $shareTmpl['previewURL']),
461
-			new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', $shareTmpl['owner'], $shareTmpl['displayName'], $shareTmpl['filename']),
462
-		]);
463
-
464
-		$response->setContentSecurityPolicy($csp);
465
-
466
-		$this->emitAccessShareHook($share);
467
-
468
-		return $response;
469
-	}
470
-
471
-	/**
472
-	 * @PublicPage
473
-	 * @NoCSRFRequired
474
-	 *
475
-	 * @param string $token
476
-	 * @param string $files
477
-	 * @param string $path
478
-	 * @param string $downloadStartSecret
479
-	 * @return void|\OCP\AppFramework\Http\Response
480
-	 * @throws NotFoundException
481
-	 */
482
-	public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
483
-		\OC_User::setIncognitoMode(true);
484
-
485
-		$share = $this->shareManager->getShareByToken($token);
486
-
487
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
488
-			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
489
-		}
490
-
491
-		// Share is password protected - check whether the user is permitted to access the share
492
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
493
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
494
-				['token' => $token, 'redirect' => 'download']));
495
-		}
496
-
497
-		$files_list = null;
498
-		if (!is_null($files)) { // download selected files
499
-			$files_list = json_decode($files);
500
-			// in case we get only a single file
501
-			if ($files_list === null) {
502
-				$files_list = [$files];
503
-			}
504
-			// Just in case $files is a single int like '1234'
505
-			if (!is_array($files_list)) {
506
-				$files_list = [$files_list];
507
-			}
508
-		}
509
-
510
-		$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
511
-		$originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
512
-
513
-		if (!$this->validateShare($share)) {
514
-			throw new NotFoundException();
515
-		}
516
-
517
-		// Single file share
518
-		if ($share->getNode() instanceof \OCP\Files\File) {
519
-			// Single file download
520
-			$this->singleFileDownloaded($share, $share->getNode());
521
-		}
522
-		// Directory share
523
-		else {
524
-			/** @var \OCP\Files\Folder $node */
525
-			$node = $share->getNode();
526
-
527
-			// Try to get the path
528
-			if ($path !== '') {
529
-				try {
530
-					$node = $node->get($path);
531
-				} catch (NotFoundException $e) {
532
-					$this->emitAccessShareHook($share, 404, 'Share not found');
533
-					return new NotFoundResponse();
534
-				}
535
-			}
536
-
537
-			$originalSharePath = $userFolder->getRelativePath($node->getPath());
538
-
539
-			if ($node instanceof \OCP\Files\File) {
540
-				// Single file download
541
-				$this->singleFileDownloaded($share, $share->getNode());
542
-			} else if (!empty($files_list)) {
543
-				$this->fileListDownloaded($share, $files_list, $node);
544
-			} else {
545
-				// The folder is downloaded
546
-				$this->singleFileDownloaded($share, $share->getNode());
547
-			}
548
-		}
549
-
550
-		/* FIXME: We should do this all nicely in OCP */
551
-		OC_Util::tearDownFS();
552
-		OC_Util::setupFS($share->getShareOwner());
553
-
554
-		/**
555
-		 * this sets a cookie to be able to recognize the start of the download
556
-		 * the content must not be longer than 32 characters and must only contain
557
-		 * alphanumeric characters
558
-		 */
559
-		if (!empty($downloadStartSecret)
560
-			&& !isset($downloadStartSecret[32])
561
-			&& preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
562
-
563
-			// FIXME: set on the response once we use an actual app framework response
564
-			setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
565
-		}
566
-
567
-		$this->emitAccessShareHook($share);
568
-
569
-		$server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
570
-
571
-		/**
572
-		 * Http range requests support
573
-		 */
574
-		if (isset($_SERVER['HTTP_RANGE'])) {
575
-			$server_params['range'] = $this->request->getHeader('Range');
576
-		}
577
-
578
-		// download selected files
579
-		if (!is_null($files) && $files !== '') {
580
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
581
-			// after dispatching the request which results in a "Cannot modify header information" notice.
582
-			OC_Files::get($originalSharePath, $files_list, $server_params);
583
-			exit();
584
-		} else {
585
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
586
-			// after dispatching the request which results in a "Cannot modify header information" notice.
587
-			OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
588
-			exit();
589
-		}
590
-	}
591
-
592
-	/**
593
-	 * create activity for every downloaded file
594
-	 *
595
-	 * @param Share\IShare $share
596
-	 * @param array $files_list
597
-	 * @param \OCP\Files\Folder $node
598
-	 */
599
-	protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
600
-		foreach ($files_list as $file) {
601
-			$subNode = $node->get($file);
602
-			$this->singleFileDownloaded($share, $subNode);
603
-		}
604
-
605
-	}
606
-
607
-	/**
608
-	 * create activity if a single file was downloaded from a link share
609
-	 *
610
-	 * @param Share\IShare $share
611
-	 */
612
-	protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
613
-
614
-		$fileId = $node->getId();
615
-
616
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
617
-		$userNodeList = $userFolder->getById($fileId);
618
-		$userNode = $userNodeList[0];
619
-		$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
620
-		$userPath = $userFolder->getRelativePath($userNode->getPath());
621
-		$ownerPath = $ownerFolder->getRelativePath($node->getPath());
622
-
623
-		$parameters = [$userPath];
624
-
625
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
626
-			if ($node instanceof \OCP\Files\File) {
627
-				$subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
628
-			} else {
629
-				$subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
630
-			}
631
-			$parameters[] = $share->getSharedWith();
632
-		} else {
633
-			if ($node instanceof \OCP\Files\File) {
634
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
635
-			} else {
636
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
637
-			}
638
-		}
639
-
640
-		$this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
641
-
642
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
643
-			$parameters[0] = $ownerPath;
644
-			$this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
645
-		}
646
-	}
647
-
648
-	/**
649
-	 * publish activity
650
-	 *
651
-	 * @param string $subject
652
-	 * @param array $parameters
653
-	 * @param string $affectedUser
654
-	 * @param int $fileId
655
-	 * @param string $filePath
656
-	 */
657
-	protected function publishActivity($subject,
658
-										array $parameters,
659
-										$affectedUser,
660
-										$fileId,
661
-										$filePath) {
662
-
663
-		$event = $this->activityManager->generateEvent();
664
-		$event->setApp('files_sharing')
665
-			->setType('public_links')
666
-			->setSubject($subject, $parameters)
667
-			->setAffectedUser($affectedUser)
668
-			->setObject('files', $fileId, $filePath);
669
-		$this->activityManager->publish($event);
670
-	}
358
+            $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
359
+            if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
360
+                $freeSpace = max($freeSpace, 0);
361
+            } else {
362
+                $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
363
+            }
364
+
365
+            $hideFileList = !($share->getPermissions() & \OCP\Constants::PERMISSION_READ);
366
+            $maxUploadFilesize = $freeSpace;
367
+
368
+            $folder = new Template('files', 'list', '');
369
+            $folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
370
+            $folder->assign('dirToken', $token);
371
+            $folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
372
+            $folder->assign('isPublic', true);
373
+            $folder->assign('hideFileList', $hideFileList);
374
+            $folder->assign('publicUploadEnabled', 'no');
375
+            $folder->assign('uploadMaxFilesize', $maxUploadFilesize);
376
+            $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
377
+            $folder->assign('freeSpace', $freeSpace);
378
+            $folder->assign('usedSpacePercent', 0);
379
+            $folder->assign('trash', false);
380
+            $shareTmpl['folder'] = $folder->fetchPage();
381
+        }
382
+
383
+        $shareTmpl['hideFileList'] = $hideFileList;
384
+        $shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
385
+        $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
386
+        $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
387
+        $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
388
+        $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
389
+        $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
390
+        $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
391
+        $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
392
+        $shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
393
+        $ogPreview = '';
394
+        if ($shareTmpl['previewSupported']) {
395
+            $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
396
+                ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
397
+            $ogPreview = $shareTmpl['previewImage'];
398
+
399
+            // We just have direct previews for image files
400
+            if ($share->getNode()->getMimePart() === 'image') {
401
+                $shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $token]);
402
+
403
+                $ogPreview = $shareTmpl['previewURL'];
404
+
405
+                //Whatapp is kind of picky about their size requirements
406
+                if ($this->request->isUserAgent(['/^WhatsApp/'])) {
407
+                    $ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
408
+                        't' => $token,
409
+                        'x' => 256,
410
+                        'y' => 256,
411
+                        'a' => true,
412
+                    ]);
413
+                }
414
+            }
415
+        } else {
416
+            $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
417
+            $ogPreview = $shareTmpl['previewImage'];
418
+        }
419
+
420
+        // Load files we need
421
+        \OCP\Util::addScript('files', 'file-upload');
422
+        \OCP\Util::addStyle('files_sharing', 'publicView');
423
+        \OCP\Util::addScript('files_sharing', 'public');
424
+        \OCP\Util::addScript('files', 'fileactions');
425
+        \OCP\Util::addScript('files', 'fileactionsmenu');
426
+        \OCP\Util::addScript('files', 'jquery.fileupload');
427
+        \OCP\Util::addScript('files_sharing', 'files_drop');
428
+
429
+        if (isset($shareTmpl['folder'])) {
430
+            // JS required for folders
431
+            \OCP\Util::addStyle('files', 'merged');
432
+            \OCP\Util::addScript('files', 'filesummary');
433
+            \OCP\Util::addScript('files', 'breadcrumb');
434
+            \OCP\Util::addScript('files', 'fileinfomodel');
435
+            \OCP\Util::addScript('files', 'newfilemenu');
436
+            \OCP\Util::addScript('files', 'files');
437
+            \OCP\Util::addScript('files', 'filelist');
438
+            \OCP\Util::addScript('files', 'keyboardshortcuts');
439
+        }
440
+
441
+        // OpenGraph Support: http://ogp.me/
442
+        \OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
443
+        \OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
444
+        \OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
445
+        \OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
446
+        \OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
447
+        \OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
448
+
449
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
450
+
451
+        $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
452
+        $csp->addAllowedFrameDomain('\'self\'');
453
+
454
+        $response = new PublicTemplateResponse($this->appName, 'public', $shareTmpl);
455
+        $response->setHeaderTitle($shareTmpl['filename']);
456
+        $response->setHeaderDetails($this->l10n->t('shared by %s', [$shareTmpl['displayName']]));
457
+        $response->setHeaderActions([
458
+            new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download-white', $shareTmpl['downloadURL'], 0),
459
+            new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']),
460
+            new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $shareTmpl['previewURL']),
461
+            new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', $shareTmpl['owner'], $shareTmpl['displayName'], $shareTmpl['filename']),
462
+        ]);
463
+
464
+        $response->setContentSecurityPolicy($csp);
465
+
466
+        $this->emitAccessShareHook($share);
467
+
468
+        return $response;
469
+    }
470
+
471
+    /**
472
+     * @PublicPage
473
+     * @NoCSRFRequired
474
+     *
475
+     * @param string $token
476
+     * @param string $files
477
+     * @param string $path
478
+     * @param string $downloadStartSecret
479
+     * @return void|\OCP\AppFramework\Http\Response
480
+     * @throws NotFoundException
481
+     */
482
+    public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
483
+        \OC_User::setIncognitoMode(true);
484
+
485
+        $share = $this->shareManager->getShareByToken($token);
486
+
487
+        if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
488
+            return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
489
+        }
490
+
491
+        // Share is password protected - check whether the user is permitted to access the share
492
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
493
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
494
+                ['token' => $token, 'redirect' => 'download']));
495
+        }
496
+
497
+        $files_list = null;
498
+        if (!is_null($files)) { // download selected files
499
+            $files_list = json_decode($files);
500
+            // in case we get only a single file
501
+            if ($files_list === null) {
502
+                $files_list = [$files];
503
+            }
504
+            // Just in case $files is a single int like '1234'
505
+            if (!is_array($files_list)) {
506
+                $files_list = [$files_list];
507
+            }
508
+        }
509
+
510
+        $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
511
+        $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
512
+
513
+        if (!$this->validateShare($share)) {
514
+            throw new NotFoundException();
515
+        }
516
+
517
+        // Single file share
518
+        if ($share->getNode() instanceof \OCP\Files\File) {
519
+            // Single file download
520
+            $this->singleFileDownloaded($share, $share->getNode());
521
+        }
522
+        // Directory share
523
+        else {
524
+            /** @var \OCP\Files\Folder $node */
525
+            $node = $share->getNode();
526
+
527
+            // Try to get the path
528
+            if ($path !== '') {
529
+                try {
530
+                    $node = $node->get($path);
531
+                } catch (NotFoundException $e) {
532
+                    $this->emitAccessShareHook($share, 404, 'Share not found');
533
+                    return new NotFoundResponse();
534
+                }
535
+            }
536
+
537
+            $originalSharePath = $userFolder->getRelativePath($node->getPath());
538
+
539
+            if ($node instanceof \OCP\Files\File) {
540
+                // Single file download
541
+                $this->singleFileDownloaded($share, $share->getNode());
542
+            } else if (!empty($files_list)) {
543
+                $this->fileListDownloaded($share, $files_list, $node);
544
+            } else {
545
+                // The folder is downloaded
546
+                $this->singleFileDownloaded($share, $share->getNode());
547
+            }
548
+        }
549
+
550
+        /* FIXME: We should do this all nicely in OCP */
551
+        OC_Util::tearDownFS();
552
+        OC_Util::setupFS($share->getShareOwner());
553
+
554
+        /**
555
+         * this sets a cookie to be able to recognize the start of the download
556
+         * the content must not be longer than 32 characters and must only contain
557
+         * alphanumeric characters
558
+         */
559
+        if (!empty($downloadStartSecret)
560
+            && !isset($downloadStartSecret[32])
561
+            && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
562
+
563
+            // FIXME: set on the response once we use an actual app framework response
564
+            setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
565
+        }
566
+
567
+        $this->emitAccessShareHook($share);
568
+
569
+        $server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
570
+
571
+        /**
572
+         * Http range requests support
573
+         */
574
+        if (isset($_SERVER['HTTP_RANGE'])) {
575
+            $server_params['range'] = $this->request->getHeader('Range');
576
+        }
577
+
578
+        // download selected files
579
+        if (!is_null($files) && $files !== '') {
580
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
581
+            // after dispatching the request which results in a "Cannot modify header information" notice.
582
+            OC_Files::get($originalSharePath, $files_list, $server_params);
583
+            exit();
584
+        } else {
585
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
586
+            // after dispatching the request which results in a "Cannot modify header information" notice.
587
+            OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
588
+            exit();
589
+        }
590
+    }
591
+
592
+    /**
593
+     * create activity for every downloaded file
594
+     *
595
+     * @param Share\IShare $share
596
+     * @param array $files_list
597
+     * @param \OCP\Files\Folder $node
598
+     */
599
+    protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
600
+        foreach ($files_list as $file) {
601
+            $subNode = $node->get($file);
602
+            $this->singleFileDownloaded($share, $subNode);
603
+        }
604
+
605
+    }
606
+
607
+    /**
608
+     * create activity if a single file was downloaded from a link share
609
+     *
610
+     * @param Share\IShare $share
611
+     */
612
+    protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
613
+
614
+        $fileId = $node->getId();
615
+
616
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
617
+        $userNodeList = $userFolder->getById($fileId);
618
+        $userNode = $userNodeList[0];
619
+        $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
620
+        $userPath = $userFolder->getRelativePath($userNode->getPath());
621
+        $ownerPath = $ownerFolder->getRelativePath($node->getPath());
622
+
623
+        $parameters = [$userPath];
624
+
625
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
626
+            if ($node instanceof \OCP\Files\File) {
627
+                $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
628
+            } else {
629
+                $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
630
+            }
631
+            $parameters[] = $share->getSharedWith();
632
+        } else {
633
+            if ($node instanceof \OCP\Files\File) {
634
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
635
+            } else {
636
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
637
+            }
638
+        }
639
+
640
+        $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
641
+
642
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
643
+            $parameters[0] = $ownerPath;
644
+            $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
645
+        }
646
+    }
647
+
648
+    /**
649
+     * publish activity
650
+     *
651
+     * @param string $subject
652
+     * @param array $parameters
653
+     * @param string $affectedUser
654
+     * @param int $fileId
655
+     * @param string $filePath
656
+     */
657
+    protected function publishActivity($subject,
658
+                                        array $parameters,
659
+                                        $affectedUser,
660
+                                        $fileId,
661
+                                        $filePath) {
662
+
663
+        $event = $this->activityManager->generateEvent();
664
+        $event->setApp('files_sharing')
665
+            ->setType('public_links')
666
+            ->setSubject($subject, $parameters)
667
+            ->setAffectedUser($affectedUser)
668
+            ->setObject('files', $fileId, $filePath);
669
+        $this->activityManager->publish($event);
670
+    }
671 671
 
672 672
 
673 673
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 	public function showAuthenticate($token) {
157 157
 		$share = $this->shareManager->getShareByToken($token);
158 158
 
159
-		if($this->linkShareAuth($share)) {
159
+		if ($this->linkShareAuth($share)) {
160 160
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
161 161
 		}
162 162
 
@@ -218,15 +218,15 @@  discard block
 block discarded – undo
218 218
 		if ($password !== null) {
219 219
 			if ($this->shareManager->checkPassword($share, $password)) {
220 220
 				$this->session->regenerateId();
221
-				$this->session->set('public_link_authenticated', (string)$share->getId());
221
+				$this->session->set('public_link_authenticated', (string) $share->getId());
222 222
 			} else {
223 223
 				$this->emitAccessShareHook($share, 403, 'Wrong password');
224 224
 				return false;
225 225
 			}
226 226
 		} else {
227 227
 			// not authenticated ?
228
-			if ( ! $this->session->exists('public_link_authenticated')
229
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
228
+			if (!$this->session->exists('public_link_authenticated')
229
+				|| $this->session->get('public_link_authenticated') !== (string) $share->getId()) {
230 230
 				return false;
231 231
 			}
232 232
 		}
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
 		$itemType = $itemSource = $uidOwner = '';
248 248
 		$token = $share;
249 249
 		$exception = null;
250
-		if($share instanceof \OCP\Share\IShare) {
250
+		if ($share instanceof \OCP\Share\IShare) {
251 251
 			try {
252 252
 				$token = $share->getToken();
253 253
 				$uidOwner = $share->getSharedBy();
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 			'errorCode' => $errorCode,
267 267
 			'errorMessage' => $errorMessage,
268 268
 		]);
269
-		if(!is_null($exception)) {
269
+		if (!is_null($exception)) {
270 270
 			throw $exception;
271 271
 		}
272 272
 	}
@@ -392,7 +392,7 @@  discard block
 block discarded – undo
392 392
 		$shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
393 393
 		$ogPreview = '';
394 394
 		if ($shareTmpl['previewSupported']) {
395
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
395
+			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview',
396 396
 				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
397 397
 			$ogPreview = $shareTmpl['previewImage'];
398 398
 
@@ -440,7 +440,7 @@  discard block
 block discarded – undo
440 440
 
441 441
 		// OpenGraph Support: http://ogp.me/
442 442
 		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
443
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
443
+		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName().($this->defaults->getSlogan() !== '' ? ' - '.$this->defaults->getSlogan() : '')]);
444 444
 		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
445 445
 		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
446 446
 		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
@@ -484,7 +484,7 @@  discard block
 block discarded – undo
484 484
 
485 485
 		$share = $this->shareManager->getShareByToken($token);
486 486
 
487
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
487
+		if (!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
488 488
 			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
489 489
 		}
490 490
 
@@ -566,7 +566,7 @@  discard block
 block discarded – undo
566 566
 
567 567
 		$this->emitAccessShareHook($share);
568 568
 
569
-		$server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
569
+		$server_params = array('head' => $this->request->getMethod() === 'HEAD');
570 570
 
571 571
 		/**
572 572
 		 * Http range requests support
Please login to merge, or discard this patch.
lib/private/Files/Cache/Wrapper/CacheJail.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -194,6 +194,9 @@
 block discarded – undo
194 194
 		return $this->getCache()->getStatus($this->getSourcePath($file));
195 195
 	}
196 196
 
197
+	/**
198
+	 * @param ICacheEntry[] $results
199
+	 */
197 200
 	private function formatSearchResults($results) {
198 201
 		$results = array_filter($results, array($this, 'filterCacheEntry'));
199 202
 		$results = array_values($results);
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 		if ($path === '') {
59 59
 			return $this->getRoot();
60 60
 		} else {
61
-			return $this->getRoot() . '/' . ltrim($path, '/');
61
+			return $this->getRoot().'/'.ltrim($path, '/');
62 62
 		}
63 63
 	}
64 64
 
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
 		$rootLength = strlen($this->getRoot()) + 1;
74 74
 		if ($path === $this->getRoot()) {
75 75
 			return '';
76
-		} else if (substr($path, 0, $rootLength) === $this->getRoot() . '/') {
76
+		} else if (substr($path, 0, $rootLength) === $this->getRoot().'/') {
77 77
 			return substr($path, $rootLength);
78 78
 		} else {
79 79
 			return null;
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 
94 94
 	protected function filterCacheEntry($entry) {
95 95
 		$rootLength = strlen($this->getRoot()) + 1;
96
-		return ($entry['path'] === $this->getRoot()) or (substr($entry['path'], 0, $rootLength) === $this->getRoot() . '/');
96
+		return ($entry['path'] === $this->getRoot()) or (substr($entry['path'], 0, $rootLength) === $this->getRoot().'/');
97 97
 	}
98 98
 
99 99
 	/**
Please login to merge, or discard this patch.
Indentation   +304 added lines, -304 removed lines patch added patch discarded remove patch
@@ -37,308 +37,308 @@
 block discarded – undo
37 37
  * Jail to a subdirectory of the wrapped cache
38 38
  */
39 39
 class CacheJail extends CacheWrapper {
40
-	/**
41
-	 * @var string
42
-	 */
43
-	protected $root;
44
-
45
-	/**
46
-	 * @param \OCP\Files\Cache\ICache $cache
47
-	 * @param string $root
48
-	 */
49
-	public function __construct($cache, $root) {
50
-		parent::__construct($cache);
51
-		$this->root = $root;
52
-	}
53
-
54
-	protected function getRoot() {
55
-		return $this->root;
56
-	}
57
-
58
-	protected function getSourcePath($path) {
59
-		if ($path === '') {
60
-			return $this->getRoot();
61
-		} else {
62
-			return $this->getRoot() . '/' . ltrim($path, '/');
63
-		}
64
-	}
65
-
66
-	/**
67
-	 * @param string $path
68
-	 * @return null|string the jailed path or null if the path is outside the jail
69
-	 */
70
-	protected function getJailedPath($path) {
71
-		if ($this->getRoot() === '') {
72
-			return $path;
73
-		}
74
-		$rootLength = strlen($this->getRoot()) + 1;
75
-		if ($path === $this->getRoot()) {
76
-			return '';
77
-		} else if (substr($path, 0, $rootLength) === $this->getRoot() . '/') {
78
-			return substr($path, $rootLength);
79
-		} else {
80
-			return null;
81
-		}
82
-	}
83
-
84
-	/**
85
-	 * @param ICacheEntry|array $entry
86
-	 * @return array
87
-	 */
88
-	protected function formatCacheEntry($entry) {
89
-		if (isset($entry['path'])) {
90
-			$entry['path'] = $this->getJailedPath($entry['path']);
91
-		}
92
-		return $entry;
93
-	}
94
-
95
-	protected function filterCacheEntry($entry) {
96
-		$rootLength = strlen($this->getRoot()) + 1;
97
-		return ($entry['path'] === $this->getRoot()) or (substr($entry['path'], 0, $rootLength) === $this->getRoot() . '/');
98
-	}
99
-
100
-	/**
101
-	 * get the stored metadata of a file or folder
102
-	 *
103
-	 * @param string /int $file
104
-	 * @return ICacheEntry|false
105
-	 */
106
-	public function get($file) {
107
-		if (is_string($file) or $file == '') {
108
-			$file = $this->getSourcePath($file);
109
-		}
110
-		return parent::get($file);
111
-	}
112
-
113
-	/**
114
-	 * insert meta data for a new file or folder
115
-	 *
116
-	 * @param string $file
117
-	 * @param array $data
118
-	 *
119
-	 * @return int file id
120
-	 * @throws \RuntimeException
121
-	 */
122
-	public function insert($file, array $data) {
123
-		return $this->getCache()->insert($this->getSourcePath($file), $data);
124
-	}
125
-
126
-	/**
127
-	 * update the metadata in the cache
128
-	 *
129
-	 * @param int $id
130
-	 * @param array $data
131
-	 */
132
-	public function update($id, array $data) {
133
-		$this->getCache()->update($id, $data);
134
-	}
135
-
136
-	/**
137
-	 * get the file id for a file
138
-	 *
139
-	 * @param string $file
140
-	 * @return int
141
-	 */
142
-	public function getId($file) {
143
-		return $this->getCache()->getId($this->getSourcePath($file));
144
-	}
145
-
146
-	/**
147
-	 * get the id of the parent folder of a file
148
-	 *
149
-	 * @param string $file
150
-	 * @return int
151
-	 */
152
-	public function getParentId($file) {
153
-		return $this->getCache()->getParentId($this->getSourcePath($file));
154
-	}
155
-
156
-	/**
157
-	 * check if a file is available in the cache
158
-	 *
159
-	 * @param string $file
160
-	 * @return bool
161
-	 */
162
-	public function inCache($file) {
163
-		return $this->getCache()->inCache($this->getSourcePath($file));
164
-	}
165
-
166
-	/**
167
-	 * remove a file or folder from the cache
168
-	 *
169
-	 * @param string $file
170
-	 */
171
-	public function remove($file) {
172
-		$this->getCache()->remove($this->getSourcePath($file));
173
-	}
174
-
175
-	/**
176
-	 * Move a file or folder in the cache
177
-	 *
178
-	 * @param string $source
179
-	 * @param string $target
180
-	 */
181
-	public function move($source, $target) {
182
-		$this->getCache()->move($this->getSourcePath($source), $this->getSourcePath($target));
183
-	}
184
-
185
-	/**
186
-	 * Get the storage id and path needed for a move
187
-	 *
188
-	 * @param string $path
189
-	 * @return array [$storageId, $internalPath]
190
-	 */
191
-	protected function getMoveInfo($path) {
192
-		return [$this->getNumericStorageId(), $this->getSourcePath($path)];
193
-	}
194
-
195
-	/**
196
-	 * remove all entries for files that are stored on the storage from the cache
197
-	 */
198
-	public function clear() {
199
-		$this->getCache()->remove($this->getRoot());
200
-	}
201
-
202
-	/**
203
-	 * @param string $file
204
-	 *
205
-	 * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
206
-	 */
207
-	public function getStatus($file) {
208
-		return $this->getCache()->getStatus($this->getSourcePath($file));
209
-	}
210
-
211
-	private function formatSearchResults($results) {
212
-		$results = array_filter($results, array($this, 'filterCacheEntry'));
213
-		$results = array_values($results);
214
-		return array_map(array($this, 'formatCacheEntry'), $results);
215
-	}
216
-
217
-	/**
218
-	 * search for files matching $pattern
219
-	 *
220
-	 * @param string $pattern
221
-	 * @return array an array of file data
222
-	 */
223
-	public function search($pattern) {
224
-		$results = $this->getCache()->search($pattern);
225
-		return $this->formatSearchResults($results);
226
-	}
227
-
228
-	/**
229
-	 * search for files by mimetype
230
-	 *
231
-	 * @param string $mimetype
232
-	 * @return array
233
-	 */
234
-	public function searchByMime($mimetype) {
235
-		$results = $this->getCache()->searchByMime($mimetype);
236
-		return $this->formatSearchResults($results);
237
-	}
238
-
239
-	public function searchQuery(ISearchQuery $query) {
240
-		$simpleQuery = new SearchQuery($query->getSearchOperation(), 0, 0, $query->getOrder(), $query->getUser());
241
-		$results = $this->getCache()->searchQuery($simpleQuery);
242
-		$results = $this->formatSearchResults($results);
243
-
244
-		$limit = $query->getLimit() === 0 ? NULL : $query->getLimit();
245
-		$results = array_slice($results, $query->getOffset(), $limit);
246
-
247
-		return $results;
248
-	}
249
-
250
-	/**
251
-	 * search for files by mimetype
252
-	 *
253
-	 * @param string|int $tag name or tag id
254
-	 * @param string $userId owner of the tags
255
-	 * @return array
256
-	 */
257
-	public function searchByTag($tag, $userId) {
258
-		$results = $this->getCache()->searchByTag($tag, $userId);
259
-		return $this->formatSearchResults($results);
260
-	}
261
-
262
-	/**
263
-	 * update the folder size and the size of all parent folders
264
-	 *
265
-	 * @param string|boolean $path
266
-	 * @param array $data (optional) meta data of the folder
267
-	 */
268
-	public function correctFolderSize($path, $data = null) {
269
-		if ($this->getCache() instanceof Cache) {
270
-			$this->getCache()->correctFolderSize($this->getSourcePath($path), $data);
271
-		}
272
-	}
273
-
274
-	/**
275
-	 * get the size of a folder and set it in the cache
276
-	 *
277
-	 * @param string $path
278
-	 * @param array $entry (optional) meta data of the folder
279
-	 * @return int
280
-	 */
281
-	public function calculateFolderSize($path, $entry = null) {
282
-		if ($this->getCache() instanceof Cache) {
283
-			return $this->getCache()->calculateFolderSize($this->getSourcePath($path), $entry);
284
-		} else {
285
-			return 0;
286
-		}
287
-
288
-	}
289
-
290
-	/**
291
-	 * get all file ids on the files on the storage
292
-	 *
293
-	 * @return int[]
294
-	 */
295
-	public function getAll() {
296
-		// not supported
297
-		return array();
298
-	}
299
-
300
-	/**
301
-	 * find a folder in the cache which has not been fully scanned
302
-	 *
303
-	 * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
304
-	 * use the one with the highest id gives the best result with the background scanner, since that is most
305
-	 * likely the folder where we stopped scanning previously
306
-	 *
307
-	 * @return string|bool the path of the folder or false when no folder matched
308
-	 */
309
-	public function getIncomplete() {
310
-		// not supported
311
-		return false;
312
-	}
313
-
314
-	/**
315
-	 * get the path of a file on this storage by it's id
316
-	 *
317
-	 * @param int $id
318
-	 * @return string|null
319
-	 */
320
-	public function getPathById($id) {
321
-		$path = $this->getCache()->getPathById($id);
322
-		if ($path === null) {
323
-			return null;
324
-		}
325
-
326
-		return $this->getJailedPath($path);
327
-	}
328
-
329
-	/**
330
-	 * Move a file or folder in the cache
331
-	 *
332
-	 * Note that this should make sure the entries are removed from the source cache
333
-	 *
334
-	 * @param \OCP\Files\Cache\ICache $sourceCache
335
-	 * @param string $sourcePath
336
-	 * @param string $targetPath
337
-	 */
338
-	public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
339
-		if ($sourceCache === $this) {
340
-			return $this->move($sourcePath, $targetPath);
341
-		}
342
-		return $this->getCache()->moveFromCache($sourceCache, $sourcePath, $this->getSourcePath($targetPath));
343
-	}
40
+    /**
41
+     * @var string
42
+     */
43
+    protected $root;
44
+
45
+    /**
46
+     * @param \OCP\Files\Cache\ICache $cache
47
+     * @param string $root
48
+     */
49
+    public function __construct($cache, $root) {
50
+        parent::__construct($cache);
51
+        $this->root = $root;
52
+    }
53
+
54
+    protected function getRoot() {
55
+        return $this->root;
56
+    }
57
+
58
+    protected function getSourcePath($path) {
59
+        if ($path === '') {
60
+            return $this->getRoot();
61
+        } else {
62
+            return $this->getRoot() . '/' . ltrim($path, '/');
63
+        }
64
+    }
65
+
66
+    /**
67
+     * @param string $path
68
+     * @return null|string the jailed path or null if the path is outside the jail
69
+     */
70
+    protected function getJailedPath($path) {
71
+        if ($this->getRoot() === '') {
72
+            return $path;
73
+        }
74
+        $rootLength = strlen($this->getRoot()) + 1;
75
+        if ($path === $this->getRoot()) {
76
+            return '';
77
+        } else if (substr($path, 0, $rootLength) === $this->getRoot() . '/') {
78
+            return substr($path, $rootLength);
79
+        } else {
80
+            return null;
81
+        }
82
+    }
83
+
84
+    /**
85
+     * @param ICacheEntry|array $entry
86
+     * @return array
87
+     */
88
+    protected function formatCacheEntry($entry) {
89
+        if (isset($entry['path'])) {
90
+            $entry['path'] = $this->getJailedPath($entry['path']);
91
+        }
92
+        return $entry;
93
+    }
94
+
95
+    protected function filterCacheEntry($entry) {
96
+        $rootLength = strlen($this->getRoot()) + 1;
97
+        return ($entry['path'] === $this->getRoot()) or (substr($entry['path'], 0, $rootLength) === $this->getRoot() . '/');
98
+    }
99
+
100
+    /**
101
+     * get the stored metadata of a file or folder
102
+     *
103
+     * @param string /int $file
104
+     * @return ICacheEntry|false
105
+     */
106
+    public function get($file) {
107
+        if (is_string($file) or $file == '') {
108
+            $file = $this->getSourcePath($file);
109
+        }
110
+        return parent::get($file);
111
+    }
112
+
113
+    /**
114
+     * insert meta data for a new file or folder
115
+     *
116
+     * @param string $file
117
+     * @param array $data
118
+     *
119
+     * @return int file id
120
+     * @throws \RuntimeException
121
+     */
122
+    public function insert($file, array $data) {
123
+        return $this->getCache()->insert($this->getSourcePath($file), $data);
124
+    }
125
+
126
+    /**
127
+     * update the metadata in the cache
128
+     *
129
+     * @param int $id
130
+     * @param array $data
131
+     */
132
+    public function update($id, array $data) {
133
+        $this->getCache()->update($id, $data);
134
+    }
135
+
136
+    /**
137
+     * get the file id for a file
138
+     *
139
+     * @param string $file
140
+     * @return int
141
+     */
142
+    public function getId($file) {
143
+        return $this->getCache()->getId($this->getSourcePath($file));
144
+    }
145
+
146
+    /**
147
+     * get the id of the parent folder of a file
148
+     *
149
+     * @param string $file
150
+     * @return int
151
+     */
152
+    public function getParentId($file) {
153
+        return $this->getCache()->getParentId($this->getSourcePath($file));
154
+    }
155
+
156
+    /**
157
+     * check if a file is available in the cache
158
+     *
159
+     * @param string $file
160
+     * @return bool
161
+     */
162
+    public function inCache($file) {
163
+        return $this->getCache()->inCache($this->getSourcePath($file));
164
+    }
165
+
166
+    /**
167
+     * remove a file or folder from the cache
168
+     *
169
+     * @param string $file
170
+     */
171
+    public function remove($file) {
172
+        $this->getCache()->remove($this->getSourcePath($file));
173
+    }
174
+
175
+    /**
176
+     * Move a file or folder in the cache
177
+     *
178
+     * @param string $source
179
+     * @param string $target
180
+     */
181
+    public function move($source, $target) {
182
+        $this->getCache()->move($this->getSourcePath($source), $this->getSourcePath($target));
183
+    }
184
+
185
+    /**
186
+     * Get the storage id and path needed for a move
187
+     *
188
+     * @param string $path
189
+     * @return array [$storageId, $internalPath]
190
+     */
191
+    protected function getMoveInfo($path) {
192
+        return [$this->getNumericStorageId(), $this->getSourcePath($path)];
193
+    }
194
+
195
+    /**
196
+     * remove all entries for files that are stored on the storage from the cache
197
+     */
198
+    public function clear() {
199
+        $this->getCache()->remove($this->getRoot());
200
+    }
201
+
202
+    /**
203
+     * @param string $file
204
+     *
205
+     * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
206
+     */
207
+    public function getStatus($file) {
208
+        return $this->getCache()->getStatus($this->getSourcePath($file));
209
+    }
210
+
211
+    private function formatSearchResults($results) {
212
+        $results = array_filter($results, array($this, 'filterCacheEntry'));
213
+        $results = array_values($results);
214
+        return array_map(array($this, 'formatCacheEntry'), $results);
215
+    }
216
+
217
+    /**
218
+     * search for files matching $pattern
219
+     *
220
+     * @param string $pattern
221
+     * @return array an array of file data
222
+     */
223
+    public function search($pattern) {
224
+        $results = $this->getCache()->search($pattern);
225
+        return $this->formatSearchResults($results);
226
+    }
227
+
228
+    /**
229
+     * search for files by mimetype
230
+     *
231
+     * @param string $mimetype
232
+     * @return array
233
+     */
234
+    public function searchByMime($mimetype) {
235
+        $results = $this->getCache()->searchByMime($mimetype);
236
+        return $this->formatSearchResults($results);
237
+    }
238
+
239
+    public function searchQuery(ISearchQuery $query) {
240
+        $simpleQuery = new SearchQuery($query->getSearchOperation(), 0, 0, $query->getOrder(), $query->getUser());
241
+        $results = $this->getCache()->searchQuery($simpleQuery);
242
+        $results = $this->formatSearchResults($results);
243
+
244
+        $limit = $query->getLimit() === 0 ? NULL : $query->getLimit();
245
+        $results = array_slice($results, $query->getOffset(), $limit);
246
+
247
+        return $results;
248
+    }
249
+
250
+    /**
251
+     * search for files by mimetype
252
+     *
253
+     * @param string|int $tag name or tag id
254
+     * @param string $userId owner of the tags
255
+     * @return array
256
+     */
257
+    public function searchByTag($tag, $userId) {
258
+        $results = $this->getCache()->searchByTag($tag, $userId);
259
+        return $this->formatSearchResults($results);
260
+    }
261
+
262
+    /**
263
+     * update the folder size and the size of all parent folders
264
+     *
265
+     * @param string|boolean $path
266
+     * @param array $data (optional) meta data of the folder
267
+     */
268
+    public function correctFolderSize($path, $data = null) {
269
+        if ($this->getCache() instanceof Cache) {
270
+            $this->getCache()->correctFolderSize($this->getSourcePath($path), $data);
271
+        }
272
+    }
273
+
274
+    /**
275
+     * get the size of a folder and set it in the cache
276
+     *
277
+     * @param string $path
278
+     * @param array $entry (optional) meta data of the folder
279
+     * @return int
280
+     */
281
+    public function calculateFolderSize($path, $entry = null) {
282
+        if ($this->getCache() instanceof Cache) {
283
+            return $this->getCache()->calculateFolderSize($this->getSourcePath($path), $entry);
284
+        } else {
285
+            return 0;
286
+        }
287
+
288
+    }
289
+
290
+    /**
291
+     * get all file ids on the files on the storage
292
+     *
293
+     * @return int[]
294
+     */
295
+    public function getAll() {
296
+        // not supported
297
+        return array();
298
+    }
299
+
300
+    /**
301
+     * find a folder in the cache which has not been fully scanned
302
+     *
303
+     * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
304
+     * use the one with the highest id gives the best result with the background scanner, since that is most
305
+     * likely the folder where we stopped scanning previously
306
+     *
307
+     * @return string|bool the path of the folder or false when no folder matched
308
+     */
309
+    public function getIncomplete() {
310
+        // not supported
311
+        return false;
312
+    }
313
+
314
+    /**
315
+     * get the path of a file on this storage by it's id
316
+     *
317
+     * @param int $id
318
+     * @return string|null
319
+     */
320
+    public function getPathById($id) {
321
+        $path = $this->getCache()->getPathById($id);
322
+        if ($path === null) {
323
+            return null;
324
+        }
325
+
326
+        return $this->getJailedPath($path);
327
+    }
328
+
329
+    /**
330
+     * Move a file or folder in the cache
331
+     *
332
+     * Note that this should make sure the entries are removed from the source cache
333
+     *
334
+     * @param \OCP\Files\Cache\ICache $sourceCache
335
+     * @param string $sourcePath
336
+     * @param string $targetPath
337
+     */
338
+    public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
339
+        if ($sourceCache === $this) {
340
+            return $this->move($sourcePath, $targetPath);
341
+        }
342
+        return $this->getCache()->moveFromCache($sourceCache, $sourcePath, $this->getSourcePath($targetPath));
343
+    }
344 344
 }
Please login to merge, or discard this patch.
lib/private/Group/Manager.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -156,7 +156,7 @@
 block discarded – undo
156 156
 	/**
157 157
 	 * @param string $gid
158 158
 	 * @param string $displayName
159
-	 * @return \OCP\IGroup
159
+	 * @return null|Group
160 160
 	 */
161 161
 	protected function getGroupObject($gid, $displayName = null) {
162 162
 		$backends = array();
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -93,20 +93,20 @@  discard block
 block discarded – undo
93 93
 		$this->logger = $logger;
94 94
 		$cachedGroups = & $this->cachedGroups;
95 95
 		$cachedUserGroups = & $this->cachedUserGroups;
96
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
96
+		$this->listen('\OC\Group', 'postDelete', function($group) use (&$cachedGroups, &$cachedUserGroups) {
97 97
 			/**
98 98
 			 * @var \OC\Group\Group $group
99 99
 			 */
100 100
 			unset($cachedGroups[$group->getGID()]);
101 101
 			$cachedUserGroups = array();
102 102
 		});
103
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
103
+		$this->listen('\OC\Group', 'postAddUser', function($group) use (&$cachedUserGroups) {
104 104
 			/**
105 105
 			 * @var \OC\Group\Group $group
106 106
 			 */
107 107
 			$cachedUserGroups = array();
108 108
 		});
109
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
109
+		$this->listen('\OC\Group', 'postRemoveUser', function($group) use (&$cachedUserGroups) {
110 110
 			/**
111 111
 			 * @var \OC\Group\Group $group
112 112
 			 */
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
 				if ($aGroup instanceof IGroup) {
236 236
 					$groups[$groupId] = $aGroup;
237 237
 				} else {
238
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
238
+					$this->logger->debug('Group "'.$groupId.'" was returned by search but not found through direct access', ['app' => 'core']);
239 239
 				}
240 240
 			}
241 241
 			if (!is_null($limit) and $limit <= 0) {
@@ -249,7 +249,7 @@  discard block
 block discarded – undo
249 249
 	 * @param IUser|null $user
250 250
 	 * @return \OC\Group\Group[]
251 251
 	 */
252
-	public function getUserGroups(IUser $user= null) {
252
+	public function getUserGroups(IUser $user = null) {
253 253
 		if (!$user instanceof IUser) {
254 254
 			return [];
255 255
 		}
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
 					if ($aGroup instanceof IGroup) {
274 274
 						$groups[$groupId] = $aGroup;
275 275
 					} else {
276
-						$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
276
+						$this->logger->debug('User "'.$uid.'" belongs to deleted group: "'.$groupId.'"', ['app' => 'core']);
277 277
 					}
278 278
 				}
279 279
 			}
@@ -322,32 +322,32 @@  discard block
 block discarded – undo
322 322
 	 */
323 323
 	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
324 324
 		$group = $this->get($gid);
325
-		if(is_null($group)) {
325
+		if (is_null($group)) {
326 326
 			return array();
327 327
 		}
328 328
 
329 329
 		$search = trim($search);
330 330
 		$groupUsers = array();
331 331
 
332
-		if(!empty($search)) {
332
+		if (!empty($search)) {
333 333
 			// only user backends have the capability to do a complex search for users
334 334
 			$searchOffset = 0;
335 335
 			$searchLimit = $limit * 100;
336
-			if($limit === -1) {
336
+			if ($limit === -1) {
337 337
 				$searchLimit = 500;
338 338
 			}
339 339
 
340 340
 			do {
341 341
 				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
342
-				foreach($filteredUsers as $filteredUser) {
343
-					if($group->inGroup($filteredUser)) {
344
-						$groupUsers[]= $filteredUser;
342
+				foreach ($filteredUsers as $filteredUser) {
343
+					if ($group->inGroup($filteredUser)) {
344
+						$groupUsers[] = $filteredUser;
345 345
 					}
346 346
 				}
347 347
 				$searchOffset += $searchLimit;
348
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
348
+			} while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
349 349
 
350
-			if($limit === -1) {
350
+			if ($limit === -1) {
351 351
 				$groupUsers = array_slice($groupUsers, $offset);
352 352
 			} else {
353 353
 				$groupUsers = array_slice($groupUsers, $offset, $limit);
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 		}
358 358
 
359 359
 		$matchingUsers = array();
360
-		foreach($groupUsers as $groupUser) {
360
+		foreach ($groupUsers as $groupUser) {
361 361
 			$matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
362 362
 		}
363 363
 		return $matchingUsers;
Please login to merge, or discard this patch.
Indentation   +344 added lines, -344 removed lines patch added patch discarded remove patch
@@ -61,348 +61,348 @@
 block discarded – undo
61 61
  * @package OC\Group
62 62
  */
63 63
 class Manager extends PublicEmitter implements IGroupManager {
64
-	/**
65
-	 * @var GroupInterface[] $backends
66
-	 */
67
-	private $backends = array();
68
-
69
-	/**
70
-	 * @var \OC\User\Manager $userManager
71
-	 */
72
-	private $userManager;
73
-
74
-	/**
75
-	 * @var \OC\Group\Group[]
76
-	 */
77
-	private $cachedGroups = array();
78
-
79
-	/**
80
-	 * @var \OC\Group\Group[]
81
-	 */
82
-	private $cachedUserGroups = array();
83
-
84
-	/** @var \OC\SubAdmin */
85
-	private $subAdmin = null;
86
-
87
-	/** @var ILogger */
88
-	private $logger;
89
-
90
-	/**
91
-	 * @param \OC\User\Manager $userManager
92
-	 * @param ILogger $logger
93
-	 */
94
-	public function __construct(\OC\User\Manager $userManager, ILogger $logger) {
95
-		$this->userManager = $userManager;
96
-		$this->logger = $logger;
97
-		$cachedGroups = & $this->cachedGroups;
98
-		$cachedUserGroups = & $this->cachedUserGroups;
99
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
100
-			/**
101
-			 * @var \OC\Group\Group $group
102
-			 */
103
-			unset($cachedGroups[$group->getGID()]);
104
-			$cachedUserGroups = array();
105
-		});
106
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
107
-			/**
108
-			 * @var \OC\Group\Group $group
109
-			 */
110
-			$cachedUserGroups = array();
111
-		});
112
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
113
-			/**
114
-			 * @var \OC\Group\Group $group
115
-			 */
116
-			$cachedUserGroups = array();
117
-		});
118
-	}
119
-
120
-	/**
121
-	 * Checks whether a given backend is used
122
-	 *
123
-	 * @param string $backendClass Full classname including complete namespace
124
-	 * @return bool
125
-	 */
126
-	public function isBackendUsed($backendClass) {
127
-		$backendClass = strtolower(ltrim($backendClass, '\\'));
128
-
129
-		foreach ($this->backends as $backend) {
130
-			if (strtolower(get_class($backend)) === $backendClass) {
131
-				return true;
132
-			}
133
-		}
134
-
135
-		return false;
136
-	}
137
-
138
-	/**
139
-	 * @param \OCP\GroupInterface $backend
140
-	 */
141
-	public function addBackend($backend) {
142
-		$this->backends[] = $backend;
143
-		$this->clearCaches();
144
-	}
145
-
146
-	public function clearBackends() {
147
-		$this->backends = array();
148
-		$this->clearCaches();
149
-	}
150
-
151
-	/**
152
-	 * Get the active backends
153
-	 * @return \OCP\GroupInterface[]
154
-	 */
155
-	public function getBackends() {
156
-		return $this->backends;
157
-	}
158
-
159
-
160
-	protected function clearCaches() {
161
-		$this->cachedGroups = array();
162
-		$this->cachedUserGroups = array();
163
-	}
164
-
165
-	/**
166
-	 * @param string $gid
167
-	 * @return \OC\Group\Group
168
-	 */
169
-	public function get($gid) {
170
-		if (isset($this->cachedGroups[$gid])) {
171
-			return $this->cachedGroups[$gid];
172
-		}
173
-		return $this->getGroupObject($gid);
174
-	}
175
-
176
-	/**
177
-	 * @param string $gid
178
-	 * @param string $displayName
179
-	 * @return \OCP\IGroup
180
-	 */
181
-	protected function getGroupObject($gid, $displayName = null) {
182
-		$backends = array();
183
-		foreach ($this->backends as $backend) {
184
-			if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
185
-				$groupData = $backend->getGroupDetails($gid);
186
-				if (is_array($groupData)) {
187
-					// take the display name from the first backend that has a non-null one
188
-					if (is_null($displayName) && isset($groupData['displayName'])) {
189
-						$displayName = $groupData['displayName'];
190
-					}
191
-					$backends[] = $backend;
192
-				}
193
-			} else if ($backend->groupExists($gid)) {
194
-				$backends[] = $backend;
195
-			}
196
-		}
197
-		if (count($backends) === 0) {
198
-			return null;
199
-		}
200
-		$this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
201
-		return $this->cachedGroups[$gid];
202
-	}
203
-
204
-	/**
205
-	 * @param string $gid
206
-	 * @return bool
207
-	 */
208
-	public function groupExists($gid) {
209
-		return $this->get($gid) instanceof IGroup;
210
-	}
211
-
212
-	/**
213
-	 * @param string $gid
214
-	 * @return \OC\Group\Group
215
-	 */
216
-	public function createGroup($gid) {
217
-		if ($gid === '' || $gid === null) {
218
-			return false;
219
-		} else if ($group = $this->get($gid)) {
220
-			return $group;
221
-		} else {
222
-			$this->emit('\OC\Group', 'preCreate', array($gid));
223
-			foreach ($this->backends as $backend) {
224
-				if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
225
-					$backend->createGroup($gid);
226
-					$group = $this->getGroupObject($gid);
227
-					$this->emit('\OC\Group', 'postCreate', array($group));
228
-					return $group;
229
-				}
230
-			}
231
-			return null;
232
-		}
233
-	}
234
-
235
-	/**
236
-	 * @param string $search
237
-	 * @param int $limit
238
-	 * @param int $offset
239
-	 * @return \OC\Group\Group[]
240
-	 */
241
-	public function search($search, $limit = null, $offset = null) {
242
-		$groups = array();
243
-		foreach ($this->backends as $backend) {
244
-			$groupIds = $backend->getGroups($search, $limit, $offset);
245
-			foreach ($groupIds as $groupId) {
246
-				$aGroup = $this->get($groupId);
247
-				if ($aGroup instanceof IGroup) {
248
-					$groups[$groupId] = $aGroup;
249
-				} else {
250
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
251
-				}
252
-			}
253
-			if (!is_null($limit) and $limit <= 0) {
254
-				return array_values($groups);
255
-			}
256
-		}
257
-		return array_values($groups);
258
-	}
259
-
260
-	/**
261
-	 * @param IUser|null $user
262
-	 * @return \OC\Group\Group[]
263
-	 */
264
-	public function getUserGroups(IUser $user= null) {
265
-		if (!$user instanceof IUser) {
266
-			return [];
267
-		}
268
-		return $this->getUserIdGroups($user->getUID());
269
-	}
270
-
271
-	/**
272
-	 * @param string $uid the user id
273
-	 * @return \OC\Group\Group[]
274
-	 */
275
-	public function getUserIdGroups($uid) {
276
-		if (isset($this->cachedUserGroups[$uid])) {
277
-			return $this->cachedUserGroups[$uid];
278
-		}
279
-		$groups = array();
280
-		foreach ($this->backends as $backend) {
281
-			$groupIds = $backend->getUserGroups($uid);
282
-			if (is_array($groupIds)) {
283
-				foreach ($groupIds as $groupId) {
284
-					$aGroup = $this->get($groupId);
285
-					if ($aGroup instanceof IGroup) {
286
-						$groups[$groupId] = $aGroup;
287
-					} else {
288
-						$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
289
-					}
290
-				}
291
-			}
292
-		}
293
-		$this->cachedUserGroups[$uid] = $groups;
294
-		return $this->cachedUserGroups[$uid];
295
-	}
296
-
297
-	/**
298
-	 * Checks if a userId is in the admin group
299
-	 * @param string $userId
300
-	 * @return bool if admin
301
-	 */
302
-	public function isAdmin($userId) {
303
-		foreach ($this->backends as $backend) {
304
-			if ($backend->implementsActions(\OC\Group\Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
305
-				return true;
306
-			}
307
-		}
308
-		return $this->isInGroup($userId, 'admin');
309
-	}
310
-
311
-	/**
312
-	 * Checks if a userId is in a group
313
-	 * @param string $userId
314
-	 * @param string $group
315
-	 * @return bool if in group
316
-	 */
317
-	public function isInGroup($userId, $group) {
318
-		return array_key_exists($group, $this->getUserIdGroups($userId));
319
-	}
320
-
321
-	/**
322
-	 * get a list of group ids for a user
323
-	 * @param IUser $user
324
-	 * @return array with group ids
325
-	 */
326
-	public function getUserGroupIds(IUser $user) {
327
-		return array_map(function($value) {
328
-			return (string) $value;
329
-		}, array_keys($this->getUserGroups($user)));
330
-	}
331
-
332
-	/**
333
-	 * get an array of groupid and displayName for a user
334
-	 * @param IUser $user
335
-	 * @return array ['displayName' => displayname]
336
-	 */
337
-	public function getUserGroupNames(IUser $user) {
338
-		return array_map(function($group) {
339
-			return array('displayName' => $group->getDisplayName());
340
-		}, $this->getUserGroups($user));
341
-	}
342
-
343
-	/**
344
-	 * get a list of all display names in a group
345
-	 * @param string $gid
346
-	 * @param string $search
347
-	 * @param int $limit
348
-	 * @param int $offset
349
-	 * @return array an array of display names (value) and user ids (key)
350
-	 */
351
-	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
352
-		$group = $this->get($gid);
353
-		if(is_null($group)) {
354
-			return array();
355
-		}
356
-
357
-		$search = trim($search);
358
-		$groupUsers = array();
359
-
360
-		if(!empty($search)) {
361
-			// only user backends have the capability to do a complex search for users
362
-			$searchOffset = 0;
363
-			$searchLimit = $limit * 100;
364
-			if($limit === -1) {
365
-				$searchLimit = 500;
366
-			}
367
-
368
-			do {
369
-				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
370
-				foreach($filteredUsers as $filteredUser) {
371
-					if($group->inGroup($filteredUser)) {
372
-						$groupUsers[]= $filteredUser;
373
-					}
374
-				}
375
-				$searchOffset += $searchLimit;
376
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
377
-
378
-			if($limit === -1) {
379
-				$groupUsers = array_slice($groupUsers, $offset);
380
-			} else {
381
-				$groupUsers = array_slice($groupUsers, $offset, $limit);
382
-			}
383
-		} else {
384
-			$groupUsers = $group->searchUsers('', $limit, $offset);
385
-		}
386
-
387
-		$matchingUsers = array();
388
-		foreach($groupUsers as $groupUser) {
389
-			$matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
390
-		}
391
-		return $matchingUsers;
392
-	}
393
-
394
-	/**
395
-	 * @return \OC\SubAdmin
396
-	 */
397
-	public function getSubAdmin() {
398
-		if (!$this->subAdmin) {
399
-			$this->subAdmin = new \OC\SubAdmin(
400
-				$this->userManager,
401
-				$this,
402
-				\OC::$server->getDatabaseConnection()
403
-			);
404
-		}
405
-
406
-		return $this->subAdmin;
407
-	}
64
+    /**
65
+     * @var GroupInterface[] $backends
66
+     */
67
+    private $backends = array();
68
+
69
+    /**
70
+     * @var \OC\User\Manager $userManager
71
+     */
72
+    private $userManager;
73
+
74
+    /**
75
+     * @var \OC\Group\Group[]
76
+     */
77
+    private $cachedGroups = array();
78
+
79
+    /**
80
+     * @var \OC\Group\Group[]
81
+     */
82
+    private $cachedUserGroups = array();
83
+
84
+    /** @var \OC\SubAdmin */
85
+    private $subAdmin = null;
86
+
87
+    /** @var ILogger */
88
+    private $logger;
89
+
90
+    /**
91
+     * @param \OC\User\Manager $userManager
92
+     * @param ILogger $logger
93
+     */
94
+    public function __construct(\OC\User\Manager $userManager, ILogger $logger) {
95
+        $this->userManager = $userManager;
96
+        $this->logger = $logger;
97
+        $cachedGroups = & $this->cachedGroups;
98
+        $cachedUserGroups = & $this->cachedUserGroups;
99
+        $this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
100
+            /**
101
+             * @var \OC\Group\Group $group
102
+             */
103
+            unset($cachedGroups[$group->getGID()]);
104
+            $cachedUserGroups = array();
105
+        });
106
+        $this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
107
+            /**
108
+             * @var \OC\Group\Group $group
109
+             */
110
+            $cachedUserGroups = array();
111
+        });
112
+        $this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
113
+            /**
114
+             * @var \OC\Group\Group $group
115
+             */
116
+            $cachedUserGroups = array();
117
+        });
118
+    }
119
+
120
+    /**
121
+     * Checks whether a given backend is used
122
+     *
123
+     * @param string $backendClass Full classname including complete namespace
124
+     * @return bool
125
+     */
126
+    public function isBackendUsed($backendClass) {
127
+        $backendClass = strtolower(ltrim($backendClass, '\\'));
128
+
129
+        foreach ($this->backends as $backend) {
130
+            if (strtolower(get_class($backend)) === $backendClass) {
131
+                return true;
132
+            }
133
+        }
134
+
135
+        return false;
136
+    }
137
+
138
+    /**
139
+     * @param \OCP\GroupInterface $backend
140
+     */
141
+    public function addBackend($backend) {
142
+        $this->backends[] = $backend;
143
+        $this->clearCaches();
144
+    }
145
+
146
+    public function clearBackends() {
147
+        $this->backends = array();
148
+        $this->clearCaches();
149
+    }
150
+
151
+    /**
152
+     * Get the active backends
153
+     * @return \OCP\GroupInterface[]
154
+     */
155
+    public function getBackends() {
156
+        return $this->backends;
157
+    }
158
+
159
+
160
+    protected function clearCaches() {
161
+        $this->cachedGroups = array();
162
+        $this->cachedUserGroups = array();
163
+    }
164
+
165
+    /**
166
+     * @param string $gid
167
+     * @return \OC\Group\Group
168
+     */
169
+    public function get($gid) {
170
+        if (isset($this->cachedGroups[$gid])) {
171
+            return $this->cachedGroups[$gid];
172
+        }
173
+        return $this->getGroupObject($gid);
174
+    }
175
+
176
+    /**
177
+     * @param string $gid
178
+     * @param string $displayName
179
+     * @return \OCP\IGroup
180
+     */
181
+    protected function getGroupObject($gid, $displayName = null) {
182
+        $backends = array();
183
+        foreach ($this->backends as $backend) {
184
+            if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
185
+                $groupData = $backend->getGroupDetails($gid);
186
+                if (is_array($groupData)) {
187
+                    // take the display name from the first backend that has a non-null one
188
+                    if (is_null($displayName) && isset($groupData['displayName'])) {
189
+                        $displayName = $groupData['displayName'];
190
+                    }
191
+                    $backends[] = $backend;
192
+                }
193
+            } else if ($backend->groupExists($gid)) {
194
+                $backends[] = $backend;
195
+            }
196
+        }
197
+        if (count($backends) === 0) {
198
+            return null;
199
+        }
200
+        $this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
201
+        return $this->cachedGroups[$gid];
202
+    }
203
+
204
+    /**
205
+     * @param string $gid
206
+     * @return bool
207
+     */
208
+    public function groupExists($gid) {
209
+        return $this->get($gid) instanceof IGroup;
210
+    }
211
+
212
+    /**
213
+     * @param string $gid
214
+     * @return \OC\Group\Group
215
+     */
216
+    public function createGroup($gid) {
217
+        if ($gid === '' || $gid === null) {
218
+            return false;
219
+        } else if ($group = $this->get($gid)) {
220
+            return $group;
221
+        } else {
222
+            $this->emit('\OC\Group', 'preCreate', array($gid));
223
+            foreach ($this->backends as $backend) {
224
+                if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
225
+                    $backend->createGroup($gid);
226
+                    $group = $this->getGroupObject($gid);
227
+                    $this->emit('\OC\Group', 'postCreate', array($group));
228
+                    return $group;
229
+                }
230
+            }
231
+            return null;
232
+        }
233
+    }
234
+
235
+    /**
236
+     * @param string $search
237
+     * @param int $limit
238
+     * @param int $offset
239
+     * @return \OC\Group\Group[]
240
+     */
241
+    public function search($search, $limit = null, $offset = null) {
242
+        $groups = array();
243
+        foreach ($this->backends as $backend) {
244
+            $groupIds = $backend->getGroups($search, $limit, $offset);
245
+            foreach ($groupIds as $groupId) {
246
+                $aGroup = $this->get($groupId);
247
+                if ($aGroup instanceof IGroup) {
248
+                    $groups[$groupId] = $aGroup;
249
+                } else {
250
+                    $this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
251
+                }
252
+            }
253
+            if (!is_null($limit) and $limit <= 0) {
254
+                return array_values($groups);
255
+            }
256
+        }
257
+        return array_values($groups);
258
+    }
259
+
260
+    /**
261
+     * @param IUser|null $user
262
+     * @return \OC\Group\Group[]
263
+     */
264
+    public function getUserGroups(IUser $user= null) {
265
+        if (!$user instanceof IUser) {
266
+            return [];
267
+        }
268
+        return $this->getUserIdGroups($user->getUID());
269
+    }
270
+
271
+    /**
272
+     * @param string $uid the user id
273
+     * @return \OC\Group\Group[]
274
+     */
275
+    public function getUserIdGroups($uid) {
276
+        if (isset($this->cachedUserGroups[$uid])) {
277
+            return $this->cachedUserGroups[$uid];
278
+        }
279
+        $groups = array();
280
+        foreach ($this->backends as $backend) {
281
+            $groupIds = $backend->getUserGroups($uid);
282
+            if (is_array($groupIds)) {
283
+                foreach ($groupIds as $groupId) {
284
+                    $aGroup = $this->get($groupId);
285
+                    if ($aGroup instanceof IGroup) {
286
+                        $groups[$groupId] = $aGroup;
287
+                    } else {
288
+                        $this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
289
+                    }
290
+                }
291
+            }
292
+        }
293
+        $this->cachedUserGroups[$uid] = $groups;
294
+        return $this->cachedUserGroups[$uid];
295
+    }
296
+
297
+    /**
298
+     * Checks if a userId is in the admin group
299
+     * @param string $userId
300
+     * @return bool if admin
301
+     */
302
+    public function isAdmin($userId) {
303
+        foreach ($this->backends as $backend) {
304
+            if ($backend->implementsActions(\OC\Group\Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
305
+                return true;
306
+            }
307
+        }
308
+        return $this->isInGroup($userId, 'admin');
309
+    }
310
+
311
+    /**
312
+     * Checks if a userId is in a group
313
+     * @param string $userId
314
+     * @param string $group
315
+     * @return bool if in group
316
+     */
317
+    public function isInGroup($userId, $group) {
318
+        return array_key_exists($group, $this->getUserIdGroups($userId));
319
+    }
320
+
321
+    /**
322
+     * get a list of group ids for a user
323
+     * @param IUser $user
324
+     * @return array with group ids
325
+     */
326
+    public function getUserGroupIds(IUser $user) {
327
+        return array_map(function($value) {
328
+            return (string) $value;
329
+        }, array_keys($this->getUserGroups($user)));
330
+    }
331
+
332
+    /**
333
+     * get an array of groupid and displayName for a user
334
+     * @param IUser $user
335
+     * @return array ['displayName' => displayname]
336
+     */
337
+    public function getUserGroupNames(IUser $user) {
338
+        return array_map(function($group) {
339
+            return array('displayName' => $group->getDisplayName());
340
+        }, $this->getUserGroups($user));
341
+    }
342
+
343
+    /**
344
+     * get a list of all display names in a group
345
+     * @param string $gid
346
+     * @param string $search
347
+     * @param int $limit
348
+     * @param int $offset
349
+     * @return array an array of display names (value) and user ids (key)
350
+     */
351
+    public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
352
+        $group = $this->get($gid);
353
+        if(is_null($group)) {
354
+            return array();
355
+        }
356
+
357
+        $search = trim($search);
358
+        $groupUsers = array();
359
+
360
+        if(!empty($search)) {
361
+            // only user backends have the capability to do a complex search for users
362
+            $searchOffset = 0;
363
+            $searchLimit = $limit * 100;
364
+            if($limit === -1) {
365
+                $searchLimit = 500;
366
+            }
367
+
368
+            do {
369
+                $filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
370
+                foreach($filteredUsers as $filteredUser) {
371
+                    if($group->inGroup($filteredUser)) {
372
+                        $groupUsers[]= $filteredUser;
373
+                    }
374
+                }
375
+                $searchOffset += $searchLimit;
376
+            } while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
377
+
378
+            if($limit === -1) {
379
+                $groupUsers = array_slice($groupUsers, $offset);
380
+            } else {
381
+                $groupUsers = array_slice($groupUsers, $offset, $limit);
382
+            }
383
+        } else {
384
+            $groupUsers = $group->searchUsers('', $limit, $offset);
385
+        }
386
+
387
+        $matchingUsers = array();
388
+        foreach($groupUsers as $groupUser) {
389
+            $matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
390
+        }
391
+        return $matchingUsers;
392
+    }
393
+
394
+    /**
395
+     * @return \OC\SubAdmin
396
+     */
397
+    public function getSubAdmin() {
398
+        if (!$this->subAdmin) {
399
+            $this->subAdmin = new \OC\SubAdmin(
400
+                $this->userManager,
401
+                $this,
402
+                \OC::$server->getDatabaseConnection()
403
+            );
404
+        }
405
+
406
+        return $this->subAdmin;
407
+    }
408 408
 }
Please login to merge, or discard this patch.
lib/private/Memcache/APCu.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@
 block discarded – undo
65 65
 	 * Set a value in the cache if it's not already stored
66 66
 	 *
67 67
 	 * @param string $key
68
-	 * @param mixed $value
68
+	 * @param integer $value
69 69
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
70 70
 	 * @return bool
71 71
 	 */
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
 	use CADTrait;
38 38
 
39 39
 	public function get($key) {
40
-		$result = apcu_fetch($this->getPrefix() . $key, $success);
40
+		$result = apcu_fetch($this->getPrefix().$key, $success);
41 41
 		if (!$success) {
42 42
 			return null;
43 43
 		}
@@ -45,24 +45,24 @@  discard block
 block discarded – undo
45 45
 	}
46 46
 
47 47
 	public function set($key, $value, $ttl = 0) {
48
-		return apcu_store($this->getPrefix() . $key, $value, $ttl);
48
+		return apcu_store($this->getPrefix().$key, $value, $ttl);
49 49
 	}
50 50
 
51 51
 	public function hasKey($key) {
52
-		return apcu_exists($this->getPrefix() . $key);
52
+		return apcu_exists($this->getPrefix().$key);
53 53
 	}
54 54
 
55 55
 	public function remove($key) {
56
-		return apcu_delete($this->getPrefix() . $key);
56
+		return apcu_delete($this->getPrefix().$key);
57 57
 	}
58 58
 
59 59
 	public function clear($prefix = '') {
60
-		$ns = $this->getPrefix() . $prefix;
60
+		$ns = $this->getPrefix().$prefix;
61 61
 		$ns = preg_quote($ns, '/');
62
-		if(class_exists('\APCIterator')) {
63
-			$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
62
+		if (class_exists('\APCIterator')) {
63
+			$iter = new \APCIterator('user', '/^'.$ns.'/', APC_ITER_KEY);
64 64
 		} else {
65
-			$iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
65
+			$iter = new \APCUIterator('/^'.$ns.'/', APC_ITER_KEY);
66 66
 		}
67 67
 		return apcu_delete($iter);
68 68
 	}
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	 * @return bool
77 77
 	 */
78 78
 	public function add($key, $value, $ttl = 0) {
79
-		return apcu_add($this->getPrefix() . $key, $value, $ttl);
79
+		return apcu_add($this->getPrefix().$key, $value, $ttl);
80 80
 	}
81 81
 
82 82
 	/**
@@ -100,8 +100,8 @@  discard block
 block discarded – undo
100 100
 		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101 101
 		 * for details
102 102
 		 */
103
-		return apcu_exists($this->getPrefix() . $key)
104
-			? apcu_inc($this->getPrefix() . $key, $step)
103
+		return apcu_exists($this->getPrefix().$key)
104
+			? apcu_inc($this->getPrefix().$key, $step)
105 105
 			: false;
106 106
 	}
107 107
 
@@ -125,8 +125,8 @@  discard block
 block discarded – undo
125 125
 		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126 126
 		 * for details
127 127
 		 */
128
-		return apcu_exists($this->getPrefix() . $key)
129
-			? apcu_dec($this->getPrefix() . $key, $step)
128
+		return apcu_exists($this->getPrefix().$key)
129
+			? apcu_dec($this->getPrefix().$key, $step)
130 130
 			: false;
131 131
 	}
132 132
 
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 	public function cas($key, $old, $new) {
142 142
 		// apc only does cas for ints
143 143
 		if (is_int($old) and is_int($new)) {
144
-			return apcu_cas($this->getPrefix() . $key, $old, $new);
144
+			return apcu_cas($this->getPrefix().$key, $old, $new);
145 145
 		} else {
146 146
 			return $this->casEmulated($key, $old, $new);
147 147
 		}
Please login to merge, or discard this patch.
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -30,140 +30,140 @@
 block discarded – undo
30 30
 use OCP\IMemcache;
31 31
 
32 32
 class APCu extends Cache implements IMemcache {
33
-	use CASTrait {
34
-		cas as casEmulated;
35
-	}
33
+    use CASTrait {
34
+        cas as casEmulated;
35
+    }
36 36
 
37
-	use CADTrait;
37
+    use CADTrait;
38 38
 
39
-	public function get($key) {
40
-		$result = apcu_fetch($this->getPrefix() . $key, $success);
41
-		if (!$success) {
42
-			return null;
43
-		}
44
-		return $result;
45
-	}
39
+    public function get($key) {
40
+        $result = apcu_fetch($this->getPrefix() . $key, $success);
41
+        if (!$success) {
42
+            return null;
43
+        }
44
+        return $result;
45
+    }
46 46
 
47
-	public function set($key, $value, $ttl = 0) {
48
-		return apcu_store($this->getPrefix() . $key, $value, $ttl);
49
-	}
47
+    public function set($key, $value, $ttl = 0) {
48
+        return apcu_store($this->getPrefix() . $key, $value, $ttl);
49
+    }
50 50
 
51
-	public function hasKey($key) {
52
-		return apcu_exists($this->getPrefix() . $key);
53
-	}
51
+    public function hasKey($key) {
52
+        return apcu_exists($this->getPrefix() . $key);
53
+    }
54 54
 
55
-	public function remove($key) {
56
-		return apcu_delete($this->getPrefix() . $key);
57
-	}
55
+    public function remove($key) {
56
+        return apcu_delete($this->getPrefix() . $key);
57
+    }
58 58
 
59
-	public function clear($prefix = '') {
60
-		$ns = $this->getPrefix() . $prefix;
61
-		$ns = preg_quote($ns, '/');
62
-		if(class_exists('\APCIterator')) {
63
-			$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
64
-		} else {
65
-			$iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
66
-		}
67
-		return apcu_delete($iter);
68
-	}
59
+    public function clear($prefix = '') {
60
+        $ns = $this->getPrefix() . $prefix;
61
+        $ns = preg_quote($ns, '/');
62
+        if(class_exists('\APCIterator')) {
63
+            $iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
64
+        } else {
65
+            $iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
66
+        }
67
+        return apcu_delete($iter);
68
+    }
69 69
 
70
-	/**
71
-	 * Set a value in the cache if it's not already stored
72
-	 *
73
-	 * @param string $key
74
-	 * @param mixed $value
75
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
76
-	 * @return bool
77
-	 */
78
-	public function add($key, $value, $ttl = 0) {
79
-		return apcu_add($this->getPrefix() . $key, $value, $ttl);
80
-	}
70
+    /**
71
+     * Set a value in the cache if it's not already stored
72
+     *
73
+     * @param string $key
74
+     * @param mixed $value
75
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
76
+     * @return bool
77
+     */
78
+    public function add($key, $value, $ttl = 0) {
79
+        return apcu_add($this->getPrefix() . $key, $value, $ttl);
80
+    }
81 81
 
82
-	/**
83
-	 * Increase a stored number
84
-	 *
85
-	 * @param string $key
86
-	 * @param int $step
87
-	 * @return int | bool
88
-	 */
89
-	public function inc($key, $step = 1) {
90
-		$this->add($key, 0);
91
-		/**
92
-		 * TODO - hack around a PHP 7 specific issue in APCu
93
-		 *
94
-		 * on PHP 7 the apcu_inc method on a non-existing object will increment
95
-		 * "0" and result in "1" as value - therefore we check for existence
96
-		 * first
97
-		 *
98
-		 * on PHP 5.6 this is not the case
99
-		 *
100
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101
-		 * for details
102
-		 */
103
-		return apcu_exists($this->getPrefix() . $key)
104
-			? apcu_inc($this->getPrefix() . $key, $step)
105
-			: false;
106
-	}
82
+    /**
83
+     * Increase a stored number
84
+     *
85
+     * @param string $key
86
+     * @param int $step
87
+     * @return int | bool
88
+     */
89
+    public function inc($key, $step = 1) {
90
+        $this->add($key, 0);
91
+        /**
92
+         * TODO - hack around a PHP 7 specific issue in APCu
93
+         *
94
+         * on PHP 7 the apcu_inc method on a non-existing object will increment
95
+         * "0" and result in "1" as value - therefore we check for existence
96
+         * first
97
+         *
98
+         * on PHP 5.6 this is not the case
99
+         *
100
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101
+         * for details
102
+         */
103
+        return apcu_exists($this->getPrefix() . $key)
104
+            ? apcu_inc($this->getPrefix() . $key, $step)
105
+            : false;
106
+    }
107 107
 
108
-	/**
109
-	 * Decrease a stored number
110
-	 *
111
-	 * @param string $key
112
-	 * @param int $step
113
-	 * @return int | bool
114
-	 */
115
-	public function dec($key, $step = 1) {
116
-		/**
117
-		 * TODO - hack around a PHP 7 specific issue in APCu
118
-		 *
119
-		 * on PHP 7 the apcu_dec method on a non-existing object will decrement
120
-		 * "0" and result in "-1" as value - therefore we check for existence
121
-		 * first
122
-		 *
123
-		 * on PHP 5.6 this is not the case
124
-		 *
125
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126
-		 * for details
127
-		 */
128
-		return apcu_exists($this->getPrefix() . $key)
129
-			? apcu_dec($this->getPrefix() . $key, $step)
130
-			: false;
131
-	}
108
+    /**
109
+     * Decrease a stored number
110
+     *
111
+     * @param string $key
112
+     * @param int $step
113
+     * @return int | bool
114
+     */
115
+    public function dec($key, $step = 1) {
116
+        /**
117
+         * TODO - hack around a PHP 7 specific issue in APCu
118
+         *
119
+         * on PHP 7 the apcu_dec method on a non-existing object will decrement
120
+         * "0" and result in "-1" as value - therefore we check for existence
121
+         * first
122
+         *
123
+         * on PHP 5.6 this is not the case
124
+         *
125
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126
+         * for details
127
+         */
128
+        return apcu_exists($this->getPrefix() . $key)
129
+            ? apcu_dec($this->getPrefix() . $key, $step)
130
+            : false;
131
+    }
132 132
 
133
-	/**
134
-	 * Compare and set
135
-	 *
136
-	 * @param string $key
137
-	 * @param mixed $old
138
-	 * @param mixed $new
139
-	 * @return bool
140
-	 */
141
-	public function cas($key, $old, $new) {
142
-		// apc only does cas for ints
143
-		if (is_int($old) and is_int($new)) {
144
-			return apcu_cas($this->getPrefix() . $key, $old, $new);
145
-		} else {
146
-			return $this->casEmulated($key, $old, $new);
147
-		}
148
-	}
133
+    /**
134
+     * Compare and set
135
+     *
136
+     * @param string $key
137
+     * @param mixed $old
138
+     * @param mixed $new
139
+     * @return bool
140
+     */
141
+    public function cas($key, $old, $new) {
142
+        // apc only does cas for ints
143
+        if (is_int($old) and is_int($new)) {
144
+            return apcu_cas($this->getPrefix() . $key, $old, $new);
145
+        } else {
146
+            return $this->casEmulated($key, $old, $new);
147
+        }
148
+    }
149 149
 
150
-	/**
151
-	 * @return bool
152
-	 */
153
-	static public function isAvailable() {
154
-		if (!extension_loaded('apcu')) {
155
-			return false;
156
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
157
-			return false;
158
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
159
-			return false;
160
-		} elseif (
161
-				version_compare(phpversion('apc') ?: '0.0.0', '4.0.6') === -1 &&
162
-				version_compare(phpversion('apcu') ?: '0.0.0', '5.1.0') === -1
163
-		) {
164
-			return false;
165
-		} else {
166
-			return true;
167
-		}
168
-	}
150
+    /**
151
+     * @return bool
152
+     */
153
+    static public function isAvailable() {
154
+        if (!extension_loaded('apcu')) {
155
+            return false;
156
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
157
+            return false;
158
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
159
+            return false;
160
+        } elseif (
161
+                version_compare(phpversion('apc') ?: '0.0.0', '4.0.6') === -1 &&
162
+                version_compare(phpversion('apcu') ?: '0.0.0', '5.1.0') === -1
163
+        ) {
164
+            return false;
165
+        } else {
166
+            return true;
167
+        }
168
+    }
169 169
 }
Please login to merge, or discard this patch.
lib/private/Memcache/ArrayCache.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@
 block discarded – undo
65 65
 	 * Set a value in the cache if it's not already stored
66 66
 	 *
67 67
 	 * @param string $key
68
-	 * @param mixed $value
68
+	 * @param integer $value
69 69
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
70 70
 	 * @return bool
71 71
 	 */
Please login to merge, or discard this patch.
Indentation   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -27,133 +27,133 @@
 block discarded – undo
27 27
 use OCP\IMemcache;
28 28
 
29 29
 class ArrayCache extends Cache implements IMemcache {
30
-	/** @var array Array with the cached data */
31
-	protected $cachedData = array();
30
+    /** @var array Array with the cached data */
31
+    protected $cachedData = array();
32 32
 
33
-	use CADTrait;
33
+    use CADTrait;
34 34
 
35
-	/**
36
-	 * {@inheritDoc}
37
-	 */
38
-	public function get($key) {
39
-		if ($this->hasKey($key)) {
40
-			return $this->cachedData[$key];
41
-		}
42
-		return null;
43
-	}
35
+    /**
36
+     * {@inheritDoc}
37
+     */
38
+    public function get($key) {
39
+        if ($this->hasKey($key)) {
40
+            return $this->cachedData[$key];
41
+        }
42
+        return null;
43
+    }
44 44
 
45
-	/**
46
-	 * {@inheritDoc}
47
-	 */
48
-	public function set($key, $value, $ttl = 0) {
49
-		$this->cachedData[$key] = $value;
50
-		return true;
51
-	}
45
+    /**
46
+     * {@inheritDoc}
47
+     */
48
+    public function set($key, $value, $ttl = 0) {
49
+        $this->cachedData[$key] = $value;
50
+        return true;
51
+    }
52 52
 
53
-	/**
54
-	 * {@inheritDoc}
55
-	 */
56
-	public function hasKey($key) {
57
-		return isset($this->cachedData[$key]);
58
-	}
53
+    /**
54
+     * {@inheritDoc}
55
+     */
56
+    public function hasKey($key) {
57
+        return isset($this->cachedData[$key]);
58
+    }
59 59
 
60
-	/**
61
-	 * {@inheritDoc}
62
-	 */
63
-	public function remove($key) {
64
-		unset($this->cachedData[$key]);
65
-		return true;
66
-	}
60
+    /**
61
+     * {@inheritDoc}
62
+     */
63
+    public function remove($key) {
64
+        unset($this->cachedData[$key]);
65
+        return true;
66
+    }
67 67
 
68
-	/**
69
-	 * {@inheritDoc}
70
-	 */
71
-	public function clear($prefix = '') {
72
-		if ($prefix === '') {
73
-			$this->cachedData = [];
74
-			return true;
75
-		}
68
+    /**
69
+     * {@inheritDoc}
70
+     */
71
+    public function clear($prefix = '') {
72
+        if ($prefix === '') {
73
+            $this->cachedData = [];
74
+            return true;
75
+        }
76 76
 
77
-		foreach ($this->cachedData as $key => $value) {
78
-			if (strpos($key, $prefix) === 0) {
79
-				$this->remove($key);
80
-			}
81
-		}
82
-		return true;
83
-	}
77
+        foreach ($this->cachedData as $key => $value) {
78
+            if (strpos($key, $prefix) === 0) {
79
+                $this->remove($key);
80
+            }
81
+        }
82
+        return true;
83
+    }
84 84
 
85
-	/**
86
-	 * Set a value in the cache if it's not already stored
87
-	 *
88
-	 * @param string $key
89
-	 * @param mixed $value
90
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
91
-	 * @return bool
92
-	 */
93
-	public function add($key, $value, $ttl = 0) {
94
-		// since this cache is not shared race conditions aren't an issue
95
-		if ($this->hasKey($key)) {
96
-			return false;
97
-		} else {
98
-			return $this->set($key, $value, $ttl);
99
-		}
100
-	}
85
+    /**
86
+     * Set a value in the cache if it's not already stored
87
+     *
88
+     * @param string $key
89
+     * @param mixed $value
90
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
91
+     * @return bool
92
+     */
93
+    public function add($key, $value, $ttl = 0) {
94
+        // since this cache is not shared race conditions aren't an issue
95
+        if ($this->hasKey($key)) {
96
+            return false;
97
+        } else {
98
+            return $this->set($key, $value, $ttl);
99
+        }
100
+    }
101 101
 
102
-	/**
103
-	 * Increase a stored number
104
-	 *
105
-	 * @param string $key
106
-	 * @param int $step
107
-	 * @return int | bool
108
-	 */
109
-	public function inc($key, $step = 1) {
110
-		$oldValue = $this->get($key);
111
-		if (is_int($oldValue)) {
112
-			$this->set($key, $oldValue + $step);
113
-			return $oldValue + $step;
114
-		} else {
115
-			$success = $this->add($key, $step);
116
-			return $success ? $step : false;
117
-		}
118
-	}
102
+    /**
103
+     * Increase a stored number
104
+     *
105
+     * @param string $key
106
+     * @param int $step
107
+     * @return int | bool
108
+     */
109
+    public function inc($key, $step = 1) {
110
+        $oldValue = $this->get($key);
111
+        if (is_int($oldValue)) {
112
+            $this->set($key, $oldValue + $step);
113
+            return $oldValue + $step;
114
+        } else {
115
+            $success = $this->add($key, $step);
116
+            return $success ? $step : false;
117
+        }
118
+    }
119 119
 
120
-	/**
121
-	 * Decrease a stored number
122
-	 *
123
-	 * @param string $key
124
-	 * @param int $step
125
-	 * @return int | bool
126
-	 */
127
-	public function dec($key, $step = 1) {
128
-		$oldValue = $this->get($key);
129
-		if (is_int($oldValue)) {
130
-			$this->set($key, $oldValue - $step);
131
-			return $oldValue - $step;
132
-		} else {
133
-			return false;
134
-		}
135
-	}
120
+    /**
121
+     * Decrease a stored number
122
+     *
123
+     * @param string $key
124
+     * @param int $step
125
+     * @return int | bool
126
+     */
127
+    public function dec($key, $step = 1) {
128
+        $oldValue = $this->get($key);
129
+        if (is_int($oldValue)) {
130
+            $this->set($key, $oldValue - $step);
131
+            return $oldValue - $step;
132
+        } else {
133
+            return false;
134
+        }
135
+    }
136 136
 
137
-	/**
138
-	 * Compare and set
139
-	 *
140
-	 * @param string $key
141
-	 * @param mixed $old
142
-	 * @param mixed $new
143
-	 * @return bool
144
-	 */
145
-	public function cas($key, $old, $new) {
146
-		if ($this->get($key) === $old) {
147
-			return $this->set($key, $new);
148
-		} else {
149
-			return false;
150
-		}
151
-	}
137
+    /**
138
+     * Compare and set
139
+     *
140
+     * @param string $key
141
+     * @param mixed $old
142
+     * @param mixed $new
143
+     * @return bool
144
+     */
145
+    public function cas($key, $old, $new) {
146
+        if ($this->get($key) === $old) {
147
+            return $this->set($key, $new);
148
+        } else {
149
+            return false;
150
+        }
151
+    }
152 152
 
153
-	/**
154
-	 * {@inheritDoc}
155
-	 */
156
-	static public function isAvailable() {
157
-		return true;
158
-	}
153
+    /**
154
+     * {@inheritDoc}
155
+     */
156
+    static public function isAvailable() {
157
+        return true;
158
+    }
159 159
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/SMB.php 4 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -498,6 +498,9 @@
 block discarded – undo
498 498
 		});
499 499
 	}
500 500
 
501
+	/**
502
+	 * @param string $path
503
+	 */
501 504
 	public function notify($path) {
502 505
 		$path = '/' . ltrim($path, '/');
503 506
 		$shareNotifyHandler = $this->share->notify($this->buildPath($path));
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -85,8 +85,8 @@  discard block
 block discarded – undo
85 85
 			$this->share = $this->server->getShare(trim($params['share'], '/'));
86 86
 
87 87
 			$this->root = $params['root'] ?? '/';
88
-			$this->root = '/' . ltrim($this->root, '/');
89
-			$this->root = rtrim($this->root, '/') . '/';
88
+			$this->root = '/'.ltrim($this->root, '/');
89
+			$this->root = rtrim($this->root, '/').'/';
90 90
 		} else {
91 91
 			throw new \Exception('Invalid configuration');
92 92
 		}
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
 		// FIXME: double slash to keep compatible with the old storage ids,
102 102
 		// failure to do so will lead to creation of a new storage id and
103 103
 		// loss of shares from the storage
104
-		return 'smb::' . $this->server->getUser() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
104
+		return 'smb::'.$this->server->getUser().'@'.$this->server->getHost().'//'.$this->share->getName().'/'.$this->root;
105 105
 	}
106 106
 
107 107
 	/**
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 	 * @return string
110 110
 	 */
111 111
 	protected function buildPath($path) {
112
-		return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
112
+		return Filesystem::normalizePath($this->root.'/'.$path, true, false, true);
113 113
 	}
114 114
 
115 115
 	protected function relativePath($fullPath) {
@@ -149,9 +149,9 @@  discard block
 block discarded – undo
149 149
 			$path = $this->buildPath($path);
150 150
 			$files = $this->share->dir($path);
151 151
 			foreach ($files as $file) {
152
-				$this->statCache[$path . '/' . $file->getName()] = $file;
152
+				$this->statCache[$path.'/'.$file->getName()] = $file;
153 153
 			}
154
-			return array_filter($files, function (IFileInfo $file) {
154
+			return array_filter($files, function(IFileInfo $file) {
155 155
 				try {
156 156
 					return !$file->isHidden();
157 157
 				} catch (ForbiddenException $e) {
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
 				case 'w':
326 326
 				case 'wb':
327 327
 					$source = $this->share->write($fullPath);
328
-					return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
328
+					return CallBackWrapper::wrap($source, null, null, function() use ($fullPath) {
329 329
 						unset($this->statCache[$fullPath]);
330 330
 					});
331 331
 				case 'a':
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 					}
358 358
 					$source = fopen($tmpFile, $mode);
359 359
 					$share = $this->share;
360
-					return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
360
+					return CallbackWrapper::wrap($source, null, null, function() use ($tmpFile, $fullPath, $share) {
361 361
 						unset($this->statCache[$fullPath]);
362 362
 						$share->put($tmpFile, $fullPath);
363 363
 						unlink($tmpFile);
@@ -383,7 +383,7 @@  discard block
 block discarded – undo
383 383
 			$content = $this->share->dir($this->buildPath($path));
384 384
 			foreach ($content as $file) {
385 385
 				if ($file->isDirectory()) {
386
-					$this->rmdir($path . '/' . $file->getName());
386
+					$this->rmdir($path.'/'.$file->getName());
387 387
 				} else {
388 388
 					$this->share->del($file->getPath());
389 389
 				}
@@ -420,7 +420,7 @@  discard block
 block discarded – undo
420 420
 		} catch (ForbiddenException $e) {
421 421
 			return false;
422 422
 		}
423
-		$names = array_map(function ($info) {
423
+		$names = array_map(function($info) {
424 424
 			/** @var \Icewind\SMB\IFileInfo $info */
425 425
 			return $info->getName();
426 426
 		}, $files);
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
 	 */
503 503
 	public static function checkDependencies() {
504 504
 		return (
505
-			(bool)\OC_Helper::findBinaryPath('smbclient')
505
+			(bool) \OC_Helper::findBinaryPath('smbclient')
506 506
 			|| Server::NativeAvailable()
507 507
 		) ? true : ['smbclient'];
508 508
 	}
@@ -521,7 +521,7 @@  discard block
 block discarded – undo
521 521
 	}
522 522
 
523 523
 	public function listen($path, callable $callback) {
524
-		$this->notify($path)->listen(function (IChange $change) use ($callback) {
524
+		$this->notify($path)->listen(function(IChange $change) use ($callback) {
525 525
 			if ($change instanceof IRenameChange) {
526 526
 				return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
527 527
 			} else {
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 	}
532 532
 
533 533
 	public function notify($path) {
534
-		$path = '/' . ltrim($path, '/');
534
+		$path = '/'.ltrim($path, '/');
535 535
 		$shareNotifyHandler = $this->share->notify($this->buildPath($path));
536 536
 		return new SMBNotifyHandler($shareNotifyHandler, $this->root);
537 537
 	}
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -53,7 +53,6 @@
 block discarded – undo
53 53
 use OCP\Files\Storage\INotifyStorage;
54 54
 use OCP\Files\StorageNotAvailableException;
55 55
 use OCP\ILogger;
56
-use OCP\Util;
57 56
 
58 57
 class SMB extends Common implements INotifyStorage {
59 58
 	/**
Please login to merge, or discard this patch.
Indentation   +480 added lines, -480 removed lines patch added patch discarded remove patch
@@ -56,484 +56,484 @@
 block discarded – undo
56 56
 use OCP\Util;
57 57
 
58 58
 class SMB extends Common implements INotifyStorage {
59
-	/**
60
-	 * @var \Icewind\SMB\Server
61
-	 */
62
-	protected $server;
63
-
64
-	/**
65
-	 * @var \Icewind\SMB\Share
66
-	 */
67
-	protected $share;
68
-
69
-	/**
70
-	 * @var string
71
-	 */
72
-	protected $root;
73
-
74
-	/**
75
-	 * @var \Icewind\SMB\FileInfo[]
76
-	 */
77
-	protected $statCache;
78
-
79
-	public function __construct($params) {
80
-		if (isset($params['host']) && isset($params['user']) && isset($params['password']) && isset($params['share'])) {
81
-			if (Server::NativeAvailable()) {
82
-				$this->server = new NativeServer($params['host'], $params['user'], $params['password']);
83
-			} else {
84
-				$this->server = new Server($params['host'], $params['user'], $params['password']);
85
-			}
86
-			$this->share = $this->server->getShare(trim($params['share'], '/'));
87
-
88
-			$this->root = $params['root'] ?? '/';
89
-			$this->root = '/' . ltrim($this->root, '/');
90
-			$this->root = rtrim($this->root, '/') . '/';
91
-		} else {
92
-			throw new \Exception('Invalid configuration');
93
-		}
94
-		$this->statCache = new CappedMemoryCache();
95
-		parent::__construct($params);
96
-	}
97
-
98
-	/**
99
-	 * @return string
100
-	 */
101
-	public function getId() {
102
-		// FIXME: double slash to keep compatible with the old storage ids,
103
-		// failure to do so will lead to creation of a new storage id and
104
-		// loss of shares from the storage
105
-		return 'smb::' . $this->server->getUser() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
106
-	}
107
-
108
-	/**
109
-	 * @param string $path
110
-	 * @return string
111
-	 */
112
-	protected function buildPath($path) {
113
-		return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
114
-	}
115
-
116
-	protected function relativePath($fullPath) {
117
-		if ($fullPath === $this->root) {
118
-			return '';
119
-		} else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
120
-			return substr($fullPath, strlen($this->root));
121
-		} else {
122
-			return null;
123
-		}
124
-	}
125
-
126
-	/**
127
-	 * @param string $path
128
-	 * @return \Icewind\SMB\IFileInfo
129
-	 * @throws StorageNotAvailableException
130
-	 */
131
-	protected function getFileInfo($path) {
132
-		try {
133
-			$path = $this->buildPath($path);
134
-			if (!isset($this->statCache[$path])) {
135
-				$this->statCache[$path] = $this->share->stat($path);
136
-			}
137
-			return $this->statCache[$path];
138
-		} catch (ConnectException $e) {
139
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
140
-		}
141
-	}
142
-
143
-	/**
144
-	 * @param string $path
145
-	 * @return \Icewind\SMB\IFileInfo[]
146
-	 * @throws StorageNotAvailableException
147
-	 */
148
-	protected function getFolderContents($path) {
149
-		try {
150
-			$path = $this->buildPath($path);
151
-			$files = $this->share->dir($path);
152
-			foreach ($files as $file) {
153
-				$this->statCache[$path . '/' . $file->getName()] = $file;
154
-			}
155
-			return array_filter($files, function (IFileInfo $file) {
156
-				try {
157
-					return !$file->isHidden();
158
-				} catch (ForbiddenException $e) {
159
-					return false;
160
-				} catch (NotFoundException $e) {
161
-					return false;
162
-				}
163
-			});
164
-		} catch (ConnectException $e) {
165
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
166
-		}
167
-	}
168
-
169
-	/**
170
-	 * @param \Icewind\SMB\IFileInfo $info
171
-	 * @return array
172
-	 */
173
-	protected function formatInfo($info) {
174
-		$result = [
175
-			'size' => $info->getSize(),
176
-			'mtime' => $info->getMTime(),
177
-		];
178
-		if ($info->isDirectory()) {
179
-			$result['type'] = 'dir';
180
-		} else {
181
-			$result['type'] = 'file';
182
-		}
183
-		return $result;
184
-	}
185
-
186
-	/**
187
-	 * Rename the files. If the source or the target is the root, the rename won't happen.
188
-	 *
189
-	 * @param string $source the old name of the path
190
-	 * @param string $target the new name of the path
191
-	 * @return bool true if the rename is successful, false otherwise
192
-	 */
193
-	public function rename($source, $target) {
194
-		if ($this->isRootDir($source) || $this->isRootDir($target)) {
195
-			return false;
196
-		}
197
-
198
-		$absoluteSource = $this->buildPath($source);
199
-		$absoluteTarget = $this->buildPath($target);
200
-		try {
201
-			$result = $this->share->rename($absoluteSource, $absoluteTarget);
202
-		} catch (AlreadyExistsException $e) {
203
-			$this->remove($target);
204
-			$result = $this->share->rename($absoluteSource, $absoluteTarget);
205
-		} catch (\Exception $e) {
206
-			\OC::$server->getLogger()->logException($e, ['level' => ILogger::WARN]);
207
-			return false;
208
-		}
209
-		unset($this->statCache[$absoluteSource], $this->statCache[$absoluteTarget]);
210
-		return $result;
211
-	}
212
-
213
-	public function stat($path) {
214
-		try {
215
-			$result = $this->formatInfo($this->getFileInfo($path));
216
-		} catch (ForbiddenException $e) {
217
-			return false;
218
-		} catch (NotFoundException $e) {
219
-			return false;
220
-		}
221
-		if ($this->remoteIsShare() && $this->isRootDir($path)) {
222
-			$result['mtime'] = $this->shareMTime();
223
-		}
224
-		return $result;
225
-	}
226
-
227
-	/**
228
-	 * get the best guess for the modification time of the share
229
-	 *
230
-	 * @return int
231
-	 */
232
-	private function shareMTime() {
233
-		$highestMTime = 0;
234
-		$files = $this->share->dir($this->root);
235
-		foreach ($files as $fileInfo) {
236
-			try {
237
-				if ($fileInfo->getMTime() > $highestMTime) {
238
-					$highestMTime = $fileInfo->getMTime();
239
-				}
240
-			} catch (NotFoundException $e) {
241
-				// Ignore this, can happen on unavailable DFS shares
242
-			}
243
-		}
244
-		return $highestMTime;
245
-	}
246
-
247
-	/**
248
-	 * Check if the path is our root dir (not the smb one)
249
-	 *
250
-	 * @param string $path the path
251
-	 * @return bool
252
-	 */
253
-	private function isRootDir($path) {
254
-		return $path === '' || $path === '/' || $path === '.';
255
-	}
256
-
257
-	/**
258
-	 * Check if our root points to a smb share
259
-	 *
260
-	 * @return bool true if our root points to a share false otherwise
261
-	 */
262
-	private function remoteIsShare() {
263
-		return $this->share->getName() && (!$this->root || $this->root === '/');
264
-	}
265
-
266
-	/**
267
-	 * @param string $path
268
-	 * @return bool
269
-	 */
270
-	public function unlink($path) {
271
-		if ($this->isRootDir($path)) {
272
-			return false;
273
-		}
274
-
275
-		try {
276
-			if ($this->is_dir($path)) {
277
-				return $this->rmdir($path);
278
-			} else {
279
-				$path = $this->buildPath($path);
280
-				unset($this->statCache[$path]);
281
-				$this->share->del($path);
282
-				return true;
283
-			}
284
-		} catch (NotFoundException $e) {
285
-			return false;
286
-		} catch (ForbiddenException $e) {
287
-			return false;
288
-		} catch (ConnectException $e) {
289
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
290
-		}
291
-	}
292
-
293
-	/**
294
-	 * check if a file or folder has been updated since $time
295
-	 *
296
-	 * @param string $path
297
-	 * @param int $time
298
-	 * @return bool
299
-	 */
300
-	public function hasUpdated($path, $time) {
301
-		if (!$path and $this->root === '/') {
302
-			// mtime doesn't work for shares, but giving the nature of the backend,
303
-			// doing a full update is still just fast enough
304
-			return true;
305
-		} else {
306
-			$actualTime = $this->filemtime($path);
307
-			return $actualTime > $time;
308
-		}
309
-	}
310
-
311
-	/**
312
-	 * @param string $path
313
-	 * @param string $mode
314
-	 * @return resource|false
315
-	 */
316
-	public function fopen($path, $mode) {
317
-		$fullPath = $this->buildPath($path);
318
-		try {
319
-			switch ($mode) {
320
-				case 'r':
321
-				case 'rb':
322
-					if (!$this->file_exists($path)) {
323
-						return false;
324
-					}
325
-					return $this->share->read($fullPath);
326
-				case 'w':
327
-				case 'wb':
328
-					$source = $this->share->write($fullPath);
329
-					return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
330
-						unset($this->statCache[$fullPath]);
331
-					});
332
-				case 'a':
333
-				case 'ab':
334
-				case 'r+':
335
-				case 'w+':
336
-				case 'wb+':
337
-				case 'a+':
338
-				case 'x':
339
-				case 'x+':
340
-				case 'c':
341
-				case 'c+':
342
-					//emulate these
343
-					if (strrpos($path, '.') !== false) {
344
-						$ext = substr($path, strrpos($path, '.'));
345
-					} else {
346
-						$ext = '';
347
-					}
348
-					if ($this->file_exists($path)) {
349
-						if (!$this->isUpdatable($path)) {
350
-							return false;
351
-						}
352
-						$tmpFile = $this->getCachedFile($path);
353
-					} else {
354
-						if (!$this->isCreatable(dirname($path))) {
355
-							return false;
356
-						}
357
-						$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
358
-					}
359
-					$source = fopen($tmpFile, $mode);
360
-					$share = $this->share;
361
-					return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
362
-						unset($this->statCache[$fullPath]);
363
-						$share->put($tmpFile, $fullPath);
364
-						unlink($tmpFile);
365
-					});
366
-			}
367
-			return false;
368
-		} catch (NotFoundException $e) {
369
-			return false;
370
-		} catch (ForbiddenException $e) {
371
-			return false;
372
-		} catch (ConnectException $e) {
373
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
374
-		}
375
-	}
376
-
377
-	public function rmdir($path) {
378
-		if ($this->isRootDir($path)) {
379
-			return false;
380
-		}
381
-
382
-		try {
383
-			$this->statCache = array();
384
-			$content = $this->share->dir($this->buildPath($path));
385
-			foreach ($content as $file) {
386
-				if ($file->isDirectory()) {
387
-					$this->rmdir($path . '/' . $file->getName());
388
-				} else {
389
-					$this->share->del($file->getPath());
390
-				}
391
-			}
392
-			$this->share->rmdir($this->buildPath($path));
393
-			return true;
394
-		} catch (NotFoundException $e) {
395
-			return false;
396
-		} catch (ForbiddenException $e) {
397
-			return false;
398
-		} catch (ConnectException $e) {
399
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
400
-		}
401
-	}
402
-
403
-	public function touch($path, $time = null) {
404
-		try {
405
-			if (!$this->file_exists($path)) {
406
-				$fh = $this->share->write($this->buildPath($path));
407
-				fclose($fh);
408
-				return true;
409
-			}
410
-			return false;
411
-		} catch (ConnectException $e) {
412
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
413
-		}
414
-	}
415
-
416
-	public function opendir($path) {
417
-		try {
418
-			$files = $this->getFolderContents($path);
419
-		} catch (NotFoundException $e) {
420
-			return false;
421
-		} catch (ForbiddenException $e) {
422
-			return false;
423
-		}
424
-		$names = array_map(function ($info) {
425
-			/** @var \Icewind\SMB\IFileInfo $info */
426
-			return $info->getName();
427
-		}, $files);
428
-		return IteratorDirectory::wrap($names);
429
-	}
430
-
431
-	public function filetype($path) {
432
-		try {
433
-			return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
434
-		} catch (NotFoundException $e) {
435
-			return false;
436
-		} catch (ForbiddenException $e) {
437
-			return false;
438
-		}
439
-	}
440
-
441
-	public function mkdir($path) {
442
-		$path = $this->buildPath($path);
443
-		try {
444
-			$this->share->mkdir($path);
445
-			return true;
446
-		} catch (ConnectException $e) {
447
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
448
-		} catch (Exception $e) {
449
-			return false;
450
-		}
451
-	}
452
-
453
-	public function file_exists($path) {
454
-		try {
455
-			$this->getFileInfo($path);
456
-			return true;
457
-		} catch (NotFoundException $e) {
458
-			return false;
459
-		} catch (ForbiddenException $e) {
460
-			return false;
461
-		} catch (ConnectException $e) {
462
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
463
-		}
464
-	}
465
-
466
-	public function isReadable($path) {
467
-		try {
468
-			$info = $this->getFileInfo($path);
469
-			return !$info->isHidden();
470
-		} catch (NotFoundException $e) {
471
-			return false;
472
-		} catch (ForbiddenException $e) {
473
-			return false;
474
-		}
475
-	}
476
-
477
-	public function isUpdatable($path) {
478
-		try {
479
-			$info = $this->getFileInfo($path);
480
-			// following windows behaviour for read-only folders: they can be written into
481
-			// (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
482
-			return !$info->isHidden() && (!$info->isReadOnly() || $this->is_dir($path));
483
-		} catch (NotFoundException $e) {
484
-			return false;
485
-		} catch (ForbiddenException $e) {
486
-			return false;
487
-		}
488
-	}
489
-
490
-	public function isDeletable($path) {
491
-		try {
492
-			$info = $this->getFileInfo($path);
493
-			return !$info->isHidden() && !$info->isReadOnly();
494
-		} catch (NotFoundException $e) {
495
-			return false;
496
-		} catch (ForbiddenException $e) {
497
-			return false;
498
-		}
499
-	}
500
-
501
-	/**
502
-	 * check if smbclient is installed
503
-	 */
504
-	public static function checkDependencies() {
505
-		return (
506
-			(bool)\OC_Helper::findBinaryPath('smbclient')
507
-			|| Server::NativeAvailable()
508
-		) ? true : ['smbclient'];
509
-	}
510
-
511
-	/**
512
-	 * Test a storage for availability
513
-	 *
514
-	 * @return bool
515
-	 */
516
-	public function test() {
517
-		try {
518
-			return parent::test();
519
-		} catch (Exception $e) {
520
-			return false;
521
-		}
522
-	}
523
-
524
-	public function listen($path, callable $callback) {
525
-		$this->notify($path)->listen(function (IChange $change) use ($callback) {
526
-			if ($change instanceof IRenameChange) {
527
-				return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
528
-			} else {
529
-				return $callback($change->getType(), $change->getPath());
530
-			}
531
-		});
532
-	}
533
-
534
-	public function notify($path) {
535
-		$path = '/' . ltrim($path, '/');
536
-		$shareNotifyHandler = $this->share->notify($this->buildPath($path));
537
-		return new SMBNotifyHandler($shareNotifyHandler, $this->root);
538
-	}
59
+    /**
60
+     * @var \Icewind\SMB\Server
61
+     */
62
+    protected $server;
63
+
64
+    /**
65
+     * @var \Icewind\SMB\Share
66
+     */
67
+    protected $share;
68
+
69
+    /**
70
+     * @var string
71
+     */
72
+    protected $root;
73
+
74
+    /**
75
+     * @var \Icewind\SMB\FileInfo[]
76
+     */
77
+    protected $statCache;
78
+
79
+    public function __construct($params) {
80
+        if (isset($params['host']) && isset($params['user']) && isset($params['password']) && isset($params['share'])) {
81
+            if (Server::NativeAvailable()) {
82
+                $this->server = new NativeServer($params['host'], $params['user'], $params['password']);
83
+            } else {
84
+                $this->server = new Server($params['host'], $params['user'], $params['password']);
85
+            }
86
+            $this->share = $this->server->getShare(trim($params['share'], '/'));
87
+
88
+            $this->root = $params['root'] ?? '/';
89
+            $this->root = '/' . ltrim($this->root, '/');
90
+            $this->root = rtrim($this->root, '/') . '/';
91
+        } else {
92
+            throw new \Exception('Invalid configuration');
93
+        }
94
+        $this->statCache = new CappedMemoryCache();
95
+        parent::__construct($params);
96
+    }
97
+
98
+    /**
99
+     * @return string
100
+     */
101
+    public function getId() {
102
+        // FIXME: double slash to keep compatible with the old storage ids,
103
+        // failure to do so will lead to creation of a new storage id and
104
+        // loss of shares from the storage
105
+        return 'smb::' . $this->server->getUser() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
106
+    }
107
+
108
+    /**
109
+     * @param string $path
110
+     * @return string
111
+     */
112
+    protected function buildPath($path) {
113
+        return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
114
+    }
115
+
116
+    protected function relativePath($fullPath) {
117
+        if ($fullPath === $this->root) {
118
+            return '';
119
+        } else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
120
+            return substr($fullPath, strlen($this->root));
121
+        } else {
122
+            return null;
123
+        }
124
+    }
125
+
126
+    /**
127
+     * @param string $path
128
+     * @return \Icewind\SMB\IFileInfo
129
+     * @throws StorageNotAvailableException
130
+     */
131
+    protected function getFileInfo($path) {
132
+        try {
133
+            $path = $this->buildPath($path);
134
+            if (!isset($this->statCache[$path])) {
135
+                $this->statCache[$path] = $this->share->stat($path);
136
+            }
137
+            return $this->statCache[$path];
138
+        } catch (ConnectException $e) {
139
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
140
+        }
141
+    }
142
+
143
+    /**
144
+     * @param string $path
145
+     * @return \Icewind\SMB\IFileInfo[]
146
+     * @throws StorageNotAvailableException
147
+     */
148
+    protected function getFolderContents($path) {
149
+        try {
150
+            $path = $this->buildPath($path);
151
+            $files = $this->share->dir($path);
152
+            foreach ($files as $file) {
153
+                $this->statCache[$path . '/' . $file->getName()] = $file;
154
+            }
155
+            return array_filter($files, function (IFileInfo $file) {
156
+                try {
157
+                    return !$file->isHidden();
158
+                } catch (ForbiddenException $e) {
159
+                    return false;
160
+                } catch (NotFoundException $e) {
161
+                    return false;
162
+                }
163
+            });
164
+        } catch (ConnectException $e) {
165
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
166
+        }
167
+    }
168
+
169
+    /**
170
+     * @param \Icewind\SMB\IFileInfo $info
171
+     * @return array
172
+     */
173
+    protected function formatInfo($info) {
174
+        $result = [
175
+            'size' => $info->getSize(),
176
+            'mtime' => $info->getMTime(),
177
+        ];
178
+        if ($info->isDirectory()) {
179
+            $result['type'] = 'dir';
180
+        } else {
181
+            $result['type'] = 'file';
182
+        }
183
+        return $result;
184
+    }
185
+
186
+    /**
187
+     * Rename the files. If the source or the target is the root, the rename won't happen.
188
+     *
189
+     * @param string $source the old name of the path
190
+     * @param string $target the new name of the path
191
+     * @return bool true if the rename is successful, false otherwise
192
+     */
193
+    public function rename($source, $target) {
194
+        if ($this->isRootDir($source) || $this->isRootDir($target)) {
195
+            return false;
196
+        }
197
+
198
+        $absoluteSource = $this->buildPath($source);
199
+        $absoluteTarget = $this->buildPath($target);
200
+        try {
201
+            $result = $this->share->rename($absoluteSource, $absoluteTarget);
202
+        } catch (AlreadyExistsException $e) {
203
+            $this->remove($target);
204
+            $result = $this->share->rename($absoluteSource, $absoluteTarget);
205
+        } catch (\Exception $e) {
206
+            \OC::$server->getLogger()->logException($e, ['level' => ILogger::WARN]);
207
+            return false;
208
+        }
209
+        unset($this->statCache[$absoluteSource], $this->statCache[$absoluteTarget]);
210
+        return $result;
211
+    }
212
+
213
+    public function stat($path) {
214
+        try {
215
+            $result = $this->formatInfo($this->getFileInfo($path));
216
+        } catch (ForbiddenException $e) {
217
+            return false;
218
+        } catch (NotFoundException $e) {
219
+            return false;
220
+        }
221
+        if ($this->remoteIsShare() && $this->isRootDir($path)) {
222
+            $result['mtime'] = $this->shareMTime();
223
+        }
224
+        return $result;
225
+    }
226
+
227
+    /**
228
+     * get the best guess for the modification time of the share
229
+     *
230
+     * @return int
231
+     */
232
+    private function shareMTime() {
233
+        $highestMTime = 0;
234
+        $files = $this->share->dir($this->root);
235
+        foreach ($files as $fileInfo) {
236
+            try {
237
+                if ($fileInfo->getMTime() > $highestMTime) {
238
+                    $highestMTime = $fileInfo->getMTime();
239
+                }
240
+            } catch (NotFoundException $e) {
241
+                // Ignore this, can happen on unavailable DFS shares
242
+            }
243
+        }
244
+        return $highestMTime;
245
+    }
246
+
247
+    /**
248
+     * Check if the path is our root dir (not the smb one)
249
+     *
250
+     * @param string $path the path
251
+     * @return bool
252
+     */
253
+    private function isRootDir($path) {
254
+        return $path === '' || $path === '/' || $path === '.';
255
+    }
256
+
257
+    /**
258
+     * Check if our root points to a smb share
259
+     *
260
+     * @return bool true if our root points to a share false otherwise
261
+     */
262
+    private function remoteIsShare() {
263
+        return $this->share->getName() && (!$this->root || $this->root === '/');
264
+    }
265
+
266
+    /**
267
+     * @param string $path
268
+     * @return bool
269
+     */
270
+    public function unlink($path) {
271
+        if ($this->isRootDir($path)) {
272
+            return false;
273
+        }
274
+
275
+        try {
276
+            if ($this->is_dir($path)) {
277
+                return $this->rmdir($path);
278
+            } else {
279
+                $path = $this->buildPath($path);
280
+                unset($this->statCache[$path]);
281
+                $this->share->del($path);
282
+                return true;
283
+            }
284
+        } catch (NotFoundException $e) {
285
+            return false;
286
+        } catch (ForbiddenException $e) {
287
+            return false;
288
+        } catch (ConnectException $e) {
289
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
290
+        }
291
+    }
292
+
293
+    /**
294
+     * check if a file or folder has been updated since $time
295
+     *
296
+     * @param string $path
297
+     * @param int $time
298
+     * @return bool
299
+     */
300
+    public function hasUpdated($path, $time) {
301
+        if (!$path and $this->root === '/') {
302
+            // mtime doesn't work for shares, but giving the nature of the backend,
303
+            // doing a full update is still just fast enough
304
+            return true;
305
+        } else {
306
+            $actualTime = $this->filemtime($path);
307
+            return $actualTime > $time;
308
+        }
309
+    }
310
+
311
+    /**
312
+     * @param string $path
313
+     * @param string $mode
314
+     * @return resource|false
315
+     */
316
+    public function fopen($path, $mode) {
317
+        $fullPath = $this->buildPath($path);
318
+        try {
319
+            switch ($mode) {
320
+                case 'r':
321
+                case 'rb':
322
+                    if (!$this->file_exists($path)) {
323
+                        return false;
324
+                    }
325
+                    return $this->share->read($fullPath);
326
+                case 'w':
327
+                case 'wb':
328
+                    $source = $this->share->write($fullPath);
329
+                    return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
330
+                        unset($this->statCache[$fullPath]);
331
+                    });
332
+                case 'a':
333
+                case 'ab':
334
+                case 'r+':
335
+                case 'w+':
336
+                case 'wb+':
337
+                case 'a+':
338
+                case 'x':
339
+                case 'x+':
340
+                case 'c':
341
+                case 'c+':
342
+                    //emulate these
343
+                    if (strrpos($path, '.') !== false) {
344
+                        $ext = substr($path, strrpos($path, '.'));
345
+                    } else {
346
+                        $ext = '';
347
+                    }
348
+                    if ($this->file_exists($path)) {
349
+                        if (!$this->isUpdatable($path)) {
350
+                            return false;
351
+                        }
352
+                        $tmpFile = $this->getCachedFile($path);
353
+                    } else {
354
+                        if (!$this->isCreatable(dirname($path))) {
355
+                            return false;
356
+                        }
357
+                        $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
358
+                    }
359
+                    $source = fopen($tmpFile, $mode);
360
+                    $share = $this->share;
361
+                    return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
362
+                        unset($this->statCache[$fullPath]);
363
+                        $share->put($tmpFile, $fullPath);
364
+                        unlink($tmpFile);
365
+                    });
366
+            }
367
+            return false;
368
+        } catch (NotFoundException $e) {
369
+            return false;
370
+        } catch (ForbiddenException $e) {
371
+            return false;
372
+        } catch (ConnectException $e) {
373
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
374
+        }
375
+    }
376
+
377
+    public function rmdir($path) {
378
+        if ($this->isRootDir($path)) {
379
+            return false;
380
+        }
381
+
382
+        try {
383
+            $this->statCache = array();
384
+            $content = $this->share->dir($this->buildPath($path));
385
+            foreach ($content as $file) {
386
+                if ($file->isDirectory()) {
387
+                    $this->rmdir($path . '/' . $file->getName());
388
+                } else {
389
+                    $this->share->del($file->getPath());
390
+                }
391
+            }
392
+            $this->share->rmdir($this->buildPath($path));
393
+            return true;
394
+        } catch (NotFoundException $e) {
395
+            return false;
396
+        } catch (ForbiddenException $e) {
397
+            return false;
398
+        } catch (ConnectException $e) {
399
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
400
+        }
401
+    }
402
+
403
+    public function touch($path, $time = null) {
404
+        try {
405
+            if (!$this->file_exists($path)) {
406
+                $fh = $this->share->write($this->buildPath($path));
407
+                fclose($fh);
408
+                return true;
409
+            }
410
+            return false;
411
+        } catch (ConnectException $e) {
412
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
413
+        }
414
+    }
415
+
416
+    public function opendir($path) {
417
+        try {
418
+            $files = $this->getFolderContents($path);
419
+        } catch (NotFoundException $e) {
420
+            return false;
421
+        } catch (ForbiddenException $e) {
422
+            return false;
423
+        }
424
+        $names = array_map(function ($info) {
425
+            /** @var \Icewind\SMB\IFileInfo $info */
426
+            return $info->getName();
427
+        }, $files);
428
+        return IteratorDirectory::wrap($names);
429
+    }
430
+
431
+    public function filetype($path) {
432
+        try {
433
+            return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
434
+        } catch (NotFoundException $e) {
435
+            return false;
436
+        } catch (ForbiddenException $e) {
437
+            return false;
438
+        }
439
+    }
440
+
441
+    public function mkdir($path) {
442
+        $path = $this->buildPath($path);
443
+        try {
444
+            $this->share->mkdir($path);
445
+            return true;
446
+        } catch (ConnectException $e) {
447
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
448
+        } catch (Exception $e) {
449
+            return false;
450
+        }
451
+    }
452
+
453
+    public function file_exists($path) {
454
+        try {
455
+            $this->getFileInfo($path);
456
+            return true;
457
+        } catch (NotFoundException $e) {
458
+            return false;
459
+        } catch (ForbiddenException $e) {
460
+            return false;
461
+        } catch (ConnectException $e) {
462
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
463
+        }
464
+    }
465
+
466
+    public function isReadable($path) {
467
+        try {
468
+            $info = $this->getFileInfo($path);
469
+            return !$info->isHidden();
470
+        } catch (NotFoundException $e) {
471
+            return false;
472
+        } catch (ForbiddenException $e) {
473
+            return false;
474
+        }
475
+    }
476
+
477
+    public function isUpdatable($path) {
478
+        try {
479
+            $info = $this->getFileInfo($path);
480
+            // following windows behaviour for read-only folders: they can be written into
481
+            // (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
482
+            return !$info->isHidden() && (!$info->isReadOnly() || $this->is_dir($path));
483
+        } catch (NotFoundException $e) {
484
+            return false;
485
+        } catch (ForbiddenException $e) {
486
+            return false;
487
+        }
488
+    }
489
+
490
+    public function isDeletable($path) {
491
+        try {
492
+            $info = $this->getFileInfo($path);
493
+            return !$info->isHidden() && !$info->isReadOnly();
494
+        } catch (NotFoundException $e) {
495
+            return false;
496
+        } catch (ForbiddenException $e) {
497
+            return false;
498
+        }
499
+    }
500
+
501
+    /**
502
+     * check if smbclient is installed
503
+     */
504
+    public static function checkDependencies() {
505
+        return (
506
+            (bool)\OC_Helper::findBinaryPath('smbclient')
507
+            || Server::NativeAvailable()
508
+        ) ? true : ['smbclient'];
509
+    }
510
+
511
+    /**
512
+     * Test a storage for availability
513
+     *
514
+     * @return bool
515
+     */
516
+    public function test() {
517
+        try {
518
+            return parent::test();
519
+        } catch (Exception $e) {
520
+            return false;
521
+        }
522
+    }
523
+
524
+    public function listen($path, callable $callback) {
525
+        $this->notify($path)->listen(function (IChange $change) use ($callback) {
526
+            if ($change instanceof IRenameChange) {
527
+                return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
528
+            } else {
529
+                return $callback($change->getType(), $change->getPath());
530
+            }
531
+        });
532
+    }
533
+
534
+    public function notify($path) {
535
+        $path = '/' . ltrim($path, '/');
536
+        $shareNotifyHandler = $this->share->notify($this->buildPath($path));
537
+        return new SMBNotifyHandler($shareNotifyHandler, $this->root);
538
+    }
539 539
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Http/StreamResponse.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@
 block discarded – undo
37 37
 	private $filePath;
38 38
 
39 39
 	/**
40
-	 * @param string|resource $filePath the path to the file or a file handle which should be streamed
40
+	 * @param string $filePath the path to the file or a file handle which should be streamed
41 41
 	 * @since 8.1.0
42 42
 	 */
43 43
 	public function __construct ($filePath) {
Please login to merge, or discard this patch.
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -33,33 +33,33 @@
 block discarded – undo
33 33
  * @since 8.1.0
34 34
  */
35 35
 class StreamResponse extends Response implements ICallbackResponse {
36
-	/** @var string */
37
-	private $filePath;
36
+    /** @var string */
37
+    private $filePath;
38 38
 
39
-	/**
40
-	 * @param string|resource $filePath the path to the file or a file handle which should be streamed
41
-	 * @since 8.1.0
42
-	 */
43
-	public function __construct ($filePath) {
44
-		$this->filePath = $filePath;
45
-	}
39
+    /**
40
+     * @param string|resource $filePath the path to the file or a file handle which should be streamed
41
+     * @since 8.1.0
42
+     */
43
+    public function __construct ($filePath) {
44
+        $this->filePath = $filePath;
45
+    }
46 46
 
47 47
 
48
-	/**
49
-	 * Streams the file using readfile
50
-	 *
51
-	 * @param IOutput $output a small wrapper that handles output
52
-	 * @since 8.1.0
53
-	 */
54
-	public function callback (IOutput $output) {
55
-		// handle caching
56
-		if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
57
-			if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
58
-				$output->setHttpResponseCode(Http::STATUS_NOT_FOUND);
59
-			} elseif ($output->setReadfile($this->filePath) === false) {
60
-				$output->setHttpResponseCode(Http::STATUS_BAD_REQUEST);
61
-			}
62
-		}
63
-	}
48
+    /**
49
+     * Streams the file using readfile
50
+     *
51
+     * @param IOutput $output a small wrapper that handles output
52
+     * @since 8.1.0
53
+     */
54
+    public function callback (IOutput $output) {
55
+        // handle caching
56
+        if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
57
+            if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
58
+                $output->setHttpResponseCode(Http::STATUS_NOT_FOUND);
59
+            } elseif ($output->setReadfile($this->filePath) === false) {
60
+                $output->setHttpResponseCode(Http::STATUS_BAD_REQUEST);
61
+            }
62
+        }
63
+    }
64 64
 
65 65
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
 	 * @param string|resource $filePath the path to the file or a file handle which should be streamed
41 41
 	 * @since 8.1.0
42 42
 	 */
43
-	public function __construct ($filePath) {
43
+	public function __construct($filePath) {
44 44
 		$this->filePath = $filePath;
45 45
 	}
46 46
 
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
 	 * @param IOutput $output a small wrapper that handles output
52 52
 	 * @since 8.1.0
53 53
 	 */
54
-	public function callback (IOutput $output) {
54
+	public function callback(IOutput $output) {
55 55
 		// handle caching
56 56
 		if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
57 57
 			if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
Please login to merge, or discard this patch.