Passed
Push — master ( 62403d...0c3e2f )
by Joas
14:50 queued 14s
created
lib/private/legacy/files.php 1 patch
Indentation   +380 added lines, -380 removed lines patch added patch discarded remove patch
@@ -50,385 +50,385 @@
 block discarded – undo
50 50
  *
51 51
  */
52 52
 class OC_Files {
53
-	const FILE = 1;
54
-	const ZIP_FILES = 2;
55
-	const ZIP_DIR = 3;
56
-
57
-	const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
58
-
59
-
60
-	private static $multipartBoundary = '';
61
-
62
-	/**
63
-	 * @return string
64
-	 */
65
-	private static function getBoundary() {
66
-		if (empty(self::$multipartBoundary)) {
67
-			self::$multipartBoundary = md5(mt_rand());
68
-		}
69
-		return self::$multipartBoundary;
70
-	}
71
-
72
-	/**
73
-	 * @param string $filename
74
-	 * @param string $name
75
-	 * @param array $rangeArray ('from'=>int,'to'=>int), ...
76
-	 */
77
-	private static function sendHeaders($filename, $name, array $rangeArray) {
78
-		OC_Response::setContentDispositionHeader($name, 'attachment');
79
-		header('Content-Transfer-Encoding: binary', true);
80
-		header('Pragma: public');// enable caching in IE
81
-		header('Expires: 0');
82
-		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
83
-		$fileSize = \OC\Files\Filesystem::filesize($filename);
84
-		$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
85
-		if ($fileSize > -1) {
86
-			if (!empty($rangeArray)) {
87
-			    http_response_code(206);
88
-			    header('Accept-Ranges: bytes', true);
89
-			    if (count($rangeArray) > 1) {
90
-				$type = 'multipart/byteranges; boundary='.self::getBoundary();
91
-				// no Content-Length header here
92
-			    }
93
-			    else {
94
-				header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
95
-				OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
96
-			    }
97
-			}
98
-			else {
99
-			    OC_Response::setContentLengthHeader($fileSize);
100
-			}
101
-		}
102
-		header('Content-Type: '.$type, true);
103
-	}
104
-
105
-	/**
106
-	 * return the content of a file or return a zip file containing multiple files
107
-	 *
108
-	 * @param string $dir
109
-	 * @param string $files ; separated list of files to download
110
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
111
-	 */
112
-	public static function get($dir, $files, $params = null) {
113
-
114
-		$view = \OC\Files\Filesystem::getView();
115
-		$getType = self::FILE;
116
-		$filename = $dir;
117
-		try {
118
-
119
-			if (is_array($files) && count($files) === 1) {
120
-				$files = $files[0];
121
-			}
122
-
123
-			if (!is_array($files)) {
124
-				$filename = $dir . '/' . $files;
125
-				if (!$view->is_dir($filename)) {
126
-					self::getSingleFile($view, $dir, $files, is_null($params) ? [] : $params);
127
-					return;
128
-				}
129
-			}
130
-
131
-			$name = 'download';
132
-			if (is_array($files)) {
133
-				$getType = self::ZIP_FILES;
134
-				$basename = basename($dir);
135
-				if ($basename) {
136
-					$name = $basename;
137
-				}
138
-
139
-				$filename = $dir . '/' . $name;
140
-			} else {
141
-				$filename = $dir . '/' . $files;
142
-				$getType = self::ZIP_DIR;
143
-				// downloading root ?
144
-				if ($files !== '') {
145
-					$name = $files;
146
-				}
147
-			}
148
-
149
-			self::lockFiles($view, $dir, $files);
150
-
151
-			/* Calculate filesize and number of files */
152
-			if ($getType === self::ZIP_FILES) {
153
-				$fileInfos = [];
154
-				$fileSize = 0;
155
-				foreach ($files as $file) {
156
-					$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
157
-					$fileSize += $fileInfo->getSize();
158
-					$fileInfos[] = $fileInfo;
159
-				}
160
-				$numberOfFiles = self::getNumberOfFiles($fileInfos);
161
-			} elseif ($getType === self::ZIP_DIR) {
162
-				$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
163
-				$fileSize = $fileInfo->getSize();
164
-				$numberOfFiles = self::getNumberOfFiles([$fileInfo]);
165
-			}
166
-
167
-			$streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
168
-			OC_Util::obEnd();
169
-
170
-			$streamer->sendHeaders($name);
171
-			$executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
172
-			if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
173
-				@set_time_limit(0);
174
-			}
175
-			ignore_user_abort(true);
176
-
177
-			if ($getType === self::ZIP_FILES) {
178
-				foreach ($files as $file) {
179
-					$file = $dir . '/' . $file;
180
-					if (\OC\Files\Filesystem::is_file($file)) {
181
-						$userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
182
-						$file = $userFolder->get($file);
183
-						if($file instanceof \OC\Files\Node\File) {
184
-							try {
185
-								$fh = $file->fopen('r');
186
-							} catch (\OCP\Files\NotPermittedException $e) {
187
-								continue;
188
-							}
189
-							$fileSize = $file->getSize();
190
-							$fileTime = $file->getMTime();
191
-						} else {
192
-							// File is not a file? …
193
-							\OC::$server->getLogger()->debug(
194
-								'File given, but no Node available. Name {file}',
195
-								[ 'app' => 'files', 'file' => $file ]
196
-							);
197
-							continue;
198
-						}
199
-						$streamer->addFileFromStream($fh, $file->getName(), $fileSize, $fileTime);
200
-						fclose($fh);
201
-					} elseif (\OC\Files\Filesystem::is_dir($file)) {
202
-						$streamer->addDirRecursive($file);
203
-					}
204
-				}
205
-			} elseif ($getType === self::ZIP_DIR) {
206
-				$file = $dir . '/' . $files;
207
-				$streamer->addDirRecursive($file);
208
-			}
209
-			$streamer->finalize();
210
-			set_time_limit($executionTime);
211
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
212
-		} catch (\OCP\Lock\LockedException $ex) {
213
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
214
-			OC::$server->getLogger()->logException($ex);
215
-			$l = \OC::$server->getL10N('core');
216
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
217
-			\OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint, 200);
218
-		} catch (\OCP\Files\ForbiddenException $ex) {
219
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
220
-			OC::$server->getLogger()->logException($ex);
221
-			$l = \OC::$server->getL10N('core');
222
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage(), 200);
223
-		} catch (\Exception $ex) {
224
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
225
-			OC::$server->getLogger()->logException($ex);
226
-			$l = \OC::$server->getL10N('core');
227
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
228
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $hint, 200);
229
-		}
230
-	}
231
-
232
-	/**
233
-	 * @param string $rangeHeaderPos
234
-	 * @param int $fileSize
235
-	 * @return array $rangeArray ('from'=>int,'to'=>int), ...
236
-	 */
237
-	private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
238
-		$rArray=explode(',', $rangeHeaderPos);
239
-		$minOffset = 0;
240
-		$ind = 0;
241
-
242
-		$rangeArray = [];
243
-
244
-		foreach ($rArray as $value) {
245
-			$ranges = explode('-', $value);
246
-			if (is_numeric($ranges[0])) {
247
-				if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
248
-					$ranges[0] = $minOffset;
249
-				}
250
-				if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
251
-					$ind--;
252
-					$ranges[0] = $rangeArray[$ind]['from'];
253
-				}
254
-			}
255
-
256
-			if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
257
-				// case: x-x
258
-				if ($ranges[1] >= $fileSize) {
259
-					$ranges[1] = $fileSize-1;
260
-				}
261
-				$rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize ];
262
-				$minOffset = $ranges[1] + 1;
263
-				if ($minOffset >= $fileSize) {
264
-					break;
265
-				}
266
-			}
267
-			elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
268
-				// case: x-
269
-				$rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize ];
270
-				break;
271
-			}
272
-			elseif (is_numeric($ranges[1])) {
273
-				// case: -x
274
-				if ($ranges[1] > $fileSize) {
275
-					$ranges[1] = $fileSize;
276
-				}
277
-				$rangeArray[$ind++] = [ 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize ];
278
-				break;
279
-			}
280
-		}
281
-		return $rangeArray;
282
-	}
283
-
284
-	/**
285
-	 * @param View $view
286
-	 * @param string $name
287
-	 * @param string $dir
288
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
289
-	 */
290
-	private static function getSingleFile($view, $dir, $name, $params) {
291
-		$filename = $dir . '/' . $name;
292
-		$file = null;
293
-
294
-		try {
295
-			$userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
296
-			$file = $userFolder->get($filename);
297
-			if(!$file instanceof \OC\Files\Node\File || !$file->isReadable()) {
298
-				http_response_code(403);
299
-				die('403 Forbidden');
300
-			}
301
-			$fileSize = $file->getSize();
302
-		} catch (\OCP\Files\NotPermittedException $e) {
303
-			http_response_code(403);
304
-			die('403 Forbidden');
305
-		} catch (\OCP\Files\InvalidPathException $e) {
306
-			http_response_code(403);
307
-			die('403 Forbidden');
308
-		} catch (\OCP\Files\NotFoundException $e) {
309
-			http_response_code(404);
310
-			$tmpl = new OC_Template('', '404', 'guest');
311
-			$tmpl->printPage();
312
-			exit();
313
-		}
314
-
315
-		OC_Util::obEnd();
316
-		$view->lockFile($filename, ILockingProvider::LOCK_SHARED);
317
-
318
-		$rangeArray = [];
319
-
320
-		if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
321
-			$rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), $fileSize);
322
-		}
323
-
324
-		self::sendHeaders($filename, $name, $rangeArray);
325
-
326
-		if (isset($params['head']) && $params['head']) {
327
-			return;
328
-		}
329
-
330
-		if (!empty($rangeArray)) {
331
-			try {
332
-			    if (count($rangeArray) == 1) {
333
-				$view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
334
-			    }
335
-			    else {
336
-				// check if file is seekable (if not throw UnseekableException)
337
-				// we have to check it before body contents
338
-				$view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
339
-
340
-				$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
341
-
342
-				foreach ($rangeArray as $range) {
343
-				    echo "\r\n--".self::getBoundary()."\r\n".
344
-				         "Content-type: ".$type."\r\n".
345
-				         "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
346
-				    $view->readfilePart($filename, $range['from'], $range['to']);
347
-				}
348
-				echo "\r\n--".self::getBoundary()."--\r\n";
349
-			    }
350
-			} catch (\OCP\Files\UnseekableException $ex) {
351
-			    // file is unseekable
352
-			    header_remove('Accept-Ranges');
353
-			    header_remove('Content-Range');
354
-			    http_response_code(200);
355
-			    self::sendHeaders($filename, $name, []);
356
-			    $view->readfile($filename);
357
-			}
358
-		}
359
-		else {
360
-		    $view->readfile($filename);
361
-		}
362
-	}
363
-
364
-	/**
365
-	 * Returns the total (recursive) number of files and folders in the given
366
-	 * FileInfos.
367
-	 *
368
-	 * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
369
-	 * @return int the total number of files and folders
370
-	 */
371
-	private static function getNumberOfFiles($fileInfos) {
372
-		$numberOfFiles = 0;
373
-
374
-		$view = new View();
375
-
376
-		while ($fileInfo = array_pop($fileInfos)) {
377
-			$numberOfFiles++;
378
-
379
-			if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
380
-				$fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
381
-			}
382
-		}
383
-
384
-		return $numberOfFiles;
385
-	}
386
-
387
-	/**
388
-	 * @param View $view
389
-	 * @param string $dir
390
-	 * @param string[]|string $files
391
-	 */
392
-	public static function lockFiles($view, $dir, $files) {
393
-		if (!is_array($files)) {
394
-			$file = $dir . '/' . $files;
395
-			$files = [$file];
396
-		}
397
-		foreach ($files as $file) {
398
-			$file = $dir . '/' . $file;
399
-			$view->lockFile($file, ILockingProvider::LOCK_SHARED);
400
-			if ($view->is_dir($file)) {
401
-				$contents = $view->getDirectoryContent($file);
402
-				$contents = array_map(function($fileInfo) use ($file) {
403
-					/** @var \OCP\Files\FileInfo $fileInfo */
404
-					return $file . '/' . $fileInfo->getName();
405
-				}, $contents);
406
-				self::lockFiles($view, $dir, $contents);
407
-			}
408
-		}
409
-	}
410
-
411
-	/**
412
-	 * @param string $dir
413
-	 * @param $files
414
-	 * @param integer $getType
415
-	 * @param View $view
416
-	 * @param string $filename
417
-	 */
418
-	private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
419
-		if ($getType === self::FILE) {
420
-			$view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
421
-		}
422
-		if ($getType === self::ZIP_FILES) {
423
-			foreach ($files as $file) {
424
-				$file = $dir . '/' . $file;
425
-				$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
426
-			}
427
-		}
428
-		if ($getType === self::ZIP_DIR) {
429
-			$file = $dir . '/' . $files;
430
-			$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
431
-		}
432
-	}
53
+    const FILE = 1;
54
+    const ZIP_FILES = 2;
55
+    const ZIP_DIR = 3;
56
+
57
+    const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
58
+
59
+
60
+    private static $multipartBoundary = '';
61
+
62
+    /**
63
+     * @return string
64
+     */
65
+    private static function getBoundary() {
66
+        if (empty(self::$multipartBoundary)) {
67
+            self::$multipartBoundary = md5(mt_rand());
68
+        }
69
+        return self::$multipartBoundary;
70
+    }
71
+
72
+    /**
73
+     * @param string $filename
74
+     * @param string $name
75
+     * @param array $rangeArray ('from'=>int,'to'=>int), ...
76
+     */
77
+    private static function sendHeaders($filename, $name, array $rangeArray) {
78
+        OC_Response::setContentDispositionHeader($name, 'attachment');
79
+        header('Content-Transfer-Encoding: binary', true);
80
+        header('Pragma: public');// enable caching in IE
81
+        header('Expires: 0');
82
+        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
83
+        $fileSize = \OC\Files\Filesystem::filesize($filename);
84
+        $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
85
+        if ($fileSize > -1) {
86
+            if (!empty($rangeArray)) {
87
+                http_response_code(206);
88
+                header('Accept-Ranges: bytes', true);
89
+                if (count($rangeArray) > 1) {
90
+                $type = 'multipart/byteranges; boundary='.self::getBoundary();
91
+                // no Content-Length header here
92
+                }
93
+                else {
94
+                header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
95
+                OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
96
+                }
97
+            }
98
+            else {
99
+                OC_Response::setContentLengthHeader($fileSize);
100
+            }
101
+        }
102
+        header('Content-Type: '.$type, true);
103
+    }
104
+
105
+    /**
106
+     * return the content of a file or return a zip file containing multiple files
107
+     *
108
+     * @param string $dir
109
+     * @param string $files ; separated list of files to download
110
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
111
+     */
112
+    public static function get($dir, $files, $params = null) {
113
+
114
+        $view = \OC\Files\Filesystem::getView();
115
+        $getType = self::FILE;
116
+        $filename = $dir;
117
+        try {
118
+
119
+            if (is_array($files) && count($files) === 1) {
120
+                $files = $files[0];
121
+            }
122
+
123
+            if (!is_array($files)) {
124
+                $filename = $dir . '/' . $files;
125
+                if (!$view->is_dir($filename)) {
126
+                    self::getSingleFile($view, $dir, $files, is_null($params) ? [] : $params);
127
+                    return;
128
+                }
129
+            }
130
+
131
+            $name = 'download';
132
+            if (is_array($files)) {
133
+                $getType = self::ZIP_FILES;
134
+                $basename = basename($dir);
135
+                if ($basename) {
136
+                    $name = $basename;
137
+                }
138
+
139
+                $filename = $dir . '/' . $name;
140
+            } else {
141
+                $filename = $dir . '/' . $files;
142
+                $getType = self::ZIP_DIR;
143
+                // downloading root ?
144
+                if ($files !== '') {
145
+                    $name = $files;
146
+                }
147
+            }
148
+
149
+            self::lockFiles($view, $dir, $files);
150
+
151
+            /* Calculate filesize and number of files */
152
+            if ($getType === self::ZIP_FILES) {
153
+                $fileInfos = [];
154
+                $fileSize = 0;
155
+                foreach ($files as $file) {
156
+                    $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
157
+                    $fileSize += $fileInfo->getSize();
158
+                    $fileInfos[] = $fileInfo;
159
+                }
160
+                $numberOfFiles = self::getNumberOfFiles($fileInfos);
161
+            } elseif ($getType === self::ZIP_DIR) {
162
+                $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
163
+                $fileSize = $fileInfo->getSize();
164
+                $numberOfFiles = self::getNumberOfFiles([$fileInfo]);
165
+            }
166
+
167
+            $streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
168
+            OC_Util::obEnd();
169
+
170
+            $streamer->sendHeaders($name);
171
+            $executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
172
+            if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
173
+                @set_time_limit(0);
174
+            }
175
+            ignore_user_abort(true);
176
+
177
+            if ($getType === self::ZIP_FILES) {
178
+                foreach ($files as $file) {
179
+                    $file = $dir . '/' . $file;
180
+                    if (\OC\Files\Filesystem::is_file($file)) {
181
+                        $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
182
+                        $file = $userFolder->get($file);
183
+                        if($file instanceof \OC\Files\Node\File) {
184
+                            try {
185
+                                $fh = $file->fopen('r');
186
+                            } catch (\OCP\Files\NotPermittedException $e) {
187
+                                continue;
188
+                            }
189
+                            $fileSize = $file->getSize();
190
+                            $fileTime = $file->getMTime();
191
+                        } else {
192
+                            // File is not a file? …
193
+                            \OC::$server->getLogger()->debug(
194
+                                'File given, but no Node available. Name {file}',
195
+                                [ 'app' => 'files', 'file' => $file ]
196
+                            );
197
+                            continue;
198
+                        }
199
+                        $streamer->addFileFromStream($fh, $file->getName(), $fileSize, $fileTime);
200
+                        fclose($fh);
201
+                    } elseif (\OC\Files\Filesystem::is_dir($file)) {
202
+                        $streamer->addDirRecursive($file);
203
+                    }
204
+                }
205
+            } elseif ($getType === self::ZIP_DIR) {
206
+                $file = $dir . '/' . $files;
207
+                $streamer->addDirRecursive($file);
208
+            }
209
+            $streamer->finalize();
210
+            set_time_limit($executionTime);
211
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
212
+        } catch (\OCP\Lock\LockedException $ex) {
213
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
214
+            OC::$server->getLogger()->logException($ex);
215
+            $l = \OC::$server->getL10N('core');
216
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
217
+            \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint, 200);
218
+        } catch (\OCP\Files\ForbiddenException $ex) {
219
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
220
+            OC::$server->getLogger()->logException($ex);
221
+            $l = \OC::$server->getL10N('core');
222
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage(), 200);
223
+        } catch (\Exception $ex) {
224
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
225
+            OC::$server->getLogger()->logException($ex);
226
+            $l = \OC::$server->getL10N('core');
227
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
228
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint, 200);
229
+        }
230
+    }
231
+
232
+    /**
233
+     * @param string $rangeHeaderPos
234
+     * @param int $fileSize
235
+     * @return array $rangeArray ('from'=>int,'to'=>int), ...
236
+     */
237
+    private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
238
+        $rArray=explode(',', $rangeHeaderPos);
239
+        $minOffset = 0;
240
+        $ind = 0;
241
+
242
+        $rangeArray = [];
243
+
244
+        foreach ($rArray as $value) {
245
+            $ranges = explode('-', $value);
246
+            if (is_numeric($ranges[0])) {
247
+                if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
248
+                    $ranges[0] = $minOffset;
249
+                }
250
+                if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
251
+                    $ind--;
252
+                    $ranges[0] = $rangeArray[$ind]['from'];
253
+                }
254
+            }
255
+
256
+            if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
257
+                // case: x-x
258
+                if ($ranges[1] >= $fileSize) {
259
+                    $ranges[1] = $fileSize-1;
260
+                }
261
+                $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize ];
262
+                $minOffset = $ranges[1] + 1;
263
+                if ($minOffset >= $fileSize) {
264
+                    break;
265
+                }
266
+            }
267
+            elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
268
+                // case: x-
269
+                $rangeArray[$ind++] = [ 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize ];
270
+                break;
271
+            }
272
+            elseif (is_numeric($ranges[1])) {
273
+                // case: -x
274
+                if ($ranges[1] > $fileSize) {
275
+                    $ranges[1] = $fileSize;
276
+                }
277
+                $rangeArray[$ind++] = [ 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize ];
278
+                break;
279
+            }
280
+        }
281
+        return $rangeArray;
282
+    }
283
+
284
+    /**
285
+     * @param View $view
286
+     * @param string $name
287
+     * @param string $dir
288
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
289
+     */
290
+    private static function getSingleFile($view, $dir, $name, $params) {
291
+        $filename = $dir . '/' . $name;
292
+        $file = null;
293
+
294
+        try {
295
+            $userFolder = \OC::$server->getRootFolder()->get(\OC\Files\Filesystem::getRoot());
296
+            $file = $userFolder->get($filename);
297
+            if(!$file instanceof \OC\Files\Node\File || !$file->isReadable()) {
298
+                http_response_code(403);
299
+                die('403 Forbidden');
300
+            }
301
+            $fileSize = $file->getSize();
302
+        } catch (\OCP\Files\NotPermittedException $e) {
303
+            http_response_code(403);
304
+            die('403 Forbidden');
305
+        } catch (\OCP\Files\InvalidPathException $e) {
306
+            http_response_code(403);
307
+            die('403 Forbidden');
308
+        } catch (\OCP\Files\NotFoundException $e) {
309
+            http_response_code(404);
310
+            $tmpl = new OC_Template('', '404', 'guest');
311
+            $tmpl->printPage();
312
+            exit();
313
+        }
314
+
315
+        OC_Util::obEnd();
316
+        $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
317
+
318
+        $rangeArray = [];
319
+
320
+        if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
321
+            $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), $fileSize);
322
+        }
323
+
324
+        self::sendHeaders($filename, $name, $rangeArray);
325
+
326
+        if (isset($params['head']) && $params['head']) {
327
+            return;
328
+        }
329
+
330
+        if (!empty($rangeArray)) {
331
+            try {
332
+                if (count($rangeArray) == 1) {
333
+                $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
334
+                }
335
+                else {
336
+                // check if file is seekable (if not throw UnseekableException)
337
+                // we have to check it before body contents
338
+                $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
339
+
340
+                $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
341
+
342
+                foreach ($rangeArray as $range) {
343
+                    echo "\r\n--".self::getBoundary()."\r\n".
344
+                            "Content-type: ".$type."\r\n".
345
+                            "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
346
+                    $view->readfilePart($filename, $range['from'], $range['to']);
347
+                }
348
+                echo "\r\n--".self::getBoundary()."--\r\n";
349
+                }
350
+            } catch (\OCP\Files\UnseekableException $ex) {
351
+                // file is unseekable
352
+                header_remove('Accept-Ranges');
353
+                header_remove('Content-Range');
354
+                http_response_code(200);
355
+                self::sendHeaders($filename, $name, []);
356
+                $view->readfile($filename);
357
+            }
358
+        }
359
+        else {
360
+            $view->readfile($filename);
361
+        }
362
+    }
363
+
364
+    /**
365
+     * Returns the total (recursive) number of files and folders in the given
366
+     * FileInfos.
367
+     *
368
+     * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
369
+     * @return int the total number of files and folders
370
+     */
371
+    private static function getNumberOfFiles($fileInfos) {
372
+        $numberOfFiles = 0;
373
+
374
+        $view = new View();
375
+
376
+        while ($fileInfo = array_pop($fileInfos)) {
377
+            $numberOfFiles++;
378
+
379
+            if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
380
+                $fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
381
+            }
382
+        }
383
+
384
+        return $numberOfFiles;
385
+    }
386
+
387
+    /**
388
+     * @param View $view
389
+     * @param string $dir
390
+     * @param string[]|string $files
391
+     */
392
+    public static function lockFiles($view, $dir, $files) {
393
+        if (!is_array($files)) {
394
+            $file = $dir . '/' . $files;
395
+            $files = [$file];
396
+        }
397
+        foreach ($files as $file) {
398
+            $file = $dir . '/' . $file;
399
+            $view->lockFile($file, ILockingProvider::LOCK_SHARED);
400
+            if ($view->is_dir($file)) {
401
+                $contents = $view->getDirectoryContent($file);
402
+                $contents = array_map(function($fileInfo) use ($file) {
403
+                    /** @var \OCP\Files\FileInfo $fileInfo */
404
+                    return $file . '/' . $fileInfo->getName();
405
+                }, $contents);
406
+                self::lockFiles($view, $dir, $contents);
407
+            }
408
+        }
409
+    }
410
+
411
+    /**
412
+     * @param string $dir
413
+     * @param $files
414
+     * @param integer $getType
415
+     * @param View $view
416
+     * @param string $filename
417
+     */
418
+    private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
419
+        if ($getType === self::FILE) {
420
+            $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
421
+        }
422
+        if ($getType === self::ZIP_FILES) {
423
+            foreach ($files as $file) {
424
+                $file = $dir . '/' . $file;
425
+                $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
426
+            }
427
+        }
428
+        if ($getType === self::ZIP_DIR) {
429
+            $file = $dir . '/' . $files;
430
+            $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
431
+        }
432
+    }
433 433
 
434 434
 }
Please login to merge, or discard this patch.
lib/private/legacy/template/functions.php 1 patch
Indentation   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
  * @param string $string the string which will be escaped and printed
37 37
  */
38 38
 function p($string) {
39
-	print(\OCP\Util::sanitizeHTML($string));
39
+    print(\OCP\Util::sanitizeHTML($string));
40 40
 }
41 41
 
42 42
 
@@ -46,14 +46,14 @@  discard block
 block discarded – undo
46 46
  * @param string $opts, additional optional options
47 47
 */
48 48
 function emit_css_tag($href, $opts = '') {
49
-	$s='<link rel="stylesheet"';
50
-	if (!empty($href)) {
51
-		$s.=' href="' . $href .'"';
52
-	}
53
-	if (!empty($opts)) {
54
-		$s.=' '.$opts;
55
-	}
56
-	print_unescaped($s.">\n");
49
+    $s='<link rel="stylesheet"';
50
+    if (!empty($href)) {
51
+        $s.=' href="' . $href .'"';
52
+    }
53
+    if (!empty($opts)) {
54
+        $s.=' '.$opts;
55
+    }
56
+    print_unescaped($s.">\n");
57 57
 }
58 58
 
59 59
 /**
@@ -61,12 +61,12 @@  discard block
 block discarded – undo
61 61
  * @param array $obj all the script information from template
62 62
 */
63 63
 function emit_css_loading_tags($obj) {
64
-	foreach($obj['cssfiles'] as $css) {
65
-		emit_css_tag($css);
66
-	}
67
-	foreach($obj['printcssfiles'] as $css) {
68
-		emit_css_tag($css, 'media="print"');
69
-	}
64
+    foreach($obj['cssfiles'] as $css) {
65
+        emit_css_tag($css);
66
+    }
67
+    foreach($obj['printcssfiles'] as $css) {
68
+        emit_css_tag($css, 'media="print"');
69
+    }
70 70
 }
71 71
 
72 72
 /**
@@ -75,20 +75,20 @@  discard block
 block discarded – undo
75 75
  * @param string $script_content the inline script content, ignored when empty
76 76
 */
77 77
 function emit_script_tag($src, $script_content='') {
78
-	$defer_str=' defer';
79
-	$s='<script nonce="' . \OC::$server->getContentSecurityPolicyNonceManager()->getNonce() . '"';
80
-	if (!empty($src)) {
81
-		 // emit script tag for deferred loading from $src
82
-		$s.=$defer_str.' src="' . $src .'">';
83
-	} else if (!empty($script_content)) {
84
-		// emit script tag for inline script from $script_content without defer (see MDN)
85
-		$s.=">\n".$script_content."\n";
86
-	} else {
87
-		// no $src nor $src_content, really useless empty tag
88
-		$s.='>';
89
-	}
90
-	$s.='</script>';
91
-	print_unescaped($s."\n");
78
+    $defer_str=' defer';
79
+    $s='<script nonce="' . \OC::$server->getContentSecurityPolicyNonceManager()->getNonce() . '"';
80
+    if (!empty($src)) {
81
+            // emit script tag for deferred loading from $src
82
+        $s.=$defer_str.' src="' . $src .'">';
83
+    } else if (!empty($script_content)) {
84
+        // emit script tag for inline script from $script_content without defer (see MDN)
85
+        $s.=">\n".$script_content."\n";
86
+    } else {
87
+        // no $src nor $src_content, really useless empty tag
88
+        $s.='>';
89
+    }
90
+    $s.='</script>';
91
+    print_unescaped($s."\n");
92 92
 }
93 93
 
94 94
 /**
@@ -96,12 +96,12 @@  discard block
 block discarded – undo
96 96
  * @param array $obj all the script information from template
97 97
 */
98 98
 function emit_script_loading_tags($obj) {
99
-	foreach($obj['jsfiles'] as $jsfile) {
100
-		emit_script_tag($jsfile, '');
101
-	}
102
-	if (!empty($obj['inline_ocjs'])) {
103
-		emit_script_tag('', $obj['inline_ocjs']);
104
-	}
99
+    foreach($obj['jsfiles'] as $jsfile) {
100
+        emit_script_tag($jsfile, '');
101
+    }
102
+    if (!empty($obj['inline_ocjs'])) {
103
+        emit_script_tag('', $obj['inline_ocjs']);
104
+    }
105 105
 }
106 106
 
107 107
 /**
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
  * @param string|array $string the string which will be printed as it is
111 111
  */
112 112
 function print_unescaped($string) {
113
-	print($string);
113
+    print($string);
114 114
 }
115 115
 
116 116
 /**
@@ -120,13 +120,13 @@  discard block
 block discarded – undo
120 120
  * if an array is given it will add all scripts
121 121
  */
122 122
 function script($app, $file = null) {
123
-	if(is_array($file)) {
124
-		foreach($file as $f) {
125
-			OC_Util::addScript($app, $f);
126
-		}
127
-	} else {
128
-		OC_Util::addScript($app, $file);
129
-	}
123
+    if(is_array($file)) {
124
+        foreach($file as $f) {
125
+            OC_Util::addScript($app, $f);
126
+        }
127
+    } else {
128
+        OC_Util::addScript($app, $file);
129
+    }
130 130
 }
131 131
 
132 132
 /**
@@ -136,13 +136,13 @@  discard block
 block discarded – undo
136 136
  * if an array is given it will add all scripts
137 137
  */
138 138
 function vendor_script($app, $file = null) {
139
-	if(is_array($file)) {
140
-		foreach($file as $f) {
141
-			OC_Util::addVendorScript($app, $f);
142
-		}
143
-	} else {
144
-		OC_Util::addVendorScript($app, $file);
145
-	}
139
+    if(is_array($file)) {
140
+        foreach($file as $f) {
141
+            OC_Util::addVendorScript($app, $f);
142
+        }
143
+    } else {
144
+        OC_Util::addVendorScript($app, $file);
145
+    }
146 146
 }
147 147
 
148 148
 /**
@@ -152,13 +152,13 @@  discard block
 block discarded – undo
152 152
  * if an array is given it will add all styles
153 153
  */
154 154
 function style($app, $file = null) {
155
-	if(is_array($file)) {
156
-		foreach($file as $f) {
157
-			OC_Util::addStyle($app, $f);
158
-		}
159
-	} else {
160
-		OC_Util::addStyle($app, $file);
161
-	}
155
+    if(is_array($file)) {
156
+        foreach($file as $f) {
157
+            OC_Util::addStyle($app, $f);
158
+        }
159
+    } else {
160
+        OC_Util::addStyle($app, $file);
161
+    }
162 162
 }
163 163
 
164 164
 /**
@@ -168,13 +168,13 @@  discard block
 block discarded – undo
168 168
  * if an array is given it will add all styles
169 169
  */
170 170
 function vendor_style($app, $file = null) {
171
-	if(is_array($file)) {
172
-		foreach($file as $f) {
173
-			OC_Util::addVendorStyle($app, $f);
174
-		}
175
-	} else {
176
-		OC_Util::addVendorStyle($app, $file);
177
-	}
171
+    if(is_array($file)) {
172
+        foreach($file as $f) {
173
+            OC_Util::addVendorStyle($app, $f);
174
+        }
175
+    } else {
176
+        OC_Util::addVendorStyle($app, $file);
177
+    }
178 178
 }
179 179
 
180 180
 /**
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
  * if an array is given it will add all styles
184 184
  */
185 185
 function translation($app) {
186
-	OC_Util::addTranslations($app);
186
+    OC_Util::addTranslations($app);
187 187
 }
188 188
 
189 189
 /**
@@ -193,15 +193,15 @@  discard block
 block discarded – undo
193 193
  * if an array is given it will add all components
194 194
  */
195 195
 function component($app, $file) {
196
-	if(is_array($file)) {
197
-		foreach($file as $f) {
198
-			$url = link_to($app, 'component/' . $f . '.html');
199
-			OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
200
-		}
201
-	} else {
202
-		$url = link_to($app, 'component/' . $file . '.html');
203
-		OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
204
-	}
196
+    if(is_array($file)) {
197
+        foreach($file as $f) {
198
+            $url = link_to($app, 'component/' . $f . '.html');
199
+            OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
200
+        }
201
+    } else {
202
+        $url = link_to($app, 'component/' . $file . '.html');
203
+        OC_Util::addHeader('link', ['rel' => 'import', 'href' => $url]);
204
+    }
205 205
 }
206 206
 
207 207
 /**
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
  * For further information have a look at \OCP\IURLGenerator::linkTo
215 215
  */
216 216
 function link_to( $app, $file, $args = [] ) {
217
-	return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
217
+    return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
218 218
 }
219 219
 
220 220
 /**
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
  * @return string url to the online documentation
223 223
  */
224 224
 function link_to_docs($key) {
225
-	return \OC::$server->getURLGenerator()->linkToDocs($key);
225
+    return \OC::$server->getURLGenerator()->linkToDocs($key);
226 226
 }
227 227
 
228 228
 /**
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
  * For further information have a look at \OCP\IURLGenerator::imagePath
235 235
  */
236 236
 function image_path( $app, $image ) {
237
-	return \OC::$server->getURLGenerator()->imagePath( $app, $image );
237
+    return \OC::$server->getURLGenerator()->imagePath( $app, $image );
238 238
 }
239 239
 
240 240
 /**
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
  * @return string link to the image
244 244
  */
245 245
 function mimetype_icon( $mimetype ) {
246
-	return \OC::$server->getMimeTypeDetector()->mimeTypeIcon( $mimetype );
246
+    return \OC::$server->getMimeTypeDetector()->mimeTypeIcon( $mimetype );
247 247
 }
248 248
 
249 249
 /**
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
  * @return string link to the preview
254 254
  */
255 255
 function preview_icon( $path ) {
256
-	return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
256
+    return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
257 257
 }
258 258
 
259 259
 /**
@@ -262,7 +262,7 @@  discard block
 block discarded – undo
262 262
  * @return string
263 263
  */
264 264
 function publicPreview_icon ( $path, $token ) {
265
-	return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 'token' => $token]);
265
+    return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 'token' => $token]);
266 266
 }
267 267
 
268 268
 /**
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
  * For further information have a look at OC_Helper::humanFileSize
274 274
  */
275 275
 function human_file_size( $bytes ) {
276
-	return OC_Helper::humanFileSize( $bytes );
276
+    return OC_Helper::humanFileSize( $bytes );
277 277
 }
278 278
 
279 279
 /**
@@ -282,9 +282,9 @@  discard block
 block discarded – undo
282 282
  * @return int timestamp without time value
283 283
  */
284 284
 function strip_time($timestamp){
285
-	$date = new \DateTime("@{$timestamp}");
286
-	$date->setTime(0, 0, 0);
287
-	return (int)$date->format('U');
285
+    $date = new \DateTime("@{$timestamp}");
286
+    $date->setTime(0, 0, 0);
287
+    return (int)$date->format('U');
288 288
 }
289 289
 
290 290
 /**
@@ -296,39 +296,39 @@  discard block
 block discarded – undo
296 296
  * @return string timestamp
297 297
  */
298 298
 function relative_modified_date($timestamp, $fromTime = null, $dateOnly = false) {
299
-	/** @var \OC\DateTimeFormatter $formatter */
300
-	$formatter = \OC::$server->query('DateTimeFormatter');
299
+    /** @var \OC\DateTimeFormatter $formatter */
300
+    $formatter = \OC::$server->query('DateTimeFormatter');
301 301
 
302
-	if ($dateOnly){
303
-		return $formatter->formatDateSpan($timestamp, $fromTime);
304
-	}
305
-	return $formatter->formatTimeSpan($timestamp, $fromTime);
302
+    if ($dateOnly){
303
+        return $formatter->formatDateSpan($timestamp, $fromTime);
304
+    }
305
+    return $formatter->formatTimeSpan($timestamp, $fromTime);
306 306
 }
307 307
 
308 308
 function html_select_options($options, $selected, $params=[]) {
309
-	if (!is_array($selected)) {
310
-		$selected=[$selected];
311
-	}
312
-	if (isset($params['combine']) && $params['combine']) {
313
-		$options = array_combine($options, $options);
314
-	}
315
-	$value_name = $label_name = false;
316
-	if (isset($params['value'])) {
317
-		$value_name = $params['value'];
318
-	}
319
-	if (isset($params['label'])) {
320
-		$label_name = $params['label'];
321
-	}
322
-	$html = '';
323
-	foreach($options as $value => $label) {
324
-		if ($value_name && is_array($label)) {
325
-			$value = $label[$value_name];
326
-		}
327
-		if ($label_name && is_array($label)) {
328
-			$label = $label[$label_name];
329
-		}
330
-		$select = in_array($value, $selected) ? ' selected="selected"' : '';
331
-		$html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
332
-	}
333
-	return $html;
309
+    if (!is_array($selected)) {
310
+        $selected=[$selected];
311
+    }
312
+    if (isset($params['combine']) && $params['combine']) {
313
+        $options = array_combine($options, $options);
314
+    }
315
+    $value_name = $label_name = false;
316
+    if (isset($params['value'])) {
317
+        $value_name = $params['value'];
318
+    }
319
+    if (isset($params['label'])) {
320
+        $label_name = $params['label'];
321
+    }
322
+    $html = '';
323
+    foreach($options as $value => $label) {
324
+        if ($value_name && is_array($label)) {
325
+            $value = $label[$value_name];
326
+        }
327
+        if ($label_name && is_array($label)) {
328
+            $label = $label[$label_name];
329
+        }
330
+        $select = in_array($value, $selected) ? ' selected="selected"' : '';
331
+        $html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
332
+    }
333
+    return $html;
334 334
 }
Please login to merge, or discard this patch.
lib/private/legacy/db/statementwrapper.php 1 patch
Indentation   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -37,83 +37,83 @@
 block discarded – undo
37 37
  * @method array fetchAll(integer $fetchMode = null);
38 38
  */
39 39
 class OC_DB_StatementWrapper {
40
-	/**
41
-	 * @var \Doctrine\DBAL\Driver\Statement
42
-	 */
43
-	private $statement = null;
44
-	private $isManipulation = false;
45
-	private $lastArguments = [];
40
+    /**
41
+     * @var \Doctrine\DBAL\Driver\Statement
42
+     */
43
+    private $statement = null;
44
+    private $isManipulation = false;
45
+    private $lastArguments = [];
46 46
 
47
-	/**
48
-	 * @param boolean $isManipulation
49
-	 */
50
-	public function __construct($statement, $isManipulation) {
51
-		$this->statement = $statement;
52
-		$this->isManipulation = $isManipulation;
53
-	}
47
+    /**
48
+     * @param boolean $isManipulation
49
+     */
50
+    public function __construct($statement, $isManipulation) {
51
+        $this->statement = $statement;
52
+        $this->isManipulation = $isManipulation;
53
+    }
54 54
 
55
-	/**
56
-	 * pass all other function directly to the \Doctrine\DBAL\Driver\Statement
57
-	 */
58
-	public function __call($name,$arguments) {
59
-		return call_user_func_array([$this->statement,$name], $arguments);
60
-	}
55
+    /**
56
+     * pass all other function directly to the \Doctrine\DBAL\Driver\Statement
57
+     */
58
+    public function __call($name,$arguments) {
59
+        return call_user_func_array([$this->statement,$name], $arguments);
60
+    }
61 61
 
62
-	/**
63
-	 * make execute return the result instead of a bool
64
-	 *
65
-	 * @param array $input
66
-	 * @return \OC_DB_StatementWrapper|int|bool
67
-	 */
68
-	public function execute($input= []) {
69
-		$this->lastArguments = $input;
70
-		if (count($input) > 0) {
71
-			$result = $this->statement->execute($input);
72
-		} else {
73
-			$result = $this->statement->execute();
74
-		}
62
+    /**
63
+     * make execute return the result instead of a bool
64
+     *
65
+     * @param array $input
66
+     * @return \OC_DB_StatementWrapper|int|bool
67
+     */
68
+    public function execute($input= []) {
69
+        $this->lastArguments = $input;
70
+        if (count($input) > 0) {
71
+            $result = $this->statement->execute($input);
72
+        } else {
73
+            $result = $this->statement->execute();
74
+        }
75 75
 
76
-		if ($result === false) {
77
-			return false;
78
-		}
79
-		if ($this->isManipulation) {
80
-			return $this->statement->rowCount();
81
-		} else {
82
-			return $this;
83
-		}
84
-	}
76
+        if ($result === false) {
77
+            return false;
78
+        }
79
+        if ($this->isManipulation) {
80
+            return $this->statement->rowCount();
81
+        } else {
82
+            return $this;
83
+        }
84
+    }
85 85
 
86
-	/**
87
-	 * provide an alias for fetch
88
-	 *
89
-	 * @return mixed
90
-	 */
91
-	public function fetchRow() {
92
-		return $this->statement->fetch();
93
-	}
86
+    /**
87
+     * provide an alias for fetch
88
+     *
89
+     * @return mixed
90
+     */
91
+    public function fetchRow() {
92
+        return $this->statement->fetch();
93
+    }
94 94
 
95
-	/**
96
-	 * Provide a simple fetchOne.
97
-	 *
98
-	 * fetch single column from the next row
99
-	 * @param int $column the column number to fetch
100
-	 * @return string
101
-	 */
102
-	public function fetchOne($column = 0) {
103
-		return $this->statement->fetchColumn($column);
104
-	}
95
+    /**
96
+     * Provide a simple fetchOne.
97
+     *
98
+     * fetch single column from the next row
99
+     * @param int $column the column number to fetch
100
+     * @return string
101
+     */
102
+    public function fetchOne($column = 0) {
103
+        return $this->statement->fetchColumn($column);
104
+    }
105 105
 
106
-	/**
107
-	 * Binds a PHP variable to a corresponding named or question mark placeholder in the
108
-	 * SQL statement that was use to prepare the statement.
109
-	 *
110
-	 * @param mixed $column Either the placeholder name or the 1-indexed placeholder index
111
-	 * @param mixed $variable The variable to bind
112
-	 * @param integer|null $type one of the  PDO::PARAM_* constants
113
-	 * @param integer|null $length max length when using an OUT bind
114
-	 * @return boolean
115
-	 */
116
-	public function bindParam($column, &$variable, $type = null, $length = null){
117
-		return $this->statement->bindParam($column, $variable, $type, $length);
118
-	}
106
+    /**
107
+     * Binds a PHP variable to a corresponding named or question mark placeholder in the
108
+     * SQL statement that was use to prepare the statement.
109
+     *
110
+     * @param mixed $column Either the placeholder name or the 1-indexed placeholder index
111
+     * @param mixed $variable The variable to bind
112
+     * @param integer|null $type one of the  PDO::PARAM_* constants
113
+     * @param integer|null $length max length when using an OUT bind
114
+     * @return boolean
115
+     */
116
+    public function bindParam($column, &$variable, $type = null, $length = null){
117
+        return $this->statement->bindParam($column, $variable, $type, $length);
118
+    }
119 119
 }
Please login to merge, or discard this patch.
lib/private/legacy/template.php 1 patch
Indentation   +311 added lines, -311 removed lines patch added patch discarded remove patch
@@ -47,315 +47,315 @@
 block discarded – undo
47 47
  */
48 48
 class OC_Template extends \OC\Template\Base {
49 49
 
50
-	/** @var string */
51
-	private $renderAs; // Create a full page?
52
-
53
-	/** @var string */
54
-	private $path; // The path to the template
55
-
56
-	/** @var array */
57
-	private $headers = []; //custom headers
58
-
59
-	/** @var string */
60
-	protected $app; // app id
61
-
62
-	protected static $initTemplateEngineFirstRun = true;
63
-
64
-	/**
65
-	 * Constructor
66
-	 *
67
-	 * @param string $app app providing the template
68
-	 * @param string $name of the template file (without suffix)
69
-	 * @param string $renderAs If $renderAs is set, OC_Template will try to
70
-	 *                         produce a full page in the according layout. For
71
-	 *                         now, $renderAs can be set to "guest", "user" or
72
-	 *                         "admin".
73
-	 * @param bool $registerCall = true
74
-	 */
75
-	public function __construct( $app, $name, $renderAs = "", $registerCall = true ) {
76
-		// Read the selected theme from the config file
77
-		self::initTemplateEngine($renderAs);
78
-
79
-		$theme = OC_Util::getTheme();
80
-
81
-		$requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
82
-
83
-		$parts = explode('/', $app); // fix translation when app is something like core/lostpassword
84
-		$l10n = \OC::$server->getL10N($parts[0]);
85
-		/** @var \OCP\Defaults $themeDefaults */
86
-		$themeDefaults = \OC::$server->query(\OCP\Defaults::class);
87
-
88
-		list($path, $template) = $this->findTemplate($theme, $app, $name);
89
-
90
-		// Set the private data
91
-		$this->renderAs = $renderAs;
92
-		$this->path = $path;
93
-		$this->app = $app;
94
-
95
-		parent::__construct($template, $requestToken, $l10n, $themeDefaults);
96
-	}
97
-
98
-	/**
99
-	 * @param string $renderAs
100
-	 */
101
-	public static function initTemplateEngine($renderAs) {
102
-		if (self::$initTemplateEngineFirstRun){
103
-
104
-			//apps that started before the template initialization can load their own scripts/styles
105
-			//so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
106
-			//meaning the last script/style in this list will be loaded first
107
-			if (\OC::$server->getSystemConfig()->getValue ('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
108
-				if (\OC::$server->getConfig ()->getAppValue ( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax') {
109
-					OC_Util::addScript ( 'backgroundjobs', null, true );
110
-				}
111
-			}
112
-			OC_Util::addStyle('css-variables', null, true);
113
-			OC_Util::addStyle('server', null, true);
114
-			OC_Util::addTranslations('core', null, true);
115
-
116
-			if (\OC::$server->getSystemConfig()->getValue ('installed', false)) {
117
-				OC_Util::addStyle('search', 'results');
118
-				OC_Util::addScript('search', 'search', true);
119
-				OC_Util::addScript('search', 'searchprovider');
120
-				OC_Util::addScript('merged-template-prepend', null, true);
121
-				OC_Util::addScript('files/fileinfo');
122
-				OC_Util::addScript('files/client');
123
-			}
124
-			OC_Util::addScript('core', 'dist/main', true);
125
-
126
-			if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
127
-				// shim for the davclient.js library
128
-				\OCP\Util::addScript('files/iedavclient');
129
-			}
130
-
131
-			self::$initTemplateEngineFirstRun = false;
132
-		}
133
-
134
-	}
135
-
136
-
137
-	/**
138
-	 * find the template with the given name
139
-	 * @param string $name of the template file (without suffix)
140
-	 *
141
-	 * Will select the template file for the selected theme.
142
-	 * Checking all the possible locations.
143
-	 * @param string $theme
144
-	 * @param string $app
145
-	 * @return string[]
146
-	 */
147
-	protected function findTemplate($theme, $app, $name) {
148
-		// Check if it is a app template or not.
149
-		if( $app !== '' ) {
150
-			$dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
151
-		} else {
152
-			$dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
153
-		}
154
-		$locator = new \OC\Template\TemplateFileLocator( $dirs );
155
-		$template = $locator->find($name);
156
-		$path = $locator->getPath();
157
-		return [$path, $template];
158
-	}
159
-
160
-	/**
161
-	 * Add a custom element to the header
162
-	 * @param string $tag tag name of the element
163
-	 * @param array $attributes array of attributes for the element
164
-	 * @param string $text the text content for the element. If $text is null then the
165
-	 * element will be written as empty element. So use "" to get a closing tag.
166
-	 */
167
-	public function addHeader($tag, $attributes, $text=null) {
168
-		$this->headers[]= [
169
-			'tag' => $tag,
170
-			'attributes' => $attributes,
171
-			'text' => $text
172
-		];
173
-	}
174
-
175
-	/**
176
-	 * Process the template
177
-	 * @return boolean|string
178
-	 *
179
-	 * This function process the template. If $this->renderAs is set, it
180
-	 * will produce a full page.
181
-	 */
182
-	public function fetchPage($additionalParams = null) {
183
-		$data = parent::fetchPage($additionalParams);
184
-
185
-		if( $this->renderAs ) {
186
-			$page = new TemplateLayout($this->renderAs, $this->app);
187
-
188
-			if(is_array($additionalParams)) {
189
-				foreach ($additionalParams as $key => $value) {
190
-					$page->assign($key, $value);
191
-				}
192
-			}
193
-
194
-			// Add custom headers
195
-			$headers = '';
196
-			foreach(OC_Util::$headers as $header) {
197
-				$headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
198
-				if ( strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes']))) ) {
199
-					$headers .= ' defer';
200
-				}
201
-				foreach($header['attributes'] as $name=>$value) {
202
-					$headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
203
-				}
204
-				if ($header['text'] !== null) {
205
-					$headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
206
-				} else {
207
-					$headers .= '/>';
208
-				}
209
-			}
210
-
211
-			$page->assign('headers', $headers);
212
-
213
-			$page->assign('content', $data);
214
-			return $page->fetchPage($additionalParams);
215
-		}
216
-
217
-		return $data;
218
-	}
219
-
220
-	/**
221
-	 * Include template
222
-	 *
223
-	 * @param string $file
224
-	 * @param array|null $additionalParams
225
-	 * @return string returns content of included template
226
-	 *
227
-	 * Includes another template. use <?php echo $this->inc('template'); ?> to
228
-	 * do this.
229
-	 */
230
-	public function inc( $file, $additionalParams = null ) {
231
-		return $this->load($this->path.$file.'.php', $additionalParams);
232
-	}
233
-
234
-	/**
235
-	 * Shortcut to print a simple page for users
236
-	 * @param string $application The application we render the template for
237
-	 * @param string $name Name of the template
238
-	 * @param array $parameters Parameters for the template
239
-	 * @return boolean|null
240
-	 */
241
-	public static function printUserPage( $application, $name, $parameters = [] ) {
242
-		$content = new OC_Template( $application, $name, "user" );
243
-		foreach( $parameters as $key => $value ) {
244
-			$content->assign( $key, $value );
245
-		}
246
-		print $content->printPage();
247
-	}
248
-
249
-	/**
250
-	 * Shortcut to print a simple page for admins
251
-	 * @param string $application The application we render the template for
252
-	 * @param string $name Name of the template
253
-	 * @param array $parameters Parameters for the template
254
-	 * @return bool
255
-	 */
256
-	public static function printAdminPage( $application, $name, $parameters = [] ) {
257
-		$content = new OC_Template( $application, $name, "admin" );
258
-		foreach( $parameters as $key => $value ) {
259
-			$content->assign( $key, $value );
260
-		}
261
-		return $content->printPage();
262
-	}
263
-
264
-	/**
265
-	 * Shortcut to print a simple page for guests
266
-	 * @param string $application The application we render the template for
267
-	 * @param string $name Name of the template
268
-	 * @param array|string $parameters Parameters for the template
269
-	 * @return bool
270
-	 */
271
-	public static function printGuestPage( $application, $name, $parameters = [] ) {
272
-		$content = new OC_Template($application, $name, $name === 'error' ? $name : 'guest');
273
-		foreach( $parameters as $key => $value ) {
274
-			$content->assign( $key, $value );
275
-		}
276
-		return $content->printPage();
277
-	}
278
-
279
-	/**
280
-	 * Print a fatal error page and terminates the script
281
-	 * @param string $error_msg The error message to show
282
-	 * @param string $hint An optional hint message - needs to be properly escape
283
-	 * @param int $statusCode
284
-	 * @suppress PhanAccessMethodInternal
285
-	 */
286
-	public static function printErrorPage( $error_msg, $hint = '', $statusCode = 500) {
287
-		if (\OC::$server->getAppManager()->isEnabledForUser('theming') && !\OC_App::isAppLoaded('theming')) {
288
-			\OC_App::loadApp('theming');
289
-		}
290
-
291
-
292
-		if ($error_msg === $hint) {
293
-			// If the hint is the same as the message there is no need to display it twice.
294
-			$hint = '';
295
-		}
296
-
297
-		http_response_code($statusCode);
298
-		try {
299
-			$content = new \OC_Template( '', 'error', 'error', false );
300
-			$errors = [['error' => $error_msg, 'hint' => $hint]];
301
-			$content->assign( 'errors', $errors );
302
-			$content->printPage();
303
-		} catch (\Exception $e) {
304
-			$logger = \OC::$server->getLogger();
305
-			$logger->error("$error_msg $hint", ['app' => 'core']);
306
-			$logger->logException($e, ['app' => 'core']);
307
-
308
-			header('Content-Type: text/plain; charset=utf-8');
309
-			print("$error_msg $hint");
310
-		}
311
-		die();
312
-	}
313
-
314
-	/**
315
-	 * print error page using Exception details
316
-	 * @param Exception|Throwable $exception
317
-	 * @param int $statusCode
318
-	 * @return bool|string
319
-	 * @suppress PhanAccessMethodInternal
320
-	 */
321
-	public static function printExceptionErrorPage($exception, $statusCode = 503) {
322
-		http_response_code($statusCode);
323
-		try {
324
-			$request = \OC::$server->getRequest();
325
-			$content = new \OC_Template('', 'exception', 'error', false);
326
-			$content->assign('errorClass', get_class($exception));
327
-			$content->assign('errorMsg', $exception->getMessage());
328
-			$content->assign('errorCode', $exception->getCode());
329
-			$content->assign('file', $exception->getFile());
330
-			$content->assign('line', $exception->getLine());
331
-			$content->assign('trace', $exception->getTraceAsString());
332
-			$content->assign('debugMode', \OC::$server->getSystemConfig()->getValue('debug', false));
333
-			$content->assign('remoteAddr', $request->getRemoteAddress());
334
-			$content->assign('requestID', $request->getId());
335
-			$content->printPage();
336
-		} catch (\Exception $e) {
337
-			try {
338
-				$logger = \OC::$server->getLogger();
339
-				$logger->logException($exception, ['app' => 'core']);
340
-				$logger->logException($e, ['app' => 'core']);
341
-			} catch (Throwable $e) {
342
-				// no way to log it properly - but to avoid a white page of death we send some output
343
-				header('Content-Type: text/plain; charset=utf-8');
344
-				print("Internal Server Error\n\n");
345
-				print("The server encountered an internal error and was unable to complete your request.\n");
346
-				print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
347
-				print("More details can be found in the server log.\n");
348
-
349
-				// and then throw it again to log it at least to the web server error log
350
-				throw $e;
351
-			}
352
-
353
-			header('Content-Type: text/plain; charset=utf-8');
354
-			print("Internal Server Error\n\n");
355
-			print("The server encountered an internal error and was unable to complete your request.\n");
356
-			print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
357
-			print("More details can be found in the server log.\n");
358
-		}
359
-		die();
360
-	}
50
+    /** @var string */
51
+    private $renderAs; // Create a full page?
52
+
53
+    /** @var string */
54
+    private $path; // The path to the template
55
+
56
+    /** @var array */
57
+    private $headers = []; //custom headers
58
+
59
+    /** @var string */
60
+    protected $app; // app id
61
+
62
+    protected static $initTemplateEngineFirstRun = true;
63
+
64
+    /**
65
+     * Constructor
66
+     *
67
+     * @param string $app app providing the template
68
+     * @param string $name of the template file (without suffix)
69
+     * @param string $renderAs If $renderAs is set, OC_Template will try to
70
+     *                         produce a full page in the according layout. For
71
+     *                         now, $renderAs can be set to "guest", "user" or
72
+     *                         "admin".
73
+     * @param bool $registerCall = true
74
+     */
75
+    public function __construct( $app, $name, $renderAs = "", $registerCall = true ) {
76
+        // Read the selected theme from the config file
77
+        self::initTemplateEngine($renderAs);
78
+
79
+        $theme = OC_Util::getTheme();
80
+
81
+        $requestToken = (OC::$server->getSession() && $registerCall) ? \OCP\Util::callRegister() : '';
82
+
83
+        $parts = explode('/', $app); // fix translation when app is something like core/lostpassword
84
+        $l10n = \OC::$server->getL10N($parts[0]);
85
+        /** @var \OCP\Defaults $themeDefaults */
86
+        $themeDefaults = \OC::$server->query(\OCP\Defaults::class);
87
+
88
+        list($path, $template) = $this->findTemplate($theme, $app, $name);
89
+
90
+        // Set the private data
91
+        $this->renderAs = $renderAs;
92
+        $this->path = $path;
93
+        $this->app = $app;
94
+
95
+        parent::__construct($template, $requestToken, $l10n, $themeDefaults);
96
+    }
97
+
98
+    /**
99
+     * @param string $renderAs
100
+     */
101
+    public static function initTemplateEngine($renderAs) {
102
+        if (self::$initTemplateEngineFirstRun){
103
+
104
+            //apps that started before the template initialization can load their own scripts/styles
105
+            //so to make sure this scripts/styles here are loaded first we use OC_Util::addScript() with $prepend=true
106
+            //meaning the last script/style in this list will be loaded first
107
+            if (\OC::$server->getSystemConfig()->getValue ('installed', false) && $renderAs !== 'error' && !\OCP\Util::needUpgrade()) {
108
+                if (\OC::$server->getConfig ()->getAppValue ( 'core', 'backgroundjobs_mode', 'ajax' ) == 'ajax') {
109
+                    OC_Util::addScript ( 'backgroundjobs', null, true );
110
+                }
111
+            }
112
+            OC_Util::addStyle('css-variables', null, true);
113
+            OC_Util::addStyle('server', null, true);
114
+            OC_Util::addTranslations('core', null, true);
115
+
116
+            if (\OC::$server->getSystemConfig()->getValue ('installed', false)) {
117
+                OC_Util::addStyle('search', 'results');
118
+                OC_Util::addScript('search', 'search', true);
119
+                OC_Util::addScript('search', 'searchprovider');
120
+                OC_Util::addScript('merged-template-prepend', null, true);
121
+                OC_Util::addScript('files/fileinfo');
122
+                OC_Util::addScript('files/client');
123
+            }
124
+            OC_Util::addScript('core', 'dist/main', true);
125
+
126
+            if (\OC::$server->getRequest()->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_IE])) {
127
+                // shim for the davclient.js library
128
+                \OCP\Util::addScript('files/iedavclient');
129
+            }
130
+
131
+            self::$initTemplateEngineFirstRun = false;
132
+        }
133
+
134
+    }
135
+
136
+
137
+    /**
138
+     * find the template with the given name
139
+     * @param string $name of the template file (without suffix)
140
+     *
141
+     * Will select the template file for the selected theme.
142
+     * Checking all the possible locations.
143
+     * @param string $theme
144
+     * @param string $app
145
+     * @return string[]
146
+     */
147
+    protected function findTemplate($theme, $app, $name) {
148
+        // Check if it is a app template or not.
149
+        if( $app !== '' ) {
150
+            $dirs = $this->getAppTemplateDirs($theme, $app, OC::$SERVERROOT, OC_App::getAppPath($app));
151
+        } else {
152
+            $dirs = $this->getCoreTemplateDirs($theme, OC::$SERVERROOT);
153
+        }
154
+        $locator = new \OC\Template\TemplateFileLocator( $dirs );
155
+        $template = $locator->find($name);
156
+        $path = $locator->getPath();
157
+        return [$path, $template];
158
+    }
159
+
160
+    /**
161
+     * Add a custom element to the header
162
+     * @param string $tag tag name of the element
163
+     * @param array $attributes array of attributes for the element
164
+     * @param string $text the text content for the element. If $text is null then the
165
+     * element will be written as empty element. So use "" to get a closing tag.
166
+     */
167
+    public function addHeader($tag, $attributes, $text=null) {
168
+        $this->headers[]= [
169
+            'tag' => $tag,
170
+            'attributes' => $attributes,
171
+            'text' => $text
172
+        ];
173
+    }
174
+
175
+    /**
176
+     * Process the template
177
+     * @return boolean|string
178
+     *
179
+     * This function process the template. If $this->renderAs is set, it
180
+     * will produce a full page.
181
+     */
182
+    public function fetchPage($additionalParams = null) {
183
+        $data = parent::fetchPage($additionalParams);
184
+
185
+        if( $this->renderAs ) {
186
+            $page = new TemplateLayout($this->renderAs, $this->app);
187
+
188
+            if(is_array($additionalParams)) {
189
+                foreach ($additionalParams as $key => $value) {
190
+                    $page->assign($key, $value);
191
+                }
192
+            }
193
+
194
+            // Add custom headers
195
+            $headers = '';
196
+            foreach(OC_Util::$headers as $header) {
197
+                $headers .= '<'.\OCP\Util::sanitizeHTML($header['tag']);
198
+                if ( strcasecmp($header['tag'], 'script') === 0 && in_array('src', array_map('strtolower', array_keys($header['attributes']))) ) {
199
+                    $headers .= ' defer';
200
+                }
201
+                foreach($header['attributes'] as $name=>$value) {
202
+                    $headers .= ' '.\OCP\Util::sanitizeHTML($name).'="'.\OCP\Util::sanitizeHTML($value).'"';
203
+                }
204
+                if ($header['text'] !== null) {
205
+                    $headers .= '>'.\OCP\Util::sanitizeHTML($header['text']).'</'.\OCP\Util::sanitizeHTML($header['tag']).'>';
206
+                } else {
207
+                    $headers .= '/>';
208
+                }
209
+            }
210
+
211
+            $page->assign('headers', $headers);
212
+
213
+            $page->assign('content', $data);
214
+            return $page->fetchPage($additionalParams);
215
+        }
216
+
217
+        return $data;
218
+    }
219
+
220
+    /**
221
+     * Include template
222
+     *
223
+     * @param string $file
224
+     * @param array|null $additionalParams
225
+     * @return string returns content of included template
226
+     *
227
+     * Includes another template. use <?php echo $this->inc('template'); ?> to
228
+     * do this.
229
+     */
230
+    public function inc( $file, $additionalParams = null ) {
231
+        return $this->load($this->path.$file.'.php', $additionalParams);
232
+    }
233
+
234
+    /**
235
+     * Shortcut to print a simple page for users
236
+     * @param string $application The application we render the template for
237
+     * @param string $name Name of the template
238
+     * @param array $parameters Parameters for the template
239
+     * @return boolean|null
240
+     */
241
+    public static function printUserPage( $application, $name, $parameters = [] ) {
242
+        $content = new OC_Template( $application, $name, "user" );
243
+        foreach( $parameters as $key => $value ) {
244
+            $content->assign( $key, $value );
245
+        }
246
+        print $content->printPage();
247
+    }
248
+
249
+    /**
250
+     * Shortcut to print a simple page for admins
251
+     * @param string $application The application we render the template for
252
+     * @param string $name Name of the template
253
+     * @param array $parameters Parameters for the template
254
+     * @return bool
255
+     */
256
+    public static function printAdminPage( $application, $name, $parameters = [] ) {
257
+        $content = new OC_Template( $application, $name, "admin" );
258
+        foreach( $parameters as $key => $value ) {
259
+            $content->assign( $key, $value );
260
+        }
261
+        return $content->printPage();
262
+    }
263
+
264
+    /**
265
+     * Shortcut to print a simple page for guests
266
+     * @param string $application The application we render the template for
267
+     * @param string $name Name of the template
268
+     * @param array|string $parameters Parameters for the template
269
+     * @return bool
270
+     */
271
+    public static function printGuestPage( $application, $name, $parameters = [] ) {
272
+        $content = new OC_Template($application, $name, $name === 'error' ? $name : 'guest');
273
+        foreach( $parameters as $key => $value ) {
274
+            $content->assign( $key, $value );
275
+        }
276
+        return $content->printPage();
277
+    }
278
+
279
+    /**
280
+     * Print a fatal error page and terminates the script
281
+     * @param string $error_msg The error message to show
282
+     * @param string $hint An optional hint message - needs to be properly escape
283
+     * @param int $statusCode
284
+     * @suppress PhanAccessMethodInternal
285
+     */
286
+    public static function printErrorPage( $error_msg, $hint = '', $statusCode = 500) {
287
+        if (\OC::$server->getAppManager()->isEnabledForUser('theming') && !\OC_App::isAppLoaded('theming')) {
288
+            \OC_App::loadApp('theming');
289
+        }
290
+
291
+
292
+        if ($error_msg === $hint) {
293
+            // If the hint is the same as the message there is no need to display it twice.
294
+            $hint = '';
295
+        }
296
+
297
+        http_response_code($statusCode);
298
+        try {
299
+            $content = new \OC_Template( '', 'error', 'error', false );
300
+            $errors = [['error' => $error_msg, 'hint' => $hint]];
301
+            $content->assign( 'errors', $errors );
302
+            $content->printPage();
303
+        } catch (\Exception $e) {
304
+            $logger = \OC::$server->getLogger();
305
+            $logger->error("$error_msg $hint", ['app' => 'core']);
306
+            $logger->logException($e, ['app' => 'core']);
307
+
308
+            header('Content-Type: text/plain; charset=utf-8');
309
+            print("$error_msg $hint");
310
+        }
311
+        die();
312
+    }
313
+
314
+    /**
315
+     * print error page using Exception details
316
+     * @param Exception|Throwable $exception
317
+     * @param int $statusCode
318
+     * @return bool|string
319
+     * @suppress PhanAccessMethodInternal
320
+     */
321
+    public static function printExceptionErrorPage($exception, $statusCode = 503) {
322
+        http_response_code($statusCode);
323
+        try {
324
+            $request = \OC::$server->getRequest();
325
+            $content = new \OC_Template('', 'exception', 'error', false);
326
+            $content->assign('errorClass', get_class($exception));
327
+            $content->assign('errorMsg', $exception->getMessage());
328
+            $content->assign('errorCode', $exception->getCode());
329
+            $content->assign('file', $exception->getFile());
330
+            $content->assign('line', $exception->getLine());
331
+            $content->assign('trace', $exception->getTraceAsString());
332
+            $content->assign('debugMode', \OC::$server->getSystemConfig()->getValue('debug', false));
333
+            $content->assign('remoteAddr', $request->getRemoteAddress());
334
+            $content->assign('requestID', $request->getId());
335
+            $content->printPage();
336
+        } catch (\Exception $e) {
337
+            try {
338
+                $logger = \OC::$server->getLogger();
339
+                $logger->logException($exception, ['app' => 'core']);
340
+                $logger->logException($e, ['app' => 'core']);
341
+            } catch (Throwable $e) {
342
+                // no way to log it properly - but to avoid a white page of death we send some output
343
+                header('Content-Type: text/plain; charset=utf-8');
344
+                print("Internal Server Error\n\n");
345
+                print("The server encountered an internal error and was unable to complete your request.\n");
346
+                print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
347
+                print("More details can be found in the server log.\n");
348
+
349
+                // and then throw it again to log it at least to the web server error log
350
+                throw $e;
351
+            }
352
+
353
+            header('Content-Type: text/plain; charset=utf-8');
354
+            print("Internal Server Error\n\n");
355
+            print("The server encountered an internal error and was unable to complete your request.\n");
356
+            print("Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.\n");
357
+            print("More details can be found in the server log.\n");
358
+        }
359
+        die();
360
+    }
361 361
 }
Please login to merge, or discard this patch.
lib/private/legacy/api.php 1 patch
Indentation   +152 added lines, -152 removed lines patch added patch discarded remove patch
@@ -33,156 +33,156 @@
 block discarded – undo
33 33
 
34 34
 class OC_API {
35 35
 
36
-	/**
37
-	 * api actions
38
-	 */
39
-	protected static $actions = [];
40
-
41
-	/**
42
-	 * respond to a call
43
-	 * @param \OC\OCS\Result $result
44
-	 * @param string $format the format xml|json
45
-	 */
46
-	public static function respond($result, $format='xml') {
47
-		$request = \OC::$server->getRequest();
48
-
49
-		// Send 401 headers if unauthorised
50
-		if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
51
-			// If request comes from JS return dummy auth request
52
-			if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
53
-				header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
54
-			} else {
55
-				header('WWW-Authenticate: Basic realm="Authorisation Required"');
56
-			}
57
-			http_response_code(401);
58
-		}
59
-
60
-		foreach($result->getHeaders() as $name => $value) {
61
-			header($name . ': ' . $value);
62
-		}
63
-
64
-		$meta = $result->getMeta();
65
-		$data = $result->getData();
66
-		if (self::isV2($request)) {
67
-			$statusCode = self::mapStatusCodes($result->getStatusCode());
68
-			if (!is_null($statusCode)) {
69
-				$meta['statuscode'] = $statusCode;
70
-				http_response_code($statusCode);
71
-			}
72
-		}
73
-
74
-		self::setContentType($format);
75
-		$body = self::renderResult($format, $meta, $data);
76
-		echo $body;
77
-	}
78
-
79
-	/**
80
-	 * @param XMLWriter $writer
81
-	 */
82
-	private static function toXML($array, $writer) {
83
-		foreach($array as $k => $v) {
84
-			if ($k[0] === '@') {
85
-				$writer->writeAttribute(substr($k, 1), $v);
86
-				continue;
87
-			} else if (is_numeric($k)) {
88
-				$k = 'element';
89
-			}
90
-			if(is_array($v)) {
91
-				$writer->startElement($k);
92
-				self::toXML($v, $writer);
93
-				$writer->endElement();
94
-			} else {
95
-				$writer->writeElement($k, $v);
96
-			}
97
-		}
98
-	}
99
-
100
-	/**
101
-	 * @return string
102
-	 */
103
-	public static function requestedFormat() {
104
-		$formats = ['json', 'xml'];
105
-
106
-		$format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
107
-		return $format;
108
-	}
109
-
110
-	/**
111
-	 * Based on the requested format the response content type is set
112
-	 * @param string $format
113
-	 */
114
-	public static function setContentType($format = null) {
115
-		$format = is_null($format) ? self::requestedFormat() : $format;
116
-		if ($format === 'xml') {
117
-			header('Content-type: text/xml; charset=UTF-8');
118
-			return;
119
-		}
120
-
121
-		if ($format === 'json') {
122
-			header('Content-Type: application/json; charset=utf-8');
123
-			return;
124
-		}
125
-
126
-		header('Content-Type: application/octet-stream; charset=utf-8');
127
-	}
128
-
129
-	/**
130
-	 * @param \OCP\IRequest $request
131
-	 * @return bool
132
-	 */
133
-	protected static function isV2(\OCP\IRequest $request) {
134
-		$script = $request->getScriptName();
135
-
136
-		return substr($script, -11) === '/ocs/v2.php';
137
-	}
138
-
139
-	/**
140
-	 * @param integer $sc
141
-	 * @return int
142
-	 */
143
-	public static function mapStatusCodes($sc) {
144
-		switch ($sc) {
145
-			case API::RESPOND_NOT_FOUND:
146
-				return Http::STATUS_NOT_FOUND;
147
-			case API::RESPOND_SERVER_ERROR:
148
-				return Http::STATUS_INTERNAL_SERVER_ERROR;
149
-			case API::RESPOND_UNKNOWN_ERROR:
150
-				return Http::STATUS_INTERNAL_SERVER_ERROR;
151
-			case API::RESPOND_UNAUTHORISED:
152
-				// already handled for v1
153
-				return null;
154
-			case 100:
155
-				return Http::STATUS_OK;
156
-		}
157
-		// any 2xx, 4xx and 5xx will be used as is
158
-		if ($sc >= 200 && $sc < 600) {
159
-			return $sc;
160
-		}
161
-
162
-		return Http::STATUS_BAD_REQUEST;
163
-	}
164
-
165
-	/**
166
-	 * @param string $format
167
-	 * @return string
168
-	 */
169
-	public static function renderResult($format, $meta, $data) {
170
-		$response = [
171
-			'ocs' => [
172
-				'meta' => $meta,
173
-				'data' => $data,
174
-			],
175
-		];
176
-		if ($format == 'json') {
177
-			return OC_JSON::encode($response);
178
-		}
179
-
180
-		$writer = new XMLWriter();
181
-		$writer->openMemory();
182
-		$writer->setIndent(true);
183
-		$writer->startDocument();
184
-		self::toXML($response, $writer);
185
-		$writer->endDocument();
186
-		return $writer->outputMemory(true);
187
-	}
36
+    /**
37
+     * api actions
38
+     */
39
+    protected static $actions = [];
40
+
41
+    /**
42
+     * respond to a call
43
+     * @param \OC\OCS\Result $result
44
+     * @param string $format the format xml|json
45
+     */
46
+    public static function respond($result, $format='xml') {
47
+        $request = \OC::$server->getRequest();
48
+
49
+        // Send 401 headers if unauthorised
50
+        if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
51
+            // If request comes from JS return dummy auth request
52
+            if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
53
+                header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
54
+            } else {
55
+                header('WWW-Authenticate: Basic realm="Authorisation Required"');
56
+            }
57
+            http_response_code(401);
58
+        }
59
+
60
+        foreach($result->getHeaders() as $name => $value) {
61
+            header($name . ': ' . $value);
62
+        }
63
+
64
+        $meta = $result->getMeta();
65
+        $data = $result->getData();
66
+        if (self::isV2($request)) {
67
+            $statusCode = self::mapStatusCodes($result->getStatusCode());
68
+            if (!is_null($statusCode)) {
69
+                $meta['statuscode'] = $statusCode;
70
+                http_response_code($statusCode);
71
+            }
72
+        }
73
+
74
+        self::setContentType($format);
75
+        $body = self::renderResult($format, $meta, $data);
76
+        echo $body;
77
+    }
78
+
79
+    /**
80
+     * @param XMLWriter $writer
81
+     */
82
+    private static function toXML($array, $writer) {
83
+        foreach($array as $k => $v) {
84
+            if ($k[0] === '@') {
85
+                $writer->writeAttribute(substr($k, 1), $v);
86
+                continue;
87
+            } else if (is_numeric($k)) {
88
+                $k = 'element';
89
+            }
90
+            if(is_array($v)) {
91
+                $writer->startElement($k);
92
+                self::toXML($v, $writer);
93
+                $writer->endElement();
94
+            } else {
95
+                $writer->writeElement($k, $v);
96
+            }
97
+        }
98
+    }
99
+
100
+    /**
101
+     * @return string
102
+     */
103
+    public static function requestedFormat() {
104
+        $formats = ['json', 'xml'];
105
+
106
+        $format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
107
+        return $format;
108
+    }
109
+
110
+    /**
111
+     * Based on the requested format the response content type is set
112
+     * @param string $format
113
+     */
114
+    public static function setContentType($format = null) {
115
+        $format = is_null($format) ? self::requestedFormat() : $format;
116
+        if ($format === 'xml') {
117
+            header('Content-type: text/xml; charset=UTF-8');
118
+            return;
119
+        }
120
+
121
+        if ($format === 'json') {
122
+            header('Content-Type: application/json; charset=utf-8');
123
+            return;
124
+        }
125
+
126
+        header('Content-Type: application/octet-stream; charset=utf-8');
127
+    }
128
+
129
+    /**
130
+     * @param \OCP\IRequest $request
131
+     * @return bool
132
+     */
133
+    protected static function isV2(\OCP\IRequest $request) {
134
+        $script = $request->getScriptName();
135
+
136
+        return substr($script, -11) === '/ocs/v2.php';
137
+    }
138
+
139
+    /**
140
+     * @param integer $sc
141
+     * @return int
142
+     */
143
+    public static function mapStatusCodes($sc) {
144
+        switch ($sc) {
145
+            case API::RESPOND_NOT_FOUND:
146
+                return Http::STATUS_NOT_FOUND;
147
+            case API::RESPOND_SERVER_ERROR:
148
+                return Http::STATUS_INTERNAL_SERVER_ERROR;
149
+            case API::RESPOND_UNKNOWN_ERROR:
150
+                return Http::STATUS_INTERNAL_SERVER_ERROR;
151
+            case API::RESPOND_UNAUTHORISED:
152
+                // already handled for v1
153
+                return null;
154
+            case 100:
155
+                return Http::STATUS_OK;
156
+        }
157
+        // any 2xx, 4xx and 5xx will be used as is
158
+        if ($sc >= 200 && $sc < 600) {
159
+            return $sc;
160
+        }
161
+
162
+        return Http::STATUS_BAD_REQUEST;
163
+    }
164
+
165
+    /**
166
+     * @param string $format
167
+     * @return string
168
+     */
169
+    public static function renderResult($format, $meta, $data) {
170
+        $response = [
171
+            'ocs' => [
172
+                'meta' => $meta,
173
+                'data' => $data,
174
+            ],
175
+        ];
176
+        if ($format == 'json') {
177
+            return OC_JSON::encode($response);
178
+        }
179
+
180
+        $writer = new XMLWriter();
181
+        $writer->openMemory();
182
+        $writer->setIndent(true);
183
+        $writer->startDocument();
184
+        self::toXML($response, $writer);
185
+        $writer->endDocument();
186
+        return $writer->outputMemory(true);
187
+    }
188 188
 }
Please login to merge, or discard this patch.
lib/private/URLGenerator.php 1 patch
Indentation   +194 added lines, -194 removed lines patch added patch discarded remove patch
@@ -49,224 +49,224 @@
 block discarded – undo
49 49
  * Class to generate URLs
50 50
  */
51 51
 class URLGenerator implements IURLGenerator {
52
-	/** @var IConfig */
53
-	private $config;
54
-	/** @var ICacheFactory */
55
-	private $cacheFactory;
56
-	/** @var IRequest */
57
-	private $request;
52
+    /** @var IConfig */
53
+    private $config;
54
+    /** @var ICacheFactory */
55
+    private $cacheFactory;
56
+    /** @var IRequest */
57
+    private $request;
58 58
 
59
-	/**
60
-	 * @param IConfig $config
61
-	 * @param ICacheFactory $cacheFactory
62
-	 * @param IRequest $request
63
-	 */
64
-	public function __construct(IConfig $config,
65
-								ICacheFactory $cacheFactory,
66
-								IRequest $request) {
67
-		$this->config = $config;
68
-		$this->cacheFactory = $cacheFactory;
69
-		$this->request = $request;
70
-	}
59
+    /**
60
+     * @param IConfig $config
61
+     * @param ICacheFactory $cacheFactory
62
+     * @param IRequest $request
63
+     */
64
+    public function __construct(IConfig $config,
65
+                                ICacheFactory $cacheFactory,
66
+                                IRequest $request) {
67
+        $this->config = $config;
68
+        $this->cacheFactory = $cacheFactory;
69
+        $this->request = $request;
70
+    }
71 71
 
72
-	/**
73
-	 * Creates an url using a defined route
74
-	 * @param string $route
75
-	 * @param array $parameters args with param=>value, will be appended to the returned url
76
-	 * @return string the url
77
-	 *
78
-	 * Returns a url to the given route.
79
-	 */
80
-	public function linkToRoute(string $route, array $parameters = []): string {
81
-		// TODO: mock router
82
-		return \OC::$server->getRouter()->generate($route, $parameters);
83
-	}
72
+    /**
73
+     * Creates an url using a defined route
74
+     * @param string $route
75
+     * @param array $parameters args with param=>value, will be appended to the returned url
76
+     * @return string the url
77
+     *
78
+     * Returns a url to the given route.
79
+     */
80
+    public function linkToRoute(string $route, array $parameters = []): string {
81
+        // TODO: mock router
82
+        return \OC::$server->getRouter()->generate($route, $parameters);
83
+    }
84 84
 
85
-	/**
86
-	 * Creates an absolute url using a defined route
87
-	 * @param string $routeName
88
-	 * @param array $arguments args with param=>value, will be appended to the returned url
89
-	 * @return string the url
90
-	 *
91
-	 * Returns an absolute url to the given route.
92
-	 */
93
-	public function linkToRouteAbsolute(string $routeName, array $arguments = []): string {
94
-		return $this->getAbsoluteURL($this->linkToRoute($routeName, $arguments));
95
-	}
85
+    /**
86
+     * Creates an absolute url using a defined route
87
+     * @param string $routeName
88
+     * @param array $arguments args with param=>value, will be appended to the returned url
89
+     * @return string the url
90
+     *
91
+     * Returns an absolute url to the given route.
92
+     */
93
+    public function linkToRouteAbsolute(string $routeName, array $arguments = []): string {
94
+        return $this->getAbsoluteURL($this->linkToRoute($routeName, $arguments));
95
+    }
96 96
 
97
-	public function linkToOCSRouteAbsolute(string $routeName, array $arguments = []): string {
98
-		$route = \OC::$server->getRouter()->generate('ocs.'.$routeName, $arguments, false);
97
+    public function linkToOCSRouteAbsolute(string $routeName, array $arguments = []): string {
98
+        $route = \OC::$server->getRouter()->generate('ocs.'.$routeName, $arguments, false);
99 99
 
100
-		$indexPhpPos = strpos($route, '/index.php/');
101
-		if ($indexPhpPos !== false) {
102
-			$route = substr($route, $indexPhpPos + 10);
103
-		}
100
+        $indexPhpPos = strpos($route, '/index.php/');
101
+        if ($indexPhpPos !== false) {
102
+            $route = substr($route, $indexPhpPos + 10);
103
+        }
104 104
 
105
-		$route = substr($route, 7);
106
-		$route = '/ocs/v2.php' . $route;
105
+        $route = substr($route, 7);
106
+        $route = '/ocs/v2.php' . $route;
107 107
 
108
-		return $this->getAbsoluteURL($route);
109
-	}
108
+        return $this->getAbsoluteURL($route);
109
+    }
110 110
 
111
-	/**
112
-	 * Creates an url
113
-	 * @param string $app app
114
-	 * @param string $file file
115
-	 * @param array $args array with param=>value, will be appended to the returned url
116
-	 *    The value of $args will be urlencoded
117
-	 * @return string the url
118
-	 *
119
-	 * Returns a url to the given app and file.
120
-	 */
121
-	public function linkTo(string $app, string $file, array $args = []): string {
122
-		$frontControllerActive = ($this->config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true');
111
+    /**
112
+     * Creates an url
113
+     * @param string $app app
114
+     * @param string $file file
115
+     * @param array $args array with param=>value, will be appended to the returned url
116
+     *    The value of $args will be urlencoded
117
+     * @return string the url
118
+     *
119
+     * Returns a url to the given app and file.
120
+     */
121
+    public function linkTo(string $app, string $file, array $args = []): string {
122
+        $frontControllerActive = ($this->config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true');
123 123
 
124
-		if( $app !== '' ) {
125
-			$app_path = \OC_App::getAppPath($app);
126
-			// Check if the app is in the app folder
127
-			if ($app_path && file_exists($app_path . '/' . $file)) {
128
-				if (substr($file, -3) === 'php') {
124
+        if( $app !== '' ) {
125
+            $app_path = \OC_App::getAppPath($app);
126
+            // Check if the app is in the app folder
127
+            if ($app_path && file_exists($app_path . '/' . $file)) {
128
+                if (substr($file, -3) === 'php') {
129 129
 
130
-					$urlLinkTo = \OC::$WEBROOT . '/index.php/apps/' . $app;
131
-					if ($frontControllerActive) {
132
-						$urlLinkTo = \OC::$WEBROOT . '/apps/' . $app;
133
-					}
134
-					$urlLinkTo .= ($file !== 'index.php') ? '/' . $file : '';
135
-				} else {
136
-					$urlLinkTo = \OC_App::getAppWebPath($app) . '/' . $file;
137
-				}
138
-			} else {
139
-				$urlLinkTo = \OC::$WEBROOT . '/' . $app . '/' . $file;
140
-			}
141
-		} else {
142
-			if (file_exists(\OC::$SERVERROOT . '/core/' . $file)) {
143
-				$urlLinkTo = \OC::$WEBROOT . '/core/' . $file;
144
-			} else {
145
-				if ($frontControllerActive && $file === 'index.php') {
146
-					$urlLinkTo = \OC::$WEBROOT . '/';
147
-				} else {
148
-					$urlLinkTo = \OC::$WEBROOT . '/' . $file;
149
-				}
150
-			}
151
-		}
130
+                    $urlLinkTo = \OC::$WEBROOT . '/index.php/apps/' . $app;
131
+                    if ($frontControllerActive) {
132
+                        $urlLinkTo = \OC::$WEBROOT . '/apps/' . $app;
133
+                    }
134
+                    $urlLinkTo .= ($file !== 'index.php') ? '/' . $file : '';
135
+                } else {
136
+                    $urlLinkTo = \OC_App::getAppWebPath($app) . '/' . $file;
137
+                }
138
+            } else {
139
+                $urlLinkTo = \OC::$WEBROOT . '/' . $app . '/' . $file;
140
+            }
141
+        } else {
142
+            if (file_exists(\OC::$SERVERROOT . '/core/' . $file)) {
143
+                $urlLinkTo = \OC::$WEBROOT . '/core/' . $file;
144
+            } else {
145
+                if ($frontControllerActive && $file === 'index.php') {
146
+                    $urlLinkTo = \OC::$WEBROOT . '/';
147
+                } else {
148
+                    $urlLinkTo = \OC::$WEBROOT . '/' . $file;
149
+                }
150
+            }
151
+        }
152 152
 
153
-		if ($args && $query = http_build_query($args, '', '&')) {
154
-			$urlLinkTo .= '?' . $query;
155
-		}
153
+        if ($args && $query = http_build_query($args, '', '&')) {
154
+            $urlLinkTo .= '?' . $query;
155
+        }
156 156
 
157
-		return $urlLinkTo;
158
-	}
157
+        return $urlLinkTo;
158
+    }
159 159
 
160
-	/**
161
-	 * Creates path to an image
162
-	 * @param string $app app
163
-	 * @param string $image image name
164
-	 * @throws \RuntimeException If the image does not exist
165
-	 * @return string the url
166
-	 *
167
-	 * Returns the path to the image.
168
-	 */
169
-	public function imagePath(string $app, string $image): string {
170
-		$cache = $this->cacheFactory->createDistributed('imagePath-'.md5($this->getBaseUrl()).'-');
171
-		$cacheKey = $app.'-'.$image;
172
-		if($key = $cache->get($cacheKey)) {
173
-			return $key;
174
-		}
160
+    /**
161
+     * Creates path to an image
162
+     * @param string $app app
163
+     * @param string $image image name
164
+     * @throws \RuntimeException If the image does not exist
165
+     * @return string the url
166
+     *
167
+     * Returns the path to the image.
168
+     */
169
+    public function imagePath(string $app, string $image): string {
170
+        $cache = $this->cacheFactory->createDistributed('imagePath-'.md5($this->getBaseUrl()).'-');
171
+        $cacheKey = $app.'-'.$image;
172
+        if($key = $cache->get($cacheKey)) {
173
+            return $key;
174
+        }
175 175
 
176
-		// Read the selected theme from the config file
177
-		$theme = \OC_Util::getTheme();
176
+        // Read the selected theme from the config file
177
+        $theme = \OC_Util::getTheme();
178 178
 
179
-		//if a theme has a png but not an svg always use the png
180
-		$basename = substr(basename($image),0,-4);
179
+        //if a theme has a png but not an svg always use the png
180
+        $basename = substr(basename($image),0,-4);
181 181
 
182
-		$appPath = \OC_App::getAppPath($app);
182
+        $appPath = \OC_App::getAppPath($app);
183 183
 
184
-		// Check if the app is in the app folder
185
-		$path = '';
186
-		$themingEnabled = $this->config->getSystemValue('installed', false) && \OCP\App::isEnabled('theming') && \OC_App::isAppLoaded('theming');
187
-		$themingImagePath = false;
188
-		if($themingEnabled) {
189
-			$themingDefaults = \OC::$server->getThemingDefaults();
190
-			if ($themingDefaults instanceof ThemingDefaults) {
191
-				$themingImagePath = $themingDefaults->replaceImagePath($app, $image);
192
-			}
193
-		}
184
+        // Check if the app is in the app folder
185
+        $path = '';
186
+        $themingEnabled = $this->config->getSystemValue('installed', false) && \OCP\App::isEnabled('theming') && \OC_App::isAppLoaded('theming');
187
+        $themingImagePath = false;
188
+        if($themingEnabled) {
189
+            $themingDefaults = \OC::$server->getThemingDefaults();
190
+            if ($themingDefaults instanceof ThemingDefaults) {
191
+                $themingImagePath = $themingDefaults->replaceImagePath($app, $image);
192
+            }
193
+        }
194 194
 
195
-		if (file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$app/img/$image")) {
196
-			$path = \OC::$WEBROOT . "/themes/$theme/apps/$app/img/$image";
197
-		} elseif (!file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$app/img/$basename.svg")
198
-			&& file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$app/img/$basename.png")) {
199
-			$path =  \OC::$WEBROOT . "/themes/$theme/apps/$app/img/$basename.png";
200
-		} elseif (!empty($app) and file_exists(\OC::$SERVERROOT . "/themes/$theme/$app/img/$image")) {
201
-			$path =  \OC::$WEBROOT . "/themes/$theme/$app/img/$image";
202
-		} elseif (!empty($app) and (!file_exists(\OC::$SERVERROOT . "/themes/$theme/$app/img/$basename.svg")
203
-			&& file_exists(\OC::$SERVERROOT . "/themes/$theme/$app/img/$basename.png"))) {
204
-			$path =  \OC::$WEBROOT . "/themes/$theme/$app/img/$basename.png";
205
-		} elseif (file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$image")) {
206
-			$path =  \OC::$WEBROOT . "/themes/$theme/core/img/$image";
207
-		} elseif (!file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.svg")
208
-			&& file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.png")) {
209
-			$path =  \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png";
210
-		} elseif($themingEnabled && $themingImagePath) {
211
-			$path = $themingImagePath;
212
-		} elseif ($appPath && file_exists($appPath . "/img/$image")) {
213
-			$path =  \OC_App::getAppWebPath($app) . "/img/$image";
214
-		} elseif ($appPath && !file_exists($appPath . "/img/$basename.svg")
215
-			&& file_exists($appPath . "/img/$basename.png")) {
216
-			$path =  \OC_App::getAppWebPath($app) . "/img/$basename.png";
217
-		} elseif (!empty($app) and file_exists(\OC::$SERVERROOT . "/$app/img/$image")) {
218
-			$path =  \OC::$WEBROOT . "/$app/img/$image";
219
-		} elseif (!empty($app) and (!file_exists(\OC::$SERVERROOT . "/$app/img/$basename.svg")
220
-				&& file_exists(\OC::$SERVERROOT . "/$app/img/$basename.png"))) {
221
-			$path =  \OC::$WEBROOT . "/$app/img/$basename.png";
222
-		} elseif (file_exists(\OC::$SERVERROOT . "/core/img/$image")) {
223
-			$path =  \OC::$WEBROOT . "/core/img/$image";
224
-		} elseif (!file_exists(\OC::$SERVERROOT . "/core/img/$basename.svg")
225
-			&& file_exists(\OC::$SERVERROOT . "/core/img/$basename.png")) {
226
-			$path =  \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png";
227
-		}
195
+        if (file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$app/img/$image")) {
196
+            $path = \OC::$WEBROOT . "/themes/$theme/apps/$app/img/$image";
197
+        } elseif (!file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$app/img/$basename.svg")
198
+            && file_exists(\OC::$SERVERROOT . "/themes/$theme/apps/$app/img/$basename.png")) {
199
+            $path =  \OC::$WEBROOT . "/themes/$theme/apps/$app/img/$basename.png";
200
+        } elseif (!empty($app) and file_exists(\OC::$SERVERROOT . "/themes/$theme/$app/img/$image")) {
201
+            $path =  \OC::$WEBROOT . "/themes/$theme/$app/img/$image";
202
+        } elseif (!empty($app) and (!file_exists(\OC::$SERVERROOT . "/themes/$theme/$app/img/$basename.svg")
203
+            && file_exists(\OC::$SERVERROOT . "/themes/$theme/$app/img/$basename.png"))) {
204
+            $path =  \OC::$WEBROOT . "/themes/$theme/$app/img/$basename.png";
205
+        } elseif (file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$image")) {
206
+            $path =  \OC::$WEBROOT . "/themes/$theme/core/img/$image";
207
+        } elseif (!file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.svg")
208
+            && file_exists(\OC::$SERVERROOT . "/themes/$theme/core/img/$basename.png")) {
209
+            $path =  \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png";
210
+        } elseif($themingEnabled && $themingImagePath) {
211
+            $path = $themingImagePath;
212
+        } elseif ($appPath && file_exists($appPath . "/img/$image")) {
213
+            $path =  \OC_App::getAppWebPath($app) . "/img/$image";
214
+        } elseif ($appPath && !file_exists($appPath . "/img/$basename.svg")
215
+            && file_exists($appPath . "/img/$basename.png")) {
216
+            $path =  \OC_App::getAppWebPath($app) . "/img/$basename.png";
217
+        } elseif (!empty($app) and file_exists(\OC::$SERVERROOT . "/$app/img/$image")) {
218
+            $path =  \OC::$WEBROOT . "/$app/img/$image";
219
+        } elseif (!empty($app) and (!file_exists(\OC::$SERVERROOT . "/$app/img/$basename.svg")
220
+                && file_exists(\OC::$SERVERROOT . "/$app/img/$basename.png"))) {
221
+            $path =  \OC::$WEBROOT . "/$app/img/$basename.png";
222
+        } elseif (file_exists(\OC::$SERVERROOT . "/core/img/$image")) {
223
+            $path =  \OC::$WEBROOT . "/core/img/$image";
224
+        } elseif (!file_exists(\OC::$SERVERROOT . "/core/img/$basename.svg")
225
+            && file_exists(\OC::$SERVERROOT . "/core/img/$basename.png")) {
226
+            $path =  \OC::$WEBROOT . "/themes/$theme/core/img/$basename.png";
227
+        }
228 228
 
229
-		if($path !== '') {
230
-			$cache->set($cacheKey, $path);
231
-			return $path;
232
-		}
229
+        if($path !== '') {
230
+            $cache->set($cacheKey, $path);
231
+            return $path;
232
+        }
233 233
 
234
-		throw new RuntimeException('image not found: image:' . $image . ' webroot:' . \OC::$WEBROOT . ' serverroot:' . \OC::$SERVERROOT);
235
-	}
234
+        throw new RuntimeException('image not found: image:' . $image . ' webroot:' . \OC::$WEBROOT . ' serverroot:' . \OC::$SERVERROOT);
235
+    }
236 236
 
237 237
 
238
-	/**
239
-	 * Makes an URL absolute
240
-	 * @param string $url the url in the ownCloud host
241
-	 * @return string the absolute version of the url
242
-	 */
243
-	public function getAbsoluteURL(string $url): string {
244
-		$separator = strpos($url, '/') === 0 ? '' : '/';
238
+    /**
239
+     * Makes an URL absolute
240
+     * @param string $url the url in the ownCloud host
241
+     * @return string the absolute version of the url
242
+     */
243
+    public function getAbsoluteURL(string $url): string {
244
+        $separator = strpos($url, '/') === 0 ? '' : '/';
245 245
 
246
-		if (\OC::$CLI && !\defined('PHPUNIT_RUN')) {
247
-			return rtrim($this->config->getSystemValue('overwrite.cli.url'), '/') . '/' . ltrim($url, '/');
248
-		}
249
-		// The ownCloud web root can already be prepended.
250
-		if(\OC::$WEBROOT !== '' && strpos($url, \OC::$WEBROOT) === 0) {
251
-			$url = substr($url, \strlen(\OC::$WEBROOT));
252
-		}
246
+        if (\OC::$CLI && !\defined('PHPUNIT_RUN')) {
247
+            return rtrim($this->config->getSystemValue('overwrite.cli.url'), '/') . '/' . ltrim($url, '/');
248
+        }
249
+        // The ownCloud web root can already be prepended.
250
+        if(\OC::$WEBROOT !== '' && strpos($url, \OC::$WEBROOT) === 0) {
251
+            $url = substr($url, \strlen(\OC::$WEBROOT));
252
+        }
253 253
 
254
-		return $this->getBaseUrl() . $separator . $url;
255
-	}
254
+        return $this->getBaseUrl() . $separator . $url;
255
+    }
256 256
 
257
-	/**
258
-	 * @param string $key
259
-	 * @return string url to the online documentation
260
-	 */
261
-	public function linkToDocs(string $key): string {
262
-		$theme = \OC::$server->getThemingDefaults();
263
-		return $theme->buildDocLinkToKey($key);
264
-	}
257
+    /**
258
+     * @param string $key
259
+     * @return string url to the online documentation
260
+     */
261
+    public function linkToDocs(string $key): string {
262
+        $theme = \OC::$server->getThemingDefaults();
263
+        return $theme->buildDocLinkToKey($key);
264
+    }
265 265
 
266
-	/**
267
-	 * @return string base url of the current request
268
-	 */
269
-	public function getBaseUrl(): string {
270
-		return $this->request->getServerProtocol() . '://' . $this->request->getServerHost() . \OC::$WEBROOT;
271
-	}
266
+    /**
267
+     * @return string base url of the current request
268
+     */
269
+    public function getBaseUrl(): string {
270
+        return $this->request->getServerProtocol() . '://' . $this->request->getServerHost() . \OC::$WEBROOT;
271
+    }
272 272
 }
Please login to merge, or discard this patch.
lib/private/Tagging/TagMapper.php 1 patch
Indentation   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -34,46 +34,46 @@
 block discarded – undo
34 34
  */
35 35
 class TagMapper extends Mapper {
36 36
 
37
-	/**
38
-	* Constructor.
39
-	*
40
-	* @param IDBConnection $db Instance of the Db abstraction layer.
41
-	*/
42
-	public function __construct(IDBConnection $db) {
43
-		parent::__construct($db, 'vcategory', Tag::class);
44
-	}
37
+    /**
38
+     * Constructor.
39
+     *
40
+     * @param IDBConnection $db Instance of the Db abstraction layer.
41
+     */
42
+    public function __construct(IDBConnection $db) {
43
+        parent::__construct($db, 'vcategory', Tag::class);
44
+    }
45 45
 
46
-	/**
47
-	* Load tags from the database.
48
-	*
49
-	* @param array|string $owners The user(s) whose tags we are going to load.
50
-	* @param string $type The type of item for which we are loading tags.
51
-	* @return array An array of Tag objects.
52
-	*/
53
-	public function loadTags($owners, $type) {
54
-		if(!is_array($owners)) {
55
-			$owners = [$owners];
56
-		}
46
+    /**
47
+     * Load tags from the database.
48
+     *
49
+     * @param array|string $owners The user(s) whose tags we are going to load.
50
+     * @param string $type The type of item for which we are loading tags.
51
+     * @return array An array of Tag objects.
52
+     */
53
+    public function loadTags($owners, $type) {
54
+        if(!is_array($owners)) {
55
+            $owners = [$owners];
56
+        }
57 57
 
58
-		$sql = 'SELECT `id`, `uid`, `type`, `category` FROM `' . $this->getTableName() . '` '
59
-			. 'WHERE `uid` IN (' . str_repeat('?,', count($owners)-1) . '?) AND `type` = ? ORDER BY `category`';
60
-		return $this->findEntities($sql, array_merge($owners, [$type]));
61
-	}
58
+        $sql = 'SELECT `id`, `uid`, `type`, `category` FROM `' . $this->getTableName() . '` '
59
+            . 'WHERE `uid` IN (' . str_repeat('?,', count($owners)-1) . '?) AND `type` = ? ORDER BY `category`';
60
+        return $this->findEntities($sql, array_merge($owners, [$type]));
61
+    }
62 62
 
63
-	/**
64
-	* Check if a given Tag object already exists in the database.
65
-	*
66
-	* @param Tag $tag The tag to look for in the database.
67
-	* @return bool
68
-	*/
69
-	public function tagExists($tag) {
70
-		$sql = 'SELECT `id`, `uid`, `type`, `category` FROM `' . $this->getTableName() . '` '
71
-			. 'WHERE `uid` = ? AND `type` = ? AND `category` = ?';
72
-		try {
73
-			$this->findEntity($sql, [$tag->getOwner(), $tag->getType(), $tag->getName()]);
74
-		} catch (DoesNotExistException $e) {
75
-			return false;
76
-		}
77
-		return true;
78
-	}
63
+    /**
64
+     * Check if a given Tag object already exists in the database.
65
+     *
66
+     * @param Tag $tag The tag to look for in the database.
67
+     * @return bool
68
+     */
69
+    public function tagExists($tag) {
70
+        $sql = 'SELECT `id`, `uid`, `type`, `category` FROM `' . $this->getTableName() . '` '
71
+            . 'WHERE `uid` = ? AND `type` = ? AND `category` = ?';
72
+        try {
73
+            $this->findEntity($sql, [$tag->getOwner(), $tag->getType(), $tag->getName()]);
74
+        } catch (DoesNotExistException $e) {
75
+            return false;
76
+        }
77
+        return true;
78
+    }
79 79
 }
Please login to merge, or discard this patch.
lib/private/NavigationManager.php 1 patch
Indentation   +260 added lines, -260 removed lines patch added patch discarded remove patch
@@ -45,290 +45,290 @@
 block discarded – undo
45 45
  */
46 46
 
47 47
 class NavigationManager implements INavigationManager {
48
-	protected $entries = [];
49
-	protected $closureEntries = [];
50
-	protected $activeEntry;
51
-	/** @var bool */
52
-	protected $init = false;
53
-	/** @var IAppManager|AppManager */
54
-	protected $appManager;
55
-	/** @var IURLGenerator */
56
-	private $urlGenerator;
57
-	/** @var IFactory */
58
-	private $l10nFac;
59
-	/** @var IUserSession */
60
-	private $userSession;
61
-	/** @var IGroupManager|Manager */
62
-	private $groupManager;
63
-	/** @var IConfig */
64
-	private $config;
48
+    protected $entries = [];
49
+    protected $closureEntries = [];
50
+    protected $activeEntry;
51
+    /** @var bool */
52
+    protected $init = false;
53
+    /** @var IAppManager|AppManager */
54
+    protected $appManager;
55
+    /** @var IURLGenerator */
56
+    private $urlGenerator;
57
+    /** @var IFactory */
58
+    private $l10nFac;
59
+    /** @var IUserSession */
60
+    private $userSession;
61
+    /** @var IGroupManager|Manager */
62
+    private $groupManager;
63
+    /** @var IConfig */
64
+    private $config;
65 65
 
66
-	public function __construct(IAppManager $appManager,
67
-						 IURLGenerator $urlGenerator,
68
-						 IFactory $l10nFac,
69
-						 IUserSession $userSession,
70
-						 IGroupManager $groupManager,
71
-						 IConfig $config) {
72
-		$this->appManager = $appManager;
73
-		$this->urlGenerator = $urlGenerator;
74
-		$this->l10nFac = $l10nFac;
75
-		$this->userSession = $userSession;
76
-		$this->groupManager = $groupManager;
77
-		$this->config = $config;
78
-	}
66
+    public function __construct(IAppManager $appManager,
67
+                            IURLGenerator $urlGenerator,
68
+                            IFactory $l10nFac,
69
+                            IUserSession $userSession,
70
+                            IGroupManager $groupManager,
71
+                            IConfig $config) {
72
+        $this->appManager = $appManager;
73
+        $this->urlGenerator = $urlGenerator;
74
+        $this->l10nFac = $l10nFac;
75
+        $this->userSession = $userSession;
76
+        $this->groupManager = $groupManager;
77
+        $this->config = $config;
78
+    }
79 79
 
80
-	/**
81
-	 * Creates a new navigation entry
82
-	 *
83
-	 * @param array|\Closure $entry Array containing: id, name, order, icon and href key
84
-	 *					The use of a closure is preferred, because it will avoid
85
-	 * 					loading the routing of your app, unless required.
86
-	 * @return void
87
-	 */
88
-	public function add($entry) {
89
-		if ($entry instanceof \Closure) {
90
-			$this->closureEntries[] = $entry;
91
-			return;
92
-		}
80
+    /**
81
+     * Creates a new navigation entry
82
+     *
83
+     * @param array|\Closure $entry Array containing: id, name, order, icon and href key
84
+     *					The use of a closure is preferred, because it will avoid
85
+     * 					loading the routing of your app, unless required.
86
+     * @return void
87
+     */
88
+    public function add($entry) {
89
+        if ($entry instanceof \Closure) {
90
+            $this->closureEntries[] = $entry;
91
+            return;
92
+        }
93 93
 
94
-		$entry['active'] = false;
95
-		if(!isset($entry['icon'])) {
96
-			$entry['icon'] = '';
97
-		}
98
-		if(!isset($entry['classes'])) {
99
-			$entry['classes'] = '';
100
-		}
101
-		if(!isset($entry['type'])) {
102
-			$entry['type'] = 'link';
103
-		}
104
-		$this->entries[$entry['id']] = $entry;
105
-	}
94
+        $entry['active'] = false;
95
+        if(!isset($entry['icon'])) {
96
+            $entry['icon'] = '';
97
+        }
98
+        if(!isset($entry['classes'])) {
99
+            $entry['classes'] = '';
100
+        }
101
+        if(!isset($entry['type'])) {
102
+            $entry['type'] = 'link';
103
+        }
104
+        $this->entries[$entry['id']] = $entry;
105
+    }
106 106
 
107
-	/**
108
-	 * Get a list of navigation entries
109
-	 *
110
-	 * @param string $type type of the navigation entries
111
-	 * @return array
112
-	 */
113
-	public function getAll(string $type = 'link'): array {
114
-		$this->init();
115
-		foreach ($this->closureEntries as $c) {
116
-			$this->add($c());
117
-		}
118
-		$this->closureEntries = [];
107
+    /**
108
+     * Get a list of navigation entries
109
+     *
110
+     * @param string $type type of the navigation entries
111
+     * @return array
112
+     */
113
+    public function getAll(string $type = 'link'): array {
114
+        $this->init();
115
+        foreach ($this->closureEntries as $c) {
116
+            $this->add($c());
117
+        }
118
+        $this->closureEntries = [];
119 119
 
120
-		$result = $this->entries;
121
-		if ($type !== 'all') {
122
-			$result = array_filter($this->entries, function($entry) use ($type) {
123
-				return $entry['type'] === $type;
124
-			});
125
-		}
120
+        $result = $this->entries;
121
+        if ($type !== 'all') {
122
+            $result = array_filter($this->entries, function($entry) use ($type) {
123
+                return $entry['type'] === $type;
124
+            });
125
+        }
126 126
 
127
-		return $this->proceedNavigation($result);
128
-	}
127
+        return $this->proceedNavigation($result);
128
+    }
129 129
 
130
-	/**
131
-	 * Sort navigation entries by order, name and set active flag
132
-	 *
133
-	 * @param array $list
134
-	 * @return array
135
-	 */
136
-	private function proceedNavigation(array $list): array {
137
-		uasort($list, function($a, $b) {
138
-			if (isset($a['order']) && isset($b['order'])) {
139
-				return ($a['order'] < $b['order']) ? -1 : 1;
140
-			} else if (isset($a['order']) || isset($b['order'])) {
141
-				return isset($a['order']) ? -1 : 1;
142
-			} else {
143
-				return ($a['name'] < $b['name']) ? -1 : 1;
144
-			}
145
-		});
130
+    /**
131
+     * Sort navigation entries by order, name and set active flag
132
+     *
133
+     * @param array $list
134
+     * @return array
135
+     */
136
+    private function proceedNavigation(array $list): array {
137
+        uasort($list, function($a, $b) {
138
+            if (isset($a['order']) && isset($b['order'])) {
139
+                return ($a['order'] < $b['order']) ? -1 : 1;
140
+            } else if (isset($a['order']) || isset($b['order'])) {
141
+                return isset($a['order']) ? -1 : 1;
142
+            } else {
143
+                return ($a['name'] < $b['name']) ? -1 : 1;
144
+            }
145
+        });
146 146
 
147
-		$activeApp = $this->getActiveEntry();
148
-		if ($activeApp !== null) {
149
-			foreach ($list as $index => &$navEntry) {
150
-				if ($navEntry['id'] == $activeApp) {
151
-					$navEntry['active'] = true;
152
-				} else {
153
-					$navEntry['active'] = false;
154
-				}
155
-			}
156
-			unset($navEntry);
157
-		}
147
+        $activeApp = $this->getActiveEntry();
148
+        if ($activeApp !== null) {
149
+            foreach ($list as $index => &$navEntry) {
150
+                if ($navEntry['id'] == $activeApp) {
151
+                    $navEntry['active'] = true;
152
+                } else {
153
+                    $navEntry['active'] = false;
154
+                }
155
+            }
156
+            unset($navEntry);
157
+        }
158 158
 
159
-		return $list;
160
-	}
159
+        return $list;
160
+    }
161 161
 
162 162
 
163
-	/**
164
-	 * removes all the entries
165
-	 */
166
-	public function clear($loadDefaultLinks = true) {
167
-		$this->entries = [];
168
-		$this->closureEntries = [];
169
-		$this->init = !$loadDefaultLinks;
170
-	}
163
+    /**
164
+     * removes all the entries
165
+     */
166
+    public function clear($loadDefaultLinks = true) {
167
+        $this->entries = [];
168
+        $this->closureEntries = [];
169
+        $this->init = !$loadDefaultLinks;
170
+    }
171 171
 
172
-	/**
173
-	 * Sets the current navigation entry of the currently running app
174
-	 * @param string $id of the app entry to activate (from added $entry)
175
-	 */
176
-	public function setActiveEntry($id) {
177
-		$this->activeEntry = $id;
178
-	}
172
+    /**
173
+     * Sets the current navigation entry of the currently running app
174
+     * @param string $id of the app entry to activate (from added $entry)
175
+     */
176
+    public function setActiveEntry($id) {
177
+        $this->activeEntry = $id;
178
+    }
179 179
 
180
-	/**
181
-	 * gets the active Menu entry
182
-	 * @return string id or empty string
183
-	 *
184
-	 * This function returns the id of the active navigation entry (set by
185
-	 * setActiveEntry
186
-	 */
187
-	public function getActiveEntry() {
188
-		return $this->activeEntry;
189
-	}
180
+    /**
181
+     * gets the active Menu entry
182
+     * @return string id or empty string
183
+     *
184
+     * This function returns the id of the active navigation entry (set by
185
+     * setActiveEntry
186
+     */
187
+    public function getActiveEntry() {
188
+        return $this->activeEntry;
189
+    }
190 190
 
191
-	private function init() {
192
-		if ($this->init) {
193
-			return;
194
-		}
195
-		$this->init = true;
191
+    private function init() {
192
+        if ($this->init) {
193
+            return;
194
+        }
195
+        $this->init = true;
196 196
 
197
-		$l = $this->l10nFac->get('lib');
198
-		if ($this->config->getSystemValue('knowledgebaseenabled', true)) {
199
-			$this->add([
200
-				'type' => 'settings',
201
-				'id' => 'help',
202
-				'order' => 5,
203
-				'href' => $this->urlGenerator->linkToRoute('settings.Help.help'),
204
-				'name' => $l->t('Help'),
205
-				'icon' => $this->urlGenerator->imagePath('settings', 'help.svg'),
206
-			]);
207
-		}
197
+        $l = $this->l10nFac->get('lib');
198
+        if ($this->config->getSystemValue('knowledgebaseenabled', true)) {
199
+            $this->add([
200
+                'type' => 'settings',
201
+                'id' => 'help',
202
+                'order' => 5,
203
+                'href' => $this->urlGenerator->linkToRoute('settings.Help.help'),
204
+                'name' => $l->t('Help'),
205
+                'icon' => $this->urlGenerator->imagePath('settings', 'help.svg'),
206
+            ]);
207
+        }
208 208
 
209
-		if ($this->userSession->isLoggedIn()) {
210
-			if ($this->isAdmin()) {
211
-				// App management
212
-				$this->add([
213
-					'type' => 'settings',
214
-					'id' => 'core_apps',
215
-					'order' => 3,
216
-					'href' => $this->urlGenerator->linkToRoute('settings.AppSettings.viewApps'),
217
-					'icon' => $this->urlGenerator->imagePath('settings', 'apps.svg'),
218
-					'name' => $l->t('Apps'),
219
-				]);
220
-			}
209
+        if ($this->userSession->isLoggedIn()) {
210
+            if ($this->isAdmin()) {
211
+                // App management
212
+                $this->add([
213
+                    'type' => 'settings',
214
+                    'id' => 'core_apps',
215
+                    'order' => 3,
216
+                    'href' => $this->urlGenerator->linkToRoute('settings.AppSettings.viewApps'),
217
+                    'icon' => $this->urlGenerator->imagePath('settings', 'apps.svg'),
218
+                    'name' => $l->t('Apps'),
219
+                ]);
220
+            }
221 221
 
222
-			// Personal and (if applicable) admin settings
223
-			$this->add([
224
-				'type' => 'settings',
225
-				'id' => 'settings',
226
-				'order' => 1,
227
-				'href' => $this->urlGenerator->linkToRoute('settings.PersonalSettings.index'),
228
-				'name' => $l->t('Settings'),
229
-				'icon' => $this->urlGenerator->imagePath('settings', 'admin.svg'),
230
-			]);
222
+            // Personal and (if applicable) admin settings
223
+            $this->add([
224
+                'type' => 'settings',
225
+                'id' => 'settings',
226
+                'order' => 1,
227
+                'href' => $this->urlGenerator->linkToRoute('settings.PersonalSettings.index'),
228
+                'name' => $l->t('Settings'),
229
+                'icon' => $this->urlGenerator->imagePath('settings', 'admin.svg'),
230
+            ]);
231 231
 
232
-			$logoutUrl = \OC_User::getLogoutUrl($this->urlGenerator);
233
-			if($logoutUrl !== '') {
234
-				// Logout
235
-				$this->add([
236
-					'type' => 'settings',
237
-					'id' => 'logout',
238
-					'order' => 99999,
239
-					'href' => $logoutUrl,
240
-					'name' => $l->t('Log out'),
241
-					'icon' => $this->urlGenerator->imagePath('core', 'actions/logout.svg'),
242
-				]);
243
-			}
232
+            $logoutUrl = \OC_User::getLogoutUrl($this->urlGenerator);
233
+            if($logoutUrl !== '') {
234
+                // Logout
235
+                $this->add([
236
+                    'type' => 'settings',
237
+                    'id' => 'logout',
238
+                    'order' => 99999,
239
+                    'href' => $logoutUrl,
240
+                    'name' => $l->t('Log out'),
241
+                    'icon' => $this->urlGenerator->imagePath('core', 'actions/logout.svg'),
242
+                ]);
243
+            }
244 244
 
245
-			if ($this->isSubadmin()) {
246
-				// User management
247
-				$this->add([
248
-					'type' => 'settings',
249
-					'id' => 'core_users',
250
-					'order' => 4,
251
-					'href' => $this->urlGenerator->linkToRoute('settings.Users.usersList'),
252
-					'name' => $l->t('Users'),
253
-					'icon' => $this->urlGenerator->imagePath('settings', 'users.svg'),
254
-				]);
255
-			}
256
-		}
245
+            if ($this->isSubadmin()) {
246
+                // User management
247
+                $this->add([
248
+                    'type' => 'settings',
249
+                    'id' => 'core_users',
250
+                    'order' => 4,
251
+                    'href' => $this->urlGenerator->linkToRoute('settings.Users.usersList'),
252
+                    'name' => $l->t('Users'),
253
+                    'icon' => $this->urlGenerator->imagePath('settings', 'users.svg'),
254
+                ]);
255
+            }
256
+        }
257 257
 
258
-		if ($this->appManager === 'null') {
259
-			return;
260
-		}
258
+        if ($this->appManager === 'null') {
259
+            return;
260
+        }
261 261
 
262
-		if ($this->userSession->isLoggedIn()) {
263
-			$apps = $this->appManager->getEnabledAppsForUser($this->userSession->getUser());
264
-		} else {
265
-			$apps = $this->appManager->getInstalledApps();
266
-		}
262
+        if ($this->userSession->isLoggedIn()) {
263
+            $apps = $this->appManager->getEnabledAppsForUser($this->userSession->getUser());
264
+        } else {
265
+            $apps = $this->appManager->getInstalledApps();
266
+        }
267 267
 
268
-		foreach ($apps as $app) {
269
-			if (!$this->userSession->isLoggedIn() && !$this->appManager->isEnabledForUser($app, $this->userSession->getUser())) {
270
-				continue;
271
-			}
268
+        foreach ($apps as $app) {
269
+            if (!$this->userSession->isLoggedIn() && !$this->appManager->isEnabledForUser($app, $this->userSession->getUser())) {
270
+                continue;
271
+            }
272 272
 
273
-			// load plugins and collections from info.xml
274
-			$info = $this->appManager->getAppInfo($app);
275
-			if (!isset($info['navigations']['navigation'])) {
276
-				continue;
277
-			}
278
-			foreach ($info['navigations']['navigation'] as $key => $nav) {
279
-				if (!isset($nav['name'])) {
280
-					continue;
281
-				}
282
-				if (!isset($nav['route'])) {
283
-					continue;
284
-				}
285
-				$role = isset($nav['@attributes']['role']) ? $nav['@attributes']['role'] : 'all';
286
-				if ($role === 'admin' && !$this->isAdmin()) {
287
-					continue;
288
-				}
289
-				$l = $this->l10nFac->get($app);
290
-				$id = $nav['id'] ?? $app . ($key === 0 ? '' : $key);
291
-				$order = isset($nav['order']) ? $nav['order'] : 100;
292
-				$type = isset($nav['type']) ? $nav['type'] : 'link';
293
-				$route = $nav['route'] !== '' ? $this->urlGenerator->linkToRoute($nav['route']) : '';
294
-				$icon = isset($nav['icon']) ? $nav['icon'] : 'app.svg';
295
-				foreach ([$icon, "$app.svg"] as $i) {
296
-					try {
297
-						$icon = $this->urlGenerator->imagePath($app, $i);
298
-						break;
299
-					} catch (\RuntimeException $ex) {
300
-						// no icon? - ignore it then
301
-					}
302
-				}
303
-				if ($icon === null) {
304
-					$icon = $this->urlGenerator->imagePath('core', 'default-app-icon');
305
-				}
273
+            // load plugins and collections from info.xml
274
+            $info = $this->appManager->getAppInfo($app);
275
+            if (!isset($info['navigations']['navigation'])) {
276
+                continue;
277
+            }
278
+            foreach ($info['navigations']['navigation'] as $key => $nav) {
279
+                if (!isset($nav['name'])) {
280
+                    continue;
281
+                }
282
+                if (!isset($nav['route'])) {
283
+                    continue;
284
+                }
285
+                $role = isset($nav['@attributes']['role']) ? $nav['@attributes']['role'] : 'all';
286
+                if ($role === 'admin' && !$this->isAdmin()) {
287
+                    continue;
288
+                }
289
+                $l = $this->l10nFac->get($app);
290
+                $id = $nav['id'] ?? $app . ($key === 0 ? '' : $key);
291
+                $order = isset($nav['order']) ? $nav['order'] : 100;
292
+                $type = isset($nav['type']) ? $nav['type'] : 'link';
293
+                $route = $nav['route'] !== '' ? $this->urlGenerator->linkToRoute($nav['route']) : '';
294
+                $icon = isset($nav['icon']) ? $nav['icon'] : 'app.svg';
295
+                foreach ([$icon, "$app.svg"] as $i) {
296
+                    try {
297
+                        $icon = $this->urlGenerator->imagePath($app, $i);
298
+                        break;
299
+                    } catch (\RuntimeException $ex) {
300
+                        // no icon? - ignore it then
301
+                    }
302
+                }
303
+                if ($icon === null) {
304
+                    $icon = $this->urlGenerator->imagePath('core', 'default-app-icon');
305
+                }
306 306
 
307
-				$this->add([
308
-					'id' => $id,
309
-					'order' => $order,
310
-					'href' => $route,
311
-					'icon' => $icon,
312
-					'type' => $type,
313
-					'name' => $l->t($nav['name']),
314
-				]);
315
-			}
316
-		}
317
-	}
307
+                $this->add([
308
+                    'id' => $id,
309
+                    'order' => $order,
310
+                    'href' => $route,
311
+                    'icon' => $icon,
312
+                    'type' => $type,
313
+                    'name' => $l->t($nav['name']),
314
+                ]);
315
+            }
316
+        }
317
+    }
318 318
 
319
-	private function isAdmin() {
320
-		$user = $this->userSession->getUser();
321
-		if ($user !== null) {
322
-			return $this->groupManager->isAdmin($user->getUID());
323
-		}
324
-		return false;
325
-	}
319
+    private function isAdmin() {
320
+        $user = $this->userSession->getUser();
321
+        if ($user !== null) {
322
+            return $this->groupManager->isAdmin($user->getUID());
323
+        }
324
+        return false;
325
+    }
326 326
 
327
-	private function isSubadmin() {
328
-		$user = $this->userSession->getUser();
329
-		if ($user !== null) {
330
-			return $this->groupManager->getSubAdmin()->isSubAdmin($user);
331
-		}
332
-		return false;
333
-	}
327
+    private function isSubadmin() {
328
+        $user = $this->userSession->getUser();
329
+        if ($user !== null) {
330
+            return $this->groupManager->getSubAdmin()->isSubAdmin($user);
331
+        }
332
+        return false;
333
+    }
334 334
 }
Please login to merge, or discard this patch.
lib/private/Archive/TAR.php 1 patch
Indentation   +326 added lines, -326 removed lines patch added patch discarded remove patch
@@ -35,350 +35,350 @@
 block discarded – undo
35 35
 use Icewind\Streams\CallbackWrapper;
36 36
 
37 37
 class TAR extends Archive {
38
-	const PLAIN = 0;
39
-	const GZIP = 1;
40
-	const BZIP = 2;
38
+    const PLAIN = 0;
39
+    const GZIP = 1;
40
+    const BZIP = 2;
41 41
 
42
-	private $fileList;
43
-	private $cachedHeaders;
42
+    private $fileList;
43
+    private $cachedHeaders;
44 44
 
45
-	/**
46
-	 * @var \Archive_Tar tar
47
-	 */
48
-	private $tar = null;
49
-	private $path;
45
+    /**
46
+     * @var \Archive_Tar tar
47
+     */
48
+    private $tar = null;
49
+    private $path;
50 50
 
51
-	/**
52
-	 * @param string $source
53
-	 */
54
-	public function __construct($source) {
55
-		$types = [null, 'gz', 'bz2'];
56
-		$this->path = $source;
57
-		$this->tar = new \Archive_Tar($source, $types[self::getTarType($source)]);
58
-	}
51
+    /**
52
+     * @param string $source
53
+     */
54
+    public function __construct($source) {
55
+        $types = [null, 'gz', 'bz2'];
56
+        $this->path = $source;
57
+        $this->tar = new \Archive_Tar($source, $types[self::getTarType($source)]);
58
+    }
59 59
 
60
-	/**
61
-	 * try to detect the type of tar compression
62
-	 *
63
-	 * @param string $file
64
-	 * @return integer
65
-	 */
66
-	static public function getTarType($file) {
67
-		if (strpos($file, '.')) {
68
-			$extension = substr($file, strrpos($file, '.'));
69
-			switch ($extension) {
70
-				case '.gz':
71
-				case '.tgz':
72
-					return self::GZIP;
73
-				case '.bz':
74
-				case '.bz2':
75
-					return self::BZIP;
76
-				case '.tar':
77
-					return self::PLAIN;
78
-				default:
79
-					return self::PLAIN;
80
-			}
81
-		} else {
82
-			return self::PLAIN;
83
-		}
84
-	}
60
+    /**
61
+     * try to detect the type of tar compression
62
+     *
63
+     * @param string $file
64
+     * @return integer
65
+     */
66
+    static public function getTarType($file) {
67
+        if (strpos($file, '.')) {
68
+            $extension = substr($file, strrpos($file, '.'));
69
+            switch ($extension) {
70
+                case '.gz':
71
+                case '.tgz':
72
+                    return self::GZIP;
73
+                case '.bz':
74
+                case '.bz2':
75
+                    return self::BZIP;
76
+                case '.tar':
77
+                    return self::PLAIN;
78
+                default:
79
+                    return self::PLAIN;
80
+            }
81
+        } else {
82
+            return self::PLAIN;
83
+        }
84
+    }
85 85
 
86
-	/**
87
-	 * add an empty folder to the archive
88
-	 *
89
-	 * @param string $path
90
-	 * @return bool
91
-	 */
92
-	public function addFolder($path) {
93
-		$tmpBase = \OC::$server->getTempManager()->getTemporaryFolder();
94
-		$path = rtrim($path, '/') . '/';
95
-		if ($this->fileExists($path)) {
96
-			return false;
97
-		}
98
-		$parts = explode('/', $path);
99
-		$folder = $tmpBase;
100
-		foreach ($parts as $part) {
101
-			$folder .= '/' . $part;
102
-			if (!is_dir($folder)) {
103
-				mkdir($folder);
104
-			}
105
-		}
106
-		$result = $this->tar->addModify([$tmpBase . $path], '', $tmpBase);
107
-		rmdir($tmpBase . $path);
108
-		$this->fileList = false;
109
-		$this->cachedHeaders = false;
110
-		return $result;
111
-	}
86
+    /**
87
+     * add an empty folder to the archive
88
+     *
89
+     * @param string $path
90
+     * @return bool
91
+     */
92
+    public function addFolder($path) {
93
+        $tmpBase = \OC::$server->getTempManager()->getTemporaryFolder();
94
+        $path = rtrim($path, '/') . '/';
95
+        if ($this->fileExists($path)) {
96
+            return false;
97
+        }
98
+        $parts = explode('/', $path);
99
+        $folder = $tmpBase;
100
+        foreach ($parts as $part) {
101
+            $folder .= '/' . $part;
102
+            if (!is_dir($folder)) {
103
+                mkdir($folder);
104
+            }
105
+        }
106
+        $result = $this->tar->addModify([$tmpBase . $path], '', $tmpBase);
107
+        rmdir($tmpBase . $path);
108
+        $this->fileList = false;
109
+        $this->cachedHeaders = false;
110
+        return $result;
111
+    }
112 112
 
113
-	/**
114
-	 * add a file to the archive
115
-	 *
116
-	 * @param string $path
117
-	 * @param string $source either a local file or string data
118
-	 * @return bool
119
-	 */
120
-	public function addFile($path, $source = '') {
121
-		if ($this->fileExists($path)) {
122
-			$this->remove($path);
123
-		}
124
-		if ($source and $source[0] == '/' and file_exists($source)) {
125
-			$source = file_get_contents($source);
126
-		}
127
-		$result = $this->tar->addString($path, $source);
128
-		$this->fileList = false;
129
-		$this->cachedHeaders = false;
130
-		return $result;
131
-	}
113
+    /**
114
+     * add a file to the archive
115
+     *
116
+     * @param string $path
117
+     * @param string $source either a local file or string data
118
+     * @return bool
119
+     */
120
+    public function addFile($path, $source = '') {
121
+        if ($this->fileExists($path)) {
122
+            $this->remove($path);
123
+        }
124
+        if ($source and $source[0] == '/' and file_exists($source)) {
125
+            $source = file_get_contents($source);
126
+        }
127
+        $result = $this->tar->addString($path, $source);
128
+        $this->fileList = false;
129
+        $this->cachedHeaders = false;
130
+        return $result;
131
+    }
132 132
 
133
-	/**
134
-	 * rename a file or folder in the archive
135
-	 *
136
-	 * @param string $source
137
-	 * @param string $dest
138
-	 * @return bool
139
-	 */
140
-	public function rename($source, $dest) {
141
-		//no proper way to delete, rename entire archive, rename file and remake archive
142
-		$tmp = \OC::$server->getTempManager()->getTemporaryFolder();
143
-		$this->tar->extract($tmp);
144
-		rename($tmp . $source, $tmp . $dest);
145
-		$this->tar = null;
146
-		unlink($this->path);
147
-		$types = [null, 'gz', 'bz'];
148
-		$this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
149
-		$this->tar->createModify([$tmp], '', $tmp . '/');
150
-		$this->fileList = false;
151
-		$this->cachedHeaders = false;
152
-		return true;
153
-	}
133
+    /**
134
+     * rename a file or folder in the archive
135
+     *
136
+     * @param string $source
137
+     * @param string $dest
138
+     * @return bool
139
+     */
140
+    public function rename($source, $dest) {
141
+        //no proper way to delete, rename entire archive, rename file and remake archive
142
+        $tmp = \OC::$server->getTempManager()->getTemporaryFolder();
143
+        $this->tar->extract($tmp);
144
+        rename($tmp . $source, $tmp . $dest);
145
+        $this->tar = null;
146
+        unlink($this->path);
147
+        $types = [null, 'gz', 'bz'];
148
+        $this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
149
+        $this->tar->createModify([$tmp], '', $tmp . '/');
150
+        $this->fileList = false;
151
+        $this->cachedHeaders = false;
152
+        return true;
153
+    }
154 154
 
155
-	/**
156
-	 * @param string $file
157
-	 */
158
-	private function getHeader($file) {
159
-		if (!$this->cachedHeaders) {
160
-			$this->cachedHeaders = $this->tar->listContent();
161
-		}
162
-		foreach ($this->cachedHeaders as $header) {
163
-			if ($file == $header['filename']
164
-				or $file . '/' == $header['filename']
165
-				or '/' . $file . '/' == $header['filename']
166
-				or '/' . $file == $header['filename']
167
-			) {
168
-				return $header;
169
-			}
170
-		}
171
-		return null;
172
-	}
155
+    /**
156
+     * @param string $file
157
+     */
158
+    private function getHeader($file) {
159
+        if (!$this->cachedHeaders) {
160
+            $this->cachedHeaders = $this->tar->listContent();
161
+        }
162
+        foreach ($this->cachedHeaders as $header) {
163
+            if ($file == $header['filename']
164
+                or $file . '/' == $header['filename']
165
+                or '/' . $file . '/' == $header['filename']
166
+                or '/' . $file == $header['filename']
167
+            ) {
168
+                return $header;
169
+            }
170
+        }
171
+        return null;
172
+    }
173 173
 
174
-	/**
175
-	 * get the uncompressed size of a file in the archive
176
-	 *
177
-	 * @param string $path
178
-	 * @return int
179
-	 */
180
-	public function filesize($path) {
181
-		$stat = $this->getHeader($path);
182
-		return $stat['size'];
183
-	}
174
+    /**
175
+     * get the uncompressed size of a file in the archive
176
+     *
177
+     * @param string $path
178
+     * @return int
179
+     */
180
+    public function filesize($path) {
181
+        $stat = $this->getHeader($path);
182
+        return $stat['size'];
183
+    }
184 184
 
185
-	/**
186
-	 * get the last modified time of a file in the archive
187
-	 *
188
-	 * @param string $path
189
-	 * @return int
190
-	 */
191
-	public function mtime($path) {
192
-		$stat = $this->getHeader($path);
193
-		return $stat['mtime'];
194
-	}
185
+    /**
186
+     * get the last modified time of a file in the archive
187
+     *
188
+     * @param string $path
189
+     * @return int
190
+     */
191
+    public function mtime($path) {
192
+        $stat = $this->getHeader($path);
193
+        return $stat['mtime'];
194
+    }
195 195
 
196
-	/**
197
-	 * get the files in a folder
198
-	 *
199
-	 * @param string $path
200
-	 * @return array
201
-	 */
202
-	public function getFolder($path) {
203
-		$files = $this->getFiles();
204
-		$folderContent = [];
205
-		$pathLength = strlen($path);
206
-		foreach ($files as $file) {
207
-			if ($file[0] == '/') {
208
-				$file = substr($file, 1);
209
-			}
210
-			if (substr($file, 0, $pathLength) == $path and $file != $path) {
211
-				$result = substr($file, $pathLength);
212
-				if ($pos = strpos($result, '/')) {
213
-					$result = substr($result, 0, $pos + 1);
214
-				}
215
-				if (array_search($result, $folderContent) === false) {
216
-					$folderContent[] = $result;
217
-				}
218
-			}
219
-		}
220
-		return $folderContent;
221
-	}
196
+    /**
197
+     * get the files in a folder
198
+     *
199
+     * @param string $path
200
+     * @return array
201
+     */
202
+    public function getFolder($path) {
203
+        $files = $this->getFiles();
204
+        $folderContent = [];
205
+        $pathLength = strlen($path);
206
+        foreach ($files as $file) {
207
+            if ($file[0] == '/') {
208
+                $file = substr($file, 1);
209
+            }
210
+            if (substr($file, 0, $pathLength) == $path and $file != $path) {
211
+                $result = substr($file, $pathLength);
212
+                if ($pos = strpos($result, '/')) {
213
+                    $result = substr($result, 0, $pos + 1);
214
+                }
215
+                if (array_search($result, $folderContent) === false) {
216
+                    $folderContent[] = $result;
217
+                }
218
+            }
219
+        }
220
+        return $folderContent;
221
+    }
222 222
 
223
-	/**
224
-	 * get all files in the archive
225
-	 *
226
-	 * @return array
227
-	 */
228
-	public function getFiles() {
229
-		if ($this->fileList) {
230
-			return $this->fileList;
231
-		}
232
-		if (!$this->cachedHeaders) {
233
-			$this->cachedHeaders = $this->tar->listContent();
234
-		}
235
-		$files = [];
236
-		foreach ($this->cachedHeaders as $header) {
237
-			$files[] = $header['filename'];
238
-		}
239
-		$this->fileList = $files;
240
-		return $files;
241
-	}
223
+    /**
224
+     * get all files in the archive
225
+     *
226
+     * @return array
227
+     */
228
+    public function getFiles() {
229
+        if ($this->fileList) {
230
+            return $this->fileList;
231
+        }
232
+        if (!$this->cachedHeaders) {
233
+            $this->cachedHeaders = $this->tar->listContent();
234
+        }
235
+        $files = [];
236
+        foreach ($this->cachedHeaders as $header) {
237
+            $files[] = $header['filename'];
238
+        }
239
+        $this->fileList = $files;
240
+        return $files;
241
+    }
242 242
 
243
-	/**
244
-	 * get the content of a file
245
-	 *
246
-	 * @param string $path
247
-	 * @return string
248
-	 */
249
-	public function getFile($path) {
250
-		return $this->tar->extractInString($path);
251
-	}
243
+    /**
244
+     * get the content of a file
245
+     *
246
+     * @param string $path
247
+     * @return string
248
+     */
249
+    public function getFile($path) {
250
+        return $this->tar->extractInString($path);
251
+    }
252 252
 
253
-	/**
254
-	 * extract a single file from the archive
255
-	 *
256
-	 * @param string $path
257
-	 * @param string $dest
258
-	 * @return bool
259
-	 */
260
-	public function extractFile($path, $dest) {
261
-		$tmp = \OC::$server->getTempManager()->getTemporaryFolder();
262
-		if (!$this->fileExists($path)) {
263
-			return false;
264
-		}
265
-		if ($this->fileExists('/' . $path)) {
266
-			$success = $this->tar->extractList(['/' . $path], $tmp);
267
-		} else {
268
-			$success = $this->tar->extractList([$path], $tmp);
269
-		}
270
-		if ($success) {
271
-			rename($tmp . $path, $dest);
272
-		}
273
-		\OCP\Files::rmdirr($tmp);
274
-		return $success;
275
-	}
253
+    /**
254
+     * extract a single file from the archive
255
+     *
256
+     * @param string $path
257
+     * @param string $dest
258
+     * @return bool
259
+     */
260
+    public function extractFile($path, $dest) {
261
+        $tmp = \OC::$server->getTempManager()->getTemporaryFolder();
262
+        if (!$this->fileExists($path)) {
263
+            return false;
264
+        }
265
+        if ($this->fileExists('/' . $path)) {
266
+            $success = $this->tar->extractList(['/' . $path], $tmp);
267
+        } else {
268
+            $success = $this->tar->extractList([$path], $tmp);
269
+        }
270
+        if ($success) {
271
+            rename($tmp . $path, $dest);
272
+        }
273
+        \OCP\Files::rmdirr($tmp);
274
+        return $success;
275
+    }
276 276
 
277
-	/**
278
-	 * extract the archive
279
-	 *
280
-	 * @param string $dest
281
-	 * @return bool
282
-	 */
283
-	public function extract($dest) {
284
-		return $this->tar->extract($dest);
285
-	}
277
+    /**
278
+     * extract the archive
279
+     *
280
+     * @param string $dest
281
+     * @return bool
282
+     */
283
+    public function extract($dest) {
284
+        return $this->tar->extract($dest);
285
+    }
286 286
 
287
-	/**
288
-	 * check if a file or folder exists in the archive
289
-	 *
290
-	 * @param string $path
291
-	 * @return bool
292
-	 */
293
-	public function fileExists($path) {
294
-		$files = $this->getFiles();
295
-		if ((array_search($path, $files) !== false) or (array_search($path . '/', $files) !== false)) {
296
-			return true;
297
-		} else {
298
-			$folderPath = rtrim($path, '/') . '/';
299
-			$pathLength = strlen($folderPath);
300
-			foreach ($files as $file) {
301
-				if (strlen($file) > $pathLength and substr($file, 0, $pathLength) == $folderPath) {
302
-					return true;
303
-				}
304
-			}
305
-		}
306
-		if ($path[0] != '/') { //not all programs agree on the use of a leading /
307
-			return $this->fileExists('/' . $path);
308
-		} else {
309
-			return false;
310
-		}
311
-	}
287
+    /**
288
+     * check if a file or folder exists in the archive
289
+     *
290
+     * @param string $path
291
+     * @return bool
292
+     */
293
+    public function fileExists($path) {
294
+        $files = $this->getFiles();
295
+        if ((array_search($path, $files) !== false) or (array_search($path . '/', $files) !== false)) {
296
+            return true;
297
+        } else {
298
+            $folderPath = rtrim($path, '/') . '/';
299
+            $pathLength = strlen($folderPath);
300
+            foreach ($files as $file) {
301
+                if (strlen($file) > $pathLength and substr($file, 0, $pathLength) == $folderPath) {
302
+                    return true;
303
+                }
304
+            }
305
+        }
306
+        if ($path[0] != '/') { //not all programs agree on the use of a leading /
307
+            return $this->fileExists('/' . $path);
308
+        } else {
309
+            return false;
310
+        }
311
+    }
312 312
 
313
-	/**
314
-	 * remove a file or folder from the archive
315
-	 *
316
-	 * @param string $path
317
-	 * @return bool
318
-	 */
319
-	public function remove($path) {
320
-		if (!$this->fileExists($path)) {
321
-			return false;
322
-		}
323
-		$this->fileList = false;
324
-		$this->cachedHeaders = false;
325
-		//no proper way to delete, extract entire archive, delete file and remake archive
326
-		$tmp = \OC::$server->getTempManager()->getTemporaryFolder();
327
-		$this->tar->extract($tmp);
328
-		\OCP\Files::rmdirr($tmp . $path);
329
-		$this->tar = null;
330
-		unlink($this->path);
331
-		$this->reopen();
332
-		$this->tar->createModify([$tmp], '', $tmp);
333
-		return true;
334
-	}
313
+    /**
314
+     * remove a file or folder from the archive
315
+     *
316
+     * @param string $path
317
+     * @return bool
318
+     */
319
+    public function remove($path) {
320
+        if (!$this->fileExists($path)) {
321
+            return false;
322
+        }
323
+        $this->fileList = false;
324
+        $this->cachedHeaders = false;
325
+        //no proper way to delete, extract entire archive, delete file and remake archive
326
+        $tmp = \OC::$server->getTempManager()->getTemporaryFolder();
327
+        $this->tar->extract($tmp);
328
+        \OCP\Files::rmdirr($tmp . $path);
329
+        $this->tar = null;
330
+        unlink($this->path);
331
+        $this->reopen();
332
+        $this->tar->createModify([$tmp], '', $tmp);
333
+        return true;
334
+    }
335 335
 
336
-	/**
337
-	 * get a file handler
338
-	 *
339
-	 * @param string $path
340
-	 * @param string $mode
341
-	 * @return resource
342
-	 */
343
-	public function getStream($path, $mode) {
344
-		if (strrpos($path, '.') !== false) {
345
-			$ext = substr($path, strrpos($path, '.'));
346
-		} else {
347
-			$ext = '';
348
-		}
349
-		$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
350
-		if ($this->fileExists($path)) {
351
-			$this->extractFile($path, $tmpFile);
352
-		} elseif ($mode == 'r' or $mode == 'rb') {
353
-			return false;
354
-		}
355
-		if ($mode == 'r' or $mode == 'rb') {
356
-			return fopen($tmpFile, $mode);
357
-		} else {
358
-			$handle = fopen($tmpFile, $mode);
359
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
360
-				$this->writeBack($tmpFile, $path);
361
-			});
362
-		}
363
-	}
336
+    /**
337
+     * get a file handler
338
+     *
339
+     * @param string $path
340
+     * @param string $mode
341
+     * @return resource
342
+     */
343
+    public function getStream($path, $mode) {
344
+        if (strrpos($path, '.') !== false) {
345
+            $ext = substr($path, strrpos($path, '.'));
346
+        } else {
347
+            $ext = '';
348
+        }
349
+        $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
350
+        if ($this->fileExists($path)) {
351
+            $this->extractFile($path, $tmpFile);
352
+        } elseif ($mode == 'r' or $mode == 'rb') {
353
+            return false;
354
+        }
355
+        if ($mode == 'r' or $mode == 'rb') {
356
+            return fopen($tmpFile, $mode);
357
+        } else {
358
+            $handle = fopen($tmpFile, $mode);
359
+            return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
360
+                $this->writeBack($tmpFile, $path);
361
+            });
362
+        }
363
+    }
364 364
 
365
-	/**
366
-	 * write back temporary files
367
-	 */
368
-	public function writeBack($tmpFile, $path) {
369
-		$this->addFile($path, $tmpFile);
370
-		unlink($tmpFile);
371
-	}
365
+    /**
366
+     * write back temporary files
367
+     */
368
+    public function writeBack($tmpFile, $path) {
369
+        $this->addFile($path, $tmpFile);
370
+        unlink($tmpFile);
371
+    }
372 372
 
373
-	/**
374
-	 * reopen the archive to ensure everything is written
375
-	 */
376
-	private function reopen() {
377
-		if ($this->tar) {
378
-			$this->tar->_close();
379
-			$this->tar = null;
380
-		}
381
-		$types = [null, 'gz', 'bz'];
382
-		$this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
383
-	}
373
+    /**
374
+     * reopen the archive to ensure everything is written
375
+     */
376
+    private function reopen() {
377
+        if ($this->tar) {
378
+            $this->tar->_close();
379
+            $this->tar = null;
380
+        }
381
+        $types = [null, 'gz', 'bz'];
382
+        $this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
383
+    }
384 384
 }
Please login to merge, or discard this patch.