Teknik is a suite of services with attractive and functional interfaces. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ResponseBuilder.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. <?php
  2. /**
  3. * Piwik - free/libre analytics platform
  4. *
  5. * @link http://piwik.org
  6. * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  7. *
  8. */
  9. namespace Piwik\API;
  10. use Exception;
  11. use Piwik\API\DataTableManipulator\Flattener;
  12. use Piwik\API\DataTableManipulator\LabelFilter;
  13. use Piwik\API\DataTableManipulator\ReportTotalsCalculator;
  14. use Piwik\Common;
  15. use Piwik\DataTable;
  16. use Piwik\DataTable\Filter\PivotByDimension;
  17. use Piwik\DataTable\Renderer;
  18. use Piwik\DataTable\DataTableInterface;
  19. use Piwik\DataTable\Filter\ColumnDelete;
  20. use Piwik\Piwik;
  21. /**
  22. */
  23. class ResponseBuilder
  24. {
  25. private $outputFormat = null;
  26. private $apiRenderer = null;
  27. private $request = null;
  28. private $apiModule = false;
  29. private $apiMethod = false;
  30. /**
  31. * @param string $outputFormat
  32. * @param array $request
  33. */
  34. public function __construct($outputFormat, $request = array())
  35. {
  36. $this->outputFormat = $outputFormat;
  37. $this->request = $request;
  38. $this->apiRenderer = ApiRenderer::factory($outputFormat, $request);
  39. }
  40. /**
  41. * This method processes the data resulting from the API call.
  42. *
  43. * - If the data resulted from the API call is a DataTable then
  44. * - we apply the standard filters if the parameters have been found
  45. * in the URL. For example to offset,limit the Table you can add the following parameters to any API
  46. * call that returns a DataTable: filter_limit=10&filter_offset=20
  47. * - we apply the filters that have been previously queued on the DataTable
  48. * @see DataTable::queueFilter()
  49. * - we apply the renderer that generate the DataTable in a given format (XML, PHP, HTML, JSON, etc.)
  50. * the format can be changed using the 'format' parameter in the request.
  51. * Example: format=xml
  52. *
  53. * - If there is nothing returned (void) we display a standard success message
  54. *
  55. * - If there is a PHP array returned, we try to convert it to a dataTable
  56. * It is then possible to convert this datatable to any requested format (xml/etc)
  57. *
  58. * - If a bool is returned we convert to a string (true is displayed as 'true' false as 'false')
  59. *
  60. * - If an integer / float is returned, we simply return it
  61. *
  62. * @param mixed $value The initial returned value, before post process. If set to null, success response is returned.
  63. * @param bool|string $apiModule The API module that was called
  64. * @param bool|string $apiMethod The API method that was called
  65. * @return mixed Usually a string, but can still be a PHP data structure if the format requested is 'original'
  66. */
  67. public function getResponse($value = null, $apiModule = false, $apiMethod = false)
  68. {
  69. $this->apiModule = $apiModule;
  70. $this->apiMethod = $apiMethod;
  71. $this->apiRenderer->sendHeader();
  72. // when null or void is returned from the api call, we handle it as a successful operation
  73. if (!isset($value)) {
  74. if (ob_get_contents()) {
  75. return null;
  76. }
  77. return $this->apiRenderer->renderSuccess('ok');
  78. }
  79. // If the returned value is an object DataTable we
  80. // apply the set of generic filters if asked in the URL
  81. // and we render the DataTable according to the format specified in the URL
  82. if ($value instanceof DataTableInterface) {
  83. return $this->handleDataTable($value);
  84. }
  85. // Case an array is returned from the API call, we convert it to the requested format
  86. // - if calling from inside the application (format = original)
  87. // => the data stays unchanged (ie. a standard php array or whatever data structure)
  88. // - if any other format is requested, we have to convert this data structure (which we assume
  89. // to be an array) to a DataTable in order to apply the requested DataTable_Renderer (for example XML)
  90. if (is_array($value)) {
  91. return $this->handleArray($value);
  92. }
  93. if (is_object($value)) {
  94. return $this->apiRenderer->renderObject($value);
  95. }
  96. if (is_resource($value)) {
  97. return $this->apiRenderer->renderResource($value);
  98. }
  99. return $this->apiRenderer->renderScalar($value);
  100. }
  101. /**
  102. * Returns an error $message in the requested $format
  103. *
  104. * @param Exception $e
  105. * @throws Exception
  106. * @return string
  107. */
  108. public function getResponseException(Exception $e)
  109. {
  110. $e = $this->decorateExceptionWithDebugTrace($e);
  111. $message = $this->formatExceptionMessage($e);
  112. $this->apiRenderer->sendHeader();
  113. return $this->apiRenderer->renderException($message, $e);
  114. }
  115. /**
  116. * @param Exception $e
  117. * @return Exception
  118. */
  119. private function decorateExceptionWithDebugTrace(Exception $e)
  120. {
  121. // If we are in tests, show full backtrace
  122. if (defined('PIWIK_PATH_TEST_TO_ROOT')) {
  123. if (\Piwik_ShouldPrintBackTraceWithMessage()) {
  124. $message = $e->getMessage() . " in \n " . $e->getFile() . ":" . $e->getLine() . " \n " . $e->getTraceAsString();
  125. } else {
  126. $message = $e->getMessage() . "\n \n --> To temporarily debug this error further, set const PIWIK_PRINT_ERROR_BACKTRACE=true; in index.php";
  127. }
  128. return new Exception($message);
  129. }
  130. return $e;
  131. }
  132. private function formatExceptionMessage(Exception $exception)
  133. {
  134. $message = $exception->getMessage();
  135. if (\Piwik_ShouldPrintBackTraceWithMessage()) {
  136. $message .= "\n" . $exception->getTraceAsString();
  137. }
  138. return Renderer::formatValueXml($message);
  139. }
  140. protected function handleDataTable(DataTableInterface $datatable)
  141. {
  142. $label = $this->getLabelFromRequest($this->request);
  143. // handle pivot by dimension filter
  144. $pivotBy = Common::getRequestVar('pivotBy', false, 'string', $this->request);
  145. if (!empty($pivotBy)) {
  146. $reportId = $this->apiModule . '.' . $this->apiMethod;
  147. $pivotByColumn = Common::getRequestVar('pivotByColumn', false, 'string', $this->request);
  148. $pivotByColumnLimit = Common::getRequestVar('pivotByColumnLimit', false, 'int', $this->request);
  149. $datatable->filter('PivotByDimension', array($reportId, $pivotBy, $pivotByColumn, $pivotByColumnLimit,
  150. PivotByDimension::isSegmentFetchingEnabledInConfig()));
  151. }
  152. // if requested, flatten nested tables
  153. if (Common::getRequestVar('flat', '0', 'string', $this->request) == '1') {
  154. $flattener = new Flattener($this->apiModule, $this->apiMethod, $this->request);
  155. if (Common::getRequestVar('include_aggregate_rows', '0', 'string', $this->request) == '1') {
  156. $flattener->includeAggregateRows();
  157. }
  158. $datatable = $flattener->flatten($datatable);
  159. }
  160. if (1 == Common::getRequestVar('totals', '1', 'integer', $this->request)) {
  161. $genericFilter = new ReportTotalsCalculator($this->apiModule, $this->apiMethod, $this->request);
  162. $datatable = $genericFilter->calculate($datatable);
  163. }
  164. // if the flag disable_generic_filters is defined we skip the generic filters
  165. if (0 == Common::getRequestVar('disable_generic_filters', '0', 'string', $this->request)) {
  166. $genericFilter = new DataTableGenericFilter($this->request);
  167. if (!empty($label)) {
  168. $genericFilter->disableFilters(array('Limit', 'Truncate'));
  169. }
  170. $genericFilter->filter($datatable);
  171. }
  172. // we automatically safe decode all datatable labels (against xss)
  173. $datatable->queueFilter('SafeDecodeLabel');
  174. // if the flag disable_queued_filters is defined we skip the filters that were queued
  175. if (Common::getRequestVar('disable_queued_filters', 0, 'int', $this->request) == 0) {
  176. $datatable->applyQueuedFilters();
  177. }
  178. // use the ColumnDelete filter if hideColumns/showColumns is provided (must be done
  179. // after queued filters are run so processed metrics can be removed, too)
  180. $hideColumns = Common::getRequestVar('hideColumns', '', 'string', $this->request);
  181. $showColumns = Common::getRequestVar('showColumns', '', 'string', $this->request);
  182. if ($hideColumns !== '' || $showColumns !== '') {
  183. $datatable->filter('ColumnDelete', array($hideColumns, $showColumns));
  184. }
  185. // apply label filter: only return rows matching the label parameter (more than one if more than one label)
  186. if (!empty($label)) {
  187. $addLabelIndex = Common::getRequestVar('labelFilterAddLabelIndex', 0, 'int', $this->request) == 1;
  188. $filter = new LabelFilter($this->apiModule, $this->apiMethod, $this->request);
  189. $datatable = $filter->filter($label, $datatable, $addLabelIndex);
  190. }
  191. return $this->apiRenderer->renderDataTable($datatable);
  192. }
  193. protected function handleArray($array)
  194. {
  195. $firstArray = null;
  196. $firstKey = null;
  197. if (!empty($array)) {
  198. $firstArray = reset($array);
  199. $firstKey = key($array);
  200. }
  201. $isAssoc = !empty($firstArray) && is_numeric($firstKey) && is_array($firstArray) && count(array_filter(array_keys($firstArray), 'is_string'));
  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. } else if (is_numeric($firstKey)) {
  210. $limit = Common::getRequestVar('filter_limit', -1, 'integer', $this->request);
  211. $offset = Common::getRequestVar('filter_offset', '0', 'integer', $this->request);
  212. if (-1 !== $limit) {
  213. $array = array_slice($array, $offset, $limit);
  214. }
  215. }
  216. return $this->apiRenderer->renderArray($array);
  217. }
  218. /**
  219. * Returns the value for the label query parameter which can be either a string
  220. * (ie, label=...) or array (ie, label[]=...).
  221. *
  222. * @param array $request
  223. * @return array
  224. */
  225. public static function getLabelFromRequest($request)
  226. {
  227. $label = Common::getRequestVar('label', array(), 'array', $request);
  228. if (empty($label)) {
  229. $label = Common::getRequestVar('label', '', 'string', $request);
  230. if (!empty($label)) {
  231. $label = array($label);
  232. }
  233. }
  234. $label = self::unsanitizeLabelParameter($label);
  235. return $label;
  236. }
  237. public static function unsanitizeLabelParameter($label)
  238. {
  239. // this is needed because Proxy uses Common::getRequestVar which in turn
  240. // uses Common::sanitizeInputValue. This causes the > that separates recursive labels
  241. // to become &gt; and we need to undo that here.
  242. $label = Common::unsanitizeInputValues($label);
  243. return $label;
  244. }
  245. }