Passed
Push — master ( 6156a4...5d03b5 )
by Blizzz
14:08 queued 10s
created
lib/private/DateTimeZone.php 2 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
 		try {
66 66
 			return new \DateTimeZone($timeZone);
67 67
 		} catch (\Exception $e) {
68
-			\OCP\Util::writeLog('datetimezone', 'Failed to created DateTimeZone "' . $timeZone . "'", ILogger::DEBUG);
68
+			\OCP\Util::writeLog('datetimezone', 'Failed to created DateTimeZone "'.$timeZone."'", ILogger::DEBUG);
69 69
 			return new \DateTimeZone($this->getDefaultTimeZone());
70 70
 		}
71 71
 	}
@@ -86,9 +86,9 @@  discard block
 block discarded – undo
86 86
 			// so a positive offset means negative timeZone
87 87
 			// and the other way around.
88 88
 			if ($offset > 0) {
89
-				$timeZone = 'Etc/GMT-' . $offset;
89
+				$timeZone = 'Etc/GMT-'.$offset;
90 90
 			} else {
91
-				$timeZone = 'Etc/GMT+' . abs($offset);
91
+				$timeZone = 'Etc/GMT+'.abs($offset);
92 92
 			}
93 93
 
94 94
 			return new \DateTimeZone($timeZone);
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 			}
111 111
 
112 112
 			// No timezone found, fallback to UTC
113
-			\OCP\Util::writeLog('datetimezone', 'Failed to find DateTimeZone for offset "' . $offset . "'", ILogger::DEBUG);
113
+			\OCP\Util::writeLog('datetimezone', 'Failed to find DateTimeZone for offset "'.$offset."'", ILogger::DEBUG);
114 114
 			return new \DateTimeZone($this->getDefaultTimeZone());
115 115
 		}
116 116
 	}
Please login to merge, or discard this patch.
Indentation   +86 added lines, -86 removed lines patch added patch discarded remove patch
@@ -30,100 +30,100 @@
 block discarded – undo
30 30
 use OCP\ISession;
31 31
 
32 32
 class DateTimeZone implements IDateTimeZone {
33
-	/** @var IConfig */
34
-	protected $config;
33
+    /** @var IConfig */
34
+    protected $config;
35 35
 
36
-	/** @var ISession */
37
-	protected $session;
36
+    /** @var ISession */
37
+    protected $session;
38 38
 
39
-	/**
40
-	 * Constructor
41
-	 *
42
-	 * @param IConfig $config
43
-	 * @param ISession $session
44
-	 */
45
-	public function __construct(IConfig $config, ISession $session) {
46
-		$this->config = $config;
47
-		$this->session = $session;
48
-	}
39
+    /**
40
+     * Constructor
41
+     *
42
+     * @param IConfig $config
43
+     * @param ISession $session
44
+     */
45
+    public function __construct(IConfig $config, ISession $session) {
46
+        $this->config = $config;
47
+        $this->session = $session;
48
+    }
49 49
 
50
-	/**
51
-	 * Get the timezone of the current user, based on his session information and config data
52
-	 *
53
-	 * @param bool|int $timestamp
54
-	 * @return \DateTimeZone
55
-	 */
56
-	public function getTimeZone($timestamp = false) {
57
-		$timeZone = $this->config->getUserValue($this->session->get('user_id'), 'core', 'timezone', null);
58
-		if ($timeZone === null) {
59
-			if ($this->session->exists('timezone')) {
60
-				return $this->guessTimeZoneFromOffset($this->session->get('timezone'), $timestamp);
61
-			}
62
-			$timeZone = $this->getDefaultTimeZone();
63
-		}
50
+    /**
51
+     * Get the timezone of the current user, based on his session information and config data
52
+     *
53
+     * @param bool|int $timestamp
54
+     * @return \DateTimeZone
55
+     */
56
+    public function getTimeZone($timestamp = false) {
57
+        $timeZone = $this->config->getUserValue($this->session->get('user_id'), 'core', 'timezone', null);
58
+        if ($timeZone === null) {
59
+            if ($this->session->exists('timezone')) {
60
+                return $this->guessTimeZoneFromOffset($this->session->get('timezone'), $timestamp);
61
+            }
62
+            $timeZone = $this->getDefaultTimeZone();
63
+        }
64 64
 
65
-		try {
66
-			return new \DateTimeZone($timeZone);
67
-		} catch (\Exception $e) {
68
-			\OCP\Util::writeLog('datetimezone', 'Failed to created DateTimeZone "' . $timeZone . "'", ILogger::DEBUG);
69
-			return new \DateTimeZone($this->getDefaultTimeZone());
70
-		}
71
-	}
65
+        try {
66
+            return new \DateTimeZone($timeZone);
67
+        } catch (\Exception $e) {
68
+            \OCP\Util::writeLog('datetimezone', 'Failed to created DateTimeZone "' . $timeZone . "'", ILogger::DEBUG);
69
+            return new \DateTimeZone($this->getDefaultTimeZone());
70
+        }
71
+    }
72 72
 
73
-	/**
74
-	 * Guess the DateTimeZone for a given offset
75
-	 *
76
-	 * We first try to find a Etc/GMT* timezone, if that does not exist,
77
-	 * we try to find it manually, before falling back to UTC.
78
-	 *
79
-	 * @param mixed $offset
80
-	 * @param bool|int $timestamp
81
-	 * @return \DateTimeZone
82
-	 */
83
-	protected function guessTimeZoneFromOffset($offset, $timestamp) {
84
-		try {
85
-			// Note: the timeZone name is the inverse to the offset,
86
-			// so a positive offset means negative timeZone
87
-			// and the other way around.
88
-			if ($offset > 0) {
89
-				$timeZone = 'Etc/GMT-' . $offset;
90
-			} else {
91
-				$timeZone = 'Etc/GMT+' . abs($offset);
92
-			}
73
+    /**
74
+     * Guess the DateTimeZone for a given offset
75
+     *
76
+     * We first try to find a Etc/GMT* timezone, if that does not exist,
77
+     * we try to find it manually, before falling back to UTC.
78
+     *
79
+     * @param mixed $offset
80
+     * @param bool|int $timestamp
81
+     * @return \DateTimeZone
82
+     */
83
+    protected function guessTimeZoneFromOffset($offset, $timestamp) {
84
+        try {
85
+            // Note: the timeZone name is the inverse to the offset,
86
+            // so a positive offset means negative timeZone
87
+            // and the other way around.
88
+            if ($offset > 0) {
89
+                $timeZone = 'Etc/GMT-' . $offset;
90
+            } else {
91
+                $timeZone = 'Etc/GMT+' . abs($offset);
92
+            }
93 93
 
94
-			return new \DateTimeZone($timeZone);
95
-		} catch (\Exception $e) {
96
-			// If the offset has no Etc/GMT* timezone,
97
-			// we try to guess one timezone that has the same offset
98
-			foreach (\DateTimeZone::listIdentifiers() as $timeZone) {
99
-				$dtz = new \DateTimeZone($timeZone);
100
-				$dateTime = new \DateTime();
94
+            return new \DateTimeZone($timeZone);
95
+        } catch (\Exception $e) {
96
+            // If the offset has no Etc/GMT* timezone,
97
+            // we try to guess one timezone that has the same offset
98
+            foreach (\DateTimeZone::listIdentifiers() as $timeZone) {
99
+                $dtz = new \DateTimeZone($timeZone);
100
+                $dateTime = new \DateTime();
101 101
 
102
-				if ($timestamp !== false) {
103
-					$dateTime->setTimestamp($timestamp);
104
-				}
102
+                if ($timestamp !== false) {
103
+                    $dateTime->setTimestamp($timestamp);
104
+                }
105 105
 
106
-				$dtOffset = $dtz->getOffset($dateTime);
107
-				if ($dtOffset == 3600 * $offset) {
108
-					return $dtz;
109
-				}
110
-			}
106
+                $dtOffset = $dtz->getOffset($dateTime);
107
+                if ($dtOffset == 3600 * $offset) {
108
+                    return $dtz;
109
+                }
110
+            }
111 111
 
112
-			// No timezone found, fallback to UTC
113
-			\OCP\Util::writeLog('datetimezone', 'Failed to find DateTimeZone for offset "' . $offset . "'", ILogger::DEBUG);
114
-			return new \DateTimeZone($this->getDefaultTimeZone());
115
-		}
116
-	}
112
+            // No timezone found, fallback to UTC
113
+            \OCP\Util::writeLog('datetimezone', 'Failed to find DateTimeZone for offset "' . $offset . "'", ILogger::DEBUG);
114
+            return new \DateTimeZone($this->getDefaultTimeZone());
115
+        }
116
+    }
117 117
 
118
-	/**
119
-	 * Get the default timezone of the server
120
-	 *
121
-	 * Falls back to UTC if it is not yet set.
122
-	 *
123
-	 * @return string
124
-	 */
125
-	protected function getDefaultTimeZone() {
126
-		$serverTimeZone = date_default_timezone_get();
127
-		return $serverTimeZone ?: 'UTC';
128
-	}
118
+    /**
119
+     * Get the default timezone of the server
120
+     *
121
+     * Falls back to UTC if it is not yet set.
122
+     *
123
+     * @return string
124
+     */
125
+    protected function getDefaultTimeZone() {
126
+        $serverTimeZone = date_default_timezone_get();
127
+        return $serverTimeZone ?: 'UTC';
128
+    }
129 129
 }
Please login to merge, or discard this patch.
apps/federation/lib/BackgroundJob/GetSharedSecret.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 
146 146
 	protected function run($argument) {
147 147
 		$target = $argument['url'];
148
-		$created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
148
+		$created = isset($argument['created']) ? (int) $argument['created'] : $this->timeFactory->getTime();
149 149
 		$currentTime = $this->timeFactory->getTime();
150 150
 		$source = $this->urlGenerator->getAbsoluteURL('/');
151 151
 		$source = rtrim($source, '/');
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 		$deadline = $currentTime - $this->maxLifespan;
156 156
 		if ($created < $deadline) {
157 157
 			$this->retainJob = false;
158
-			$this->trustedServers->setServerStatus($target,TrustedServers::STATUS_FAILURE);
158
+			$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
159 159
 			return;
160 160
 		}
161 161
 
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
164 164
 
165 165
 		// make sure that we have a well formatted url
166
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/');
166
+		$url = rtrim($target, '/').'/'.trim($endPoint, '/');
167 167
 
168 168
 		$result = null;
169 169
 		try {
@@ -186,21 +186,21 @@  discard block
 block discarded – undo
186 186
 		} catch (ClientException $e) {
187 187
 			$status = $e->getCode();
188 188
 			if ($status === Http::STATUS_FORBIDDEN) {
189
-				$this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
189
+				$this->logger->info($target.' refused to exchange a shared secret with you.', ['app' => 'federation']);
190 190
 			} else {
191
-				$this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
191
+				$this->logger->info($target.' responded with a '.$status.' containing: '.$e->getMessage(), ['app' => 'federation']);
192 192
 			}
193 193
 		} catch (RequestException $e) {
194 194
 			$status = -1; // There is no status code if we could not connect
195 195
 			$this->logger->logException($e, [
196
-				'message' => 'Could not connect to ' . $target,
196
+				'message' => 'Could not connect to '.$target,
197 197
 				'level' => ILogger::INFO,
198 198
 				'app' => 'federation',
199 199
 			]);
200 200
 		} catch (RingException $e) {
201 201
 			$status = -1; // There is no status code if we could not connect
202 202
 			$this->logger->logException($e, [
203
-				'message' => 'Could not connect to ' . $target,
203
+				'message' => 'Could not connect to '.$target,
204 204
 				'level' => ILogger::INFO,
205 205
 				'app' => 'federation',
206 206
 			]);
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
 				);
228 228
 			} else {
229 229
 				$this->logger->error(
230
-						'remote server "' . $target . '"" does not return a valid shared secret. Received data: ' . $body,
230
+						'remote server "'.$target.'"" does not return a valid shared secret. Received data: '.$body,
231 231
 						['app' => 'federation']
232 232
 				);
233 233
 				$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
 	 */
244 244
 	protected function reAddJob(array $argument) {
245 245
 		$url = $argument['url'];
246
-		$created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
246
+		$created = isset($argument['created']) ? (int) $argument['created'] : $this->timeFactory->getTime();
247 247
 		$token = $argument['token'];
248 248
 		$this->jobList->add(
249 249
 			GetSharedSecret::class,
Please login to merge, or discard this patch.
Indentation   +197 added lines, -197 removed lines patch added patch discarded remove patch
@@ -54,201 +54,201 @@
 block discarded – undo
54 54
  */
55 55
 class GetSharedSecret extends Job {
56 56
 
57
-	/** @var IClient */
58
-	private $httpClient;
59
-
60
-	/** @var IJobList */
61
-	private $jobList;
62
-
63
-	/** @var IURLGenerator */
64
-	private $urlGenerator;
65
-
66
-	/** @var TrustedServers  */
67
-	private $trustedServers;
68
-
69
-	/** @var IDiscoveryService  */
70
-	private $ocsDiscoveryService;
71
-
72
-	/** @var ILogger */
73
-	private $logger;
74
-
75
-	/** @var ITimeFactory */
76
-	private $timeFactory;
77
-
78
-	/** @var bool */
79
-	protected $retainJob = false;
80
-
81
-	private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret';
82
-
83
-	/** @var  int  30 day = 2592000sec */
84
-	private $maxLifespan = 2592000;
85
-
86
-	/**
87
-	 * RequestSharedSecret constructor.
88
-	 *
89
-	 * @param IClientService $httpClientService
90
-	 * @param IURLGenerator $urlGenerator
91
-	 * @param IJobList $jobList
92
-	 * @param TrustedServers $trustedServers
93
-	 * @param ILogger $logger
94
-	 * @param IDiscoveryService $ocsDiscoveryService
95
-	 * @param ITimeFactory $timeFactory
96
-	 */
97
-	public function __construct(
98
-		IClientService $httpClientService,
99
-		IURLGenerator $urlGenerator,
100
-		IJobList $jobList,
101
-		TrustedServers $trustedServers,
102
-		ILogger $logger,
103
-		IDiscoveryService $ocsDiscoveryService,
104
-		ITimeFactory $timeFactory
105
-	) {
106
-		$this->logger = $logger;
107
-		$this->httpClient = $httpClientService->newClient();
108
-		$this->jobList = $jobList;
109
-		$this->urlGenerator = $urlGenerator;
110
-		$this->ocsDiscoveryService = $ocsDiscoveryService;
111
-		$this->trustedServers = $trustedServers;
112
-		$this->timeFactory = $timeFactory;
113
-	}
114
-
115
-	/**
116
-	 * run the job, then remove it from the joblist
117
-	 *
118
-	 * @param JobList $jobList
119
-	 * @param ILogger|null $logger
120
-	 */
121
-	public function execute(IJobList $jobList, ILogger $logger = null) {
122
-		$target = $this->argument['url'];
123
-		// only execute if target is still in the list of trusted domains
124
-		if ($this->trustedServers->isTrustedServer($target)) {
125
-			$this->parentExecute($jobList, $logger);
126
-		}
127
-
128
-		$jobList->remove($this, $this->argument);
129
-
130
-		if ($this->retainJob) {
131
-			$this->reAddJob($this->argument);
132
-		}
133
-	}
134
-
135
-	/**
136
-	 * call execute() method of parent
137
-	 *
138
-	 * @param JobList $jobList
139
-	 * @param ILogger $logger
140
-	 */
141
-	protected function parentExecute($jobList, $logger = null) {
142
-		parent::execute($jobList, $logger);
143
-	}
144
-
145
-	protected function run($argument) {
146
-		$target = $argument['url'];
147
-		$created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
148
-		$currentTime = $this->timeFactory->getTime();
149
-		$source = $this->urlGenerator->getAbsoluteURL('/');
150
-		$source = rtrim($source, '/');
151
-		$token = $argument['token'];
152
-
153
-		// kill job after 30 days of trying
154
-		$deadline = $currentTime - $this->maxLifespan;
155
-		if ($created < $deadline) {
156
-			$this->retainJob = false;
157
-			$this->trustedServers->setServerStatus($target,TrustedServers::STATUS_FAILURE);
158
-			return;
159
-		}
160
-
161
-		$endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
162
-		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
163
-
164
-		// make sure that we have a well formatted url
165
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/');
166
-
167
-		$result = null;
168
-		try {
169
-			$result = $this->httpClient->get(
170
-				$url,
171
-				[
172
-					'query' =>
173
-						[
174
-							'url' => $source,
175
-							'token' => $token,
176
-							'format' => 'json',
177
-						],
178
-					'timeout' => 3,
179
-					'connect_timeout' => 3,
180
-				]
181
-			);
182
-
183
-			$status = $result->getStatusCode();
184
-		} catch (ClientException $e) {
185
-			$status = $e->getCode();
186
-			if ($status === Http::STATUS_FORBIDDEN) {
187
-				$this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
188
-			} else {
189
-				$this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
190
-			}
191
-		} catch (RequestException $e) {
192
-			$status = -1; // There is no status code if we could not connect
193
-			$this->logger->logException($e, [
194
-				'message' => 'Could not connect to ' . $target,
195
-				'level' => ILogger::INFO,
196
-				'app' => 'federation',
197
-			]);
198
-		} catch (RingException $e) {
199
-			$status = -1; // There is no status code if we could not connect
200
-			$this->logger->logException($e, [
201
-				'message' => 'Could not connect to ' . $target,
202
-				'level' => ILogger::INFO,
203
-				'app' => 'federation',
204
-			]);
205
-		} catch (\Exception $e) {
206
-			$status = Http::STATUS_INTERNAL_SERVER_ERROR;
207
-			$this->logger->logException($e, ['app' => 'federation']);
208
-		}
209
-
210
-		// if we received a unexpected response we try again later
211
-		if (
212
-			$status !== Http::STATUS_OK
213
-			&& $status !== Http::STATUS_FORBIDDEN
214
-		) {
215
-			$this->retainJob = true;
216
-		}
217
-
218
-		if ($status === Http::STATUS_OK && $result instanceof IResponse) {
219
-			$body = $result->getBody();
220
-			$result = json_decode($body, true);
221
-			if (isset($result['ocs']['data']['sharedSecret'])) {
222
-				$this->trustedServers->addSharedSecret(
223
-						$target,
224
-						$result['ocs']['data']['sharedSecret']
225
-				);
226
-			} else {
227
-				$this->logger->error(
228
-						'remote server "' . $target . '"" does not return a valid shared secret. Received data: ' . $body,
229
-						['app' => 'federation']
230
-				);
231
-				$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
232
-			}
233
-		}
234
-	}
235
-
236
-	/**
237
-	 * re-add background job
238
-	 *
239
-	 * @param array $argument
240
-	 */
241
-	protected function reAddJob(array $argument) {
242
-		$url = $argument['url'];
243
-		$created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
244
-		$token = $argument['token'];
245
-		$this->jobList->add(
246
-			GetSharedSecret::class,
247
-			[
248
-				'url' => $url,
249
-				'token' => $token,
250
-				'created' => $created
251
-			]
252
-		);
253
-	}
57
+    /** @var IClient */
58
+    private $httpClient;
59
+
60
+    /** @var IJobList */
61
+    private $jobList;
62
+
63
+    /** @var IURLGenerator */
64
+    private $urlGenerator;
65
+
66
+    /** @var TrustedServers  */
67
+    private $trustedServers;
68
+
69
+    /** @var IDiscoveryService  */
70
+    private $ocsDiscoveryService;
71
+
72
+    /** @var ILogger */
73
+    private $logger;
74
+
75
+    /** @var ITimeFactory */
76
+    private $timeFactory;
77
+
78
+    /** @var bool */
79
+    protected $retainJob = false;
80
+
81
+    private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret';
82
+
83
+    /** @var  int  30 day = 2592000sec */
84
+    private $maxLifespan = 2592000;
85
+
86
+    /**
87
+     * RequestSharedSecret constructor.
88
+     *
89
+     * @param IClientService $httpClientService
90
+     * @param IURLGenerator $urlGenerator
91
+     * @param IJobList $jobList
92
+     * @param TrustedServers $trustedServers
93
+     * @param ILogger $logger
94
+     * @param IDiscoveryService $ocsDiscoveryService
95
+     * @param ITimeFactory $timeFactory
96
+     */
97
+    public function __construct(
98
+        IClientService $httpClientService,
99
+        IURLGenerator $urlGenerator,
100
+        IJobList $jobList,
101
+        TrustedServers $trustedServers,
102
+        ILogger $logger,
103
+        IDiscoveryService $ocsDiscoveryService,
104
+        ITimeFactory $timeFactory
105
+    ) {
106
+        $this->logger = $logger;
107
+        $this->httpClient = $httpClientService->newClient();
108
+        $this->jobList = $jobList;
109
+        $this->urlGenerator = $urlGenerator;
110
+        $this->ocsDiscoveryService = $ocsDiscoveryService;
111
+        $this->trustedServers = $trustedServers;
112
+        $this->timeFactory = $timeFactory;
113
+    }
114
+
115
+    /**
116
+     * run the job, then remove it from the joblist
117
+     *
118
+     * @param JobList $jobList
119
+     * @param ILogger|null $logger
120
+     */
121
+    public function execute(IJobList $jobList, ILogger $logger = null) {
122
+        $target = $this->argument['url'];
123
+        // only execute if target is still in the list of trusted domains
124
+        if ($this->trustedServers->isTrustedServer($target)) {
125
+            $this->parentExecute($jobList, $logger);
126
+        }
127
+
128
+        $jobList->remove($this, $this->argument);
129
+
130
+        if ($this->retainJob) {
131
+            $this->reAddJob($this->argument);
132
+        }
133
+    }
134
+
135
+    /**
136
+     * call execute() method of parent
137
+     *
138
+     * @param JobList $jobList
139
+     * @param ILogger $logger
140
+     */
141
+    protected function parentExecute($jobList, $logger = null) {
142
+        parent::execute($jobList, $logger);
143
+    }
144
+
145
+    protected function run($argument) {
146
+        $target = $argument['url'];
147
+        $created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
148
+        $currentTime = $this->timeFactory->getTime();
149
+        $source = $this->urlGenerator->getAbsoluteURL('/');
150
+        $source = rtrim($source, '/');
151
+        $token = $argument['token'];
152
+
153
+        // kill job after 30 days of trying
154
+        $deadline = $currentTime - $this->maxLifespan;
155
+        if ($created < $deadline) {
156
+            $this->retainJob = false;
157
+            $this->trustedServers->setServerStatus($target,TrustedServers::STATUS_FAILURE);
158
+            return;
159
+        }
160
+
161
+        $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
162
+        $endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
163
+
164
+        // make sure that we have a well formatted url
165
+        $url = rtrim($target, '/') . '/' . trim($endPoint, '/');
166
+
167
+        $result = null;
168
+        try {
169
+            $result = $this->httpClient->get(
170
+                $url,
171
+                [
172
+                    'query' =>
173
+                        [
174
+                            'url' => $source,
175
+                            'token' => $token,
176
+                            'format' => 'json',
177
+                        ],
178
+                    'timeout' => 3,
179
+                    'connect_timeout' => 3,
180
+                ]
181
+            );
182
+
183
+            $status = $result->getStatusCode();
184
+        } catch (ClientException $e) {
185
+            $status = $e->getCode();
186
+            if ($status === Http::STATUS_FORBIDDEN) {
187
+                $this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
188
+            } else {
189
+                $this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
190
+            }
191
+        } catch (RequestException $e) {
192
+            $status = -1; // There is no status code if we could not connect
193
+            $this->logger->logException($e, [
194
+                'message' => 'Could not connect to ' . $target,
195
+                'level' => ILogger::INFO,
196
+                'app' => 'federation',
197
+            ]);
198
+        } catch (RingException $e) {
199
+            $status = -1; // There is no status code if we could not connect
200
+            $this->logger->logException($e, [
201
+                'message' => 'Could not connect to ' . $target,
202
+                'level' => ILogger::INFO,
203
+                'app' => 'federation',
204
+            ]);
205
+        } catch (\Exception $e) {
206
+            $status = Http::STATUS_INTERNAL_SERVER_ERROR;
207
+            $this->logger->logException($e, ['app' => 'federation']);
208
+        }
209
+
210
+        // if we received a unexpected response we try again later
211
+        if (
212
+            $status !== Http::STATUS_OK
213
+            && $status !== Http::STATUS_FORBIDDEN
214
+        ) {
215
+            $this->retainJob = true;
216
+        }
217
+
218
+        if ($status === Http::STATUS_OK && $result instanceof IResponse) {
219
+            $body = $result->getBody();
220
+            $result = json_decode($body, true);
221
+            if (isset($result['ocs']['data']['sharedSecret'])) {
222
+                $this->trustedServers->addSharedSecret(
223
+                        $target,
224
+                        $result['ocs']['data']['sharedSecret']
225
+                );
226
+            } else {
227
+                $this->logger->error(
228
+                        'remote server "' . $target . '"" does not return a valid shared secret. Received data: ' . $body,
229
+                        ['app' => 'federation']
230
+                );
231
+                $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
232
+            }
233
+        }
234
+    }
235
+
236
+    /**
237
+     * re-add background job
238
+     *
239
+     * @param array $argument
240
+     */
241
+    protected function reAddJob(array $argument) {
242
+        $url = $argument['url'];
243
+        $created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
244
+        $token = $argument['token'];
245
+        $this->jobList->add(
246
+            GetSharedSecret::class,
247
+            [
248
+                'url' => $url,
249
+                'token' => $token,
250
+                'created' => $created
251
+            ]
252
+        );
253
+    }
254 254
 }
Please login to merge, or discard this patch.
lib/public/Log/RotationTrait.php 2 patches
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -32,40 +32,40 @@
 block discarded – undo
32 32
  */
33 33
 trait RotationTrait {
34 34
 
35
-	/**
36
-	 * @var string
37
-	 * @since 14.0.0
38
-	 */
39
-	protected $filePath;
35
+    /**
36
+     * @var string
37
+     * @since 14.0.0
38
+     */
39
+    protected $filePath;
40 40
 
41
-	/**
42
-	 * @var int
43
-	 * @since 14.0.0
44
-	 */
45
-	protected $maxSize;
41
+    /**
42
+     * @var int
43
+     * @since 14.0.0
44
+     */
45
+    protected $maxSize;
46 46
 
47
-	/**
48
-	 * @return string the resulting new filepath
49
-	 * @since 14.0.0
50
-	 */
51
-	protected function rotate():string {
52
-		$rotatedFile = $this->filePath.'.1';
53
-		rename($this->filePath, $rotatedFile);
54
-		return $rotatedFile;
55
-	}
47
+    /**
48
+     * @return string the resulting new filepath
49
+     * @since 14.0.0
50
+     */
51
+    protected function rotate():string {
52
+        $rotatedFile = $this->filePath.'.1';
53
+        rename($this->filePath, $rotatedFile);
54
+        return $rotatedFile;
55
+    }
56 56
 
57
-	/**
58
-	 * @return bool
59
-	 * @since 14.0.0
60
-	 */
61
-	protected function shouldRotateBySize():bool {
62
-		if ((int)$this->maxSize > 0) {
63
-			$filesize = @filesize($this->filePath);
64
-			if ($filesize >= (int)$this->maxSize) {
65
-				return true;
66
-			}
67
-		}
68
-		return false;
69
-	}
57
+    /**
58
+     * @return bool
59
+     * @since 14.0.0
60
+     */
61
+    protected function shouldRotateBySize():bool {
62
+        if ((int)$this->maxSize > 0) {
63
+            $filesize = @filesize($this->filePath);
64
+            if ($filesize >= (int)$this->maxSize) {
65
+                return true;
66
+            }
67
+        }
68
+        return false;
69
+    }
70 70
 
71 71
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -59,9 +59,9 @@
 block discarded – undo
59 59
 	 * @since 14.0.0
60 60
 	 */
61 61
 	protected function shouldRotateBySize():bool {
62
-		if ((int)$this->maxSize > 0) {
62
+		if ((int) $this->maxSize > 0) {
63 63
 			$filesize = @filesize($this->filePath);
64
-			if ($filesize >= (int)$this->maxSize) {
64
+			if ($filesize >= (int) $this->maxSize) {
65 65
 				return true;
66 66
 			}
67 67
 		}
Please login to merge, or discard this patch.
apps/admin_audit/composer/composer/autoload_static.php 1 patch
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -6,39 +6,39 @@
 block discarded – undo
6 6
 
7 7
 class ComposerStaticInitAdminAudit
8 8
 {
9
-    public static $prefixLengthsPsr4 = array (
9
+    public static $prefixLengthsPsr4 = array(
10 10
         'O' => 
11
-        array (
11
+        array(
12 12
             'OCA\\AdminAudit\\' => 15,
13 13
         ),
14 14
     );
15 15
 
16
-    public static $prefixDirsPsr4 = array (
16
+    public static $prefixDirsPsr4 = array(
17 17
         'OCA\\AdminAudit\\' => 
18
-        array (
19
-            0 => __DIR__ . '/..' . '/../lib',
18
+        array(
19
+            0 => __DIR__.'/..'.'/../lib',
20 20
         ),
21 21
     );
22 22
 
23
-    public static $classMap = array (
24
-        'OCA\\AdminAudit\\Actions\\Action' => __DIR__ . '/..' . '/../lib/Actions/Action.php',
25
-        'OCA\\AdminAudit\\Actions\\AppManagement' => __DIR__ . '/..' . '/../lib/Actions/AppManagement.php',
26
-        'OCA\\AdminAudit\\Actions\\Auth' => __DIR__ . '/..' . '/../lib/Actions/Auth.php',
27
-        'OCA\\AdminAudit\\Actions\\Console' => __DIR__ . '/..' . '/../lib/Actions/Console.php',
28
-        'OCA\\AdminAudit\\Actions\\Files' => __DIR__ . '/..' . '/../lib/Actions/Files.php',
29
-        'OCA\\AdminAudit\\Actions\\GroupManagement' => __DIR__ . '/..' . '/../lib/Actions/GroupManagement.php',
30
-        'OCA\\AdminAudit\\Actions\\Security' => __DIR__ . '/..' . '/../lib/Actions/Security.php',
31
-        'OCA\\AdminAudit\\Actions\\Sharing' => __DIR__ . '/..' . '/../lib/Actions/Sharing.php',
32
-        'OCA\\AdminAudit\\Actions\\Trashbin' => __DIR__ . '/..' . '/../lib/Actions/Trashbin.php',
33
-        'OCA\\AdminAudit\\Actions\\UserManagement' => __DIR__ . '/..' . '/../lib/Actions/UserManagement.php',
34
-        'OCA\\AdminAudit\\Actions\\Versions' => __DIR__ . '/..' . '/../lib/Actions/Versions.php',
35
-        'OCA\\AdminAudit\\AppInfo\\Application' => __DIR__ . '/..' . '/../lib/AppInfo/Application.php',
36
-        'OCA\\AdminAudit\\BackgroundJobs\\Rotate' => __DIR__ . '/..' . '/../lib/BackgroundJobs/Rotate.php',
23
+    public static $classMap = array(
24
+        'OCA\\AdminAudit\\Actions\\Action' => __DIR__.'/..'.'/../lib/Actions/Action.php',
25
+        'OCA\\AdminAudit\\Actions\\AppManagement' => __DIR__.'/..'.'/../lib/Actions/AppManagement.php',
26
+        'OCA\\AdminAudit\\Actions\\Auth' => __DIR__.'/..'.'/../lib/Actions/Auth.php',
27
+        'OCA\\AdminAudit\\Actions\\Console' => __DIR__.'/..'.'/../lib/Actions/Console.php',
28
+        'OCA\\AdminAudit\\Actions\\Files' => __DIR__.'/..'.'/../lib/Actions/Files.php',
29
+        'OCA\\AdminAudit\\Actions\\GroupManagement' => __DIR__.'/..'.'/../lib/Actions/GroupManagement.php',
30
+        'OCA\\AdminAudit\\Actions\\Security' => __DIR__.'/..'.'/../lib/Actions/Security.php',
31
+        'OCA\\AdminAudit\\Actions\\Sharing' => __DIR__.'/..'.'/../lib/Actions/Sharing.php',
32
+        'OCA\\AdminAudit\\Actions\\Trashbin' => __DIR__.'/..'.'/../lib/Actions/Trashbin.php',
33
+        'OCA\\AdminAudit\\Actions\\UserManagement' => __DIR__.'/..'.'/../lib/Actions/UserManagement.php',
34
+        'OCA\\AdminAudit\\Actions\\Versions' => __DIR__.'/..'.'/../lib/Actions/Versions.php',
35
+        'OCA\\AdminAudit\\AppInfo\\Application' => __DIR__.'/..'.'/../lib/AppInfo/Application.php',
36
+        'OCA\\AdminAudit\\BackgroundJobs\\Rotate' => __DIR__.'/..'.'/../lib/BackgroundJobs/Rotate.php',
37 37
     );
38 38
 
39 39
     public static function getInitializer(ClassLoader $loader)
40 40
     {
41
-        return \Closure::bind(function () use ($loader) {
41
+        return \Closure::bind(function() use ($loader) {
42 42
             $loader->prefixLengthsPsr4 = ComposerStaticInitAdminAudit::$prefixLengthsPsr4;
43 43
             $loader->prefixDirsPsr4 = ComposerStaticInitAdminAudit::$prefixDirsPsr4;
44 44
             $loader->classMap = ComposerStaticInitAdminAudit::$classMap;
Please login to merge, or discard this patch.
apps/admin_audit/composer/composer/autoload_classmap.php 1 patch
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -6,17 +6,17 @@
 block discarded – undo
6 6
 $baseDir = $vendorDir;
7 7
 
8 8
 return array(
9
-    'OCA\\AdminAudit\\Actions\\Action' => $baseDir . '/../lib/Actions/Action.php',
10
-    'OCA\\AdminAudit\\Actions\\AppManagement' => $baseDir . '/../lib/Actions/AppManagement.php',
11
-    'OCA\\AdminAudit\\Actions\\Auth' => $baseDir . '/../lib/Actions/Auth.php',
12
-    'OCA\\AdminAudit\\Actions\\Console' => $baseDir . '/../lib/Actions/Console.php',
13
-    'OCA\\AdminAudit\\Actions\\Files' => $baseDir . '/../lib/Actions/Files.php',
14
-    'OCA\\AdminAudit\\Actions\\GroupManagement' => $baseDir . '/../lib/Actions/GroupManagement.php',
15
-    'OCA\\AdminAudit\\Actions\\Security' => $baseDir . '/../lib/Actions/Security.php',
16
-    'OCA\\AdminAudit\\Actions\\Sharing' => $baseDir . '/../lib/Actions/Sharing.php',
17
-    'OCA\\AdminAudit\\Actions\\Trashbin' => $baseDir . '/../lib/Actions/Trashbin.php',
18
-    'OCA\\AdminAudit\\Actions\\UserManagement' => $baseDir . '/../lib/Actions/UserManagement.php',
19
-    'OCA\\AdminAudit\\Actions\\Versions' => $baseDir . '/../lib/Actions/Versions.php',
20
-    'OCA\\AdminAudit\\AppInfo\\Application' => $baseDir . '/../lib/AppInfo/Application.php',
21
-    'OCA\\AdminAudit\\BackgroundJobs\\Rotate' => $baseDir . '/../lib/BackgroundJobs/Rotate.php',
9
+    'OCA\\AdminAudit\\Actions\\Action' => $baseDir.'/../lib/Actions/Action.php',
10
+    'OCA\\AdminAudit\\Actions\\AppManagement' => $baseDir.'/../lib/Actions/AppManagement.php',
11
+    'OCA\\AdminAudit\\Actions\\Auth' => $baseDir.'/../lib/Actions/Auth.php',
12
+    'OCA\\AdminAudit\\Actions\\Console' => $baseDir.'/../lib/Actions/Console.php',
13
+    'OCA\\AdminAudit\\Actions\\Files' => $baseDir.'/../lib/Actions/Files.php',
14
+    'OCA\\AdminAudit\\Actions\\GroupManagement' => $baseDir.'/../lib/Actions/GroupManagement.php',
15
+    'OCA\\AdminAudit\\Actions\\Security' => $baseDir.'/../lib/Actions/Security.php',
16
+    'OCA\\AdminAudit\\Actions\\Sharing' => $baseDir.'/../lib/Actions/Sharing.php',
17
+    'OCA\\AdminAudit\\Actions\\Trashbin' => $baseDir.'/../lib/Actions/Trashbin.php',
18
+    'OCA\\AdminAudit\\Actions\\UserManagement' => $baseDir.'/../lib/Actions/UserManagement.php',
19
+    'OCA\\AdminAudit\\Actions\\Versions' => $baseDir.'/../lib/Actions/Versions.php',
20
+    'OCA\\AdminAudit\\AppInfo\\Application' => $baseDir.'/../lib/AppInfo/Application.php',
21
+    'OCA\\AdminAudit\\BackgroundJobs\\Rotate' => $baseDir.'/../lib/BackgroundJobs/Rotate.php',
22 22
 );
Please login to merge, or discard this patch.
apps/dav/lib/Direct/DirectHome.php 1 patch
Indentation   +77 added lines, -77 removed lines patch added patch discarded remove patch
@@ -37,82 +37,82 @@
 block discarded – undo
37 37
 
38 38
 class DirectHome implements ICollection {
39 39
 
40
-	/** @var IRootFolder */
41
-	private $rootFolder;
42
-
43
-	/** @var DirectMapper */
44
-	private $mapper;
45
-
46
-	/** @var ITimeFactory */
47
-	private $timeFactory;
48
-
49
-	/** @var Throttler */
50
-	private $throttler;
51
-
52
-	/** @var IRequest */
53
-	private $request;
54
-
55
-	public function __construct(IRootFolder $rootFolder,
56
-								DirectMapper $mapper,
57
-								ITimeFactory $timeFactory,
58
-								Throttler $throttler,
59
-								IRequest $request) {
60
-		$this->rootFolder = $rootFolder;
61
-		$this->mapper = $mapper;
62
-		$this->timeFactory = $timeFactory;
63
-		$this->throttler = $throttler;
64
-		$this->request = $request;
65
-	}
66
-
67
-	public function createFile($name, $data = null) {
68
-		throw new Forbidden();
69
-	}
70
-
71
-	public function createDirectory($name) {
72
-		throw new Forbidden();
73
-	}
74
-
75
-	public function getChild($name): DirectFile {
76
-		try {
77
-			$direct = $this->mapper->getByToken($name);
78
-
79
-			// Expired
80
-			if ($direct->getExpiration() < $this->timeFactory->getTime()) {
81
-				throw new NotFound();
82
-			}
83
-
84
-			return new DirectFile($direct, $this->rootFolder);
85
-		} catch (DoesNotExistException $e) {
86
-			// Since the token space is so huge only throttle on non exsisting token
87
-			$this->throttler->registerAttempt('directlink', $this->request->getRemoteAddress());
88
-			$this->throttler->sleepDelay($this->request->getRemoteAddress(), 'directlink');
89
-
90
-			throw new NotFound();
91
-		}
92
-	}
93
-
94
-	public function getChildren() {
95
-		throw new MethodNotAllowed('Listing members of this collection is disabled');
96
-	}
97
-
98
-	public function childExists($name): bool {
99
-		return false;
100
-	}
101
-
102
-	public function delete() {
103
-		throw new Forbidden();
104
-	}
105
-
106
-	public function getName(): string {
107
-		return 'direct';
108
-	}
109
-
110
-	public function setName($name) {
111
-		throw new Forbidden();
112
-	}
113
-
114
-	public function getLastModified(): int {
115
-		return 0;
116
-	}
40
+    /** @var IRootFolder */
41
+    private $rootFolder;
42
+
43
+    /** @var DirectMapper */
44
+    private $mapper;
45
+
46
+    /** @var ITimeFactory */
47
+    private $timeFactory;
48
+
49
+    /** @var Throttler */
50
+    private $throttler;
51
+
52
+    /** @var IRequest */
53
+    private $request;
54
+
55
+    public function __construct(IRootFolder $rootFolder,
56
+                                DirectMapper $mapper,
57
+                                ITimeFactory $timeFactory,
58
+                                Throttler $throttler,
59
+                                IRequest $request) {
60
+        $this->rootFolder = $rootFolder;
61
+        $this->mapper = $mapper;
62
+        $this->timeFactory = $timeFactory;
63
+        $this->throttler = $throttler;
64
+        $this->request = $request;
65
+    }
66
+
67
+    public function createFile($name, $data = null) {
68
+        throw new Forbidden();
69
+    }
70
+
71
+    public function createDirectory($name) {
72
+        throw new Forbidden();
73
+    }
74
+
75
+    public function getChild($name): DirectFile {
76
+        try {
77
+            $direct = $this->mapper->getByToken($name);
78
+
79
+            // Expired
80
+            if ($direct->getExpiration() < $this->timeFactory->getTime()) {
81
+                throw new NotFound();
82
+            }
83
+
84
+            return new DirectFile($direct, $this->rootFolder);
85
+        } catch (DoesNotExistException $e) {
86
+            // Since the token space is so huge only throttle on non exsisting token
87
+            $this->throttler->registerAttempt('directlink', $this->request->getRemoteAddress());
88
+            $this->throttler->sleepDelay($this->request->getRemoteAddress(), 'directlink');
89
+
90
+            throw new NotFound();
91
+        }
92
+    }
93
+
94
+    public function getChildren() {
95
+        throw new MethodNotAllowed('Listing members of this collection is disabled');
96
+    }
97
+
98
+    public function childExists($name): bool {
99
+        return false;
100
+    }
101
+
102
+    public function delete() {
103
+        throw new Forbidden();
104
+    }
105
+
106
+    public function getName(): string {
107
+        return 'direct';
108
+    }
109
+
110
+    public function setName($name) {
111
+        throw new Forbidden();
112
+    }
113
+
114
+    public function getLastModified(): int {
115
+        return 0;
116
+    }
117 117
 
118 118
 }
Please login to merge, or discard this patch.
ocm-provider/index.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@
 block discarded – undo
20 20
  */
21 21
 
22 22
 
23
-require_once __DIR__ . '/../lib/base.php';
23
+require_once __DIR__.'/../lib/base.php';
24 24
 
25 25
 header('Content-Type: application/json');
26 26
 
Please login to merge, or discard this patch.
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -29,12 +29,12 @@
 block discarded – undo
29 29
 $isEnabled = $server->getAppManager()->isEnabledForUser('cloud_federation_api');
30 30
 
31 31
 if ($isEnabled) {
32
-	// Make sure the routes are loaded
33
-	\OC_App::loadApp('cloud_federation_api');
34
-	$capabilities = new OCA\CloudFederationAPI\Capabilities($server->getURLGenerator());
35
-	header('Content-Type: application/json');
36
-	echo json_encode($capabilities->getCapabilities()['ocm']);
32
+    // Make sure the routes are loaded
33
+    \OC_App::loadApp('cloud_federation_api');
34
+    $capabilities = new OCA\CloudFederationAPI\Capabilities($server->getURLGenerator());
35
+    header('Content-Type: application/json');
36
+    echo json_encode($capabilities->getCapabilities()['ocm']);
37 37
 } else {
38
-	header($_SERVER["SERVER_PROTOCOL"]." 501 Not Implemented", true, 501);
39
-	exit("501 Not Implemented");
38
+    header($_SERVER["SERVER_PROTOCOL"]." 501 Not Implemented", true, 501);
39
+    exit("501 Not Implemented");
40 40
 }
Please login to merge, or discard this patch.
lib/public/Federation/Exceptions/ProviderDoesNotExistsException.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -32,7 +32,7 @@
 block discarded – undo
32 32
 	 */
33 33
 	public function __construct($providerId) {
34 34
 		$l = \OC::$server->getL10N('federation');
35
-		$message = 'Cloud Federation Provider with ID: "' . $providerId . '" does not exist.';
35
+		$message = 'Cloud Federation Provider with ID: "'.$providerId.'" does not exist.';
36 36
 		$hint = $l->t('Cloud Federation Provider with ID: "%s" does not exist.', [$providerId]);
37 37
 		parent::__construct($message, $hint);
38 38
 	}
Please login to merge, or discard this patch.
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -32,18 +32,18 @@
 block discarded – undo
32 32
  */
33 33
 class ProviderDoesNotExistsException extends HintException {
34 34
 
35
-	/**
36
-	 * ProviderDoesNotExistsException constructor.
37
-	 *
38
-	 * @since 14.0.0
39
-	 *
40
-	 * @param string $providerId cloud federation provider ID
41
-	 */
42
-	public function __construct($providerId) {
43
-		$l = \OC::$server->getL10N('federation');
44
-		$message = 'Cloud Federation Provider with ID: "' . $providerId . '" does not exist.';
45
-		$hint = $l->t('Cloud Federation Provider with ID: "%s" does not exist.', [$providerId]);
46
-		parent::__construct($message, $hint);
47
-	}
35
+    /**
36
+     * ProviderDoesNotExistsException constructor.
37
+     *
38
+     * @since 14.0.0
39
+     *
40
+     * @param string $providerId cloud federation provider ID
41
+     */
42
+    public function __construct($providerId) {
43
+        $l = \OC::$server->getL10N('federation');
44
+        $message = 'Cloud Federation Provider with ID: "' . $providerId . '" does not exist.';
45
+        $hint = $l->t('Cloud Federation Provider with ID: "%s" does not exist.', [$providerId]);
46
+        parent::__construct($message, $hint);
47
+    }
48 48
 
49 49
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/Directory.php 2 patches
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 				// exit if we can't create a new file and we don't updatable existing file
127 127
 				$chunkInfo = \OC_FileChunking::decodeName($name);
128 128
 				if (!$this->fileView->isCreatable($this->path) &&
129
-					!$this->fileView->isUpdatable($this->path . '/' . $chunkInfo['name'])
129
+					!$this->fileView->isUpdatable($this->path.'/'.$chunkInfo['name'])
130 130
 				) {
131 131
 					throw new \Sabre\DAV\Exception\Forbidden();
132 132
 				}
@@ -140,9 +140,9 @@  discard block
 block discarded – undo
140 140
 
141 141
 			$this->fileView->verifyPath($this->path, $name);
142 142
 
143
-			$path = $this->fileView->getAbsolutePath($this->path) . '/' . $name;
143
+			$path = $this->fileView->getAbsolutePath($this->path).'/'.$name;
144 144
 			// in case the file already exists/overwriting
145
-			$info = $this->fileView->getFileInfo($this->path . '/' . $name);
145
+			$info = $this->fileView->getFileInfo($this->path.'/'.$name);
146 146
 			if (!$info) {
147 147
 				// use a dummy FileInfo which is acceptable here since it will be refreshed after the put is complete
148 148
 				$info = new \OC\Files\FileInfo($path, null, null, [], null);
@@ -151,11 +151,11 @@  discard block
 block discarded – undo
151 151
 
152 152
 			// only allow 1 process to upload a file at once but still allow reading the file while writing the part file
153 153
 			$node->acquireLock(ILockingProvider::LOCK_SHARED);
154
-			$this->fileView->lockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
154
+			$this->fileView->lockFile($path.'.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
155 155
 
156 156
 			$result = $node->put($data);
157 157
 
158
-			$this->fileView->unlockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
158
+			$this->fileView->unlockFile($path.'.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
159 159
 			$node->releaseLock(ILockingProvider::LOCK_SHARED);
160 160
 			return $result;
161 161
 		} catch (\OCP\Files\StorageNotAvailableException $e) {
@@ -185,9 +185,9 @@  discard block
 block discarded – undo
185 185
 			}
186 186
 
187 187
 			$this->fileView->verifyPath($this->path, $name);
188
-			$newPath = $this->path . '/' . $name;
188
+			$newPath = $this->path.'/'.$name;
189 189
 			if (!$this->fileView->mkdir($newPath)) {
190
-				throw new \Sabre\DAV\Exception\Forbidden('Could not create directory ' . $newPath);
190
+				throw new \Sabre\DAV\Exception\Forbidden('Could not create directory '.$newPath);
191 191
 			}
192 192
 		} catch (\OCP\Files\StorageNotAvailableException $e) {
193 193
 			throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 			throw new NotFound();
217 217
 		}
218 218
 
219
-		$path = $this->path . '/' . $name;
219
+		$path = $this->path.'/'.$name;
220 220
 		if (is_null($info)) {
221 221
 			try {
222 222
 				$this->fileView->verifyPath($this->path, $name);
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 		}
232 232
 
233 233
 		if (!$info) {
234
-			throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
234
+			throw new \Sabre\DAV\Exception\NotFound('File with name '.$path.' could not be located');
235 235
 		}
236 236
 
237 237
 		if ($info['mimetype'] === 'httpd/unix-directory') {
@@ -290,7 +290,7 @@  discard block
 block discarded – undo
290 290
 		// (required old code) instead of "updateFile".
291 291
 		//
292 292
 		// TODO: resolve chunk file name here and implement "updateFile"
293
-		$path = $this->path . '/' . $name;
293
+		$path = $this->path.'/'.$name;
294 294
 		return $this->fileView->file_exists($path);
295 295
 
296 296
 	}
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
 			throw new ServiceUnavailable('filesystem not setup');
386 386
 		}
387 387
 
388
-		$destinationPath = $this->getPath() . '/' . $targetName;
388
+		$destinationPath = $this->getPath().'/'.$targetName;
389 389
 
390 390
 
391 391
 		$targetNodeExists = $this->childExists($targetName);
@@ -393,7 +393,7 @@  discard block
 block discarded – undo
393 393
 		// at getNodeForPath we also check the path for isForbiddenFileOrDir
394 394
 		// with that we have covered both source and destination
395 395
 		if ($sourceNode instanceof Directory && $targetNodeExists) {
396
-			throw new \Sabre\DAV\Exception\Forbidden('Could not copy directory ' . $sourceNode->getName() . ', target exists');
396
+			throw new \Sabre\DAV\Exception\Forbidden('Could not copy directory '.$sourceNode->getName().', target exists');
397 397
 		}
398 398
 
399 399
 		list($sourceDir,) = \Sabre\Uri\split($sourceNode->getPath());
Please login to merge, or discard this patch.
Indentation   +396 added lines, -396 removed lines patch added patch discarded remove patch
@@ -52,400 +52,400 @@
 block discarded – undo
52 52
 
53 53
 class Directory extends \OCA\DAV\Connector\Sabre\Node implements \Sabre\DAV\ICollection, \Sabre\DAV\IQuota, \Sabre\DAV\IMoveTarget {
54 54
 
55
-	/**
56
-	 * Cached directory content
57
-	 *
58
-	 * @var \OCP\Files\FileInfo[]
59
-	 */
60
-	private $dirContent;
61
-
62
-	/**
63
-	 * Cached quota info
64
-	 *
65
-	 * @var array
66
-	 */
67
-	private $quotaInfo;
68
-
69
-	/**
70
-	 * @var ObjectTree|null
71
-	 */
72
-	private $tree;
73
-
74
-	/**
75
-	 * Sets up the node, expects a full path name
76
-	 *
77
-	 * @param \OC\Files\View $view
78
-	 * @param \OCP\Files\FileInfo $info
79
-	 * @param ObjectTree|null $tree
80
-	 * @param \OCP\Share\IManager $shareManager
81
-	 */
82
-	public function __construct(View $view, FileInfo $info, $tree = null, $shareManager = null) {
83
-		parent::__construct($view, $info, $shareManager);
84
-		$this->tree = $tree;
85
-	}
86
-
87
-	/**
88
-	 * Creates a new file in the directory
89
-	 *
90
-	 * Data will either be supplied as a stream resource, or in certain cases
91
-	 * as a string. Keep in mind that you may have to support either.
92
-	 *
93
-	 * After successful creation of the file, you may choose to return the ETag
94
-	 * of the new file here.
95
-	 *
96
-	 * The returned ETag must be surrounded by double-quotes (The quotes should
97
-	 * be part of the actual string).
98
-	 *
99
-	 * If you cannot accurately determine the ETag, you should not return it.
100
-	 * If you don't store the file exactly as-is (you're transforming it
101
-	 * somehow) you should also not return an ETag.
102
-	 *
103
-	 * This means that if a subsequent GET to this new file does not exactly
104
-	 * return the same contents of what was submitted here, you are strongly
105
-	 * recommended to omit the ETag.
106
-	 *
107
-	 * @param string $name Name of the file
108
-	 * @param resource|string $data Initial payload
109
-	 * @return null|string
110
-	 * @throws Exception\EntityTooLarge
111
-	 * @throws Exception\UnsupportedMediaType
112
-	 * @throws FileLocked
113
-	 * @throws InvalidPath
114
-	 * @throws \Sabre\DAV\Exception
115
-	 * @throws \Sabre\DAV\Exception\BadRequest
116
-	 * @throws \Sabre\DAV\Exception\Forbidden
117
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
118
-	 */
119
-	public function createFile($name, $data = null) {
120
-		try {
121
-			// for chunked upload also updating a existing file is a "createFile"
122
-			// because we create all the chunks before re-assemble them to the existing file.
123
-			if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
124
-
125
-				// exit if we can't create a new file and we don't updatable existing file
126
-				$chunkInfo = \OC_FileChunking::decodeName($name);
127
-				if (!$this->fileView->isCreatable($this->path) &&
128
-					!$this->fileView->isUpdatable($this->path . '/' . $chunkInfo['name'])
129
-				) {
130
-					throw new \Sabre\DAV\Exception\Forbidden();
131
-				}
132
-			} else {
133
-				// For non-chunked upload it is enough to check if we can create a new file
134
-				if (!$this->fileView->isCreatable($this->path)) {
135
-					throw new \Sabre\DAV\Exception\Forbidden();
136
-				}
137
-			}
138
-
139
-			$this->fileView->verifyPath($this->path, $name);
140
-
141
-			$path = $this->fileView->getAbsolutePath($this->path) . '/' . $name;
142
-			// in case the file already exists/overwriting
143
-			$info = $this->fileView->getFileInfo($this->path . '/' . $name);
144
-			if (!$info) {
145
-				// use a dummy FileInfo which is acceptable here since it will be refreshed after the put is complete
146
-				$info = new \OC\Files\FileInfo($path, null, null, [], null);
147
-			}
148
-			$node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info);
149
-
150
-			// only allow 1 process to upload a file at once but still allow reading the file while writing the part file
151
-			$node->acquireLock(ILockingProvider::LOCK_SHARED);
152
-			$this->fileView->lockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
153
-
154
-			$result = $node->put($data);
155
-
156
-			$this->fileView->unlockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
157
-			$node->releaseLock(ILockingProvider::LOCK_SHARED);
158
-			return $result;
159
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
160
-			throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage(), $e->getCode(), $e);
161
-		} catch (InvalidPathException $ex) {
162
-			throw new InvalidPath($ex->getMessage(), false, $ex);
163
-		} catch (ForbiddenException $ex) {
164
-			throw new Forbidden($ex->getMessage(), $ex->getRetry(), $ex);
165
-		} catch (LockedException $e) {
166
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
167
-		}
168
-	}
169
-
170
-	/**
171
-	 * Creates a new subdirectory
172
-	 *
173
-	 * @param string $name
174
-	 * @throws FileLocked
175
-	 * @throws InvalidPath
176
-	 * @throws \Sabre\DAV\Exception\Forbidden
177
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
178
-	 */
179
-	public function createDirectory($name) {
180
-		try {
181
-			if (!$this->info->isCreatable()) {
182
-				throw new \Sabre\DAV\Exception\Forbidden();
183
-			}
184
-
185
-			$this->fileView->verifyPath($this->path, $name);
186
-			$newPath = $this->path . '/' . $name;
187
-			if (!$this->fileView->mkdir($newPath)) {
188
-				throw new \Sabre\DAV\Exception\Forbidden('Could not create directory ' . $newPath);
189
-			}
190
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
191
-			throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
192
-		} catch (InvalidPathException $ex) {
193
-			throw new InvalidPath($ex->getMessage());
194
-		} catch (ForbiddenException $ex) {
195
-			throw new Forbidden($ex->getMessage(), $ex->getRetry());
196
-		} catch (LockedException $e) {
197
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
198
-		}
199
-	}
200
-
201
-	/**
202
-	 * Returns a specific child node, referenced by its name
203
-	 *
204
-	 * @param string $name
205
-	 * @param \OCP\Files\FileInfo $info
206
-	 * @return \Sabre\DAV\INode
207
-	 * @throws InvalidPath
208
-	 * @throws \Sabre\DAV\Exception\NotFound
209
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
210
-	 */
211
-	public function getChild($name, $info = null) {
212
-		if (!$this->info->isReadable()) {
213
-			// avoid detecting files through this way
214
-			throw new NotFound();
215
-		}
216
-
217
-		$path = $this->path . '/' . $name;
218
-		if (is_null($info)) {
219
-			try {
220
-				$this->fileView->verifyPath($this->path, $name);
221
-				$info = $this->fileView->getFileInfo($path);
222
-			} catch (\OCP\Files\StorageNotAvailableException $e) {
223
-				throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
224
-			} catch (InvalidPathException $ex) {
225
-				throw new InvalidPath($ex->getMessage());
226
-			} catch (ForbiddenException $e) {
227
-				throw new \Sabre\DAV\Exception\Forbidden();
228
-			}
229
-		}
230
-
231
-		if (!$info) {
232
-			throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
233
-		}
234
-
235
-		if ($info['mimetype'] === 'httpd/unix-directory') {
236
-			$node = new \OCA\DAV\Connector\Sabre\Directory($this->fileView, $info, $this->tree, $this->shareManager);
237
-		} else {
238
-			$node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info, $this->shareManager);
239
-		}
240
-		if ($this->tree) {
241
-			$this->tree->cacheNode($node);
242
-		}
243
-		return $node;
244
-	}
245
-
246
-	/**
247
-	 * Returns an array with all the child nodes
248
-	 *
249
-	 * @return \Sabre\DAV\INode[]
250
-	 * @throws \Sabre\DAV\Exception\Locked
251
-	 * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden
252
-	 */
253
-	public function getChildren() {
254
-		if (!is_null($this->dirContent)) {
255
-			return $this->dirContent;
256
-		}
257
-		try {
258
-			if (!$this->info->isReadable()) {
259
-				// return 403 instead of 404 because a 404 would make
260
-				// the caller believe that the collection itself does not exist
261
-				throw new Forbidden('No read permissions');
262
-			}
263
-			$folderContent = $this->fileView->getDirectoryContent($this->path);
264
-		} catch (LockedException $e) {
265
-			throw new Locked();
266
-		}
267
-
268
-		$nodes = [];
269
-		foreach ($folderContent as $info) {
270
-			$node = $this->getChild($info->getName(), $info);
271
-			$nodes[] = $node;
272
-		}
273
-		$this->dirContent = $nodes;
274
-		return $this->dirContent;
275
-	}
276
-
277
-	/**
278
-	 * Checks if a child exists.
279
-	 *
280
-	 * @param string $name
281
-	 * @return bool
282
-	 */
283
-	public function childExists($name) {
284
-		// note: here we do NOT resolve the chunk file name to the real file name
285
-		// to make sure we return false when checking for file existence with a chunk
286
-		// file name.
287
-		// This is to make sure that "createFile" is still triggered
288
-		// (required old code) instead of "updateFile".
289
-		//
290
-		// TODO: resolve chunk file name here and implement "updateFile"
291
-		$path = $this->path . '/' . $name;
292
-		return $this->fileView->file_exists($path);
293
-	}
294
-
295
-	/**
296
-	 * Deletes all files in this directory, and then itself
297
-	 *
298
-	 * @return void
299
-	 * @throws FileLocked
300
-	 * @throws \Sabre\DAV\Exception\Forbidden
301
-	 */
302
-	public function delete() {
303
-		if ($this->path === '' || $this->path === '/' || !$this->info->isDeletable()) {
304
-			throw new \Sabre\DAV\Exception\Forbidden();
305
-		}
306
-
307
-		try {
308
-			if (!$this->fileView->rmdir($this->path)) {
309
-				// assume it wasn't possible to remove due to permission issue
310
-				throw new \Sabre\DAV\Exception\Forbidden();
311
-			}
312
-		} catch (ForbiddenException $ex) {
313
-			throw new Forbidden($ex->getMessage(), $ex->getRetry());
314
-		} catch (LockedException $e) {
315
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
316
-		}
317
-	}
318
-
319
-	/**
320
-	 * Returns available diskspace information
321
-	 *
322
-	 * @return array
323
-	 */
324
-	public function getQuotaInfo() {
325
-		if ($this->quotaInfo) {
326
-			return $this->quotaInfo;
327
-		}
328
-		try {
329
-			$info = $this->fileView->getFileInfo($this->path, false);
330
-			$storageInfo = \OC_Helper::getStorageInfo($this->info->getPath(), $info);
331
-			if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
332
-				$free = \OCP\Files\FileInfo::SPACE_UNLIMITED;
333
-			} else {
334
-				$free = $storageInfo['free'];
335
-			}
336
-			$this->quotaInfo = [
337
-				$storageInfo['used'],
338
-				$free
339
-			];
340
-			return $this->quotaInfo;
341
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
342
-			return [0, 0];
343
-		}
344
-	}
345
-
346
-	/**
347
-	 * Moves a node into this collection.
348
-	 *
349
-	 * It is up to the implementors to:
350
-	 *   1. Create the new resource.
351
-	 *   2. Remove the old resource.
352
-	 *   3. Transfer any properties or other data.
353
-	 *
354
-	 * Generally you should make very sure that your collection can easily move
355
-	 * the move.
356
-	 *
357
-	 * If you don't, just return false, which will trigger sabre/dav to handle
358
-	 * the move itself. If you return true from this function, the assumption
359
-	 * is that the move was successful.
360
-	 *
361
-	 * @param string $targetName New local file/collection name.
362
-	 * @param string $fullSourcePath Full path to source node
363
-	 * @param INode $sourceNode Source node itself
364
-	 * @return bool
365
-	 * @throws BadRequest
366
-	 * @throws ServiceUnavailable
367
-	 * @throws Forbidden
368
-	 * @throws FileLocked
369
-	 * @throws \Sabre\DAV\Exception\Forbidden
370
-	 */
371
-	public function moveInto($targetName, $fullSourcePath, INode $sourceNode) {
372
-		if (!$sourceNode instanceof Node) {
373
-			// it's a file of another kind, like FutureFile
374
-			if ($sourceNode instanceof IFile) {
375
-				// fallback to default copy+delete handling
376
-				return false;
377
-			}
378
-			throw new BadRequest('Incompatible node types');
379
-		}
380
-
381
-		if (!$this->fileView) {
382
-			throw new ServiceUnavailable('filesystem not setup');
383
-		}
384
-
385
-		$destinationPath = $this->getPath() . '/' . $targetName;
386
-
387
-
388
-		$targetNodeExists = $this->childExists($targetName);
389
-
390
-		// at getNodeForPath we also check the path for isForbiddenFileOrDir
391
-		// with that we have covered both source and destination
392
-		if ($sourceNode instanceof Directory && $targetNodeExists) {
393
-			throw new \Sabre\DAV\Exception\Forbidden('Could not copy directory ' . $sourceNode->getName() . ', target exists');
394
-		}
395
-
396
-		list($sourceDir,) = \Sabre\Uri\split($sourceNode->getPath());
397
-		$destinationDir = $this->getPath();
398
-
399
-		$sourcePath = $sourceNode->getPath();
400
-
401
-		$isMovableMount = false;
402
-		$sourceMount = \OC::$server->getMountManager()->find($this->fileView->getAbsolutePath($sourcePath));
403
-		$internalPath = $sourceMount->getInternalPath($this->fileView->getAbsolutePath($sourcePath));
404
-		if ($sourceMount instanceof MoveableMount && $internalPath === '') {
405
-			$isMovableMount = true;
406
-		}
407
-
408
-		try {
409
-			$sameFolder = ($sourceDir === $destinationDir);
410
-			// if we're overwriting or same folder
411
-			if ($targetNodeExists || $sameFolder) {
412
-				// note that renaming a share mount point is always allowed
413
-				if (!$this->fileView->isUpdatable($destinationDir) && !$isMovableMount) {
414
-					throw new \Sabre\DAV\Exception\Forbidden();
415
-				}
416
-			} else {
417
-				if (!$this->fileView->isCreatable($destinationDir)) {
418
-					throw new \Sabre\DAV\Exception\Forbidden();
419
-				}
420
-			}
421
-
422
-			if (!$sameFolder) {
423
-				// moving to a different folder, source will be gone, like a deletion
424
-				// note that moving a share mount point is always allowed
425
-				if (!$this->fileView->isDeletable($sourcePath) && !$isMovableMount) {
426
-					throw new \Sabre\DAV\Exception\Forbidden();
427
-				}
428
-			}
429
-
430
-			$fileName = basename($destinationPath);
431
-			try {
432
-				$this->fileView->verifyPath($destinationDir, $fileName);
433
-			} catch (InvalidPathException $ex) {
434
-				throw new InvalidPath($ex->getMessage());
435
-			}
436
-
437
-			$renameOkay = $this->fileView->rename($sourcePath, $destinationPath);
438
-			if (!$renameOkay) {
439
-				throw new \Sabre\DAV\Exception\Forbidden('');
440
-			}
441
-		} catch (StorageNotAvailableException $e) {
442
-			throw new ServiceUnavailable($e->getMessage());
443
-		} catch (ForbiddenException $ex) {
444
-			throw new Forbidden($ex->getMessage(), $ex->getRetry());
445
-		} catch (LockedException $e) {
446
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
447
-		}
448
-
449
-		return true;
450
-	}
55
+    /**
56
+     * Cached directory content
57
+     *
58
+     * @var \OCP\Files\FileInfo[]
59
+     */
60
+    private $dirContent;
61
+
62
+    /**
63
+     * Cached quota info
64
+     *
65
+     * @var array
66
+     */
67
+    private $quotaInfo;
68
+
69
+    /**
70
+     * @var ObjectTree|null
71
+     */
72
+    private $tree;
73
+
74
+    /**
75
+     * Sets up the node, expects a full path name
76
+     *
77
+     * @param \OC\Files\View $view
78
+     * @param \OCP\Files\FileInfo $info
79
+     * @param ObjectTree|null $tree
80
+     * @param \OCP\Share\IManager $shareManager
81
+     */
82
+    public function __construct(View $view, FileInfo $info, $tree = null, $shareManager = null) {
83
+        parent::__construct($view, $info, $shareManager);
84
+        $this->tree = $tree;
85
+    }
86
+
87
+    /**
88
+     * Creates a new file in the directory
89
+     *
90
+     * Data will either be supplied as a stream resource, or in certain cases
91
+     * as a string. Keep in mind that you may have to support either.
92
+     *
93
+     * After successful creation of the file, you may choose to return the ETag
94
+     * of the new file here.
95
+     *
96
+     * The returned ETag must be surrounded by double-quotes (The quotes should
97
+     * be part of the actual string).
98
+     *
99
+     * If you cannot accurately determine the ETag, you should not return it.
100
+     * If you don't store the file exactly as-is (you're transforming it
101
+     * somehow) you should also not return an ETag.
102
+     *
103
+     * This means that if a subsequent GET to this new file does not exactly
104
+     * return the same contents of what was submitted here, you are strongly
105
+     * recommended to omit the ETag.
106
+     *
107
+     * @param string $name Name of the file
108
+     * @param resource|string $data Initial payload
109
+     * @return null|string
110
+     * @throws Exception\EntityTooLarge
111
+     * @throws Exception\UnsupportedMediaType
112
+     * @throws FileLocked
113
+     * @throws InvalidPath
114
+     * @throws \Sabre\DAV\Exception
115
+     * @throws \Sabre\DAV\Exception\BadRequest
116
+     * @throws \Sabre\DAV\Exception\Forbidden
117
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
118
+     */
119
+    public function createFile($name, $data = null) {
120
+        try {
121
+            // for chunked upload also updating a existing file is a "createFile"
122
+            // because we create all the chunks before re-assemble them to the existing file.
123
+            if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
124
+
125
+                // exit if we can't create a new file and we don't updatable existing file
126
+                $chunkInfo = \OC_FileChunking::decodeName($name);
127
+                if (!$this->fileView->isCreatable($this->path) &&
128
+                    !$this->fileView->isUpdatable($this->path . '/' . $chunkInfo['name'])
129
+                ) {
130
+                    throw new \Sabre\DAV\Exception\Forbidden();
131
+                }
132
+            } else {
133
+                // For non-chunked upload it is enough to check if we can create a new file
134
+                if (!$this->fileView->isCreatable($this->path)) {
135
+                    throw new \Sabre\DAV\Exception\Forbidden();
136
+                }
137
+            }
138
+
139
+            $this->fileView->verifyPath($this->path, $name);
140
+
141
+            $path = $this->fileView->getAbsolutePath($this->path) . '/' . $name;
142
+            // in case the file already exists/overwriting
143
+            $info = $this->fileView->getFileInfo($this->path . '/' . $name);
144
+            if (!$info) {
145
+                // use a dummy FileInfo which is acceptable here since it will be refreshed after the put is complete
146
+                $info = new \OC\Files\FileInfo($path, null, null, [], null);
147
+            }
148
+            $node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info);
149
+
150
+            // only allow 1 process to upload a file at once but still allow reading the file while writing the part file
151
+            $node->acquireLock(ILockingProvider::LOCK_SHARED);
152
+            $this->fileView->lockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
153
+
154
+            $result = $node->put($data);
155
+
156
+            $this->fileView->unlockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
157
+            $node->releaseLock(ILockingProvider::LOCK_SHARED);
158
+            return $result;
159
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
160
+            throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage(), $e->getCode(), $e);
161
+        } catch (InvalidPathException $ex) {
162
+            throw new InvalidPath($ex->getMessage(), false, $ex);
163
+        } catch (ForbiddenException $ex) {
164
+            throw new Forbidden($ex->getMessage(), $ex->getRetry(), $ex);
165
+        } catch (LockedException $e) {
166
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
167
+        }
168
+    }
169
+
170
+    /**
171
+     * Creates a new subdirectory
172
+     *
173
+     * @param string $name
174
+     * @throws FileLocked
175
+     * @throws InvalidPath
176
+     * @throws \Sabre\DAV\Exception\Forbidden
177
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
178
+     */
179
+    public function createDirectory($name) {
180
+        try {
181
+            if (!$this->info->isCreatable()) {
182
+                throw new \Sabre\DAV\Exception\Forbidden();
183
+            }
184
+
185
+            $this->fileView->verifyPath($this->path, $name);
186
+            $newPath = $this->path . '/' . $name;
187
+            if (!$this->fileView->mkdir($newPath)) {
188
+                throw new \Sabre\DAV\Exception\Forbidden('Could not create directory ' . $newPath);
189
+            }
190
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
191
+            throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
192
+        } catch (InvalidPathException $ex) {
193
+            throw new InvalidPath($ex->getMessage());
194
+        } catch (ForbiddenException $ex) {
195
+            throw new Forbidden($ex->getMessage(), $ex->getRetry());
196
+        } catch (LockedException $e) {
197
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
198
+        }
199
+    }
200
+
201
+    /**
202
+     * Returns a specific child node, referenced by its name
203
+     *
204
+     * @param string $name
205
+     * @param \OCP\Files\FileInfo $info
206
+     * @return \Sabre\DAV\INode
207
+     * @throws InvalidPath
208
+     * @throws \Sabre\DAV\Exception\NotFound
209
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
210
+     */
211
+    public function getChild($name, $info = null) {
212
+        if (!$this->info->isReadable()) {
213
+            // avoid detecting files through this way
214
+            throw new NotFound();
215
+        }
216
+
217
+        $path = $this->path . '/' . $name;
218
+        if (is_null($info)) {
219
+            try {
220
+                $this->fileView->verifyPath($this->path, $name);
221
+                $info = $this->fileView->getFileInfo($path);
222
+            } catch (\OCP\Files\StorageNotAvailableException $e) {
223
+                throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
224
+            } catch (InvalidPathException $ex) {
225
+                throw new InvalidPath($ex->getMessage());
226
+            } catch (ForbiddenException $e) {
227
+                throw new \Sabre\DAV\Exception\Forbidden();
228
+            }
229
+        }
230
+
231
+        if (!$info) {
232
+            throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
233
+        }
234
+
235
+        if ($info['mimetype'] === 'httpd/unix-directory') {
236
+            $node = new \OCA\DAV\Connector\Sabre\Directory($this->fileView, $info, $this->tree, $this->shareManager);
237
+        } else {
238
+            $node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info, $this->shareManager);
239
+        }
240
+        if ($this->tree) {
241
+            $this->tree->cacheNode($node);
242
+        }
243
+        return $node;
244
+    }
245
+
246
+    /**
247
+     * Returns an array with all the child nodes
248
+     *
249
+     * @return \Sabre\DAV\INode[]
250
+     * @throws \Sabre\DAV\Exception\Locked
251
+     * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden
252
+     */
253
+    public function getChildren() {
254
+        if (!is_null($this->dirContent)) {
255
+            return $this->dirContent;
256
+        }
257
+        try {
258
+            if (!$this->info->isReadable()) {
259
+                // return 403 instead of 404 because a 404 would make
260
+                // the caller believe that the collection itself does not exist
261
+                throw new Forbidden('No read permissions');
262
+            }
263
+            $folderContent = $this->fileView->getDirectoryContent($this->path);
264
+        } catch (LockedException $e) {
265
+            throw new Locked();
266
+        }
267
+
268
+        $nodes = [];
269
+        foreach ($folderContent as $info) {
270
+            $node = $this->getChild($info->getName(), $info);
271
+            $nodes[] = $node;
272
+        }
273
+        $this->dirContent = $nodes;
274
+        return $this->dirContent;
275
+    }
276
+
277
+    /**
278
+     * Checks if a child exists.
279
+     *
280
+     * @param string $name
281
+     * @return bool
282
+     */
283
+    public function childExists($name) {
284
+        // note: here we do NOT resolve the chunk file name to the real file name
285
+        // to make sure we return false when checking for file existence with a chunk
286
+        // file name.
287
+        // This is to make sure that "createFile" is still triggered
288
+        // (required old code) instead of "updateFile".
289
+        //
290
+        // TODO: resolve chunk file name here and implement "updateFile"
291
+        $path = $this->path . '/' . $name;
292
+        return $this->fileView->file_exists($path);
293
+    }
294
+
295
+    /**
296
+     * Deletes all files in this directory, and then itself
297
+     *
298
+     * @return void
299
+     * @throws FileLocked
300
+     * @throws \Sabre\DAV\Exception\Forbidden
301
+     */
302
+    public function delete() {
303
+        if ($this->path === '' || $this->path === '/' || !$this->info->isDeletable()) {
304
+            throw new \Sabre\DAV\Exception\Forbidden();
305
+        }
306
+
307
+        try {
308
+            if (!$this->fileView->rmdir($this->path)) {
309
+                // assume it wasn't possible to remove due to permission issue
310
+                throw new \Sabre\DAV\Exception\Forbidden();
311
+            }
312
+        } catch (ForbiddenException $ex) {
313
+            throw new Forbidden($ex->getMessage(), $ex->getRetry());
314
+        } catch (LockedException $e) {
315
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
316
+        }
317
+    }
318
+
319
+    /**
320
+     * Returns available diskspace information
321
+     *
322
+     * @return array
323
+     */
324
+    public function getQuotaInfo() {
325
+        if ($this->quotaInfo) {
326
+            return $this->quotaInfo;
327
+        }
328
+        try {
329
+            $info = $this->fileView->getFileInfo($this->path, false);
330
+            $storageInfo = \OC_Helper::getStorageInfo($this->info->getPath(), $info);
331
+            if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
332
+                $free = \OCP\Files\FileInfo::SPACE_UNLIMITED;
333
+            } else {
334
+                $free = $storageInfo['free'];
335
+            }
336
+            $this->quotaInfo = [
337
+                $storageInfo['used'],
338
+                $free
339
+            ];
340
+            return $this->quotaInfo;
341
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
342
+            return [0, 0];
343
+        }
344
+    }
345
+
346
+    /**
347
+     * Moves a node into this collection.
348
+     *
349
+     * It is up to the implementors to:
350
+     *   1. Create the new resource.
351
+     *   2. Remove the old resource.
352
+     *   3. Transfer any properties or other data.
353
+     *
354
+     * Generally you should make very sure that your collection can easily move
355
+     * the move.
356
+     *
357
+     * If you don't, just return false, which will trigger sabre/dav to handle
358
+     * the move itself. If you return true from this function, the assumption
359
+     * is that the move was successful.
360
+     *
361
+     * @param string $targetName New local file/collection name.
362
+     * @param string $fullSourcePath Full path to source node
363
+     * @param INode $sourceNode Source node itself
364
+     * @return bool
365
+     * @throws BadRequest
366
+     * @throws ServiceUnavailable
367
+     * @throws Forbidden
368
+     * @throws FileLocked
369
+     * @throws \Sabre\DAV\Exception\Forbidden
370
+     */
371
+    public function moveInto($targetName, $fullSourcePath, INode $sourceNode) {
372
+        if (!$sourceNode instanceof Node) {
373
+            // it's a file of another kind, like FutureFile
374
+            if ($sourceNode instanceof IFile) {
375
+                // fallback to default copy+delete handling
376
+                return false;
377
+            }
378
+            throw new BadRequest('Incompatible node types');
379
+        }
380
+
381
+        if (!$this->fileView) {
382
+            throw new ServiceUnavailable('filesystem not setup');
383
+        }
384
+
385
+        $destinationPath = $this->getPath() . '/' . $targetName;
386
+
387
+
388
+        $targetNodeExists = $this->childExists($targetName);
389
+
390
+        // at getNodeForPath we also check the path for isForbiddenFileOrDir
391
+        // with that we have covered both source and destination
392
+        if ($sourceNode instanceof Directory && $targetNodeExists) {
393
+            throw new \Sabre\DAV\Exception\Forbidden('Could not copy directory ' . $sourceNode->getName() . ', target exists');
394
+        }
395
+
396
+        list($sourceDir,) = \Sabre\Uri\split($sourceNode->getPath());
397
+        $destinationDir = $this->getPath();
398
+
399
+        $sourcePath = $sourceNode->getPath();
400
+
401
+        $isMovableMount = false;
402
+        $sourceMount = \OC::$server->getMountManager()->find($this->fileView->getAbsolutePath($sourcePath));
403
+        $internalPath = $sourceMount->getInternalPath($this->fileView->getAbsolutePath($sourcePath));
404
+        if ($sourceMount instanceof MoveableMount && $internalPath === '') {
405
+            $isMovableMount = true;
406
+        }
407
+
408
+        try {
409
+            $sameFolder = ($sourceDir === $destinationDir);
410
+            // if we're overwriting or same folder
411
+            if ($targetNodeExists || $sameFolder) {
412
+                // note that renaming a share mount point is always allowed
413
+                if (!$this->fileView->isUpdatable($destinationDir) && !$isMovableMount) {
414
+                    throw new \Sabre\DAV\Exception\Forbidden();
415
+                }
416
+            } else {
417
+                if (!$this->fileView->isCreatable($destinationDir)) {
418
+                    throw new \Sabre\DAV\Exception\Forbidden();
419
+                }
420
+            }
421
+
422
+            if (!$sameFolder) {
423
+                // moving to a different folder, source will be gone, like a deletion
424
+                // note that moving a share mount point is always allowed
425
+                if (!$this->fileView->isDeletable($sourcePath) && !$isMovableMount) {
426
+                    throw new \Sabre\DAV\Exception\Forbidden();
427
+                }
428
+            }
429
+
430
+            $fileName = basename($destinationPath);
431
+            try {
432
+                $this->fileView->verifyPath($destinationDir, $fileName);
433
+            } catch (InvalidPathException $ex) {
434
+                throw new InvalidPath($ex->getMessage());
435
+            }
436
+
437
+            $renameOkay = $this->fileView->rename($sourcePath, $destinationPath);
438
+            if (!$renameOkay) {
439
+                throw new \Sabre\DAV\Exception\Forbidden('');
440
+            }
441
+        } catch (StorageNotAvailableException $e) {
442
+            throw new ServiceUnavailable($e->getMessage());
443
+        } catch (ForbiddenException $ex) {
444
+            throw new Forbidden($ex->getMessage(), $ex->getRetry());
445
+        } catch (LockedException $e) {
446
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
447
+        }
448
+
449
+        return true;
450
+    }
451 451
 }
Please login to merge, or discard this patch.