3 * @copyright Copyright (C) 2010-2022, 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, $xml, 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
112 private function addRSSValues(array $arr, int $cid)
118 $user_info = $this->twitterUser->createFromContactId($cid)->toArray();
120 $arr['$user'] = $user_info;
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',
135 * Formats the data according to the data type
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
142 * @return array|string (string|array) XML data or JSON data
144 public function formatData(string $root_element, string $type, array $data, int $cid = 0)
148 $data = $this->addRSSValues($data, $cid);
151 return $this->createXML($data, $root_element);
159 * Callback function to transform the array in an array that can be transformed in a XML file
161 * @param mixed $item Array item value
162 * @param string $key Array key
166 public static function reformatXML(&$item, string &$key): bool
168 if (is_bool($item)) {
169 $item = ($item ? 'true' : 'false');
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);
181 * Exit with error code
184 * @param string $description
185 * @param string $message
186 * @param string|null $format
190 public function error(int $code, string $description, string $message, string $format = null)
193 'error' => $message ?: $description,
194 'code' => $code . ' ' . $description,
195 'request' => $this->args->getQueryString()
198 $this->setHeader(($_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1') . ' ' . $code . ' ' . $description);
200 $this->exit('status', ['status' => $error], $format);
204 * Outputs formatted data according to the data type and then exits the execution.
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)
212 public function exit(string $root_element, array $data, string $format = null, int $cid = 0)
214 $format = $format ?? 'json';
216 $return = $this->formatData($root_element, $format, $data, $cid);
220 $this->setType(static::TYPE_XML);
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 . ')';
233 $this->setType(static::TYPE_RSS);
236 $this->setType(static::TYPE_ATOM);
240 $this->addContent($return);
244 * Wrapper around exit() for JSON only responses
248 public function exitWithJson(array $data)
250 $this->exit('content', ['content' => $data], static::TYPE_JSON);
254 * Quit execution with the message that the endpoint isn't implemented
256 * @param string $method
257 * @param array $request (optional) The request content of the current call for later analysis
262 public function unsupported(string $method = 'all', array $request = [])
264 $path = $this->args->getQueryString();
265 $this->logger->info('Unimplemented API call',
269 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
270 'request' => $request,
272 $error = $this->l10n->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
273 $error_description = $this->l10n->t('The API endpoint is currently not implemented but might be in the future.');
275 $this->exit('error', ['error' => ['error' => $error, 'error_description' => $error_description]]);