Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Replication.php « lib « server - github.com/nextcloud/lookup-server.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 002cd4776e61c29f9db39f36010b44adedbbc71f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
<?php

namespace LookupServer;

use GuzzleHttp\Client;
use Slim\Http\Request;
use Slim\Http\Response;

class Replication {

	/** @var \PDO */
	private $db;

	/** @var string */
	private $auth;

	/** @var string[] */
	private $replicationHosts;

	public function __construct(\PDO $db, $auth, $replicationHosts) {
		$this->db = $db;
		$this->auth = $auth;
		$this->replicationHosts = $replicationHosts;
	}

	public function export(Request $request, Response $response) {
		$userInfo = $request->getUri()->getUserInfo();

		$userInfo = explode(':', $userInfo, 2);

		if (count($userInfo) !== 2 || $userInfo[0] !== 'lookup' || $userInfo[1] !== $this->auth)  {
			$response = $response->withStatus(401);
			return $response;
		}

		$params = $request->getQueryParams();
		if (!isset($params['timestamp'], $params['page']) || !ctype_digit($params['timestamp']) ||
		    !ctype_digit($params['page'])) {
			$response = $response->withStatus(400);
			return $response;
		}

		$timestamp = (int)$params['timestamp'];
		$page = (int)$params['page'];

		$stmt = $this->db->prepare('SELECT id, federationId, UNIX_TIMESTAMP(timestamp) AS timestamp
			FROM users 
			WHERE UNIX_TIMESTAMP(timestamp) >= :timestamp
			ORDER BY timestamp, id
			LIMIT :limit
			OFFSET :offset');
		$stmt->bindParam('timestamp', $timestamp);
		$stmt->bindValue('limit', 100, \PDO::PARAM_INT);
		$stmt->bindValue('offset', 100 * $page, \PDO::PARAM_INT);

		$stmt->execute();

		$result = [];
		while($data = $stmt->fetch()) {
			$user = [
				'cloudId' => $data['federationId'],
				'timestamp' => (int)$data['timestamp'],
				'data' => [],
			];

			$stmt2 = $this->db->prepare('SELECT *
				FROM store
				WHERE userId = :uid');
			$stmt2->bindValue('uid', $data['id']);
			$stmt2->execute();

			while($userData = $stmt2->fetch()) {
				$user['data'][] = [
					'key' => $userData['k'],
					'value' => $userData['v'],
					'validated' => (int)$userData['valid'],
				];
			}
			$stmt2->closeCursor();

			$result[] = $user;
		}

		$response->getBody()->write(json_encode($result));
		return $response;
	}

	public function import(Request $request, Response $response) {
		$replicationStatus = [];

		if (file_exists(__DIR__ . '/../config/replication.json')) {
			$replicationStatus = json_decode(file_get_contents(__DIR__ . '/../config/replication.json'), true);
		}

		foreach ($this->replicationHosts as $replicationHost) {
			$timestamp = 0;

			if (isset($replicationStatus[$replicationHost])) {
				$timestamp = $replicationStatus[$replicationHost];
			}

			$page = 0;
			while(true) {
				// Retrieve public key && store
				$req = new \GuzzleHttp\Psr7\Request('GET', $replicationHost . '?timestamp=' . $timestamp . '&page=' . $page);

				$client = new Client();
				$resp = $client->send($req, [
					'timeout' => 5,
				]);

				$data = json_decode($resp->getBody(), true);
				if (count($data) === 0) {
					break;
				}

				foreach ($data as $user) {
					$this->parseUser($user);
					$replicationStatus[$replicationHost] = $user['timestamp'];
				}

				$page++;
			}

			file_put_contents(__DIR__. '/../config/replication.json', json_encode($replicationStatus, JSON_PRETTY_PRINT));
		}

		return $response;
	}

	private function parseUser($user) {
		$stmt = $this->db->prepare('SELECT id, UNIX_TIMESTAMP(timestamp) AS timestamp
			FROM users
			WHERE federationId = :id');
		$stmt->bindParam('id', $user['cloudId']);

		$stmt->execute();

		// New
		if ($stmt->rowCount() === 1) {
			$data = $stmt->fetch();
			if ($data['timestamp'] > $user['timestamp']) {
				$stmt->closeCursor();
				return;
			}

			$stmt2 = $this->db->prepare('DELETE FROM users
				WHERE federationId = :id');
			$stmt2->bindParam('id', $user['cloudId']);
			$stmt2->execute();
			$stmt2->closeCursor();
		}

		$stmt->closeCursor();

		$stmt = $this->db->prepare('INSERT INTO users (federationId, timestamp) VALUES (:federationId, FROM_UNIXTIME(:timestamp))');
		$stmt->bindParam(':federationId', $user['cloudId'], \PDO::PARAM_STR);
		$stmt->bindParam(':timestamp', $user['timestamp'], \PDO::PARAM_INT);
		$stmt->execute();
		$id = $this->db->lastInsertId();
		$stmt->closeCursor();

		foreach ($user['data'] as $data) {
			$stmt = $this->db->prepare('INSERT INTO store (userId, k, v, valid) VALUES (:userId, :k, :v, :valid)');
			$stmt->bindParam(':userId', $id, \PDO::PARAM_INT);
			$stmt->bindParam(':k', $data['key'], \PDO::PARAM_STR);
			$stmt->bindParam(':v', $data['value'], \PDO::PARAM_STR);
			$stmt->bindParam(':valid', $data['validated'], \PDO::PARAM_INT);

			$stmt->execute();
			$stmt->closeCursor();
		}
	}
}