-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI.php
More file actions
501 lines (450 loc) · 17 KB
/
API.php
File metadata and controls
501 lines (450 loc) · 17 KB
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
<?php
namespace Piwik\Plugins\Swagger;
use Piwik\API\Proxy;
use Piwik\API\Request;
use Piwik\Piwik;
use Piwik\Url;
use Piwik\Version;
class API extends \Piwik\Plugin\API
{
private function ensureAllPluginsRegistered()
{
try {
$plugins = \Piwik\Plugin\Manager::getInstance()->getLoadedPluginsName();
foreach ($plugins as $plugin) {
try {
$className = Request::getClassNameAPI($plugin);
Proxy::getInstance()->registerClass($className);
} catch (\Exception $e) {
// Skip plugins without API class
}
}
} catch (\Exception $e) {
// If plugin registration fails, continue anyway
}
}
public function getOpenApi()
{
// Piwik::checkUserHasSuperUserAccess();
// Ensure all plugins are registered before generating the spec
$this->ensureAllPluginsRegistered();
try {
$info = $this->getInfo();
$externalDocs = $this->getExternalDocs();
$servers = $this->getServers();
$tags = $this->getTags();
$paths = $this->getPaths();
$openapi = [
"openapi" => "3.1.0",
"info" => $info,
"externalDocs" => $externalDocs,
"servers" => $servers,
"tags" => $tags,
"paths" => $paths,
"components" => [
"securitySchemes" => [
"BearerAuth" => [
"type" => "http",
"scheme" => "bearer",
"description" => "Matomo API token authentication. Use your Matomo API token as the Bearer token."
]
]
],
"security" => [
[
"BearerAuth" => [],
]
],
];
return $openapi;
} catch (\Exception $e) {
return [
"openapi" => "3.1.0",
"info" => [
"title" => "Matomo API - Error",
"version" => "1.0.0",
"description" => "Error generating OpenAPI spec: " . $e->getMessage() . " | File: " . $e->getFile() . " | Line: " . $e->getLine()
],
"paths" => []
];
} catch (\Throwable $e) {
return [
"openapi" => "3.1.0",
"info" => [
"title" => "Matomo API - Fatal Error",
"version" => "1.0.0",
"description" => "Fatal error: " . $e->getMessage() . " | File: " . $e->getFile() . " | Line: " . $e->getLine()
],
"paths" => []
];
}
}
private function getMetadata()
{
return Proxy::getInstance()->getMetadata();
}
private function getPluginInformation($moduleName)
{
try {
$pluginManager = \Piwik\Plugin\Manager::getInstance();
$plugin = $pluginManager->getLoadedPlugin($moduleName);
if ($plugin) {
return $plugin->getInformation();
}
} catch (\Exception $e) {
// Plugin might not have metadata
}
return null;
}
private function getAllApiMethods()
{
$result = array();
foreach (Proxy::getInstance()->getMetadata() as $class => $info) {
$moduleName = Proxy::getInstance()->getModuleNameFromClassName($class);
foreach ($info as $actionName => $infoMethod) {
if ($actionName !== '__documentation' && $actionName !== 'usesAutoSanitizeInputParams') {
$method = "$moduleName.$actionName";
$result[$method] = array(
'module' => $moduleName,
'action' => $actionName,
'method' => $method,
'parameters' => isset($infoMethod['parameters']) ? $infoMethod['parameters'] : array(),
'isDeprecated' => isset($infoMethod['isDeprecated']) ? $infoMethod['isDeprecated'] : false,
);
}
}
}
return $result;
}
/**
* Get OpenAPI info section with dynamic Matomo version
*
* @return array
*/
private function getInfo()
{
$info = [
"title" => "Matomo API",
"summary" => "Matomo reporting API",
"description" => "Complete Matomo reporting API documentation",
"version" => Version::VERSION // Dynamically retrieved from Matomo installation
];
return $info;
}
private function getExternalDocs()
{
$externalDocs = [
"description" => "Official Matomo documentation",
"url" => "https://developer.matomo.org/api-reference/reporting-api"
];
return $externalDocs;
}
/**
* Get OpenAPI servers list with dynamic protocol detection
*
* @return array
*/
private function getServers()
{
$host = Url::getHost();
$scheme = Url::getCurrentScheme();
$servers = [
[
"url" => "$scheme://$host",
"description" => "This Matomo server",
],
[
"url" => "https://demo.matomo.cloud",
"description" => "The Matomo demo server",
]
];
return $servers;
}
/**
* Generate OpenAPI tags dynamically from installed plugins
*
* This method generates tags based on the loaded plugins in Matomo,
* ensuring all modules are discovered dynamically from the current installation.
*
* @return array Array of tag definitions with module names
*/
private function getTags()
{
$tags = [];
foreach (Proxy::getInstance()->getMetadata() as $class => $info) {
$moduleName = Proxy::getInstance()->getModuleNameFromClassName($class);
$tag = [
'name' => $moduleName,
];
$tags[] = $tag;
}
return $tags;
}
/**
* Generate OpenAPI paths dynamically from all available API methods
*
* This method generates API paths based on all registered API methods from loaded plugins.
* It includes proper OpenAPI 3.1.0 structure with parameters, responses, and documentation.
*
* @return array Array of path definitions
*/
private function getPaths()
{
$paths = [];
$metadata = $this->getMetadata(); // Get metadata once, not in every iteration
foreach ($this->getAllApiMethods() as $method) {
$operationId = str_replace('.', '_', $method['method']);
$summary = $method['action'] . ' from ' . $method['module'];
// Get method documentation if available from API metadata
$description = '';
foreach ($metadata as $class => $info) {
if (Proxy::getInstance()->getModuleNameFromClassName($class) === $method['module']) {
if (isset($info[$method['action']]['description'])) {
$description = $info[$method['action']]['description'];
}
break;
}
}
// Build path with method in query string for clarity
$pathKey = '/index.php?method=' . $method['method'];
$paths[$pathKey] = [
"post" => [
"summary" => $summary,
"description" => $description ?: "Execute " . $method['method'] . " API method",
"operationId" => $operationId,
"tags" => [
$method['module'],
],
"deprecated" => $method['isDeprecated'],
"requestBody" => [
"required" => false,
"content" => [
"application/x-www-form-urlencoded" => [
"schema" => [
"type" => "object",
"required" => ["module", "format"],
"properties" => $this->getPostBodyProperties($method)
]
],
"application/json" => [
"schema" => [
"type" => "object",
"required" => ["module", "format"],
"properties" => $this->getPostBodyProperties($method)
]
]
]
],
"responses" => [
"200" => [
"description" => "Successful response",
"content" => [
"application/json" => [
"schema" => [
"type" => "object"
]
]
]
]
]
],
];
}
return $paths;
}
private function getRequiredProperties($method)
{
$required = [];
if (isset($method['parameters'])) {
foreach ($method['parameters'] as $parameter => $config) {
if ($config['default'] === is_object('Piwik\API\NoDefaultValue')) {
$required[] = $parameter;
}
}
}
return $required;
}
/**
* Generate OpenAPI parameter definitions for a specific API method
*
* Converts Matomo API method parameters into OpenAPI 3.1.0 parameter format,
* including proper types, required flags, descriptions, and default values.
*
* @param array $method Method information including parameters
* @return array Array of parameter definitions
*/
private function getParametersArray($method)
{
$parameters = [
[
"name" => "method",
"in" => "query",
"required" => true,
"description" => "API method to call",
"schema" => [
"type" => "string",
"example" => $method["method"]
]
],
[
"name" => "format",
"in" => "query",
"required" => false,
"description" => "Response format",
"schema" => [
"type" => "string",
"enum" => ["json", "xml", "csv", "tsv", "html", "rss", "original"],
"default" => "json"
]
],
];
if (isset($method['parameters'])) {
foreach ($method['parameters'] as $parameter => $config) {
// Check if parameter is required (has NoDefaultValue or no default at all)
$hasDefault = isset($config['default']);
$isNoDefaultValue = $hasDefault && is_object($config['default']) &&
get_class($config['default']) === 'Piwik\API\NoDefaultValue';
$isRequired = !$hasDefault || $isNoDefaultValue;
$param = [
'name' => $parameter,
'in' => 'query',
'required' => $isRequired,
'schema' => [
'type' => 'string',
]
];
// Add description if available and not a translation key
if (isset($config['description']) &&
!empty($config['description']) &&
!preg_match('/^[A-Z][a-zA-Z]+_[a-zA-Z_]+$/', $config['description'])) {
$param['description'] = $config['description'];
}
// Add default value: use meaningful value if exists, otherwise empty string for optional params
if ($hasDefault &&
!is_object($config['default']) &&
$config['default'] !== null &&
trim((string)$config['default']) !== '' &&
strtolower(trim((string)$config['default'])) !== 'string') {
// Has a meaningful default value
$param['schema']['default'] = $config['default'];
} elseif (!$isRequired) {
// Optional parameter with no meaningful default - set empty string
$param['schema']['default'] = '';
}
$parameters[] = $param;
}
}
return $parameters;
}
/**
* Generate OpenAPI POST body properties for a specific API method
*
* Creates properties for request body parameters in POST requests.
* Includes format parameter and all method-specific parameters.
*
* @param array $method Method information including parameters
* @return array Array of property definitions for request body
*/
private function getPostBodyProperties($method)
{
$properties = [
"module" => [
"type" => "string",
"enum" => ["API"],
"default" => "API",
"description" => "API module name (required)"
],
"format" => [
"type" => "string",
"enum" => ["json", "xml", "csv", "tsv", "html", "rss", "original"],
"default" => "json",
"description" => "Response format (required)"
],
];
if (isset($method['parameters'])) {
foreach ($method['parameters'] as $parameter => $config) {
// Check if parameter is required (has NoDefaultValue or no default at all)
$hasDefault = isset($config['default']);
$isNoDefaultValue = $hasDefault && is_object($config['default']) &&
get_class($config['default']) === 'Piwik\API\NoDefaultValue';
$prop = [
'type' => 'string',
];
// Add description if available and not a translation key
if (isset($config['description']) &&
!empty($config['description']) &&
!preg_match('/^[A-Z][a-zA-Z]+_[a-zA-Z_]+$/', $config['description'])) {
$prop['description'] = $config['description'];
}
// Add default value: use meaningful value if exists, otherwise empty string for optional params
if ($hasDefault &&
!is_object($config['default']) &&
$config['default'] !== null &&
trim((string)$config['default']) !== '' &&
strtolower(trim((string)$config['default'])) !== 'string') {
// Has a meaningful default value
$prop['default'] = $config['default'];
} elseif (!$isNoDefaultValue) {
// Optional parameter with no meaningful default - set empty string
$prop['default'] = '';
}
$properties[$parameter] = $prop;
}
}
return $properties;
}
private function getProperties($method)
{
$properties = [
"module" => [
"name" => "module",
"in" => "query",
"examples" => ["API"],
"schema" => [
"type" => "string",
]
],
"format" => [
"name" => "format",
"in" => "query",
"examples" => [
"json",
"xml",
"csv",
"tsv",
"html",
"rss",
"original"
],
"schema" => [
"type" => "string",
]
],
"method" => [
"name" => "method",
"in" => "query",
"examples" => [
$method["method"]
],
"schema" => [
"type" => "string",
]
],
];
if (isset($method['parameters'])) {
foreach ($method['parameters'] as $parameter => $config) {
$properties[$parameter] = [
'name' => $parameter,
'in' => 'query',
'examples' => [
'', '',
],
'schema' => [
'type' => 'string',
]
];
}
}
return $properties;
}
}