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\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;
36 * This class is used to format and create API responses
38 class ApiResponse extends Response
44 /** @var LoggerInterface */
48 /** @var TwitterUser */
49 protected $twitterUser;
53 protected $jsonpCallback;
55 public function __construct(L10n $l10n, Arguments $args, LoggerInterface $logger, BaseURL $baseUrl, TwitterUser $twitterUser, array $server = [], string $jsonpCallback = '')
59 $this->logger = $logger;
60 $this->baseUrl = $baseUrl;
61 $this->twitterUser = $twitterUser;
62 $this->server = $server;
63 $this->jsonpCallback = $jsonpCallback;
67 * Creates the XML from a JSON style array
69 * @param array $data JSON style array
70 * @param string $root_element Name of the root element
72 * @return string The XML data
75 public function createXML(array $data, string $root_element): string
77 $childname = key($data);
78 $data2 = array_pop($data);
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'
87 /// @todo Auto detection of needed namespaces
88 if (in_array($root_element, ['ok', 'hash', 'config', 'version', 'ids', 'notes', 'photos'])) {
92 if (is_array($data2)) {
94 Arrays::walkRecursive($data2, ['Friendica\Module\Api\ApiResponse', 'reformatXML']);
100 foreach ($data2 as $item) {
101 $data4[$i++ . ':' . $childname] = $item;
108 $data3 = [$root_element => $data2];
110 return XML::fromArray($data3, $dummy, false, $namespaces);
114 * Set values for RSS template
116 * @param array $arr Array to be passed to template
117 * @param int $cid Contact ID of template
120 * @throws HTTPException\InternalServerErrorException
122 private function addRSSValues(array $arr, int $cid): array
128 $user_info = $this->twitterUser->createFromContactId($cid)->toArray();
130 $arr['$user'] = $user_info;
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',
145 * Formats the data according to the data type
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
152 * @return array|string (string|array) XML data or JSON data
153 * @throws HTTPException\InternalServerErrorException
155 public function formatData(string $root_element, string $type, array $data, int $cid = 0)
159 $data = $this->addRSSValues($data, $cid);
162 return $this->createXML($data, $root_element);
171 * Callback function to transform the array in an array that can be transformed in a XML file
173 * @param mixed $item Array item value
174 * @param string $key Array key
178 public static function reformatXML(&$item, string &$key): bool
180 if (is_bool($item)) {
181 $item = ($item ? 'true' : 'false');
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);
193 * Add formatted error message to response
196 * @param string $description
197 * @param string $message
198 * @param string|null $format
201 * @throws HTTPException\InternalServerErrorException
203 public function error(int $code, string $description, string $message, string $format = null)
206 'error' => $message ?: $description,
207 'code' => $code . ' ' . $description,
208 'request' => $this->args->getQueryString()
211 $this->setHeader(($this->server['SERVER_PROTOCOL'] ?? 'HTTP/1.1') . ' ' . $code . ' ' . $description);
213 $this->addFormattedContent('status', ['status' => $error], $format);
217 * Add formatted data according to the data type to the response.
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)
225 * @throws HTTPException\InternalServerErrorException
227 public function addFormattedContent(string $root_element, array $data, string $format = null, int $cid = 0)
229 $format = $format ?? 'json';
231 $return = $this->formatData($root_element, $format, $data, $cid);
235 $this->setType(static::TYPE_XML);
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 . ')';
250 $this->setType(static::TYPE_RSS);
254 $this->setType(static::TYPE_ATOM);
258 $this->addContent($return);
262 * Wrapper around addFormattedContent() for JSON only responses
267 * @throws HTTPException\InternalServerErrorException
269 public function addJsonContent(array $data)
271 $this->addFormattedContent('content', ['content' => $data], static::TYPE_JSON);
275 * Quit execution with the message that the endpoint isn't implemented
277 * @param string $method
278 * @param array $request (optional) The request content of the current call for later analysis
283 public function unsupported(string $method = 'all', array $request = [])
285 $path = $this->args->getQueryString();
286 $this->logger->info('Unimplemented API call',
290 'agent' => $this->server['HTTP_USER_AGENT'] ?? '',
291 'request' => $request,
293 $error = $this->l10n->t('API endpoint %s %s is not implemented but might be in the future.', strtoupper($method), $path);
295 $this->error(501, 'Not Implemented', $error);