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