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