PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / trunk
Matomo Analytics – Powerful, Privacy-First Insights for WordPress vtrunk
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 / ResponseBuilder.php
matomo / app / core / API Last commit date
DataTableManipulator 1 month ago ApiRenderer.php 3 months ago CORSHandler.php 1 year ago DataTableGenericFilter.php 1 month ago DataTableManipulator.php 1 month ago DataTablePostProcessor.php 1 month ago DocumentationGenerator.php 6 months ago Inconsistencies.php 2 years ago NoDefaultValue.php 2 years ago Proxy.php 1 month ago Request.php 1 month ago ResponseBuilder.php 1 month ago
ResponseBuilder.php
225 lines
1 <?php
2
3 /**
4 * Matomo - free/libre analytics platform
5 *
6 * @link https://matomo.org
7 * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8 */
9 namespace Piwik\API;
10
11 use Exception;
12 use Piwik\Common;
13 use Piwik\DataTable;
14 use Piwik\DataTable\DataTableInterface;
15 use Piwik\DataTable\Filter\ColumnDelete;
16 use Piwik\DataTable\Filter\Pattern;
17 use Piwik\DataTable\Renderer;
18 use Piwik\ExceptionHandler;
19 use Piwik\Http\HttpCodeException;
20 use Piwik\Plugin\ReportsProvider;
21 use Piwik\Plugins\Monolog\Processor\ExceptionToTextProcessor;
22 use Piwik\Plugins\PrivacyManager\DataRounding;
23 class ResponseBuilder
24 {
25 private $outputFormat = null;
26 private $apiRenderer = null;
27 private $request = null;
28 private $sendHeader = \true;
29 private $postProcessDataTable = \true;
30 private $apiModule = \false;
31 private $apiMethod = \false;
32 private $shouldPrintBacktrace = \false;
33 /**
34 * @param string $outputFormat
35 * @param array $request
36 */
37 public function __construct($outputFormat, $request = array(), $shouldPrintBacktrace = null)
38 {
39 $this->outputFormat = $outputFormat;
40 $this->request = $request;
41 $this->apiRenderer = \Piwik\API\ApiRenderer::factory($outputFormat, $request);
42 $this->shouldPrintBacktrace = $shouldPrintBacktrace === null ? ExceptionHandler::shouldPrintBackTraceWithMessage() : $shouldPrintBacktrace;
43 }
44 public function disableSendHeader()
45 {
46 $this->sendHeader = \false;
47 }
48 public function disableDataTablePostProcessor()
49 {
50 $this->postProcessDataTable = \false;
51 }
52 /**
53 * This method processes the data resulting from the API call.
54 *
55 * - If the data resulted from the API call is a DataTable then
56 * - we apply the standard filters if the parameters have been found
57 * in the URL. For example to offset,limit the Table you can add the following parameters to any API
58 * call that returns a DataTable: filter_limit=10&filter_offset=20
59 * - we apply the filters that have been previously queued on the DataTable
60 * @see DataTable::queueFilter()
61 * - we apply the renderer that generate the DataTable in a given format (XML, PHP, HTML, JSON, etc.)
62 * the format can be changed using the 'format' parameter in the request.
63 * Example: format=xml
64 *
65 * - If there is nothing returned (void) we display a standard success message
66 *
67 * - If there is a PHP array returned, we try to convert it to a dataTable
68 * It is then possible to convert this datatable to any requested format (xml/etc)
69 *
70 * - If a bool is returned we convert to a string (true is displayed as 'true' false as 'false')
71 *
72 * - If an integer / float is returned, we simply return it
73 *
74 * @param mixed $value The initial returned value, before post process. If set to null, success response is returned.
75 * @param bool|string $apiModule The API module that was called
76 * @param bool|string $apiMethod The API method that was called
77 * @return mixed Usually a string, but can still be a PHP data structure if the format requested is 'original'
78 */
79 public function getResponse($value = null, $apiModule = \false, $apiMethod = \false)
80 {
81 $this->apiModule = $apiModule;
82 $this->apiMethod = $apiMethod;
83 $this->sendHeaderIfEnabled();
84 // when null or void is returned from the api call, we handle it as a successful operation
85 if (!isset($value)) {
86 if (ob_get_contents()) {
87 return null;
88 }
89 return $this->apiRenderer->renderSuccess('ok');
90 }
91 // If the returned value is an object DataTable we
92 // apply the set of generic filters if asked in the URL
93 // and we render the DataTable according to the format specified in the URL
94 if ($value instanceof DataTableInterface) {
95 return $this->handleDataTable($value);
96 }
97 // Case an array is returned from the API call, we convert it to the requested format
98 // - if calling from inside the application (format = original)
99 // => the data stays unchanged (ie. a standard php array or whatever data structure)
100 // - if any other format is requested, we have to convert this data structure (which we assume
101 // to be an array) to a DataTable in order to apply the requested DataTable_Renderer (for example XML)
102 if (is_array($value)) {
103 return $this->handleArray($value);
104 }
105 if (is_object($value)) {
106 return $this->apiRenderer->renderObject($value);
107 }
108 if (is_resource($value)) {
109 return $this->apiRenderer->renderResource($value);
110 }
111 return $this->apiRenderer->renderScalar($value);
112 }
113 /**
114 * Returns an error $message in the requested $format
115 *
116 * @param Exception|\Throwable $e
117 * @throws Exception
118 * @return string
119 */
120 public function getResponseException($e)
121 {
122 $e = $this->decorateExceptionWithDebugTrace($e);
123 $message = $this->formatExceptionMessage($e);
124 if ($this->sendHeader && $e instanceof HttpCodeException && $e->getCode() > 0) {
125 http_response_code($e->getCode());
126 }
127 $this->sendHeaderIfEnabled();
128 return $this->apiRenderer->renderException($message, $e);
129 }
130 /**
131 * @param Exception|\Throwable $e
132 * @return Exception
133 */
134 private function decorateExceptionWithDebugTrace($e)
135 {
136 // If we are in tests, show full backtrace
137 if (defined('PIWIK_PATH_TEST_TO_ROOT')) {
138 if ($this->shouldPrintBacktrace) {
139 $message = $e->getMessage() . " in \n " . $e->getFile() . ":" . $e->getLine() . " \n " . $e->getTraceAsString();
140 } else {
141 $message = $e->getMessage() . "\n \n --> To temporarily debug this error further, set const PIWIK_PRINT_ERROR_BACKTRACE=true; in index.php";
142 }
143 return new Exception($message);
144 }
145 return $e;
146 }
147 /**
148 * @param Exception|\Throwable $exception
149 * @return string
150 */
151 private function formatExceptionMessage($exception)
152 {
153 $message = ExceptionToTextProcessor::getMessageAndWholeBacktrace($exception, $this->shouldPrintBacktrace);
154 if ($exception instanceof \Piwik\Exception\Exception && $exception->isHtmlMessage() && \Piwik\API\Request::isRootRequestApiRequest()) {
155 $message = strip_tags(str_replace('<br />', \PHP_EOL, $message));
156 }
157 return Renderer::formatValueXml($message);
158 }
159 private function handleDataTable(DataTableInterface $datatable)
160 {
161 if ($this->postProcessDataTable) {
162 $postProcessor = new \Piwik\API\DataTablePostProcessor($this->apiModule, $this->apiMethod, $this->request);
163 $datatable = $postProcessor->process($datatable);
164 } else {
165 $report = null;
166 if (DataRounding::shouldApplyForRequest($this->request) && !empty($this->apiModule) && !empty($this->apiMethod)) {
167 $report = ReportsProvider::factory($this->apiModule, $this->apiMethod);
168 }
169 DataRounding::roundCountMetricsForRequest($datatable, $this->request, $report);
170 }
171 return $this->apiRenderer->renderDataTable($datatable);
172 }
173 private function handleArray($array)
174 {
175 if (!$this->shouldSkipRequestBasedArrayRounding() && DataRounding::shouldApplyForRequest($this->request)) {
176 $array = DataRounding::roundCountArrayValuesForRequest($array, $this->request);
177 }
178 $firstArray = null;
179 $firstKey = null;
180 if (!empty($array)) {
181 $firstArray = reset($array);
182 $firstKey = key($array);
183 }
184 $isAssoc = !empty($firstArray) && is_numeric($firstKey) && is_array($firstArray) && count(array_filter(array_keys($firstArray), 'is_string'));
185 if (is_numeric($firstKey)) {
186 $columns = Common::getRequestVar('filter_column', \false, 'array', $this->request);
187 $pattern = Common::getRequestVar('filter_pattern', '', 'string', $this->request);
188 if ($columns != array(\false) && $pattern !== '') {
189 $pattern = new Pattern(new DataTable(), $columns, $pattern);
190 $array = $pattern->filterArray($array);
191 }
192 $limit = Common::getRequestVar('filter_limit', -1, 'integer', $this->request);
193 $offset = Common::getRequestVar('filter_offset', '0', 'integer', $this->request);
194 if ($limit >= 0 || $offset > 0) {
195 if ($limit < 0) {
196 $limit = null;
197 // make sure to return all results from offset
198 }
199 $array = array_slice($array, $offset, $limit, $preserveKeys = \false);
200 }
201 }
202 if ($isAssoc) {
203 $hideColumns = Common::getRequestVar('hideColumns', '', 'string', $this->request);
204 $showColumns = Common::getRequestVar('showColumns', '', 'string', $this->request);
205 if ($hideColumns !== '' || $showColumns !== '') {
206 $columnDelete = new ColumnDelete(new DataTable(), $hideColumns, $showColumns);
207 $array = $columnDelete->filter($array);
208 }
209 }
210 return $this->apiRenderer->renderArray($array);
211 }
212 private function shouldSkipRequestBasedArrayRounding() : bool
213 {
214 // MultiSites.getAllWithGroups applies per-row site-aware rounding later, so request-level array
215 // rounding here would double-round mixed-policy payloads based on the ambient request site list.
216 return $this->apiModule === 'MultiSites' && $this->apiMethod === 'getAllWithGroups';
217 }
218 private function sendHeaderIfEnabled()
219 {
220 if ($this->sendHeader) {
221 $this->apiRenderer->sendHeader();
222 }
223 }
224 }
225