PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 1.3.1
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v1.3.1
5.11.1 5.11.0 5.10.2 5.10.1 trunk 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.1.0 1.1.1 1.1.2 1.1.3 1.2.0 1.3.0 1.3.1 1.3.2 4.0.0 4.0.1 4.0.2 4.0.3 4.0.4 4.1.0 4.1.1 4.1.2 4.1.3 4.10.0 4.11.0 4.12.0 4.13.0 4.13.2 4.13.3 4.13.4 4.13.5 4.14.0 4.14.1 4.14.2 4.15.0 4.15.1 4.15.2 4.15.3 4.2.0 4.3.0 4.3.1 4.4.1 4.4.2 4.5.0 4.6.0 5.0.1 5.0.2 5.0.3 5.0.4 5.0.5 5.0.6 5.0.7 5.0.8 5.1.0 5.1.1 5.1.2 5.1.3 5.1.4 5.1.5 5.1.6 5.1.7 5.10.0 5.2.0 5.2.1 5.2.2 5.3.0 5.3.1 5.3.2 5.3.3 5.6.0 5.6.1 5.7.0 5.7.1 5.8.0 5.8.1 5.8.2
matomo / app / core / API / Proxy.php
matomo / app / core / API Last commit date
DataTableManipulator 6 years ago ApiRenderer.php 6 years ago CORSHandler.php 6 years ago DataTableGenericFilter.php 6 years ago DataTableManipulator.php 6 years ago DataTablePostProcessor.php 6 years ago DocumentationGenerator.php 6 years ago Inconsistencies.php 6 years ago Proxy.php 6 years ago Request.php 6 years ago ResponseBuilder.php 6 years ago
Proxy.php
583 lines
1 <?php
2 /**
3 * Piwik - free/libre analytics platform
4 *
5 * @link https://matomo.org
6 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
7 *
8 */
9
10 namespace Piwik\API;
11
12 use Exception;
13 use Piwik\Common;
14 use Piwik\Container\StaticContainer;
15 use Piwik\Context;
16 use Piwik\Piwik;
17 use Piwik\Plugin\Manager;
18 use Piwik\Singleton;
19 use ReflectionClass;
20 use ReflectionMethod;
21
22 /**
23 * Proxy is a singleton that has the knowledge of every method available, their parameters
24 * and default values.
25 * Proxy receives all the API calls requests via call() and forwards them to the right
26 * object, with the parameters in the right order.
27 *
28 * It will also log the performance of API calls (time spent, parameter values, etc.) if logger available
29 */
30 class Proxy
31 {
32 // array of already registered plugins names
33 protected $alreadyRegistered = array();
34
35 protected $metadataArray = array();
36 private $hideIgnoredFunctions = true;
37
38 // when a parameter doesn't have a default value we use this
39 private $noDefaultValue;
40
41 public function __construct()
42 {
43 $this->noDefaultValue = new NoDefaultValue();
44 }
45
46 public static function getInstance()
47 {
48 return StaticContainer::get(self::class);
49 }
50
51 /**
52 * Returns array containing reflection meta data for all the loaded classes
53 * eg. number of parameters, method names, etc.
54 *
55 * @return array
56 */
57 public function getMetadata()
58 {
59 ksort($this->metadataArray);
60 return $this->metadataArray;
61 }
62
63 /**
64 * Registers the API information of a given module.
65 *
66 * The module to be registered must be
67 * - a singleton (providing a getInstance() method)
68 * - the API file must be located in plugins/ModuleName/API.php
69 * for example plugins/Referrers/API.php
70 *
71 * The method will introspect the methods, their parameters, etc.
72 *
73 * @param string $className ModuleName eg. "API"
74 */
75 public function registerClass($className)
76 {
77 if (isset($this->alreadyRegistered[$className])) {
78 return;
79 }
80 $this->includeApiFile($className);
81 $this->checkClassIsSingleton($className);
82
83 $rClass = new ReflectionClass($className);
84 if (!$this->shouldHideAPIMethod($rClass->getDocComment())) {
85 foreach ($rClass->getMethods() as $method) {
86 $this->loadMethodMetadata($className, $method);
87 }
88
89 $this->setDocumentation($rClass, $className);
90 $this->alreadyRegistered[$className] = true;
91 }
92 }
93
94 /**
95 * Will be displayed in the API page
96 *
97 * @param ReflectionClass $rClass Instance of ReflectionClass
98 * @param string $className Name of the class
99 */
100 private function setDocumentation($rClass, $className)
101 {
102 // Doc comment
103 $doc = $rClass->getDocComment();
104 $doc = str_replace(" * " . PHP_EOL, "<br>", $doc);
105
106 // boldify the first line only if there is more than one line, otherwise too much bold
107 if (substr_count($doc, '<br>') > 1) {
108 $firstLineBreak = strpos($doc, "<br>");
109 $doc = "<div class='apiFirstLine'>" . substr($doc, 0, $firstLineBreak) . "</div>" . substr($doc, $firstLineBreak + strlen("<br>"));
110 }
111 $doc = preg_replace("/(@package)[a-z _A-Z]*/", "", $doc);
112 $doc = preg_replace("/(@method).*/", "", $doc);
113 $doc = str_replace(array("\t", "\n", "/**", "*/", " * ", " *", " ", "\t*", " * @package"), " ", $doc);
114
115 // replace 'foo' and `bar` and "foobar" with code blocks... much magic
116 $doc = preg_replace('/`(.*?)`/', '<code>$1</code>', $doc);
117 $this->metadataArray[$className]['__documentation'] = $doc;
118 }
119
120 /**
121 * Returns number of classes already loaded
122 * @return int
123 */
124 public function getCountRegisteredClasses()
125 {
126 return count($this->alreadyRegistered);
127 }
128
129 /**
130 * Will execute $className->$methodName($parametersValues)
131 * If any error is detected (wrong number of parameters, method not found, class not found, etc.)
132 * it will throw an exception
133 *
134 * It also logs the API calls, with the parameters values, the returned value, the performance, etc.
135 * You can enable logging in config/global.ini.php (log_api_call)
136 *
137 * @param string $className The class name (eg. API)
138 * @param string $methodName The method name
139 * @param array $parametersRequest The parameters pairs (name=>value)
140 *
141 * @return mixed|null
142 * @throws Exception|\Piwik\NoAccessException
143 */
144 public function call($className, $methodName, $parametersRequest)
145 {
146 // Temporarily sets the Request array to this API call context
147 return Context::executeWithQueryParameters($parametersRequest, function () use ($className, $methodName, $parametersRequest) {
148 $returnedValue = null;
149
150 $this->registerClass($className);
151
152 // instanciate the object
153 $object = $className::getInstance();
154
155 // check method exists
156 $this->checkMethodExists($className, $methodName);
157
158 // get the list of parameters required by the method
159 $parameterNamesDefaultValues = $this->getParametersList($className, $methodName);
160
161 // load parameters in the right order, etc.
162 $finalParameters = $this->getRequestParametersArray($parameterNamesDefaultValues, $parametersRequest);
163
164 // allow plugins to manipulate the value
165 $pluginName = $this->getModuleNameFromClassName($className);
166
167 $returnedValue = null;
168
169 /**
170 * Triggered before an API request is dispatched.
171 *
172 * This event can be used to modify the arguments passed to one or more API methods.
173 *
174 * **Example**
175 *
176 * Piwik::addAction('API.Request.dispatch', function (&$parameters, $pluginName, $methodName) {
177 * if ($pluginName == 'Actions') {
178 * if ($methodName == 'getPageUrls') {
179 * // ... do something ...
180 * } else {
181 * // ... do something else ...
182 * }
183 * }
184 * });
185 *
186 * @param array &$finalParameters List of parameters that will be passed to the API method.
187 * @param string $pluginName The name of the plugin the API method belongs to.
188 * @param string $methodName The name of the API method that will be called.
189 */
190 Piwik::postEvent('API.Request.dispatch', array(&$finalParameters, $pluginName, $methodName));
191
192 /**
193 * Triggered before an API request is dispatched.
194 *
195 * This event exists for convenience and is triggered directly after the {@hook API.Request.dispatch}
196 * event is triggered. It can be used to modify the arguments passed to a **single** API method.
197 *
198 * _Note: This is can be accomplished with the {@hook API.Request.dispatch} event as well, however
199 * event handlers for that event will have to do more work._
200 *
201 * **Example**
202 *
203 * Piwik::addAction('API.Actions.getPageUrls', function (&$parameters) {
204 * // force use of a single website. for some reason.
205 * $parameters['idSite'] = 1;
206 * });
207 *
208 * @param array &$finalParameters List of parameters that will be passed to the API method.
209 */
210 Piwik::postEvent(sprintf('API.%s.%s', $pluginName, $methodName), array(&$finalParameters));
211
212 /**
213 * Triggered before an API request is dispatched.
214 *
215 * Use this event to intercept an API request and execute your own code instead. If you set
216 * `$returnedValue` in a handler for this event, the original API method will not be executed,
217 * and the result will be what you set in the event handler.
218 *
219 * @param mixed &$returnedValue Set this to set the result and preempt normal API invocation.
220 * @param array &$finalParameters List of parameters that will be passed to the API method.
221 * @param string $pluginName The name of the plugin the API method belongs to.
222 * @param string $methodName The name of the API method that will be called.
223 * @param array $parametersRequest The query parameters for this request.
224 */
225 Piwik::postEvent('API.Request.intercept', [&$returnedValue, $finalParameters, $pluginName, $methodName, $parametersRequest]);
226
227 $apiParametersInCorrectOrder = array();
228
229 foreach ($parameterNamesDefaultValues as $name => $defaultValue) {
230 if (isset($finalParameters[$name]) || array_key_exists($name, $finalParameters)) {
231 $apiParametersInCorrectOrder[] = $finalParameters[$name];
232 }
233 }
234
235 // call the method if a hook hasn't already set an output variable
236 if ($returnedValue === null) {
237 $returnedValue = call_user_func_array(array($object, $methodName), $apiParametersInCorrectOrder);
238 }
239
240 $endHookParams = array(
241 &$returnedValue,
242 array('className' => $className,
243 'module' => $pluginName,
244 'action' => $methodName,
245 'parameters' => $finalParameters)
246 );
247
248 /**
249 * Triggered directly after an API request is dispatched.
250 *
251 * This event exists for convenience and is triggered immediately before the
252 * {@hook API.Request.dispatch.end} event. It can be used to modify the output of a **single**
253 * API method.
254 *
255 * _Note: This can be accomplished with the {@hook API.Request.dispatch.end} event as well,
256 * however event handlers for that event will have to do more work._
257 *
258 * **Example**
259 *
260 * // append (0 hits) to the end of row labels whose row has 0 hits
261 * Piwik::addAction('API.Actions.getPageUrls', function (&$returnValue, $info)) {
262 * $returnValue->filter('ColumnCallbackReplace', 'label', function ($label, $hits) {
263 * if ($hits === 0) {
264 * return $label . " (0 hits)";
265 * } else {
266 * return $label;
267 * }
268 * }, null, array('nb_hits'));
269 * }
270 *
271 * @param mixed &$returnedValue The API method's return value. Can be an object, such as a
272 * {@link Piwik\DataTable DataTable} instance.
273 * could be a {@link Piwik\DataTable DataTable}.
274 * @param array $extraInfo An array holding information regarding the API request. Will
275 * contain the following data:
276 *
277 * - **className**: The namespace-d class name of the API instance
278 * that's being called.
279 * - **module**: The name of the plugin the API request was
280 * dispatched to.
281 * - **action**: The name of the API method that was executed.
282 * - **parameters**: The array of parameters passed to the API
283 * method.
284 */
285 Piwik::postEvent(sprintf('API.%s.%s.end', $pluginName, $methodName), $endHookParams);
286
287 /**
288 * Triggered directly after an API request is dispatched.
289 *
290 * This event can be used to modify the output of any API method.
291 *
292 * **Example**
293 *
294 * // append (0 hits) to the end of row labels whose row has 0 hits for any report that has the 'nb_hits' metric
295 * Piwik::addAction('API.Actions.getPageUrls.end', function (&$returnValue, $info)) {
296 * // don't process non-DataTable reports and reports that don't have the nb_hits column
297 * if (!($returnValue instanceof DataTableInterface)
298 * || in_array('nb_hits', $returnValue->getColumns())
299 * ) {
300 * return;
301 * }
302 *
303 * $returnValue->filter('ColumnCallbackReplace', 'label', function ($label, $hits) {
304 * if ($hits === 0) {
305 * return $label . " (0 hits)";
306 * } else {
307 * return $label;
308 * }
309 * }, null, array('nb_hits'));
310 * }
311 *
312 * @param mixed &$returnedValue The API method's return value. Can be an object, such as a
313 * {@link Piwik\DataTable DataTable} instance.
314 * @param array $extraInfo An array holding information regarding the API request. Will
315 * contain the following data:
316 *
317 * - **className**: The namespace-d class name of the API instance
318 * that's being called.
319 * - **module**: The name of the plugin the API request was
320 * dispatched to.
321 * - **action**: The name of the API method that was executed.
322 * - **parameters**: The array of parameters passed to the API
323 * method.
324 */
325 Piwik::postEvent('API.Request.dispatch.end', $endHookParams);
326
327 return $returnedValue;
328 });
329 }
330
331 /**
332 * Returns the parameters names and default values for the method $name
333 * of the class $class
334 *
335 * @param string $class The class name
336 * @param string $name The method name
337 * @return array Format array(
338 * 'testParameter' => null, // no default value
339 * 'life' => 42, // default value = 42
340 * 'date' => 'yesterday',
341 * );
342 */
343 public function getParametersList($class, $name)
344 {
345 return $this->metadataArray[$class][$name]['parameters'];
346 }
347
348 /**
349 * Check if given method name is deprecated or not.
350 */
351 public function isDeprecatedMethod($class, $methodName)
352 {
353 return $this->metadataArray[$class][$methodName]['isDeprecated'];
354 }
355
356 /**
357 * Returns the 'moduleName' part of '\\Piwik\\Plugins\\moduleName\\API'
358 *
359 * @param string $className "API"
360 * @return string "Referrers"
361 */
362 public function getModuleNameFromClassName($className)
363 {
364 return str_replace(array('\\Piwik\\Plugins\\', '\\API'), '', $className);
365 }
366
367 public function isExistingApiAction($pluginName, $apiAction)
368 {
369 $namespacedApiClassName = "\\Piwik\\Plugins\\$pluginName\\API";
370 $api = $namespacedApiClassName::getInstance();
371
372 return method_exists($api, $apiAction);
373 }
374
375 public function buildApiActionName($pluginName, $apiAction)
376 {
377 return sprintf("%s.%s", $pluginName, $apiAction);
378 }
379
380 /**
381 * Sets whether to hide '@ignore'd functions from method metadata or not.
382 *
383 * @param bool $hideIgnoredFunctions
384 */
385 public function setHideIgnoredFunctions($hideIgnoredFunctions)
386 {
387 $this->hideIgnoredFunctions = $hideIgnoredFunctions;
388
389 // make sure metadata gets reloaded
390 $this->alreadyRegistered = array();
391 $this->metadataArray = array();
392 }
393
394 /**
395 * Returns an array containing the values of the parameters to pass to the method to call
396 *
397 * @param array $requiredParameters array of (parameter name, default value)
398 * @param array $parametersRequest
399 * @throws Exception
400 * @return array values to pass to the function call
401 */
402 private function getRequestParametersArray($requiredParameters, $parametersRequest)
403 {
404 $finalParameters = array();
405 foreach ($requiredParameters as $name => $defaultValue) {
406 try {
407 if ($defaultValue instanceof NoDefaultValue) {
408 $requestValue = Common::getRequestVar($name, null, null, $parametersRequest);
409 } else {
410 try {
411 if ($name == 'segment' && !empty($parametersRequest['segment'])) {
412 // segment parameter is an exception: we do not want to sanitize user input or it would break the segment encoding
413 $requestValue = ($parametersRequest['segment']);
414 } else {
415 $requestValue = Common::getRequestVar($name, $defaultValue, null, $parametersRequest);
416 }
417 } catch (Exception $e) {
418 // Special case: empty parameter in the URL, should return the empty string
419 if (isset($parametersRequest[$name])
420 && $parametersRequest[$name] === ''
421 ) {
422 $requestValue = '';
423 } else {
424 $requestValue = $defaultValue;
425 }
426 }
427 }
428 } catch (Exception $e) {
429 throw new Exception(Piwik::translate('General_PleaseSpecifyValue', array($name)));
430 }
431 $finalParameters[$name] = $requestValue;
432 }
433 return $finalParameters;
434 }
435
436 /**
437 * Includes the class API by looking up plugins/xxx/API.php
438 *
439 * @param string $fileName api class name eg. "API"
440 * @throws Exception
441 */
442 private function includeApiFile($fileName)
443 {
444 $module = self::getModuleNameFromClassName($fileName);
445 $path = Manager::getPluginDirectory($module) . '/API.php';
446
447 if (is_readable($path)) {
448 require_once $path; // prefixed by PIWIK_INCLUDE_PATH
449 } else {
450 throw new Exception("API module $module not found.");
451 }
452 }
453
454 /**
455 * @param string $class name of a class
456 * @param ReflectionMethod $method instance of ReflectionMethod
457 */
458 private function loadMethodMetadata($class, $method)
459 {
460 if (!$this->checkIfMethodIsAvailable($method)) {
461 return;
462 }
463 $name = $method->getName();
464 $parameters = $method->getParameters();
465 $docComment = $method->getDocComment();
466
467 $aParameters = array();
468 foreach ($parameters as $parameter) {
469 $nameVariable = $parameter->getName();
470
471 $defaultValue = $this->noDefaultValue;
472 if ($parameter->isDefaultValueAvailable()) {
473 $defaultValue = $parameter->getDefaultValue();
474 }
475
476 $aParameters[$nameVariable] = $defaultValue;
477 }
478 $this->metadataArray[$class][$name]['parameters'] = $aParameters;
479 $this->metadataArray[$class][$name]['numberOfRequiredParameters'] = $method->getNumberOfRequiredParameters();
480 $this->metadataArray[$class][$name]['isDeprecated'] = false !== strstr($docComment, '@deprecated');
481 }
482
483 /**
484 * Checks that the method exists in the class
485 *
486 * @param string $className The class name
487 * @param string $methodName The method name
488 * @throws Exception If the method is not found
489 */
490 private function checkMethodExists($className, $methodName)
491 {
492 if (!$this->isMethodAvailable($className, $methodName)) {
493 throw new Exception(Piwik::translate('General_ExceptionMethodNotFound', array($methodName, $className)));
494 }
495 }
496
497 /**
498 * @param $docComment
499 * @return bool
500 */
501 public function shouldHideAPIMethod($docComment)
502 {
503 $hideLine = strstr($docComment, '@hide');
504
505 if ($hideLine === false) {
506 return false;
507 }
508
509 $hideLine = trim($hideLine);
510 $hideLine .= ' ';
511
512 $token = trim(strtok($hideLine, " "), "\n");
513
514 $hide = false;
515
516 if (!empty($token)) {
517 /**
518 * This event exists for checking whether a Plugin API class or a Plugin API method tagged
519 * with a `@hideXYZ` should be hidden in the API listing.
520 *
521 * @param bool &$hide whether to hide APIs tagged with $token should be displayed.
522 */
523 Piwik::postEvent(sprintf('API.DocumentationGenerator.%s', $token), array(&$hide));
524 }
525
526 return $hide;
527 }
528
529 /**
530 * @param ReflectionMethod $method
531 * @return bool
532 */
533 protected function checkIfMethodIsAvailable(ReflectionMethod $method)
534 {
535 if (!$method->isPublic() || $method->isConstructor() || $method->getName() === 'getInstance') {
536 return false;
537 }
538
539 if ($this->hideIgnoredFunctions && false !== strstr($method->getDocComment(), '@ignore')) {
540 return false;
541 }
542
543 if ($this->shouldHideAPIMethod($method->getDocComment())) {
544 return false;
545 }
546
547 return true;
548 }
549
550 /**
551 * Returns true if the method is found in the API of the given class name.
552 *
553 * @param string $className The class name
554 * @param string $methodName The method name
555 * @return bool
556 */
557 private function isMethodAvailable($className, $methodName)
558 {
559 return isset($this->metadataArray[$className][$methodName]);
560 }
561
562 /**
563 * Checks that the class is a Singleton (presence of the getInstance() method)
564 *
565 * @param string $className The class name
566 * @throws Exception If the class is not a Singleton
567 */
568 private function checkClassIsSingleton($className)
569 {
570 if (!method_exists($className, "getInstance")) {
571 throw new Exception("$className that provide an API must be Singleton and have a 'public static function getInstance()' method.");
572 }
573 }
574 }
575
576 /**
577 * To differentiate between "no value" and default value of null
578 *
579 */
580 class NoDefaultValue
581 {
582 }
583