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