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
|
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\API\Renderer;
use Piwik\API\ApiRenderer;
use Piwik\Common;
use Piwik\DataTable\Renderer;
use Piwik\Piwik;
use Piwik\ProxyHttp;
/**
* API output renderer for JSON.
*/
class Json extends ApiRenderer
{
public function renderSuccess($message)
{
$result = json_encode(array('result' => 'success', 'message' => $message));
return $this->applyJsonpIfNeeded($result);
}
/**
* @param $message
* @param \Exception|\Throwable $exception
* @return string
*/
public function renderException($message, $exception)
{
$exceptionMessage = str_replace(array("\r\n", "\n"), " ", $message);
$data = array('result' => 'error', 'message' => $exceptionMessage);
if ($this->shouldSendBacktrace()) {
$data['backtrace'] = $exception->getTraceAsString();
}
$result = json_encode($data);
return $this->applyJsonpIfNeeded($result);
}
public function renderDataTable($dataTable)
{
$result = parent::renderDataTable($dataTable);
return $this->applyJsonpIfNeeded($result);
}
public function renderArray($array)
{
if (Piwik::isMultiDimensionalArray($array)) {
$jsonRenderer = Renderer::factory('json');
$jsonRenderer->setTable($array);
$result = $jsonRenderer->render();
return $this->applyJsonpIfNeeded($result);
}
$result = $this->renderDataTable($array);
// if $array is a simple associative array, remove the JSON root array that is added by renderDataTable
if (!empty($array)
&& Piwik::isAssociativeArray($array)
&& !Piwik::isMultiDimensionalArray($array)
) {
$result = substr($result, 1, strlen($result) - 2);
}
return $result;
}
public function sendHeader()
{
if ($this->isJsonp()) {
Common::sendHeader('Content-Type: application/javascript; charset=utf-8');
} else {
Renderer\Json::sendHeaderJSON();
}
ProxyHttp::overrideCacheControlHeaders();
}
private function isJsonp()
{
$callback = $this->getJsonpCallback();
if (false === $callback) {
return false;
}
return preg_match('/^[0-9a-zA-Z_.]*$/D', $callback) > 0;
}
private function getJsonpCallback()
{
$jsonCallback = Common::getRequestVar('callback', false, null, $this->request);
if ($jsonCallback === false) {
$jsonCallback = Common::getRequestVar('jsoncallback', false, null, $this->request);
}
return $jsonCallback;
}
/**
* @param $str
* @return string
*/
private function applyJsonpIfNeeded($str)
{
if ($this->isJsonp()) {
$jsonCallback = $this->getJsonpCallback();
$str = $jsonCallback . "(" . $str . ")";
}
return $str;
}
}
|