Completed
Push — stable9 ( 11047b...318578 )
by Lukas
20:03 queued 09:36
created
apps/files_external/command/backends.php 3 patches
Unused Use Statements   -6 removed lines patch added patch discarded remove patch
@@ -22,18 +22,12 @@
 block discarded – undo
22 22
 namespace OCA\Files_External\Command;
23 23
 
24 24
 use OC\Core\Command\Base;
25
-use OCA\Files_External\Lib\Auth\AuthMechanism;
26 25
 use OCA\Files_External\Lib\Backend\Backend;
27 26
 use OCA\Files_External\Lib\DefinitionParameter;
28 27
 use OCA\Files_External\Service\BackendService;
29 28
 use Symfony\Component\Console\Command\Command;
30
-use Symfony\Component\Console\Helper\Table;
31
-use Symfony\Component\Console\Helper\TableHelper;
32
-use Symfony\Component\Console\Input\ArrayInput;
33 29
 use Symfony\Component\Console\Input\InputArgument;
34 30
 use Symfony\Component\Console\Input\InputInterface;
35
-use Symfony\Component\Console\Input\InputOption;
36
-use Symfony\Component\Console\Input\Input;
37 31
 use Symfony\Component\Console\Output\OutputInterface;
38 32
 
39 33
 class Backends extends Base {
Please login to merge, or discard this patch.
Indentation   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -38,76 +38,76 @@
 block discarded – undo
38 38
 use Symfony\Component\Console\Output\OutputInterface;
39 39
 
40 40
 class Backends extends Base {
41
-	/** @var BackendService */
42
-	private $backendService;
41
+    /** @var BackendService */
42
+    private $backendService;
43 43
 
44
-	function __construct(BackendService $backendService
45
-	) {
46
-		parent::__construct();
44
+    function __construct(BackendService $backendService
45
+    ) {
46
+        parent::__construct();
47 47
 
48
-		$this->backendService = $backendService;
49
-	}
48
+        $this->backendService = $backendService;
49
+    }
50 50
 
51
-	protected function configure() {
52
-		$this
53
-			->setName('files_external:backends')
54
-			->setDescription('Show available authentication and storage backends')
55
-			->addArgument(
56
-				'type',
57
-				InputArgument::OPTIONAL,
58
-				'only show backends of a certain type. Possible values are "authentication" or "storage"'
59
-			)->addArgument(
60
-				'backend',
61
-				InputArgument::OPTIONAL,
62
-				'only show information of a specific backend'
63
-			);
64
-		parent::configure();
65
-	}
51
+    protected function configure() {
52
+        $this
53
+            ->setName('files_external:backends')
54
+            ->setDescription('Show available authentication and storage backends')
55
+            ->addArgument(
56
+                'type',
57
+                InputArgument::OPTIONAL,
58
+                'only show backends of a certain type. Possible values are "authentication" or "storage"'
59
+            )->addArgument(
60
+                'backend',
61
+                InputArgument::OPTIONAL,
62
+                'only show information of a specific backend'
63
+            );
64
+        parent::configure();
65
+    }
66 66
 
67
-	protected function execute(InputInterface $input, OutputInterface $output) {
68
-		$authBackends = $this->backendService->getAuthMechanisms();
69
-		$storageBackends = $this->backendService->getBackends();
67
+    protected function execute(InputInterface $input, OutputInterface $output) {
68
+        $authBackends = $this->backendService->getAuthMechanisms();
69
+        $storageBackends = $this->backendService->getBackends();
70 70
 
71
-		$data = [
72
-			'authentication' => array_map([$this, 'serializeAuthBackend'], $authBackends),
73
-			'storage' => array_map([$this, 'serializeAuthBackend'], $storageBackends)
74
-		];
71
+        $data = [
72
+            'authentication' => array_map([$this, 'serializeAuthBackend'], $authBackends),
73
+            'storage' => array_map([$this, 'serializeAuthBackend'], $storageBackends)
74
+        ];
75 75
 
76
-		$type = $input->getArgument('type');
77
-		$backend = $input->getArgument('backend');
78
-		if ($type) {
79
-			if (!isset($data[$type])) {
80
-				$output->writeln('<error>Invalid type "' . $type . '". Possible values are "authentication" or "storage"</error>');
81
-				return 1;
82
-			}
83
-			$data = $data[$type];
76
+        $type = $input->getArgument('type');
77
+        $backend = $input->getArgument('backend');
78
+        if ($type) {
79
+            if (!isset($data[$type])) {
80
+                $output->writeln('<error>Invalid type "' . $type . '". Possible values are "authentication" or "storage"</error>');
81
+                return 1;
82
+            }
83
+            $data = $data[$type];
84 84
 
85
-			if ($backend) {
86
-				if (!isset($data[$backend])) {
87
-					$output->writeln('<error>Unknown backend "' . $backend . '" of type  "' . $type . '"</error>');
88
-					return 1;
89
-				}
90
-				$data = $data[$backend];
91
-			}
92
-		}
85
+            if ($backend) {
86
+                if (!isset($data[$backend])) {
87
+                    $output->writeln('<error>Unknown backend "' . $backend . '" of type  "' . $type . '"</error>');
88
+                    return 1;
89
+                }
90
+                $data = $data[$backend];
91
+            }
92
+        }
93 93
 
94
-		$this->writeArrayInOutputFormat($input, $output, $data);
95
-	}
94
+        $this->writeArrayInOutputFormat($input, $output, $data);
95
+    }
96 96
 
97
-	private function serializeAuthBackend(\JsonSerializable $backend) {
98
-		$data = $backend->jsonSerialize();
99
-		$result = [
100
-			'name' => $data['name'],
101
-			'identifier' => $data['identifier'],
102
-			'configuration' => array_map(function (DefinitionParameter $parameter) {
103
-				return $parameter->getTypeName();
104
-			}, $data['configuration'])
105
-		];
106
-		if ($backend instanceof Backend) {
107
-			$result['storage_class'] = $backend->getStorageClass();
108
-			$authBackends = $this->backendService->getAuthMechanismsByScheme(array_keys($backend->getAuthSchemes()));
109
-			$result['supported_authentication_backends'] = array_keys($authBackends);
110
-		}
111
-		return $result;
112
-	}
97
+    private function serializeAuthBackend(\JsonSerializable $backend) {
98
+        $data = $backend->jsonSerialize();
99
+        $result = [
100
+            'name' => $data['name'],
101
+            'identifier' => $data['identifier'],
102
+            'configuration' => array_map(function (DefinitionParameter $parameter) {
103
+                return $parameter->getTypeName();
104
+            }, $data['configuration'])
105
+        ];
106
+        if ($backend instanceof Backend) {
107
+            $result['storage_class'] = $backend->getStorageClass();
108
+            $authBackends = $this->backendService->getAuthMechanismsByScheme(array_keys($backend->getAuthSchemes()));
109
+            $result['supported_authentication_backends'] = array_keys($authBackends);
110
+        }
111
+        return $result;
112
+    }
113 113
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -77,14 +77,14 @@  discard block
 block discarded – undo
77 77
 		$backend = $input->getArgument('backend');
78 78
 		if ($type) {
79 79
 			if (!isset($data[$type])) {
80
-				$output->writeln('<error>Invalid type "' . $type . '". Possible values are "authentication" or "storage"</error>');
80
+				$output->writeln('<error>Invalid type "'.$type.'". Possible values are "authentication" or "storage"</error>');
81 81
 				return 1;
82 82
 			}
83 83
 			$data = $data[$type];
84 84
 
85 85
 			if ($backend) {
86 86
 				if (!isset($data[$backend])) {
87
-					$output->writeln('<error>Unknown backend "' . $backend . '" of type  "' . $type . '"</error>');
87
+					$output->writeln('<error>Unknown backend "'.$backend.'" of type  "'.$type.'"</error>');
88 88
 					return 1;
89 89
 				}
90 90
 				$data = $data[$backend];
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
 		$result = [
100 100
 			'name' => $data['name'],
101 101
 			'identifier' => $data['identifier'],
102
-			'configuration' => array_map(function (DefinitionParameter $parameter) {
102
+			'configuration' => array_map(function(DefinitionParameter $parameter) {
103 103
 				return $parameter->getTypeName();
104 104
 			}, $data['configuration'])
105 105
 		];
Please login to merge, or discard this patch.
apps/files_external/command/create.php 3 patches
Unused Use Statements   -4 removed lines patch added patch discarded remove patch
@@ -30,18 +30,14 @@
 block discarded – undo
30 30
 use OCA\Files_external\Lib\StorageConfig;
31 31
 use OCA\Files_External\Service\BackendService;
32 32
 use OCA\Files_external\Service\GlobalStoragesService;
33
-use OCA\Files_external\Service\ImportLegacyStoragesService;
34 33
 use OCA\Files_external\Service\UserStoragesService;
35 34
 use OCP\IUserManager;
36 35
 use OCP\IUserSession;
37 36
 use Symfony\Component\Console\Command\Command;
38
-use Symfony\Component\Console\Helper\Table;
39
-use Symfony\Component\Console\Helper\TableHelper;
40 37
 use Symfony\Component\Console\Input\ArrayInput;
41 38
 use Symfony\Component\Console\Input\InputArgument;
42 39
 use Symfony\Component\Console\Input\InputInterface;
43 40
 use Symfony\Component\Console\Input\InputOption;
44
-use Symfony\Component\Console\Input\Input;
45 41
 use Symfony\Component\Console\Output\OutputInterface;
46 42
 
47 43
 class Create extends Base {
Please login to merge, or discard this patch.
Indentation   +178 added lines, -178 removed lines patch added patch discarded remove patch
@@ -42,182 +42,182 @@
 block discarded – undo
42 42
 use Symfony\Component\Console\Output\OutputInterface;
43 43
 
44 44
 class Create extends Base {
45
-	/**
46
-	 * @var GlobalStoragesService
47
-	 */
48
-	private $globalService;
49
-
50
-	/**
51
-	 * @var UserStoragesService
52
-	 */
53
-	private $userService;
54
-
55
-	/**
56
-	 * @var IUserManager
57
-	 */
58
-	private $userManager;
59
-
60
-	/** @var BackendService */
61
-	private $backendService;
62
-
63
-	/** @var IUserSession */
64
-	private $userSession;
65
-
66
-	function __construct(GlobalStoragesService $globalService,
67
-						 UserStoragesService $userService,
68
-						 IUserManager $userManager,
69
-						 IUserSession $userSession,
70
-						 BackendService $backendService
71
-	) {
72
-		parent::__construct();
73
-		$this->globalService = $globalService;
74
-		$this->userService = $userService;
75
-		$this->userManager = $userManager;
76
-		$this->userSession = $userSession;
77
-		$this->backendService = $backendService;
78
-	}
79
-
80
-	protected function configure() {
81
-		$this
82
-			->setName('files_external:create')
83
-			->setDescription('Create a new mount configuration')
84
-			->addOption(
85
-				'user',
86
-				null,
87
-				InputOption::VALUE_OPTIONAL,
88
-				'user to add the mount configuration for, if not set the mount will be added as system mount'
89
-			)
90
-			->addArgument(
91
-				'mount_point',
92
-				InputArgument::REQUIRED,
93
-				'mount point for the new mount'
94
-			)
95
-			->addArgument(
96
-				'storage_backend',
97
-				InputArgument::REQUIRED,
98
-				'storage backend identifier for the new mount, see `occ files_external:backends` for possible values'
99
-			)
100
-			->addArgument(
101
-				'authentication_backend',
102
-				InputArgument::REQUIRED,
103
-				'authentication backend identifier for the new mount, see `occ files_external:backends` for possible values'
104
-			)
105
-			->addOption(
106
-				'config',
107
-				'c',
108
-				InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
109
-				'Mount configuration option in key=value format'
110
-			)
111
-			->addOption(
112
-				'dry',
113
-				null,
114
-				InputOption::VALUE_NONE,
115
-				'Don\'t save the created mount, only list the new mount'
116
-			);
117
-		parent::configure();
118
-	}
119
-
120
-	protected function execute(InputInterface $input, OutputInterface $output) {
121
-		$user = $input->getOption('user');
122
-		$mountPoint = $input->getArgument('mount_point');
123
-		$storageIdentifier = $input->getArgument('storage_backend');
124
-		$authIdentifier = $input->getArgument('authentication_backend');
125
-		$configInput = $input->getOption('config');
126
-
127
-		$storageBackend = $this->backendService->getBackend($storageIdentifier);
128
-		$authBackend = $this->backendService->getAuthMechanism($authIdentifier);
129
-
130
-		if (!Filesystem::isValidPath($mountPoint)) {
131
-			$output->writeln('<error>Invalid mountpoint "' . $mountPoint . '"</error>');
132
-			return 1;
133
-		}
134
-		if (is_null($storageBackend)) {
135
-			$output->writeln('<error>Storage backend with identifier "' . $storageIdentifier . '" not found (see `occ files_external:backends` for possible values)</error>');
136
-			return 404;
137
-		}
138
-		if (is_null($authBackend)) {
139
-			$output->writeln('<error>Authentication backend with identifier "' . $authIdentifier . '" not found (see `occ files_external:backends` for possible values)</error>');
140
-			return 404;
141
-		}
142
-		$supportedSchemes = array_keys($storageBackend->getAuthSchemes());
143
-		if (!in_array($authBackend->getScheme(), $supportedSchemes)) {
144
-			$output->writeln('<error>Authentication backend "' . $authIdentifier . '" not valid for storage backend "' . $storageIdentifier . '" (see `occ files_external:backends storage ' . $storageIdentifier . '` for possible values)</error>');
145
-			return 1;
146
-		}
147
-
148
-		$config = [];
149
-		foreach ($configInput as $configOption) {
150
-			if (!strpos($configOption, '=')) {
151
-				$output->writeln('<error>Invalid mount configuration option "' . $configOption . '"</error>');
152
-				return 1;
153
-			}
154
-			list($key, $value) = explode('=', $configOption, 2);
155
-			if (!$this->validateParam($key, $value, $storageBackend, $authBackend)) {
156
-				$output->writeln('<error>Unknown configuration for backends "' . $key . '"</error>');
157
-				return 1;
158
-			}
159
-			$config[$key] = $value;
160
-		}
161
-
162
-		$mount = new StorageConfig();
163
-		$mount->setMountPoint($mountPoint);
164
-		$mount->setBackend($storageBackend);
165
-		$mount->setAuthMechanism($authBackend);
166
-		$mount->setBackendOptions($config);
167
-
168
-		if ($user) {
169
-			if (!$this->userManager->userExists($user)) {
170
-				$output->writeln('<error>User "' . $user . '" not found</error>');
171
-				return 1;
172
-			}
173
-			$mount->setApplicableUsers([$user]);
174
-		}
175
-
176
-		if ($input->getOption('dry')) {
177
-			$this->showMount($user, $mount, $input, $output);
178
-		} else {
179
-			$this->getStorageService($user)->addStorage($mount);
180
-			if ($input->getOption('output') === self::OUTPUT_FORMAT_PLAIN) {
181
-				$output->writeln('<info>Storage created with id ' . $mount->getId() . '</info>');
182
-			} else {
183
-				$output->writeln($mount->getId());
184
-			}
185
-		}
186
-		return 0;
187
-	}
188
-
189
-	private function validateParam($key, &$value, Backend $storageBackend, AuthMechanism $authBackend) {
190
-		$params = array_merge($storageBackend->getParameters(), $authBackend->getParameters());
191
-		foreach ($params as $param) {
192
-			/** @var DefinitionParameter $param */
193
-			if ($param->getName() === $key) {
194
-				if ($param->getType() === DefinitionParameter::VALUE_BOOLEAN) {
195
-					$value = ($value === 'true');
196
-				}
197
-				return true;
198
-			}
199
-		}
200
-		return false;
201
-	}
202
-
203
-	private function showMount($user, StorageConfig $mount, InputInterface $input, OutputInterface $output) {
204
-		$listCommand = new ListCommand($this->globalService, $this->userService, $this->userSession, $this->userManager);
205
-		$listInput = new ArrayInput([], $listCommand->getDefinition());
206
-		$listInput->setOption('output', $input->getOption('output'));
207
-		$listInput->setOption('show-password', true);
208
-		$listCommand->listMounts($user, [$mount], $listInput, $output);
209
-	}
210
-
211
-	protected function getStorageService($userId) {
212
-		if (!empty($userId)) {
213
-			$user = $this->userManager->get($userId);
214
-			if (is_null($user)) {
215
-				throw new NoUserException("user $userId not found");
216
-			}
217
-			$this->userSession->setUser($user);
218
-			return $this->userService;
219
-		} else {
220
-			return $this->globalService;
221
-		}
222
-	}
45
+    /**
46
+     * @var GlobalStoragesService
47
+     */
48
+    private $globalService;
49
+
50
+    /**
51
+     * @var UserStoragesService
52
+     */
53
+    private $userService;
54
+
55
+    /**
56
+     * @var IUserManager
57
+     */
58
+    private $userManager;
59
+
60
+    /** @var BackendService */
61
+    private $backendService;
62
+
63
+    /** @var IUserSession */
64
+    private $userSession;
65
+
66
+    function __construct(GlobalStoragesService $globalService,
67
+                            UserStoragesService $userService,
68
+                            IUserManager $userManager,
69
+                            IUserSession $userSession,
70
+                            BackendService $backendService
71
+    ) {
72
+        parent::__construct();
73
+        $this->globalService = $globalService;
74
+        $this->userService = $userService;
75
+        $this->userManager = $userManager;
76
+        $this->userSession = $userSession;
77
+        $this->backendService = $backendService;
78
+    }
79
+
80
+    protected function configure() {
81
+        $this
82
+            ->setName('files_external:create')
83
+            ->setDescription('Create a new mount configuration')
84
+            ->addOption(
85
+                'user',
86
+                null,
87
+                InputOption::VALUE_OPTIONAL,
88
+                'user to add the mount configuration for, if not set the mount will be added as system mount'
89
+            )
90
+            ->addArgument(
91
+                'mount_point',
92
+                InputArgument::REQUIRED,
93
+                'mount point for the new mount'
94
+            )
95
+            ->addArgument(
96
+                'storage_backend',
97
+                InputArgument::REQUIRED,
98
+                'storage backend identifier for the new mount, see `occ files_external:backends` for possible values'
99
+            )
100
+            ->addArgument(
101
+                'authentication_backend',
102
+                InputArgument::REQUIRED,
103
+                'authentication backend identifier for the new mount, see `occ files_external:backends` for possible values'
104
+            )
105
+            ->addOption(
106
+                'config',
107
+                'c',
108
+                InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
109
+                'Mount configuration option in key=value format'
110
+            )
111
+            ->addOption(
112
+                'dry',
113
+                null,
114
+                InputOption::VALUE_NONE,
115
+                'Don\'t save the created mount, only list the new mount'
116
+            );
117
+        parent::configure();
118
+    }
119
+
120
+    protected function execute(InputInterface $input, OutputInterface $output) {
121
+        $user = $input->getOption('user');
122
+        $mountPoint = $input->getArgument('mount_point');
123
+        $storageIdentifier = $input->getArgument('storage_backend');
124
+        $authIdentifier = $input->getArgument('authentication_backend');
125
+        $configInput = $input->getOption('config');
126
+
127
+        $storageBackend = $this->backendService->getBackend($storageIdentifier);
128
+        $authBackend = $this->backendService->getAuthMechanism($authIdentifier);
129
+
130
+        if (!Filesystem::isValidPath($mountPoint)) {
131
+            $output->writeln('<error>Invalid mountpoint "' . $mountPoint . '"</error>');
132
+            return 1;
133
+        }
134
+        if (is_null($storageBackend)) {
135
+            $output->writeln('<error>Storage backend with identifier "' . $storageIdentifier . '" not found (see `occ files_external:backends` for possible values)</error>');
136
+            return 404;
137
+        }
138
+        if (is_null($authBackend)) {
139
+            $output->writeln('<error>Authentication backend with identifier "' . $authIdentifier . '" not found (see `occ files_external:backends` for possible values)</error>');
140
+            return 404;
141
+        }
142
+        $supportedSchemes = array_keys($storageBackend->getAuthSchemes());
143
+        if (!in_array($authBackend->getScheme(), $supportedSchemes)) {
144
+            $output->writeln('<error>Authentication backend "' . $authIdentifier . '" not valid for storage backend "' . $storageIdentifier . '" (see `occ files_external:backends storage ' . $storageIdentifier . '` for possible values)</error>');
145
+            return 1;
146
+        }
147
+
148
+        $config = [];
149
+        foreach ($configInput as $configOption) {
150
+            if (!strpos($configOption, '=')) {
151
+                $output->writeln('<error>Invalid mount configuration option "' . $configOption . '"</error>');
152
+                return 1;
153
+            }
154
+            list($key, $value) = explode('=', $configOption, 2);
155
+            if (!$this->validateParam($key, $value, $storageBackend, $authBackend)) {
156
+                $output->writeln('<error>Unknown configuration for backends "' . $key . '"</error>');
157
+                return 1;
158
+            }
159
+            $config[$key] = $value;
160
+        }
161
+
162
+        $mount = new StorageConfig();
163
+        $mount->setMountPoint($mountPoint);
164
+        $mount->setBackend($storageBackend);
165
+        $mount->setAuthMechanism($authBackend);
166
+        $mount->setBackendOptions($config);
167
+
168
+        if ($user) {
169
+            if (!$this->userManager->userExists($user)) {
170
+                $output->writeln('<error>User "' . $user . '" not found</error>');
171
+                return 1;
172
+            }
173
+            $mount->setApplicableUsers([$user]);
174
+        }
175
+
176
+        if ($input->getOption('dry')) {
177
+            $this->showMount($user, $mount, $input, $output);
178
+        } else {
179
+            $this->getStorageService($user)->addStorage($mount);
180
+            if ($input->getOption('output') === self::OUTPUT_FORMAT_PLAIN) {
181
+                $output->writeln('<info>Storage created with id ' . $mount->getId() . '</info>');
182
+            } else {
183
+                $output->writeln($mount->getId());
184
+            }
185
+        }
186
+        return 0;
187
+    }
188
+
189
+    private function validateParam($key, &$value, Backend $storageBackend, AuthMechanism $authBackend) {
190
+        $params = array_merge($storageBackend->getParameters(), $authBackend->getParameters());
191
+        foreach ($params as $param) {
192
+            /** @var DefinitionParameter $param */
193
+            if ($param->getName() === $key) {
194
+                if ($param->getType() === DefinitionParameter::VALUE_BOOLEAN) {
195
+                    $value = ($value === 'true');
196
+                }
197
+                return true;
198
+            }
199
+        }
200
+        return false;
201
+    }
202
+
203
+    private function showMount($user, StorageConfig $mount, InputInterface $input, OutputInterface $output) {
204
+        $listCommand = new ListCommand($this->globalService, $this->userService, $this->userSession, $this->userManager);
205
+        $listInput = new ArrayInput([], $listCommand->getDefinition());
206
+        $listInput->setOption('output', $input->getOption('output'));
207
+        $listInput->setOption('show-password', true);
208
+        $listCommand->listMounts($user, [$mount], $listInput, $output);
209
+    }
210
+
211
+    protected function getStorageService($userId) {
212
+        if (!empty($userId)) {
213
+            $user = $this->userManager->get($userId);
214
+            if (is_null($user)) {
215
+                throw new NoUserException("user $userId not found");
216
+            }
217
+            $this->userSession->setUser($user);
218
+            return $this->userService;
219
+        } else {
220
+            return $this->globalService;
221
+        }
222
+    }
223 223
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -128,32 +128,32 @@  discard block
 block discarded – undo
128 128
 		$authBackend = $this->backendService->getAuthMechanism($authIdentifier);
129 129
 
130 130
 		if (!Filesystem::isValidPath($mountPoint)) {
131
-			$output->writeln('<error>Invalid mountpoint "' . $mountPoint . '"</error>');
131
+			$output->writeln('<error>Invalid mountpoint "'.$mountPoint.'"</error>');
132 132
 			return 1;
133 133
 		}
134 134
 		if (is_null($storageBackend)) {
135
-			$output->writeln('<error>Storage backend with identifier "' . $storageIdentifier . '" not found (see `occ files_external:backends` for possible values)</error>');
135
+			$output->writeln('<error>Storage backend with identifier "'.$storageIdentifier.'" not found (see `occ files_external:backends` for possible values)</error>');
136 136
 			return 404;
137 137
 		}
138 138
 		if (is_null($authBackend)) {
139
-			$output->writeln('<error>Authentication backend with identifier "' . $authIdentifier . '" not found (see `occ files_external:backends` for possible values)</error>');
139
+			$output->writeln('<error>Authentication backend with identifier "'.$authIdentifier.'" not found (see `occ files_external:backends` for possible values)</error>');
140 140
 			return 404;
141 141
 		}
142 142
 		$supportedSchemes = array_keys($storageBackend->getAuthSchemes());
143 143
 		if (!in_array($authBackend->getScheme(), $supportedSchemes)) {
144
-			$output->writeln('<error>Authentication backend "' . $authIdentifier . '" not valid for storage backend "' . $storageIdentifier . '" (see `occ files_external:backends storage ' . $storageIdentifier . '` for possible values)</error>');
144
+			$output->writeln('<error>Authentication backend "'.$authIdentifier.'" not valid for storage backend "'.$storageIdentifier.'" (see `occ files_external:backends storage '.$storageIdentifier.'` for possible values)</error>');
145 145
 			return 1;
146 146
 		}
147 147
 
148 148
 		$config = [];
149 149
 		foreach ($configInput as $configOption) {
150 150
 			if (!strpos($configOption, '=')) {
151
-				$output->writeln('<error>Invalid mount configuration option "' . $configOption . '"</error>');
151
+				$output->writeln('<error>Invalid mount configuration option "'.$configOption.'"</error>');
152 152
 				return 1;
153 153
 			}
154 154
 			list($key, $value) = explode('=', $configOption, 2);
155 155
 			if (!$this->validateParam($key, $value, $storageBackend, $authBackend)) {
156
-				$output->writeln('<error>Unknown configuration for backends "' . $key . '"</error>');
156
+				$output->writeln('<error>Unknown configuration for backends "'.$key.'"</error>');
157 157
 				return 1;
158 158
 			}
159 159
 			$config[$key] = $value;
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 
168 168
 		if ($user) {
169 169
 			if (!$this->userManager->userExists($user)) {
170
-				$output->writeln('<error>User "' . $user . '" not found</error>');
170
+				$output->writeln('<error>User "'.$user.'" not found</error>');
171 171
 				return 1;
172 172
 			}
173 173
 			$mount->setApplicableUsers([$user]);
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 		} else {
179 179
 			$this->getStorageService($user)->addStorage($mount);
180 180
 			if ($input->getOption('output') === self::OUTPUT_FORMAT_PLAIN) {
181
-				$output->writeln('<info>Storage created with id ' . $mount->getId() . '</info>');
181
+				$output->writeln('<info>Storage created with id '.$mount->getId().'</info>');
182 182
 			} else {
183 183
 				$output->writeln($mount->getId());
184 184
 			}
Please login to merge, or discard this patch.
apps/files_external/command/delete.php 3 patches
Unused Use Statements   -3 removed lines patch added patch discarded remove patch
@@ -22,15 +22,12 @@
 block discarded – undo
22 22
 namespace OCA\Files_External\Command;
23 23
 
24 24
 use OC\Core\Command\Base;
25
-use OCA\Files_external\Lib\StorageConfig;
26 25
 use OCA\Files_external\NotFoundException;
27 26
 use OCA\Files_external\Service\GlobalStoragesService;
28 27
 use OCA\Files_external\Service\UserStoragesService;
29 28
 use OCP\IUserManager;
30 29
 use OCP\IUserSession;
31 30
 use Symfony\Component\Console\Command\Command;
32
-use Symfony\Component\Console\Helper\Table;
33
-use Symfony\Component\Console\Helper\TableHelper;
34 31
 use Symfony\Component\Console\Input\ArrayInput;
35 32
 use Symfony\Component\Console\Input\InputArgument;
36 33
 use Symfony\Component\Console\Input\InputInterface;
Please login to merge, or discard this patch.
Indentation   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -37,76 +37,76 @@
 block discarded – undo
37 37
 use Symfony\Component\Console\Question\ConfirmationQuestion;
38 38
 
39 39
 class Delete extends Base {
40
-	/**
41
-	 * @var GlobalStoragesService
42
-	 */
43
-	protected $globalService;
40
+    /**
41
+     * @var GlobalStoragesService
42
+     */
43
+    protected $globalService;
44 44
 
45
-	/**
46
-	 * @var UserStoragesService
47
-	 */
48
-	protected $userService;
45
+    /**
46
+     * @var UserStoragesService
47
+     */
48
+    protected $userService;
49 49
 
50
-	/**
51
-	 * @var IUserSession
52
-	 */
53
-	protected $userSession;
50
+    /**
51
+     * @var IUserSession
52
+     */
53
+    protected $userSession;
54 54
 
55
-	/**
56
-	 * @var IUserManager
57
-	 */
58
-	protected $userManager;
55
+    /**
56
+     * @var IUserManager
57
+     */
58
+    protected $userManager;
59 59
 
60
-	function __construct(GlobalStoragesService $globalService, UserStoragesService $userService, IUserSession $userSession, IUserManager $userManager) {
61
-		parent::__construct();
62
-		$this->globalService = $globalService;
63
-		$this->userService = $userService;
64
-		$this->userSession = $userSession;
65
-		$this->userManager = $userManager;
66
-	}
60
+    function __construct(GlobalStoragesService $globalService, UserStoragesService $userService, IUserSession $userSession, IUserManager $userManager) {
61
+        parent::__construct();
62
+        $this->globalService = $globalService;
63
+        $this->userService = $userService;
64
+        $this->userSession = $userSession;
65
+        $this->userManager = $userManager;
66
+    }
67 67
 
68
-	protected function configure() {
69
-		$this
70
-			->setName('files_external:delete')
71
-			->setDescription('Delete an external mount')
72
-			->addArgument(
73
-				'mount_id',
74
-				InputArgument::REQUIRED,
75
-				'The id of the mount to edit'
76
-			)->addOption(
77
-				'yes',
78
-				'y',
79
-				InputOption::VALUE_NONE,
80
-				'Skip confirmation'
81
-			);
82
-		parent::configure();
83
-	}
68
+    protected function configure() {
69
+        $this
70
+            ->setName('files_external:delete')
71
+            ->setDescription('Delete an external mount')
72
+            ->addArgument(
73
+                'mount_id',
74
+                InputArgument::REQUIRED,
75
+                'The id of the mount to edit'
76
+            )->addOption(
77
+                'yes',
78
+                'y',
79
+                InputOption::VALUE_NONE,
80
+                'Skip confirmation'
81
+            );
82
+        parent::configure();
83
+    }
84 84
 
85
-	protected function execute(InputInterface $input, OutputInterface $output) {
86
-		$mountId = $input->getArgument('mount_id');
87
-		try {
88
-			$mount = $this->globalService->getStorage($mountId);
89
-		} catch (NotFoundException $e) {
90
-			$output->writeln('<error>Mount with id "' . $mountId . ' not found, check "occ files_external:list" to get available mounts"</error>');
91
-			return 404;
92
-		}
85
+    protected function execute(InputInterface $input, OutputInterface $output) {
86
+        $mountId = $input->getArgument('mount_id');
87
+        try {
88
+            $mount = $this->globalService->getStorage($mountId);
89
+        } catch (NotFoundException $e) {
90
+            $output->writeln('<error>Mount with id "' . $mountId . ' not found, check "occ files_external:list" to get available mounts"</error>');
91
+            return 404;
92
+        }
93 93
 
94
-		$noConfirm = $input->getOption('yes');
94
+        $noConfirm = $input->getOption('yes');
95 95
 
96
-		if (!$noConfirm) {
97
-			$listCommand = new ListCommand($this->globalService, $this->userService, $this->userSession, $this->userManager);
98
-			$listInput = new ArrayInput([], $listCommand->getDefinition());
99
-			$listInput->setOption('output', $input->getOption('output'));
100
-			$listCommand->listMounts(null, [$mount], $listInput, $output);
96
+        if (!$noConfirm) {
97
+            $listCommand = new ListCommand($this->globalService, $this->userService, $this->userSession, $this->userManager);
98
+            $listInput = new ArrayInput([], $listCommand->getDefinition());
99
+            $listInput->setOption('output', $input->getOption('output'));
100
+            $listCommand->listMounts(null, [$mount], $listInput, $output);
101 101
 
102
-			$questionHelper = $this->getHelper('question');
103
-			$question = new ConfirmationQuestion('Delete this mount? [y/N] ', false);
102
+            $questionHelper = $this->getHelper('question');
103
+            $question = new ConfirmationQuestion('Delete this mount? [y/N] ', false);
104 104
 
105
-			if (!$questionHelper->ask($input, $output, $question)) {
106
-				return;
107
-			}
108
-		}
105
+            if (!$questionHelper->ask($input, $output, $question)) {
106
+                return;
107
+            }
108
+        }
109 109
 
110
-		$this->globalService->removeStorage($mountId);
111
-	}
110
+        $this->globalService->removeStorage($mountId);
111
+    }
112 112
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@
 block discarded – undo
68 68
 		try {
69 69
 			$mount = $this->globalService->getStorage($mountId);
70 70
 		} catch (NotFoundException $e) {
71
-			$output->writeln('<error>Mount with id "' . $mountId . ' not found, check "occ files_external:list" to get available mounts"</error>');
71
+			$output->writeln('<error>Mount with id "'.$mountId.' not found, check "occ files_external:list" to get available mounts"</error>');
72 72
 			return 404;
73 73
 		}
74 74
 
Please login to merge, or discard this patch.
apps/files_external/command/import.php 3 patches
Unused Use Statements   -3 removed lines patch added patch discarded remove patch
@@ -31,13 +31,10 @@
 block discarded – undo
31 31
 use OCP\IUserManager;
32 32
 use OCP\IUserSession;
33 33
 use Symfony\Component\Console\Command\Command;
34
-use Symfony\Component\Console\Helper\Table;
35
-use Symfony\Component\Console\Helper\TableHelper;
36 34
 use Symfony\Component\Console\Input\ArrayInput;
37 35
 use Symfony\Component\Console\Input\InputArgument;
38 36
 use Symfony\Component\Console\Input\InputInterface;
39 37
 use Symfony\Component\Console\Input\InputOption;
40
-use Symfony\Component\Console\Input\Input;
41 38
 use Symfony\Component\Console\Output\OutputInterface;
42 39
 
43 40
 class Import extends Base {
Please login to merge, or discard this patch.
Indentation   +183 added lines, -183 removed lines patch added patch discarded remove patch
@@ -39,187 +39,187 @@
 block discarded – undo
39 39
 use Symfony\Component\Console\Output\OutputInterface;
40 40
 
41 41
 class Import extends Base {
42
-	/**
43
-	 * @var GlobalStoragesService
44
-	 */
45
-	private $globalService;
46
-
47
-	/**
48
-	 * @var UserStoragesService
49
-	 */
50
-	private $userService;
51
-
52
-	/**
53
-	 * @var IUserSession
54
-	 */
55
-	private $userSession;
56
-
57
-	/**
58
-	 * @var IUserManager
59
-	 */
60
-	private $userManager;
61
-
62
-	/** @var ImportLegacyStoragesService */
63
-	private $importLegacyStorageService;
64
-
65
-	/** @var BackendService */
66
-	private $backendService;
67
-
68
-	function __construct(GlobalStoragesService $globalService,
69
-						 UserStoragesService $userService,
70
-						 IUserSession $userSession,
71
-						 IUserManager $userManager,
72
-						 ImportLegacyStoragesService $importLegacyStorageService,
73
-						 BackendService $backendService
74
-	) {
75
-		parent::__construct();
76
-		$this->globalService = $globalService;
77
-		$this->userService = $userService;
78
-		$this->userSession = $userSession;
79
-		$this->userManager = $userManager;
80
-		$this->importLegacyStorageService = $importLegacyStorageService;
81
-		$this->backendService = $backendService;
82
-	}
83
-
84
-	protected function configure() {
85
-		$this
86
-			->setName('files_external:import')
87
-			->setDescription('Import mount configurations')
88
-			->addOption(
89
-				'user',
90
-				null,
91
-				InputOption::VALUE_OPTIONAL,
92
-				'user to add the mount configurations for, if not set the mount will be added as system mount'
93
-			)
94
-			->addArgument(
95
-				'path',
96
-				InputArgument::REQUIRED,
97
-				'path to a json file containing the mounts to import, use "-" to read from stdin'
98
-			)
99
-			->addOption(
100
-				'dry',
101
-				null,
102
-				InputOption::VALUE_NONE,
103
-				'Don\'t save the imported mounts, only list the new mounts'
104
-			);
105
-		parent::configure();
106
-	}
107
-
108
-	protected function execute(InputInterface $input, OutputInterface $output) {
109
-		$user = $input->getOption('user');
110
-		$path = $input->getArgument('path');
111
-		if ($path === '-') {
112
-			$json = file_get_contents('php://stdin');
113
-		} else {
114
-			if (!file_exists($path)) {
115
-				$output->writeln('<error>File not found: ' . $path . '</error>');
116
-				return 1;
117
-			}
118
-			$json = file_get_contents($path);
119
-		}
120
-		if (!is_string($json) || strlen($json) < 2) {
121
-			$output->writeln('<error>Error while reading json</error>');
122
-			return 1;
123
-		}
124
-		$data = json_decode($json, true);
125
-		if (!is_array($data)) {
126
-			$output->writeln('<error>Error while parsing json</error>');
127
-			return 1;
128
-		}
129
-
130
-		$isLegacy = isset($data['user']) || isset($data['group']);
131
-		if ($isLegacy) {
132
-			$this->importLegacyStorageService->setData($data);
133
-			$mounts = $this->importLegacyStorageService->getAllStorages();
134
-			foreach ($mounts as $mount) {
135
-				if ($mount->getBackendOption('password') === false) {
136
-					$output->writeln('<error>Failed to decrypt password</error>');
137
-					return 1;
138
-				}
139
-			}
140
-		} else {
141
-			if (!isset($data[0])) { //normalize to an array of mounts
142
-				$data = [$data];
143
-			}
144
-			$mounts = array_map([$this, 'parseData'], $data);
145
-		}
146
-
147
-		if ($user) {
148
-			// ensure applicables are correct for personal mounts
149
-			foreach ($mounts as $mount) {
150
-				$mount->setApplicableGroups([]);
151
-				$mount->setApplicableUsers([$user]);
152
-			}
153
-		}
154
-
155
-		$storageService = $this->getStorageService($user);
156
-
157
-		$existingMounts = $storageService->getAllStorages();
158
-
159
-		foreach ($mounts as $mount) {
160
-			foreach ($existingMounts as $existingMount) {
161
-				if (
162
-					$existingMount->getMountPoint() === $mount->getMountPoint() &&
163
-					$existingMount->getApplicableGroups() === $mount->getApplicableGroups() &&
164
-					$existingMount->getApplicableUsers() == $mount->getApplicableUsers() &&
165
-					$existingMount->getBackendOptions() == $mount->getBackendOptions()
166
-				) {
167
-					$output->writeln("<error>Duplicate mount (" . $mount->getMountPoint() . ")</error>");
168
-					return 1;
169
-				}
170
-			}
171
-		}
172
-
173
-		if ($input->getOption('dry')) {
174
-			if (count($mounts) === 0) {
175
-				$output->writeln('<error>No mounts to be imported</error>');
176
-				return 1;
177
-			}
178
-			$listCommand = new ListCommand($this->globalService, $this->userService, $this->userSession, $this->userManager);
179
-			$listInput = new ArrayInput([], $listCommand->getDefinition());
180
-			$listInput->setOption('output', $input->getOption('output'));
181
-			$listInput->setOption('show-password', true);
182
-			$listCommand->listMounts($user, $mounts, $listInput, $output);
183
-		} else {
184
-			foreach ($mounts as $mount) {
185
-				$storageService->addStorage($mount);
186
-			}
187
-		}
188
-		return 0;
189
-	}
190
-
191
-	private function parseData(array $data) {
192
-		$mount = new StorageConfig($data['mount_id']);
193
-		$mount->setMountPoint($data['mount_point']);
194
-		$mount->setBackend($this->getBackendByClass($data['storage']));
195
-		$authBackend = $this->backendService->getAuthMechanism($data['authentication_type']);
196
-		$mount->setAuthMechanism($authBackend);
197
-		$mount->setBackendOptions($data['configuration']);
198
-		$mount->setMountOptions($data['options']);
199
-		$mount->setApplicableUsers(isset($data['applicable_users']) ? $data['applicable_users'] : []);
200
-		$mount->setApplicableGroups(isset($data['applicable_groups']) ? $data['applicable_groups'] : []);
201
-		return $mount;
202
-	}
203
-
204
-	private function getBackendByClass($className) {
205
-		$backends = $this->backendService->getBackends();
206
-		foreach ($backends as $backend) {
207
-			if ($backend->getStorageClass() === $className) {
208
-				return $backend;
209
-			}
210
-		}
211
-	}
212
-
213
-	protected function getStorageService($userId) {
214
-		if (!empty($userId)) {
215
-			$user = $this->userManager->get($userId);
216
-			if (is_null($user)) {
217
-				throw new NoUserException("user $userId not found");
218
-			}
219
-			$this->userSession->setUser($user);
220
-			return $this->userService;
221
-		} else {
222
-			return $this->globalService;
223
-		}
224
-	}
42
+    /**
43
+     * @var GlobalStoragesService
44
+     */
45
+    private $globalService;
46
+
47
+    /**
48
+     * @var UserStoragesService
49
+     */
50
+    private $userService;
51
+
52
+    /**
53
+     * @var IUserSession
54
+     */
55
+    private $userSession;
56
+
57
+    /**
58
+     * @var IUserManager
59
+     */
60
+    private $userManager;
61
+
62
+    /** @var ImportLegacyStoragesService */
63
+    private $importLegacyStorageService;
64
+
65
+    /** @var BackendService */
66
+    private $backendService;
67
+
68
+    function __construct(GlobalStoragesService $globalService,
69
+                            UserStoragesService $userService,
70
+                            IUserSession $userSession,
71
+                            IUserManager $userManager,
72
+                            ImportLegacyStoragesService $importLegacyStorageService,
73
+                            BackendService $backendService
74
+    ) {
75
+        parent::__construct();
76
+        $this->globalService = $globalService;
77
+        $this->userService = $userService;
78
+        $this->userSession = $userSession;
79
+        $this->userManager = $userManager;
80
+        $this->importLegacyStorageService = $importLegacyStorageService;
81
+        $this->backendService = $backendService;
82
+    }
83
+
84
+    protected function configure() {
85
+        $this
86
+            ->setName('files_external:import')
87
+            ->setDescription('Import mount configurations')
88
+            ->addOption(
89
+                'user',
90
+                null,
91
+                InputOption::VALUE_OPTIONAL,
92
+                'user to add the mount configurations for, if not set the mount will be added as system mount'
93
+            )
94
+            ->addArgument(
95
+                'path',
96
+                InputArgument::REQUIRED,
97
+                'path to a json file containing the mounts to import, use "-" to read from stdin'
98
+            )
99
+            ->addOption(
100
+                'dry',
101
+                null,
102
+                InputOption::VALUE_NONE,
103
+                'Don\'t save the imported mounts, only list the new mounts'
104
+            );
105
+        parent::configure();
106
+    }
107
+
108
+    protected function execute(InputInterface $input, OutputInterface $output) {
109
+        $user = $input->getOption('user');
110
+        $path = $input->getArgument('path');
111
+        if ($path === '-') {
112
+            $json = file_get_contents('php://stdin');
113
+        } else {
114
+            if (!file_exists($path)) {
115
+                $output->writeln('<error>File not found: ' . $path . '</error>');
116
+                return 1;
117
+            }
118
+            $json = file_get_contents($path);
119
+        }
120
+        if (!is_string($json) || strlen($json) < 2) {
121
+            $output->writeln('<error>Error while reading json</error>');
122
+            return 1;
123
+        }
124
+        $data = json_decode($json, true);
125
+        if (!is_array($data)) {
126
+            $output->writeln('<error>Error while parsing json</error>');
127
+            return 1;
128
+        }
129
+
130
+        $isLegacy = isset($data['user']) || isset($data['group']);
131
+        if ($isLegacy) {
132
+            $this->importLegacyStorageService->setData($data);
133
+            $mounts = $this->importLegacyStorageService->getAllStorages();
134
+            foreach ($mounts as $mount) {
135
+                if ($mount->getBackendOption('password') === false) {
136
+                    $output->writeln('<error>Failed to decrypt password</error>');
137
+                    return 1;
138
+                }
139
+            }
140
+        } else {
141
+            if (!isset($data[0])) { //normalize to an array of mounts
142
+                $data = [$data];
143
+            }
144
+            $mounts = array_map([$this, 'parseData'], $data);
145
+        }
146
+
147
+        if ($user) {
148
+            // ensure applicables are correct for personal mounts
149
+            foreach ($mounts as $mount) {
150
+                $mount->setApplicableGroups([]);
151
+                $mount->setApplicableUsers([$user]);
152
+            }
153
+        }
154
+
155
+        $storageService = $this->getStorageService($user);
156
+
157
+        $existingMounts = $storageService->getAllStorages();
158
+
159
+        foreach ($mounts as $mount) {
160
+            foreach ($existingMounts as $existingMount) {
161
+                if (
162
+                    $existingMount->getMountPoint() === $mount->getMountPoint() &&
163
+                    $existingMount->getApplicableGroups() === $mount->getApplicableGroups() &&
164
+                    $existingMount->getApplicableUsers() == $mount->getApplicableUsers() &&
165
+                    $existingMount->getBackendOptions() == $mount->getBackendOptions()
166
+                ) {
167
+                    $output->writeln("<error>Duplicate mount (" . $mount->getMountPoint() . ")</error>");
168
+                    return 1;
169
+                }
170
+            }
171
+        }
172
+
173
+        if ($input->getOption('dry')) {
174
+            if (count($mounts) === 0) {
175
+                $output->writeln('<error>No mounts to be imported</error>');
176
+                return 1;
177
+            }
178
+            $listCommand = new ListCommand($this->globalService, $this->userService, $this->userSession, $this->userManager);
179
+            $listInput = new ArrayInput([], $listCommand->getDefinition());
180
+            $listInput->setOption('output', $input->getOption('output'));
181
+            $listInput->setOption('show-password', true);
182
+            $listCommand->listMounts($user, $mounts, $listInput, $output);
183
+        } else {
184
+            foreach ($mounts as $mount) {
185
+                $storageService->addStorage($mount);
186
+            }
187
+        }
188
+        return 0;
189
+    }
190
+
191
+    private function parseData(array $data) {
192
+        $mount = new StorageConfig($data['mount_id']);
193
+        $mount->setMountPoint($data['mount_point']);
194
+        $mount->setBackend($this->getBackendByClass($data['storage']));
195
+        $authBackend = $this->backendService->getAuthMechanism($data['authentication_type']);
196
+        $mount->setAuthMechanism($authBackend);
197
+        $mount->setBackendOptions($data['configuration']);
198
+        $mount->setMountOptions($data['options']);
199
+        $mount->setApplicableUsers(isset($data['applicable_users']) ? $data['applicable_users'] : []);
200
+        $mount->setApplicableGroups(isset($data['applicable_groups']) ? $data['applicable_groups'] : []);
201
+        return $mount;
202
+    }
203
+
204
+    private function getBackendByClass($className) {
205
+        $backends = $this->backendService->getBackends();
206
+        foreach ($backends as $backend) {
207
+            if ($backend->getStorageClass() === $className) {
208
+                return $backend;
209
+            }
210
+        }
211
+    }
212
+
213
+    protected function getStorageService($userId) {
214
+        if (!empty($userId)) {
215
+            $user = $this->userManager->get($userId);
216
+            if (is_null($user)) {
217
+                throw new NoUserException("user $userId not found");
218
+            }
219
+            $this->userSession->setUser($user);
220
+            return $this->userService;
221
+        } else {
222
+            return $this->globalService;
223
+        }
224
+    }
225 225
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -112,7 +112,7 @@  discard block
 block discarded – undo
112 112
 			$json = file_get_contents('php://stdin');
113 113
 		} else {
114 114
 			if (!file_exists($path)) {
115
-				$output->writeln('<error>File not found: ' . $path . '</error>');
115
+				$output->writeln('<error>File not found: '.$path.'</error>');
116 116
 				return 1;
117 117
 			}
118 118
 			$json = file_get_contents($path);
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
 					$existingMount->getApplicableUsers() == $mount->getApplicableUsers() &&
165 165
 					$existingMount->getBackendOptions() == $mount->getBackendOptions()
166 166
 				) {
167
-					$output->writeln("<error>Duplicate mount (" . $mount->getMountPoint() . ")</error>");
167
+					$output->writeln("<error>Duplicate mount (".$mount->getMountPoint().")</error>");
168 168
 					return 1;
169 169
 				}
170 170
 			}
Please login to merge, or discard this patch.
apps/files_external/command/verify.php 3 patches
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -30,8 +30,6 @@
 block discarded – undo
30 30
 use OCA\Files_external\Service\GlobalStoragesService;
31 31
 use OCP\Files\StorageNotAvailableException;
32 32
 use Symfony\Component\Console\Command\Command;
33
-use Symfony\Component\Console\Helper\Table;
34
-use Symfony\Component\Console\Helper\TableHelper;
35 33
 use Symfony\Component\Console\Input\InputArgument;
36 34
 use Symfony\Component\Console\Input\InputInterface;
37 35
 use Symfony\Component\Console\Input\InputOption;
Please login to merge, or discard this patch.
Indentation   +94 added lines, -94 removed lines patch added patch discarded remove patch
@@ -37,108 +37,108 @@
 block discarded – undo
37 37
 use Symfony\Component\Console\Output\OutputInterface;
38 38
 
39 39
 class Verify extends Base {
40
-	/**
41
-	 * @var GlobalStoragesService
42
-	 */
43
-	protected $globalService;
40
+    /**
41
+     * @var GlobalStoragesService
42
+     */
43
+    protected $globalService;
44 44
 
45
-	function __construct(GlobalStoragesService $globalService) {
46
-		parent::__construct();
47
-		$this->globalService = $globalService;
48
-	}
45
+    function __construct(GlobalStoragesService $globalService) {
46
+        parent::__construct();
47
+        $this->globalService = $globalService;
48
+    }
49 49
 
50
-	protected function configure() {
51
-		$this
52
-			->setName('files_external:verify')
53
-			->setDescription('Verify mount configuration')
54
-			->addArgument(
55
-				'mount_id',
56
-				InputArgument::REQUIRED,
57
-				'The id of the mount to check'
58
-			)->addOption(
59
-				'config',
60
-				'c',
61
-				InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
62
-				'Additional config option to set before checking in key=value pairs, required for certain auth backends such as login credentails'
63
-			);
64
-		parent::configure();
65
-	}
50
+    protected function configure() {
51
+        $this
52
+            ->setName('files_external:verify')
53
+            ->setDescription('Verify mount configuration')
54
+            ->addArgument(
55
+                'mount_id',
56
+                InputArgument::REQUIRED,
57
+                'The id of the mount to check'
58
+            )->addOption(
59
+                'config',
60
+                'c',
61
+                InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
62
+                'Additional config option to set before checking in key=value pairs, required for certain auth backends such as login credentails'
63
+            );
64
+        parent::configure();
65
+    }
66 66
 
67
-	protected function execute(InputInterface $input, OutputInterface $output) {
68
-		$mountId = $input->getArgument('mount_id');
69
-		$configInput = $input->getOption('config');
67
+    protected function execute(InputInterface $input, OutputInterface $output) {
68
+        $mountId = $input->getArgument('mount_id');
69
+        $configInput = $input->getOption('config');
70 70
 
71
-		try {
72
-			$mount = $this->globalService->getStorage($mountId);
73
-		} catch (NotFoundException $e) {
74
-			$output->writeln('<error>Mount with id "' . $mountId . ' not found, check "occ files_external:list" to get available mounts"</error>');
75
-			return 404;
76
-		}
71
+        try {
72
+            $mount = $this->globalService->getStorage($mountId);
73
+        } catch (NotFoundException $e) {
74
+            $output->writeln('<error>Mount with id "' . $mountId . ' not found, check "occ files_external:list" to get available mounts"</error>');
75
+            return 404;
76
+        }
77 77
 
78
-		$this->updateStorageStatus($mount, $configInput, $output);
78
+        $this->updateStorageStatus($mount, $configInput, $output);
79 79
 
80
-		$this->writeArrayInOutputFormat($input, $output, [
81
-			'status' => StorageNotAvailableException::getStateCodeName($mount->getStatus()),
82
-			'code' => $mount->getStatus(),
83
-			'message' => $mount->getStatusMessage()
84
-		]);
85
-	}
80
+        $this->writeArrayInOutputFormat($input, $output, [
81
+            'status' => StorageNotAvailableException::getStateCodeName($mount->getStatus()),
82
+            'code' => $mount->getStatus(),
83
+            'message' => $mount->getStatusMessage()
84
+        ]);
85
+    }
86 86
 
87
-	private function manipulateStorageConfig(StorageConfig $storage) {
88
-		/** @var AuthMechanism */
89
-		$authMechanism = $storage->getAuthMechanism();
90
-		$authMechanism->manipulateStorageConfig($storage);
91
-		/** @var Backend */
92
-		$backend = $storage->getBackend();
93
-		$backend->manipulateStorageConfig($storage);
94
-	}
87
+    private function manipulateStorageConfig(StorageConfig $storage) {
88
+        /** @var AuthMechanism */
89
+        $authMechanism = $storage->getAuthMechanism();
90
+        $authMechanism->manipulateStorageConfig($storage);
91
+        /** @var Backend */
92
+        $backend = $storage->getBackend();
93
+        $backend->manipulateStorageConfig($storage);
94
+    }
95 95
 
96
-	private function updateStorageStatus(StorageConfig &$storage, $configInput, OutputInterface $output) {
97
-		try {
98
-			try {
99
-				$this->manipulateStorageConfig($storage);
100
-			} catch (InsufficientDataForMeaningfulAnswerException $e) {
101
-				if (count($configInput) === 0) { // extra config options might solve the error
102
-					throw $e;
103
-				}
104
-			}
96
+    private function updateStorageStatus(StorageConfig &$storage, $configInput, OutputInterface $output) {
97
+        try {
98
+            try {
99
+                $this->manipulateStorageConfig($storage);
100
+            } catch (InsufficientDataForMeaningfulAnswerException $e) {
101
+                if (count($configInput) === 0) { // extra config options might solve the error
102
+                    throw $e;
103
+                }
104
+            }
105 105
 
106
-			foreach ($configInput as $configOption) {
107
-				if (!strpos($configOption, '=')) {
108
-					$output->writeln('<error>Invalid mount configuration option "' . $configOption . '"</error>');
109
-					return;
110
-				}
111
-				list($key, $value) = explode('=', $configOption, 2);
112
-				$storage->setBackendOption($key, $value);
113
-			}
106
+            foreach ($configInput as $configOption) {
107
+                if (!strpos($configOption, '=')) {
108
+                    $output->writeln('<error>Invalid mount configuration option "' . $configOption . '"</error>');
109
+                    return;
110
+                }
111
+                list($key, $value) = explode('=', $configOption, 2);
112
+                $storage->setBackendOption($key, $value);
113
+            }
114 114
 
115
-			/** @var Backend */
116
-			$backend = $storage->getBackend();
117
-			// update status (can be time-consuming)
118
-			$storage->setStatus(
119
-				\OC_Mount_Config::getBackendStatus(
120
-					$backend->getStorageClass(),
121
-					$storage->getBackendOptions(),
122
-					false
123
-				)
124
-			);
125
-		} catch (InsufficientDataForMeaningfulAnswerException $e) {
126
-			$status = $e->getCode() ? $e->getCode() : StorageNotAvailableException::STATUS_INDETERMINATE;
127
-			$storage->setStatus(
128
-				$status,
129
-				$e->getMessage()
130
-			);
131
-		} catch (StorageNotAvailableException $e) {
132
-			$storage->setStatus(
133
-				$e->getCode(),
134
-				$e->getMessage()
135
-			);
136
-		} catch (\Exception $e) {
137
-			// FIXME: convert storage exceptions to StorageNotAvailableException
138
-			$storage->setStatus(
139
-				StorageNotAvailableException::STATUS_ERROR,
140
-				get_class($e) . ': ' . $e->getMessage()
141
-			);
142
-		}
143
-	}
115
+            /** @var Backend */
116
+            $backend = $storage->getBackend();
117
+            // update status (can be time-consuming)
118
+            $storage->setStatus(
119
+                \OC_Mount_Config::getBackendStatus(
120
+                    $backend->getStorageClass(),
121
+                    $storage->getBackendOptions(),
122
+                    false
123
+                )
124
+            );
125
+        } catch (InsufficientDataForMeaningfulAnswerException $e) {
126
+            $status = $e->getCode() ? $e->getCode() : StorageNotAvailableException::STATUS_INDETERMINATE;
127
+            $storage->setStatus(
128
+                $status,
129
+                $e->getMessage()
130
+            );
131
+        } catch (StorageNotAvailableException $e) {
132
+            $storage->setStatus(
133
+                $e->getCode(),
134
+                $e->getMessage()
135
+            );
136
+        } catch (\Exception $e) {
137
+            // FIXME: convert storage exceptions to StorageNotAvailableException
138
+            $storage->setStatus(
139
+                StorageNotAvailableException::STATUS_ERROR,
140
+                get_class($e) . ': ' . $e->getMessage()
141
+            );
142
+        }
143
+    }
144 144
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
 		try {
72 72
 			$mount = $this->globalService->getStorage($mountId);
73 73
 		} catch (NotFoundException $e) {
74
-			$output->writeln('<error>Mount with id "' . $mountId . ' not found, check "occ files_external:list" to get available mounts"</error>');
74
+			$output->writeln('<error>Mount with id "'.$mountId.' not found, check "occ files_external:list" to get available mounts"</error>');
75 75
 			return 404;
76 76
 		}
77 77
 
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 		$backend->manipulateStorageConfig($storage);
94 94
 	}
95 95
 
96
-	private function updateStorageStatus(StorageConfig &$storage, $configInput, OutputInterface $output) {
96
+	private function updateStorageStatus(StorageConfig & $storage, $configInput, OutputInterface $output) {
97 97
 		try {
98 98
 			try {
99 99
 				$this->manipulateStorageConfig($storage);
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 
106 106
 			foreach ($configInput as $configOption) {
107 107
 				if (!strpos($configOption, '=')) {
108
-					$output->writeln('<error>Invalid mount configuration option "' . $configOption . '"</error>');
108
+					$output->writeln('<error>Invalid mount configuration option "'.$configOption.'"</error>');
109 109
 					return;
110 110
 				}
111 111
 				list($key, $value) = explode('=', $configOption, 2);
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 			// FIXME: convert storage exceptions to StorageNotAvailableException
138 138
 			$storage->setStatus(
139 139
 				StorageNotAvailableException::STATUS_ERROR,
140
-				get_class($e) . ': ' . $e->getMessage()
140
+				get_class($e).': '.$e->getMessage()
141 141
 			);
142 142
 		}
143 143
 	}
Please login to merge, or discard this patch.
apps/files_external/controller/storagescontroller.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -27,7 +27,6 @@
 block discarded – undo
27 27
 
28 28
 use \OCP\IConfig;
29 29
 use OCP\ILogger;
30
-use OCP\IUser;
31 30
 use \OCP\IUserSession;
32 31
 use \OCP\IRequest;
33 32
 use \OCP\IL10N;
Please login to merge, or discard this patch.
Indentation   +272 added lines, -272 removed lines patch added patch discarded remove patch
@@ -47,298 +47,298 @@
 block discarded – undo
47 47
  */
48 48
 abstract class StoragesController extends Controller {
49 49
 
50
-	/**
51
-	 * L10N service
52
-	 *
53
-	 * @var IL10N
54
-	 */
55
-	protected $l10n;
50
+    /**
51
+     * L10N service
52
+     *
53
+     * @var IL10N
54
+     */
55
+    protected $l10n;
56 56
 
57
-	/**
58
-	 * Storages service
59
-	 *
60
-	 * @var StoragesService
61
-	 */
62
-	protected $service;
57
+    /**
58
+     * Storages service
59
+     *
60
+     * @var StoragesService
61
+     */
62
+    protected $service;
63 63
 
64
-	/**
65
-	 * @var ILogger
66
-	 */
67
-	protected $logger;
64
+    /**
65
+     * @var ILogger
66
+     */
67
+    protected $logger;
68 68
 
69
-	/**
70
-	 * Creates a new storages controller.
71
-	 *
72
-	 * @param string $AppName application name
73
-	 * @param IRequest $request request object
74
-	 * @param IL10N $l10n l10n service
75
-	 * @param StoragesService $storagesService storage service
76
-	 * @param ILogger $logger
77
-	 */
78
-	public function __construct(
79
-		$AppName,
80
-		IRequest $request,
81
-		IL10N $l10n,
82
-		StoragesService $storagesService,
83
-		ILogger $logger
84
-	) {
85
-		parent::__construct($AppName, $request);
86
-		$this->l10n = $l10n;
87
-		$this->service = $storagesService;
88
-		$this->logger = $logger;
89
-	}
69
+    /**
70
+     * Creates a new storages controller.
71
+     *
72
+     * @param string $AppName application name
73
+     * @param IRequest $request request object
74
+     * @param IL10N $l10n l10n service
75
+     * @param StoragesService $storagesService storage service
76
+     * @param ILogger $logger
77
+     */
78
+    public function __construct(
79
+        $AppName,
80
+        IRequest $request,
81
+        IL10N $l10n,
82
+        StoragesService $storagesService,
83
+        ILogger $logger
84
+    ) {
85
+        parent::__construct($AppName, $request);
86
+        $this->l10n = $l10n;
87
+        $this->service = $storagesService;
88
+        $this->logger = $logger;
89
+    }
90 90
 
91
-	/**
92
-	 * Create a storage from its parameters
93
-	 *
94
-	 * @param string $mountPoint storage mount point
95
-	 * @param string $backend backend identifier
96
-	 * @param string $authMechanism authentication mechanism identifier
97
-	 * @param array $backendOptions backend-specific options
98
-	 * @param array|null $mountOptions mount-specific options
99
-	 * @param array|null $applicableUsers users for which to mount the storage
100
-	 * @param array|null $applicableGroups groups for which to mount the storage
101
-	 * @param int|null $priority priority
102
-	 *
103
-	 * @return StorageConfig|DataResponse
104
-	 */
105
-	protected function createStorage(
106
-		$mountPoint,
107
-		$backend,
108
-		$authMechanism,
109
-		$backendOptions,
110
-		$mountOptions = null,
111
-		$applicableUsers = null,
112
-		$applicableGroups = null,
113
-		$priority = null
114
-	) {
115
-		try {
116
-			return $this->service->createStorage(
117
-				$mountPoint,
118
-				$backend,
119
-				$authMechanism,
120
-				$backendOptions,
121
-				$mountOptions,
122
-				$applicableUsers,
123
-				$applicableGroups,
124
-				$priority
125
-			);
126
-		} catch (\InvalidArgumentException $e) {
127
-			$this->logger->logException($e);
128
-			return new DataResponse(
129
-				[
130
-					'message' => (string)$this->l10n->t('Invalid backend or authentication mechanism class')
131
-				],
132
-				Http::STATUS_UNPROCESSABLE_ENTITY
133
-			);
134
-		}
135
-	}
91
+    /**
92
+     * Create a storage from its parameters
93
+     *
94
+     * @param string $mountPoint storage mount point
95
+     * @param string $backend backend identifier
96
+     * @param string $authMechanism authentication mechanism identifier
97
+     * @param array $backendOptions backend-specific options
98
+     * @param array|null $mountOptions mount-specific options
99
+     * @param array|null $applicableUsers users for which to mount the storage
100
+     * @param array|null $applicableGroups groups for which to mount the storage
101
+     * @param int|null $priority priority
102
+     *
103
+     * @return StorageConfig|DataResponse
104
+     */
105
+    protected function createStorage(
106
+        $mountPoint,
107
+        $backend,
108
+        $authMechanism,
109
+        $backendOptions,
110
+        $mountOptions = null,
111
+        $applicableUsers = null,
112
+        $applicableGroups = null,
113
+        $priority = null
114
+    ) {
115
+        try {
116
+            return $this->service->createStorage(
117
+                $mountPoint,
118
+                $backend,
119
+                $authMechanism,
120
+                $backendOptions,
121
+                $mountOptions,
122
+                $applicableUsers,
123
+                $applicableGroups,
124
+                $priority
125
+            );
126
+        } catch (\InvalidArgumentException $e) {
127
+            $this->logger->logException($e);
128
+            return new DataResponse(
129
+                [
130
+                    'message' => (string)$this->l10n->t('Invalid backend or authentication mechanism class')
131
+                ],
132
+                Http::STATUS_UNPROCESSABLE_ENTITY
133
+            );
134
+        }
135
+    }
136 136
 
137
-	/**
138
-	 * Validate storage config
139
-	 *
140
-	 * @param StorageConfig $storage storage config
141
-	 *1
142
-	 * @return DataResponse|null returns response in case of validation error
143
-	 */
144
-	protected function validate(StorageConfig $storage) {
145
-		$mountPoint = $storage->getMountPoint();
146
-		if ($mountPoint === '' || $mountPoint === '/') {
147
-			return new DataResponse(
148
-				array(
149
-					'message' => (string)$this->l10n->t('Invalid mount point')
150
-				),
151
-				Http::STATUS_UNPROCESSABLE_ENTITY
152
-			);
153
-		}
137
+    /**
138
+     * Validate storage config
139
+     *
140
+     * @param StorageConfig $storage storage config
141
+     *1
142
+     * @return DataResponse|null returns response in case of validation error
143
+     */
144
+    protected function validate(StorageConfig $storage) {
145
+        $mountPoint = $storage->getMountPoint();
146
+        if ($mountPoint === '' || $mountPoint === '/') {
147
+            return new DataResponse(
148
+                array(
149
+                    'message' => (string)$this->l10n->t('Invalid mount point')
150
+                ),
151
+                Http::STATUS_UNPROCESSABLE_ENTITY
152
+            );
153
+        }
154 154
 
155
-		if ($storage->getBackendOption('objectstore')) {
156
-			// objectstore must not be sent from client side
157
-			return new DataResponse(
158
-				array(
159
-					'message' => (string)$this->l10n->t('Objectstore forbidden')
160
-				),
161
-				Http::STATUS_UNPROCESSABLE_ENTITY
162
-			);
163
-		}
155
+        if ($storage->getBackendOption('objectstore')) {
156
+            // objectstore must not be sent from client side
157
+            return new DataResponse(
158
+                array(
159
+                    'message' => (string)$this->l10n->t('Objectstore forbidden')
160
+                ),
161
+                Http::STATUS_UNPROCESSABLE_ENTITY
162
+            );
163
+        }
164 164
 
165
-		/** @var Backend */
166
-		$backend = $storage->getBackend();
167
-		/** @var AuthMechanism */
168
-		$authMechanism = $storage->getAuthMechanism();
169
-		if ($backend->checkDependencies()) {
170
-			// invalid backend
171
-			return new DataResponse(
172
-				array(
173
-					'message' => (string)$this->l10n->t('Invalid storage backend "%s"', [
174
-						$backend->getIdentifier()
175
-					])
176
-				),
177
-				Http::STATUS_UNPROCESSABLE_ENTITY
178
-			);
179
-		}
165
+        /** @var Backend */
166
+        $backend = $storage->getBackend();
167
+        /** @var AuthMechanism */
168
+        $authMechanism = $storage->getAuthMechanism();
169
+        if ($backend->checkDependencies()) {
170
+            // invalid backend
171
+            return new DataResponse(
172
+                array(
173
+                    'message' => (string)$this->l10n->t('Invalid storage backend "%s"', [
174
+                        $backend->getIdentifier()
175
+                    ])
176
+                ),
177
+                Http::STATUS_UNPROCESSABLE_ENTITY
178
+            );
179
+        }
180 180
 
181
-		if (!$backend->isVisibleFor($this->service->getVisibilityType())) {
182
-			// not permitted to use backend
183
-			return new DataResponse(
184
-				array(
185
-					'message' => (string)$this->l10n->t('Not permitted to use backend "%s"', [
186
-						$backend->getIdentifier()
187
-					])
188
-				),
189
-				Http::STATUS_UNPROCESSABLE_ENTITY
190
-			);
191
-		}
192
-		if (!$authMechanism->isVisibleFor($this->service->getVisibilityType())) {
193
-			// not permitted to use auth mechanism
194
-			return new DataResponse(
195
-				array(
196
-					'message' => (string)$this->l10n->t('Not permitted to use authentication mechanism "%s"', [
197
-						$authMechanism->getIdentifier()
198
-					])
199
-				),
200
-				Http::STATUS_UNPROCESSABLE_ENTITY
201
-			);
202
-		}
181
+        if (!$backend->isVisibleFor($this->service->getVisibilityType())) {
182
+            // not permitted to use backend
183
+            return new DataResponse(
184
+                array(
185
+                    'message' => (string)$this->l10n->t('Not permitted to use backend "%s"', [
186
+                        $backend->getIdentifier()
187
+                    ])
188
+                ),
189
+                Http::STATUS_UNPROCESSABLE_ENTITY
190
+            );
191
+        }
192
+        if (!$authMechanism->isVisibleFor($this->service->getVisibilityType())) {
193
+            // not permitted to use auth mechanism
194
+            return new DataResponse(
195
+                array(
196
+                    'message' => (string)$this->l10n->t('Not permitted to use authentication mechanism "%s"', [
197
+                        $authMechanism->getIdentifier()
198
+                    ])
199
+                ),
200
+                Http::STATUS_UNPROCESSABLE_ENTITY
201
+            );
202
+        }
203 203
 
204
-		if (!$backend->validateStorage($storage)) {
205
-			// unsatisfied parameters
206
-			return new DataResponse(
207
-				array(
208
-					'message' => (string)$this->l10n->t('Unsatisfied backend parameters')
209
-				),
210
-				Http::STATUS_UNPROCESSABLE_ENTITY
211
-			);
212
-		}
213
-		if (!$authMechanism->validateStorage($storage)) {
214
-			// unsatisfied parameters
215
-			return new DataResponse(
216
-				[
217
-					'message' => (string)$this->l10n->t('Unsatisfied authentication mechanism parameters')
218
-				],
219
-				Http::STATUS_UNPROCESSABLE_ENTITY
220
-			);
221
-		}
204
+        if (!$backend->validateStorage($storage)) {
205
+            // unsatisfied parameters
206
+            return new DataResponse(
207
+                array(
208
+                    'message' => (string)$this->l10n->t('Unsatisfied backend parameters')
209
+                ),
210
+                Http::STATUS_UNPROCESSABLE_ENTITY
211
+            );
212
+        }
213
+        if (!$authMechanism->validateStorage($storage)) {
214
+            // unsatisfied parameters
215
+            return new DataResponse(
216
+                [
217
+                    'message' => (string)$this->l10n->t('Unsatisfied authentication mechanism parameters')
218
+                ],
219
+                Http::STATUS_UNPROCESSABLE_ENTITY
220
+            );
221
+        }
222 222
 
223
-		return null;
224
-	}
223
+        return null;
224
+    }
225 225
 
226
-	protected function manipulateStorageConfig(StorageConfig $storage) {
227
-		/** @var AuthMechanism */
228
-		$authMechanism = $storage->getAuthMechanism();
229
-		$authMechanism->manipulateStorageConfig($storage);
230
-		/** @var Backend */
231
-		$backend = $storage->getBackend();
232
-		$backend->manipulateStorageConfig($storage);
233
-	}
226
+    protected function manipulateStorageConfig(StorageConfig $storage) {
227
+        /** @var AuthMechanism */
228
+        $authMechanism = $storage->getAuthMechanism();
229
+        $authMechanism->manipulateStorageConfig($storage);
230
+        /** @var Backend */
231
+        $backend = $storage->getBackend();
232
+        $backend->manipulateStorageConfig($storage);
233
+    }
234 234
 
235
-	/**
236
-	 * Check whether the given storage is available / valid.
237
-	 *
238
-	 * Note that this operation can be time consuming depending
239
-	 * on whether the remote storage is available or not.
240
-	 *
241
-	 * @param StorageConfig $storage storage configuration
242
-	 * @param bool $testOnly whether to storage should only test the connection or do more things
243
-	 */
244
-	protected function updateStorageStatus(StorageConfig &$storage, $testOnly = true) {
245
-		try {
246
-			$this->manipulateStorageConfig($storage);
235
+    /**
236
+     * Check whether the given storage is available / valid.
237
+     *
238
+     * Note that this operation can be time consuming depending
239
+     * on whether the remote storage is available or not.
240
+     *
241
+     * @param StorageConfig $storage storage configuration
242
+     * @param bool $testOnly whether to storage should only test the connection or do more things
243
+     */
244
+    protected function updateStorageStatus(StorageConfig &$storage, $testOnly = true) {
245
+        try {
246
+            $this->manipulateStorageConfig($storage);
247 247
 
248
-			/** @var Backend */
249
-			$backend = $storage->getBackend();
250
-			// update status (can be time-consuming)
251
-			$storage->setStatus(
252
-				\OC_Mount_Config::getBackendStatus(
253
-					$backend->getStorageClass(),
254
-					$storage->getBackendOptions(),
255
-					false,
256
-					$testOnly
257
-				)
258
-			);
259
-		} catch (InsufficientDataForMeaningfulAnswerException $e) {
260
-			$status = $e->getCode() ? $e->getCode() : StorageNotAvailableException::STATUS_INDETERMINATE;
261
-			$storage->setStatus(
262
-				$status,
263
-				$this->l10n->t('Insufficient data: %s', [$e->getMessage()])
264
-			);
265
-		} catch (StorageNotAvailableException $e) {
266
-			$storage->setStatus(
267
-				$e->getCode(),
268
-				$this->l10n->t('%s', [$e->getMessage()])
269
-			);
270
-		} catch (\Exception $e) {
271
-			// FIXME: convert storage exceptions to StorageNotAvailableException
272
-			$storage->setStatus(
273
-				StorageNotAvailableException::STATUS_ERROR,
274
-				get_class($e).': '.$e->getMessage()
275
-			);
276
-		}
277
-	}
248
+            /** @var Backend */
249
+            $backend = $storage->getBackend();
250
+            // update status (can be time-consuming)
251
+            $storage->setStatus(
252
+                \OC_Mount_Config::getBackendStatus(
253
+                    $backend->getStorageClass(),
254
+                    $storage->getBackendOptions(),
255
+                    false,
256
+                    $testOnly
257
+                )
258
+            );
259
+        } catch (InsufficientDataForMeaningfulAnswerException $e) {
260
+            $status = $e->getCode() ? $e->getCode() : StorageNotAvailableException::STATUS_INDETERMINATE;
261
+            $storage->setStatus(
262
+                $status,
263
+                $this->l10n->t('Insufficient data: %s', [$e->getMessage()])
264
+            );
265
+        } catch (StorageNotAvailableException $e) {
266
+            $storage->setStatus(
267
+                $e->getCode(),
268
+                $this->l10n->t('%s', [$e->getMessage()])
269
+            );
270
+        } catch (\Exception $e) {
271
+            // FIXME: convert storage exceptions to StorageNotAvailableException
272
+            $storage->setStatus(
273
+                StorageNotAvailableException::STATUS_ERROR,
274
+                get_class($e).': '.$e->getMessage()
275
+            );
276
+        }
277
+    }
278 278
 
279
-	/**
280
-	 * Get all storage entries
281
-	 *
282
-	 * @return DataResponse
283
-	 */
284
-	public function index() {
285
-		$storages = $this->service->getStorages();
279
+    /**
280
+     * Get all storage entries
281
+     *
282
+     * @return DataResponse
283
+     */
284
+    public function index() {
285
+        $storages = $this->service->getStorages();
286 286
 
287
-		return new DataResponse(
288
-			$storages,
289
-			Http::STATUS_OK
290
-		);
291
-	}
287
+        return new DataResponse(
288
+            $storages,
289
+            Http::STATUS_OK
290
+        );
291
+    }
292 292
 
293
-	/**
294
-	 * Get an external storage entry.
295
-	 *
296
-	 * @param int $id storage id
297
-	 * @param bool $testOnly whether to storage should only test the connection or do more things
298
-	 *
299
-	 * @return DataResponse
300
-	 */
301
-	public function show($id, $testOnly = true) {
302
-		try {
303
-			$storage = $this->service->getStorage($id);
293
+    /**
294
+     * Get an external storage entry.
295
+     *
296
+     * @param int $id storage id
297
+     * @param bool $testOnly whether to storage should only test the connection or do more things
298
+     *
299
+     * @return DataResponse
300
+     */
301
+    public function show($id, $testOnly = true) {
302
+        try {
303
+            $storage = $this->service->getStorage($id);
304 304
 
305
-			$this->updateStorageStatus($storage, $testOnly);
306
-		} catch (NotFoundException $e) {
307
-			return new DataResponse(
308
-				[
309
-					'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
310
-				],
311
-				Http::STATUS_NOT_FOUND
312
-			);
313
-		}
305
+            $this->updateStorageStatus($storage, $testOnly);
306
+        } catch (NotFoundException $e) {
307
+            return new DataResponse(
308
+                [
309
+                    'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
310
+                ],
311
+                Http::STATUS_NOT_FOUND
312
+            );
313
+        }
314 314
 
315
-		return new DataResponse(
316
-			$storage,
317
-			Http::STATUS_OK
318
-		);
319
-	}
315
+        return new DataResponse(
316
+            $storage,
317
+            Http::STATUS_OK
318
+        );
319
+    }
320 320
 
321
-	/**
322
-	 * Deletes the storage with the given id.
323
-	 *
324
-	 * @param int $id storage id
325
-	 *
326
-	 * @return DataResponse
327
-	 */
328
-	public function destroy($id) {
329
-		try {
330
-			$this->service->removeStorage($id);
331
-		} catch (NotFoundException $e) {
332
-			return new DataResponse(
333
-				[
334
-					'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
335
-				],
336
-				Http::STATUS_NOT_FOUND
337
-			);
338
-		}
321
+    /**
322
+     * Deletes the storage with the given id.
323
+     *
324
+     * @param int $id storage id
325
+     *
326
+     * @return DataResponse
327
+     */
328
+    public function destroy($id) {
329
+        try {
330
+            $this->service->removeStorage($id);
331
+        } catch (NotFoundException $e) {
332
+            return new DataResponse(
333
+                [
334
+                    'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
335
+                ],
336
+                Http::STATUS_NOT_FOUND
337
+            );
338
+        }
339 339
 
340
-		return new DataResponse([], Http::STATUS_NO_CONTENT);
341
-	}
340
+        return new DataResponse([], Http::STATUS_NO_CONTENT);
341
+    }
342 342
 
343 343
 }
344 344
 
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
 			$this->logger->logException($e);
128 128
 			return new DataResponse(
129 129
 				[
130
-					'message' => (string)$this->l10n->t('Invalid backend or authentication mechanism class')
130
+					'message' => (string) $this->l10n->t('Invalid backend or authentication mechanism class')
131 131
 				],
132 132
 				Http::STATUS_UNPROCESSABLE_ENTITY
133 133
 			);
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
 		if ($mountPoint === '' || $mountPoint === '/') {
147 147
 			return new DataResponse(
148 148
 				array(
149
-					'message' => (string)$this->l10n->t('Invalid mount point')
149
+					'message' => (string) $this->l10n->t('Invalid mount point')
150 150
 				),
151 151
 				Http::STATUS_UNPROCESSABLE_ENTITY
152 152
 			);
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 			// objectstore must not be sent from client side
157 157
 			return new DataResponse(
158 158
 				array(
159
-					'message' => (string)$this->l10n->t('Objectstore forbidden')
159
+					'message' => (string) $this->l10n->t('Objectstore forbidden')
160 160
 				),
161 161
 				Http::STATUS_UNPROCESSABLE_ENTITY
162 162
 			);
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 			// invalid backend
171 171
 			return new DataResponse(
172 172
 				array(
173
-					'message' => (string)$this->l10n->t('Invalid storage backend "%s"', [
173
+					'message' => (string) $this->l10n->t('Invalid storage backend "%s"', [
174 174
 						$backend->getIdentifier()
175 175
 					])
176 176
 				),
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 			// not permitted to use backend
183 183
 			return new DataResponse(
184 184
 				array(
185
-					'message' => (string)$this->l10n->t('Not permitted to use backend "%s"', [
185
+					'message' => (string) $this->l10n->t('Not permitted to use backend "%s"', [
186 186
 						$backend->getIdentifier()
187 187
 					])
188 188
 				),
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
 			// not permitted to use auth mechanism
194 194
 			return new DataResponse(
195 195
 				array(
196
-					'message' => (string)$this->l10n->t('Not permitted to use authentication mechanism "%s"', [
196
+					'message' => (string) $this->l10n->t('Not permitted to use authentication mechanism "%s"', [
197 197
 						$authMechanism->getIdentifier()
198 198
 					])
199 199
 				),
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 			// unsatisfied parameters
206 206
 			return new DataResponse(
207 207
 				array(
208
-					'message' => (string)$this->l10n->t('Unsatisfied backend parameters')
208
+					'message' => (string) $this->l10n->t('Unsatisfied backend parameters')
209 209
 				),
210 210
 				Http::STATUS_UNPROCESSABLE_ENTITY
211 211
 			);
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
 			// unsatisfied parameters
215 215
 			return new DataResponse(
216 216
 				[
217
-					'message' => (string)$this->l10n->t('Unsatisfied authentication mechanism parameters')
217
+					'message' => (string) $this->l10n->t('Unsatisfied authentication mechanism parameters')
218 218
 				],
219 219
 				Http::STATUS_UNPROCESSABLE_ENTITY
220 220
 			);
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
 	 * @param StorageConfig $storage storage configuration
242 242
 	 * @param bool $testOnly whether to storage should only test the connection or do more things
243 243
 	 */
244
-	protected function updateStorageStatus(StorageConfig &$storage, $testOnly = true) {
244
+	protected function updateStorageStatus(StorageConfig & $storage, $testOnly = true) {
245 245
 		try {
246 246
 			$this->manipulateStorageConfig($storage);
247 247
 
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
 		} catch (NotFoundException $e) {
307 307
 			return new DataResponse(
308 308
 				[
309
-					'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
309
+					'message' => (string) $this->l10n->t('Storage with id "%i" not found', array($id))
310 310
 				],
311 311
 				Http::STATUS_NOT_FOUND
312 312
 			);
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 		} catch (NotFoundException $e) {
332 332
 			return new DataResponse(
333 333
 				[
334
-					'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
334
+					'message' => (string) $this->l10n->t('Storage with id "%i" not found', array($id))
335 335
 				],
336 336
 				Http::STATUS_NOT_FOUND
337 337
 			);
Please login to merge, or discard this patch.
apps/files_external/controller/userstoragescontroller.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -27,7 +27,6 @@
 block discarded – undo
27 27
 use OCA\Files_External\Lib\Auth\AuthMechanism;
28 28
 use \OCP\IConfig;
29 29
 use OCP\ILogger;
30
-use OCP\IUser;
31 30
 use \OCP\IUserSession;
32 31
 use \OCP\IRequest;
33 32
 use \OCP\IL10N;
Please login to merge, or discard this patch.
Indentation   +180 added lines, -180 removed lines patch added patch discarded remove patch
@@ -43,185 +43,185 @@
 block discarded – undo
43 43
  * User storages controller
44 44
  */
45 45
 class UserStoragesController extends StoragesController {
46
-	/**
47
-	 * @var IUserSession
48
-	 */
49
-	private $userSession;
50
-
51
-	/**
52
-	 * Creates a new user storages controller.
53
-	 *
54
-	 * @param string $AppName application name
55
-	 * @param IRequest $request request object
56
-	 * @param IL10N $l10n l10n service
57
-	 * @param UserStoragesService $userStoragesService storage service
58
-	 * @param IUserSession $userSession
59
-	 * @param ILogger $logger
60
-	 */
61
-	public function __construct(
62
-		$AppName,
63
-		IRequest $request,
64
-		IL10N $l10n,
65
-		UserStoragesService $userStoragesService,
66
-		IUserSession $userSession,
67
-		ILogger $logger
68
-	) {
69
-		parent::__construct(
70
-			$AppName,
71
-			$request,
72
-			$l10n,
73
-			$userStoragesService,
74
-			$logger
75
-		);
76
-		$this->userSession = $userSession;
77
-	}
78
-
79
-	protected function manipulateStorageConfig(StorageConfig $storage) {
80
-		/** @var AuthMechanism */
81
-		$authMechanism = $storage->getAuthMechanism();
82
-		$authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
83
-		/** @var Backend */
84
-		$backend = $storage->getBackend();
85
-		$backend->manipulateStorageConfig($storage, $this->userSession->getUser());
86
-	}
87
-
88
-	/**
89
-	 * Get all storage entries
90
-	 *
91
-	 * @NoAdminRequired
92
-	 *
93
-	 * @return DataResponse
94
-	 */
95
-	public function index() {
96
-		return parent::index();
97
-	}
98
-
99
-	/**
100
-	 * Return storage
101
-	 *
102
-	 * @NoAdminRequired
103
-	 *
104
-	 * {@inheritdoc}
105
-	 */
106
-	public function show($id, $testOnly = true) {
107
-		return parent::show($id, $testOnly);
108
-	}
109
-
110
-	/**
111
-	 * Create an external storage entry.
112
-	 *
113
-	 * @param string $mountPoint storage mount point
114
-	 * @param string $backend backend identifier
115
-	 * @param string $authMechanism authentication mechanism identifier
116
-	 * @param array $backendOptions backend-specific options
117
-	 * @param array $mountOptions backend-specific mount options
118
-	 *
119
-	 * @return DataResponse
120
-	 *
121
-	 * @NoAdminRequired
122
-	 */
123
-	public function create(
124
-		$mountPoint,
125
-		$backend,
126
-		$authMechanism,
127
-		$backendOptions,
128
-		$mountOptions
129
-	) {
130
-		$newStorage = $this->createStorage(
131
-			$mountPoint,
132
-			$backend,
133
-			$authMechanism,
134
-			$backendOptions,
135
-			$mountOptions
136
-		);
137
-		if ($newStorage instanceOf DataResponse) {
138
-			return $newStorage;
139
-		}
140
-
141
-		$response = $this->validate($newStorage);
142
-		if (!empty($response)) {
143
-			return $response;
144
-		}
145
-
146
-		$newStorage = $this->service->addStorage($newStorage);
147
-		$this->updateStorageStatus($newStorage);
148
-
149
-		return new DataResponse(
150
-			$newStorage,
151
-			Http::STATUS_CREATED
152
-		);
153
-	}
154
-
155
-	/**
156
-	 * Update an external storage entry.
157
-	 *
158
-	 * @param int $id storage id
159
-	 * @param string $mountPoint storage mount point
160
-	 * @param string $backend backend identifier
161
-	 * @param string $authMechanism authentication mechanism identifier
162
-	 * @param array $backendOptions backend-specific options
163
-	 * @param array $mountOptions backend-specific mount options
164
-	 * @param bool $testOnly whether to storage should only test the connection or do more things
165
-	 *
166
-	 * @return DataResponse
167
-	 *
168
-	 * @NoAdminRequired
169
-	 */
170
-	public function update(
171
-		$id,
172
-		$mountPoint,
173
-		$backend,
174
-		$authMechanism,
175
-		$backendOptions,
176
-		$mountOptions,
177
-		$testOnly = true
178
-	) {
179
-		$storage = $this->createStorage(
180
-			$mountPoint,
181
-			$backend,
182
-			$authMechanism,
183
-			$backendOptions,
184
-			$mountOptions
185
-		);
186
-		if ($storage instanceOf DataResponse) {
187
-			return $storage;
188
-		}
189
-		$storage->setId($id);
190
-
191
-		$response = $this->validate($storage);
192
-		if (!empty($response)) {
193
-			return $response;
194
-		}
195
-
196
-		try {
197
-			$storage = $this->service->updateStorage($storage);
198
-		} catch (NotFoundException $e) {
199
-			return new DataResponse(
200
-				[
201
-					'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
202
-				],
203
-				Http::STATUS_NOT_FOUND
204
-			);
205
-		}
206
-
207
-		$this->updateStorageStatus($storage, $testOnly);
208
-
209
-		return new DataResponse(
210
-			$storage,
211
-			Http::STATUS_OK
212
-		);
213
-
214
-	}
215
-
216
-	/**
217
-	 * Delete storage
218
-	 *
219
-	 * @NoAdminRequired
220
-	 *
221
-	 * {@inheritdoc}
222
-	 */
223
-	public function destroy($id) {
224
-		return parent::destroy($id);
225
-	}
46
+    /**
47
+     * @var IUserSession
48
+     */
49
+    private $userSession;
50
+
51
+    /**
52
+     * Creates a new user storages controller.
53
+     *
54
+     * @param string $AppName application name
55
+     * @param IRequest $request request object
56
+     * @param IL10N $l10n l10n service
57
+     * @param UserStoragesService $userStoragesService storage service
58
+     * @param IUserSession $userSession
59
+     * @param ILogger $logger
60
+     */
61
+    public function __construct(
62
+        $AppName,
63
+        IRequest $request,
64
+        IL10N $l10n,
65
+        UserStoragesService $userStoragesService,
66
+        IUserSession $userSession,
67
+        ILogger $logger
68
+    ) {
69
+        parent::__construct(
70
+            $AppName,
71
+            $request,
72
+            $l10n,
73
+            $userStoragesService,
74
+            $logger
75
+        );
76
+        $this->userSession = $userSession;
77
+    }
78
+
79
+    protected function manipulateStorageConfig(StorageConfig $storage) {
80
+        /** @var AuthMechanism */
81
+        $authMechanism = $storage->getAuthMechanism();
82
+        $authMechanism->manipulateStorageConfig($storage, $this->userSession->getUser());
83
+        /** @var Backend */
84
+        $backend = $storage->getBackend();
85
+        $backend->manipulateStorageConfig($storage, $this->userSession->getUser());
86
+    }
87
+
88
+    /**
89
+     * Get all storage entries
90
+     *
91
+     * @NoAdminRequired
92
+     *
93
+     * @return DataResponse
94
+     */
95
+    public function index() {
96
+        return parent::index();
97
+    }
98
+
99
+    /**
100
+     * Return storage
101
+     *
102
+     * @NoAdminRequired
103
+     *
104
+     * {@inheritdoc}
105
+     */
106
+    public function show($id, $testOnly = true) {
107
+        return parent::show($id, $testOnly);
108
+    }
109
+
110
+    /**
111
+     * Create an external storage entry.
112
+     *
113
+     * @param string $mountPoint storage mount point
114
+     * @param string $backend backend identifier
115
+     * @param string $authMechanism authentication mechanism identifier
116
+     * @param array $backendOptions backend-specific options
117
+     * @param array $mountOptions backend-specific mount options
118
+     *
119
+     * @return DataResponse
120
+     *
121
+     * @NoAdminRequired
122
+     */
123
+    public function create(
124
+        $mountPoint,
125
+        $backend,
126
+        $authMechanism,
127
+        $backendOptions,
128
+        $mountOptions
129
+    ) {
130
+        $newStorage = $this->createStorage(
131
+            $mountPoint,
132
+            $backend,
133
+            $authMechanism,
134
+            $backendOptions,
135
+            $mountOptions
136
+        );
137
+        if ($newStorage instanceOf DataResponse) {
138
+            return $newStorage;
139
+        }
140
+
141
+        $response = $this->validate($newStorage);
142
+        if (!empty($response)) {
143
+            return $response;
144
+        }
145
+
146
+        $newStorage = $this->service->addStorage($newStorage);
147
+        $this->updateStorageStatus($newStorage);
148
+
149
+        return new DataResponse(
150
+            $newStorage,
151
+            Http::STATUS_CREATED
152
+        );
153
+    }
154
+
155
+    /**
156
+     * Update an external storage entry.
157
+     *
158
+     * @param int $id storage id
159
+     * @param string $mountPoint storage mount point
160
+     * @param string $backend backend identifier
161
+     * @param string $authMechanism authentication mechanism identifier
162
+     * @param array $backendOptions backend-specific options
163
+     * @param array $mountOptions backend-specific mount options
164
+     * @param bool $testOnly whether to storage should only test the connection or do more things
165
+     *
166
+     * @return DataResponse
167
+     *
168
+     * @NoAdminRequired
169
+     */
170
+    public function update(
171
+        $id,
172
+        $mountPoint,
173
+        $backend,
174
+        $authMechanism,
175
+        $backendOptions,
176
+        $mountOptions,
177
+        $testOnly = true
178
+    ) {
179
+        $storage = $this->createStorage(
180
+            $mountPoint,
181
+            $backend,
182
+            $authMechanism,
183
+            $backendOptions,
184
+            $mountOptions
185
+        );
186
+        if ($storage instanceOf DataResponse) {
187
+            return $storage;
188
+        }
189
+        $storage->setId($id);
190
+
191
+        $response = $this->validate($storage);
192
+        if (!empty($response)) {
193
+            return $response;
194
+        }
195
+
196
+        try {
197
+            $storage = $this->service->updateStorage($storage);
198
+        } catch (NotFoundException $e) {
199
+            return new DataResponse(
200
+                [
201
+                    'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
202
+                ],
203
+                Http::STATUS_NOT_FOUND
204
+            );
205
+        }
206
+
207
+        $this->updateStorageStatus($storage, $testOnly);
208
+
209
+        return new DataResponse(
210
+            $storage,
211
+            Http::STATUS_OK
212
+        );
213
+
214
+    }
215
+
216
+    /**
217
+     * Delete storage
218
+     *
219
+     * @NoAdminRequired
220
+     *
221
+     * {@inheritdoc}
222
+     */
223
+    public function destroy($id) {
224
+        return parent::destroy($id);
225
+    }
226 226
 
227 227
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -198,7 +198,7 @@
 block discarded – undo
198 198
 		} catch (NotFoundException $e) {
199 199
 			return new DataResponse(
200 200
 				[
201
-					'message' => (string)$this->l10n->t('Storage with id "%i" not found', array($id))
201
+					'message' => (string) $this->l10n->t('Storage with id "%i" not found', array($id))
202 202
 				],
203 203
 				Http::STATUS_NOT_FOUND
204 204
 			);
Please login to merge, or discard this patch.
apps/files_sharing/api/sharees.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -335,7 +335,7 @@
 block discarded – undo
335 335
 	 * split user and remote from federated cloud id
336 336
 	 *
337 337
 	 * @param string $address federated share address
338
-	 * @return array [user, remoteURL]
338
+	 * @return string[] [user, remoteURL]
339 339
 	 * @throws \Exception
340 340
 	 */
341 341
 	public function splitUserRemote($address) {
Please login to merge, or discard this patch.
Indentation   +495 added lines, -495 removed lines patch added patch discarded remove patch
@@ -39,499 +39,499 @@
 block discarded – undo
39 39
 
40 40
 class Sharees {
41 41
 
42
-	/** @var IGroupManager */
43
-	protected $groupManager;
44
-
45
-	/** @var IUserManager */
46
-	protected $userManager;
47
-
48
-	/** @var IManager */
49
-	protected $contactsManager;
50
-
51
-	/** @var IConfig */
52
-	protected $config;
53
-
54
-	/** @var IUserSession */
55
-	protected $userSession;
56
-
57
-	/** @var IRequest */
58
-	protected $request;
59
-
60
-	/** @var IURLGenerator */
61
-	protected $urlGenerator;
62
-
63
-	/** @var ILogger */
64
-	protected $logger;
65
-
66
-	/** @var \OCP\Share\IManager */
67
-	protected $shareManager;
68
-
69
-	/** @var bool */
70
-	protected $shareWithGroupOnly = false;
71
-
72
-	/** @var bool */
73
-	protected $shareeEnumeration = true;
74
-
75
-	/** @var int */
76
-	protected $offset = 0;
77
-
78
-	/** @var int */
79
-	protected $limit = 10;
80
-
81
-	/** @var array */
82
-	protected $result = [
83
-		'exact' => [
84
-			'users' => [],
85
-			'groups' => [],
86
-			'remotes' => [],
87
-		],
88
-		'users' => [],
89
-		'groups' => [],
90
-		'remotes' => [],
91
-	];
92
-
93
-	protected $reachedEndFor = [];
94
-
95
-	/**
96
-	 * @param IGroupManager $groupManager
97
-	 * @param IUserManager $userManager
98
-	 * @param IManager $contactsManager
99
-	 * @param IConfig $config
100
-	 * @param IUserSession $userSession
101
-	 * @param IURLGenerator $urlGenerator
102
-	 * @param IRequest $request
103
-	 * @param ILogger $logger
104
-	 * @param \OCP\Share\IManager $shareManager
105
-	 */
106
-	public function __construct(IGroupManager $groupManager,
107
-								IUserManager $userManager,
108
-								IManager $contactsManager,
109
-								IConfig $config,
110
-								IUserSession $userSession,
111
-								IURLGenerator $urlGenerator,
112
-								IRequest $request,
113
-								ILogger $logger,
114
-								\OCP\Share\IManager $shareManager) {
115
-		$this->groupManager = $groupManager;
116
-		$this->userManager = $userManager;
117
-		$this->contactsManager = $contactsManager;
118
-		$this->config = $config;
119
-		$this->userSession = $userSession;
120
-		$this->urlGenerator = $urlGenerator;
121
-		$this->request = $request;
122
-		$this->logger = $logger;
123
-		$this->shareManager = $shareManager;
124
-	}
125
-
126
-	/**
127
-	 * @param string $search
128
-	 */
129
-	protected function getUsers($search) {
130
-		$this->result['users'] = $this->result['exact']['users'] = $users = [];
131
-
132
-		$userGroups = [];
133
-		if ($this->shareWithGroupOnly) {
134
-			// Search in all the groups this user is part of
135
-			$userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
136
-			foreach ($userGroups as $userGroup) {
137
-				$usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $this->limit, $this->offset);
138
-				foreach ($usersTmp as $uid => $userDisplayName) {
139
-					$users[$uid] = $userDisplayName;
140
-				}
141
-			}
142
-		} else {
143
-			// Search in all users
144
-			$usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset);
145
-
146
-			foreach ($usersTmp as $user) {
147
-				$users[$user->getUID()] = $user->getDisplayName();
148
-			}
149
-		}
150
-
151
-		if (!$this->shareeEnumeration || sizeof($users) < $this->limit) {
152
-			$this->reachedEndFor[] = 'users';
153
-		}
154
-
155
-		$foundUserById = false;
156
-		foreach ($users as $uid => $userDisplayName) {
157
-			if (strtolower($uid) === strtolower($search) || strtolower($userDisplayName) === strtolower($search)) {
158
-				if (strtolower($uid) === strtolower($search)) {
159
-					$foundUserById = true;
160
-				}
161
-				$this->result['exact']['users'][] = [
162
-					'label' => $userDisplayName,
163
-					'value' => [
164
-						'shareType' => Share::SHARE_TYPE_USER,
165
-						'shareWith' => $uid,
166
-					],
167
-				];
168
-			} else {
169
-				$this->result['users'][] = [
170
-					'label' => $userDisplayName,
171
-					'value' => [
172
-						'shareType' => Share::SHARE_TYPE_USER,
173
-						'shareWith' => $uid,
174
-					],
175
-				];
176
-			}
177
-		}
178
-
179
-		if ($this->offset === 0 && !$foundUserById) {
180
-			// On page one we try if the search result has a direct hit on the
181
-			// user id and if so, we add that to the exact match list
182
-			$user = $this->userManager->get($search);
183
-			if ($user instanceof IUser) {
184
-				$addUser = true;
185
-
186
-				if ($this->shareWithGroupOnly) {
187
-					// Only add, if we have a common group
188
-					$commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
189
-					$addUser = !empty($commonGroups);
190
-				}
191
-
192
-				if ($addUser) {
193
-					array_push($this->result['exact']['users'], [
194
-						'label' => $user->getDisplayName(),
195
-						'value' => [
196
-							'shareType' => Share::SHARE_TYPE_USER,
197
-							'shareWith' => $user->getUID(),
198
-						],
199
-					]);
200
-				}
201
-			}
202
-		}
203
-
204
-		if (!$this->shareeEnumeration) {
205
-			$this->result['users'] = [];
206
-		}
207
-	}
208
-
209
-	/**
210
-	 * @param string $search
211
-	 */
212
-	protected function getGroups($search) {
213
-		$this->result['groups'] = $this->result['exact']['groups'] = [];
214
-
215
-		$groups = $this->groupManager->search($search, $this->limit, $this->offset);
216
-		$groups = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
217
-
218
-		if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
219
-			$this->reachedEndFor[] = 'groups';
220
-		}
221
-
222
-		$userGroups =  [];
223
-		if (!empty($groups) && $this->shareWithGroupOnly) {
224
-			// Intersect all the groups that match with the groups this user is a member of
225
-			$userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
226
-			$userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
227
-			$groups = array_intersect($groups, $userGroups);
228
-		}
229
-
230
-		foreach ($groups as $gid) {
231
-			if (strtolower($gid) === strtolower($search)) {
232
-				$this->result['exact']['groups'][] = [
233
-					'label' => $gid,
234
-					'value' => [
235
-						'shareType' => Share::SHARE_TYPE_GROUP,
236
-						'shareWith' => $gid,
237
-					],
238
-				];
239
-			} else {
240
-				$this->result['groups'][] = [
241
-					'label' => $gid,
242
-					'value' => [
243
-						'shareType' => Share::SHARE_TYPE_GROUP,
244
-						'shareWith' => $gid,
245
-					],
246
-				];
247
-			}
248
-		}
249
-
250
-		if ($this->offset === 0 && empty($this->result['exact']['groups'])) {
251
-			// On page one we try if the search result has a direct hit on the
252
-			// user id and if so, we add that to the exact match list
253
-			$group = $this->groupManager->get($search);
254
-			if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
255
-				array_push($this->result['exact']['groups'], [
256
-					'label' => $group->getGID(),
257
-					'value' => [
258
-						'shareType' => Share::SHARE_TYPE_GROUP,
259
-						'shareWith' => $group->getGID(),
260
-					],
261
-				]);
262
-			}
263
-		}
264
-
265
-		if (!$this->shareeEnumeration) {
266
-			$this->result['groups'] = [];
267
-		}
268
-	}
269
-
270
-	/**
271
-	 * @param string $search
272
-	 * @return array possible sharees
273
-	 */
274
-	protected function getRemote($search) {
275
-		$this->result['remotes'] = [];
276
-
277
-		// Search in contacts
278
-		//@todo Pagination missing
279
-		$addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']);
280
-		$foundRemoteById = false;
281
-		foreach ($addressBookContacts as $contact) {
282
-			if (isset($contact['isLocalSystemBook'])) {
283
-				continue;
284
-			}
285
-			if (isset($contact['CLOUD'])) {
286
-				$cloudIds = $contact['CLOUD'];
287
-				if (!is_array($cloudIds)) {
288
-					$cloudIds = [$cloudIds];
289
-				}
290
-				foreach ($cloudIds as $cloudId) {
291
-					list(, $serverUrl) = $this->splitUserRemote($cloudId);
292
-					if (strtolower($contact['FN']) === strtolower($search) || strtolower($cloudId) === strtolower($search)) {
293
-						if (strtolower($cloudId) === strtolower($search)) {
294
-							$foundRemoteById = true;
295
-						}
296
-						$this->result['exact']['remotes'][] = [
297
-							'label' => $contact['FN'],
298
-							'value' => [
299
-								'shareType' => Share::SHARE_TYPE_REMOTE,
300
-								'shareWith' => $cloudId,
301
-								'server' => $serverUrl,
302
-							],
303
-						];
304
-					} else {
305
-						$this->result['remotes'][] = [
306
-							'label' => $contact['FN'],
307
-							'value' => [
308
-								'shareType' => Share::SHARE_TYPE_REMOTE,
309
-								'shareWith' => $cloudId,
310
-								'server' => $serverUrl,
311
-							],
312
-						];
313
-					}
314
-				}
315
-			}
316
-		}
317
-
318
-		if (!$this->shareeEnumeration) {
319
-			$this->result['remotes'] = [];
320
-		}
321
-
322
-		if (!$foundRemoteById && substr_count($search, '@') >= 1 && substr_count($search, ' ') === 0 && $this->offset === 0) {
323
-			$this->result['exact']['remotes'][] = [
324
-				'label' => $search,
325
-				'value' => [
326
-					'shareType' => Share::SHARE_TYPE_REMOTE,
327
-					'shareWith' => $search,
328
-				],
329
-			];
330
-		}
331
-
332
-		$this->reachedEndFor[] = 'remotes';
333
-	}
334
-
335
-	/**
336
-	 * split user and remote from federated cloud id
337
-	 *
338
-	 * @param string $address federated share address
339
-	 * @return array [user, remoteURL]
340
-	 * @throws \Exception
341
-	 */
342
-	public function splitUserRemote($address) {
343
-		if (strpos($address, '@') === false) {
344
-			throw new \Exception('Invalid Federated Cloud ID');
345
-		}
346
-
347
-		// Find the first character that is not allowed in user names
348
-		$id = str_replace('\\', '/', $address);
349
-		$posSlash = strpos($id, '/');
350
-		$posColon = strpos($id, ':');
351
-
352
-		if ($posSlash === false && $posColon === false) {
353
-			$invalidPos = strlen($id);
354
-		} else if ($posSlash === false) {
355
-			$invalidPos = $posColon;
356
-		} else if ($posColon === false) {
357
-			$invalidPos = $posSlash;
358
-		} else {
359
-			$invalidPos = min($posSlash, $posColon);
360
-		}
361
-
362
-		// Find the last @ before $invalidPos
363
-		$pos = $lastAtPos = 0;
364
-		while ($lastAtPos !== false && $lastAtPos <= $invalidPos) {
365
-			$pos = $lastAtPos;
366
-			$lastAtPos = strpos($id, '@', $pos + 1);
367
-		}
368
-
369
-		if ($pos !== false) {
370
-			$user = substr($id, 0, $pos);
371
-			$remote = substr($id, $pos + 1);
372
-			$remote = $this->fixRemoteURL($remote);
373
-			if (!empty($user) && !empty($remote)) {
374
-				return array($user, $remote);
375
-			}
376
-		}
377
-
378
-		throw new \Exception('Invalid Federated Cloud ID');
379
-	}
380
-
381
-	/**
382
-	 * Strips away a potential file names and trailing slashes:
383
-	 * - http://localhost
384
-	 * - http://localhost/
385
-	 * - http://localhost/index.php
386
-	 * - http://localhost/index.php/s/{shareToken}
387
-	 *
388
-	 * all return: http://localhost
389
-	 *
390
-	 * @param string $remote
391
-	 * @return string
392
-	 */
393
-	protected function fixRemoteURL($remote) {
394
-		$remote = str_replace('\\', '/', $remote);
395
-		if ($fileNamePosition = strpos($remote, '/index.php')) {
396
-			$remote = substr($remote, 0, $fileNamePosition);
397
-		}
398
-		$remote = rtrim($remote, '/');
399
-
400
-		return $remote;
401
-	}
402
-
403
-	/**
404
-	 * @return \OC_OCS_Result
405
-	 */
406
-	public function search() {
407
-		$search = isset($_GET['search']) ? (string) $_GET['search'] : '';
408
-		$itemType = isset($_GET['itemType']) ? (string) $_GET['itemType'] : null;
409
-		$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
410
-		$perPage = isset($_GET['perPage']) ? (int) $_GET['perPage'] : 200;
411
-
412
-		if ($perPage <= 0) {
413
-			return new \OC_OCS_Result(null, Http::STATUS_BAD_REQUEST, 'Invalid perPage argument');
414
-		}
415
-		if ($page <= 0) {
416
-			return new \OC_OCS_Result(null, Http::STATUS_BAD_REQUEST, 'Invalid page');
417
-		}
418
-
419
-		$shareTypes = [
420
-			Share::SHARE_TYPE_USER,
421
-		];
422
-
423
-		if ($this->shareManager->allowGroupSharing()) {
424
-			$shareTypes[] = Share::SHARE_TYPE_GROUP;
425
-		}
426
-
427
-		$shareTypes[] = Share::SHARE_TYPE_REMOTE;
428
-
429
-		if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
430
-			$shareTypes = array_intersect($shareTypes, $_GET['shareType']);
431
-			sort($shareTypes);
432
-
433
-		} else if (isset($_GET['shareType']) && is_numeric($_GET['shareType'])) {
434
-			$shareTypes = array_intersect($shareTypes, [(int) $_GET['shareType']]);
435
-			sort($shareTypes);
436
-		}
437
-
438
-		if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes) && !$this->isRemoteSharingAllowed($itemType)) {
439
-			// Remove remote shares from type array, because it is not allowed.
440
-			$shareTypes = array_diff($shareTypes, [Share::SHARE_TYPE_REMOTE]);
441
-		}
442
-
443
-		$this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
444
-		$this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
445
-		$this->limit = (int) $perPage;
446
-		$this->offset = $perPage * ($page - 1);
447
-
448
-		return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage);
449
-	}
450
-
451
-	/**
452
-	 * Method to get out the static call for better testing
453
-	 *
454
-	 * @param string $itemType
455
-	 * @return bool
456
-	 */
457
-	protected function isRemoteSharingAllowed($itemType) {
458
-		try {
459
-			$backend = Share::getBackend($itemType);
460
-			return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
461
-		} catch (\Exception $e) {
462
-			return false;
463
-		}
464
-	}
465
-
466
-	/**
467
-	 * Testable search function that does not need globals
468
-	 *
469
-	 * @param string $search
470
-	 * @param string $itemType
471
-	 * @param array $shareTypes
472
-	 * @param int $page
473
-	 * @param int $perPage
474
-	 * @return \OC_OCS_Result
475
-	 */
476
-	protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage) {
477
-		// Verify arguments
478
-		if ($itemType === null) {
479
-			return new \OC_OCS_Result(null, Http::STATUS_BAD_REQUEST, 'Missing itemType');
480
-		}
481
-
482
-		// Get users
483
-		if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) {
484
-			$this->getUsers($search);
485
-		}
486
-
487
-		// Get groups
488
-		if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) {
489
-			$this->getGroups($search);
490
-		}
491
-
492
-		// Get remote
493
-		if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) {
494
-			$this->getRemote($search);
495
-		}
496
-
497
-		$response = new \OC_OCS_Result($this->result);
498
-		$response->setItemsPerPage($perPage);
499
-
500
-		if (sizeof($this->reachedEndFor) < 3) {
501
-			$response->addHeader('Link', $this->getPaginationLink($page, [
502
-				'search' => $search,
503
-				'itemType' => $itemType,
504
-				'shareType' => $shareTypes,
505
-				'perPage' => $perPage,
506
-			]));
507
-		}
508
-
509
-		return $response;
510
-	}
511
-
512
-	/**
513
-	 * Generates a bunch of pagination links for the current page
514
-	 *
515
-	 * @param int $page Current page
516
-	 * @param array $params Parameters for the URL
517
-	 * @return string
518
-	 */
519
-	protected function getPaginationLink($page, array $params) {
520
-		if ($this->isV2()) {
521
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
522
-		} else {
523
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
524
-		}
525
-		$params['page'] = $page + 1;
526
-		$link = '<' . $url . http_build_query($params) . '>; rel="next"';
527
-
528
-		return $link;
529
-	}
530
-
531
-	/**
532
-	 * @return bool
533
-	 */
534
-	protected function isV2() {
535
-		return $this->request->getScriptName() === '/ocs/v2.php';
536
-	}
42
+    /** @var IGroupManager */
43
+    protected $groupManager;
44
+
45
+    /** @var IUserManager */
46
+    protected $userManager;
47
+
48
+    /** @var IManager */
49
+    protected $contactsManager;
50
+
51
+    /** @var IConfig */
52
+    protected $config;
53
+
54
+    /** @var IUserSession */
55
+    protected $userSession;
56
+
57
+    /** @var IRequest */
58
+    protected $request;
59
+
60
+    /** @var IURLGenerator */
61
+    protected $urlGenerator;
62
+
63
+    /** @var ILogger */
64
+    protected $logger;
65
+
66
+    /** @var \OCP\Share\IManager */
67
+    protected $shareManager;
68
+
69
+    /** @var bool */
70
+    protected $shareWithGroupOnly = false;
71
+
72
+    /** @var bool */
73
+    protected $shareeEnumeration = true;
74
+
75
+    /** @var int */
76
+    protected $offset = 0;
77
+
78
+    /** @var int */
79
+    protected $limit = 10;
80
+
81
+    /** @var array */
82
+    protected $result = [
83
+        'exact' => [
84
+            'users' => [],
85
+            'groups' => [],
86
+            'remotes' => [],
87
+        ],
88
+        'users' => [],
89
+        'groups' => [],
90
+        'remotes' => [],
91
+    ];
92
+
93
+    protected $reachedEndFor = [];
94
+
95
+    /**
96
+     * @param IGroupManager $groupManager
97
+     * @param IUserManager $userManager
98
+     * @param IManager $contactsManager
99
+     * @param IConfig $config
100
+     * @param IUserSession $userSession
101
+     * @param IURLGenerator $urlGenerator
102
+     * @param IRequest $request
103
+     * @param ILogger $logger
104
+     * @param \OCP\Share\IManager $shareManager
105
+     */
106
+    public function __construct(IGroupManager $groupManager,
107
+                                IUserManager $userManager,
108
+                                IManager $contactsManager,
109
+                                IConfig $config,
110
+                                IUserSession $userSession,
111
+                                IURLGenerator $urlGenerator,
112
+                                IRequest $request,
113
+                                ILogger $logger,
114
+                                \OCP\Share\IManager $shareManager) {
115
+        $this->groupManager = $groupManager;
116
+        $this->userManager = $userManager;
117
+        $this->contactsManager = $contactsManager;
118
+        $this->config = $config;
119
+        $this->userSession = $userSession;
120
+        $this->urlGenerator = $urlGenerator;
121
+        $this->request = $request;
122
+        $this->logger = $logger;
123
+        $this->shareManager = $shareManager;
124
+    }
125
+
126
+    /**
127
+     * @param string $search
128
+     */
129
+    protected function getUsers($search) {
130
+        $this->result['users'] = $this->result['exact']['users'] = $users = [];
131
+
132
+        $userGroups = [];
133
+        if ($this->shareWithGroupOnly) {
134
+            // Search in all the groups this user is part of
135
+            $userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
136
+            foreach ($userGroups as $userGroup) {
137
+                $usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $this->limit, $this->offset);
138
+                foreach ($usersTmp as $uid => $userDisplayName) {
139
+                    $users[$uid] = $userDisplayName;
140
+                }
141
+            }
142
+        } else {
143
+            // Search in all users
144
+            $usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset);
145
+
146
+            foreach ($usersTmp as $user) {
147
+                $users[$user->getUID()] = $user->getDisplayName();
148
+            }
149
+        }
150
+
151
+        if (!$this->shareeEnumeration || sizeof($users) < $this->limit) {
152
+            $this->reachedEndFor[] = 'users';
153
+        }
154
+
155
+        $foundUserById = false;
156
+        foreach ($users as $uid => $userDisplayName) {
157
+            if (strtolower($uid) === strtolower($search) || strtolower($userDisplayName) === strtolower($search)) {
158
+                if (strtolower($uid) === strtolower($search)) {
159
+                    $foundUserById = true;
160
+                }
161
+                $this->result['exact']['users'][] = [
162
+                    'label' => $userDisplayName,
163
+                    'value' => [
164
+                        'shareType' => Share::SHARE_TYPE_USER,
165
+                        'shareWith' => $uid,
166
+                    ],
167
+                ];
168
+            } else {
169
+                $this->result['users'][] = [
170
+                    'label' => $userDisplayName,
171
+                    'value' => [
172
+                        'shareType' => Share::SHARE_TYPE_USER,
173
+                        'shareWith' => $uid,
174
+                    ],
175
+                ];
176
+            }
177
+        }
178
+
179
+        if ($this->offset === 0 && !$foundUserById) {
180
+            // On page one we try if the search result has a direct hit on the
181
+            // user id and if so, we add that to the exact match list
182
+            $user = $this->userManager->get($search);
183
+            if ($user instanceof IUser) {
184
+                $addUser = true;
185
+
186
+                if ($this->shareWithGroupOnly) {
187
+                    // Only add, if we have a common group
188
+                    $commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
189
+                    $addUser = !empty($commonGroups);
190
+                }
191
+
192
+                if ($addUser) {
193
+                    array_push($this->result['exact']['users'], [
194
+                        'label' => $user->getDisplayName(),
195
+                        'value' => [
196
+                            'shareType' => Share::SHARE_TYPE_USER,
197
+                            'shareWith' => $user->getUID(),
198
+                        ],
199
+                    ]);
200
+                }
201
+            }
202
+        }
203
+
204
+        if (!$this->shareeEnumeration) {
205
+            $this->result['users'] = [];
206
+        }
207
+    }
208
+
209
+    /**
210
+     * @param string $search
211
+     */
212
+    protected function getGroups($search) {
213
+        $this->result['groups'] = $this->result['exact']['groups'] = [];
214
+
215
+        $groups = $this->groupManager->search($search, $this->limit, $this->offset);
216
+        $groups = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
217
+
218
+        if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
219
+            $this->reachedEndFor[] = 'groups';
220
+        }
221
+
222
+        $userGroups =  [];
223
+        if (!empty($groups) && $this->shareWithGroupOnly) {
224
+            // Intersect all the groups that match with the groups this user is a member of
225
+            $userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
226
+            $userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
227
+            $groups = array_intersect($groups, $userGroups);
228
+        }
229
+
230
+        foreach ($groups as $gid) {
231
+            if (strtolower($gid) === strtolower($search)) {
232
+                $this->result['exact']['groups'][] = [
233
+                    'label' => $gid,
234
+                    'value' => [
235
+                        'shareType' => Share::SHARE_TYPE_GROUP,
236
+                        'shareWith' => $gid,
237
+                    ],
238
+                ];
239
+            } else {
240
+                $this->result['groups'][] = [
241
+                    'label' => $gid,
242
+                    'value' => [
243
+                        'shareType' => Share::SHARE_TYPE_GROUP,
244
+                        'shareWith' => $gid,
245
+                    ],
246
+                ];
247
+            }
248
+        }
249
+
250
+        if ($this->offset === 0 && empty($this->result['exact']['groups'])) {
251
+            // On page one we try if the search result has a direct hit on the
252
+            // user id and if so, we add that to the exact match list
253
+            $group = $this->groupManager->get($search);
254
+            if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
255
+                array_push($this->result['exact']['groups'], [
256
+                    'label' => $group->getGID(),
257
+                    'value' => [
258
+                        'shareType' => Share::SHARE_TYPE_GROUP,
259
+                        'shareWith' => $group->getGID(),
260
+                    ],
261
+                ]);
262
+            }
263
+        }
264
+
265
+        if (!$this->shareeEnumeration) {
266
+            $this->result['groups'] = [];
267
+        }
268
+    }
269
+
270
+    /**
271
+     * @param string $search
272
+     * @return array possible sharees
273
+     */
274
+    protected function getRemote($search) {
275
+        $this->result['remotes'] = [];
276
+
277
+        // Search in contacts
278
+        //@todo Pagination missing
279
+        $addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']);
280
+        $foundRemoteById = false;
281
+        foreach ($addressBookContacts as $contact) {
282
+            if (isset($contact['isLocalSystemBook'])) {
283
+                continue;
284
+            }
285
+            if (isset($contact['CLOUD'])) {
286
+                $cloudIds = $contact['CLOUD'];
287
+                if (!is_array($cloudIds)) {
288
+                    $cloudIds = [$cloudIds];
289
+                }
290
+                foreach ($cloudIds as $cloudId) {
291
+                    list(, $serverUrl) = $this->splitUserRemote($cloudId);
292
+                    if (strtolower($contact['FN']) === strtolower($search) || strtolower($cloudId) === strtolower($search)) {
293
+                        if (strtolower($cloudId) === strtolower($search)) {
294
+                            $foundRemoteById = true;
295
+                        }
296
+                        $this->result['exact']['remotes'][] = [
297
+                            'label' => $contact['FN'],
298
+                            'value' => [
299
+                                'shareType' => Share::SHARE_TYPE_REMOTE,
300
+                                'shareWith' => $cloudId,
301
+                                'server' => $serverUrl,
302
+                            ],
303
+                        ];
304
+                    } else {
305
+                        $this->result['remotes'][] = [
306
+                            'label' => $contact['FN'],
307
+                            'value' => [
308
+                                'shareType' => Share::SHARE_TYPE_REMOTE,
309
+                                'shareWith' => $cloudId,
310
+                                'server' => $serverUrl,
311
+                            ],
312
+                        ];
313
+                    }
314
+                }
315
+            }
316
+        }
317
+
318
+        if (!$this->shareeEnumeration) {
319
+            $this->result['remotes'] = [];
320
+        }
321
+
322
+        if (!$foundRemoteById && substr_count($search, '@') >= 1 && substr_count($search, ' ') === 0 && $this->offset === 0) {
323
+            $this->result['exact']['remotes'][] = [
324
+                'label' => $search,
325
+                'value' => [
326
+                    'shareType' => Share::SHARE_TYPE_REMOTE,
327
+                    'shareWith' => $search,
328
+                ],
329
+            ];
330
+        }
331
+
332
+        $this->reachedEndFor[] = 'remotes';
333
+    }
334
+
335
+    /**
336
+     * split user and remote from federated cloud id
337
+     *
338
+     * @param string $address federated share address
339
+     * @return array [user, remoteURL]
340
+     * @throws \Exception
341
+     */
342
+    public function splitUserRemote($address) {
343
+        if (strpos($address, '@') === false) {
344
+            throw new \Exception('Invalid Federated Cloud ID');
345
+        }
346
+
347
+        // Find the first character that is not allowed in user names
348
+        $id = str_replace('\\', '/', $address);
349
+        $posSlash = strpos($id, '/');
350
+        $posColon = strpos($id, ':');
351
+
352
+        if ($posSlash === false && $posColon === false) {
353
+            $invalidPos = strlen($id);
354
+        } else if ($posSlash === false) {
355
+            $invalidPos = $posColon;
356
+        } else if ($posColon === false) {
357
+            $invalidPos = $posSlash;
358
+        } else {
359
+            $invalidPos = min($posSlash, $posColon);
360
+        }
361
+
362
+        // Find the last @ before $invalidPos
363
+        $pos = $lastAtPos = 0;
364
+        while ($lastAtPos !== false && $lastAtPos <= $invalidPos) {
365
+            $pos = $lastAtPos;
366
+            $lastAtPos = strpos($id, '@', $pos + 1);
367
+        }
368
+
369
+        if ($pos !== false) {
370
+            $user = substr($id, 0, $pos);
371
+            $remote = substr($id, $pos + 1);
372
+            $remote = $this->fixRemoteURL($remote);
373
+            if (!empty($user) && !empty($remote)) {
374
+                return array($user, $remote);
375
+            }
376
+        }
377
+
378
+        throw new \Exception('Invalid Federated Cloud ID');
379
+    }
380
+
381
+    /**
382
+     * Strips away a potential file names and trailing slashes:
383
+     * - http://localhost
384
+     * - http://localhost/
385
+     * - http://localhost/index.php
386
+     * - http://localhost/index.php/s/{shareToken}
387
+     *
388
+     * all return: http://localhost
389
+     *
390
+     * @param string $remote
391
+     * @return string
392
+     */
393
+    protected function fixRemoteURL($remote) {
394
+        $remote = str_replace('\\', '/', $remote);
395
+        if ($fileNamePosition = strpos($remote, '/index.php')) {
396
+            $remote = substr($remote, 0, $fileNamePosition);
397
+        }
398
+        $remote = rtrim($remote, '/');
399
+
400
+        return $remote;
401
+    }
402
+
403
+    /**
404
+     * @return \OC_OCS_Result
405
+     */
406
+    public function search() {
407
+        $search = isset($_GET['search']) ? (string) $_GET['search'] : '';
408
+        $itemType = isset($_GET['itemType']) ? (string) $_GET['itemType'] : null;
409
+        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
410
+        $perPage = isset($_GET['perPage']) ? (int) $_GET['perPage'] : 200;
411
+
412
+        if ($perPage <= 0) {
413
+            return new \OC_OCS_Result(null, Http::STATUS_BAD_REQUEST, 'Invalid perPage argument');
414
+        }
415
+        if ($page <= 0) {
416
+            return new \OC_OCS_Result(null, Http::STATUS_BAD_REQUEST, 'Invalid page');
417
+        }
418
+
419
+        $shareTypes = [
420
+            Share::SHARE_TYPE_USER,
421
+        ];
422
+
423
+        if ($this->shareManager->allowGroupSharing()) {
424
+            $shareTypes[] = Share::SHARE_TYPE_GROUP;
425
+        }
426
+
427
+        $shareTypes[] = Share::SHARE_TYPE_REMOTE;
428
+
429
+        if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
430
+            $shareTypes = array_intersect($shareTypes, $_GET['shareType']);
431
+            sort($shareTypes);
432
+
433
+        } else if (isset($_GET['shareType']) && is_numeric($_GET['shareType'])) {
434
+            $shareTypes = array_intersect($shareTypes, [(int) $_GET['shareType']]);
435
+            sort($shareTypes);
436
+        }
437
+
438
+        if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes) && !$this->isRemoteSharingAllowed($itemType)) {
439
+            // Remove remote shares from type array, because it is not allowed.
440
+            $shareTypes = array_diff($shareTypes, [Share::SHARE_TYPE_REMOTE]);
441
+        }
442
+
443
+        $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
444
+        $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
445
+        $this->limit = (int) $perPage;
446
+        $this->offset = $perPage * ($page - 1);
447
+
448
+        return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage);
449
+    }
450
+
451
+    /**
452
+     * Method to get out the static call for better testing
453
+     *
454
+     * @param string $itemType
455
+     * @return bool
456
+     */
457
+    protected function isRemoteSharingAllowed($itemType) {
458
+        try {
459
+            $backend = Share::getBackend($itemType);
460
+            return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
461
+        } catch (\Exception $e) {
462
+            return false;
463
+        }
464
+    }
465
+
466
+    /**
467
+     * Testable search function that does not need globals
468
+     *
469
+     * @param string $search
470
+     * @param string $itemType
471
+     * @param array $shareTypes
472
+     * @param int $page
473
+     * @param int $perPage
474
+     * @return \OC_OCS_Result
475
+     */
476
+    protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage) {
477
+        // Verify arguments
478
+        if ($itemType === null) {
479
+            return new \OC_OCS_Result(null, Http::STATUS_BAD_REQUEST, 'Missing itemType');
480
+        }
481
+
482
+        // Get users
483
+        if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) {
484
+            $this->getUsers($search);
485
+        }
486
+
487
+        // Get groups
488
+        if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) {
489
+            $this->getGroups($search);
490
+        }
491
+
492
+        // Get remote
493
+        if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) {
494
+            $this->getRemote($search);
495
+        }
496
+
497
+        $response = new \OC_OCS_Result($this->result);
498
+        $response->setItemsPerPage($perPage);
499
+
500
+        if (sizeof($this->reachedEndFor) < 3) {
501
+            $response->addHeader('Link', $this->getPaginationLink($page, [
502
+                'search' => $search,
503
+                'itemType' => $itemType,
504
+                'shareType' => $shareTypes,
505
+                'perPage' => $perPage,
506
+            ]));
507
+        }
508
+
509
+        return $response;
510
+    }
511
+
512
+    /**
513
+     * Generates a bunch of pagination links for the current page
514
+     *
515
+     * @param int $page Current page
516
+     * @param array $params Parameters for the URL
517
+     * @return string
518
+     */
519
+    protected function getPaginationLink($page, array $params) {
520
+        if ($this->isV2()) {
521
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
522
+        } else {
523
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
524
+        }
525
+        $params['page'] = $page + 1;
526
+        $link = '<' . $url . http_build_query($params) . '>; rel="next"';
527
+
528
+        return $link;
529
+    }
530
+
531
+    /**
532
+     * @return bool
533
+     */
534
+    protected function isV2() {
535
+        return $this->request->getScriptName() === '/ocs/v2.php';
536
+    }
537 537
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -213,17 +213,17 @@  discard block
 block discarded – undo
213 213
 		$this->result['groups'] = $this->result['exact']['groups'] = [];
214 214
 
215 215
 		$groups = $this->groupManager->search($search, $this->limit, $this->offset);
216
-		$groups = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
216
+		$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
217 217
 
218 218
 		if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
219 219
 			$this->reachedEndFor[] = 'groups';
220 220
 		}
221 221
 
222
-		$userGroups =  [];
222
+		$userGroups = [];
223 223
 		if (!empty($groups) && $this->shareWithGroupOnly) {
224 224
 			// Intersect all the groups that match with the groups this user is a member of
225 225
 			$userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
226
-			$userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
226
+			$userGroups = array_map(function(IGroup $group) { return $group->getGID(); }, $userGroups);
227 227
 			$groups = array_intersect($groups, $userGroups);
228 228
 		}
229 229
 
@@ -518,12 +518,12 @@  discard block
 block discarded – undo
518 518
 	 */
519 519
 	protected function getPaginationLink($page, array $params) {
520 520
 		if ($this->isV2()) {
521
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
521
+			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees').'?';
522 522
 		} else {
523
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
523
+			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees').'?';
524 524
 		}
525 525
 		$params['page'] = $page + 1;
526
-		$link = '<' . $url . http_build_query($params) . '>; rel="next"';
526
+		$link = '<'.$url.http_build_query($params).'>; rel="next"';
527 527
 
528 528
 		return $link;
529 529
 	}
Please login to merge, or discard this patch.
apps/files_sharing/lib/migration.php 3 patches
Doc Comments   -1 removed lines patch added patch discarded remove patch
@@ -130,7 +130,6 @@
 block discarded – undo
130 130
 	/**
131 131
 	 * Get $n re-shares from the database
132 132
 	 *
133
-	 * @param int $n The max number of shares to fetch
134 133
 	 * @return \Doctrine\DBAL\Driver\Statement
135 134
 	 */
136 135
 	private function getReShares() {
Please login to merge, or discard this patch.
Indentation   +235 added lines, -235 removed lines patch added patch discarded remove patch
@@ -36,240 +36,240 @@
 block discarded – undo
36 36
  */
37 37
 class Migration {
38 38
 
39
-	/** @var IDBConnection */
40
-	private $connection;
41
-
42
-	/** @var  array with all shares we already saw */
43
-	private $shareCache;
44
-
45
-	/** @var string */
46
-	private $table = 'share';
47
-
48
-	public function __construct(IDBConnection $connection) {
49
-		$this->connection = $connection;
50
-
51
-		// We cache up to 10k share items (~20MB)
52
-		$this->shareCache = new CappedMemoryCache(10000);
53
-	}
54
-
55
-	/**
56
-	 * move all re-shares to the owner in order to have a flat list of shares
57
-	 * upgrade from oC 8.2 to 9.0 with the new sharing
58
-	 */
59
-	public function removeReShares() {
60
-
61
-		$stmt = $this->getReShares();
62
-
63
-		$owners = [];
64
-		while($share = $stmt->fetch()) {
65
-
66
-			$this->shareCache[$share['id']] = $share;
67
-
68
-			$owners[$share['id']] = [
69
-					'owner' => $this->findOwner($share),
70
-					'initiator' => $share['uid_owner'],
71
-					'type' => $share['share_type'],
72
-			];
73
-
74
-			if (count($owners) === 1000) {
75
-				$this->updateOwners($owners);
76
-				$owners = [];
77
-			}
78
-		}
79
-
80
-		$stmt->closeCursor();
81
-
82
-		if (count($owners)) {
83
-			$this->updateOwners($owners);
84
-		}
85
-	}
86
-
87
-	/**
88
-	 * update all owner information so that all shares have an owner
89
-	 * and an initiator for the upgrade from oC 8.2 to 9.0 with the new sharing
90
-	 */
91
-	public function updateInitiatorInfo() {
92
-		while (true) {
93
-			$shares = $this->getMissingInitiator(1000);
94
-
95
-			if (empty($shares)) {
96
-				break;
97
-			}
98
-
99
-			$owners = [];
100
-			foreach ($shares as $share) {
101
-				$owners[$share['id']] = [
102
-					'owner' => $share['uid_owner'],
103
-					'initiator' => $share['uid_owner'],
104
-					'type' => $share['share_type'],
105
-				];
106
-			}
107
-			$this->updateOwners($owners);
108
-		}
109
-	}
110
-
111
-	/**
112
-	 * find the owner of a re-shared file/folder
113
-	 *
114
-	 * @param array $share
115
-	 * @return array
116
-	 */
117
-	private function findOwner($share) {
118
-		$currentShare = $share;
119
-		while(!is_null($currentShare['parent'])) {
120
-			if (isset($this->shareCache[$currentShare['parent']])) {
121
-				$currentShare = $this->shareCache[$currentShare['parent']];
122
-			} else {
123
-				$currentShare = $this->getShare((int)$currentShare['parent']);
124
-				$this->shareCache[$currentShare['id']] = $currentShare;
125
-			}
126
-		}
127
-
128
-		return $currentShare['uid_owner'];
129
-	}
130
-
131
-	/**
132
-	 * Get $n re-shares from the database
133
-	 *
134
-	 * @param int $n The max number of shares to fetch
135
-	 * @return \Doctrine\DBAL\Driver\Statement
136
-	 */
137
-	private function getReShares() {
138
-		$query = $this->connection->getQueryBuilder();
139
-		$query->select(['id', 'parent', 'uid_owner', 'share_type'])
140
-			->from($this->table)
141
-			->where($query->expr()->in(
142
-				'share_type',
143
-				$query->createNamedParameter(
144
-					[
145
-						\OCP\Share::SHARE_TYPE_USER,
146
-						\OCP\Share::SHARE_TYPE_GROUP,
147
-						\OCP\Share::SHARE_TYPE_LINK,
148
-						\OCP\Share::SHARE_TYPE_REMOTE,
149
-					],
150
-					Connection::PARAM_INT_ARRAY
151
-				)
152
-			))
153
-			->andWhere($query->expr()->in(
154
-				'item_type',
155
-				$query->createNamedParameter(
156
-					['file', 'folder'],
157
-					Connection::PARAM_STR_ARRAY
158
-				)
159
-			))
160
-			->andWhere($query->expr()->isNotNull('parent'))
161
-			->orderBy('id', 'asc');
162
-		return $query->execute();
163
-
164
-
165
-		$shares = $result->fetchAll();
166
-		$result->closeCursor();
167
-
168
-		$ordered = [];
169
-		foreach ($shares as $share) {
170
-			$ordered[(int)$share['id']] = $share;
171
-		}
172
-
173
-		return $ordered;
174
-	}
175
-
176
-	/**
177
-	 * Get $n re-shares from the database
178
-	 *
179
-	 * @param int $n The max number of shares to fetch
180
-	 * @return array
181
-	 */
182
-	private function getMissingInitiator($n = 1000) {
183
-		$query = $this->connection->getQueryBuilder();
184
-		$query->select(['id', 'uid_owner', 'share_type'])
185
-			->from($this->table)
186
-			->where($query->expr()->in(
187
-				'share_type',
188
-				$query->createNamedParameter(
189
-					[
190
-						\OCP\Share::SHARE_TYPE_USER,
191
-						\OCP\Share::SHARE_TYPE_GROUP,
192
-						\OCP\Share::SHARE_TYPE_LINK,
193
-						\OCP\Share::SHARE_TYPE_REMOTE,
194
-					],
195
-					Connection::PARAM_INT_ARRAY
196
-				)
197
-			))
198
-			->andWhere($query->expr()->in(
199
-				'item_type',
200
-				$query->createNamedParameter(
201
-					['file', 'folder'],
202
-					Connection::PARAM_STR_ARRAY
203
-				)
204
-			))
205
-			->andWhere($query->expr()->isNull('uid_initiator'))
206
-			->orderBy('id', 'asc')
207
-			->setMaxResults($n);
208
-		$result = $query->execute();
209
-		$shares = $result->fetchAll();
210
-		$result->closeCursor();
211
-
212
-		$ordered = [];
213
-		foreach ($shares as $share) {
214
-			$ordered[(int)$share['id']] = $share;
215
-		}
216
-
217
-		return $ordered;
218
-	}
219
-
220
-	/**
221
-	 * get a specific share
222
-	 *
223
-	 * @param int $id
224
-	 * @return array
225
-	 */
226
-	private function getShare($id) {
227
-		$query = $this->connection->getQueryBuilder();
228
-		$query->select(['id', 'parent', 'uid_owner'])
229
-			->from($this->table)
230
-			->where($query->expr()->eq('id', $query->createNamedParameter($id)));
231
-		$result = $query->execute();
232
-		$share = $result->fetchAll();
233
-		$result->closeCursor();
234
-
235
-		return $share[0];
236
-	}
237
-
238
-	/**
239
-	 * update database with the new owners
240
-	 *
241
-	 * @param array $owners
242
-	 * @throws \Exception
243
-	 */
244
-	private function updateOwners($owners) {
245
-
246
-		$this->connection->beginTransaction();
247
-
248
-		try {
249
-
250
-			foreach ($owners as $id => $owner) {
251
-				$query = $this->connection->getQueryBuilder();
252
-				$query->update($this->table)
253
-					->set('uid_owner', $query->createNamedParameter($owner['owner']))
254
-					->set('uid_initiator', $query->createNamedParameter($owner['initiator']));
255
-
256
-
257
-				if ((int)$owner['type'] !== \OCP\Share::SHARE_TYPE_LINK) {
258
-					$query->set('parent', $query->createNamedParameter(null));
259
-				}
260
-
261
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($id)));
262
-
263
-				$query->execute();
264
-			}
265
-
266
-			$this->connection->commit();
267
-
268
-		} catch (\Exception $e) {
269
-			$this->connection->rollBack();
270
-			throw $e;
271
-		}
272
-
273
-	}
39
+    /** @var IDBConnection */
40
+    private $connection;
41
+
42
+    /** @var  array with all shares we already saw */
43
+    private $shareCache;
44
+
45
+    /** @var string */
46
+    private $table = 'share';
47
+
48
+    public function __construct(IDBConnection $connection) {
49
+        $this->connection = $connection;
50
+
51
+        // We cache up to 10k share items (~20MB)
52
+        $this->shareCache = new CappedMemoryCache(10000);
53
+    }
54
+
55
+    /**
56
+     * move all re-shares to the owner in order to have a flat list of shares
57
+     * upgrade from oC 8.2 to 9.0 with the new sharing
58
+     */
59
+    public function removeReShares() {
60
+
61
+        $stmt = $this->getReShares();
62
+
63
+        $owners = [];
64
+        while($share = $stmt->fetch()) {
65
+
66
+            $this->shareCache[$share['id']] = $share;
67
+
68
+            $owners[$share['id']] = [
69
+                    'owner' => $this->findOwner($share),
70
+                    'initiator' => $share['uid_owner'],
71
+                    'type' => $share['share_type'],
72
+            ];
73
+
74
+            if (count($owners) === 1000) {
75
+                $this->updateOwners($owners);
76
+                $owners = [];
77
+            }
78
+        }
79
+
80
+        $stmt->closeCursor();
81
+
82
+        if (count($owners)) {
83
+            $this->updateOwners($owners);
84
+        }
85
+    }
86
+
87
+    /**
88
+     * update all owner information so that all shares have an owner
89
+     * and an initiator for the upgrade from oC 8.2 to 9.0 with the new sharing
90
+     */
91
+    public function updateInitiatorInfo() {
92
+        while (true) {
93
+            $shares = $this->getMissingInitiator(1000);
94
+
95
+            if (empty($shares)) {
96
+                break;
97
+            }
98
+
99
+            $owners = [];
100
+            foreach ($shares as $share) {
101
+                $owners[$share['id']] = [
102
+                    'owner' => $share['uid_owner'],
103
+                    'initiator' => $share['uid_owner'],
104
+                    'type' => $share['share_type'],
105
+                ];
106
+            }
107
+            $this->updateOwners($owners);
108
+        }
109
+    }
110
+
111
+    /**
112
+     * find the owner of a re-shared file/folder
113
+     *
114
+     * @param array $share
115
+     * @return array
116
+     */
117
+    private function findOwner($share) {
118
+        $currentShare = $share;
119
+        while(!is_null($currentShare['parent'])) {
120
+            if (isset($this->shareCache[$currentShare['parent']])) {
121
+                $currentShare = $this->shareCache[$currentShare['parent']];
122
+            } else {
123
+                $currentShare = $this->getShare((int)$currentShare['parent']);
124
+                $this->shareCache[$currentShare['id']] = $currentShare;
125
+            }
126
+        }
127
+
128
+        return $currentShare['uid_owner'];
129
+    }
130
+
131
+    /**
132
+     * Get $n re-shares from the database
133
+     *
134
+     * @param int $n The max number of shares to fetch
135
+     * @return \Doctrine\DBAL\Driver\Statement
136
+     */
137
+    private function getReShares() {
138
+        $query = $this->connection->getQueryBuilder();
139
+        $query->select(['id', 'parent', 'uid_owner', 'share_type'])
140
+            ->from($this->table)
141
+            ->where($query->expr()->in(
142
+                'share_type',
143
+                $query->createNamedParameter(
144
+                    [
145
+                        \OCP\Share::SHARE_TYPE_USER,
146
+                        \OCP\Share::SHARE_TYPE_GROUP,
147
+                        \OCP\Share::SHARE_TYPE_LINK,
148
+                        \OCP\Share::SHARE_TYPE_REMOTE,
149
+                    ],
150
+                    Connection::PARAM_INT_ARRAY
151
+                )
152
+            ))
153
+            ->andWhere($query->expr()->in(
154
+                'item_type',
155
+                $query->createNamedParameter(
156
+                    ['file', 'folder'],
157
+                    Connection::PARAM_STR_ARRAY
158
+                )
159
+            ))
160
+            ->andWhere($query->expr()->isNotNull('parent'))
161
+            ->orderBy('id', 'asc');
162
+        return $query->execute();
163
+
164
+
165
+        $shares = $result->fetchAll();
166
+        $result->closeCursor();
167
+
168
+        $ordered = [];
169
+        foreach ($shares as $share) {
170
+            $ordered[(int)$share['id']] = $share;
171
+        }
172
+
173
+        return $ordered;
174
+    }
175
+
176
+    /**
177
+     * Get $n re-shares from the database
178
+     *
179
+     * @param int $n The max number of shares to fetch
180
+     * @return array
181
+     */
182
+    private function getMissingInitiator($n = 1000) {
183
+        $query = $this->connection->getQueryBuilder();
184
+        $query->select(['id', 'uid_owner', 'share_type'])
185
+            ->from($this->table)
186
+            ->where($query->expr()->in(
187
+                'share_type',
188
+                $query->createNamedParameter(
189
+                    [
190
+                        \OCP\Share::SHARE_TYPE_USER,
191
+                        \OCP\Share::SHARE_TYPE_GROUP,
192
+                        \OCP\Share::SHARE_TYPE_LINK,
193
+                        \OCP\Share::SHARE_TYPE_REMOTE,
194
+                    ],
195
+                    Connection::PARAM_INT_ARRAY
196
+                )
197
+            ))
198
+            ->andWhere($query->expr()->in(
199
+                'item_type',
200
+                $query->createNamedParameter(
201
+                    ['file', 'folder'],
202
+                    Connection::PARAM_STR_ARRAY
203
+                )
204
+            ))
205
+            ->andWhere($query->expr()->isNull('uid_initiator'))
206
+            ->orderBy('id', 'asc')
207
+            ->setMaxResults($n);
208
+        $result = $query->execute();
209
+        $shares = $result->fetchAll();
210
+        $result->closeCursor();
211
+
212
+        $ordered = [];
213
+        foreach ($shares as $share) {
214
+            $ordered[(int)$share['id']] = $share;
215
+        }
216
+
217
+        return $ordered;
218
+    }
219
+
220
+    /**
221
+     * get a specific share
222
+     *
223
+     * @param int $id
224
+     * @return array
225
+     */
226
+    private function getShare($id) {
227
+        $query = $this->connection->getQueryBuilder();
228
+        $query->select(['id', 'parent', 'uid_owner'])
229
+            ->from($this->table)
230
+            ->where($query->expr()->eq('id', $query->createNamedParameter($id)));
231
+        $result = $query->execute();
232
+        $share = $result->fetchAll();
233
+        $result->closeCursor();
234
+
235
+        return $share[0];
236
+    }
237
+
238
+    /**
239
+     * update database with the new owners
240
+     *
241
+     * @param array $owners
242
+     * @throws \Exception
243
+     */
244
+    private function updateOwners($owners) {
245
+
246
+        $this->connection->beginTransaction();
247
+
248
+        try {
249
+
250
+            foreach ($owners as $id => $owner) {
251
+                $query = $this->connection->getQueryBuilder();
252
+                $query->update($this->table)
253
+                    ->set('uid_owner', $query->createNamedParameter($owner['owner']))
254
+                    ->set('uid_initiator', $query->createNamedParameter($owner['initiator']));
255
+
256
+
257
+                if ((int)$owner['type'] !== \OCP\Share::SHARE_TYPE_LINK) {
258
+                    $query->set('parent', $query->createNamedParameter(null));
259
+                }
260
+
261
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($id)));
262
+
263
+                $query->execute();
264
+            }
265
+
266
+            $this->connection->commit();
267
+
268
+        } catch (\Exception $e) {
269
+            $this->connection->rollBack();
270
+            throw $e;
271
+        }
272
+
273
+    }
274 274
 
275 275
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 		$stmt = $this->getReShares();
69 69
 
70 70
 		$owners = [];
71
-		while($share = $stmt->fetch()) {
71
+		while ($share = $stmt->fetch()) {
72 72
 
73 73
 			$this->shareCache[$share['id']] = $share;
74 74
 
@@ -131,11 +131,11 @@  discard block
 block discarded – undo
131 131
 	 */
132 132
 	private function findOwner($share) {
133 133
 		$currentShare = $share;
134
-		while(!is_null($currentShare['parent'])) {
134
+		while (!is_null($currentShare['parent'])) {
135 135
 			if (isset($this->shareCache[$currentShare['parent']])) {
136 136
 				$currentShare = $this->shareCache[$currentShare['parent']];
137 137
 			} else {
138
-				$currentShare = $this->getShare((int)$currentShare['parent']);
138
+				$currentShare = $this->getShare((int) $currentShare['parent']);
139 139
 				$this->shareCache[$currentShare['id']] = $currentShare;
140 140
 			}
141 141
 		}
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 
183 183
 		$ordered = [];
184 184
 		foreach ($shares as $share) {
185
-			$ordered[(int)$share['id']] = $share;
185
+			$ordered[(int) $share['id']] = $share;
186 186
 		}
187 187
 
188 188
 		return $ordered;
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 
227 227
 		$ordered = [];
228 228
 		foreach ($shares as $share) {
229
-			$ordered[(int)$share['id']] = $share;
229
+			$ordered[(int) $share['id']] = $share;
230 230
 		}
231 231
 
232 232
 		return $ordered;
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
 					->set('uid_initiator', $query->createNamedParameter($owner['initiator']));
270 270
 
271 271
 
272
-				if ((int)$owner['type'] !== \OCP\Share::SHARE_TYPE_LINK) {
272
+				if ((int) $owner['type'] !== \OCP\Share::SHARE_TYPE_LINK) {
273 273
 					$query->set('parent', $query->createNamedParameter(null));
274 274
 				}
275 275
 
Please login to merge, or discard this patch.