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