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