Completed
Push — master ( 57c5a1...72d3bf )
by Blizzz
32s
created
core/Controller/LoginController.php 1 patch
Indentation   +248 added lines, -248 removed lines patch added patch discarded remove patch
@@ -49,278 +49,278 @@
 block discarded – undo
49 49
 use OC\Hooks\PublicEmitter;
50 50
 
51 51
 class LoginController extends Controller {
52
-	/** @var IUserManager */
53
-	private $userManager;
54
-	/** @var IConfig */
55
-	private $config;
56
-	/** @var ISession */
57
-	private $session;
58
-	/** @var IUserSession|Session */
59
-	private $userSession;
60
-	/** @var IURLGenerator */
61
-	private $urlGenerator;
62
-	/** @var ILogger */
63
-	private $logger;
64
-	/** @var Manager */
65
-	private $twoFactorManager;
52
+    /** @var IUserManager */
53
+    private $userManager;
54
+    /** @var IConfig */
55
+    private $config;
56
+    /** @var ISession */
57
+    private $session;
58
+    /** @var IUserSession|Session */
59
+    private $userSession;
60
+    /** @var IURLGenerator */
61
+    private $urlGenerator;
62
+    /** @var ILogger */
63
+    private $logger;
64
+    /** @var Manager */
65
+    private $twoFactorManager;
66 66
 
67
-	/**
68
-	 * @param string $appName
69
-	 * @param IRequest $request
70
-	 * @param IUserManager $userManager
71
-	 * @param IConfig $config
72
-	 * @param ISession $session
73
-	 * @param IUserSession $userSession
74
-	 * @param IURLGenerator $urlGenerator
75
-	 * @param ILogger $logger
76
-	 * @param Manager $twoFactorManager
77
-	 */
78
-	public function __construct($appName,
79
-						 IRequest $request,
80
-						 IUserManager $userManager,
81
-						 IConfig $config,
82
-						 ISession $session,
83
-						 IUserSession $userSession,
84
-						 IURLGenerator $urlGenerator,
85
-						 ILogger $logger,
86
-						 Manager $twoFactorManager) {
87
-		parent::__construct($appName, $request);
88
-		$this->userManager = $userManager;
89
-		$this->config = $config;
90
-		$this->session = $session;
91
-		$this->userSession = $userSession;
92
-		$this->urlGenerator = $urlGenerator;
93
-		$this->logger = $logger;
94
-		$this->twoFactorManager = $twoFactorManager;
95
-	}
67
+    /**
68
+     * @param string $appName
69
+     * @param IRequest $request
70
+     * @param IUserManager $userManager
71
+     * @param IConfig $config
72
+     * @param ISession $session
73
+     * @param IUserSession $userSession
74
+     * @param IURLGenerator $urlGenerator
75
+     * @param ILogger $logger
76
+     * @param Manager $twoFactorManager
77
+     */
78
+    public function __construct($appName,
79
+                            IRequest $request,
80
+                            IUserManager $userManager,
81
+                            IConfig $config,
82
+                            ISession $session,
83
+                            IUserSession $userSession,
84
+                            IURLGenerator $urlGenerator,
85
+                            ILogger $logger,
86
+                            Manager $twoFactorManager) {
87
+        parent::__construct($appName, $request);
88
+        $this->userManager = $userManager;
89
+        $this->config = $config;
90
+        $this->session = $session;
91
+        $this->userSession = $userSession;
92
+        $this->urlGenerator = $urlGenerator;
93
+        $this->logger = $logger;
94
+        $this->twoFactorManager = $twoFactorManager;
95
+    }
96 96
 
97
-	/**
98
-	 * @NoAdminRequired
99
-	 * @UseSession
100
-	 *
101
-	 * @return RedirectResponse
102
-	 */
103
-	public function logout() {
104
-		$loginToken = $this->request->getCookie('nc_token');
105
-		if (!is_null($loginToken)) {
106
-			$this->config->deleteUserValue($this->userSession->getUser()->getUID(), 'login_token', $loginToken);
107
-		}
108
-		$this->userSession->logout();
97
+    /**
98
+     * @NoAdminRequired
99
+     * @UseSession
100
+     *
101
+     * @return RedirectResponse
102
+     */
103
+    public function logout() {
104
+        $loginToken = $this->request->getCookie('nc_token');
105
+        if (!is_null($loginToken)) {
106
+            $this->config->deleteUserValue($this->userSession->getUser()->getUID(), 'login_token', $loginToken);
107
+        }
108
+        $this->userSession->logout();
109 109
 
110
-		$response = new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
111
-		$response->addHeader('Clear-Site-Data', '"cache", "cookies", "storage", "executionContexts"');
112
-		return $response;
113
-	}
110
+        $response = new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
111
+        $response->addHeader('Clear-Site-Data', '"cache", "cookies", "storage", "executionContexts"');
112
+        return $response;
113
+    }
114 114
 
115
-	/**
116
-	 * @PublicPage
117
-	 * @NoCSRFRequired
118
-	 * @UseSession
119
-	 *
120
-	 * @param string $user
121
-	 * @param string $redirect_url
122
-	 * @param string $remember_login
123
-	 *
124
-	 * @return TemplateResponse|RedirectResponse
125
-	 */
126
-	public function showLoginForm($user, $redirect_url, $remember_login) {
127
-		if ($this->userSession->isLoggedIn()) {
128
-			return new RedirectResponse(OC_Util::getDefaultPageUrl());
129
-		}
115
+    /**
116
+     * @PublicPage
117
+     * @NoCSRFRequired
118
+     * @UseSession
119
+     *
120
+     * @param string $user
121
+     * @param string $redirect_url
122
+     * @param string $remember_login
123
+     *
124
+     * @return TemplateResponse|RedirectResponse
125
+     */
126
+    public function showLoginForm($user, $redirect_url, $remember_login) {
127
+        if ($this->userSession->isLoggedIn()) {
128
+            return new RedirectResponse(OC_Util::getDefaultPageUrl());
129
+        }
130 130
 
131
-		$parameters = array();
132
-		$loginMessages = $this->session->get('loginMessages');
133
-		$errors = [];
134
-		$messages = [];
135
-		if (is_array($loginMessages)) {
136
-			list($errors, $messages) = $loginMessages;
137
-		}
138
-		$this->session->remove('loginMessages');
139
-		foreach ($errors as $value) {
140
-			$parameters[$value] = true;
141
-		}
131
+        $parameters = array();
132
+        $loginMessages = $this->session->get('loginMessages');
133
+        $errors = [];
134
+        $messages = [];
135
+        if (is_array($loginMessages)) {
136
+            list($errors, $messages) = $loginMessages;
137
+        }
138
+        $this->session->remove('loginMessages');
139
+        foreach ($errors as $value) {
140
+            $parameters[$value] = true;
141
+        }
142 142
 
143
-		$parameters['messages'] = $messages;
144
-		if (!is_null($user) && $user !== '') {
145
-			$parameters['loginName'] = $user;
146
-			$parameters['user_autofocus'] = false;
147
-		} else {
148
-			$parameters['loginName'] = '';
149
-			$parameters['user_autofocus'] = true;
150
-		}
151
-		if (!empty($redirect_url)) {
152
-			$parameters['redirect_url'] = $redirect_url;
153
-		}
143
+        $parameters['messages'] = $messages;
144
+        if (!is_null($user) && $user !== '') {
145
+            $parameters['loginName'] = $user;
146
+            $parameters['user_autofocus'] = false;
147
+        } else {
148
+            $parameters['loginName'] = '';
149
+            $parameters['user_autofocus'] = true;
150
+        }
151
+        if (!empty($redirect_url)) {
152
+            $parameters['redirect_url'] = $redirect_url;
153
+        }
154 154
 
155
-		$parameters['canResetPassword'] = true;
156
-		$parameters['resetPasswordLink'] = $this->config->getSystemValue('lost_password_link', '');
157
-		if (!$parameters['resetPasswordLink']) {
158
-			if (!is_null($user) && $user !== '') {
159
-				$userObj = $this->userManager->get($user);
160
-				if ($userObj instanceof IUser) {
161
-					$parameters['canResetPassword'] = $userObj->canChangePassword();
162
-				}
163
-			}
164
-		} elseif ($parameters['resetPasswordLink'] === 'disabled') {
165
-			$parameters['canResetPassword'] = false;
166
-		}
155
+        $parameters['canResetPassword'] = true;
156
+        $parameters['resetPasswordLink'] = $this->config->getSystemValue('lost_password_link', '');
157
+        if (!$parameters['resetPasswordLink']) {
158
+            if (!is_null($user) && $user !== '') {
159
+                $userObj = $this->userManager->get($user);
160
+                if ($userObj instanceof IUser) {
161
+                    $parameters['canResetPassword'] = $userObj->canChangePassword();
162
+                }
163
+            }
164
+        } elseif ($parameters['resetPasswordLink'] === 'disabled') {
165
+            $parameters['canResetPassword'] = false;
166
+        }
167 167
 
168
-		$parameters['alt_login'] = OC_App::getAlternativeLogIns();
169
-		$parameters['rememberLoginState'] = !empty($remember_login) ? $remember_login : 0;
168
+        $parameters['alt_login'] = OC_App::getAlternativeLogIns();
169
+        $parameters['rememberLoginState'] = !empty($remember_login) ? $remember_login : 0;
170 170
 
171
-		if (!is_null($user) && $user !== '') {
172
-			$parameters['loginName'] = $user;
173
-			$parameters['user_autofocus'] = false;
174
-		} else {
175
-			$parameters['loginName'] = '';
176
-			$parameters['user_autofocus'] = true;
177
-		}
171
+        if (!is_null($user) && $user !== '') {
172
+            $parameters['loginName'] = $user;
173
+            $parameters['user_autofocus'] = false;
174
+        } else {
175
+            $parameters['loginName'] = '';
176
+            $parameters['user_autofocus'] = true;
177
+        }
178 178
 
179
-		return new TemplateResponse(
180
-			$this->appName, 'login', $parameters, 'guest'
181
-		);
182
-	}
179
+        return new TemplateResponse(
180
+            $this->appName, 'login', $parameters, 'guest'
181
+        );
182
+    }
183 183
 
184
-	/**
185
-	 * @param string $redirectUrl
186
-	 * @return RedirectResponse
187
-	 */
188
-	private function generateRedirect($redirectUrl) {
189
-		if (!is_null($redirectUrl) && $this->userSession->isLoggedIn()) {
190
-			$location = $this->urlGenerator->getAbsoluteURL(urldecode($redirectUrl));
191
-			// Deny the redirect if the URL contains a @
192
-			// This prevents unvalidated redirects like ?redirect_url=:[email protected]
193
-			if (strpos($location, '@') === false) {
194
-				return new RedirectResponse($location);
195
-			}
196
-		}
197
-		return new RedirectResponse(OC_Util::getDefaultPageUrl());
198
-	}
184
+    /**
185
+     * @param string $redirectUrl
186
+     * @return RedirectResponse
187
+     */
188
+    private function generateRedirect($redirectUrl) {
189
+        if (!is_null($redirectUrl) && $this->userSession->isLoggedIn()) {
190
+            $location = $this->urlGenerator->getAbsoluteURL(urldecode($redirectUrl));
191
+            // Deny the redirect if the URL contains a @
192
+            // This prevents unvalidated redirects like ?redirect_url=:[email protected]
193
+            if (strpos($location, '@') === false) {
194
+                return new RedirectResponse($location);
195
+            }
196
+        }
197
+        return new RedirectResponse(OC_Util::getDefaultPageUrl());
198
+    }
199 199
 
200
-	/**
201
-	 * @PublicPage
202
-	 * @UseSession
203
-	 * @NoCSRFRequired
204
-	 * @BruteForceProtection(action=login)
205
-	 *
206
-	 * @param string $user
207
-	 * @param string $password
208
-	 * @param string $redirect_url
209
-	 * @param boolean $remember_login
210
-	 * @param string $timezone
211
-	 * @param string $timezone_offset
212
-	 * @return RedirectResponse
213
-	 */
214
-	public function tryLogin($user, $password, $redirect_url, $remember_login = false, $timezone = '', $timezone_offset = '') {
215
-		if(!is_string($user)) {
216
-			throw new \InvalidArgumentException('Username must be string');
217
-		}
200
+    /**
201
+     * @PublicPage
202
+     * @UseSession
203
+     * @NoCSRFRequired
204
+     * @BruteForceProtection(action=login)
205
+     *
206
+     * @param string $user
207
+     * @param string $password
208
+     * @param string $redirect_url
209
+     * @param boolean $remember_login
210
+     * @param string $timezone
211
+     * @param string $timezone_offset
212
+     * @return RedirectResponse
213
+     */
214
+    public function tryLogin($user, $password, $redirect_url, $remember_login = false, $timezone = '', $timezone_offset = '') {
215
+        if(!is_string($user)) {
216
+            throw new \InvalidArgumentException('Username must be string');
217
+        }
218 218
 
219
-		// If the user is already logged in and the CSRF check does not pass then
220
-		// simply redirect the user to the correct page as required. This is the
221
-		// case when an user has already logged-in, in another tab.
222
-		if(!$this->request->passesCSRFCheck()) {
223
-			return $this->generateRedirect($redirect_url);
224
-		}
219
+        // If the user is already logged in and the CSRF check does not pass then
220
+        // simply redirect the user to the correct page as required. This is the
221
+        // case when an user has already logged-in, in another tab.
222
+        if(!$this->request->passesCSRFCheck()) {
223
+            return $this->generateRedirect($redirect_url);
224
+        }
225 225
 
226
-		if ($this->userManager instanceof PublicEmitter) {
227
-			$this->userManager->emit('\OC\User', 'preLogin', array($user, $password));
228
-		}
226
+        if ($this->userManager instanceof PublicEmitter) {
227
+            $this->userManager->emit('\OC\User', 'preLogin', array($user, $password));
228
+        }
229 229
 
230
-		$originalUser = $user;
231
-		// TODO: Add all the insane error handling
232
-		/* @var $loginResult IUser */
233
-		$loginResult = $this->userManager->checkPasswordNoLogging($user, $password);
234
-		if ($loginResult === false) {
235
-			$users = $this->userManager->getByEmail($user);
236
-			// we only allow login by email if unique
237
-			if (count($users) === 1) {
238
-				$user = $users[0]->getUID();
239
-				$loginResult = $this->userManager->checkPassword($user, $password);
240
-			} else {
241
-				$this->logger->warning('Login failed: \''. $user .'\' (Remote IP: \''. $this->request->getRemoteAddress(). '\')', ['app' => 'core']);
242
-			}
243
-		}
244
-		if ($loginResult === false) {
245
-			// Read current user and append if possible - we need to return the unmodified user otherwise we will leak the login name
246
-			$args = !is_null($user) ? ['user' => $originalUser] : [];
247
-			if (!is_null($redirect_url)) {
248
-				$args['redirect_url'] = $redirect_url;
249
-			}
250
-			$response = new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args));
251
-			$response->throttle();
252
-			$this->session->set('loginMessages', [
253
-				['invalidpassword'], []
254
-			]);
255
-			return $response;
256
-		}
257
-		// TODO: remove password checks from above and let the user session handle failures
258
-		// requires https://github.com/owncloud/core/pull/24616
259
-		$this->userSession->completeLogin($loginResult, ['loginName' => $user, 'password' => $password]);
260
-		$this->userSession->createSessionToken($this->request, $loginResult->getUID(), $user, $password, (int)$remember_login);
230
+        $originalUser = $user;
231
+        // TODO: Add all the insane error handling
232
+        /* @var $loginResult IUser */
233
+        $loginResult = $this->userManager->checkPasswordNoLogging($user, $password);
234
+        if ($loginResult === false) {
235
+            $users = $this->userManager->getByEmail($user);
236
+            // we only allow login by email if unique
237
+            if (count($users) === 1) {
238
+                $user = $users[0]->getUID();
239
+                $loginResult = $this->userManager->checkPassword($user, $password);
240
+            } else {
241
+                $this->logger->warning('Login failed: \''. $user .'\' (Remote IP: \''. $this->request->getRemoteAddress(). '\')', ['app' => 'core']);
242
+            }
243
+        }
244
+        if ($loginResult === false) {
245
+            // Read current user and append if possible - we need to return the unmodified user otherwise we will leak the login name
246
+            $args = !is_null($user) ? ['user' => $originalUser] : [];
247
+            if (!is_null($redirect_url)) {
248
+                $args['redirect_url'] = $redirect_url;
249
+            }
250
+            $response = new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args));
251
+            $response->throttle();
252
+            $this->session->set('loginMessages', [
253
+                ['invalidpassword'], []
254
+            ]);
255
+            return $response;
256
+        }
257
+        // TODO: remove password checks from above and let the user session handle failures
258
+        // requires https://github.com/owncloud/core/pull/24616
259
+        $this->userSession->completeLogin($loginResult, ['loginName' => $user, 'password' => $password]);
260
+        $this->userSession->createSessionToken($this->request, $loginResult->getUID(), $user, $password, (int)$remember_login);
261 261
 
262
-		// User has successfully logged in, now remove the password reset link, when it is available
263
-		$this->config->deleteUserValue($loginResult->getUID(), 'core', 'lostpassword');
262
+        // User has successfully logged in, now remove the password reset link, when it is available
263
+        $this->config->deleteUserValue($loginResult->getUID(), 'core', 'lostpassword');
264 264
 
265
-		$this->session->set('last-password-confirm', $loginResult->getLastLogin());
265
+        $this->session->set('last-password-confirm', $loginResult->getLastLogin());
266 266
 
267
-		if ($timezone_offset !== '') {
268
-			$this->config->setUserValue($loginResult->getUID(), 'core', 'timezone', $timezone);
269
-			$this->session->set('timezone', $timezone_offset);
270
-		}
267
+        if ($timezone_offset !== '') {
268
+            $this->config->setUserValue($loginResult->getUID(), 'core', 'timezone', $timezone);
269
+            $this->session->set('timezone', $timezone_offset);
270
+        }
271 271
 
272
-		if ($this->twoFactorManager->isTwoFactorAuthenticated($loginResult)) {
273
-			$this->twoFactorManager->prepareTwoFactorLogin($loginResult, $remember_login);
272
+        if ($this->twoFactorManager->isTwoFactorAuthenticated($loginResult)) {
273
+            $this->twoFactorManager->prepareTwoFactorLogin($loginResult, $remember_login);
274 274
 
275
-			$providers = $this->twoFactorManager->getProviders($loginResult);
276
-			if (count($providers) === 1) {
277
-				// Single provider, hence we can redirect to that provider's challenge page directly
278
-				/* @var $provider IProvider */
279
-				$provider = array_pop($providers);
280
-				$url = 'core.TwoFactorChallenge.showChallenge';
281
-				$urlParams = [
282
-					'challengeProviderId' => $provider->getId(),
283
-				];
284
-			} else {
285
-				$url = 'core.TwoFactorChallenge.selectChallenge';
286
-				$urlParams = [];
287
-			}
275
+            $providers = $this->twoFactorManager->getProviders($loginResult);
276
+            if (count($providers) === 1) {
277
+                // Single provider, hence we can redirect to that provider's challenge page directly
278
+                /* @var $provider IProvider */
279
+                $provider = array_pop($providers);
280
+                $url = 'core.TwoFactorChallenge.showChallenge';
281
+                $urlParams = [
282
+                    'challengeProviderId' => $provider->getId(),
283
+                ];
284
+            } else {
285
+                $url = 'core.TwoFactorChallenge.selectChallenge';
286
+                $urlParams = [];
287
+            }
288 288
 
289
-			if (!is_null($redirect_url)) {
290
-				$urlParams['redirect_url'] = $redirect_url;
291
-			}
289
+            if (!is_null($redirect_url)) {
290
+                $urlParams['redirect_url'] = $redirect_url;
291
+            }
292 292
 
293
-			return new RedirectResponse($this->urlGenerator->linkToRoute($url, $urlParams));
294
-		}
293
+            return new RedirectResponse($this->urlGenerator->linkToRoute($url, $urlParams));
294
+        }
295 295
 
296
-		if ($remember_login) {
297
-			$this->userSession->createRememberMeToken($loginResult);
298
-		}
296
+        if ($remember_login) {
297
+            $this->userSession->createRememberMeToken($loginResult);
298
+        }
299 299
 
300
-		return $this->generateRedirect($redirect_url);
301
-	}
300
+        return $this->generateRedirect($redirect_url);
301
+    }
302 302
 
303
-	/**
304
-	 * @NoAdminRequired
305
-	 * @UseSession
306
-	 * @BruteForceProtection(action=sudo)
307
-	 *
308
-	 * @license GNU AGPL version 3 or any later version
309
-	 *
310
-	 * @param string $password
311
-	 * @return DataResponse
312
-	 */
313
-	public function confirmPassword($password) {
314
-		$loginName = $this->userSession->getLoginName();
315
-		$loginResult = $this->userManager->checkPassword($loginName, $password);
316
-		if ($loginResult === false) {
317
-			$response = new DataResponse([], Http::STATUS_FORBIDDEN);
318
-			$response->throttle();
319
-			return $response;
320
-		}
303
+    /**
304
+     * @NoAdminRequired
305
+     * @UseSession
306
+     * @BruteForceProtection(action=sudo)
307
+     *
308
+     * @license GNU AGPL version 3 or any later version
309
+     *
310
+     * @param string $password
311
+     * @return DataResponse
312
+     */
313
+    public function confirmPassword($password) {
314
+        $loginName = $this->userSession->getLoginName();
315
+        $loginResult = $this->userManager->checkPassword($loginName, $password);
316
+        if ($loginResult === false) {
317
+            $response = new DataResponse([], Http::STATUS_FORBIDDEN);
318
+            $response->throttle();
319
+            return $response;
320
+        }
321 321
 
322
-		$confirmTimestamp = time();
323
-		$this->session->set('last-password-confirm', $confirmTimestamp);
324
-		return new DataResponse(['lastLogin' => $confirmTimestamp], Http::STATUS_OK);
325
-	}
322
+        $confirmTimestamp = time();
323
+        $this->session->set('last-password-confirm', $confirmTimestamp);
324
+        return new DataResponse(['lastLogin' => $confirmTimestamp], Http::STATUS_OK);
325
+    }
326 326
 }
Please login to merge, or discard this patch.
lib/private/Files/ObjectStore/ObjectStoreStorage.php 2 patches
Indentation   +386 added lines, -386 removed lines patch added patch discarded remove patch
@@ -31,390 +31,390 @@
 block discarded – undo
31 31
 use OCP\Files\ObjectStore\IObjectStore;
32 32
 
33 33
 class ObjectStoreStorage extends \OC\Files\Storage\Common {
34
-	/**
35
-	 * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
36
-	 */
37
-	protected $objectStore;
38
-	/**
39
-	 * @var string $id
40
-	 */
41
-	protected $id;
42
-	/**
43
-	 * @var \OC\User\User $user
44
-	 */
45
-	protected $user;
46
-
47
-	private $objectPrefix = 'urn:oid:';
48
-
49
-	private $logger;
50
-
51
-	public function __construct($params) {
52
-		if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
53
-			$this->objectStore = $params['objectstore'];
54
-		} else {
55
-			throw new \Exception('missing IObjectStore instance');
56
-		}
57
-		if (isset($params['storageid'])) {
58
-			$this->id = 'object::store:' . $params['storageid'];
59
-		} else {
60
-			$this->id = 'object::store:' . $this->objectStore->getStorageId();
61
-		}
62
-		if (isset($params['objectPrefix'])) {
63
-			$this->objectPrefix = $params['objectPrefix'];
64
-		}
65
-		//initialize cache with root directory in cache
66
-		if (!$this->is_dir('/')) {
67
-			$this->mkdir('/');
68
-		}
69
-
70
-		$this->logger = \OC::$server->getLogger();
71
-	}
72
-
73
-	public function mkdir($path) {
74
-		$path = $this->normalizePath($path);
75
-
76
-		if ($this->file_exists($path)) {
77
-			return false;
78
-		}
79
-
80
-		$mTime = time();
81
-		$data = [
82
-			'mimetype' => 'httpd/unix-directory',
83
-			'size' => 0,
84
-			'mtime' => $mTime,
85
-			'storage_mtime' => $mTime,
86
-			'permissions' => \OCP\Constants::PERMISSION_ALL,
87
-		];
88
-		if ($path === '') {
89
-			//create root on the fly
90
-			$data['etag'] = $this->getETag('');
91
-			$this->getCache()->put('', $data);
92
-			return true;
93
-		} else {
94
-			// if parent does not exist, create it
95
-			$parent = $this->normalizePath(dirname($path));
96
-			$parentType = $this->filetype($parent);
97
-			if ($parentType === false) {
98
-				if (!$this->mkdir($parent)) {
99
-					// something went wrong
100
-					return false;
101
-				}
102
-			} else if ($parentType === 'file') {
103
-				// parent is a file
104
-				return false;
105
-			}
106
-			// finally create the new dir
107
-			$mTime = time(); // update mtime
108
-			$data['mtime'] = $mTime;
109
-			$data['storage_mtime'] = $mTime;
110
-			$data['etag'] = $this->getETag($path);
111
-			$this->getCache()->put($path, $data);
112
-			return true;
113
-		}
114
-	}
115
-
116
-	/**
117
-	 * @param string $path
118
-	 * @return string
119
-	 */
120
-	private function normalizePath($path) {
121
-		$path = trim($path, '/');
122
-		//FIXME why do we sometimes get a path like 'files//username'?
123
-		$path = str_replace('//', '/', $path);
124
-
125
-		// dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
126
-		if (!$path || $path === '.') {
127
-			$path = '';
128
-		}
129
-
130
-		return $path;
131
-	}
132
-
133
-	/**
134
-	 * Object Stores use a NoopScanner because metadata is directly stored in
135
-	 * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
136
-	 *
137
-	 * @param string $path
138
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
139
-	 * @return \OC\Files\ObjectStore\NoopScanner
140
-	 */
141
-	public function getScanner($path = '', $storage = null) {
142
-		if (!$storage) {
143
-			$storage = $this;
144
-		}
145
-		if (!isset($this->scanner)) {
146
-			$this->scanner = new NoopScanner($storage);
147
-		}
148
-		return $this->scanner;
149
-	}
150
-
151
-	public function getId() {
152
-		return $this->id;
153
-	}
154
-
155
-	public function rmdir($path) {
156
-		$path = $this->normalizePath($path);
157
-
158
-		if (!$this->is_dir($path)) {
159
-			return false;
160
-		}
161
-
162
-		$this->rmObjects($path);
163
-
164
-		$this->getCache()->remove($path);
165
-
166
-		return true;
167
-	}
168
-
169
-	private function rmObjects($path) {
170
-		$children = $this->getCache()->getFolderContents($path);
171
-		foreach ($children as $child) {
172
-			if ($child['mimetype'] === 'httpd/unix-directory') {
173
-				$this->rmObjects($child['path']);
174
-			} else {
175
-				$this->unlink($child['path']);
176
-			}
177
-		}
178
-	}
179
-
180
-	public function unlink($path) {
181
-		$path = $this->normalizePath($path);
182
-		$stat = $this->stat($path);
183
-
184
-		if ($stat && isset($stat['fileid'])) {
185
-			if ($stat['mimetype'] === 'httpd/unix-directory') {
186
-				return $this->rmdir($path);
187
-			}
188
-			try {
189
-				$this->objectStore->deleteObject($this->getURN($stat['fileid']));
190
-			} catch (\Exception $ex) {
191
-				if ($ex->getCode() !== 404) {
192
-					$this->logger->logException($ex, [
193
-						'app' => 'objectstore',
194
-						'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
195
-					]);
196
-					return false;
197
-				} else {
198
-					//removing from cache is ok as it does not exist in the objectstore anyway
199
-				}
200
-			}
201
-			$this->getCache()->remove($path);
202
-			return true;
203
-		}
204
-		return false;
205
-	}
206
-
207
-	public function stat($path) {
208
-		$path = $this->normalizePath($path);
209
-		$cacheEntry = $this->getCache()->get($path);
210
-		if ($cacheEntry instanceof CacheEntry) {
211
-			return $cacheEntry->getData();
212
-		} else {
213
-			return false;
214
-		}
215
-	}
216
-
217
-	/**
218
-	 * Override this method if you need a different unique resource identifier for your object storage implementation.
219
-	 * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
220
-	 * You may need a mapping table to store your URN if it cannot be generated from the fileid.
221
-	 *
222
-	 * @param int $fileId the fileid
223
-	 * @return null|string the unified resource name used to identify the object
224
-	 */
225
-	protected function getURN($fileId) {
226
-		if (is_numeric($fileId)) {
227
-			return $this->objectPrefix . $fileId;
228
-		}
229
-		return null;
230
-	}
231
-
232
-	public function opendir($path) {
233
-		$path = $this->normalizePath($path);
234
-
235
-		try {
236
-			$files = array();
237
-			$folderContents = $this->getCache()->getFolderContents($path);
238
-			foreach ($folderContents as $file) {
239
-				$files[] = $file['name'];
240
-			}
241
-
242
-			return IteratorDirectory::wrap($files);
243
-		} catch (\Exception $e) {
244
-			$this->logger->logException($e);
245
-			return false;
246
-		}
247
-	}
248
-
249
-	public function filetype($path) {
250
-		$path = $this->normalizePath($path);
251
-		$stat = $this->stat($path);
252
-		if ($stat) {
253
-			if ($stat['mimetype'] === 'httpd/unix-directory') {
254
-				return 'dir';
255
-			}
256
-			return 'file';
257
-		} else {
258
-			return false;
259
-		}
260
-	}
261
-
262
-	public function fopen($path, $mode) {
263
-		$path = $this->normalizePath($path);
264
-
265
-		switch ($mode) {
266
-			case 'r':
267
-			case 'rb':
268
-				$stat = $this->stat($path);
269
-				if (is_array($stat)) {
270
-					try {
271
-						return $this->objectStore->readObject($this->getURN($stat['fileid']));
272
-					} catch (\Exception $ex) {
273
-						$this->logger->logException($ex, [
274
-							'app' => 'objectstore',
275
-							'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
276
-						]);
277
-						return false;
278
-					}
279
-				} else {
280
-					return false;
281
-				}
282
-			case 'w':
283
-			case 'wb':
284
-			case 'a':
285
-			case 'ab':
286
-			case 'r+':
287
-			case 'w+':
288
-			case 'wb+':
289
-			case 'a+':
290
-			case 'x':
291
-			case 'x+':
292
-			case 'c':
293
-			case 'c+':
294
-				if (strrpos($path, '.') !== false) {
295
-					$ext = substr($path, strrpos($path, '.'));
296
-				} else {
297
-					$ext = '';
298
-				}
299
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
300
-				if ($this->file_exists($path)) {
301
-					$source = $this->fopen($path, 'r');
302
-					file_put_contents($tmpFile, $source);
303
-				}
304
-				$handle = fopen($tmpFile, $mode);
305
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
306
-					$this->writeBack($tmpFile, $path);
307
-				});
308
-		}
309
-		return false;
310
-	}
311
-
312
-	public function file_exists($path) {
313
-		$path = $this->normalizePath($path);
314
-		return (bool)$this->stat($path);
315
-	}
316
-
317
-	public function rename($source, $target) {
318
-		$source = $this->normalizePath($source);
319
-		$target = $this->normalizePath($target);
320
-		$this->remove($target);
321
-		$this->getCache()->move($source, $target);
322
-		$this->touch(dirname($target));
323
-		return true;
324
-	}
325
-
326
-	public function getMimeType($path) {
327
-		$path = $this->normalizePath($path);
328
-		$stat = $this->stat($path);
329
-		if (is_array($stat)) {
330
-			return $stat['mimetype'];
331
-		} else {
332
-			return false;
333
-		}
334
-	}
335
-
336
-	public function touch($path, $mtime = null) {
337
-		if (is_null($mtime)) {
338
-			$mtime = time();
339
-		}
340
-
341
-		$path = $this->normalizePath($path);
342
-		$dirName = dirname($path);
343
-		$parentExists = $this->is_dir($dirName);
344
-		if (!$parentExists) {
345
-			return false;
346
-		}
347
-
348
-		$stat = $this->stat($path);
349
-		if (is_array($stat)) {
350
-			// update existing mtime in db
351
-			$stat['mtime'] = $mtime;
352
-			$this->getCache()->update($stat['fileid'], $stat);
353
-		} else {
354
-			$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
355
-			// create new file
356
-			$stat = array(
357
-				'etag' => $this->getETag($path),
358
-				'mimetype' => $mimeType,
359
-				'size' => 0,
360
-				'mtime' => $mtime,
361
-				'storage_mtime' => $mtime,
362
-				'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
363
-			);
364
-			$fileId = $this->getCache()->put($path, $stat);
365
-			try {
366
-				//read an empty file from memory
367
-				$this->objectStore->writeObject($this->getURN($fileId), fopen('php://memory', 'r'));
368
-			} catch (\Exception $ex) {
369
-				$this->getCache()->remove($path);
370
-				$this->logger->logException($ex, [
371
-					'app' => 'objectstore',
372
-					'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
373
-				]);
374
-				return false;
375
-			}
376
-		}
377
-		return true;
378
-	}
379
-
380
-	public function writeBack($tmpFile, $path) {
381
-		$stat = $this->stat($path);
382
-		if (empty($stat)) {
383
-			// create new file
384
-			$stat = array(
385
-				'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
386
-			);
387
-		}
388
-		// update stat with new data
389
-		$mTime = time();
390
-		$stat['size'] = filesize($tmpFile);
391
-		$stat['mtime'] = $mTime;
392
-		$stat['storage_mtime'] = $mTime;
393
-		$stat['mimetype'] = \OC::$server->getMimeTypeDetector()->detect($tmpFile);
394
-		$stat['etag'] = $this->getETag($path);
395
-
396
-		$fileId = $this->getCache()->put($path, $stat);
397
-		try {
398
-			//upload to object storage
399
-			$this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
400
-		} catch (\Exception $ex) {
401
-			$this->getCache()->remove($path);
402
-			$this->logger->logException($ex, [
403
-				'app' => 'objectstore',
404
-				'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
405
-			]);
406
-			throw $ex; // make this bubble up
407
-		}
408
-	}
409
-
410
-	/**
411
-	 * external changes are not supported, exclusive access to the object storage is assumed
412
-	 *
413
-	 * @param string $path
414
-	 * @param int $time
415
-	 * @return false
416
-	 */
417
-	public function hasUpdated($path, $time) {
418
-		return false;
419
-	}
34
+    /**
35
+     * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
36
+     */
37
+    protected $objectStore;
38
+    /**
39
+     * @var string $id
40
+     */
41
+    protected $id;
42
+    /**
43
+     * @var \OC\User\User $user
44
+     */
45
+    protected $user;
46
+
47
+    private $objectPrefix = 'urn:oid:';
48
+
49
+    private $logger;
50
+
51
+    public function __construct($params) {
52
+        if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
53
+            $this->objectStore = $params['objectstore'];
54
+        } else {
55
+            throw new \Exception('missing IObjectStore instance');
56
+        }
57
+        if (isset($params['storageid'])) {
58
+            $this->id = 'object::store:' . $params['storageid'];
59
+        } else {
60
+            $this->id = 'object::store:' . $this->objectStore->getStorageId();
61
+        }
62
+        if (isset($params['objectPrefix'])) {
63
+            $this->objectPrefix = $params['objectPrefix'];
64
+        }
65
+        //initialize cache with root directory in cache
66
+        if (!$this->is_dir('/')) {
67
+            $this->mkdir('/');
68
+        }
69
+
70
+        $this->logger = \OC::$server->getLogger();
71
+    }
72
+
73
+    public function mkdir($path) {
74
+        $path = $this->normalizePath($path);
75
+
76
+        if ($this->file_exists($path)) {
77
+            return false;
78
+        }
79
+
80
+        $mTime = time();
81
+        $data = [
82
+            'mimetype' => 'httpd/unix-directory',
83
+            'size' => 0,
84
+            'mtime' => $mTime,
85
+            'storage_mtime' => $mTime,
86
+            'permissions' => \OCP\Constants::PERMISSION_ALL,
87
+        ];
88
+        if ($path === '') {
89
+            //create root on the fly
90
+            $data['etag'] = $this->getETag('');
91
+            $this->getCache()->put('', $data);
92
+            return true;
93
+        } else {
94
+            // if parent does not exist, create it
95
+            $parent = $this->normalizePath(dirname($path));
96
+            $parentType = $this->filetype($parent);
97
+            if ($parentType === false) {
98
+                if (!$this->mkdir($parent)) {
99
+                    // something went wrong
100
+                    return false;
101
+                }
102
+            } else if ($parentType === 'file') {
103
+                // parent is a file
104
+                return false;
105
+            }
106
+            // finally create the new dir
107
+            $mTime = time(); // update mtime
108
+            $data['mtime'] = $mTime;
109
+            $data['storage_mtime'] = $mTime;
110
+            $data['etag'] = $this->getETag($path);
111
+            $this->getCache()->put($path, $data);
112
+            return true;
113
+        }
114
+    }
115
+
116
+    /**
117
+     * @param string $path
118
+     * @return string
119
+     */
120
+    private function normalizePath($path) {
121
+        $path = trim($path, '/');
122
+        //FIXME why do we sometimes get a path like 'files//username'?
123
+        $path = str_replace('//', '/', $path);
124
+
125
+        // dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
126
+        if (!$path || $path === '.') {
127
+            $path = '';
128
+        }
129
+
130
+        return $path;
131
+    }
132
+
133
+    /**
134
+     * Object Stores use a NoopScanner because metadata is directly stored in
135
+     * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
136
+     *
137
+     * @param string $path
138
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
139
+     * @return \OC\Files\ObjectStore\NoopScanner
140
+     */
141
+    public function getScanner($path = '', $storage = null) {
142
+        if (!$storage) {
143
+            $storage = $this;
144
+        }
145
+        if (!isset($this->scanner)) {
146
+            $this->scanner = new NoopScanner($storage);
147
+        }
148
+        return $this->scanner;
149
+    }
150
+
151
+    public function getId() {
152
+        return $this->id;
153
+    }
154
+
155
+    public function rmdir($path) {
156
+        $path = $this->normalizePath($path);
157
+
158
+        if (!$this->is_dir($path)) {
159
+            return false;
160
+        }
161
+
162
+        $this->rmObjects($path);
163
+
164
+        $this->getCache()->remove($path);
165
+
166
+        return true;
167
+    }
168
+
169
+    private function rmObjects($path) {
170
+        $children = $this->getCache()->getFolderContents($path);
171
+        foreach ($children as $child) {
172
+            if ($child['mimetype'] === 'httpd/unix-directory') {
173
+                $this->rmObjects($child['path']);
174
+            } else {
175
+                $this->unlink($child['path']);
176
+            }
177
+        }
178
+    }
179
+
180
+    public function unlink($path) {
181
+        $path = $this->normalizePath($path);
182
+        $stat = $this->stat($path);
183
+
184
+        if ($stat && isset($stat['fileid'])) {
185
+            if ($stat['mimetype'] === 'httpd/unix-directory') {
186
+                return $this->rmdir($path);
187
+            }
188
+            try {
189
+                $this->objectStore->deleteObject($this->getURN($stat['fileid']));
190
+            } catch (\Exception $ex) {
191
+                if ($ex->getCode() !== 404) {
192
+                    $this->logger->logException($ex, [
193
+                        'app' => 'objectstore',
194
+                        'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
195
+                    ]);
196
+                    return false;
197
+                } else {
198
+                    //removing from cache is ok as it does not exist in the objectstore anyway
199
+                }
200
+            }
201
+            $this->getCache()->remove($path);
202
+            return true;
203
+        }
204
+        return false;
205
+    }
206
+
207
+    public function stat($path) {
208
+        $path = $this->normalizePath($path);
209
+        $cacheEntry = $this->getCache()->get($path);
210
+        if ($cacheEntry instanceof CacheEntry) {
211
+            return $cacheEntry->getData();
212
+        } else {
213
+            return false;
214
+        }
215
+    }
216
+
217
+    /**
218
+     * Override this method if you need a different unique resource identifier for your object storage implementation.
219
+     * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
220
+     * You may need a mapping table to store your URN if it cannot be generated from the fileid.
221
+     *
222
+     * @param int $fileId the fileid
223
+     * @return null|string the unified resource name used to identify the object
224
+     */
225
+    protected function getURN($fileId) {
226
+        if (is_numeric($fileId)) {
227
+            return $this->objectPrefix . $fileId;
228
+        }
229
+        return null;
230
+    }
231
+
232
+    public function opendir($path) {
233
+        $path = $this->normalizePath($path);
234
+
235
+        try {
236
+            $files = array();
237
+            $folderContents = $this->getCache()->getFolderContents($path);
238
+            foreach ($folderContents as $file) {
239
+                $files[] = $file['name'];
240
+            }
241
+
242
+            return IteratorDirectory::wrap($files);
243
+        } catch (\Exception $e) {
244
+            $this->logger->logException($e);
245
+            return false;
246
+        }
247
+    }
248
+
249
+    public function filetype($path) {
250
+        $path = $this->normalizePath($path);
251
+        $stat = $this->stat($path);
252
+        if ($stat) {
253
+            if ($stat['mimetype'] === 'httpd/unix-directory') {
254
+                return 'dir';
255
+            }
256
+            return 'file';
257
+        } else {
258
+            return false;
259
+        }
260
+    }
261
+
262
+    public function fopen($path, $mode) {
263
+        $path = $this->normalizePath($path);
264
+
265
+        switch ($mode) {
266
+            case 'r':
267
+            case 'rb':
268
+                $stat = $this->stat($path);
269
+                if (is_array($stat)) {
270
+                    try {
271
+                        return $this->objectStore->readObject($this->getURN($stat['fileid']));
272
+                    } catch (\Exception $ex) {
273
+                        $this->logger->logException($ex, [
274
+                            'app' => 'objectstore',
275
+                            'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
276
+                        ]);
277
+                        return false;
278
+                    }
279
+                } else {
280
+                    return false;
281
+                }
282
+            case 'w':
283
+            case 'wb':
284
+            case 'a':
285
+            case 'ab':
286
+            case 'r+':
287
+            case 'w+':
288
+            case 'wb+':
289
+            case 'a+':
290
+            case 'x':
291
+            case 'x+':
292
+            case 'c':
293
+            case 'c+':
294
+                if (strrpos($path, '.') !== false) {
295
+                    $ext = substr($path, strrpos($path, '.'));
296
+                } else {
297
+                    $ext = '';
298
+                }
299
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
300
+                if ($this->file_exists($path)) {
301
+                    $source = $this->fopen($path, 'r');
302
+                    file_put_contents($tmpFile, $source);
303
+                }
304
+                $handle = fopen($tmpFile, $mode);
305
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
306
+                    $this->writeBack($tmpFile, $path);
307
+                });
308
+        }
309
+        return false;
310
+    }
311
+
312
+    public function file_exists($path) {
313
+        $path = $this->normalizePath($path);
314
+        return (bool)$this->stat($path);
315
+    }
316
+
317
+    public function rename($source, $target) {
318
+        $source = $this->normalizePath($source);
319
+        $target = $this->normalizePath($target);
320
+        $this->remove($target);
321
+        $this->getCache()->move($source, $target);
322
+        $this->touch(dirname($target));
323
+        return true;
324
+    }
325
+
326
+    public function getMimeType($path) {
327
+        $path = $this->normalizePath($path);
328
+        $stat = $this->stat($path);
329
+        if (is_array($stat)) {
330
+            return $stat['mimetype'];
331
+        } else {
332
+            return false;
333
+        }
334
+    }
335
+
336
+    public function touch($path, $mtime = null) {
337
+        if (is_null($mtime)) {
338
+            $mtime = time();
339
+        }
340
+
341
+        $path = $this->normalizePath($path);
342
+        $dirName = dirname($path);
343
+        $parentExists = $this->is_dir($dirName);
344
+        if (!$parentExists) {
345
+            return false;
346
+        }
347
+
348
+        $stat = $this->stat($path);
349
+        if (is_array($stat)) {
350
+            // update existing mtime in db
351
+            $stat['mtime'] = $mtime;
352
+            $this->getCache()->update($stat['fileid'], $stat);
353
+        } else {
354
+            $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
355
+            // create new file
356
+            $stat = array(
357
+                'etag' => $this->getETag($path),
358
+                'mimetype' => $mimeType,
359
+                'size' => 0,
360
+                'mtime' => $mtime,
361
+                'storage_mtime' => $mtime,
362
+                'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
363
+            );
364
+            $fileId = $this->getCache()->put($path, $stat);
365
+            try {
366
+                //read an empty file from memory
367
+                $this->objectStore->writeObject($this->getURN($fileId), fopen('php://memory', 'r'));
368
+            } catch (\Exception $ex) {
369
+                $this->getCache()->remove($path);
370
+                $this->logger->logException($ex, [
371
+                    'app' => 'objectstore',
372
+                    'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
373
+                ]);
374
+                return false;
375
+            }
376
+        }
377
+        return true;
378
+    }
379
+
380
+    public function writeBack($tmpFile, $path) {
381
+        $stat = $this->stat($path);
382
+        if (empty($stat)) {
383
+            // create new file
384
+            $stat = array(
385
+                'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
386
+            );
387
+        }
388
+        // update stat with new data
389
+        $mTime = time();
390
+        $stat['size'] = filesize($tmpFile);
391
+        $stat['mtime'] = $mTime;
392
+        $stat['storage_mtime'] = $mTime;
393
+        $stat['mimetype'] = \OC::$server->getMimeTypeDetector()->detect($tmpFile);
394
+        $stat['etag'] = $this->getETag($path);
395
+
396
+        $fileId = $this->getCache()->put($path, $stat);
397
+        try {
398
+            //upload to object storage
399
+            $this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
400
+        } catch (\Exception $ex) {
401
+            $this->getCache()->remove($path);
402
+            $this->logger->logException($ex, [
403
+                'app' => 'objectstore',
404
+                'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
405
+            ]);
406
+            throw $ex; // make this bubble up
407
+        }
408
+    }
409
+
410
+    /**
411
+     * external changes are not supported, exclusive access to the object storage is assumed
412
+     *
413
+     * @param string $path
414
+     * @param int $time
415
+     * @return false
416
+     */
417
+    public function hasUpdated($path, $time) {
418
+        return false;
419
+    }
420 420
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -55,9 +55,9 @@  discard block
 block discarded – undo
55 55
 			throw new \Exception('missing IObjectStore instance');
56 56
 		}
57 57
 		if (isset($params['storageid'])) {
58
-			$this->id = 'object::store:' . $params['storageid'];
58
+			$this->id = 'object::store:'.$params['storageid'];
59 59
 		} else {
60
-			$this->id = 'object::store:' . $this->objectStore->getStorageId();
60
+			$this->id = 'object::store:'.$this->objectStore->getStorageId();
61 61
 		}
62 62
 		if (isset($params['objectPrefix'])) {
63 63
 			$this->objectPrefix = $params['objectPrefix'];
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 				if ($ex->getCode() !== 404) {
192 192
 					$this->logger->logException($ex, [
193 193
 						'app' => 'objectstore',
194
-						'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
194
+						'message' => 'Could not delete object '.$this->getURN($stat['fileid']).' for '.$path,
195 195
 					]);
196 196
 					return false;
197 197
 				} else {
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
 	 */
225 225
 	protected function getURN($fileId) {
226 226
 		if (is_numeric($fileId)) {
227
-			return $this->objectPrefix . $fileId;
227
+			return $this->objectPrefix.$fileId;
228 228
 		}
229 229
 		return null;
230 230
 	}
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
 					} catch (\Exception $ex) {
273 273
 						$this->logger->logException($ex, [
274 274
 							'app' => 'objectstore',
275
-							'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
275
+							'message' => 'Count not get object '.$this->getURN($stat['fileid']).' for file '.$path,
276 276
 						]);
277 277
 						return false;
278 278
 					}
@@ -302,7 +302,7 @@  discard block
 block discarded – undo
302 302
 					file_put_contents($tmpFile, $source);
303 303
 				}
304 304
 				$handle = fopen($tmpFile, $mode);
305
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
305
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
306 306
 					$this->writeBack($tmpFile, $path);
307 307
 				});
308 308
 		}
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
 
312 312
 	public function file_exists($path) {
313 313
 		$path = $this->normalizePath($path);
314
-		return (bool)$this->stat($path);
314
+		return (bool) $this->stat($path);
315 315
 	}
316 316
 
317 317
 	public function rename($source, $target) {
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
 				$this->getCache()->remove($path);
370 370
 				$this->logger->logException($ex, [
371 371
 					'app' => 'objectstore',
372
-					'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
372
+					'message' => 'Could not create object '.$this->getURN($fileId).' for '.$path,
373 373
 				]);
374 374
 				return false;
375 375
 			}
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
 			$this->getCache()->remove($path);
402 402
 			$this->logger->logException($ex, [
403 403
 				'app' => 'objectstore',
404
-				'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
404
+				'message' => 'Could not create object '.$this->getURN($fileId).' for '.$path,
405 405
 			]);
406 406
 			throw $ex; // make this bubble up
407 407
 		}
Please login to merge, or discard this patch.
apps/files_trashbin/lib/Trashbin.php 2 patches
Indentation   +937 added lines, -937 removed lines patch added patch discarded remove patch
@@ -47,941 +47,941 @@
 block discarded – undo
47 47
 
48 48
 class Trashbin {
49 49
 
50
-	// unit: percentage; 50% of available disk space/quota
51
-	const DEFAULTMAXSIZE = 50;
52
-
53
-	/**
54
-	 * Whether versions have already be rescanned during this PHP request
55
-	 *
56
-	 * @var bool
57
-	 */
58
-	private static $scannedVersions = false;
59
-
60
-	/**
61
-	 * Ensure we don't need to scan the file during the move to trash
62
-	 * by triggering the scan in the pre-hook
63
-	 *
64
-	 * @param array $params
65
-	 */
66
-	public static function ensureFileScannedHook($params) {
67
-		try {
68
-			self::getUidAndFilename($params['path']);
69
-		} catch (NotFoundException $e) {
70
-			// nothing to scan for non existing files
71
-		}
72
-	}
73
-
74
-	/**
75
-	 * get the UID of the owner of the file and the path to the file relative to
76
-	 * owners files folder
77
-	 *
78
-	 * @param string $filename
79
-	 * @return array
80
-	 * @throws \OC\User\NoUserException
81
-	 */
82
-	public static function getUidAndFilename($filename) {
83
-		$uid = Filesystem::getOwner($filename);
84
-		$userManager = \OC::$server->getUserManager();
85
-		// if the user with the UID doesn't exists, e.g. because the UID points
86
-		// to a remote user with a federated cloud ID we use the current logged-in
87
-		// user. We need a valid local user to move the file to the right trash bin
88
-		if (!$userManager->userExists($uid)) {
89
-			$uid = User::getUser();
90
-		}
91
-		if (!$uid) {
92
-			// no owner, usually because of share link from ext storage
93
-			return [null, null];
94
-		}
95
-		Filesystem::initMountPoints($uid);
96
-		if ($uid != User::getUser()) {
97
-			$info = Filesystem::getFileInfo($filename);
98
-			$ownerView = new View('/' . $uid . '/files');
99
-			try {
100
-				$filename = $ownerView->getPath($info['fileid']);
101
-			} catch (NotFoundException $e) {
102
-				$filename = null;
103
-			}
104
-		}
105
-		return [$uid, $filename];
106
-	}
107
-
108
-	/**
109
-	 * get original location of files for user
110
-	 *
111
-	 * @param string $user
112
-	 * @return array (filename => array (timestamp => original location))
113
-	 */
114
-	public static function getLocations($user) {
115
-		$query = \OC_DB::prepare('SELECT `id`, `timestamp`, `location`'
116
-			. ' FROM `*PREFIX*files_trash` WHERE `user`=?');
117
-		$result = $query->execute(array($user));
118
-		$array = array();
119
-		while ($row = $result->fetchRow()) {
120
-			if (isset($array[$row['id']])) {
121
-				$array[$row['id']][$row['timestamp']] = $row['location'];
122
-			} else {
123
-				$array[$row['id']] = array($row['timestamp'] => $row['location']);
124
-			}
125
-		}
126
-		return $array;
127
-	}
128
-
129
-	/**
130
-	 * get original location of file
131
-	 *
132
-	 * @param string $user
133
-	 * @param string $filename
134
-	 * @param string $timestamp
135
-	 * @return string original location
136
-	 */
137
-	public static function getLocation($user, $filename, $timestamp) {
138
-		$query = \OC_DB::prepare('SELECT `location` FROM `*PREFIX*files_trash`'
139
-			. ' WHERE `user`=? AND `id`=? AND `timestamp`=?');
140
-		$result = $query->execute(array($user, $filename, $timestamp))->fetchAll();
141
-		if (isset($result[0]['location'])) {
142
-			return $result[0]['location'];
143
-		} else {
144
-			return false;
145
-		}
146
-	}
147
-
148
-	private static function setUpTrash($user) {
149
-		$view = new View('/' . $user);
150
-		if (!$view->is_dir('files_trashbin')) {
151
-			$view->mkdir('files_trashbin');
152
-		}
153
-		if (!$view->is_dir('files_trashbin/files')) {
154
-			$view->mkdir('files_trashbin/files');
155
-		}
156
-		if (!$view->is_dir('files_trashbin/versions')) {
157
-			$view->mkdir('files_trashbin/versions');
158
-		}
159
-		if (!$view->is_dir('files_trashbin/keys')) {
160
-			$view->mkdir('files_trashbin/keys');
161
-		}
162
-	}
163
-
164
-
165
-	/**
166
-	 * copy file to owners trash
167
-	 *
168
-	 * @param string $sourcePath
169
-	 * @param string $owner
170
-	 * @param string $targetPath
171
-	 * @param $user
172
-	 * @param integer $timestamp
173
-	 */
174
-	private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) {
175
-		self::setUpTrash($owner);
176
-
177
-		$targetFilename = basename($targetPath);
178
-		$targetLocation = dirname($targetPath);
179
-
180
-		$sourceFilename = basename($sourcePath);
181
-
182
-		$view = new View('/');
183
-
184
-		$target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp;
185
-		$source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp;
186
-		self::copy_recursive($source, $target, $view);
187
-
188
-
189
-		if ($view->file_exists($target)) {
190
-			$query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
191
-			$result = $query->execute(array($targetFilename, $timestamp, $targetLocation, $user));
192
-			if (!$result) {
193
-				\OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated for the files owner', \OCP\Util::ERROR);
194
-			}
195
-		}
196
-	}
197
-
198
-
199
-	/**
200
-	 * move file to the trash bin
201
-	 *
202
-	 * @param string $file_path path to the deleted file/directory relative to the files root directory
203
-	 * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
204
-	 *
205
-	 * @return bool
206
-	 */
207
-	public static function move2trash($file_path, $ownerOnly = false) {
208
-		// get the user for which the filesystem is setup
209
-		$root = Filesystem::getRoot();
210
-		list(, $user) = explode('/', $root);
211
-		list($owner, $ownerPath) = self::getUidAndFilename($file_path);
212
-
213
-		// if no owner found (ex: ext storage + share link), will use the current user's trashbin then
214
-		if (is_null($owner)) {
215
-			$owner = $user;
216
-			$ownerPath = $file_path;
217
-		}
218
-
219
-		$ownerView = new View('/' . $owner);
220
-		// file has been deleted in between
221
-		if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) {
222
-			return true;
223
-		}
224
-
225
-		self::setUpTrash($user);
226
-		if ($owner !== $user) {
227
-			// also setup for owner
228
-			self::setUpTrash($owner);
229
-		}
230
-
231
-		$path_parts = pathinfo($ownerPath);
232
-
233
-		$filename = $path_parts['basename'];
234
-		$location = $path_parts['dirname'];
235
-		$timestamp = time();
236
-
237
-		// disable proxy to prevent recursive calls
238
-		$trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
239
-
240
-		/** @var \OC\Files\Storage\Storage $trashStorage */
241
-		list($trashStorage, $trashInternalPath) = $ownerView->resolvePath($trashPath);
242
-		/** @var \OC\Files\Storage\Storage $sourceStorage */
243
-		list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/' . $ownerPath);
244
-		try {
245
-			$moveSuccessful = true;
246
-			if ($trashStorage->file_exists($trashInternalPath)) {
247
-				$trashStorage->unlink($trashInternalPath);
248
-			}
249
-			$trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
250
-		} catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) {
251
-			$moveSuccessful = false;
252
-			if ($trashStorage->file_exists($trashInternalPath)) {
253
-				$trashStorage->unlink($trashInternalPath);
254
-			}
255
-			\OCP\Util::writeLog('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OCP\Util::ERROR);
256
-		}
257
-
258
-		if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
259
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
260
-				$sourceStorage->rmdir($sourceInternalPath);
261
-			} else {
262
-				$sourceStorage->unlink($sourceInternalPath);
263
-			}
264
-			return false;
265
-		}
266
-
267
-		$trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
268
-
269
-		if ($moveSuccessful) {
270
-			$query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
271
-			$result = $query->execute(array($filename, $timestamp, $location, $owner));
272
-			if (!$result) {
273
-				\OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated', \OCP\Util::ERROR);
274
-			}
275
-			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', array('filePath' => Filesystem::normalizePath($file_path),
276
-				'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp)));
277
-
278
-			self::retainVersions($filename, $owner, $ownerPath, $timestamp);
279
-
280
-			// if owner !== user we need to also add a copy to the users trash
281
-			if ($user !== $owner && $ownerOnly === false) {
282
-				self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp);
283
-			}
284
-		}
285
-
286
-		self::scheduleExpire($user);
287
-
288
-		// if owner !== user we also need to update the owners trash size
289
-		if ($owner !== $user) {
290
-			self::scheduleExpire($owner);
291
-		}
292
-
293
-		return $moveSuccessful;
294
-	}
295
-
296
-	/**
297
-	 * Move file versions to trash so that they can be restored later
298
-	 *
299
-	 * @param string $filename of deleted file
300
-	 * @param string $owner owner user id
301
-	 * @param string $ownerPath path relative to the owner's home storage
302
-	 * @param integer $timestamp when the file was deleted
303
-	 */
304
-	private static function retainVersions($filename, $owner, $ownerPath, $timestamp) {
305
-		if (\OCP\App::isEnabled('files_versions') && !empty($ownerPath)) {
306
-
307
-			$user = User::getUser();
308
-			$rootView = new View('/');
309
-
310
-			if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
311
-				if ($owner !== $user) {
312
-					self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView);
313
-				}
314
-				self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp);
315
-			} else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
316
-
317
-				foreach ($versions as $v) {
318
-					if ($owner !== $user) {
319
-						self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp);
320
-					}
321
-					self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp);
322
-				}
323
-			}
324
-		}
325
-	}
326
-
327
-	/**
328
-	 * Move a file or folder on storage level
329
-	 *
330
-	 * @param View $view
331
-	 * @param string $source
332
-	 * @param string $target
333
-	 * @return bool
334
-	 */
335
-	private static function move(View $view, $source, $target) {
336
-		/** @var \OC\Files\Storage\Storage $sourceStorage */
337
-		list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source);
338
-		/** @var \OC\Files\Storage\Storage $targetStorage */
339
-		list($targetStorage, $targetInternalPath) = $view->resolvePath($target);
340
-		/** @var \OC\Files\Storage\Storage $ownerTrashStorage */
341
-
342
-		$result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
343
-		if ($result) {
344
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
345
-		}
346
-		return $result;
347
-	}
348
-
349
-	/**
350
-	 * Copy a file or folder on storage level
351
-	 *
352
-	 * @param View $view
353
-	 * @param string $source
354
-	 * @param string $target
355
-	 * @return bool
356
-	 */
357
-	private static function copy(View $view, $source, $target) {
358
-		/** @var \OC\Files\Storage\Storage $sourceStorage */
359
-		list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source);
360
-		/** @var \OC\Files\Storage\Storage $targetStorage */
361
-		list($targetStorage, $targetInternalPath) = $view->resolvePath($target);
362
-		/** @var \OC\Files\Storage\Storage $ownerTrashStorage */
363
-
364
-		$result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
365
-		if ($result) {
366
-			$targetStorage->getUpdater()->update($targetInternalPath);
367
-		}
368
-		return $result;
369
-	}
370
-
371
-	/**
372
-	 * Restore a file or folder from trash bin
373
-	 *
374
-	 * @param string $file path to the deleted file/folder relative to "files_trashbin/files/",
375
-	 * including the timestamp suffix ".d12345678"
376
-	 * @param string $filename name of the file/folder
377
-	 * @param int $timestamp time when the file/folder was deleted
378
-	 *
379
-	 * @return bool true on success, false otherwise
380
-	 */
381
-	public static function restore($file, $filename, $timestamp) {
382
-		$user = User::getUser();
383
-		$view = new View('/' . $user);
384
-
385
-		$location = '';
386
-		if ($timestamp) {
387
-			$location = self::getLocation($user, $filename, $timestamp);
388
-			if ($location === false) {
389
-				\OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', \OCP\Util::ERROR);
390
-			} else {
391
-				// if location no longer exists, restore file in the root directory
392
-				if ($location !== '/' &&
393
-					(!$view->is_dir('files/' . $location) ||
394
-						!$view->isCreatable('files/' . $location))
395
-				) {
396
-					$location = '';
397
-				}
398
-			}
399
-		}
400
-
401
-		// we need a  extension in case a file/dir with the same name already exists
402
-		$uniqueFilename = self::getUniqueFilename($location, $filename, $view);
403
-
404
-		$source = Filesystem::normalizePath('files_trashbin/files/' . $file);
405
-		$target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
406
-		if (!$view->file_exists($source)) {
407
-			return false;
408
-		}
409
-		$mtime = $view->filemtime($source);
410
-
411
-		// restore file
412
-		$restoreResult = $view->rename($source, $target);
413
-
414
-		// handle the restore result
415
-		if ($restoreResult) {
416
-			$fakeRoot = $view->getRoot();
417
-			$view->chroot('/' . $user . '/files');
418
-			$view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
419
-			$view->chroot($fakeRoot);
420
-			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename),
421
-				'trashPath' => Filesystem::normalizePath($file)));
422
-
423
-			self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
424
-
425
-			if ($timestamp) {
426
-				$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
427
-				$query->execute(array($user, $filename, $timestamp));
428
-			}
429
-
430
-			return true;
431
-		}
432
-
433
-		return false;
434
-	}
435
-
436
-	/**
437
-	 * restore versions from trash bin
438
-	 *
439
-	 * @param View $view file view
440
-	 * @param string $file complete path to file
441
-	 * @param string $filename name of file once it was deleted
442
-	 * @param string $uniqueFilename new file name to restore the file without overwriting existing files
443
-	 * @param string $location location if file
444
-	 * @param int $timestamp deletion time
445
-	 * @return false|null
446
-	 */
447
-	private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) {
448
-
449
-		if (\OCP\App::isEnabled('files_versions')) {
450
-
451
-			$user = User::getUser();
452
-			$rootView = new View('/');
453
-
454
-			$target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
455
-
456
-			list($owner, $ownerPath) = self::getUidAndFilename($target);
457
-
458
-			// file has been deleted in between
459
-			if (empty($ownerPath)) {
460
-				return false;
461
-			}
462
-
463
-			if ($timestamp) {
464
-				$versionedFile = $filename;
465
-			} else {
466
-				$versionedFile = $file;
467
-			}
468
-
469
-			if ($view->is_dir('/files_trashbin/versions/' . $file)) {
470
-				$rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
471
-			} else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
472
-				foreach ($versions as $v) {
473
-					if ($timestamp) {
474
-						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
475
-					} else {
476
-						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
477
-					}
478
-				}
479
-			}
480
-		}
481
-	}
482
-
483
-	/**
484
-	 * delete all files from the trash
485
-	 */
486
-	public static function deleteAll() {
487
-		$user = User::getUser();
488
-		$view = new View('/' . $user);
489
-		$fileInfos = $view->getDirectoryContent('files_trashbin/files');
490
-
491
-		// Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore)
492
-		$filePaths = array();
493
-		foreach($fileInfos as $fileInfo){
494
-			$filePaths[] = $view->getRelativePath($fileInfo->getPath());
495
-		}
496
-		unset($fileInfos); // save memory
497
-
498
-		// Bulk PreDelete-Hook
499
-		\OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', array('paths' => $filePaths));
500
-
501
-		// Single-File Hooks
502
-		foreach($filePaths as $path){
503
-			self::emitTrashbinPreDelete($path);
504
-		}
505
-
506
-		// actual file deletion
507
-		$view->deleteAll('files_trashbin');
508
-		$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
509
-		$query->execute(array($user));
510
-
511
-		// Bulk PostDelete-Hook
512
-		\OC_Hook::emit('\OCP\Trashbin', 'deleteAll', array('paths' => $filePaths));
513
-
514
-		// Single-File Hooks
515
-		foreach($filePaths as $path){
516
-			self::emitTrashbinPostDelete($path);
517
-		}
518
-
519
-		$view->mkdir('files_trashbin');
520
-		$view->mkdir('files_trashbin/files');
521
-
522
-		return true;
523
-	}
524
-
525
-	/**
526
-	 * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted
527
-	 * @param string $path
528
-	 */
529
-	protected static function emitTrashbinPreDelete($path){
530
-		\OC_Hook::emit('\OCP\Trashbin', 'preDelete', array('path' => $path));
531
-	}
532
-
533
-	/**
534
-	 * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted
535
-	 * @param string $path
536
-	 */
537
-	protected static function emitTrashbinPostDelete($path){
538
-		\OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => $path));
539
-	}
540
-
541
-	/**
542
-	 * delete file from trash bin permanently
543
-	 *
544
-	 * @param string $filename path to the file
545
-	 * @param string $user
546
-	 * @param int $timestamp of deletion time
547
-	 *
548
-	 * @return int size of deleted files
549
-	 */
550
-	public static function delete($filename, $user, $timestamp = null) {
551
-		$view = new View('/' . $user);
552
-		$size = 0;
553
-
554
-		if ($timestamp) {
555
-			$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
556
-			$query->execute(array($user, $filename, $timestamp));
557
-			$file = $filename . '.d' . $timestamp;
558
-		} else {
559
-			$file = $filename;
560
-		}
561
-
562
-		$size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
563
-
564
-		if ($view->is_dir('/files_trashbin/files/' . $file)) {
565
-			$size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
566
-		} else {
567
-			$size += $view->filesize('/files_trashbin/files/' . $file);
568
-		}
569
-		self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
570
-		$view->unlink('/files_trashbin/files/' . $file);
571
-		self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
572
-
573
-		return $size;
574
-	}
575
-
576
-	/**
577
-	 * @param View $view
578
-	 * @param string $file
579
-	 * @param string $filename
580
-	 * @param integer|null $timestamp
581
-	 * @param string $user
582
-	 * @return int
583
-	 */
584
-	private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) {
585
-		$size = 0;
586
-		if (\OCP\App::isEnabled('files_versions')) {
587
-			if ($view->is_dir('files_trashbin/versions/' . $file)) {
588
-				$size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file));
589
-				$view->unlink('files_trashbin/versions/' . $file);
590
-			} else if ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
591
-				foreach ($versions as $v) {
592
-					if ($timestamp) {
593
-						$size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
594
-						$view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
595
-					} else {
596
-						$size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
597
-						$view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
598
-					}
599
-				}
600
-			}
601
-		}
602
-		return $size;
603
-	}
604
-
605
-	/**
606
-	 * check to see whether a file exists in trashbin
607
-	 *
608
-	 * @param string $filename path to the file
609
-	 * @param int $timestamp of deletion time
610
-	 * @return bool true if file exists, otherwise false
611
-	 */
612
-	public static function file_exists($filename, $timestamp = null) {
613
-		$user = User::getUser();
614
-		$view = new View('/' . $user);
615
-
616
-		if ($timestamp) {
617
-			$filename = $filename . '.d' . $timestamp;
618
-		} else {
619
-			$filename = $filename;
620
-		}
621
-
622
-		$target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
623
-		return $view->file_exists($target);
624
-	}
625
-
626
-	/**
627
-	 * deletes used space for trash bin in db if user was deleted
628
-	 *
629
-	 * @param string $uid id of deleted user
630
-	 * @return bool result of db delete operation
631
-	 */
632
-	public static function deleteUser($uid) {
633
-		$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
634
-		return $query->execute(array($uid));
635
-	}
636
-
637
-	/**
638
-	 * calculate remaining free space for trash bin
639
-	 *
640
-	 * @param integer $trashbinSize current size of the trash bin
641
-	 * @param string $user
642
-	 * @return int available free space for trash bin
643
-	 */
644
-	private static function calculateFreeSpace($trashbinSize, $user) {
645
-		$softQuota = true;
646
-		$userObject = \OC::$server->getUserManager()->get($user);
647
-		if(is_null($userObject)) {
648
-			return 0;
649
-		}
650
-		$quota = $userObject->getQuota();
651
-		if ($quota === null || $quota === 'none') {
652
-			$quota = Filesystem::free_space('/');
653
-			$softQuota = false;
654
-			// inf or unknown free space
655
-			if ($quota < 0) {
656
-				$quota = PHP_INT_MAX;
657
-			}
658
-		} else {
659
-			$quota = \OCP\Util::computerFileSize($quota);
660
-		}
661
-
662
-		// calculate available space for trash bin
663
-		// subtract size of files and current trash bin size from quota
664
-		if ($softQuota) {
665
-			$userFolder = \OC::$server->getUserFolder($user);
666
-			if(is_null($userFolder)) {
667
-				return 0;
668
-			}
669
-			$free = $quota - $userFolder->getSize(); // remaining free space for user
670
-			if ($free > 0) {
671
-				$availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
672
-			} else {
673
-				$availableSpace = $free - $trashbinSize;
674
-			}
675
-		} else {
676
-			$availableSpace = $quota;
677
-		}
678
-
679
-		return $availableSpace;
680
-	}
681
-
682
-	/**
683
-	 * resize trash bin if necessary after a new file was added to Nextcloud
684
-	 *
685
-	 * @param string $user user id
686
-	 */
687
-	public static function resizeTrash($user) {
688
-
689
-		$size = self::getTrashbinSize($user);
690
-
691
-		$freeSpace = self::calculateFreeSpace($size, $user);
692
-
693
-		if ($freeSpace < 0) {
694
-			self::scheduleExpire($user);
695
-		}
696
-	}
697
-
698
-	/**
699
-	 * clean up the trash bin
700
-	 *
701
-	 * @param string $user
702
-	 */
703
-	public static function expire($user) {
704
-		$trashBinSize = self::getTrashbinSize($user);
705
-		$availableSpace = self::calculateFreeSpace($trashBinSize, $user);
706
-
707
-		$dirContent = Helper::getTrashFiles('/', $user, 'mtime');
708
-
709
-		// delete all files older then $retention_obligation
710
-		list($delSize, $count) = self::deleteExpiredFiles($dirContent, $user);
711
-
712
-		$availableSpace += $delSize;
713
-
714
-		// delete files from trash until we meet the trash bin size limit again
715
-		self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace);
716
-	}
717
-
718
-	/**
719
-	 * @param string $user
720
-	 */
721
-	private static function scheduleExpire($user) {
722
-		// let the admin disable auto expire
723
-		$application = new Application();
724
-		$expiration = $application->getContainer()->query('Expiration');
725
-		if ($expiration->isEnabled()) {
726
-			\OC::$server->getCommandBus()->push(new Expire($user));
727
-		}
728
-	}
729
-
730
-	/**
731
-	 * if the size limit for the trash bin is reached, we delete the oldest
732
-	 * files in the trash bin until we meet the limit again
733
-	 *
734
-	 * @param array $files
735
-	 * @param string $user
736
-	 * @param int $availableSpace available disc space
737
-	 * @return int size of deleted files
738
-	 */
739
-	protected static function deleteFiles($files, $user, $availableSpace) {
740
-		$application = new Application();
741
-		$expiration = $application->getContainer()->query('Expiration');
742
-		$size = 0;
743
-
744
-		if ($availableSpace < 0) {
745
-			foreach ($files as $file) {
746
-				if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
747
-					$tmp = self::delete($file['name'], $user, $file['mtime']);
748
-					\OCP\Util::writeLog('files_trashbin', 'remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', \OCP\Util::INFO);
749
-					$availableSpace += $tmp;
750
-					$size += $tmp;
751
-				} else {
752
-					break;
753
-				}
754
-			}
755
-		}
756
-		return $size;
757
-	}
758
-
759
-	/**
760
-	 * delete files older then max storage time
761
-	 *
762
-	 * @param array $files list of files sorted by mtime
763
-	 * @param string $user
764
-	 * @return integer[] size of deleted files and number of deleted files
765
-	 */
766
-	public static function deleteExpiredFiles($files, $user) {
767
-		$application = new Application();
768
-		$expiration = $application->getContainer()->query('Expiration');
769
-		$size = 0;
770
-		$count = 0;
771
-		foreach ($files as $file) {
772
-			$timestamp = $file['mtime'];
773
-			$filename = $file['name'];
774
-			if ($expiration->isExpired($timestamp)) {
775
-				$count++;
776
-				$size += self::delete($filename, $user, $timestamp);
777
-				\OC::$server->getLogger()->info(
778
-					'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
779
-					['app' => 'files_trashbin']
780
-				);
781
-			} else {
782
-				break;
783
-			}
784
-		}
785
-
786
-		return array($size, $count);
787
-	}
788
-
789
-	/**
790
-	 * recursive copy to copy a whole directory
791
-	 *
792
-	 * @param string $source source path, relative to the users files directory
793
-	 * @param string $destination destination path relative to the users root directoy
794
-	 * @param View $view file view for the users root directory
795
-	 * @return int
796
-	 * @throws Exceptions\CopyRecursiveException
797
-	 */
798
-	private static function copy_recursive($source, $destination, View $view) {
799
-		$size = 0;
800
-		if ($view->is_dir($source)) {
801
-			$view->mkdir($destination);
802
-			$view->touch($destination, $view->filemtime($source));
803
-			foreach ($view->getDirectoryContent($source) as $i) {
804
-				$pathDir = $source . '/' . $i['name'];
805
-				if ($view->is_dir($pathDir)) {
806
-					$size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
807
-				} else {
808
-					$size += $view->filesize($pathDir);
809
-					$result = $view->copy($pathDir, $destination . '/' . $i['name']);
810
-					if (!$result) {
811
-						throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
812
-					}
813
-					$view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
814
-				}
815
-			}
816
-		} else {
817
-			$size += $view->filesize($source);
818
-			$result = $view->copy($source, $destination);
819
-			if (!$result) {
820
-				throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
821
-			}
822
-			$view->touch($destination, $view->filemtime($source));
823
-		}
824
-		return $size;
825
-	}
826
-
827
-	/**
828
-	 * find all versions which belong to the file we want to restore
829
-	 *
830
-	 * @param string $filename name of the file which should be restored
831
-	 * @param int $timestamp timestamp when the file was deleted
832
-	 * @return array
833
-	 */
834
-	private static function getVersionsFromTrash($filename, $timestamp, $user) {
835
-		$view = new View('/' . $user . '/files_trashbin/versions');
836
-		$versions = array();
837
-
838
-		//force rescan of versions, local storage may not have updated the cache
839
-		if (!self::$scannedVersions) {
840
-			/** @var \OC\Files\Storage\Storage $storage */
841
-			list($storage,) = $view->resolvePath('/');
842
-			$storage->getScanner()->scan('files_trashbin/versions');
843
-			self::$scannedVersions = true;
844
-		}
845
-
846
-		if ($timestamp) {
847
-			// fetch for old versions
848
-			$matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
849
-			$offset = -strlen($timestamp) - 2;
850
-		} else {
851
-			$matches = $view->searchRaw($filename . '.v%');
852
-		}
853
-
854
-		if (is_array($matches)) {
855
-			foreach ($matches as $ma) {
856
-				if ($timestamp) {
857
-					$parts = explode('.v', substr($ma['path'], 0, $offset));
858
-					$versions[] = (end($parts));
859
-				} else {
860
-					$parts = explode('.v', $ma);
861
-					$versions[] = (end($parts));
862
-				}
863
-			}
864
-		}
865
-		return $versions;
866
-	}
867
-
868
-	/**
869
-	 * find unique extension for restored file if a file with the same name already exists
870
-	 *
871
-	 * @param string $location where the file should be restored
872
-	 * @param string $filename name of the file
873
-	 * @param View $view filesystem view relative to users root directory
874
-	 * @return string with unique extension
875
-	 */
876
-	private static function getUniqueFilename($location, $filename, View $view) {
877
-		$ext = pathinfo($filename, PATHINFO_EXTENSION);
878
-		$name = pathinfo($filename, PATHINFO_FILENAME);
879
-		$l = \OC::$server->getL10N('files_trashbin');
880
-
881
-		$location = '/' . trim($location, '/');
882
-
883
-		// if extension is not empty we set a dot in front of it
884
-		if ($ext !== '') {
885
-			$ext = '.' . $ext;
886
-		}
887
-
888
-		if ($view->file_exists('files' . $location . '/' . $filename)) {
889
-			$i = 2;
890
-			$uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
891
-			while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
892
-				$uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
893
-				$i++;
894
-			}
895
-
896
-			return $uniqueName;
897
-		}
898
-
899
-		return $filename;
900
-	}
901
-
902
-	/**
903
-	 * get the size from a given root folder
904
-	 *
905
-	 * @param View $view file view on the root folder
906
-	 * @return integer size of the folder
907
-	 */
908
-	private static function calculateSize($view) {
909
-		$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
910
-		if (!file_exists($root)) {
911
-			return 0;
912
-		}
913
-		$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
914
-		$size = 0;
915
-
916
-		/**
917
-		 * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
918
-		 * This bug is fixed in PHP 5.5.9 or before
919
-		 * See #8376
920
-		 */
921
-		$iterator->rewind();
922
-		while ($iterator->valid()) {
923
-			$path = $iterator->current();
924
-			$relpath = substr($path, strlen($root) - 1);
925
-			if (!$view->is_dir($relpath)) {
926
-				$size += $view->filesize($relpath);
927
-			}
928
-			$iterator->next();
929
-		}
930
-		return $size;
931
-	}
932
-
933
-	/**
934
-	 * get current size of trash bin from a given user
935
-	 *
936
-	 * @param string $user user who owns the trash bin
937
-	 * @return integer trash bin size
938
-	 */
939
-	private static function getTrashbinSize($user) {
940
-		$view = new View('/' . $user);
941
-		$fileInfo = $view->getFileInfo('/files_trashbin');
942
-		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
943
-	}
944
-
945
-	/**
946
-	 * register hooks
947
-	 */
948
-	public static function registerHooks() {
949
-		// create storage wrapper on setup
950
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage');
951
-		//Listen to delete user signal
952
-		\OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook');
953
-		//Listen to post write hook
954
-		\OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook');
955
-		// pre and post-rename, disable trash logic for the copy+unlink case
956
-		\OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook');
957
-		\OCP\Util::connectHook('OC_Filesystem', 'rename', 'OCA\Files_Trashbin\Storage', 'preRenameHook');
958
-		\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Files_Trashbin\Storage', 'postRenameHook');
959
-	}
960
-
961
-	/**
962
-	 * check if trash bin is empty for a given user
963
-	 *
964
-	 * @param string $user
965
-	 * @return bool
966
-	 */
967
-	public static function isEmpty($user) {
968
-
969
-		$view = new View('/' . $user . '/files_trashbin');
970
-		if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
971
-			while ($file = readdir($dh)) {
972
-				if (!Filesystem::isIgnoredDir($file)) {
973
-					return false;
974
-				}
975
-			}
976
-		}
977
-		return true;
978
-	}
979
-
980
-	/**
981
-	 * @param $path
982
-	 * @return string
983
-	 */
984
-	public static function preview_icon($path) {
985
-		return \OCP\Util::linkToRoute('core_ajax_trashbin_preview', array('x' => 32, 'y' => 32, 'file' => $path));
986
-	}
50
+    // unit: percentage; 50% of available disk space/quota
51
+    const DEFAULTMAXSIZE = 50;
52
+
53
+    /**
54
+     * Whether versions have already be rescanned during this PHP request
55
+     *
56
+     * @var bool
57
+     */
58
+    private static $scannedVersions = false;
59
+
60
+    /**
61
+     * Ensure we don't need to scan the file during the move to trash
62
+     * by triggering the scan in the pre-hook
63
+     *
64
+     * @param array $params
65
+     */
66
+    public static function ensureFileScannedHook($params) {
67
+        try {
68
+            self::getUidAndFilename($params['path']);
69
+        } catch (NotFoundException $e) {
70
+            // nothing to scan for non existing files
71
+        }
72
+    }
73
+
74
+    /**
75
+     * get the UID of the owner of the file and the path to the file relative to
76
+     * owners files folder
77
+     *
78
+     * @param string $filename
79
+     * @return array
80
+     * @throws \OC\User\NoUserException
81
+     */
82
+    public static function getUidAndFilename($filename) {
83
+        $uid = Filesystem::getOwner($filename);
84
+        $userManager = \OC::$server->getUserManager();
85
+        // if the user with the UID doesn't exists, e.g. because the UID points
86
+        // to a remote user with a federated cloud ID we use the current logged-in
87
+        // user. We need a valid local user to move the file to the right trash bin
88
+        if (!$userManager->userExists($uid)) {
89
+            $uid = User::getUser();
90
+        }
91
+        if (!$uid) {
92
+            // no owner, usually because of share link from ext storage
93
+            return [null, null];
94
+        }
95
+        Filesystem::initMountPoints($uid);
96
+        if ($uid != User::getUser()) {
97
+            $info = Filesystem::getFileInfo($filename);
98
+            $ownerView = new View('/' . $uid . '/files');
99
+            try {
100
+                $filename = $ownerView->getPath($info['fileid']);
101
+            } catch (NotFoundException $e) {
102
+                $filename = null;
103
+            }
104
+        }
105
+        return [$uid, $filename];
106
+    }
107
+
108
+    /**
109
+     * get original location of files for user
110
+     *
111
+     * @param string $user
112
+     * @return array (filename => array (timestamp => original location))
113
+     */
114
+    public static function getLocations($user) {
115
+        $query = \OC_DB::prepare('SELECT `id`, `timestamp`, `location`'
116
+            . ' FROM `*PREFIX*files_trash` WHERE `user`=?');
117
+        $result = $query->execute(array($user));
118
+        $array = array();
119
+        while ($row = $result->fetchRow()) {
120
+            if (isset($array[$row['id']])) {
121
+                $array[$row['id']][$row['timestamp']] = $row['location'];
122
+            } else {
123
+                $array[$row['id']] = array($row['timestamp'] => $row['location']);
124
+            }
125
+        }
126
+        return $array;
127
+    }
128
+
129
+    /**
130
+     * get original location of file
131
+     *
132
+     * @param string $user
133
+     * @param string $filename
134
+     * @param string $timestamp
135
+     * @return string original location
136
+     */
137
+    public static function getLocation($user, $filename, $timestamp) {
138
+        $query = \OC_DB::prepare('SELECT `location` FROM `*PREFIX*files_trash`'
139
+            . ' WHERE `user`=? AND `id`=? AND `timestamp`=?');
140
+        $result = $query->execute(array($user, $filename, $timestamp))->fetchAll();
141
+        if (isset($result[0]['location'])) {
142
+            return $result[0]['location'];
143
+        } else {
144
+            return false;
145
+        }
146
+    }
147
+
148
+    private static function setUpTrash($user) {
149
+        $view = new View('/' . $user);
150
+        if (!$view->is_dir('files_trashbin')) {
151
+            $view->mkdir('files_trashbin');
152
+        }
153
+        if (!$view->is_dir('files_trashbin/files')) {
154
+            $view->mkdir('files_trashbin/files');
155
+        }
156
+        if (!$view->is_dir('files_trashbin/versions')) {
157
+            $view->mkdir('files_trashbin/versions');
158
+        }
159
+        if (!$view->is_dir('files_trashbin/keys')) {
160
+            $view->mkdir('files_trashbin/keys');
161
+        }
162
+    }
163
+
164
+
165
+    /**
166
+     * copy file to owners trash
167
+     *
168
+     * @param string $sourcePath
169
+     * @param string $owner
170
+     * @param string $targetPath
171
+     * @param $user
172
+     * @param integer $timestamp
173
+     */
174
+    private static function copyFilesToUser($sourcePath, $owner, $targetPath, $user, $timestamp) {
175
+        self::setUpTrash($owner);
176
+
177
+        $targetFilename = basename($targetPath);
178
+        $targetLocation = dirname($targetPath);
179
+
180
+        $sourceFilename = basename($sourcePath);
181
+
182
+        $view = new View('/');
183
+
184
+        $target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp;
185
+        $source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp;
186
+        self::copy_recursive($source, $target, $view);
187
+
188
+
189
+        if ($view->file_exists($target)) {
190
+            $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
191
+            $result = $query->execute(array($targetFilename, $timestamp, $targetLocation, $user));
192
+            if (!$result) {
193
+                \OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated for the files owner', \OCP\Util::ERROR);
194
+            }
195
+        }
196
+    }
197
+
198
+
199
+    /**
200
+     * move file to the trash bin
201
+     *
202
+     * @param string $file_path path to the deleted file/directory relative to the files root directory
203
+     * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
204
+     *
205
+     * @return bool
206
+     */
207
+    public static function move2trash($file_path, $ownerOnly = false) {
208
+        // get the user for which the filesystem is setup
209
+        $root = Filesystem::getRoot();
210
+        list(, $user) = explode('/', $root);
211
+        list($owner, $ownerPath) = self::getUidAndFilename($file_path);
212
+
213
+        // if no owner found (ex: ext storage + share link), will use the current user's trashbin then
214
+        if (is_null($owner)) {
215
+            $owner = $user;
216
+            $ownerPath = $file_path;
217
+        }
218
+
219
+        $ownerView = new View('/' . $owner);
220
+        // file has been deleted in between
221
+        if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) {
222
+            return true;
223
+        }
224
+
225
+        self::setUpTrash($user);
226
+        if ($owner !== $user) {
227
+            // also setup for owner
228
+            self::setUpTrash($owner);
229
+        }
230
+
231
+        $path_parts = pathinfo($ownerPath);
232
+
233
+        $filename = $path_parts['basename'];
234
+        $location = $path_parts['dirname'];
235
+        $timestamp = time();
236
+
237
+        // disable proxy to prevent recursive calls
238
+        $trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
239
+
240
+        /** @var \OC\Files\Storage\Storage $trashStorage */
241
+        list($trashStorage, $trashInternalPath) = $ownerView->resolvePath($trashPath);
242
+        /** @var \OC\Files\Storage\Storage $sourceStorage */
243
+        list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/' . $ownerPath);
244
+        try {
245
+            $moveSuccessful = true;
246
+            if ($trashStorage->file_exists($trashInternalPath)) {
247
+                $trashStorage->unlink($trashInternalPath);
248
+            }
249
+            $trashStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
250
+        } catch (\OCA\Files_Trashbin\Exceptions\CopyRecursiveException $e) {
251
+            $moveSuccessful = false;
252
+            if ($trashStorage->file_exists($trashInternalPath)) {
253
+                $trashStorage->unlink($trashInternalPath);
254
+            }
255
+            \OCP\Util::writeLog('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OCP\Util::ERROR);
256
+        }
257
+
258
+        if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
259
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
260
+                $sourceStorage->rmdir($sourceInternalPath);
261
+            } else {
262
+                $sourceStorage->unlink($sourceInternalPath);
263
+            }
264
+            return false;
265
+        }
266
+
267
+        $trashStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $trashInternalPath);
268
+
269
+        if ($moveSuccessful) {
270
+            $query = \OC_DB::prepare("INSERT INTO `*PREFIX*files_trash` (`id`,`timestamp`,`location`,`user`) VALUES (?,?,?,?)");
271
+            $result = $query->execute(array($filename, $timestamp, $location, $owner));
272
+            if (!$result) {
273
+                \OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated', \OCP\Util::ERROR);
274
+            }
275
+            \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', array('filePath' => Filesystem::normalizePath($file_path),
276
+                'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp)));
277
+
278
+            self::retainVersions($filename, $owner, $ownerPath, $timestamp);
279
+
280
+            // if owner !== user we need to also add a copy to the users trash
281
+            if ($user !== $owner && $ownerOnly === false) {
282
+                self::copyFilesToUser($ownerPath, $owner, $file_path, $user, $timestamp);
283
+            }
284
+        }
285
+
286
+        self::scheduleExpire($user);
287
+
288
+        // if owner !== user we also need to update the owners trash size
289
+        if ($owner !== $user) {
290
+            self::scheduleExpire($owner);
291
+        }
292
+
293
+        return $moveSuccessful;
294
+    }
295
+
296
+    /**
297
+     * Move file versions to trash so that they can be restored later
298
+     *
299
+     * @param string $filename of deleted file
300
+     * @param string $owner owner user id
301
+     * @param string $ownerPath path relative to the owner's home storage
302
+     * @param integer $timestamp when the file was deleted
303
+     */
304
+    private static function retainVersions($filename, $owner, $ownerPath, $timestamp) {
305
+        if (\OCP\App::isEnabled('files_versions') && !empty($ownerPath)) {
306
+
307
+            $user = User::getUser();
308
+            $rootView = new View('/');
309
+
310
+            if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
311
+                if ($owner !== $user) {
312
+                    self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView);
313
+                }
314
+                self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp);
315
+            } else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
316
+
317
+                foreach ($versions as $v) {
318
+                    if ($owner !== $user) {
319
+                        self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp);
320
+                    }
321
+                    self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp);
322
+                }
323
+            }
324
+        }
325
+    }
326
+
327
+    /**
328
+     * Move a file or folder on storage level
329
+     *
330
+     * @param View $view
331
+     * @param string $source
332
+     * @param string $target
333
+     * @return bool
334
+     */
335
+    private static function move(View $view, $source, $target) {
336
+        /** @var \OC\Files\Storage\Storage $sourceStorage */
337
+        list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source);
338
+        /** @var \OC\Files\Storage\Storage $targetStorage */
339
+        list($targetStorage, $targetInternalPath) = $view->resolvePath($target);
340
+        /** @var \OC\Files\Storage\Storage $ownerTrashStorage */
341
+
342
+        $result = $targetStorage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
343
+        if ($result) {
344
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
345
+        }
346
+        return $result;
347
+    }
348
+
349
+    /**
350
+     * Copy a file or folder on storage level
351
+     *
352
+     * @param View $view
353
+     * @param string $source
354
+     * @param string $target
355
+     * @return bool
356
+     */
357
+    private static function copy(View $view, $source, $target) {
358
+        /** @var \OC\Files\Storage\Storage $sourceStorage */
359
+        list($sourceStorage, $sourceInternalPath) = $view->resolvePath($source);
360
+        /** @var \OC\Files\Storage\Storage $targetStorage */
361
+        list($targetStorage, $targetInternalPath) = $view->resolvePath($target);
362
+        /** @var \OC\Files\Storage\Storage $ownerTrashStorage */
363
+
364
+        $result = $targetStorage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
365
+        if ($result) {
366
+            $targetStorage->getUpdater()->update($targetInternalPath);
367
+        }
368
+        return $result;
369
+    }
370
+
371
+    /**
372
+     * Restore a file or folder from trash bin
373
+     *
374
+     * @param string $file path to the deleted file/folder relative to "files_trashbin/files/",
375
+     * including the timestamp suffix ".d12345678"
376
+     * @param string $filename name of the file/folder
377
+     * @param int $timestamp time when the file/folder was deleted
378
+     *
379
+     * @return bool true on success, false otherwise
380
+     */
381
+    public static function restore($file, $filename, $timestamp) {
382
+        $user = User::getUser();
383
+        $view = new View('/' . $user);
384
+
385
+        $location = '';
386
+        if ($timestamp) {
387
+            $location = self::getLocation($user, $filename, $timestamp);
388
+            if ($location === false) {
389
+                \OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', \OCP\Util::ERROR);
390
+            } else {
391
+                // if location no longer exists, restore file in the root directory
392
+                if ($location !== '/' &&
393
+                    (!$view->is_dir('files/' . $location) ||
394
+                        !$view->isCreatable('files/' . $location))
395
+                ) {
396
+                    $location = '';
397
+                }
398
+            }
399
+        }
400
+
401
+        // we need a  extension in case a file/dir with the same name already exists
402
+        $uniqueFilename = self::getUniqueFilename($location, $filename, $view);
403
+
404
+        $source = Filesystem::normalizePath('files_trashbin/files/' . $file);
405
+        $target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
406
+        if (!$view->file_exists($source)) {
407
+            return false;
408
+        }
409
+        $mtime = $view->filemtime($source);
410
+
411
+        // restore file
412
+        $restoreResult = $view->rename($source, $target);
413
+
414
+        // handle the restore result
415
+        if ($restoreResult) {
416
+            $fakeRoot = $view->getRoot();
417
+            $view->chroot('/' . $user . '/files');
418
+            $view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
419
+            $view->chroot($fakeRoot);
420
+            \OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename),
421
+                'trashPath' => Filesystem::normalizePath($file)));
422
+
423
+            self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
424
+
425
+            if ($timestamp) {
426
+                $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
427
+                $query->execute(array($user, $filename, $timestamp));
428
+            }
429
+
430
+            return true;
431
+        }
432
+
433
+        return false;
434
+    }
435
+
436
+    /**
437
+     * restore versions from trash bin
438
+     *
439
+     * @param View $view file view
440
+     * @param string $file complete path to file
441
+     * @param string $filename name of file once it was deleted
442
+     * @param string $uniqueFilename new file name to restore the file without overwriting existing files
443
+     * @param string $location location if file
444
+     * @param int $timestamp deletion time
445
+     * @return false|null
446
+     */
447
+    private static function restoreVersions(View $view, $file, $filename, $uniqueFilename, $location, $timestamp) {
448
+
449
+        if (\OCP\App::isEnabled('files_versions')) {
450
+
451
+            $user = User::getUser();
452
+            $rootView = new View('/');
453
+
454
+            $target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
455
+
456
+            list($owner, $ownerPath) = self::getUidAndFilename($target);
457
+
458
+            // file has been deleted in between
459
+            if (empty($ownerPath)) {
460
+                return false;
461
+            }
462
+
463
+            if ($timestamp) {
464
+                $versionedFile = $filename;
465
+            } else {
466
+                $versionedFile = $file;
467
+            }
468
+
469
+            if ($view->is_dir('/files_trashbin/versions/' . $file)) {
470
+                $rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
471
+            } else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
472
+                foreach ($versions as $v) {
473
+                    if ($timestamp) {
474
+                        $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
475
+                    } else {
476
+                        $rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
477
+                    }
478
+                }
479
+            }
480
+        }
481
+    }
482
+
483
+    /**
484
+     * delete all files from the trash
485
+     */
486
+    public static function deleteAll() {
487
+        $user = User::getUser();
488
+        $view = new View('/' . $user);
489
+        $fileInfos = $view->getDirectoryContent('files_trashbin/files');
490
+
491
+        // Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore)
492
+        $filePaths = array();
493
+        foreach($fileInfos as $fileInfo){
494
+            $filePaths[] = $view->getRelativePath($fileInfo->getPath());
495
+        }
496
+        unset($fileInfos); // save memory
497
+
498
+        // Bulk PreDelete-Hook
499
+        \OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', array('paths' => $filePaths));
500
+
501
+        // Single-File Hooks
502
+        foreach($filePaths as $path){
503
+            self::emitTrashbinPreDelete($path);
504
+        }
505
+
506
+        // actual file deletion
507
+        $view->deleteAll('files_trashbin');
508
+        $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
509
+        $query->execute(array($user));
510
+
511
+        // Bulk PostDelete-Hook
512
+        \OC_Hook::emit('\OCP\Trashbin', 'deleteAll', array('paths' => $filePaths));
513
+
514
+        // Single-File Hooks
515
+        foreach($filePaths as $path){
516
+            self::emitTrashbinPostDelete($path);
517
+        }
518
+
519
+        $view->mkdir('files_trashbin');
520
+        $view->mkdir('files_trashbin/files');
521
+
522
+        return true;
523
+    }
524
+
525
+    /**
526
+     * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted
527
+     * @param string $path
528
+     */
529
+    protected static function emitTrashbinPreDelete($path){
530
+        \OC_Hook::emit('\OCP\Trashbin', 'preDelete', array('path' => $path));
531
+    }
532
+
533
+    /**
534
+     * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted
535
+     * @param string $path
536
+     */
537
+    protected static function emitTrashbinPostDelete($path){
538
+        \OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => $path));
539
+    }
540
+
541
+    /**
542
+     * delete file from trash bin permanently
543
+     *
544
+     * @param string $filename path to the file
545
+     * @param string $user
546
+     * @param int $timestamp of deletion time
547
+     *
548
+     * @return int size of deleted files
549
+     */
550
+    public static function delete($filename, $user, $timestamp = null) {
551
+        $view = new View('/' . $user);
552
+        $size = 0;
553
+
554
+        if ($timestamp) {
555
+            $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
556
+            $query->execute(array($user, $filename, $timestamp));
557
+            $file = $filename . '.d' . $timestamp;
558
+        } else {
559
+            $file = $filename;
560
+        }
561
+
562
+        $size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
563
+
564
+        if ($view->is_dir('/files_trashbin/files/' . $file)) {
565
+            $size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
566
+        } else {
567
+            $size += $view->filesize('/files_trashbin/files/' . $file);
568
+        }
569
+        self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
570
+        $view->unlink('/files_trashbin/files/' . $file);
571
+        self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
572
+
573
+        return $size;
574
+    }
575
+
576
+    /**
577
+     * @param View $view
578
+     * @param string $file
579
+     * @param string $filename
580
+     * @param integer|null $timestamp
581
+     * @param string $user
582
+     * @return int
583
+     */
584
+    private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) {
585
+        $size = 0;
586
+        if (\OCP\App::isEnabled('files_versions')) {
587
+            if ($view->is_dir('files_trashbin/versions/' . $file)) {
588
+                $size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file));
589
+                $view->unlink('files_trashbin/versions/' . $file);
590
+            } else if ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
591
+                foreach ($versions as $v) {
592
+                    if ($timestamp) {
593
+                        $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
594
+                        $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
595
+                    } else {
596
+                        $size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
597
+                        $view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
598
+                    }
599
+                }
600
+            }
601
+        }
602
+        return $size;
603
+    }
604
+
605
+    /**
606
+     * check to see whether a file exists in trashbin
607
+     *
608
+     * @param string $filename path to the file
609
+     * @param int $timestamp of deletion time
610
+     * @return bool true if file exists, otherwise false
611
+     */
612
+    public static function file_exists($filename, $timestamp = null) {
613
+        $user = User::getUser();
614
+        $view = new View('/' . $user);
615
+
616
+        if ($timestamp) {
617
+            $filename = $filename . '.d' . $timestamp;
618
+        } else {
619
+            $filename = $filename;
620
+        }
621
+
622
+        $target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
623
+        return $view->file_exists($target);
624
+    }
625
+
626
+    /**
627
+     * deletes used space for trash bin in db if user was deleted
628
+     *
629
+     * @param string $uid id of deleted user
630
+     * @return bool result of db delete operation
631
+     */
632
+    public static function deleteUser($uid) {
633
+        $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=?');
634
+        return $query->execute(array($uid));
635
+    }
636
+
637
+    /**
638
+     * calculate remaining free space for trash bin
639
+     *
640
+     * @param integer $trashbinSize current size of the trash bin
641
+     * @param string $user
642
+     * @return int available free space for trash bin
643
+     */
644
+    private static function calculateFreeSpace($trashbinSize, $user) {
645
+        $softQuota = true;
646
+        $userObject = \OC::$server->getUserManager()->get($user);
647
+        if(is_null($userObject)) {
648
+            return 0;
649
+        }
650
+        $quota = $userObject->getQuota();
651
+        if ($quota === null || $quota === 'none') {
652
+            $quota = Filesystem::free_space('/');
653
+            $softQuota = false;
654
+            // inf or unknown free space
655
+            if ($quota < 0) {
656
+                $quota = PHP_INT_MAX;
657
+            }
658
+        } else {
659
+            $quota = \OCP\Util::computerFileSize($quota);
660
+        }
661
+
662
+        // calculate available space for trash bin
663
+        // subtract size of files and current trash bin size from quota
664
+        if ($softQuota) {
665
+            $userFolder = \OC::$server->getUserFolder($user);
666
+            if(is_null($userFolder)) {
667
+                return 0;
668
+            }
669
+            $free = $quota - $userFolder->getSize(); // remaining free space for user
670
+            if ($free > 0) {
671
+                $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $trashbinSize; // how much space can be used for versions
672
+            } else {
673
+                $availableSpace = $free - $trashbinSize;
674
+            }
675
+        } else {
676
+            $availableSpace = $quota;
677
+        }
678
+
679
+        return $availableSpace;
680
+    }
681
+
682
+    /**
683
+     * resize trash bin if necessary after a new file was added to Nextcloud
684
+     *
685
+     * @param string $user user id
686
+     */
687
+    public static function resizeTrash($user) {
688
+
689
+        $size = self::getTrashbinSize($user);
690
+
691
+        $freeSpace = self::calculateFreeSpace($size, $user);
692
+
693
+        if ($freeSpace < 0) {
694
+            self::scheduleExpire($user);
695
+        }
696
+    }
697
+
698
+    /**
699
+     * clean up the trash bin
700
+     *
701
+     * @param string $user
702
+     */
703
+    public static function expire($user) {
704
+        $trashBinSize = self::getTrashbinSize($user);
705
+        $availableSpace = self::calculateFreeSpace($trashBinSize, $user);
706
+
707
+        $dirContent = Helper::getTrashFiles('/', $user, 'mtime');
708
+
709
+        // delete all files older then $retention_obligation
710
+        list($delSize, $count) = self::deleteExpiredFiles($dirContent, $user);
711
+
712
+        $availableSpace += $delSize;
713
+
714
+        // delete files from trash until we meet the trash bin size limit again
715
+        self::deleteFiles(array_slice($dirContent, $count), $user, $availableSpace);
716
+    }
717
+
718
+    /**
719
+     * @param string $user
720
+     */
721
+    private static function scheduleExpire($user) {
722
+        // let the admin disable auto expire
723
+        $application = new Application();
724
+        $expiration = $application->getContainer()->query('Expiration');
725
+        if ($expiration->isEnabled()) {
726
+            \OC::$server->getCommandBus()->push(new Expire($user));
727
+        }
728
+    }
729
+
730
+    /**
731
+     * if the size limit for the trash bin is reached, we delete the oldest
732
+     * files in the trash bin until we meet the limit again
733
+     *
734
+     * @param array $files
735
+     * @param string $user
736
+     * @param int $availableSpace available disc space
737
+     * @return int size of deleted files
738
+     */
739
+    protected static function deleteFiles($files, $user, $availableSpace) {
740
+        $application = new Application();
741
+        $expiration = $application->getContainer()->query('Expiration');
742
+        $size = 0;
743
+
744
+        if ($availableSpace < 0) {
745
+            foreach ($files as $file) {
746
+                if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
747
+                    $tmp = self::delete($file['name'], $user, $file['mtime']);
748
+                    \OCP\Util::writeLog('files_trashbin', 'remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', \OCP\Util::INFO);
749
+                    $availableSpace += $tmp;
750
+                    $size += $tmp;
751
+                } else {
752
+                    break;
753
+                }
754
+            }
755
+        }
756
+        return $size;
757
+    }
758
+
759
+    /**
760
+     * delete files older then max storage time
761
+     *
762
+     * @param array $files list of files sorted by mtime
763
+     * @param string $user
764
+     * @return integer[] size of deleted files and number of deleted files
765
+     */
766
+    public static function deleteExpiredFiles($files, $user) {
767
+        $application = new Application();
768
+        $expiration = $application->getContainer()->query('Expiration');
769
+        $size = 0;
770
+        $count = 0;
771
+        foreach ($files as $file) {
772
+            $timestamp = $file['mtime'];
773
+            $filename = $file['name'];
774
+            if ($expiration->isExpired($timestamp)) {
775
+                $count++;
776
+                $size += self::delete($filename, $user, $timestamp);
777
+                \OC::$server->getLogger()->info(
778
+                    'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
779
+                    ['app' => 'files_trashbin']
780
+                );
781
+            } else {
782
+                break;
783
+            }
784
+        }
785
+
786
+        return array($size, $count);
787
+    }
788
+
789
+    /**
790
+     * recursive copy to copy a whole directory
791
+     *
792
+     * @param string $source source path, relative to the users files directory
793
+     * @param string $destination destination path relative to the users root directoy
794
+     * @param View $view file view for the users root directory
795
+     * @return int
796
+     * @throws Exceptions\CopyRecursiveException
797
+     */
798
+    private static function copy_recursive($source, $destination, View $view) {
799
+        $size = 0;
800
+        if ($view->is_dir($source)) {
801
+            $view->mkdir($destination);
802
+            $view->touch($destination, $view->filemtime($source));
803
+            foreach ($view->getDirectoryContent($source) as $i) {
804
+                $pathDir = $source . '/' . $i['name'];
805
+                if ($view->is_dir($pathDir)) {
806
+                    $size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
807
+                } else {
808
+                    $size += $view->filesize($pathDir);
809
+                    $result = $view->copy($pathDir, $destination . '/' . $i['name']);
810
+                    if (!$result) {
811
+                        throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
812
+                    }
813
+                    $view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
814
+                }
815
+            }
816
+        } else {
817
+            $size += $view->filesize($source);
818
+            $result = $view->copy($source, $destination);
819
+            if (!$result) {
820
+                throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
821
+            }
822
+            $view->touch($destination, $view->filemtime($source));
823
+        }
824
+        return $size;
825
+    }
826
+
827
+    /**
828
+     * find all versions which belong to the file we want to restore
829
+     *
830
+     * @param string $filename name of the file which should be restored
831
+     * @param int $timestamp timestamp when the file was deleted
832
+     * @return array
833
+     */
834
+    private static function getVersionsFromTrash($filename, $timestamp, $user) {
835
+        $view = new View('/' . $user . '/files_trashbin/versions');
836
+        $versions = array();
837
+
838
+        //force rescan of versions, local storage may not have updated the cache
839
+        if (!self::$scannedVersions) {
840
+            /** @var \OC\Files\Storage\Storage $storage */
841
+            list($storage,) = $view->resolvePath('/');
842
+            $storage->getScanner()->scan('files_trashbin/versions');
843
+            self::$scannedVersions = true;
844
+        }
845
+
846
+        if ($timestamp) {
847
+            // fetch for old versions
848
+            $matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
849
+            $offset = -strlen($timestamp) - 2;
850
+        } else {
851
+            $matches = $view->searchRaw($filename . '.v%');
852
+        }
853
+
854
+        if (is_array($matches)) {
855
+            foreach ($matches as $ma) {
856
+                if ($timestamp) {
857
+                    $parts = explode('.v', substr($ma['path'], 0, $offset));
858
+                    $versions[] = (end($parts));
859
+                } else {
860
+                    $parts = explode('.v', $ma);
861
+                    $versions[] = (end($parts));
862
+                }
863
+            }
864
+        }
865
+        return $versions;
866
+    }
867
+
868
+    /**
869
+     * find unique extension for restored file if a file with the same name already exists
870
+     *
871
+     * @param string $location where the file should be restored
872
+     * @param string $filename name of the file
873
+     * @param View $view filesystem view relative to users root directory
874
+     * @return string with unique extension
875
+     */
876
+    private static function getUniqueFilename($location, $filename, View $view) {
877
+        $ext = pathinfo($filename, PATHINFO_EXTENSION);
878
+        $name = pathinfo($filename, PATHINFO_FILENAME);
879
+        $l = \OC::$server->getL10N('files_trashbin');
880
+
881
+        $location = '/' . trim($location, '/');
882
+
883
+        // if extension is not empty we set a dot in front of it
884
+        if ($ext !== '') {
885
+            $ext = '.' . $ext;
886
+        }
887
+
888
+        if ($view->file_exists('files' . $location . '/' . $filename)) {
889
+            $i = 2;
890
+            $uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
891
+            while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
892
+                $uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
893
+                $i++;
894
+            }
895
+
896
+            return $uniqueName;
897
+        }
898
+
899
+        return $filename;
900
+    }
901
+
902
+    /**
903
+     * get the size from a given root folder
904
+     *
905
+     * @param View $view file view on the root folder
906
+     * @return integer size of the folder
907
+     */
908
+    private static function calculateSize($view) {
909
+        $root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
910
+        if (!file_exists($root)) {
911
+            return 0;
912
+        }
913
+        $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root), \RecursiveIteratorIterator::CHILD_FIRST);
914
+        $size = 0;
915
+
916
+        /**
917
+         * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
918
+         * This bug is fixed in PHP 5.5.9 or before
919
+         * See #8376
920
+         */
921
+        $iterator->rewind();
922
+        while ($iterator->valid()) {
923
+            $path = $iterator->current();
924
+            $relpath = substr($path, strlen($root) - 1);
925
+            if (!$view->is_dir($relpath)) {
926
+                $size += $view->filesize($relpath);
927
+            }
928
+            $iterator->next();
929
+        }
930
+        return $size;
931
+    }
932
+
933
+    /**
934
+     * get current size of trash bin from a given user
935
+     *
936
+     * @param string $user user who owns the trash bin
937
+     * @return integer trash bin size
938
+     */
939
+    private static function getTrashbinSize($user) {
940
+        $view = new View('/' . $user);
941
+        $fileInfo = $view->getFileInfo('/files_trashbin');
942
+        return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
943
+    }
944
+
945
+    /**
946
+     * register hooks
947
+     */
948
+    public static function registerHooks() {
949
+        // create storage wrapper on setup
950
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', 'OCA\Files_Trashbin\Storage', 'setupStorage');
951
+        //Listen to delete user signal
952
+        \OCP\Util::connectHook('OC_User', 'pre_deleteUser', 'OCA\Files_Trashbin\Hooks', 'deleteUser_hook');
953
+        //Listen to post write hook
954
+        \OCP\Util::connectHook('OC_Filesystem', 'post_write', 'OCA\Files_Trashbin\Hooks', 'post_write_hook');
955
+        // pre and post-rename, disable trash logic for the copy+unlink case
956
+        \OCP\Util::connectHook('OC_Filesystem', 'delete', 'OCA\Files_Trashbin\Trashbin', 'ensureFileScannedHook');
957
+        \OCP\Util::connectHook('OC_Filesystem', 'rename', 'OCA\Files_Trashbin\Storage', 'preRenameHook');
958
+        \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Files_Trashbin\Storage', 'postRenameHook');
959
+    }
960
+
961
+    /**
962
+     * check if trash bin is empty for a given user
963
+     *
964
+     * @param string $user
965
+     * @return bool
966
+     */
967
+    public static function isEmpty($user) {
968
+
969
+        $view = new View('/' . $user . '/files_trashbin');
970
+        if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
971
+            while ($file = readdir($dh)) {
972
+                if (!Filesystem::isIgnoredDir($file)) {
973
+                    return false;
974
+                }
975
+            }
976
+        }
977
+        return true;
978
+    }
979
+
980
+    /**
981
+     * @param $path
982
+     * @return string
983
+     */
984
+    public static function preview_icon($path) {
985
+        return \OCP\Util::linkToRoute('core_ajax_trashbin_preview', array('x' => 32, 'y' => 32, 'file' => $path));
986
+    }
987 987
 }
Please login to merge, or discard this patch.
Spacing   +73 added lines, -73 removed lines patch added patch discarded remove patch
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 		Filesystem::initMountPoints($uid);
96 96
 		if ($uid != User::getUser()) {
97 97
 			$info = Filesystem::getFileInfo($filename);
98
-			$ownerView = new View('/' . $uid . '/files');
98
+			$ownerView = new View('/'.$uid.'/files');
99 99
 			try {
100 100
 				$filename = $ownerView->getPath($info['fileid']);
101 101
 			} catch (NotFoundException $e) {
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
 	}
147 147
 
148 148
 	private static function setUpTrash($user) {
149
-		$view = new View('/' . $user);
149
+		$view = new View('/'.$user);
150 150
 		if (!$view->is_dir('files_trashbin')) {
151 151
 			$view->mkdir('files_trashbin');
152 152
 		}
@@ -181,8 +181,8 @@  discard block
 block discarded – undo
181 181
 
182 182
 		$view = new View('/');
183 183
 
184
-		$target = $user . '/files_trashbin/files/' . $targetFilename . '.d' . $timestamp;
185
-		$source = $owner . '/files_trashbin/files/' . $sourceFilename . '.d' . $timestamp;
184
+		$target = $user.'/files_trashbin/files/'.$targetFilename.'.d'.$timestamp;
185
+		$source = $owner.'/files_trashbin/files/'.$sourceFilename.'.d'.$timestamp;
186 186
 		self::copy_recursive($source, $target, $view);
187 187
 
188 188
 
@@ -216,9 +216,9 @@  discard block
 block discarded – undo
216 216
 			$ownerPath = $file_path;
217 217
 		}
218 218
 
219
-		$ownerView = new View('/' . $owner);
219
+		$ownerView = new View('/'.$owner);
220 220
 		// file has been deleted in between
221
-		if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/' . $ownerPath)) {
221
+		if (is_null($ownerPath) || $ownerPath === '' || !$ownerView->file_exists('/files/'.$ownerPath)) {
222 222
 			return true;
223 223
 		}
224 224
 
@@ -235,12 +235,12 @@  discard block
 block discarded – undo
235 235
 		$timestamp = time();
236 236
 
237 237
 		// disable proxy to prevent recursive calls
238
-		$trashPath = '/files_trashbin/files/' . $filename . '.d' . $timestamp;
238
+		$trashPath = '/files_trashbin/files/'.$filename.'.d'.$timestamp;
239 239
 
240 240
 		/** @var \OC\Files\Storage\Storage $trashStorage */
241 241
 		list($trashStorage, $trashInternalPath) = $ownerView->resolvePath($trashPath);
242 242
 		/** @var \OC\Files\Storage\Storage $sourceStorage */
243
-		list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/' . $ownerPath);
243
+		list($sourceStorage, $sourceInternalPath) = $ownerView->resolvePath('/files/'.$ownerPath);
244 244
 		try {
245 245
 			$moveSuccessful = true;
246 246
 			if ($trashStorage->file_exists($trashInternalPath)) {
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 			if ($trashStorage->file_exists($trashInternalPath)) {
253 253
 				$trashStorage->unlink($trashInternalPath);
254 254
 			}
255
-			\OCP\Util::writeLog('files_trashbin', 'Couldn\'t move ' . $file_path . ' to the trash bin', \OCP\Util::ERROR);
255
+			\OCP\Util::writeLog('files_trashbin', 'Couldn\'t move '.$file_path.' to the trash bin', \OCP\Util::ERROR);
256 256
 		}
257 257
 
258 258
 		if ($sourceStorage->file_exists($sourceInternalPath)) { // failed to delete the original file, abort
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
 				\OCP\Util::writeLog('files_trashbin', 'trash bin database couldn\'t be updated', \OCP\Util::ERROR);
274 274
 			}
275 275
 			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_moveToTrash', array('filePath' => Filesystem::normalizePath($file_path),
276
-				'trashPath' => Filesystem::normalizePath($filename . '.d' . $timestamp)));
276
+				'trashPath' => Filesystem::normalizePath($filename.'.d'.$timestamp)));
277 277
 
278 278
 			self::retainVersions($filename, $owner, $ownerPath, $timestamp);
279 279
 
@@ -307,18 +307,18 @@  discard block
 block discarded – undo
307 307
 			$user = User::getUser();
308 308
 			$rootView = new View('/');
309 309
 
310
-			if ($rootView->is_dir($owner . '/files_versions/' . $ownerPath)) {
310
+			if ($rootView->is_dir($owner.'/files_versions/'.$ownerPath)) {
311 311
 				if ($owner !== $user) {
312
-					self::copy_recursive($owner . '/files_versions/' . $ownerPath, $owner . '/files_trashbin/versions/' . basename($ownerPath) . '.d' . $timestamp, $rootView);
312
+					self::copy_recursive($owner.'/files_versions/'.$ownerPath, $owner.'/files_trashbin/versions/'.basename($ownerPath).'.d'.$timestamp, $rootView);
313 313
 				}
314
-				self::move($rootView, $owner . '/files_versions/' . $ownerPath, $user . '/files_trashbin/versions/' . $filename . '.d' . $timestamp);
314
+				self::move($rootView, $owner.'/files_versions/'.$ownerPath, $user.'/files_trashbin/versions/'.$filename.'.d'.$timestamp);
315 315
 			} else if ($versions = \OCA\Files_Versions\Storage::getVersions($owner, $ownerPath)) {
316 316
 
317 317
 				foreach ($versions as $v) {
318 318
 					if ($owner !== $user) {
319
-						self::copy($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $owner . '/files_trashbin/versions/' . $v['name'] . '.v' . $v['version'] . '.d' . $timestamp);
319
+						self::copy($rootView, $owner.'/files_versions'.$v['path'].'.v'.$v['version'], $owner.'/files_trashbin/versions/'.$v['name'].'.v'.$v['version'].'.d'.$timestamp);
320 320
 					}
321
-					self::move($rootView, $owner . '/files_versions' . $v['path'] . '.v' . $v['version'], $user . '/files_trashbin/versions/' . $filename . '.v' . $v['version'] . '.d' . $timestamp);
321
+					self::move($rootView, $owner.'/files_versions'.$v['path'].'.v'.$v['version'], $user.'/files_trashbin/versions/'.$filename.'.v'.$v['version'].'.d'.$timestamp);
322 322
 				}
323 323
 			}
324 324
 		}
@@ -380,18 +380,18 @@  discard block
 block discarded – undo
380 380
 	 */
381 381
 	public static function restore($file, $filename, $timestamp) {
382 382
 		$user = User::getUser();
383
-		$view = new View('/' . $user);
383
+		$view = new View('/'.$user);
384 384
 
385 385
 		$location = '';
386 386
 		if ($timestamp) {
387 387
 			$location = self::getLocation($user, $filename, $timestamp);
388 388
 			if ($location === false) {
389
-				\OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent! ($user: ' . $user . ' $filename: ' . $filename . ', $timestamp: ' . $timestamp . ')', \OCP\Util::ERROR);
389
+				\OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent! ($user: '.$user.' $filename: '.$filename.', $timestamp: '.$timestamp.')', \OCP\Util::ERROR);
390 390
 			} else {
391 391
 				// if location no longer exists, restore file in the root directory
392 392
 				if ($location !== '/' &&
393
-					(!$view->is_dir('files/' . $location) ||
394
-						!$view->isCreatable('files/' . $location))
393
+					(!$view->is_dir('files/'.$location) ||
394
+						!$view->isCreatable('files/'.$location))
395 395
 				) {
396 396
 					$location = '';
397 397
 				}
@@ -401,8 +401,8 @@  discard block
 block discarded – undo
401 401
 		// we need a  extension in case a file/dir with the same name already exists
402 402
 		$uniqueFilename = self::getUniqueFilename($location, $filename, $view);
403 403
 
404
-		$source = Filesystem::normalizePath('files_trashbin/files/' . $file);
405
-		$target = Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename);
404
+		$source = Filesystem::normalizePath('files_trashbin/files/'.$file);
405
+		$target = Filesystem::normalizePath('files/'.$location.'/'.$uniqueFilename);
406 406
 		if (!$view->file_exists($source)) {
407 407
 			return false;
408 408
 		}
@@ -414,10 +414,10 @@  discard block
 block discarded – undo
414 414
 		// handle the restore result
415 415
 		if ($restoreResult) {
416 416
 			$fakeRoot = $view->getRoot();
417
-			$view->chroot('/' . $user . '/files');
418
-			$view->touch('/' . $location . '/' . $uniqueFilename, $mtime);
417
+			$view->chroot('/'.$user.'/files');
418
+			$view->touch('/'.$location.'/'.$uniqueFilename, $mtime);
419 419
 			$view->chroot($fakeRoot);
420
-			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename),
420
+			\OCP\Util::emitHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', array('filePath' => Filesystem::normalizePath('/'.$location.'/'.$uniqueFilename),
421 421
 				'trashPath' => Filesystem::normalizePath($file)));
422 422
 
423 423
 			self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp);
@@ -451,7 +451,7 @@  discard block
 block discarded – undo
451 451
 			$user = User::getUser();
452 452
 			$rootView = new View('/');
453 453
 
454
-			$target = Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename);
454
+			$target = Filesystem::normalizePath('/'.$location.'/'.$uniqueFilename);
455 455
 
456 456
 			list($owner, $ownerPath) = self::getUidAndFilename($target);
457 457
 
@@ -466,14 +466,14 @@  discard block
 block discarded – undo
466 466
 				$versionedFile = $file;
467 467
 			}
468 468
 
469
-			if ($view->is_dir('/files_trashbin/versions/' . $file)) {
470
-				$rootView->rename(Filesystem::normalizePath($user . '/files_trashbin/versions/' . $file), Filesystem::normalizePath($owner . '/files_versions/' . $ownerPath));
469
+			if ($view->is_dir('/files_trashbin/versions/'.$file)) {
470
+				$rootView->rename(Filesystem::normalizePath($user.'/files_trashbin/versions/'.$file), Filesystem::normalizePath($owner.'/files_versions/'.$ownerPath));
471 471
 			} else if ($versions = self::getVersionsFromTrash($versionedFile, $timestamp, $user)) {
472 472
 				foreach ($versions as $v) {
473 473
 					if ($timestamp) {
474
-						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v . '.d' . $timestamp, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
474
+						$rootView->rename($user.'/files_trashbin/versions/'.$versionedFile.'.v'.$v.'.d'.$timestamp, $owner.'/files_versions/'.$ownerPath.'.v'.$v);
475 475
 					} else {
476
-						$rootView->rename($user . '/files_trashbin/versions/' . $versionedFile . '.v' . $v, $owner . '/files_versions/' . $ownerPath . '.v' . $v);
476
+						$rootView->rename($user.'/files_trashbin/versions/'.$versionedFile.'.v'.$v, $owner.'/files_versions/'.$ownerPath.'.v'.$v);
477 477
 					}
478 478
 				}
479 479
 			}
@@ -485,12 +485,12 @@  discard block
 block discarded – undo
485 485
 	 */
486 486
 	public static function deleteAll() {
487 487
 		$user = User::getUser();
488
-		$view = new View('/' . $user);
488
+		$view = new View('/'.$user);
489 489
 		$fileInfos = $view->getDirectoryContent('files_trashbin/files');
490 490
 
491 491
 		// Array to store the relative path in (after the file is deleted, the view won't be able to relativise the path anymore)
492 492
 		$filePaths = array();
493
-		foreach($fileInfos as $fileInfo){
493
+		foreach ($fileInfos as $fileInfo) {
494 494
 			$filePaths[] = $view->getRelativePath($fileInfo->getPath());
495 495
 		}
496 496
 		unset($fileInfos); // save memory
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
 		\OC_Hook::emit('\OCP\Trashbin', 'preDeleteAll', array('paths' => $filePaths));
500 500
 
501 501
 		// Single-File Hooks
502
-		foreach($filePaths as $path){
502
+		foreach ($filePaths as $path) {
503 503
 			self::emitTrashbinPreDelete($path);
504 504
 		}
505 505
 
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
 		\OC_Hook::emit('\OCP\Trashbin', 'deleteAll', array('paths' => $filePaths));
513 513
 
514 514
 		// Single-File Hooks
515
-		foreach($filePaths as $path){
515
+		foreach ($filePaths as $path) {
516 516
 			self::emitTrashbinPostDelete($path);
517 517
 		}
518 518
 
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
 	 * wrapper function to emit the 'preDelete' hook of \OCP\Trashbin before a file is deleted
527 527
 	 * @param string $path
528 528
 	 */
529
-	protected static function emitTrashbinPreDelete($path){
529
+	protected static function emitTrashbinPreDelete($path) {
530 530
 		\OC_Hook::emit('\OCP\Trashbin', 'preDelete', array('path' => $path));
531 531
 	}
532 532
 
@@ -534,7 +534,7 @@  discard block
 block discarded – undo
534 534
 	 * wrapper function to emit the 'delete' hook of \OCP\Trashbin after a file has been deleted
535 535
 	 * @param string $path
536 536
 	 */
537
-	protected static function emitTrashbinPostDelete($path){
537
+	protected static function emitTrashbinPostDelete($path) {
538 538
 		\OC_Hook::emit('\OCP\Trashbin', 'delete', array('path' => $path));
539 539
 	}
540 540
 
@@ -548,27 +548,27 @@  discard block
 block discarded – undo
548 548
 	 * @return int size of deleted files
549 549
 	 */
550 550
 	public static function delete($filename, $user, $timestamp = null) {
551
-		$view = new View('/' . $user);
551
+		$view = new View('/'.$user);
552 552
 		$size = 0;
553 553
 
554 554
 		if ($timestamp) {
555 555
 			$query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?');
556 556
 			$query->execute(array($user, $filename, $timestamp));
557
-			$file = $filename . '.d' . $timestamp;
557
+			$file = $filename.'.d'.$timestamp;
558 558
 		} else {
559 559
 			$file = $filename;
560 560
 		}
561 561
 
562 562
 		$size += self::deleteVersions($view, $file, $filename, $timestamp, $user);
563 563
 
564
-		if ($view->is_dir('/files_trashbin/files/' . $file)) {
565
-			$size += self::calculateSize(new View('/' . $user . '/files_trashbin/files/' . $file));
564
+		if ($view->is_dir('/files_trashbin/files/'.$file)) {
565
+			$size += self::calculateSize(new View('/'.$user.'/files_trashbin/files/'.$file));
566 566
 		} else {
567
-			$size += $view->filesize('/files_trashbin/files/' . $file);
567
+			$size += $view->filesize('/files_trashbin/files/'.$file);
568 568
 		}
569
-		self::emitTrashbinPreDelete('/files_trashbin/files/' . $file);
570
-		$view->unlink('/files_trashbin/files/' . $file);
571
-		self::emitTrashbinPostDelete('/files_trashbin/files/' . $file);
569
+		self::emitTrashbinPreDelete('/files_trashbin/files/'.$file);
570
+		$view->unlink('/files_trashbin/files/'.$file);
571
+		self::emitTrashbinPostDelete('/files_trashbin/files/'.$file);
572 572
 
573 573
 		return $size;
574 574
 	}
@@ -584,17 +584,17 @@  discard block
 block discarded – undo
584 584
 	private static function deleteVersions(View $view, $file, $filename, $timestamp, $user) {
585 585
 		$size = 0;
586 586
 		if (\OCP\App::isEnabled('files_versions')) {
587
-			if ($view->is_dir('files_trashbin/versions/' . $file)) {
588
-				$size += self::calculateSize(new View('/' . $user . '/files_trashbin/versions/' . $file));
589
-				$view->unlink('files_trashbin/versions/' . $file);
587
+			if ($view->is_dir('files_trashbin/versions/'.$file)) {
588
+				$size += self::calculateSize(new View('/'.$user.'/files_trashbin/versions/'.$file));
589
+				$view->unlink('files_trashbin/versions/'.$file);
590 590
 			} else if ($versions = self::getVersionsFromTrash($filename, $timestamp, $user)) {
591 591
 				foreach ($versions as $v) {
592 592
 					if ($timestamp) {
593
-						$size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
594
-						$view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v . '.d' . $timestamp);
593
+						$size += $view->filesize('/files_trashbin/versions/'.$filename.'.v'.$v.'.d'.$timestamp);
594
+						$view->unlink('/files_trashbin/versions/'.$filename.'.v'.$v.'.d'.$timestamp);
595 595
 					} else {
596
-						$size += $view->filesize('/files_trashbin/versions/' . $filename . '.v' . $v);
597
-						$view->unlink('/files_trashbin/versions/' . $filename . '.v' . $v);
596
+						$size += $view->filesize('/files_trashbin/versions/'.$filename.'.v'.$v);
597
+						$view->unlink('/files_trashbin/versions/'.$filename.'.v'.$v);
598 598
 					}
599 599
 				}
600 600
 			}
@@ -611,15 +611,15 @@  discard block
 block discarded – undo
611 611
 	 */
612 612
 	public static function file_exists($filename, $timestamp = null) {
613 613
 		$user = User::getUser();
614
-		$view = new View('/' . $user);
614
+		$view = new View('/'.$user);
615 615
 
616 616
 		if ($timestamp) {
617
-			$filename = $filename . '.d' . $timestamp;
617
+			$filename = $filename.'.d'.$timestamp;
618 618
 		} else {
619 619
 			$filename = $filename;
620 620
 		}
621 621
 
622
-		$target = Filesystem::normalizePath('files_trashbin/files/' . $filename);
622
+		$target = Filesystem::normalizePath('files_trashbin/files/'.$filename);
623 623
 		return $view->file_exists($target);
624 624
 	}
625 625
 
@@ -644,7 +644,7 @@  discard block
 block discarded – undo
644 644
 	private static function calculateFreeSpace($trashbinSize, $user) {
645 645
 		$softQuota = true;
646 646
 		$userObject = \OC::$server->getUserManager()->get($user);
647
-		if(is_null($userObject)) {
647
+		if (is_null($userObject)) {
648 648
 			return 0;
649 649
 		}
650 650
 		$quota = $userObject->getQuota();
@@ -663,7 +663,7 @@  discard block
 block discarded – undo
663 663
 		// subtract size of files and current trash bin size from quota
664 664
 		if ($softQuota) {
665 665
 			$userFolder = \OC::$server->getUserFolder($user);
666
-			if(is_null($userFolder)) {
666
+			if (is_null($userFolder)) {
667 667
 				return 0;
668 668
 			}
669 669
 			$free = $quota - $userFolder->getSize(); // remaining free space for user
@@ -745,7 +745,7 @@  discard block
 block discarded – undo
745 745
 			foreach ($files as $file) {
746 746
 				if ($availableSpace < 0 && $expiration->isExpired($file['mtime'], true)) {
747 747
 					$tmp = self::delete($file['name'], $user, $file['mtime']);
748
-					\OCP\Util::writeLog('files_trashbin', 'remove "' . $file['name'] . '" (' . $tmp . 'B) to meet the limit of trash bin size (50% of available quota)', \OCP\Util::INFO);
748
+					\OCP\Util::writeLog('files_trashbin', 'remove "'.$file['name'].'" ('.$tmp.'B) to meet the limit of trash bin size (50% of available quota)', \OCP\Util::INFO);
749 749
 					$availableSpace += $tmp;
750 750
 					$size += $tmp;
751 751
 				} else {
@@ -775,7 +775,7 @@  discard block
 block discarded – undo
775 775
 				$count++;
776 776
 				$size += self::delete($filename, $user, $timestamp);
777 777
 				\OC::$server->getLogger()->info(
778
-					'Remove "' . $filename . '" from trashbin because it exceeds max retention obligation term.',
778
+					'Remove "'.$filename.'" from trashbin because it exceeds max retention obligation term.',
779 779
 					['app' => 'files_trashbin']
780 780
 				);
781 781
 			} else {
@@ -801,16 +801,16 @@  discard block
 block discarded – undo
801 801
 			$view->mkdir($destination);
802 802
 			$view->touch($destination, $view->filemtime($source));
803 803
 			foreach ($view->getDirectoryContent($source) as $i) {
804
-				$pathDir = $source . '/' . $i['name'];
804
+				$pathDir = $source.'/'.$i['name'];
805 805
 				if ($view->is_dir($pathDir)) {
806
-					$size += self::copy_recursive($pathDir, $destination . '/' . $i['name'], $view);
806
+					$size += self::copy_recursive($pathDir, $destination.'/'.$i['name'], $view);
807 807
 				} else {
808 808
 					$size += $view->filesize($pathDir);
809
-					$result = $view->copy($pathDir, $destination . '/' . $i['name']);
809
+					$result = $view->copy($pathDir, $destination.'/'.$i['name']);
810 810
 					if (!$result) {
811 811
 						throw new \OCA\Files_Trashbin\Exceptions\CopyRecursiveException();
812 812
 					}
813
-					$view->touch($destination . '/' . $i['name'], $view->filemtime($pathDir));
813
+					$view->touch($destination.'/'.$i['name'], $view->filemtime($pathDir));
814 814
 				}
815 815
 			}
816 816
 		} else {
@@ -832,7 +832,7 @@  discard block
 block discarded – undo
832 832
 	 * @return array
833 833
 	 */
834 834
 	private static function getVersionsFromTrash($filename, $timestamp, $user) {
835
-		$view = new View('/' . $user . '/files_trashbin/versions');
835
+		$view = new View('/'.$user.'/files_trashbin/versions');
836 836
 		$versions = array();
837 837
 
838 838
 		//force rescan of versions, local storage may not have updated the cache
@@ -845,10 +845,10 @@  discard block
 block discarded – undo
845 845
 
846 846
 		if ($timestamp) {
847 847
 			// fetch for old versions
848
-			$matches = $view->searchRaw($filename . '.v%.d' . $timestamp);
848
+			$matches = $view->searchRaw($filename.'.v%.d'.$timestamp);
849 849
 			$offset = -strlen($timestamp) - 2;
850 850
 		} else {
851
-			$matches = $view->searchRaw($filename . '.v%');
851
+			$matches = $view->searchRaw($filename.'.v%');
852 852
 		}
853 853
 
854 854
 		if (is_array($matches)) {
@@ -878,18 +878,18 @@  discard block
 block discarded – undo
878 878
 		$name = pathinfo($filename, PATHINFO_FILENAME);
879 879
 		$l = \OC::$server->getL10N('files_trashbin');
880 880
 
881
-		$location = '/' . trim($location, '/');
881
+		$location = '/'.trim($location, '/');
882 882
 
883 883
 		// if extension is not empty we set a dot in front of it
884 884
 		if ($ext !== '') {
885
-			$ext = '.' . $ext;
885
+			$ext = '.'.$ext;
886 886
 		}
887 887
 
888
-		if ($view->file_exists('files' . $location . '/' . $filename)) {
888
+		if ($view->file_exists('files'.$location.'/'.$filename)) {
889 889
 			$i = 2;
890
-			$uniqueName = $name . " (" . $l->t("restored") . ")" . $ext;
891
-			while ($view->file_exists('files' . $location . '/' . $uniqueName)) {
892
-				$uniqueName = $name . " (" . $l->t("restored") . " " . $i . ")" . $ext;
890
+			$uniqueName = $name." (".$l->t("restored").")".$ext;
891
+			while ($view->file_exists('files'.$location.'/'.$uniqueName)) {
892
+				$uniqueName = $name." (".$l->t("restored")." ".$i.")".$ext;
893 893
 				$i++;
894 894
 			}
895 895
 
@@ -906,7 +906,7 @@  discard block
 block discarded – undo
906 906
 	 * @return integer size of the folder
907 907
 	 */
908 908
 	private static function calculateSize($view) {
909
-		$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . $view->getAbsolutePath('');
909
+		$root = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').$view->getAbsolutePath('');
910 910
 		if (!file_exists($root)) {
911 911
 			return 0;
912 912
 		}
@@ -937,7 +937,7 @@  discard block
 block discarded – undo
937 937
 	 * @return integer trash bin size
938 938
 	 */
939 939
 	private static function getTrashbinSize($user) {
940
-		$view = new View('/' . $user);
940
+		$view = new View('/'.$user);
941 941
 		$fileInfo = $view->getFileInfo('/files_trashbin');
942 942
 		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
943 943
 	}
@@ -966,7 +966,7 @@  discard block
 block discarded – undo
966 966
 	 */
967 967
 	public static function isEmpty($user) {
968 968
 
969
-		$view = new View('/' . $user . '/files_trashbin');
969
+		$view = new View('/'.$user.'/files_trashbin');
970 970
 		if ($view->is_dir('/files') && $dh = $view->opendir('/files')) {
971 971
 			while ($file = readdir($dh)) {
972 972
 				if (!Filesystem::isIgnoredDir($file)) {
Please login to merge, or discard this patch.