3 namespace Friendica\Module\Api;
5 use Friendica\App\Arguments;
6 use Friendica\App\BaseURL;
7 use Friendica\Core\L10n;
8 use Friendica\Util\Arrays;
9 use Friendica\Util\DateTimeFormat;
10 use Friendica\Util\HTTPInputData;
11 use Friendica\Util\XML;
12 use Psr\Log\LoggerInterface;
13 use Friendica\Factory\Api\Twitter\User as TwitterUser;
16 * This class is used to format and return API responses
24 /** @var LoggerInterface */
29 * @param Arguments $args
30 * @param LoggerInterface $logger
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 * Sets header directly
43 * mainly used to override it for tests
45 * @param string $header
47 protected function setHeader(string $header)
53 * Prints output directly to the caller
54 * mainly used to override it for tests
56 * @param string $output
58 protected function printOutput(string $output)
65 * Creates the XML from a JSON style array
67 * @param array $data JSON style array
68 * @param string $root_element Name of the root element
70 * @return string The XML data
72 public function createXML(array $data, string $root_element): string
74 $childname = key($data);
75 $data2 = array_pop($data);
78 '' => 'http://api.twitter.com',
79 'statusnet' => 'http://status.net/schema/api/1/',
80 'friendica' => 'http://friendi.ca/schema/api/1/',
81 'georss' => 'http://www.georss.org/georss'
84 /// @todo Auto detection of needed namespaces
85 if (in_array($root_element, ['ok', 'hash', 'config', 'version', 'ids', 'notes', 'photos'])) {
89 if (is_array($data2)) {
91 Arrays::walkRecursive($data2, ['Friendica\Module\Api\ApiResponse', 'reformatXML']);
97 foreach ($data2 as $item) {
98 $data4[$i++ . ':' . $childname] = $item;
105 $data3 = [$root_element => $data2];
107 return XML::fromArray($data3, $xml, false, $namespaces);
111 * Set values for RSS template
113 * @param array $arr Array to be passed to template
114 * @param int $cid Contact ID of template
117 private function addRSSValues(array $arr, int $cid)
123 $user_info = $this->twitterUser->createFromContactId($cid)->toArray();
125 $arr['$user'] = $user_info;
127 'alternate' => $user_info['url'],
128 'self' => $this->baseurl . '/' . $this->args->getQueryString(),
129 'base' => $this->baseurl,
130 'updated' => DateTimeFormat::utc(null, DateTimeFormat::API),
131 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
132 'language' => $user_info['lang'],
133 'logo' => $this->baseurl . '/images/friendica-32.png',
140 * Formats the data according to the data type
142 * @param string $root_element Name of the root element
143 * @param string $type Return type (atom, rss, xml, json)
144 * @param array $data JSON style array
145 * @param int $cid ID of the contact for RSS
147 * @return array|string (string|array) XML data or JSON data
149 public function formatData(string $root_element, string $type, array $data, int $cid = 0)
153 $data = $this->addRSSValues($data, $cid);
156 return $this->createXML($data, $root_element);
164 * Callback function to transform the array in an array that can be transformed in a XML file
166 * @param mixed $item Array item value
167 * @param string $key Array key
171 public static function reformatXML(&$item, string &$key): bool
173 if (is_bool($item)) {
174 $item = ($item ? 'true' : 'false');
177 if (substr($key, 0, 10) == 'statusnet_') {
178 $key = 'statusnet:' . substr($key, 10);
179 } elseif (substr($key, 0, 10) == 'friendica_') {
180 $key = 'friendica:' . substr($key, 10);
186 * Exit with error code
189 * @param string $description
190 * @param string $message
191 * @param string|null $format
195 public function error(int $code, string $description, string $message, string $format = null)
198 'error' => $message ?: $description,
199 'code' => $code . ' ' . $description,
200 'request' => $this->args->getQueryString()
203 $this->setHeader(($_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1') . ' ' . $code . ' ' . $description);
205 $this->exit('status', ['status' => $error], $format);
209 * Outputs formatted data according to the data type and then exits the execution.
211 * @param string $root_element
212 * @param array $data An array with a single element containing the returned result
213 * @param string|null $format Output format (xml, json, rss, atom)
217 public function exit(string $root_element, array $data, string $format = null)
219 $format = $format ?? 'json';
221 $return = $this->formatData($root_element, $format, $data);
225 $this->setHeader('Content-Type: text/xml');
228 $this->setHeader('Content-Type: application/json');
229 if (!empty($return)) {
230 $json = json_encode(end($return));
231 if (!empty($_GET['callback'])) {
232 $json = $_GET['callback'] . '(' . $json . ')';
238 $this->setHeader('Content-Type: application/rss+xml');
241 $this->setHeader('Content-Type: application/atom+xml');
245 $this->printOutput($return);
249 * Quit execution with the message that the endpoint isn't implemented
251 * @param string $method
256 public function unsupported(string $method = 'all')
258 $path = $this->args->getQueryString();
259 $this->logger->info('Unimplemented API call',
263 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
264 'request' => HTTPInputData::process()
266 $error = $this->l10n->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
267 $error_description = $this->l10n->t('The API endpoint is currently not implemented but might be in the future.');
269 $this->exit('error', ['error' => ['error' => $error, 'error_description' => $error_description]]);