]> git.mxchange.org Git - friendica.git/blob - src/Module/Api/ApiResponse.php
Merge pull request #12591 from MrPetovan/task/2023-licence
[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\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          *
111          * @return array
112          */
113         private function addRSSValues(array $arr, int $cid): array
114         {
115                 if (empty($cid)) {
116                         return $arr;
117                 }
118
119                 $user_info = $this->twitterUser->createFromContactId($cid)->toArray();
120
121                 $arr['$user'] = $user_info;
122                 $arr['$rss'] = [
123                         'alternate'    => $user_info['url'],
124                         'self'         => $this->baseUrl . '/' . $this->args->getQueryString(),
125                         'base'         => $this->baseUrl,
126                         'updated'      => DateTimeFormat::utcNow(DateTimeFormat::API),
127                         'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
128                         'language'     => $user_info['lang'],
129                         'logo'         => $this->baseUrl . '/images/friendica-32.png',
130                 ];
131
132                 return $arr;
133         }
134
135         /**
136          * Formats the data according to the data type
137          *
138          * @param string $root_element Name of the root element
139          * @param string $type         Return type (atom, rss, xml, json)
140          * @param array  $data         JSON style array
141          * @param int    $cid          ID of the contact for RSS
142          *
143          * @return array|string (string|array) XML data or JSON data
144          */
145         public function formatData(string $root_element, string $type, array $data, int $cid = 0)
146         {
147                 switch ($type) {
148                         case 'rss':
149                                 $data = $this->addRSSValues($data, $cid);
150                         case 'atom':
151                         case 'xml':
152                                 return $this->createXML($data, $root_element);
153
154                         case 'json':
155                         default:
156                                 return $data;
157                 }
158         }
159
160         /**
161          * Callback function to transform the array in an array that can be transformed in a XML file
162          *
163          * @param mixed  $item Array item value
164          * @param string $key  Array key
165          *
166          * @return boolean
167          */
168         public static function reformatXML(&$item, string &$key): bool
169         {
170                 if (is_bool($item)) {
171                         $item = ($item ? 'true' : 'false');
172                 }
173
174                 if (substr($key, 0, 10) == 'statusnet_') {
175                         $key = 'statusnet:' . substr($key, 10);
176                 } elseif (substr($key, 0, 10) == 'friendica_') {
177                         $key = 'friendica:' . substr($key, 10);
178                 }
179                 return true;
180         }
181
182         /**
183          * Exit with error code
184          *
185          * @param int         $code
186          * @param string      $description
187          * @param string      $message
188          * @param string|null $format
189          *
190          * @return void
191          */
192         public function error(int $code, string $description, string $message, string $format = null)
193         {
194                 $error = [
195                         'error'   => $message ?: $description,
196                         'code'    => $code . ' ' . $description,
197                         'request' => $this->args->getQueryString()
198                 ];
199
200                 $this->setHeader(($_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1') . ' ' . $code . ' ' . $description);
201
202                 $this->exit('status', ['status' => $error], $format);
203         }
204
205         /**
206          * Outputs formatted data according to the data type and then exits the execution.
207          *
208          * @param string      $root_element
209          * @param array       $data   An array with a single element containing the returned result
210          * @param string|null $format Output format (xml, json, rss, atom)
211          *
212          * @return void
213          */
214         public function exit(string $root_element, array $data, string $format = null, int $cid = 0)
215         {
216                 $format = $format ?? 'json';
217
218                 $return = $this->formatData($root_element, $format, $data, $cid);
219
220                 switch ($format) {
221                         case 'xml':
222                                 $this->setType(static::TYPE_XML);
223                                 break;
224
225                         case 'json':
226                                 $this->setType(static::TYPE_JSON);
227                                 if (!empty($return)) {
228                                         $json = json_encode(end($return));
229                                         if (!empty($_GET['callback'])) {
230                                                 $json = $_GET['callback'] . '(' . $json . ')';
231                                         }
232                                         $return = $json;
233                                 }
234                                 break;
235
236                         case 'rss':
237                                 $this->setType(static::TYPE_RSS);
238                                 break;
239
240                         case 'atom':
241                                 $this->setType(static::TYPE_ATOM);
242                                 break;
243                 }
244
245                 $this->addContent($return);
246         }
247
248         /**
249          * Wrapper around exit() for JSON only responses
250          *
251          * @param array $data
252          *
253          * @return void
254          */
255         public function exitWithJson(array $data)
256         {
257                 $this->exit('content', ['content' => $data], static::TYPE_JSON);
258         }
259
260         /**
261          * Quit execution with the message that the endpoint isn't implemented
262          *
263          * @param string $method
264          * @param array  $request (optional) The request content of the current call for later analysis
265          *
266          * @return void
267          * @throws \Exception
268          */
269         public function unsupported(string $method = 'all', array $request = [])
270         {
271                 $path = $this->args->getQueryString();
272                 $this->logger->info('Unimplemented API call',
273                         [
274                                 'method'  => $method,
275                                 'path'    => $path,
276                                 'agent'   => $_SERVER['HTTP_USER_AGENT'] ?? '',
277                                 'request' => $request,
278                         ]);
279                 $error             = $this->l10n->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
280                 $error_description = $this->l10n->t('The API endpoint is currently not implemented but might be in the future.');
281
282                 $this->exit('error', ['error' => ['error' => $error, 'error_description' => $error_description]]);
283         }
284 }