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\XML;
12 use Psr\Log\LoggerInterface;
13 use Friendica\Factory\Api\Twitter\User as TwitterUser;
16 * This class is used to format and create API responses
18 class ApiResponse extends Response
24 /** @var LoggerInterface */
28 /** @var TwitterUser */
29 protected $twitterUser;
31 public function __construct(L10n $l10n, Arguments $args, LoggerInterface $logger, BaseURL $baseUrl, TwitterUser $twitterUser)
35 $this->logger = $logger;
36 $this->baseUrl = $baseUrl;
37 $this->twitterUser = $twitterUser;
41 * Creates the XML from a JSON style array
43 * @param array $data JSON style array
44 * @param string $root_element Name of the root element
46 * @return string The XML data
48 public function createXML(array $data, string $root_element): string
50 $childname = key($data);
51 $data2 = array_pop($data);
54 '' => 'http://api.twitter.com',
55 'statusnet' => 'http://status.net/schema/api/1/',
56 'friendica' => 'http://friendi.ca/schema/api/1/',
57 'georss' => 'http://www.georss.org/georss'
60 /// @todo Auto detection of needed namespaces
61 if (in_array($root_element, ['ok', 'hash', 'config', 'version', 'ids', 'notes', 'photos'])) {
65 if (is_array($data2)) {
67 Arrays::walkRecursive($data2, ['Friendica\Module\Api\ApiResponse', 'reformatXML']);
73 foreach ($data2 as $item) {
74 $data4[$i++ . ':' . $childname] = $item;
81 $data3 = [$root_element => $data2];
83 return XML::fromArray($data3, $xml, false, $namespaces);
87 * Set values for RSS template
89 * @param array $arr Array to be passed to template
90 * @param int $cid Contact ID of template
93 private function addRSSValues(array $arr, int $cid)
99 $user_info = $this->twitterUser->createFromContactId($cid)->toArray();
101 $arr['$user'] = $user_info;
103 'alternate' => $user_info['url'],
104 'self' => $this->baseUrl . '/' . $this->args->getQueryString(),
105 'base' => $this->baseUrl,
106 'updated' => DateTimeFormat::utc(null, DateTimeFormat::API),
107 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
108 'language' => $user_info['lang'],
109 'logo' => $this->baseUrl . '/images/friendica-32.png',
116 * Formats the data according to the data type
118 * @param string $root_element Name of the root element
119 * @param string $type Return type (atom, rss, xml, json)
120 * @param array $data JSON style array
121 * @param int $cid ID of the contact for RSS
123 * @return array|string (string|array) XML data or JSON data
125 public function formatData(string $root_element, string $type, array $data, int $cid = 0)
129 $data = $this->addRSSValues($data, $cid);
132 return $this->createXML($data, $root_element);
140 * Callback function to transform the array in an array that can be transformed in a XML file
142 * @param mixed $item Array item value
143 * @param string $key Array key
147 public static function reformatXML(&$item, string &$key): bool
149 if (is_bool($item)) {
150 $item = ($item ? 'true' : 'false');
153 if (substr($key, 0, 10) == 'statusnet_') {
154 $key = 'statusnet:' . substr($key, 10);
155 } elseif (substr($key, 0, 10) == 'friendica_') {
156 $key = 'friendica:' . substr($key, 10);
162 * Exit with error code
165 * @param string $description
166 * @param string $message
167 * @param string|null $format
171 public function error(int $code, string $description, string $message, string $format = null)
174 'error' => $message ?: $description,
175 'code' => $code . ' ' . $description,
176 'request' => $this->args->getQueryString()
179 $this->setHeader(($_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1') . ' ' . $code . ' ' . $description);
181 $this->exit('status', ['status' => $error], $format);
185 * Outputs formatted data according to the data type and then exits the execution.
187 * @param string $root_element
188 * @param array $data An array with a single element containing the returned result
189 * @param string|null $format Output format (xml, json, rss, atom)
193 public function exit(string $root_element, array $data, string $format = null, int $cid = 0)
195 $format = $format ?? 'json';
197 $return = $this->formatData($root_element, $format, $data, $cid);
201 $this->setType(static::TYPE_XML);
204 $this->setType(static::TYPE_JSON);
205 if (!empty($return)) {
206 $json = json_encode(end($return));
207 if (!empty($_GET['callback'])) {
208 $json = $_GET['callback'] . '(' . $json . ')';
214 $this->setType(static::TYPE_RSS);
217 $this->setType(static::TYPE_ATOM);
221 $this->addContent($return);
225 * Quit execution with the message that the endpoint isn't implemented
227 * @param string $method
228 * @param array $request (optional) The request content of the current call for later analysis
233 public function unsupported(string $method = 'all', array $request = [])
235 $path = $this->args->getQueryString();
236 $this->logger->info('Unimplemented API call',
240 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
241 'request' => $request,
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]]);