3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Module\Api;
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;
35 * This class is used to format and create API responses
37 class ApiResponse extends Response
43 /** @var LoggerInterface */
47 /** @var TwitterUser */
48 protected $twitterUser;
50 public function __construct(L10n $l10n, Arguments $args, LoggerInterface $logger, BaseURL $baseUrl, TwitterUser $twitterUser)
54 $this->logger = $logger;
55 $this->baseUrl = $baseUrl;
56 $this->twitterUser = $twitterUser;
60 * Creates the XML from a JSON style array
62 * @param array $data JSON style array
63 * @param string $root_element Name of the root element
65 * @return string The XML data
67 public function createXML(array $data, string $root_element): string
69 $childname = key($data);
70 $data2 = array_pop($data);
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'
79 /// @todo Auto detection of needed namespaces
80 if (in_array($root_element, ['ok', 'hash', 'config', 'version', 'ids', 'notes', 'photos'])) {
84 if (is_array($data2)) {
86 Arrays::walkRecursive($data2, ['Friendica\Module\Api\ApiResponse', 'reformatXML']);
92 foreach ($data2 as $item) {
93 $data4[$i++ . ':' . $childname] = $item;
100 $data3 = [$root_element => $data2];
102 return XML::fromArray($data3, $dummy, false, $namespaces);
106 * Set values for RSS template
108 * @param array $arr Array to be passed to template
109 * @param int $cid Contact ID of template
113 private function addRSSValues(array $arr, int $cid): array
119 $user_info = $this->twitterUser->createFromContactId($cid)->toArray();
121 $arr['$user'] = $user_info;
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',
136 * Formats the data according to the data type
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
143 * @return array|string (string|array) XML data or JSON data
145 public function formatData(string $root_element, string $type, array $data, int $cid = 0)
149 $data = $this->addRSSValues($data, $cid);
152 return $this->createXML($data, $root_element);
161 * Callback function to transform the array in an array that can be transformed in a XML file
163 * @param mixed $item Array item value
164 * @param string $key Array key
168 public static function reformatXML(&$item, string &$key): bool
170 if (is_bool($item)) {
171 $item = ($item ? 'true' : 'false');
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);
183 * Exit with error code
186 * @param string $description
187 * @param string $message
188 * @param string|null $format
192 public function error(int $code, string $description, string $message, string $format = null)
195 'error' => $message ?: $description,
196 'code' => $code . ' ' . $description,
197 'request' => $this->args->getQueryString()
200 $this->setHeader(($_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1') . ' ' . $code . ' ' . $description);
202 $this->exit('status', ['status' => $error], $format);
206 * Outputs formatted data according to the data type and then exits the execution.
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)
214 public function exit(string $root_element, array $data, string $format = null, int $cid = 0)
216 $format = $format ?? 'json';
218 $return = $this->formatData($root_element, $format, $data, $cid);
222 $this->setType(static::TYPE_XML);
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 . ')';
237 $this->setType(static::TYPE_RSS);
241 $this->setType(static::TYPE_ATOM);
245 $this->addContent($return);
249 * Wrapper around exit() for JSON only responses
255 public function exitWithJson(array $data)
257 $this->exit('content', ['content' => $data], static::TYPE_JSON);
261 * Quit execution with the message that the endpoint isn't implemented
263 * @param string $method
264 * @param array $request (optional) The request content of the current call for later analysis
269 public function unsupported(string $method = 'all', array $request = [])
271 $path = $this->args->getQueryString();
272 $this->logger->info('Unimplemented API call',
276 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
277 'request' => $request,
279 $error = $this->l10n->t('API endpoint %s %s is not implemented but might be in the future.', strtoupper($method), $path);
281 $this->error(501, 'Not Implemented', $error);