3 namespace Friendica\Module\Api;
5 use Friendica\App\Arguments;
6 use Friendica\App\BaseURL;
7 use Friendica\Core\L10n;
8 use Friendica\Module\Response;
9 use Friendica\Util\Arrays;
10 use Friendica\Util\DateTimeFormat;
11 use Friendica\Util\HTTPInputData;
12 use Friendica\Util\XML;
13 use Psr\Log\LoggerInterface;
14 use Friendica\Factory\Api\Twitter\User as TwitterUser;
17 * This class is used to format and create API responses
19 class ApiResponse extends Response
25 /** @var LoggerInterface */
29 /** @var TwitterUser */
30 protected $twitterUser;
32 public function __construct(L10n $l10n, Arguments $args, LoggerInterface $logger, BaseURL $baseUrl, TwitterUser $twitterUser)
36 $this->logger = $logger;
37 $this->baseUrl = $baseUrl;
38 $this->twitterUser = $twitterUser;
42 * Creates the XML from a JSON style array
44 * @param array $data JSON style array
45 * @param string $root_element Name of the root element
47 * @return string The XML data
49 public function createXML(array $data, string $root_element): string
51 $childname = key($data);
52 $data2 = array_pop($data);
55 '' => 'http://api.twitter.com',
56 'statusnet' => 'http://status.net/schema/api/1/',
57 'friendica' => 'http://friendi.ca/schema/api/1/',
58 'georss' => 'http://www.georss.org/georss'
61 /// @todo Auto detection of needed namespaces
62 if (in_array($root_element, ['ok', 'hash', 'config', 'version', 'ids', 'notes', 'photos'])) {
66 if (is_array($data2)) {
68 Arrays::walkRecursive($data2, ['Friendica\Module\Api\ApiResponse', 'reformatXML']);
74 foreach ($data2 as $item) {
75 $data4[$i++ . ':' . $childname] = $item;
82 $data3 = [$root_element => $data2];
84 return XML::fromArray($data3, $xml, false, $namespaces);
88 * Set values for RSS template
90 * @param array $arr Array to be passed to template
91 * @param int $cid Contact ID of template
94 private function addRSSValues(array $arr, int $cid)
100 $user_info = $this->twitterUser->createFromContactId($cid)->toArray();
102 $arr['$user'] = $user_info;
104 'alternate' => $user_info['url'],
105 'self' => $this->baseUrl . '/' . $this->args->getQueryString(),
106 'base' => $this->baseUrl,
107 'updated' => DateTimeFormat::utc(null, DateTimeFormat::API),
108 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
109 'language' => $user_info['lang'],
110 'logo' => $this->baseUrl . '/images/friendica-32.png',
117 * Formats the data according to the data type
119 * @param string $root_element Name of the root element
120 * @param string $type Return type (atom, rss, xml, json)
121 * @param array $data JSON style array
122 * @param int $cid ID of the contact for RSS
124 * @return array|string (string|array) XML data or JSON data
126 public function formatData(string $root_element, string $type, array $data, int $cid = 0)
130 $data = $this->addRSSValues($data, $cid);
133 return $this->createXML($data, $root_element);
141 * Callback function to transform the array in an array that can be transformed in a XML file
143 * @param mixed $item Array item value
144 * @param string $key Array key
148 public static function reformatXML(&$item, string &$key): bool
150 if (is_bool($item)) {
151 $item = ($item ? 'true' : 'false');
154 if (substr($key, 0, 10) == 'statusnet_') {
155 $key = 'statusnet:' . substr($key, 10);
156 } elseif (substr($key, 0, 10) == 'friendica_') {
157 $key = 'friendica:' . substr($key, 10);
163 * Exit with error code
166 * @param string $description
167 * @param string $message
168 * @param string|null $format
172 public function error(int $code, string $description, string $message, string $format = null)
175 'error' => $message ?: $description,
176 'code' => $code . ' ' . $description,
177 'request' => $this->args->getQueryString()
180 $this->setHeader(($_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1') . ' ' . $code . ' ' . $description);
182 $this->exit('status', ['status' => $error], $format);
186 * Outputs formatted data according to the data type and then exits the execution.
188 * @param string $root_element
189 * @param array $data An array with a single element containing the returned result
190 * @param string|null $format Output format (xml, json, rss, atom)
194 public function exit(string $root_element, array $data, string $format = null, int $cid = 0)
196 $format = $format ?? 'json';
198 $return = $this->formatData($root_element, $format, $data, $cid);
202 $this->setHeader('Content-Type: text/xml');
205 $this->setHeader('Content-Type: application/json');
206 if (!empty($return)) {
207 $json = json_encode(end($return));
208 if (!empty($_GET['callback'])) {
209 $json = $_GET['callback'] . '(' . $json . ')';
215 $this->setHeader('Content-Type: application/rss+xml');
218 $this->setHeader('Content-Type: application/atom+xml');
222 $this->addContent($return);
226 * Quit execution with the message that the endpoint isn't implemented
228 * @param string $method
233 public function unsupported(string $method = 'all')
235 $path = $this->args->getQueryString();
236 $this->logger->info('Unimplemented API call',
240 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
241 'request' => HTTPInputData::process()
243 $error = $this->l10n->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
244 $error_description = $this->l10n->t('The API endpoint is currently not implemented but might be in the future.');
246 $this->exit('error', ['error' => ['error' => $error, 'error_description' => $error_description]]);