]> git.mxchange.org Git - friendica.git/blob - src/Module/Api/ApiResponse.php
Moved API\Notification tests
[friendica.git] / src / Module / Api / ApiResponse.php
1 <?php
2
3 namespace Friendica\Module\Api;
4
5 use Friendica\App\Arguments;
6 use Friendica\Core\L10n;
7 use Friendica\Core\System;
8 use Friendica\Object\Api\Mastodon\Error;
9 use Friendica\Util\Arrays;
10 use Friendica\Util\HTTPInputData;
11 use Friendica\Util\XML;
12 use Psr\Log\LoggerInterface;
13
14 /**
15  * This class is used to format and return API responses
16  */
17 class ApiResponse
18 {
19         /** @var L10n */
20         protected $l10n;
21         /** @var Arguments */
22         protected $args;
23         /** @var LoggerInterface */
24         protected $logger;
25
26         /**
27          * @param L10n            $l10n
28          * @param Arguments       $args
29          * @param LoggerInterface $logger
30          */
31         public function __construct(L10n $l10n, Arguments $args, LoggerInterface $logger)
32         {
33                 $this->l10n   = $l10n;
34                 $this->args   = $args;
35                 $this->logger = $logger;
36         }
37
38         /**
39          * Sets header directly
40          * mainly used to override it for tests
41          *
42          * @param string $header
43          */
44         protected function setHeader(string $header)
45         {
46                 header($header);
47         }
48
49         /**
50          * Prints output directly to the caller
51          * mainly used to override it for tests
52          *
53          * @param string $output
54          */
55         protected function printOutput(string $output)
56         {
57                 echo $output;
58                 exit;
59         }
60
61         /**
62          * Creates the XML from a JSON style array
63          *
64          * @param array  $data         JSON style array
65          * @param string $root_element Name of the root element
66          *
67          * @return string The XML data
68          */
69         public function createXML(array $data, string $root_element): string
70         {
71                 $childname = key($data);
72                 $data2     = array_pop($data);
73
74                 $namespaces = [
75                         ''          => 'http://api.twitter.com',
76                         'statusnet' => 'http://status.net/schema/api/1/',
77                         'friendica' => 'http://friendi.ca/schema/api/1/',
78                         'georss'    => 'http://www.georss.org/georss'
79                 ];
80
81                 /// @todo Auto detection of needed namespaces
82                 if (in_array($root_element, ['ok', 'hash', 'config', 'version', 'ids', 'notes', 'photos'])) {
83                         $namespaces = [];
84                 }
85
86                 if (is_array($data2)) {
87                         $key = key($data2);
88                         Arrays::walkRecursive($data2, ['Friendica\Module\Api\ApiResponse', 'reformatXML']);
89
90                         if ($key == '0') {
91                                 $data4 = [];
92                                 $i     = 1;
93
94                                 foreach ($data2 as $item) {
95                                         $data4[$i++ . ':' . $childname] = $item;
96                                 }
97
98                                 $data2 = $data4;
99                         }
100                 }
101
102                 $data3 = [$root_element => $data2];
103
104                 return XML::fromArray($data3, $xml, false, $namespaces);
105         }
106
107         /**
108          * Formats the data according to the data type
109          *
110          * @param string $root_element Name of the root element
111          * @param string $type         Return type (atom, rss, xml, json)
112          * @param array  $data         JSON style array
113          *
114          * @return array|string (string|array) XML data or JSON data
115          */
116         public function formatData(string $root_element, string $type, array $data)
117         {
118                 switch ($type) {
119                         case 'atom':
120                         case 'rss':
121                         case 'xml':
122                                 return $this->createXML($data, $root_element);
123                         case 'json':
124                         default:
125                                 return $data;
126                 }
127         }
128
129         /**
130          * Callback function to transform the array in an array that can be transformed in a XML file
131          *
132          * @param mixed  $item Array item value
133          * @param string $key  Array key
134          *
135          * @return boolean
136          */
137         public static function reformatXML(&$item, string &$key): bool
138         {
139                 if (is_bool($item)) {
140                         $item = ($item ? 'true' : 'false');
141                 }
142
143                 if (substr($key, 0, 10) == 'statusnet_') {
144                         $key = 'statusnet:' . substr($key, 10);
145                 } elseif (substr($key, 0, 10) == 'friendica_') {
146                         $key = 'friendica:' . substr($key, 10);
147                 }
148                 return true;
149         }
150
151         /**
152          * Exit with error code
153          *
154          * @param int         $code
155          * @param string      $description
156          * @param string      $message
157          * @param string|null $format
158          *
159          * @return void
160          */
161         public function error(int $code, string $description, string $message, string $format = null)
162         {
163                 $error = [
164                         'error'   => $message ?: $description,
165                         'code'    => $code . ' ' . $description,
166                         'request' => $this->args->getQueryString()
167                 ];
168
169                 $this->setHeader(($_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1') . ' ' . $code . ' ' . $description);
170
171                 $this->exit('status', ['status' => $error], $format);
172         }
173
174         /**
175          * Outputs formatted data according to the data type and then exits the execution.
176          *
177          * @param string      $root_element
178          * @param array       $data   An array with a single element containing the returned result
179          * @param string|null $format Output format (xml, json, rss, atom)
180          *
181          * @return void
182          */
183         public function exit(string $root_element, array $data, string $format = null)
184         {
185                 $format = $format ?? 'json';
186
187                 $return = $this->formatData($root_element, $format, $data);
188
189                 switch ($format) {
190                         case 'xml':
191                                 $this->setHeader('Content-Type: text/xml');
192                                 break;
193                         case 'json':
194                                 $this->setHeader('Content-Type: application/json');
195                                 if (!empty($return)) {
196                                         $json = json_encode(end($return));
197                                         if (!empty($_GET['callback'])) {
198                                                 $json = $_GET['callback'] . '(' . $json . ')';
199                                         }
200                                         $return = $json;
201                                 }
202                                 break;
203                         case 'rss':
204                                 $this->setHeader('Content-Type: application/rss+xml');
205                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
206                                 break;
207                         case 'atom':
208                                 $this->setHeader('Content-Type: application/atom+xml');
209                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
210                                 break;
211                 }
212
213                 $this->printOutput($return);
214         }
215
216         /**
217          * Quit execution with the message that the endpoint isn't implemented
218          *
219          * @param string $method
220          *
221          * @return void
222          * @throws \Exception
223          */
224         public function unsupported(string $method = 'all')
225         {
226                 $path = $this->args->getQueryString();
227                 $this->logger->info('Unimplemented API call',
228                         [
229                                 'method'  => $method,
230                                 'path'    => $path,
231                                 'agent'   => $_SERVER['HTTP_USER_AGENT'] ?? '',
232                                 'request' => HTTPInputData::process()
233                         ]);
234                 $error             = $this->l10n->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
235                 $error_description = $this->l10n->t('The API endpoint is currently not implemented but might be in the future.');
236                 $errorobj          = new Error($error, $error_description);
237                 System::jsonError(501, $errorobj->toArray());
238         }
239 }