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