]> git.mxchange.org Git - friendica.git/blob - src/Module/BaseApi.php
Merge pull request #10209 from MrPetovan/bug/10205-frio-link-preview-accents
[friendica.git] / src / Module / BaseApi.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Module;
23
24 use Friendica\BaseModule;
25 use Friendica\Core\Logger;
26 use Friendica\Core\System;
27 use Friendica\DI;
28 use Friendica\Network\HTTPException;
29
30 require_once __DIR__ . '/../../include/api.php';
31
32 class BaseApi extends BaseModule
33 {
34         /**
35          * @var string json|xml|rss|atom
36          */
37         protected static $format = 'json';
38         /**
39          * @var bool|int
40          */
41         protected static $current_user_id;
42
43         public static function init(array $parameters = [])
44         {
45                 $arguments = DI::args();
46
47                 if (substr($arguments->getCommand(), -4) === '.xml') {
48                         self::$format = 'xml';
49                 }
50                 if (substr($arguments->getCommand(), -4) === '.rss') {
51                         self::$format = 'rss';
52                 }
53                 if (substr($arguments->getCommand(), -4) === '.atom') {
54                         self::$format = 'atom';
55                 }
56         }
57
58         public static function delete(array $parameters = [])
59         {
60                 if (!api_user()) {
61                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
62                 }
63
64                 $a = DI::app();
65
66                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
67                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
68                 }
69         }
70
71         public static function patch(array $parameters = [])
72         {
73                 if (!api_user()) {
74                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
75                 }
76
77                 $a = DI::app();
78
79                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
80                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
81                 }
82         }
83
84         public static function post(array $parameters = [])
85         {
86                 if (!api_user()) {
87                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
88                 }
89
90                 $a = DI::app();
91
92                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
93                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
94                 }
95         }
96
97         public static function put(array $parameters = [])
98         {
99                 if (!api_user()) {
100                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
101                 }
102
103                 $a = DI::app();
104
105                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
106                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
107                 }
108         }
109
110         public static function unsupported(string $method = 'all')
111         {
112                 $path = DI::args()->getQueryString();
113                 Logger::info('Unimplemented API call', ['method' => $method, 'path' => $path, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
114                 $error = DI::l10n()->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
115                 $error_description = DI::l10n()->t('The API endpoint is currently not implemented but might be in the future.');;
116                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
117                 System::jsonError(501, $errorobj->toArray());
118         }
119
120         /**
121          * Log in user via OAuth1 or Simple HTTP Auth.
122          *
123          * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
124          *
125          * @return bool Was a user authenticated?
126          * @throws HTTPException\ForbiddenException
127          * @throws HTTPException\UnauthorizedException
128          * @throws HTTPException\InternalServerErrorException
129          * @hook  'authenticate'
130          *               array $addon_auth
131          *               'username' => username from login form
132          *               'password' => password from login form
133          *               'authenticated' => return status,
134          *               'user_record' => return authenticated user record
135          */
136         protected static function login()
137         {
138                 api_login(DI::app());
139
140                 self::$current_user_id = api_user();
141
142                 return (bool)self::$current_user_id;
143         }
144
145         /**
146          * Get current user id, returns 0 if not logged in
147          *
148          * @return int User ID
149          */
150         protected static function getCurrentUserID()
151         {
152                 if (is_null(self::$current_user_id)) {
153                         api_login(DI::app(), false);
154
155                         self::$current_user_id = api_user();
156                 }
157
158                 return (int)self::$current_user_id;
159         }
160
161         /**
162          * Get user info array.
163          *
164          * @param int|string $contact_id Contact ID or URL
165          * @return array|bool
166          * @throws HTTPException\BadRequestException
167          * @throws HTTPException\InternalServerErrorException
168          * @throws HTTPException\UnauthorizedException
169          * @throws \ImagickException
170          */
171         protected static function getUser($contact_id = null)
172         {
173                 return api_get_user(DI::app(), $contact_id);
174         }
175
176         /**
177          * Formats the data according to the data type
178          *
179          * @param string $root_element
180          * @param array $data An array with a single element containing the returned result
181          * @return false|string
182          */
183         protected static function format(string $root_element, array $data)
184         {
185                 $return = api_format_data($root_element, self::$format, $data);
186
187                 switch (self::$format) {
188                         case "xml":
189                                 header("Content-Type: text/xml");
190                                 break;
191                         case "json":
192                                 header("Content-Type: application/json");
193                                 if (!empty($return)) {
194                                         $json = json_encode(end($return));
195                                         if (!empty($_GET['callback'])) {
196                                                 $json = $_GET['callback'] . "(" . $json . ")";
197                                         }
198                                         $return = $json;
199                                 }
200                                 break;
201                         case "rss":
202                                 header("Content-Type: application/rss+xml");
203                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
204                                 break;
205                         case "atom":
206                                 header("Content-Type: application/atom+xml");
207                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
208                                 break;
209                 }
210                 
211                 return $return;
212         }
213
214         /**
215          * Creates the XML from a JSON style array
216          *
217          * @param $data
218          * @param $root_element
219          * @return string
220          */
221         protected static function createXml($data, $root_element)
222         {
223                 return api_create_xml($data, $root_element);
224         }
225 }