]> git.mxchange.org Git - friendica.git/blob - src/Module/Api/ApiResponse.php
Merge pull request #11841 from Quix0r/cleanups/type-hints-documentation
[friendica.git] / src / Module / Api / ApiResponse.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Module\Api;
23
24 use Friendica\App\Arguments;
25 use Friendica\App\BaseURL;
26 use Friendica\Core\L10n;
27 use Friendica\Module\Response;
28 use Friendica\Util\Arrays;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\XML;
31 use Psr\Log\LoggerInterface;
32 use Friendica\Factory\Api\Twitter\User as TwitterUser;
33
34 /**
35  * This class is used to format and create API responses
36  */
37 class ApiResponse extends Response
38 {
39         /** @var L10n */
40         protected $l10n;
41         /** @var Arguments */
42         protected $args;
43         /** @var LoggerInterface */
44         protected $logger;
45         /** @var BaseURL */
46         protected $baseUrl;
47         /** @var TwitterUser */
48         protected $twitterUser;
49
50         public function __construct(L10n $l10n, Arguments $args, LoggerInterface $logger, BaseURL $baseUrl, TwitterUser $twitterUser)
51         {
52                 $this->l10n        = $l10n;
53                 $this->args        = $args;
54                 $this->logger      = $logger;
55                 $this->baseUrl     = $baseUrl;
56                 $this->twitterUser = $twitterUser;
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          * Set values for RSS template
107          *
108          * @param array $arr Array to be passed to template
109          * @param int   $cid Contact ID of template
110          * @return array
111          */
112         private function addRSSValues(array $arr, int $cid): array
113         {
114                 if (empty($cid)) {
115                         return $arr;
116                 }
117
118                 $user_info = $this->twitterUser->createFromContactId($cid)->toArray();
119
120                 $arr['$user'] = $user_info;
121                 $arr['$rss'] = [
122                         'alternate'    => $user_info['url'],
123                         'self'         => $this->baseUrl . '/' . $this->args->getQueryString(),
124                         'base'         => $this->baseUrl,
125                         'updated'      => DateTimeFormat::utcNow(DateTimeFormat::API),
126                         'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
127                         'language'     => $user_info['lang'],
128                         'logo'         => $this->baseUrl . '/images/friendica-32.png',
129                 ];
130
131                 return $arr;
132         }
133
134         /**
135          * Formats the data according to the data type
136          *
137          * @param string $root_element Name of the root element
138          * @param string $type         Return type (atom, rss, xml, json)
139          * @param array  $data         JSON style array
140          * @param int    $cid          ID of the contact for RSS
141          *
142          * @return array|string (string|array) XML data or JSON data
143          */
144         public function formatData(string $root_element, string $type, array $data, int $cid = 0)
145         {
146                 switch ($type) {
147                         case 'rss':
148                                 $data = $this->addRSSValues($data, $cid);
149                         case 'atom':
150                         case 'xml':
151                                 return $this->createXML($data, $root_element);
152                         case 'json':
153                         default:
154                                 return $data;
155                 }
156         }
157
158         /**
159          * Callback function to transform the array in an array that can be transformed in a XML file
160          *
161          * @param mixed  $item Array item value
162          * @param string $key  Array key
163          *
164          * @return boolean
165          */
166         public static function reformatXML(&$item, string &$key): bool
167         {
168                 if (is_bool($item)) {
169                         $item = ($item ? 'true' : 'false');
170                 }
171
172                 if (substr($key, 0, 10) == 'statusnet_') {
173                         $key = 'statusnet:' . substr($key, 10);
174                 } elseif (substr($key, 0, 10) == 'friendica_') {
175                         $key = 'friendica:' . substr($key, 10);
176                 }
177                 return true;
178         }
179
180         /**
181          * Exit with error code
182          *
183          * @param int         $code
184          * @param string      $description
185          * @param string      $message
186          * @param string|null $format
187          *
188          * @return void
189          */
190         public function error(int $code, string $description, string $message, string $format = null)
191         {
192                 $error = [
193                         'error'   => $message ?: $description,
194                         'code'    => $code . ' ' . $description,
195                         'request' => $this->args->getQueryString()
196                 ];
197
198                 $this->setHeader(($_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1') . ' ' . $code . ' ' . $description);
199
200                 $this->exit('status', ['status' => $error], $format);
201         }
202
203         /**
204          * Outputs formatted data according to the data type and then exits the execution.
205          *
206          * @param string      $root_element
207          * @param array       $data   An array with a single element containing the returned result
208          * @param string|null $format Output format (xml, json, rss, atom)
209          *
210          * @return void
211          */
212         public function exit(string $root_element, array $data, string $format = null, int $cid = 0)
213         {
214                 $format = $format ?? 'json';
215
216                 $return = $this->formatData($root_element, $format, $data, $cid);
217
218                 switch ($format) {
219                         case 'xml':
220                                 $this->setType(static::TYPE_XML);
221                                 break;
222                         case 'json':
223                                 $this->setType(static::TYPE_JSON);
224                                 if (!empty($return)) {
225                                         $json = json_encode(end($return));
226                                         if (!empty($_GET['callback'])) {
227                                                 $json = $_GET['callback'] . '(' . $json . ')';
228                                         }
229                                         $return = $json;
230                                 }
231                                 break;
232                         case 'rss':
233                                 $this->setType(static::TYPE_RSS);
234                                 break;
235                         case 'atom':
236                                 $this->setType(static::TYPE_ATOM);
237                                 break;
238                 }
239
240                 $this->addContent($return);
241         }
242
243         /**
244          * Wrapper around exit() for JSON only responses
245          *
246          * @param array $data
247          *
248          * @return void
249          */
250         public function exitWithJson(array $data)
251         {
252                 $this->exit('content', ['content' => $data], static::TYPE_JSON);
253         }
254
255         /**
256          * Quit execution with the message that the endpoint isn't implemented
257          *
258          * @param string $method
259          * @param array  $request (optional) The request content of the current call for later analysis
260          *
261          * @return void
262          * @throws \Exception
263          */
264         public function unsupported(string $method = 'all', array $request = [])
265         {
266                 $path = $this->args->getQueryString();
267                 $this->logger->info('Unimplemented API call',
268                         [
269                                 'method'  => $method,
270                                 'path'    => $path,
271                                 'agent'   => $_SERVER['HTTP_USER_AGENT'] ?? '',
272                                 'request' => $request,
273                         ]);
274                 $error             = $this->l10n->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
275                 $error_description = $this->l10n->t('The API endpoint is currently not implemented but might be in the future.');
276
277                 $this->exit('error', ['error' => ['error' => $error, 'error_description' => $error_description]]);
278         }
279 }