-
Notifications
You must be signed in to change notification settings - Fork 642
/
Copy pathApi.php
228 lines (206 loc) · 8.4 KB
/
Api.php
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\helpers;
use Composer\Repository\PlatformRepository;
use Craft;
use craft\enums\LicenseKeyStatus;
use craft\errors\InvalidLicenseKeyException;
use craft\errors\InvalidPluginException;
use yii\base\Exception;
/**
* Craftnet API helper.
*
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 3.3.16
* @internal
*/
abstract class Api
{
/**
* Returns the headers that should be sent with API requests.
*
* @return array
*/
public static function headers(): array
{
$headers = [
'Accept' => 'application/json',
'X-Craft-System' => 'craft:' . Craft::$app->getVersion() . ';' . strtolower(Craft::$app->getEditionName()),
];
// platform
$platform = [];
foreach (self::platformVersions() as $name => $version) {
$platform[] = "{$name}:{$version}";
}
$headers['X-Craft-Platform'] = implode(',', $platform);
// request info
$request = Craft::$app->getRequest();
if (!$request->getIsConsoleRequest()) {
if (($host = $request->getHostInfo()) !== null) {
$headers['X-Craft-Host'] = $host;
}
if (($ip = $request->getUserIP(FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) !== null) {
$headers['X-Craft-User-Ip'] = $ip;
}
}
// email
if (($user = Craft::$app->getUser()->getIdentity()) !== null) {
$headers['X-Craft-User-Email'] = $user->email;
}
// Craft license
$headers['X-Craft-License'] = App::licenseKey() ?? (defined('CRAFT_LICENSE_KEY') ? '__INVALID__' : '__REQUEST__');
// plugin info
$pluginLicenses = [];
$pluginsService = Craft::$app->getPlugins();
foreach ($pluginsService->getAllPluginInfo() as $pluginHandle => $pluginInfo) {
if ($pluginInfo['isInstalled']) {
$headers['X-Craft-System'] .= ",plugin-{$pluginHandle}:{$pluginInfo['version']};{$pluginInfo['edition']}";
try {
$licenseKey = $pluginsService->getPluginLicenseKey($pluginHandle);
} catch (InvalidLicenseKeyException $e) {
$licenseKey = null;
}
if ($licenseKey !== null) {
$pluginLicenses[] = "{$pluginHandle}:{$licenseKey}";
}
}
}
if (!empty($pluginLicenses)) {
$headers['X-Craft-Plugin-Licenses'] = implode(',', $pluginLicenses);
}
return $headers;
}
/**
* Returns platform info.
*
* @param bool $useComposerOverrides Whether to factor in any `config.platform` overrides
* @return array
*/
public static function platformVersions(bool $useComposerOverrides = false): array
{
// Let Composer's PlatformRepository do most of the work
$overrides = [];
if ($useComposerOverrides) {
try {
$jsonPath = Craft::$app->getComposer()->getJsonPath();
$config = Json::decode(file_get_contents($jsonPath));
$overrides = $config['config']['platform'] ?? [];
} catch (Exception $e) {
// couldn't locate composer.json - NBD
}
}
$repo = new PlatformRepository([], $overrides);
$versions = [];
foreach ($repo->getPackages() as $package) {
$versions[$package->getName()] = $package->getPrettyVersion();
}
// Also include the DB driver/version
$db = Craft::$app->getDb();
$versions[$db->getDriverName()] = $db->getVersion();
return $versions;
}
/**
* Processes an API response’s headers.
*
* @param string[][]|string[] The response headers
*/
public static function processResponseHeaders(array $headers)
{
// Normalize the headers
$headers = self::_normalizeHeaders(($headers));
// cache license info from the response
$cache = Craft::$app->getCache();
$duration = 86400;
if (isset($headers['x-craft-allow-trials'])) {
$cache->set('editionTestableDomain@' . Craft::$app->getRequest()->getHostName(), (bool)reset($headers['x-craft-allow-trials']), $duration);
}
if (isset($headers['x-craft-license-status'])) {
$cache->set('licenseKeyStatus', reset($headers['x-craft-license-status']), $duration);
}
if (isset($headers['x-craft-license-domain'])) {
$cache->set('licensedDomain', reset($headers['x-craft-license-domain']), $duration);
}
if (isset($headers['x-craft-license-edition'])) {
$licensedEdition = reset($headers['x-craft-license-edition']);
switch ($licensedEdition) {
case 'solo':
$licensedEdition = Craft::Solo;
break;
case 'pro':
$licensedEdition = Craft::Pro;
break;
default:
Craft::error('Invalid X-Craft-License-Edition header value: ' . $licensedEdition, __METHOD__);
}
$cache->set('licensedEdition', $licensedEdition, $duration);
}
$pluginLicenseStatuses = [];
$pluginLicenseEditions = [];
$pluginsService = Craft::$app->getPlugins();
foreach ($pluginsService->getAllPluginInfo() as $pluginHandle => $pluginInfo) {
if ($pluginInfo['isInstalled']) {
$pluginLicenseStatuses[$pluginHandle] = LicenseKeyStatus::Unknown;
}
}
if (isset($headers['x-craft-plugin-license-statuses'])) {
$pluginLicenseInfo = explode(',', reset($headers['x-craft-plugin-license-statuses']));
foreach ($pluginLicenseInfo as $info) {
list($pluginHandle, $pluginLicenseStatus) = explode(':', $info);
$pluginLicenseStatuses[$pluginHandle] = $pluginLicenseStatus;
}
}
if (isset($headers['x-craft-plugin-license-editions'])) {
$pluginLicenseInfo = explode(',', reset($headers['x-craft-plugin-license-editions']));
foreach ($pluginLicenseInfo as $info) {
list($pluginHandle, $pluginLicenseEdition) = explode(':', $info);
$pluginLicenseEditions[$pluginHandle] = $pluginLicenseEdition;
}
}
foreach ($pluginLicenseStatuses as $pluginHandle => $pluginLicenseStatus) {
$pluginLicenseEdition = $pluginLicenseEditions[$pluginHandle] ?? null;
try {
$pluginsService->setPluginLicenseKeyStatus($pluginHandle, $pluginLicenseStatus, $pluginLicenseEdition);
} catch (InvalidPluginException $pluginException) {
}
}
// did we just get a new license key?
if (isset($headers['x-craft-license'])) {
$license = reset($headers['x-craft-license']);
$path = Craft::$app->getPath()->getLicenseKeyPath();
// just in case there's some race condition where two licenses were requested simultaneously...
if (App::licenseKey() !== null) {
$i = 0;
do {
$newPath = "{$path}." . ++$i;
} while (file_exists($newPath));
$path = $newPath;
Craft::warning("A new license key was issued, but we already had one. Writing it to {$path} instead.", __METHOD__);
}
try {
FileHelper::writeToFile($path, chunk_split($license, 50));
} catch (\ErrorException $err) {
// log and keep going
Craft::error("Could not write new license key to {$path}: {$err->getMessage()}\nLicense key: {$license}", __METHOD__);
Craft::$app->getErrorHandler()->logException($err);
}
}
}
/**
* Normalizes the header names by converting them to lowercase and ensuring their values are arrays
*
* @param string[][]|string[] $headers
* @return string[][]
*/
private static function _normalizeHeaders(array $headers): array
{
$normalizedHeaders = [];
foreach ($headers as $name => $value) {
$normalizedHeaders[strtolower($name)] = (array)$value;
}
return $normalizedHeaders;
}
}