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