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