]> git.mxchange.org Git - friendica.git/blob - src/Module/Api/ApiResponse.php
Fixing Response
[friendica.git] / src / Module / Api / ApiResponse.php
1 <?php
2
3 namespace Friendica\Module\Api;
4
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;
15
16 /**
17  * This class is used to format and create API responses
18  */
19 class ApiResponse extends Response
20 {
21         /** @var L10n */
22         protected $l10n;
23         /** @var Arguments */
24         protected $args;
25         /** @var LoggerInterface */
26         protected $logger;
27         /** @var BaseURL */
28         protected $baseUrl;
29         /** @var TwitterUser */
30         protected $twitterUser;
31
32         public function __construct(L10n $l10n, Arguments $args, LoggerInterface $logger, BaseURL $baseUrl, TwitterUser $twitterUser)
33         {
34                 $this->l10n        = $l10n;
35                 $this->args        = $args;
36                 $this->logger      = $logger;
37                 $this->baseUrl     = $baseUrl;
38                 $this->twitterUser = $twitterUser;
39         }
40
41         /**
42          * Creates the XML from a JSON style array
43          *
44          * @param array  $data         JSON style array
45          * @param string $root_element Name of the root element
46          *
47          * @return string The XML data
48          */
49         public function createXML(array $data, string $root_element): string
50         {
51                 $childname = key($data);
52                 $data2     = array_pop($data);
53
54                 $namespaces = [
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'
59                 ];
60
61                 /// @todo Auto detection of needed namespaces
62                 if (in_array($root_element, ['ok', 'hash', 'config', 'version', 'ids', 'notes', 'photos'])) {
63                         $namespaces = [];
64                 }
65
66                 if (is_array($data2)) {
67                         $key = key($data2);
68                         Arrays::walkRecursive($data2, ['Friendica\Module\Api\ApiResponse', 'reformatXML']);
69
70                         if ($key == '0') {
71                                 $data4 = [];
72                                 $i     = 1;
73
74                                 foreach ($data2 as $item) {
75                                         $data4[$i++ . ':' . $childname] = $item;
76                                 }
77
78                                 $data2 = $data4;
79                         }
80                 }
81
82                 $data3 = [$root_element => $data2];
83
84                 return XML::fromArray($data3, $xml, false, $namespaces);
85         }
86
87         /**
88          * Set values for RSS template
89          *
90          * @param array $arr Array to be passed to template
91          * @param int   $cid Contact ID of template
92          * @return array
93          */
94         private function addRSSValues(array $arr, int $cid)
95         {
96                 if (empty($cid)) {
97                         return $arr;
98                 }
99
100                 $user_info = $this->twitterUser->createFromContactId($cid)->toArray();
101
102                 $arr['$user'] = $user_info;
103                 $arr['$rss'] = [
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',
111                 ];
112
113                 return $arr;
114         }
115
116         /**
117          * Formats the data according to the data type
118          *
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
123          *
124          * @return array|string (string|array) XML data or JSON data
125          */
126         public function formatData(string $root_element, string $type, array $data, int $cid = 0)
127         {
128                 switch ($type) {
129                         case 'rss':
130                                 $data = $this->addRSSValues($data, $cid);
131                         case 'atom':
132                         case 'xml':
133                                 return $this->createXML($data, $root_element);
134                         case 'json':
135                         default:
136                                 return $data;
137                 }
138         }
139
140         /**
141          * Callback function to transform the array in an array that can be transformed in a XML file
142          *
143          * @param mixed  $item Array item value
144          * @param string $key  Array key
145          *
146          * @return boolean
147          */
148         public static function reformatXML(&$item, string &$key): bool
149         {
150                 if (is_bool($item)) {
151                         $item = ($item ? 'true' : 'false');
152                 }
153
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);
158                 }
159                 return true;
160         }
161
162         /**
163          * Exit with error code
164          *
165          * @param int         $code
166          * @param string      $description
167          * @param string      $message
168          * @param string|null $format
169          *
170          * @return void
171          */
172         public function error(int $code, string $description, string $message, string $format = null)
173         {
174                 $error = [
175                         'error'   => $message ?: $description,
176                         'code'    => $code . ' ' . $description,
177                         'request' => $this->args->getQueryString()
178                 ];
179
180                 $this->setHeader(($_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1') . ' ' . $code . ' ' . $description);
181
182                 $this->exit('status', ['status' => $error], $format);
183         }
184
185         /**
186          * Outputs formatted data according to the data type and then exits the execution.
187          *
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)
191          *
192          * @return void
193          */
194         public function exit(string $root_element, array $data, string $format = null, int $cid = 0)
195         {
196                 $format = $format ?? 'json';
197
198                 $return = $this->formatData($root_element, $format, $data, $cid);
199
200                 switch ($format) {
201                         case 'xml':
202                                 $this->setType(static::TYPE_XML);
203                                 break;
204                         case 'json':
205                                 $this->setType(static::TYPE_JSON);
206                                 if (!empty($return)) {
207                                         $json = json_encode(end($return));
208                                         if (!empty($_GET['callback'])) {
209                                                 $json = $_GET['callback'] . '(' . $json . ')';
210                                         }
211                                         $return = $json;
212                                 }
213                                 break;
214                         case 'rss':
215                                 $this->setType(static::TYPE_RSS);
216                                 break;
217                         case 'atom':
218                                 $this->setType(static::TYPE_ATOM);
219                                 break;
220                 }
221
222                 $this->addContent($return);
223         }
224
225         /**
226          * Quit execution with the message that the endpoint isn't implemented
227          *
228          * @param string $method
229          *
230          * @return void
231          * @throws \Exception
232          */
233         public function unsupported(string $method = 'all')
234         {
235                 $path = $this->args->getQueryString();
236                 $this->logger->info('Unimplemented API call',
237                         [
238                                 'method'  => $method,
239                                 'path'    => $path,
240                                 'agent'   => $_SERVER['HTTP_USER_AGENT'] ?? '',
241                                 'request' => HTTPInputData::process()
242                         ]);
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.');
245
246                 $this->exit('error', ['error' => ['error' => $error, 'error_description' => $error_description]]);
247         }
248 }