Completed
Push — stable12 ( 638d16...1c8d35 )
by
unknown
31:08 queued 20:30
created
apps/federation/lib/DAV/FedAuth.php 1 patch
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -29,40 +29,40 @@
 block discarded – undo
29 29
 
30 30
 class FedAuth extends AbstractBasic {
31 31
 
32
-	/** @var DbHandler */
33
-	private $db;
32
+    /** @var DbHandler */
33
+    private $db;
34 34
 
35
-	/**
36
-	 * FedAuth constructor.
37
-	 *
38
-	 * @param DbHandler $db
39
-	 */
40
-	public function __construct(DbHandler $db) {
41
-		$this->db = $db;
42
-		$this->principalPrefix = 'principals/system/';
35
+    /**
36
+     * FedAuth constructor.
37
+     *
38
+     * @param DbHandler $db
39
+     */
40
+    public function __construct(DbHandler $db) {
41
+        $this->db = $db;
42
+        $this->principalPrefix = 'principals/system/';
43 43
 
44
-		// setup realm
45
-		$defaults = new \OCP\Defaults();
46
-		$this->realm = $defaults->getName();
47
-	}
44
+        // setup realm
45
+        $defaults = new \OCP\Defaults();
46
+        $this->realm = $defaults->getName();
47
+    }
48 48
 
49
-	/**
50
-	 * Validates a username and password
51
-	 *
52
-	 * This method should return true or false depending on if login
53
-	 * succeeded.
54
-	 *
55
-	 * @param string $username
56
-	 * @param string $password
57
-	 * @return bool
58
-	 */
59
-	protected function validateUserPass($username, $password) {
60
-		return $this->db->auth($username, $password);
61
-	}
49
+    /**
50
+     * Validates a username and password
51
+     *
52
+     * This method should return true or false depending on if login
53
+     * succeeded.
54
+     *
55
+     * @param string $username
56
+     * @param string $password
57
+     * @return bool
58
+     */
59
+    protected function validateUserPass($username, $password) {
60
+        return $this->db->auth($username, $password);
61
+    }
62 62
 
63
-	/**
64
-	 * @inheritdoc
65
-	 */
66
-	function challenge(RequestInterface $request, ResponseInterface $response) {
67
-	}
63
+    /**
64
+     * @inheritdoc
65
+     */
66
+    function challenge(RequestInterface $request, ResponseInterface $response) {
67
+    }
68 68
 }
Please login to merge, or discard this patch.
apps/federation/lib/Controller/OCSAuthAPIController.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
  *
45 45
  * @package OCA\Federation\Controller
46 46
  */
47
-class OCSAuthAPIController extends OCSController{
47
+class OCSAuthAPIController extends OCSController {
48 48
 
49 49
 	/** @var ISecureRandom  */
50 50
 	private $secureRandom;
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
 	 */
104 104
 	public function requestSharedSecret($url, $token) {
105 105
 		if ($this->trustedServers->isTrustedServer($url) === false) {
106
-			$this->logger->error('remote server not trusted (' . $url . ') while requesting shared secret', ['app' => 'federation']);
106
+			$this->logger->error('remote server not trusted ('.$url.') while requesting shared secret', ['app' => 'federation']);
107 107
 			throw new OCSForbiddenException();
108 108
 		}
109 109
 
@@ -112,7 +112,7 @@  discard block
 block discarded – undo
112 112
 		$localToken = $this->dbHandler->getToken($url);
113 113
 		if (strcmp($localToken, $token) > 0) {
114 114
 			$this->logger->info(
115
-				'remote server (' . $url . ') presented lower token. We will initiate the exchange of the shared secret.',
115
+				'remote server ('.$url.') presented lower token. We will initiate the exchange of the shared secret.',
116 116
 				['app' => 'federation']
117 117
 			);
118 118
 			throw new OCSForbiddenException();
@@ -151,14 +151,14 @@  discard block
 block discarded – undo
151 151
 	 */
152 152
 	public function getSharedSecret($url, $token) {
153 153
 		if ($this->trustedServers->isTrustedServer($url) === false) {
154
-			$this->logger->error('remote server not trusted (' . $url . ') while getting shared secret', ['app' => 'federation']);
154
+			$this->logger->error('remote server not trusted ('.$url.') while getting shared secret', ['app' => 'federation']);
155 155
 			throw new OCSForbiddenException();
156 156
 		}
157 157
 
158 158
 		if ($this->isValidToken($url, $token) === false) {
159 159
 			$expectedToken = $this->dbHandler->getToken($url);
160 160
 			$this->logger->error(
161
-				'remote server (' . $url . ') didn\'t send a valid token (got "' . $token . '" but expected "'. $expectedToken . '") while getting shared secret',
161
+				'remote server ('.$url.') didn\'t send a valid token (got "'.$token.'" but expected "'.$expectedToken.'") while getting shared secret',
162 162
 				['app' => 'federation']
163 163
 			);
164 164
 			throw new OCSForbiddenException();
Please login to merge, or discard this patch.
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -46,169 +46,169 @@
 block discarded – undo
46 46
  */
47 47
 class OCSAuthAPIController extends OCSController{
48 48
 
49
-	/** @var ISecureRandom  */
50
-	private $secureRandom;
51
-
52
-	/** @var IJobList */
53
-	private $jobList;
54
-
55
-	/** @var TrustedServers */
56
-	private $trustedServers;
57
-
58
-	/** @var DbHandler */
59
-	private $dbHandler;
60
-
61
-	/** @var ILogger */
62
-	private $logger;
63
-
64
-	/**
65
-	 * OCSAuthAPI constructor.
66
-	 *
67
-	 * @param string $appName
68
-	 * @param IRequest $request
69
-	 * @param ISecureRandom $secureRandom
70
-	 * @param IJobList $jobList
71
-	 * @param TrustedServers $trustedServers
72
-	 * @param DbHandler $dbHandler
73
-	 * @param ILogger $logger
74
-	 */
75
-	public function __construct(
76
-		$appName,
77
-		IRequest $request,
78
-		ISecureRandom $secureRandom,
79
-		IJobList $jobList,
80
-		TrustedServers $trustedServers,
81
-		DbHandler $dbHandler,
82
-		ILogger $logger
83
-	) {
84
-		parent::__construct($appName, $request);
85
-
86
-		$this->secureRandom = $secureRandom;
87
-		$this->jobList = $jobList;
88
-		$this->trustedServers = $trustedServers;
89
-		$this->dbHandler = $dbHandler;
90
-		$this->logger = $logger;
91
-	}
92
-
93
-	/**
94
-	 * @NoCSRFRequired
95
-	 * @PublicPage
96
-	 *
97
-	 * request received to ask remote server for a shared secret, for legacy end-points
98
-	 *
99
-	 * @param string $url
100
-	 * @param string $token
101
-	 * @return Http\DataResponse
102
-	 * @throws OCSForbiddenException
103
-	 */
104
-	public function requestSharedSecretLegacy($url, $token) {
105
-		return $this->requestSharedSecret($url, $token);
106
-	}
107
-
108
-
109
-	/**
110
-	 * @NoCSRFRequired
111
-	 * @PublicPage
112
-	 *
113
-	 * create shared secret and return it, for legacy end-points
114
-	 *
115
-	 * @param string $url
116
-	 * @param string $token
117
-	 * @return Http\DataResponse
118
-	 * @throws OCSForbiddenException
119
-	 */
120
-	public function getSharedSecretLegacy($url, $token) {
121
-		return $this->getSharedSecret($url, $token);
122
-	}
123
-
124
-	/**
125
-	 * @NoCSRFRequired
126
-	 * @PublicPage
127
-	 *
128
-	 * request received to ask remote server for a shared secret
129
-	 *
130
-	 * @param string $url
131
-	 * @param string $token
132
-	 * @return Http\DataResponse
133
-	 * @throws OCSForbiddenException
134
-	 */
135
-	public function requestSharedSecret($url, $token) {
136
-		if ($this->trustedServers->isTrustedServer($url) === false) {
137
-			$this->logger->error('remote server not trusted (' . $url . ') while requesting shared secret', ['app' => 'federation']);
138
-			throw new OCSForbiddenException();
139
-		}
140
-
141
-		// if both server initiated the exchange of the shared secret the greater
142
-		// token wins
143
-		$localToken = $this->dbHandler->getToken($url);
144
-		if (strcmp($localToken, $token) > 0) {
145
-			$this->logger->info(
146
-				'remote server (' . $url . ') presented lower token. We will initiate the exchange of the shared secret.',
147
-				['app' => 'federation']
148
-			);
149
-			throw new OCSForbiddenException();
150
-		}
151
-
152
-		// we ask for the shared secret so we no longer have to ask the other server
153
-		// to request the shared secret
154
-		$this->jobList->remove('OCA\Federation\BackgroundJob\RequestSharedSecret',
155
-			[
156
-				'url' => $url,
157
-				'token' => $localToken
158
-			]
159
-		);
160
-
161
-		$this->jobList->add(
162
-			'OCA\Federation\BackgroundJob\GetSharedSecret',
163
-			[
164
-				'url' => $url,
165
-				'token' => $token,
166
-			]
167
-		);
168
-
169
-		return new Http\DataResponse();
170
-	}
171
-
172
-	/**
173
-	 * @NoCSRFRequired
174
-	 * @PublicPage
175
-	 *
176
-	 * create shared secret and return it
177
-	 *
178
-	 * @param string $url
179
-	 * @param string $token
180
-	 * @return Http\DataResponse
181
-	 * @throws OCSForbiddenException
182
-	 */
183
-	public function getSharedSecret($url, $token) {
184
-		if ($this->trustedServers->isTrustedServer($url) === false) {
185
-			$this->logger->error('remote server not trusted (' . $url . ') while getting shared secret', ['app' => 'federation']);
186
-			throw new OCSForbiddenException();
187
-		}
188
-
189
-		if ($this->isValidToken($url, $token) === false) {
190
-			$expectedToken = $this->dbHandler->getToken($url);
191
-			$this->logger->error(
192
-				'remote server (' . $url . ') didn\'t send a valid token (got "' . $token . '" but expected "'. $expectedToken . '") while getting shared secret',
193
-				['app' => 'federation']
194
-			);
195
-			throw new OCSForbiddenException();
196
-		}
197
-
198
-		$sharedSecret = $this->secureRandom->generate(32);
199
-
200
-		$this->trustedServers->addSharedSecret($url, $sharedSecret);
201
-		// reset token after the exchange of the shared secret was successful
202
-		$this->dbHandler->addToken($url, '');
203
-
204
-		return new Http\DataResponse([
205
-			'sharedSecret' => $sharedSecret
206
-		]);
207
-	}
208
-
209
-	protected function isValidToken($url, $token) {
210
-		$storedToken = $this->dbHandler->getToken($url);
211
-		return hash_equals($storedToken, $token);
212
-	}
49
+    /** @var ISecureRandom  */
50
+    private $secureRandom;
51
+
52
+    /** @var IJobList */
53
+    private $jobList;
54
+
55
+    /** @var TrustedServers */
56
+    private $trustedServers;
57
+
58
+    /** @var DbHandler */
59
+    private $dbHandler;
60
+
61
+    /** @var ILogger */
62
+    private $logger;
63
+
64
+    /**
65
+     * OCSAuthAPI constructor.
66
+     *
67
+     * @param string $appName
68
+     * @param IRequest $request
69
+     * @param ISecureRandom $secureRandom
70
+     * @param IJobList $jobList
71
+     * @param TrustedServers $trustedServers
72
+     * @param DbHandler $dbHandler
73
+     * @param ILogger $logger
74
+     */
75
+    public function __construct(
76
+        $appName,
77
+        IRequest $request,
78
+        ISecureRandom $secureRandom,
79
+        IJobList $jobList,
80
+        TrustedServers $trustedServers,
81
+        DbHandler $dbHandler,
82
+        ILogger $logger
83
+    ) {
84
+        parent::__construct($appName, $request);
85
+
86
+        $this->secureRandom = $secureRandom;
87
+        $this->jobList = $jobList;
88
+        $this->trustedServers = $trustedServers;
89
+        $this->dbHandler = $dbHandler;
90
+        $this->logger = $logger;
91
+    }
92
+
93
+    /**
94
+     * @NoCSRFRequired
95
+     * @PublicPage
96
+     *
97
+     * request received to ask remote server for a shared secret, for legacy end-points
98
+     *
99
+     * @param string $url
100
+     * @param string $token
101
+     * @return Http\DataResponse
102
+     * @throws OCSForbiddenException
103
+     */
104
+    public function requestSharedSecretLegacy($url, $token) {
105
+        return $this->requestSharedSecret($url, $token);
106
+    }
107
+
108
+
109
+    /**
110
+     * @NoCSRFRequired
111
+     * @PublicPage
112
+     *
113
+     * create shared secret and return it, for legacy end-points
114
+     *
115
+     * @param string $url
116
+     * @param string $token
117
+     * @return Http\DataResponse
118
+     * @throws OCSForbiddenException
119
+     */
120
+    public function getSharedSecretLegacy($url, $token) {
121
+        return $this->getSharedSecret($url, $token);
122
+    }
123
+
124
+    /**
125
+     * @NoCSRFRequired
126
+     * @PublicPage
127
+     *
128
+     * request received to ask remote server for a shared secret
129
+     *
130
+     * @param string $url
131
+     * @param string $token
132
+     * @return Http\DataResponse
133
+     * @throws OCSForbiddenException
134
+     */
135
+    public function requestSharedSecret($url, $token) {
136
+        if ($this->trustedServers->isTrustedServer($url) === false) {
137
+            $this->logger->error('remote server not trusted (' . $url . ') while requesting shared secret', ['app' => 'federation']);
138
+            throw new OCSForbiddenException();
139
+        }
140
+
141
+        // if both server initiated the exchange of the shared secret the greater
142
+        // token wins
143
+        $localToken = $this->dbHandler->getToken($url);
144
+        if (strcmp($localToken, $token) > 0) {
145
+            $this->logger->info(
146
+                'remote server (' . $url . ') presented lower token. We will initiate the exchange of the shared secret.',
147
+                ['app' => 'federation']
148
+            );
149
+            throw new OCSForbiddenException();
150
+        }
151
+
152
+        // we ask for the shared secret so we no longer have to ask the other server
153
+        // to request the shared secret
154
+        $this->jobList->remove('OCA\Federation\BackgroundJob\RequestSharedSecret',
155
+            [
156
+                'url' => $url,
157
+                'token' => $localToken
158
+            ]
159
+        );
160
+
161
+        $this->jobList->add(
162
+            'OCA\Federation\BackgroundJob\GetSharedSecret',
163
+            [
164
+                'url' => $url,
165
+                'token' => $token,
166
+            ]
167
+        );
168
+
169
+        return new Http\DataResponse();
170
+    }
171
+
172
+    /**
173
+     * @NoCSRFRequired
174
+     * @PublicPage
175
+     *
176
+     * create shared secret and return it
177
+     *
178
+     * @param string $url
179
+     * @param string $token
180
+     * @return Http\DataResponse
181
+     * @throws OCSForbiddenException
182
+     */
183
+    public function getSharedSecret($url, $token) {
184
+        if ($this->trustedServers->isTrustedServer($url) === false) {
185
+            $this->logger->error('remote server not trusted (' . $url . ') while getting shared secret', ['app' => 'federation']);
186
+            throw new OCSForbiddenException();
187
+        }
188
+
189
+        if ($this->isValidToken($url, $token) === false) {
190
+            $expectedToken = $this->dbHandler->getToken($url);
191
+            $this->logger->error(
192
+                'remote server (' . $url . ') didn\'t send a valid token (got "' . $token . '" but expected "'. $expectedToken . '") while getting shared secret',
193
+                ['app' => 'federation']
194
+            );
195
+            throw new OCSForbiddenException();
196
+        }
197
+
198
+        $sharedSecret = $this->secureRandom->generate(32);
199
+
200
+        $this->trustedServers->addSharedSecret($url, $sharedSecret);
201
+        // reset token after the exchange of the shared secret was successful
202
+        $this->dbHandler->addToken($url, '');
203
+
204
+        return new Http\DataResponse([
205
+            'sharedSecret' => $sharedSecret
206
+        ]);
207
+    }
208
+
209
+    protected function isValidToken($url, $token) {
210
+        $storedToken = $this->dbHandler->getToken($url);
211
+        return hash_equals($storedToken, $token);
212
+    }
213 213
 
214 214
 }
Please login to merge, or discard this patch.
apps/federation/lib/AppInfo/Application.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -82,7 +82,7 @@
 block discarded – undo
82 82
 			);
83 83
 		});
84 84
 
85
-		$container->registerService('SettingsController', function (IAppContainer $c) {
85
+		$container->registerService('SettingsController', function(IAppContainer $c) {
86 86
 			$server = $c->getServer();
87 87
 			return new SettingsController(
88 88
 				$c->getAppName(),
Please login to merge, or discard this patch.
Indentation   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -42,101 +42,101 @@
 block discarded – undo
42 42
 
43 43
 class Application extends \OCP\AppFramework\App {
44 44
 
45
-	/**
46
-	 * @param array $urlParams
47
-	 */
48
-	public function __construct($urlParams = array()) {
49
-		parent::__construct('federation', $urlParams);
50
-		$this->registerService();
51
-		$this->registerMiddleware();
52
-	}
53
-
54
-	private function registerService() {
55
-		$container = $this->getContainer();
56
-
57
-		$container->registerService('addServerMiddleware', function(IAppContainer $c) {
58
-			return new AddServerMiddleware(
59
-				$c->getAppName(),
60
-				\OC::$server->getL10N($c->getAppName()),
61
-				\OC::$server->getLogger()
62
-			);
63
-		});
64
-
65
-		$container->registerService('DbHandler', function(IAppContainer $c) {
66
-			return new DbHandler(
67
-				\OC::$server->getDatabaseConnection(),
68
-				\OC::$server->getL10N($c->getAppName())
69
-			);
70
-		});
71
-
72
-		$container->registerService('TrustedServers', function(IAppContainer $c) {
73
-			$server = $c->getServer();
74
-			return new TrustedServers(
75
-				$c->query('DbHandler'),
76
-				$server->getHTTPClientService(),
77
-				$server->getLogger(),
78
-				$server->getJobList(),
79
-				$server->getSecureRandom(),
80
-				$server->getConfig(),
81
-				$server->getEventDispatcher()
82
-			);
83
-		});
84
-
85
-		$container->registerService('SettingsController', function (IAppContainer $c) {
86
-			$server = $c->getServer();
87
-			return new SettingsController(
88
-				$c->getAppName(),
89
-				$server->getRequest(),
90
-				$server->getL10N($c->getAppName()),
91
-				$c->query('TrustedServers')
92
-			);
93
-		});
94
-
95
-	}
96
-
97
-	private function registerMiddleware() {
98
-		$container = $this->getContainer();
99
-		$container->registerMiddleware('addServerMiddleware');
100
-	}
101
-
102
-	/**
103
-	 * listen to federated_share_added hooks to auto-add new servers to the
104
-	 * list of trusted servers.
105
-	 */
106
-	public function registerHooks() {
107
-
108
-		$container = $this->getContainer();
109
-		$hooksManager = new Hooks($container->query('TrustedServers'));
110
-
111
-		Util::connectHook(
112
-				'OCP\Share',
113
-				'federated_share_added',
114
-				$hooksManager,
115
-				'addServerHook'
116
-		);
117
-
118
-		$dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
119
-		$dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function($event) use($container) {
120
-			if ($event instanceof SabrePluginEvent) {
121
-				$authPlugin = $event->getServer()->getPlugin('auth');
122
-				if ($authPlugin instanceof Plugin) {
123
-					$h = new DbHandler($container->getServer()->getDatabaseConnection(),
124
-							$container->getServer()->getL10N('federation')
125
-					);
126
-					$authPlugin->addBackend(new FedAuth($h));
127
-				}
128
-			}
129
-		});
130
-	}
131
-
132
-	/**
133
-	 * @return SyncFederationAddressBooks
134
-	 */
135
-	public function getSyncService() {
136
-		$syncService = \OC::$server->query('CardDAVSyncService');
137
-		$dbHandler = $this->getContainer()->query('DbHandler');
138
-		$discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
139
-		return new SyncFederationAddressBooks($dbHandler, $syncService, $discoveryService);
140
-	}
45
+    /**
46
+     * @param array $urlParams
47
+     */
48
+    public function __construct($urlParams = array()) {
49
+        parent::__construct('federation', $urlParams);
50
+        $this->registerService();
51
+        $this->registerMiddleware();
52
+    }
53
+
54
+    private function registerService() {
55
+        $container = $this->getContainer();
56
+
57
+        $container->registerService('addServerMiddleware', function(IAppContainer $c) {
58
+            return new AddServerMiddleware(
59
+                $c->getAppName(),
60
+                \OC::$server->getL10N($c->getAppName()),
61
+                \OC::$server->getLogger()
62
+            );
63
+        });
64
+
65
+        $container->registerService('DbHandler', function(IAppContainer $c) {
66
+            return new DbHandler(
67
+                \OC::$server->getDatabaseConnection(),
68
+                \OC::$server->getL10N($c->getAppName())
69
+            );
70
+        });
71
+
72
+        $container->registerService('TrustedServers', function(IAppContainer $c) {
73
+            $server = $c->getServer();
74
+            return new TrustedServers(
75
+                $c->query('DbHandler'),
76
+                $server->getHTTPClientService(),
77
+                $server->getLogger(),
78
+                $server->getJobList(),
79
+                $server->getSecureRandom(),
80
+                $server->getConfig(),
81
+                $server->getEventDispatcher()
82
+            );
83
+        });
84
+
85
+        $container->registerService('SettingsController', function (IAppContainer $c) {
86
+            $server = $c->getServer();
87
+            return new SettingsController(
88
+                $c->getAppName(),
89
+                $server->getRequest(),
90
+                $server->getL10N($c->getAppName()),
91
+                $c->query('TrustedServers')
92
+            );
93
+        });
94
+
95
+    }
96
+
97
+    private function registerMiddleware() {
98
+        $container = $this->getContainer();
99
+        $container->registerMiddleware('addServerMiddleware');
100
+    }
101
+
102
+    /**
103
+     * listen to federated_share_added hooks to auto-add new servers to the
104
+     * list of trusted servers.
105
+     */
106
+    public function registerHooks() {
107
+
108
+        $container = $this->getContainer();
109
+        $hooksManager = new Hooks($container->query('TrustedServers'));
110
+
111
+        Util::connectHook(
112
+                'OCP\Share',
113
+                'federated_share_added',
114
+                $hooksManager,
115
+                'addServerHook'
116
+        );
117
+
118
+        $dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
119
+        $dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function($event) use($container) {
120
+            if ($event instanceof SabrePluginEvent) {
121
+                $authPlugin = $event->getServer()->getPlugin('auth');
122
+                if ($authPlugin instanceof Plugin) {
123
+                    $h = new DbHandler($container->getServer()->getDatabaseConnection(),
124
+                            $container->getServer()->getL10N('federation')
125
+                    );
126
+                    $authPlugin->addBackend(new FedAuth($h));
127
+                }
128
+            }
129
+        });
130
+    }
131
+
132
+    /**
133
+     * @return SyncFederationAddressBooks
134
+     */
135
+    public function getSyncService() {
136
+        $syncService = \OC::$server->query('CardDAVSyncService');
137
+        $dbHandler = $this->getContainer()->query('DbHandler');
138
+        $discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
139
+        return new SyncFederationAddressBooks($dbHandler, $syncService, $discoveryService);
140
+    }
141 141
 
142 142
 }
Please login to merge, or discard this patch.
apps/federation/lib/Command/SyncFederationAddressBooks.php 2 patches
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -31,45 +31,45 @@
 block discarded – undo
31 31
 
32 32
 class SyncFederationAddressBooks extends Command {
33 33
 
34
-	/** @var \OCA\Federation\SyncFederationAddressBooks */
35
-	private $syncService;
34
+    /** @var \OCA\Federation\SyncFederationAddressBooks */
35
+    private $syncService;
36 36
 
37
-	/**
38
-	 * @param \OCA\Federation\SyncFederationAddressBooks $syncService
39
-	 */
40
-	function __construct(\OCA\Federation\SyncFederationAddressBooks $syncService) {
41
-		parent::__construct();
37
+    /**
38
+     * @param \OCA\Federation\SyncFederationAddressBooks $syncService
39
+     */
40
+    function __construct(\OCA\Federation\SyncFederationAddressBooks $syncService) {
41
+        parent::__construct();
42 42
 
43
-		$this->syncService = $syncService;
44
-	}
43
+        $this->syncService = $syncService;
44
+    }
45 45
 
46
-	protected function configure() {
47
-		$this
48
-			->setName('federation:sync-addressbooks')
49
-			->setDescription('Synchronizes addressbooks of all federated clouds');
50
-	}
46
+    protected function configure() {
47
+        $this
48
+            ->setName('federation:sync-addressbooks')
49
+            ->setDescription('Synchronizes addressbooks of all federated clouds');
50
+    }
51 51
 
52
-	/**
53
-	 * @param InputInterface $input
54
-	 * @param OutputInterface $output
55
-	 * @return int
56
-	 */
57
-	protected function execute(InputInterface $input, OutputInterface $output) {
52
+    /**
53
+     * @param InputInterface $input
54
+     * @param OutputInterface $output
55
+     * @return int
56
+     */
57
+    protected function execute(InputInterface $input, OutputInterface $output) {
58 58
 
59
-		$progress = new ProgressBar($output);
60
-		$progress->start();
61
-		$this->syncService->syncThemAll(function($url, $ex) use ($progress, $output) {
62
-			if ($ex instanceof \Exception) {
63
-				$output->writeln("Error while syncing $url : " . $ex->getMessage());
59
+        $progress = new ProgressBar($output);
60
+        $progress->start();
61
+        $this->syncService->syncThemAll(function($url, $ex) use ($progress, $output) {
62
+            if ($ex instanceof \Exception) {
63
+                $output->writeln("Error while syncing $url : " . $ex->getMessage());
64 64
 
65
-			} else {
66
-				$progress->advance();
67
-			}
68
-		});
65
+            } else {
66
+                $progress->advance();
67
+            }
68
+        });
69 69
 
70
-		$progress->finish();
71
-		$output->writeln('');
70
+        $progress->finish();
71
+        $output->writeln('');
72 72
 
73
-		return 0;
74
-	}
73
+        return 0;
74
+    }
75 75
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@
 block discarded – undo
60 60
 		$progress->start();
61 61
 		$this->syncService->syncThemAll(function($url, $ex) use ($progress, $output) {
62 62
 			if ($ex instanceof \Exception) {
63
-				$output->writeln("Error while syncing $url : " . $ex->getMessage());
63
+				$output->writeln("Error while syncing $url : ".$ex->getMessage());
64 64
 
65 65
 			} else {
66 66
 				$progress->advance();
Please login to merge, or discard this patch.
apps/federation/lib/TrustedServers.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
 		$client = $this->httpClientService->newClient();
222 222
 		try {
223 223
 			$result = $client->get(
224
-				$url . '/status.php',
224
+				$url.'/status.php',
225 225
 				[
226 226
 					'timeout' => 3,
227 227
 					'connect_timeout' => 3,
@@ -232,7 +232,7 @@  discard block
 block discarded – undo
232 232
 
233 233
 			}
234 234
 		} catch (\Exception $e) {
235
-			$this->logger->debug('No Nextcloud server: ' . $e->getMessage());
235
+			$this->logger->debug('No Nextcloud server: '.$e->getMessage());
236 236
 			return false;
237 237
 		}
238 238
 
@@ -273,6 +273,6 @@  discard block
 block discarded – undo
273 273
 
274 274
 		}
275 275
 
276
-		return 'https://' . $url;
276
+		return 'https://'.$url;
277 277
 	}
278 278
 }
Please login to merge, or discard this patch.
Indentation   +237 added lines, -237 removed lines patch added patch discarded remove patch
@@ -38,241 +38,241 @@
 block discarded – undo
38 38
 
39 39
 class TrustedServers {
40 40
 
41
-	/** after a user list was exchanged at least once successfully */
42
-	const STATUS_OK = 1;
43
-	/** waiting for shared secret or initial user list exchange */
44
-	const STATUS_PENDING = 2;
45
-	/** something went wrong, misconfigured server, software bug,... user interaction needed */
46
-	const STATUS_FAILURE = 3;
47
-	/** remote server revoked access */
48
-	const STATUS_ACCESS_REVOKED = 4;
49
-
50
-	/** @var  dbHandler */
51
-	private $dbHandler;
52
-
53
-	/** @var  IClientService */
54
-	private $httpClientService;
55
-
56
-	/** @var ILogger */
57
-	private $logger;
58
-
59
-	/** @var IJobList */
60
-	private $jobList;
61
-
62
-	/** @var ISecureRandom */
63
-	private $secureRandom;
64
-
65
-	/** @var IConfig */
66
-	private $config;
67
-
68
-	/** @var EventDispatcherInterface */
69
-	private $dispatcher;
70
-
71
-	/**
72
-	 * @param DbHandler $dbHandler
73
-	 * @param IClientService $httpClientService
74
-	 * @param ILogger $logger
75
-	 * @param IJobList $jobList
76
-	 * @param ISecureRandom $secureRandom
77
-	 * @param IConfig $config
78
-	 * @param EventDispatcherInterface $dispatcher
79
-	 */
80
-	public function __construct(
81
-		DbHandler $dbHandler,
82
-		IClientService $httpClientService,
83
-		ILogger $logger,
84
-		IJobList $jobList,
85
-		ISecureRandom $secureRandom,
86
-		IConfig $config,
87
-		EventDispatcherInterface $dispatcher
88
-	) {
89
-		$this->dbHandler = $dbHandler;
90
-		$this->httpClientService = $httpClientService;
91
-		$this->logger = $logger;
92
-		$this->jobList = $jobList;
93
-		$this->secureRandom = $secureRandom;
94
-		$this->config = $config;
95
-		$this->dispatcher = $dispatcher;
96
-	}
97
-
98
-	/**
99
-	 * add server to the list of trusted servers
100
-	 *
101
-	 * @param $url
102
-	 * @return int server id
103
-	 */
104
-	public function addServer($url) {
105
-		$url = $this->updateProtocol($url);
106
-		$result = $this->dbHandler->addServer($url);
107
-		if ($result) {
108
-			$token = $this->secureRandom->generate(16);
109
-			$this->dbHandler->addToken($url, $token);
110
-			$this->jobList->add(
111
-				'OCA\Federation\BackgroundJob\RequestSharedSecret',
112
-				[
113
-					'url' => $url,
114
-					'token' => $token
115
-				]
116
-			);
117
-		}
118
-
119
-		return $result;
120
-	}
121
-
122
-	/**
123
-	 * enable/disable to automatically add servers to the list of trusted servers
124
-	 * once a federated share was created and accepted successfully
125
-	 *
126
-	 * @param bool $status
127
-	 */
128
-	public function setAutoAddServers($status) {
129
-		$value = $status ? '1' : '0';
130
-		$this->config->setAppValue('federation', 'autoAddServers', $value);
131
-	}
132
-
133
-	/**
134
-	 * return if we automatically add servers to the list of trusted servers
135
-	 * once a federated share was created and accepted successfully
136
-	 *
137
-	 * @return bool
138
-	 */
139
-	public function getAutoAddServers() {
140
-		$value = $this->config->getAppValue('federation', 'autoAddServers', '0');
141
-		return $value === '1';
142
-	}
143
-
144
-	/**
145
-	 * get shared secret for the given server
146
-	 *
147
-	 * @param string $url
148
-	 * @return string
149
-	 */
150
-	public function getSharedSecret($url) {
151
-		return $this->dbHandler->getSharedSecret($url);
152
-	}
153
-
154
-	/**
155
-	 * add shared secret for the given server
156
-	 *
157
-	 * @param string $url
158
-	 * @param $sharedSecret
159
-	 */
160
-	public function addSharedSecret($url, $sharedSecret) {
161
-		$this->dbHandler->addSharedSecret($url, $sharedSecret);
162
-	}
163
-
164
-	/**
165
-	 * remove server from the list of trusted servers
166
-	 *
167
-	 * @param int $id
168
-	 */
169
-	public function removeServer($id) {
170
-		$server = $this->dbHandler->getServerById($id);
171
-		$this->dbHandler->removeServer($id);
172
-		$event = new GenericEvent($server['url_hash']);
173
-		$this->dispatcher->dispatch('OCP\Federation\TrustedServerEvent::remove', $event);
174
-	}
175
-
176
-	/**
177
-	 * get all trusted servers
178
-	 *
179
-	 * @return array
180
-	 */
181
-	public function getServers() {
182
-		return $this->dbHandler->getAllServer();
183
-	}
184
-
185
-	/**
186
-	 * check if given server is a trusted Nextcloud server
187
-	 *
188
-	 * @param string $url
189
-	 * @return bool
190
-	 */
191
-	public function isTrustedServer($url) {
192
-		return $this->dbHandler->serverExists($url);
193
-	}
194
-
195
-	/**
196
-	 * set server status
197
-	 *
198
-	 * @param string $url
199
-	 * @param int $status
200
-	 */
201
-	public function setServerStatus($url, $status) {
202
-		$this->dbHandler->setServerStatus($url, $status);
203
-	}
204
-
205
-	/**
206
-	 * @param string $url
207
-	 * @return int
208
-	 */
209
-	public function getServerStatus($url) {
210
-		return $this->dbHandler->getServerStatus($url);
211
-	}
212
-
213
-	/**
214
-	 * check if URL point to a ownCloud/Nextcloud server
215
-	 *
216
-	 * @param string $url
217
-	 * @return bool
218
-	 */
219
-	public function isOwnCloudServer($url) {
220
-		$isValidOwnCloud = false;
221
-		$client = $this->httpClientService->newClient();
222
-		try {
223
-			$result = $client->get(
224
-				$url . '/status.php',
225
-				[
226
-					'timeout' => 3,
227
-					'connect_timeout' => 3,
228
-				]
229
-			);
230
-			if ($result->getStatusCode() === Http::STATUS_OK) {
231
-				$isValidOwnCloud = $this->checkOwnCloudVersion($result->getBody());
232
-
233
-			}
234
-		} catch (\Exception $e) {
235
-			$this->logger->debug('No Nextcloud server: ' . $e->getMessage());
236
-			return false;
237
-		}
238
-
239
-		return $isValidOwnCloud;
240
-	}
241
-
242
-	/**
243
-	 * check if ownCloud version is >= 9.0
244
-	 *
245
-	 * @param $status
246
-	 * @return bool
247
-	 * @throws HintException
248
-	 */
249
-	protected function checkOwnCloudVersion($status) {
250
-		$decoded = json_decode($status, true);
251
-		if (!empty($decoded) && isset($decoded['version'])) {
252
-			if (!version_compare($decoded['version'], '9.0.0', '>=')) {
253
-				throw new HintException('Remote server version is too low. 9.0 is required.');
254
-			}
255
-			return true;
256
-		}
257
-		return false;
258
-	}
259
-
260
-	/**
261
-	 * check if the URL contain a protocol, if not add https
262
-	 *
263
-	 * @param string $url
264
-	 * @return string
265
-	 */
266
-	protected function updateProtocol($url) {
267
-		if (
268
-			strpos($url, 'https://') === 0
269
-			|| strpos($url, 'http://') === 0
270
-		) {
271
-
272
-			return $url;
273
-
274
-		}
275
-
276
-		return 'https://' . $url;
277
-	}
41
+    /** after a user list was exchanged at least once successfully */
42
+    const STATUS_OK = 1;
43
+    /** waiting for shared secret or initial user list exchange */
44
+    const STATUS_PENDING = 2;
45
+    /** something went wrong, misconfigured server, software bug,... user interaction needed */
46
+    const STATUS_FAILURE = 3;
47
+    /** remote server revoked access */
48
+    const STATUS_ACCESS_REVOKED = 4;
49
+
50
+    /** @var  dbHandler */
51
+    private $dbHandler;
52
+
53
+    /** @var  IClientService */
54
+    private $httpClientService;
55
+
56
+    /** @var ILogger */
57
+    private $logger;
58
+
59
+    /** @var IJobList */
60
+    private $jobList;
61
+
62
+    /** @var ISecureRandom */
63
+    private $secureRandom;
64
+
65
+    /** @var IConfig */
66
+    private $config;
67
+
68
+    /** @var EventDispatcherInterface */
69
+    private $dispatcher;
70
+
71
+    /**
72
+     * @param DbHandler $dbHandler
73
+     * @param IClientService $httpClientService
74
+     * @param ILogger $logger
75
+     * @param IJobList $jobList
76
+     * @param ISecureRandom $secureRandom
77
+     * @param IConfig $config
78
+     * @param EventDispatcherInterface $dispatcher
79
+     */
80
+    public function __construct(
81
+        DbHandler $dbHandler,
82
+        IClientService $httpClientService,
83
+        ILogger $logger,
84
+        IJobList $jobList,
85
+        ISecureRandom $secureRandom,
86
+        IConfig $config,
87
+        EventDispatcherInterface $dispatcher
88
+    ) {
89
+        $this->dbHandler = $dbHandler;
90
+        $this->httpClientService = $httpClientService;
91
+        $this->logger = $logger;
92
+        $this->jobList = $jobList;
93
+        $this->secureRandom = $secureRandom;
94
+        $this->config = $config;
95
+        $this->dispatcher = $dispatcher;
96
+    }
97
+
98
+    /**
99
+     * add server to the list of trusted servers
100
+     *
101
+     * @param $url
102
+     * @return int server id
103
+     */
104
+    public function addServer($url) {
105
+        $url = $this->updateProtocol($url);
106
+        $result = $this->dbHandler->addServer($url);
107
+        if ($result) {
108
+            $token = $this->secureRandom->generate(16);
109
+            $this->dbHandler->addToken($url, $token);
110
+            $this->jobList->add(
111
+                'OCA\Federation\BackgroundJob\RequestSharedSecret',
112
+                [
113
+                    'url' => $url,
114
+                    'token' => $token
115
+                ]
116
+            );
117
+        }
118
+
119
+        return $result;
120
+    }
121
+
122
+    /**
123
+     * enable/disable to automatically add servers to the list of trusted servers
124
+     * once a federated share was created and accepted successfully
125
+     *
126
+     * @param bool $status
127
+     */
128
+    public function setAutoAddServers($status) {
129
+        $value = $status ? '1' : '0';
130
+        $this->config->setAppValue('federation', 'autoAddServers', $value);
131
+    }
132
+
133
+    /**
134
+     * return if we automatically add servers to the list of trusted servers
135
+     * once a federated share was created and accepted successfully
136
+     *
137
+     * @return bool
138
+     */
139
+    public function getAutoAddServers() {
140
+        $value = $this->config->getAppValue('federation', 'autoAddServers', '0');
141
+        return $value === '1';
142
+    }
143
+
144
+    /**
145
+     * get shared secret for the given server
146
+     *
147
+     * @param string $url
148
+     * @return string
149
+     */
150
+    public function getSharedSecret($url) {
151
+        return $this->dbHandler->getSharedSecret($url);
152
+    }
153
+
154
+    /**
155
+     * add shared secret for the given server
156
+     *
157
+     * @param string $url
158
+     * @param $sharedSecret
159
+     */
160
+    public function addSharedSecret($url, $sharedSecret) {
161
+        $this->dbHandler->addSharedSecret($url, $sharedSecret);
162
+    }
163
+
164
+    /**
165
+     * remove server from the list of trusted servers
166
+     *
167
+     * @param int $id
168
+     */
169
+    public function removeServer($id) {
170
+        $server = $this->dbHandler->getServerById($id);
171
+        $this->dbHandler->removeServer($id);
172
+        $event = new GenericEvent($server['url_hash']);
173
+        $this->dispatcher->dispatch('OCP\Federation\TrustedServerEvent::remove', $event);
174
+    }
175
+
176
+    /**
177
+     * get all trusted servers
178
+     *
179
+     * @return array
180
+     */
181
+    public function getServers() {
182
+        return $this->dbHandler->getAllServer();
183
+    }
184
+
185
+    /**
186
+     * check if given server is a trusted Nextcloud server
187
+     *
188
+     * @param string $url
189
+     * @return bool
190
+     */
191
+    public function isTrustedServer($url) {
192
+        return $this->dbHandler->serverExists($url);
193
+    }
194
+
195
+    /**
196
+     * set server status
197
+     *
198
+     * @param string $url
199
+     * @param int $status
200
+     */
201
+    public function setServerStatus($url, $status) {
202
+        $this->dbHandler->setServerStatus($url, $status);
203
+    }
204
+
205
+    /**
206
+     * @param string $url
207
+     * @return int
208
+     */
209
+    public function getServerStatus($url) {
210
+        return $this->dbHandler->getServerStatus($url);
211
+    }
212
+
213
+    /**
214
+     * check if URL point to a ownCloud/Nextcloud server
215
+     *
216
+     * @param string $url
217
+     * @return bool
218
+     */
219
+    public function isOwnCloudServer($url) {
220
+        $isValidOwnCloud = false;
221
+        $client = $this->httpClientService->newClient();
222
+        try {
223
+            $result = $client->get(
224
+                $url . '/status.php',
225
+                [
226
+                    'timeout' => 3,
227
+                    'connect_timeout' => 3,
228
+                ]
229
+            );
230
+            if ($result->getStatusCode() === Http::STATUS_OK) {
231
+                $isValidOwnCloud = $this->checkOwnCloudVersion($result->getBody());
232
+
233
+            }
234
+        } catch (\Exception $e) {
235
+            $this->logger->debug('No Nextcloud server: ' . $e->getMessage());
236
+            return false;
237
+        }
238
+
239
+        return $isValidOwnCloud;
240
+    }
241
+
242
+    /**
243
+     * check if ownCloud version is >= 9.0
244
+     *
245
+     * @param $status
246
+     * @return bool
247
+     * @throws HintException
248
+     */
249
+    protected function checkOwnCloudVersion($status) {
250
+        $decoded = json_decode($status, true);
251
+        if (!empty($decoded) && isset($decoded['version'])) {
252
+            if (!version_compare($decoded['version'], '9.0.0', '>=')) {
253
+                throw new HintException('Remote server version is too low. 9.0 is required.');
254
+            }
255
+            return true;
256
+        }
257
+        return false;
258
+    }
259
+
260
+    /**
261
+     * check if the URL contain a protocol, if not add https
262
+     *
263
+     * @param string $url
264
+     * @return string
265
+     */
266
+    protected function updateProtocol($url) {
267
+        if (
268
+            strpos($url, 'https://') === 0
269
+            || strpos($url, 'http://') === 0
270
+        ) {
271
+
272
+            return $url;
273
+
274
+        }
275
+
276
+        return 'https://' . $url;
277
+    }
278 278
 }
Please login to merge, or discard this patch.
apps/federation/lib/BackgroundJob/GetSharedSecret.php 3 patches
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -177,7 +177,7 @@
 block discarded – undo
177 177
 			&& $status !== Http::STATUS_FORBIDDEN
178 178
 		) {
179 179
 			$this->retainJob = true;
180
-		}  else {
180
+		} else {
181 181
 			// reset token if we received a valid response
182 182
 			$this->dbHandler->addToken($target, '');
183 183
 		}
Please login to merge, or discard this patch.
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -48,171 +48,171 @@
 block discarded – undo
48 48
  */
49 49
 class GetSharedSecret extends Job{
50 50
 
51
-	/** @var IClient */
52
-	private $httpClient;
53
-
54
-	/** @var IJobList */
55
-	private $jobList;
56
-
57
-	/** @var IURLGenerator */
58
-	private $urlGenerator;
59
-
60
-	/** @var TrustedServers  */
61
-	private $trustedServers;
62
-
63
-	/** @var DbHandler */
64
-	private $dbHandler;
65
-
66
-	/** @var IDiscoveryService  */
67
-	private $ocsDiscoveryService;
68
-
69
-	/** @var ILogger */
70
-	private $logger;
71
-
72
-	/** @var bool */
73
-	protected $retainJob = false;
74
-
75
-	private $format = '?format=json';
76
-
77
-	private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret';
78
-
79
-	/**
80
-	 * RequestSharedSecret constructor.
81
-	 *
82
-	 * @param IClient $httpClient
83
-	 * @param IURLGenerator $urlGenerator
84
-	 * @param IJobList $jobList
85
-	 * @param TrustedServers $trustedServers
86
-	 * @param ILogger $logger
87
-	 * @param DbHandler $dbHandler
88
-	 * @param IDiscoveryService $ocsDiscoveryService
89
-	 */
90
-	public function __construct(
91
-		IClient $httpClient = null,
92
-		IURLGenerator $urlGenerator = null,
93
-		IJobList $jobList = null,
94
-		TrustedServers $trustedServers = null,
95
-		ILogger $logger = null,
96
-		DbHandler $dbHandler = null,
97
-		IDiscoveryService $ocsDiscoveryService = null
98
-	) {
99
-		$this->logger = $logger ? $logger : \OC::$server->getLogger();
100
-		$this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
101
-		$this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
102
-		$this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
103
-		$this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
104
-		$this->ocsDiscoveryService = $ocsDiscoveryService ? $ocsDiscoveryService : \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
105
-		if ($trustedServers) {
106
-			$this->trustedServers = $trustedServers;
107
-		} else {
108
-			$this->trustedServers = new TrustedServers(
109
-				$this->dbHandler,
110
-				\OC::$server->getHTTPClientService(),
111
-				$this->logger,
112
-				$this->jobList,
113
-				\OC::$server->getSecureRandom(),
114
-				\OC::$server->getConfig(),
115
-				\OC::$server->getEventDispatcher()
116
-			);
117
-		}
118
-	}
119
-
120
-	/**
121
-	 * run the job, then remove it from the joblist
122
-	 *
123
-	 * @param JobList $jobList
124
-	 * @param ILogger $logger
125
-	 */
126
-	public function execute($jobList, ILogger $logger = null) {
127
-		$target = $this->argument['url'];
128
-		// only execute if target is still in the list of trusted domains
129
-		if ($this->trustedServers->isTrustedServer($target)) {
130
-			$this->parentExecute($jobList, $logger);
131
-		}
132
-
133
-		if (!$this->retainJob) {
134
-			$jobList->remove($this, $this->argument);
135
-		}
136
-	}
137
-
138
-	/**
139
-	 * call execute() method of parent
140
-	 *
141
-	 * @param JobList $jobList
142
-	 * @param ILogger $logger
143
-	 */
144
-	protected function parentExecute($jobList, $logger = null) {
145
-		parent::execute($jobList, $logger);
146
-	}
147
-
148
-	protected function run($argument) {
149
-		$target = $argument['url'];
150
-		$source = $this->urlGenerator->getAbsoluteURL('/');
151
-		$source = rtrim($source, '/');
152
-		$token = $argument['token'];
153
-
154
-		$endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
155
-		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156
-
157
-		// make sure that we have a well formated url
158
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
159
-
160
-		$result = null;
161
-		try {
162
-			$result = $this->httpClient->get(
163
-				$url,
164
-				[
165
-					'query' =>
166
-						[
167
-							'url' => $source,
168
-							'token' => $token
169
-						],
170
-					'timeout' => 3,
171
-					'connect_timeout' => 3,
172
-				]
173
-			);
174
-
175
-			$status = $result->getStatusCode();
176
-
177
-		} catch (ClientException $e) {
178
-			$status = $e->getCode();
179
-			if ($status === Http::STATUS_FORBIDDEN) {
180
-				$this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
181
-			} else {
182
-				$this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
183
-			}
184
-		} catch (\Exception $e) {
185
-			$status = Http::STATUS_INTERNAL_SERVER_ERROR;
186
-			$this->logger->logException($e, ['app' => 'federation']);
187
-		}
188
-
189
-		// if we received a unexpected response we try again later
190
-		if (
191
-			$status !== Http::STATUS_OK
192
-			&& $status !== Http::STATUS_FORBIDDEN
193
-		) {
194
-			$this->retainJob = true;
195
-		}  else {
196
-			// reset token if we received a valid response
197
-			$this->dbHandler->addToken($target, '');
198
-		}
199
-
200
-		if ($status === Http::STATUS_OK && $result instanceof IResponse) {
201
-			$body = $result->getBody();
202
-			$result = json_decode($body, true);
203
-			if (isset($result['ocs']['data']['sharedSecret'])) {
204
-				$this->trustedServers->addSharedSecret(
205
-						$target,
206
-						$result['ocs']['data']['sharedSecret']
207
-				);
208
-			} else {
209
-				$this->logger->error(
210
-						'remote server "' . $target . '"" does not return a valid shared secret',
211
-						['app' => 'federation']
212
-				);
213
-				$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
214
-			}
215
-		}
216
-
217
-	}
51
+    /** @var IClient */
52
+    private $httpClient;
53
+
54
+    /** @var IJobList */
55
+    private $jobList;
56
+
57
+    /** @var IURLGenerator */
58
+    private $urlGenerator;
59
+
60
+    /** @var TrustedServers  */
61
+    private $trustedServers;
62
+
63
+    /** @var DbHandler */
64
+    private $dbHandler;
65
+
66
+    /** @var IDiscoveryService  */
67
+    private $ocsDiscoveryService;
68
+
69
+    /** @var ILogger */
70
+    private $logger;
71
+
72
+    /** @var bool */
73
+    protected $retainJob = false;
74
+
75
+    private $format = '?format=json';
76
+
77
+    private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret';
78
+
79
+    /**
80
+     * RequestSharedSecret constructor.
81
+     *
82
+     * @param IClient $httpClient
83
+     * @param IURLGenerator $urlGenerator
84
+     * @param IJobList $jobList
85
+     * @param TrustedServers $trustedServers
86
+     * @param ILogger $logger
87
+     * @param DbHandler $dbHandler
88
+     * @param IDiscoveryService $ocsDiscoveryService
89
+     */
90
+    public function __construct(
91
+        IClient $httpClient = null,
92
+        IURLGenerator $urlGenerator = null,
93
+        IJobList $jobList = null,
94
+        TrustedServers $trustedServers = null,
95
+        ILogger $logger = null,
96
+        DbHandler $dbHandler = null,
97
+        IDiscoveryService $ocsDiscoveryService = null
98
+    ) {
99
+        $this->logger = $logger ? $logger : \OC::$server->getLogger();
100
+        $this->httpClient = $httpClient ? $httpClient : \OC::$server->getHTTPClientService()->newClient();
101
+        $this->jobList = $jobList ? $jobList : \OC::$server->getJobList();
102
+        $this->urlGenerator = $urlGenerator ? $urlGenerator : \OC::$server->getURLGenerator();
103
+        $this->dbHandler = $dbHandler ? $dbHandler : new DbHandler(\OC::$server->getDatabaseConnection(), \OC::$server->getL10N('federation'));
104
+        $this->ocsDiscoveryService = $ocsDiscoveryService ? $ocsDiscoveryService : \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
105
+        if ($trustedServers) {
106
+            $this->trustedServers = $trustedServers;
107
+        } else {
108
+            $this->trustedServers = new TrustedServers(
109
+                $this->dbHandler,
110
+                \OC::$server->getHTTPClientService(),
111
+                $this->logger,
112
+                $this->jobList,
113
+                \OC::$server->getSecureRandom(),
114
+                \OC::$server->getConfig(),
115
+                \OC::$server->getEventDispatcher()
116
+            );
117
+        }
118
+    }
119
+
120
+    /**
121
+     * run the job, then remove it from the joblist
122
+     *
123
+     * @param JobList $jobList
124
+     * @param ILogger $logger
125
+     */
126
+    public function execute($jobList, ILogger $logger = null) {
127
+        $target = $this->argument['url'];
128
+        // only execute if target is still in the list of trusted domains
129
+        if ($this->trustedServers->isTrustedServer($target)) {
130
+            $this->parentExecute($jobList, $logger);
131
+        }
132
+
133
+        if (!$this->retainJob) {
134
+            $jobList->remove($this, $this->argument);
135
+        }
136
+    }
137
+
138
+    /**
139
+     * call execute() method of parent
140
+     *
141
+     * @param JobList $jobList
142
+     * @param ILogger $logger
143
+     */
144
+    protected function parentExecute($jobList, $logger = null) {
145
+        parent::execute($jobList, $logger);
146
+    }
147
+
148
+    protected function run($argument) {
149
+        $target = $argument['url'];
150
+        $source = $this->urlGenerator->getAbsoluteURL('/');
151
+        $source = rtrim($source, '/');
152
+        $token = $argument['token'];
153
+
154
+        $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
155
+        $endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156
+
157
+        // make sure that we have a well formated url
158
+        $url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
159
+
160
+        $result = null;
161
+        try {
162
+            $result = $this->httpClient->get(
163
+                $url,
164
+                [
165
+                    'query' =>
166
+                        [
167
+                            'url' => $source,
168
+                            'token' => $token
169
+                        ],
170
+                    'timeout' => 3,
171
+                    'connect_timeout' => 3,
172
+                ]
173
+            );
174
+
175
+            $status = $result->getStatusCode();
176
+
177
+        } catch (ClientException $e) {
178
+            $status = $e->getCode();
179
+            if ($status === Http::STATUS_FORBIDDEN) {
180
+                $this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
181
+            } else {
182
+                $this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
183
+            }
184
+        } catch (\Exception $e) {
185
+            $status = Http::STATUS_INTERNAL_SERVER_ERROR;
186
+            $this->logger->logException($e, ['app' => 'federation']);
187
+        }
188
+
189
+        // if we received a unexpected response we try again later
190
+        if (
191
+            $status !== Http::STATUS_OK
192
+            && $status !== Http::STATUS_FORBIDDEN
193
+        ) {
194
+            $this->retainJob = true;
195
+        }  else {
196
+            // reset token if we received a valid response
197
+            $this->dbHandler->addToken($target, '');
198
+        }
199
+
200
+        if ($status === Http::STATUS_OK && $result instanceof IResponse) {
201
+            $body = $result->getBody();
202
+            $result = json_decode($body, true);
203
+            if (isset($result['ocs']['data']['sharedSecret'])) {
204
+                $this->trustedServers->addSharedSecret(
205
+                        $target,
206
+                        $result['ocs']['data']['sharedSecret']
207
+                );
208
+            } else {
209
+                $this->logger->error(
210
+                        'remote server "' . $target . '"" does not return a valid shared secret',
211
+                        ['app' => 'federation']
212
+                );
213
+                $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
214
+            }
215
+        }
216
+
217
+    }
218 218
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
  *
47 47
  * @package OCA\Federation\Backgroundjob
48 48
  */
49
-class GetSharedSecret extends Job{
49
+class GetSharedSecret extends Job {
50 50
 
51 51
 	/** @var IClient */
52 52
 	private $httpClient;
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
156 156
 
157 157
 		// make sure that we have a well formated url
158
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/') . $this->format;
158
+		$url = rtrim($target, '/').'/'.trim($endPoint, '/').$this->format;
159 159
 
160 160
 		$result = null;
161 161
 		try {
@@ -177,9 +177,9 @@  discard block
 block discarded – undo
177 177
 		} catch (ClientException $e) {
178 178
 			$status = $e->getCode();
179 179
 			if ($status === Http::STATUS_FORBIDDEN) {
180
-				$this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
180
+				$this->logger->info($target.' refused to exchange a shared secret with you.', ['app' => 'federation']);
181 181
 			} else {
182
-				$this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
182
+				$this->logger->info($target.' responded with a '.$status.' containing: '.$e->getMessage(), ['app' => 'federation']);
183 183
 			}
184 184
 		} catch (\Exception $e) {
185 185
 			$status = Http::STATUS_INTERNAL_SERVER_ERROR;
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
 			&& $status !== Http::STATUS_FORBIDDEN
193 193
 		) {
194 194
 			$this->retainJob = true;
195
-		}  else {
195
+		} else {
196 196
 			// reset token if we received a valid response
197 197
 			$this->dbHandler->addToken($target, '');
198 198
 		}
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 				);
208 208
 			} else {
209 209
 				$this->logger->error(
210
-						'remote server "' . $target . '"" does not return a valid shared secret',
210
+						'remote server "'.$target.'"" does not return a valid shared secret',
211 211
 						['app' => 'federation']
212 212
 				);
213 213
 				$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
Please login to merge, or discard this patch.
apps/federation/lib/Settings/Admin.php 1 patch
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -29,41 +29,41 @@
 block discarded – undo
29 29
 
30 30
 class Admin implements ISettings {
31 31
 
32
-	/** @var TrustedServers */
33
-	private $trustedServers;
32
+    /** @var TrustedServers */
33
+    private $trustedServers;
34 34
 
35
-	public function __construct(TrustedServers $trustedServers) {
36
-		$this->trustedServers = $trustedServers;
37
-	}
35
+    public function __construct(TrustedServers $trustedServers) {
36
+        $this->trustedServers = $trustedServers;
37
+    }
38 38
 
39
-	/**
40
-	 * @return TemplateResponse
41
-	 */
42
-	public function getForm() {
43
-		$parameters = [
44
-			'trustedServers' => $this->trustedServers->getServers(),
45
-			'autoAddServers' => $this->trustedServers->getAutoAddServers(),
46
-		];
39
+    /**
40
+     * @return TemplateResponse
41
+     */
42
+    public function getForm() {
43
+        $parameters = [
44
+            'trustedServers' => $this->trustedServers->getServers(),
45
+            'autoAddServers' => $this->trustedServers->getAutoAddServers(),
46
+        ];
47 47
 
48
-		return new TemplateResponse('federation', 'settings-admin', $parameters, '');
49
-	}
48
+        return new TemplateResponse('federation', 'settings-admin', $parameters, '');
49
+    }
50 50
 
51
-	/**
52
-	 * @return string the section ID, e.g. 'sharing'
53
-	 */
54
-	public function getSection() {
55
-		return 'sharing';
56
-	}
51
+    /**
52
+     * @return string the section ID, e.g. 'sharing'
53
+     */
54
+    public function getSection() {
55
+        return 'sharing';
56
+    }
57 57
 
58
-	/**
59
-	 * @return int whether the form should be rather on the top or bottom of
60
-	 * the admin section. The forms are arranged in ascending order of the
61
-	 * priority values. It is required to return a value between 0 and 100.
62
-	 *
63
-	 * E.g.: 70
64
-	 */
65
-	public function getPriority() {
66
-		return 30;
67
-	}
58
+    /**
59
+     * @return int whether the form should be rather on the top or bottom of
60
+     * the admin section. The forms are arranged in ascending order of the
61
+     * priority values. It is required to return a value between 0 and 100.
62
+     *
63
+     * E.g.: 70
64
+     */
65
+    public function getPriority() {
66
+        return 30;
67
+    }
68 68
 
69 69
 }
Please login to merge, or discard this patch.
apps/federation/lib/Hooks.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -27,25 +27,25 @@
 block discarded – undo
27 27
 
28 28
 class Hooks {
29 29
 
30
-	/** @var TrustedServers */
31
-	private $trustedServers;
32
-
33
-	public function __construct(TrustedServers $trustedServers) {
34
-		$this->trustedServers = $trustedServers;
35
-	}
36
-
37
-	/**
38
-	 * add servers to the list of trusted servers once a federated share was established
39
-	 *
40
-	 * @param array $params
41
-	 */
42
-	public function addServerHook($params) {
43
-		if (
44
-			$this->trustedServers->getAutoAddServers() === true &&
45
-			$this->trustedServers->isTrustedServer($params['server']) === false
46
-		) {
47
-			$this->trustedServers->addServer($params['server']);
48
-		}
49
-	}
30
+    /** @var TrustedServers */
31
+    private $trustedServers;
32
+
33
+    public function __construct(TrustedServers $trustedServers) {
34
+        $this->trustedServers = $trustedServers;
35
+    }
36
+
37
+    /**
38
+     * add servers to the list of trusted servers once a federated share was established
39
+     *
40
+     * @param array $params
41
+     */
42
+    public function addServerHook($params) {
43
+        if (
44
+            $this->trustedServers->getAutoAddServers() === true &&
45
+            $this->trustedServers->isTrustedServer($params['server']) === false
46
+        ) {
47
+            $this->trustedServers->addServer($params['server']);
48
+        }
49
+    }
50 50
 
51 51
 }
Please login to merge, or discard this patch.
apps/federation/lib/DbHandler.php 2 patches
Indentation   +275 added lines, -275 removed lines patch added patch discarded remove patch
@@ -42,280 +42,280 @@
 block discarded – undo
42 42
  */
43 43
 class DbHandler {
44 44
 
45
-	/** @var  IDBConnection */
46
-	private $connection;
47
-
48
-	/** @var  IL10N */
49
-	private $IL10N;
50
-
51
-	/** @var string  */
52
-	private $dbTable = 'trusted_servers';
53
-
54
-	/**
55
-	 * @param IDBConnection $connection
56
-	 * @param IL10N $il10n
57
-	 */
58
-	public function __construct(
59
-		IDBConnection $connection,
60
-		IL10N $il10n
61
-	) {
62
-		$this->connection = $connection;
63
-		$this->IL10N = $il10n;
64
-	}
65
-
66
-	/**
67
-	 * add server to the list of trusted servers
68
-	 *
69
-	 * @param string $url
70
-	 * @return int
71
-	 * @throws HintException
72
-	 */
73
-	public function addServer($url) {
74
-		$hash = $this->hash($url);
75
-		$url = rtrim($url, '/');
76
-		$query = $this->connection->getQueryBuilder();
77
-		$query->insert($this->dbTable)
78
-			->values(
79
-				[
80
-					'url' =>  $query->createParameter('url'),
81
-					'url_hash' => $query->createParameter('url_hash'),
82
-				]
83
-			)
84
-			->setParameter('url', $url)
85
-			->setParameter('url_hash', $hash);
86
-
87
-		$result = $query->execute();
88
-
89
-		if ($result) {
90
-			return (int)$this->connection->lastInsertId('*PREFIX*'.$this->dbTable);
91
-		} else {
92
-			$message = 'Internal failure, Could not add trusted server: ' . $url;
93
-			$message_t = $this->IL10N->t('Could not add server');
94
-			throw new HintException($message, $message_t);
95
-		}
96
-	}
97
-
98
-	/**
99
-	 * remove server from the list of trusted servers
100
-	 *
101
-	 * @param int $id
102
-	 */
103
-	public function removeServer($id) {
104
-		$query = $this->connection->getQueryBuilder();
105
-		$query->delete($this->dbTable)
106
-			->where($query->expr()->eq('id', $query->createParameter('id')))
107
-			->setParameter('id', $id);
108
-		$query->execute();
109
-	}
110
-
111
-	/**
112
-	 * get trusted server with given ID
113
-	 *
114
-	 * @param int $id
115
-	 * @return array
116
-	 * @throws \Exception
117
-	 */
118
-	public function getServerById($id) {
119
-		$query = $this->connection->getQueryBuilder();
120
-		$query->select('*')->from($this->dbTable)
121
-			->where($query->expr()->eq('id', $query->createParameter('id')))
122
-			->setParameter('id', $id);
123
-		$query->execute();
124
-		$result = $query->execute()->fetchAll();
125
-
126
-		if (empty($result)) {
127
-			throw new \Exception('No Server found with ID: ' . $id);
128
-		}
129
-
130
-		return $result[0];
131
-	}
132
-
133
-	/**
134
-	 * get all trusted servers
135
-	 *
136
-	 * @return array
137
-	 */
138
-	public function getAllServer() {
139
-		$query = $this->connection->getQueryBuilder();
140
-		$query->select(['url', 'url_hash', 'id', 'status', 'shared_secret', 'sync_token'])->from($this->dbTable);
141
-		$result = $query->execute()->fetchAll();
142
-		return $result;
143
-	}
144
-
145
-	/**
146
-	 * check if server already exists in the database table
147
-	 *
148
-	 * @param string $url
149
-	 * @return bool
150
-	 */
151
-	public function serverExists($url) {
152
-		$hash = $this->hash($url);
153
-		$query = $this->connection->getQueryBuilder();
154
-		$query->select('url')->from($this->dbTable)
155
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
156
-			->setParameter('url_hash', $hash);
157
-		$result = $query->execute()->fetchAll();
158
-
159
-		return !empty($result);
160
-	}
161
-
162
-	/**
163
-	 * write token to database. Token is used to exchange the secret
164
-	 *
165
-	 * @param string $url
166
-	 * @param string $token
167
-	 */
168
-	public function addToken($url, $token) {
169
-		$hash = $this->hash($url);
170
-		$query = $this->connection->getQueryBuilder();
171
-		$query->update($this->dbTable)
172
-			->set('token', $query->createParameter('token'))
173
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
174
-			->setParameter('url_hash', $hash)
175
-			->setParameter('token', $token);
176
-		$query->execute();
177
-	}
178
-
179
-	/**
180
-	 * get token stored in database
181
-	 *
182
-	 * @param string $url
183
-	 * @return string
184
-	 * @throws \Exception
185
-	 */
186
-	public function getToken($url) {
187
-		$hash = $this->hash($url);
188
-		$query = $this->connection->getQueryBuilder();
189
-		$query->select('token')->from($this->dbTable)
190
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
191
-			->setParameter('url_hash', $hash);
192
-
193
-		$result = $query->execute()->fetch();
194
-
195
-		if (!isset($result['token'])) {
196
-			throw new \Exception('No token found for: ' . $url);
197
-		}
198
-
199
-		return $result['token'];
200
-	}
201
-
202
-	/**
203
-	 * add shared Secret to database
204
-	 *
205
-	 * @param string $url
206
-	 * @param string $sharedSecret
207
-	 */
208
-	public function addSharedSecret($url, $sharedSecret) {
209
-		$hash = $this->hash($url);
210
-		$query = $this->connection->getQueryBuilder();
211
-		$query->update($this->dbTable)
212
-			->set('shared_secret', $query->createParameter('sharedSecret'))
213
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
214
-			->setParameter('url_hash', $hash)
215
-			->setParameter('sharedSecret', $sharedSecret);
216
-		$query->execute();
217
-	}
218
-
219
-	/**
220
-	 * get shared secret from database
221
-	 *
222
-	 * @param string $url
223
-	 * @return string
224
-	 */
225
-	public function getSharedSecret($url) {
226
-		$hash = $this->hash($url);
227
-		$query = $this->connection->getQueryBuilder();
228
-		$query->select('shared_secret')->from($this->dbTable)
229
-			->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
230
-			->setParameter('url_hash', $hash);
231
-
232
-		$result = $query->execute()->fetch();
233
-		return $result['shared_secret'];
234
-	}
235
-
236
-	/**
237
-	 * set server status
238
-	 *
239
-	 * @param string $url
240
-	 * @param int $status
241
-	 * @param string|null $token
242
-	 */
243
-	public function setServerStatus($url, $status, $token = null) {
244
-		$hash = $this->hash($url);
245
-		$query = $this->connection->getQueryBuilder();
246
-		$query->update($this->dbTable)
247
-				->set('status', $query->createNamedParameter($status))
248
-				->where($query->expr()->eq('url_hash', $query->createNamedParameter($hash)));
249
-		if (!is_null($token)) {
250
-			$query->set('sync_token', $query->createNamedParameter($token));
251
-		}
252
-		$query->execute();
253
-	}
254
-
255
-	/**
256
-	 * get server status
257
-	 *
258
-	 * @param string $url
259
-	 * @return int
260
-	 */
261
-	public function getServerStatus($url) {
262
-		$hash = $this->hash($url);
263
-		$query = $this->connection->getQueryBuilder();
264
-		$query->select('status')->from($this->dbTable)
265
-				->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
266
-				->setParameter('url_hash', $hash);
267
-
268
-		$result = $query->execute()->fetch();
269
-		return (int)$result['status'];
270
-	}
271
-
272
-	/**
273
-	 * create hash from URL
274
-	 *
275
-	 * @param string $url
276
-	 * @return string
277
-	 */
278
-	protected function hash($url) {
279
-		$normalized = $this->normalizeUrl($url);
280
-		return sha1($normalized);
281
-	}
282
-
283
-	/**
284
-	 * normalize URL, used to create the sha1 hash
285
-	 *
286
-	 * @param string $url
287
-	 * @return string
288
-	 */
289
-	protected function normalizeUrl($url) {
290
-		$normalized = $url;
291
-
292
-		if (strpos($url, 'https://') === 0) {
293
-			$normalized = substr($url, strlen('https://'));
294
-		} else if (strpos($url, 'http://') === 0) {
295
-			$normalized = substr($url, strlen('http://'));
296
-		}
297
-
298
-		$normalized = Filesystem::normalizePath($normalized);
299
-		$normalized = trim($normalized, '/');
300
-
301
-		return $normalized;
302
-	}
303
-
304
-	/**
305
-	 * @param $username
306
-	 * @param $password
307
-	 * @return bool
308
-	 */
309
-	public function auth($username, $password) {
310
-		if ($username !== 'system') {
311
-			return false;
312
-		}
313
-		$query = $this->connection->getQueryBuilder();
314
-		$query->select('url')->from($this->dbTable)
315
-				->where($query->expr()->eq('shared_secret', $query->createNamedParameter($password)));
316
-
317
-		$result = $query->execute()->fetch();
318
-		return !empty($result);
319
-	}
45
+    /** @var  IDBConnection */
46
+    private $connection;
47
+
48
+    /** @var  IL10N */
49
+    private $IL10N;
50
+
51
+    /** @var string  */
52
+    private $dbTable = 'trusted_servers';
53
+
54
+    /**
55
+     * @param IDBConnection $connection
56
+     * @param IL10N $il10n
57
+     */
58
+    public function __construct(
59
+        IDBConnection $connection,
60
+        IL10N $il10n
61
+    ) {
62
+        $this->connection = $connection;
63
+        $this->IL10N = $il10n;
64
+    }
65
+
66
+    /**
67
+     * add server to the list of trusted servers
68
+     *
69
+     * @param string $url
70
+     * @return int
71
+     * @throws HintException
72
+     */
73
+    public function addServer($url) {
74
+        $hash = $this->hash($url);
75
+        $url = rtrim($url, '/');
76
+        $query = $this->connection->getQueryBuilder();
77
+        $query->insert($this->dbTable)
78
+            ->values(
79
+                [
80
+                    'url' =>  $query->createParameter('url'),
81
+                    'url_hash' => $query->createParameter('url_hash'),
82
+                ]
83
+            )
84
+            ->setParameter('url', $url)
85
+            ->setParameter('url_hash', $hash);
86
+
87
+        $result = $query->execute();
88
+
89
+        if ($result) {
90
+            return (int)$this->connection->lastInsertId('*PREFIX*'.$this->dbTable);
91
+        } else {
92
+            $message = 'Internal failure, Could not add trusted server: ' . $url;
93
+            $message_t = $this->IL10N->t('Could not add server');
94
+            throw new HintException($message, $message_t);
95
+        }
96
+    }
97
+
98
+    /**
99
+     * remove server from the list of trusted servers
100
+     *
101
+     * @param int $id
102
+     */
103
+    public function removeServer($id) {
104
+        $query = $this->connection->getQueryBuilder();
105
+        $query->delete($this->dbTable)
106
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
107
+            ->setParameter('id', $id);
108
+        $query->execute();
109
+    }
110
+
111
+    /**
112
+     * get trusted server with given ID
113
+     *
114
+     * @param int $id
115
+     * @return array
116
+     * @throws \Exception
117
+     */
118
+    public function getServerById($id) {
119
+        $query = $this->connection->getQueryBuilder();
120
+        $query->select('*')->from($this->dbTable)
121
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
122
+            ->setParameter('id', $id);
123
+        $query->execute();
124
+        $result = $query->execute()->fetchAll();
125
+
126
+        if (empty($result)) {
127
+            throw new \Exception('No Server found with ID: ' . $id);
128
+        }
129
+
130
+        return $result[0];
131
+    }
132
+
133
+    /**
134
+     * get all trusted servers
135
+     *
136
+     * @return array
137
+     */
138
+    public function getAllServer() {
139
+        $query = $this->connection->getQueryBuilder();
140
+        $query->select(['url', 'url_hash', 'id', 'status', 'shared_secret', 'sync_token'])->from($this->dbTable);
141
+        $result = $query->execute()->fetchAll();
142
+        return $result;
143
+    }
144
+
145
+    /**
146
+     * check if server already exists in the database table
147
+     *
148
+     * @param string $url
149
+     * @return bool
150
+     */
151
+    public function serverExists($url) {
152
+        $hash = $this->hash($url);
153
+        $query = $this->connection->getQueryBuilder();
154
+        $query->select('url')->from($this->dbTable)
155
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
156
+            ->setParameter('url_hash', $hash);
157
+        $result = $query->execute()->fetchAll();
158
+
159
+        return !empty($result);
160
+    }
161
+
162
+    /**
163
+     * write token to database. Token is used to exchange the secret
164
+     *
165
+     * @param string $url
166
+     * @param string $token
167
+     */
168
+    public function addToken($url, $token) {
169
+        $hash = $this->hash($url);
170
+        $query = $this->connection->getQueryBuilder();
171
+        $query->update($this->dbTable)
172
+            ->set('token', $query->createParameter('token'))
173
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
174
+            ->setParameter('url_hash', $hash)
175
+            ->setParameter('token', $token);
176
+        $query->execute();
177
+    }
178
+
179
+    /**
180
+     * get token stored in database
181
+     *
182
+     * @param string $url
183
+     * @return string
184
+     * @throws \Exception
185
+     */
186
+    public function getToken($url) {
187
+        $hash = $this->hash($url);
188
+        $query = $this->connection->getQueryBuilder();
189
+        $query->select('token')->from($this->dbTable)
190
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
191
+            ->setParameter('url_hash', $hash);
192
+
193
+        $result = $query->execute()->fetch();
194
+
195
+        if (!isset($result['token'])) {
196
+            throw new \Exception('No token found for: ' . $url);
197
+        }
198
+
199
+        return $result['token'];
200
+    }
201
+
202
+    /**
203
+     * add shared Secret to database
204
+     *
205
+     * @param string $url
206
+     * @param string $sharedSecret
207
+     */
208
+    public function addSharedSecret($url, $sharedSecret) {
209
+        $hash = $this->hash($url);
210
+        $query = $this->connection->getQueryBuilder();
211
+        $query->update($this->dbTable)
212
+            ->set('shared_secret', $query->createParameter('sharedSecret'))
213
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
214
+            ->setParameter('url_hash', $hash)
215
+            ->setParameter('sharedSecret', $sharedSecret);
216
+        $query->execute();
217
+    }
218
+
219
+    /**
220
+     * get shared secret from database
221
+     *
222
+     * @param string $url
223
+     * @return string
224
+     */
225
+    public function getSharedSecret($url) {
226
+        $hash = $this->hash($url);
227
+        $query = $this->connection->getQueryBuilder();
228
+        $query->select('shared_secret')->from($this->dbTable)
229
+            ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
230
+            ->setParameter('url_hash', $hash);
231
+
232
+        $result = $query->execute()->fetch();
233
+        return $result['shared_secret'];
234
+    }
235
+
236
+    /**
237
+     * set server status
238
+     *
239
+     * @param string $url
240
+     * @param int $status
241
+     * @param string|null $token
242
+     */
243
+    public function setServerStatus($url, $status, $token = null) {
244
+        $hash = $this->hash($url);
245
+        $query = $this->connection->getQueryBuilder();
246
+        $query->update($this->dbTable)
247
+                ->set('status', $query->createNamedParameter($status))
248
+                ->where($query->expr()->eq('url_hash', $query->createNamedParameter($hash)));
249
+        if (!is_null($token)) {
250
+            $query->set('sync_token', $query->createNamedParameter($token));
251
+        }
252
+        $query->execute();
253
+    }
254
+
255
+    /**
256
+     * get server status
257
+     *
258
+     * @param string $url
259
+     * @return int
260
+     */
261
+    public function getServerStatus($url) {
262
+        $hash = $this->hash($url);
263
+        $query = $this->connection->getQueryBuilder();
264
+        $query->select('status')->from($this->dbTable)
265
+                ->where($query->expr()->eq('url_hash', $query->createParameter('url_hash')))
266
+                ->setParameter('url_hash', $hash);
267
+
268
+        $result = $query->execute()->fetch();
269
+        return (int)$result['status'];
270
+    }
271
+
272
+    /**
273
+     * create hash from URL
274
+     *
275
+     * @param string $url
276
+     * @return string
277
+     */
278
+    protected function hash($url) {
279
+        $normalized = $this->normalizeUrl($url);
280
+        return sha1($normalized);
281
+    }
282
+
283
+    /**
284
+     * normalize URL, used to create the sha1 hash
285
+     *
286
+     * @param string $url
287
+     * @return string
288
+     */
289
+    protected function normalizeUrl($url) {
290
+        $normalized = $url;
291
+
292
+        if (strpos($url, 'https://') === 0) {
293
+            $normalized = substr($url, strlen('https://'));
294
+        } else if (strpos($url, 'http://') === 0) {
295
+            $normalized = substr($url, strlen('http://'));
296
+        }
297
+
298
+        $normalized = Filesystem::normalizePath($normalized);
299
+        $normalized = trim($normalized, '/');
300
+
301
+        return $normalized;
302
+    }
303
+
304
+    /**
305
+     * @param $username
306
+     * @param $password
307
+     * @return bool
308
+     */
309
+    public function auth($username, $password) {
310
+        if ($username !== 'system') {
311
+            return false;
312
+        }
313
+        $query = $this->connection->getQueryBuilder();
314
+        $query->select('url')->from($this->dbTable)
315
+                ->where($query->expr()->eq('shared_secret', $query->createNamedParameter($password)));
316
+
317
+        $result = $query->execute()->fetch();
318
+        return !empty($result);
319
+    }
320 320
 
321 321
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -87,9 +87,9 @@  discard block
 block discarded – undo
87 87
 		$result = $query->execute();
88 88
 
89 89
 		if ($result) {
90
-			return (int)$this->connection->lastInsertId('*PREFIX*'.$this->dbTable);
90
+			return (int) $this->connection->lastInsertId('*PREFIX*'.$this->dbTable);
91 91
 		} else {
92
-			$message = 'Internal failure, Could not add trusted server: ' . $url;
92
+			$message = 'Internal failure, Could not add trusted server: '.$url;
93 93
 			$message_t = $this->IL10N->t('Could not add server');
94 94
 			throw new HintException($message, $message_t);
95 95
 		}
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
 		$result = $query->execute()->fetchAll();
125 125
 
126 126
 		if (empty($result)) {
127
-			throw new \Exception('No Server found with ID: ' . $id);
127
+			throw new \Exception('No Server found with ID: '.$id);
128 128
 		}
129 129
 
130 130
 		return $result[0];
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
 		$result = $query->execute()->fetch();
194 194
 
195 195
 		if (!isset($result['token'])) {
196
-			throw new \Exception('No token found for: ' . $url);
196
+			throw new \Exception('No token found for: '.$url);
197 197
 		}
198 198
 
199 199
 		return $result['token'];
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 				->setParameter('url_hash', $hash);
267 267
 
268 268
 		$result = $query->execute()->fetch();
269
-		return (int)$result['status'];
269
+		return (int) $result['status'];
270 270
 	}
271 271
 
272 272
 	/**
Please login to merge, or discard this patch.