]> git.mxchange.org Git - friendica.git/blob - include/api.php
API: We now use the "notification-type" field for mentions
[friendica.git] / include / api.php
1 <?php
2 /**
3  * Friendica implementation of statusnet/twitter API
4  *
5  * @file include/api.php
6  * @todo Automatically detect if incoming data is HTML or BBCode
7  */
8
9 use Friendica\App;
10 use Friendica\Content\ContactSelector;
11 use Friendica\Content\Feature;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Core\Config;
15 use Friendica\Core\Hook;
16 use Friendica\Core\L10n;
17 use Friendica\Core\Logger;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\Protocol;
20 use Friendica\Core\Session;
21 use Friendica\Core\System;
22 use Friendica\Core\Worker;
23 use Friendica\Database\DBA;
24 use Friendica\DI;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Group;
27 use Friendica\Model\Item;
28 use Friendica\Model\Mail;
29 use Friendica\Model\Photo;
30 use Friendica\Model\Profile;
31 use Friendica\Model\User;
32 use Friendica\Model\UserItem;
33 use Friendica\Network\FKOAuth1;
34 use Friendica\Network\HTTPException;
35 use Friendica\Network\HTTPException\BadRequestException;
36 use Friendica\Network\HTTPException\ExpectationFailedException;
37 use Friendica\Network\HTTPException\ForbiddenException;
38 use Friendica\Network\HTTPException\InternalServerErrorException;
39 use Friendica\Network\HTTPException\MethodNotAllowedException;
40 use Friendica\Network\HTTPException\NotFoundException;
41 use Friendica\Network\HTTPException\NotImplementedException;
42 use Friendica\Network\HTTPException\TooManyRequestsException;
43 use Friendica\Network\HTTPException\UnauthorizedException;
44 use Friendica\Object\Image;
45 use Friendica\Protocol\Activity;
46 use Friendica\Protocol\Diaspora;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Images;
49 use Friendica\Util\Network;
50 use Friendica\Util\Proxy as ProxyUtils;
51 use Friendica\Util\Strings;
52 use Friendica\Util\XML;
53
54 require_once __DIR__ . '/../mod/share.php';
55 require_once __DIR__ . '/../mod/item.php';
56 require_once __DIR__ . '/../mod/wall_upload.php';
57
58 define('API_METHOD_ANY', '*');
59 define('API_METHOD_GET', 'GET');
60 define('API_METHOD_POST', 'POST,PUT');
61 define('API_METHOD_DELETE', 'POST,DELETE');
62
63 define('API_LOG_PREFIX', 'API {action} - ');
64
65 $API = [];
66 $called_api = [];
67
68 /**
69  * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
70  * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
71  * into a page, and visitors will post something without noticing it).
72  *
73  * @brief Auth API user
74  */
75 function api_user()
76 {
77         if (!empty($_SESSION['allow_api'])) {
78                 return local_user();
79         }
80
81         return false;
82 }
83
84 /**
85  * Clients can send 'source' parameter to be show in post metadata
86  * as "sent via <source>".
87  * Some clients doesn't send a source param, we support ones we know
88  * (only Twidere, atm)
89  *
90  * @brief Get source name from API client
91  *
92  * @return string
93  *        Client source name, default to "api" if unset/unknown
94  * @throws Exception
95  */
96 function api_source()
97 {
98         if (requestdata('source')) {
99                 return requestdata('source');
100         }
101
102         // Support for known clients that doesn't send a source name
103         if (!empty($_SERVER['HTTP_USER_AGENT'])) {
104                 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
105                         return "Twidere";
106                 }
107
108                 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
109         } else {
110                 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
111         }
112
113         return "api";
114 }
115
116 /**
117  * @brief Format date for API
118  *
119  * @param string $str Source date, as UTC
120  * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
121  * @throws Exception
122  */
123 function api_date($str)
124 {
125         // Wed May 23 06:01:13 +0000 2007
126         return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
127 }
128
129 /**
130  * Register a function to be the endpoint for defined API path.
131  *
132  * @brief Register API endpoint
133  *
134  * @param string $path   API URL path, relative to DI::baseUrl()
135  * @param string $func   Function name to call on path request
136  * @param bool   $auth   API need logged user
137  * @param string $method HTTP method reqiured to call this endpoint.
138  *                       One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
139  *                       Default to API_METHOD_ANY
140  */
141 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
142 {
143         global $API;
144
145         $API[$path] = [
146                 'func'   => $func,
147                 'auth'   => $auth,
148                 'method' => $method,
149         ];
150
151         // Workaround for hotot
152         $path = str_replace("api/", "api/1.1/", $path);
153
154         $API[$path] = [
155                 'func'   => $func,
156                 'auth'   => $auth,
157                 'method' => $method,
158         ];
159 }
160
161 /**
162  * Log in user via OAuth1 or Simple HTTP Auth.
163  * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
164  *
165  * @brief Login API user
166  *
167  * @param App $a App
168  * @throws ForbiddenException
169  * @throws InternalServerErrorException
170  * @throws UnauthorizedException
171  * @hook  'authenticate'
172  *               array $addon_auth
173  *               'username' => username from login form
174  *               'password' => password from login form
175  *               'authenticated' => return status,
176  *               'user_record' => return authenticated user record
177  */
178 function api_login(App $a)
179 {
180         $oauth1 = new FKOAuth1();
181         // login with oauth
182         try {
183                 $request = OAuthRequest::from_request();
184                 list($consumer, $token) = $oauth1->verify_request($request);
185                 if (!is_null($token)) {
186                         $oauth1->loginUser($token->uid);
187                         Session::set('allow_api', true);
188                         return;
189                 }
190                 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
191                 var_dump($consumer, $token);
192                 die();
193         } catch (Exception $e) {
194                 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
195         }
196
197         // workaround for HTTP-auth in CGI mode
198         if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
199                 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
200                 if (strlen($userpass)) {
201                         list($name, $password) = explode(':', $userpass);
202                         $_SERVER['PHP_AUTH_USER'] = $name;
203                         $_SERVER['PHP_AUTH_PW'] = $password;
204                 }
205         }
206
207         if (empty($_SERVER['PHP_AUTH_USER'])) {
208                 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
209                 header('WWW-Authenticate: Basic realm="Friendica"');
210                 throw new UnauthorizedException("This API requires login");
211         }
212
213         $user = $_SERVER['PHP_AUTH_USER'] ?? '';
214         $password = $_SERVER['PHP_AUTH_PW'] ?? '';
215
216         // allow "user@server" login (but ignore 'server' part)
217         $at = strstr($user, "@", true);
218         if ($at) {
219                 $user = $at;
220         }
221
222         // next code from mod/auth.php. needs better solution
223         $record = null;
224
225         $addon_auth = [
226                 'username' => trim($user),
227                 'password' => trim($password),
228                 'authenticated' => 0,
229                 'user_record' => null,
230         ];
231
232         /*
233         * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
234         * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
235         * and later addons should not interfere with an earlier one that succeeded.
236         */
237         Hook::callAll('authenticate', $addon_auth);
238
239         if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
240                 $record = $addon_auth['user_record'];
241         } else {
242                 $user_id = User::authenticate(trim($user), trim($password), true);
243                 if ($user_id !== false) {
244                         $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
245                 }
246         }
247
248         if (!DBA::isResult($record)) {
249                 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
250                 header('WWW-Authenticate: Basic realm="Friendica"');
251                 //header('HTTP/1.0 401 Unauthorized');
252                 //die('This api requires login');
253                 throw new UnauthorizedException("This API requires login");
254         }
255
256         DI::auth()->setForUser($a, $record);
257
258         $_SESSION["allow_api"] = true;
259
260         Hook::callAll('logged_in', $a->user);
261 }
262
263 /**
264  * API endpoints can define which HTTP method to accept when called.
265  * This function check the current HTTP method agains endpoint
266  * registered method.
267  *
268  * @brief Check HTTP method of called API
269  *
270  * @param string $method Required methods, uppercase, separated by comma
271  * @return bool
272  */
273 function api_check_method($method)
274 {
275         if ($method == "*") {
276                 return true;
277         }
278         return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
279 }
280
281 /**
282  * Authenticate user, call registered API function, set HTTP headers
283  *
284  * @brief Main API entry point
285  *
286  * @param App $a App
287  * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
288  * @return string|array API call result
289  * @throws Exception
290  */
291 function api_call(App $a, App\Arguments $args = null)
292 {
293         global $API, $called_api;
294
295         if ($args == null) {
296                 $args = DI::args();
297         }
298
299         $type = "json";
300         if (strpos($args->getQueryString(), ".xml") > 0) {
301                 $type = "xml";
302         }
303         if (strpos($args->getQueryString(), ".json") > 0) {
304                 $type = "json";
305         }
306         if (strpos($args->getQueryString(), ".rss") > 0) {
307                 $type = "rss";
308         }
309         if (strpos($args->getQueryString(), ".atom") > 0) {
310                 $type = "atom";
311         }
312
313         try {
314                 foreach ($API as $p => $info) {
315                         if (strpos($args->getQueryString(), $p) === 0) {
316                                 if (!api_check_method($info['method'])) {
317                                         throw new MethodNotAllowedException();
318                                 }
319
320                                 $called_api = explode("/", $p);
321                                 //unset($_SERVER['PHP_AUTH_USER']);
322
323                                 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
324                                 if (!empty($info['auth']) && api_user() === false) {
325                                         api_login($a);
326                                 }
327
328                                 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
329                                 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
330
331                                 $stamp =  microtime(true);
332                                 $return = call_user_func($info['func'], $type);
333                                 $duration = floatval(microtime(true) - $stamp);
334
335                                 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
336
337                                 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
338
339                                 if (false === $return) {
340                                         /*
341                                                 * api function returned false withour throw an
342                                                 * exception. This should not happend, throw a 500
343                                                 */
344                                         throw new InternalServerErrorException();
345                                 }
346
347                                 switch ($type) {
348                                         case "xml":
349                                                 header("Content-Type: text/xml");
350                                                 break;
351                                         case "json":
352                                                 header("Content-Type: application/json");
353                                                 if (!empty($return)) {
354                                                         $json = json_encode(end($return));
355                                                         if (!empty($_GET['callback'])) {
356                                                                 $json = $_GET['callback'] . "(" . $json . ")";
357                                                         }
358                                                         $return = $json;
359                                                 }
360                                                 break;
361                                         case "rss":
362                                                 header("Content-Type: application/rss+xml");
363                                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
364                                                 break;
365                                         case "atom":
366                                                 header("Content-Type: application/atom+xml");
367                                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
368                                                 break;
369                                 }
370                                 return $return;
371                         }
372                 }
373
374                 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
375                 throw new NotImplementedException();
376         } catch (HTTPException $e) {
377                 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
378                 return api_error($type, $e, $args);
379         }
380 }
381
382 /**
383  * @brief Format API error string
384  *
385  * @param string $type Return type (xml, json, rss, as)
386  * @param object $e    HTTPException Error object
387  * @param App\Arguments $args The App arguments
388  * @return string|array error message formatted as $type
389  */
390 function api_error($type, $e, App\Arguments $args)
391 {
392         $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
393         /// @TODO:  https://dev.twitter.com/overview/api/response-codes
394
395         $error = ["error" => $error,
396                         "code" => $e->getCode() . " " . $e->httpdesc,
397                         "request" => $args->getQueryString()];
398
399         $return = api_format_data('status', $type, ['status' => $error]);
400
401         switch ($type) {
402                 case "xml":
403                         header("Content-Type: text/xml");
404                         break;
405                 case "json":
406                         header("Content-Type: application/json");
407                         $return = json_encode($return);
408                         break;
409                 case "rss":
410                         header("Content-Type: application/rss+xml");
411                         break;
412                 case "atom":
413                         header("Content-Type: application/atom+xml");
414                         break;
415         }
416
417         return $return;
418 }
419
420 /**
421  * @brief Set values for RSS template
422  *
423  * @param App   $a
424  * @param array $arr       Array to be passed to template
425  * @param array $user_info User info
426  * @return array
427  * @throws BadRequestException
428  * @throws ImagickException
429  * @throws InternalServerErrorException
430  * @throws UnauthorizedException
431  * @todo  find proper type-hints
432  */
433 function api_rss_extra(App $a, $arr, $user_info)
434 {
435         if (is_null($user_info)) {
436                 $user_info = api_get_user($a);
437         }
438
439         $arr['$user'] = $user_info;
440         $arr['$rss'] = [
441                 'alternate'    => $user_info['url'],
442                 'self'         => DI::baseUrl() . "/" . DI::args()->getQueryString(),
443                 'base'         => DI::baseUrl(),
444                 'updated'      => api_date(null),
445                 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
446                 'language'     => $user_info['lang'],
447                 'logo'         => DI::baseUrl() . "/images/friendica-32.png",
448         ];
449
450         return $arr;
451 }
452
453
454 /**
455  * @brief Unique contact to contact url.
456  *
457  * @param int $id Contact id
458  * @return bool|string
459  *                Contact url or False if contact id is unknown
460  * @throws Exception
461  */
462 function api_unique_id_to_nurl($id)
463 {
464         $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
465
466         if (DBA::isResult($r)) {
467                 return $r["nurl"];
468         } else {
469                 return false;
470         }
471 }
472
473 /**
474  * @brief Get user info array.
475  *
476  * @param App        $a          App
477  * @param int|string $contact_id Contact ID or URL
478  * @return array|bool
479  * @throws BadRequestException
480  * @throws ImagickException
481  * @throws InternalServerErrorException
482  * @throws UnauthorizedException
483  */
484 function api_get_user(App $a, $contact_id = null)
485 {
486         global $called_api;
487
488         $user = null;
489         $extra_query = "";
490         $url = "";
491
492         Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
493
494         // Searching for contact URL
495         if (!is_null($contact_id) && (intval($contact_id) == 0)) {
496                 $user = DBA::escape(Strings::normaliseLink($contact_id));
497                 $url = $user;
498                 $extra_query = "AND `contact`.`nurl` = '%s' ";
499                 if (api_user() !== false) {
500                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
501                 }
502         }
503
504         // Searching for contact id with uid = 0
505         if (!is_null($contact_id) && (intval($contact_id) != 0)) {
506                 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
507
508                 if ($user == "") {
509                         throw new BadRequestException("User ID ".$contact_id." not found.");
510                 }
511
512                 $url = $user;
513                 $extra_query = "AND `contact`.`nurl` = '%s' ";
514                 if (api_user() !== false) {
515                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
516                 }
517         }
518
519         if (is_null($user) && !empty($_GET['user_id'])) {
520                 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
521
522                 if ($user == "") {
523                         throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
524                 }
525
526                 $url = $user;
527                 $extra_query = "AND `contact`.`nurl` = '%s' ";
528                 if (api_user() !== false) {
529                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
530                 }
531         }
532         if (is_null($user) && !empty($_GET['screen_name'])) {
533                 $user = DBA::escape($_GET['screen_name']);
534                 $extra_query = "AND `contact`.`nick` = '%s' ";
535                 if (api_user() !== false) {
536                         $extra_query .= "AND `contact`.`uid`=".intval(api_user());
537                 }
538         }
539
540         if (is_null($user) && !empty($_GET['profileurl'])) {
541                 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
542                 $extra_query = "AND `contact`.`nurl` = '%s' ";
543                 if (api_user() !== false) {
544                         $extra_query .= "AND `contact`.`uid`=".intval(api_user());
545                 }
546         }
547
548         // $called_api is the API path exploded on / and is expected to have at least 2 elements
549         if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
550                 $argid = count($called_api);
551                 if (!empty($a->argv[$argid])) {
552                         $data = explode(".", $a->argv[$argid]);
553                         if (count($data) > 1) {
554                                 list($user, $null) = $data;
555                         }
556                 }
557                 if (is_numeric($user)) {
558                         $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
559
560                         if ($user != "") {
561                                 $url = $user;
562                                 $extra_query = "AND `contact`.`nurl` = '%s' ";
563                                 if (api_user() !== false) {
564                                         $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
565                                 }
566                         }
567                 } else {
568                         $user = DBA::escape($user);
569                         $extra_query = "AND `contact`.`nick` = '%s' ";
570                         if (api_user() !== false) {
571                                 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
572                         }
573                 }
574         }
575
576         Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
577
578         if (!$user) {
579                 if (api_user() === false) {
580                         api_login($a);
581                         return false;
582                 } else {
583                         $user = $_SESSION['uid'];
584                         $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
585                 }
586         }
587
588         Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
589
590         // user info
591         $uinfo = q(
592                 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
593                         WHERE 1
594                 $extra_query",
595                 $user
596         );
597
598         // Selecting the id by priority, friendica first
599         if (is_array($uinfo)) {
600                 api_best_nickname($uinfo);
601         }
602
603         // if the contact wasn't found, fetch it from the contacts with uid = 0
604         if (!DBA::isResult($uinfo)) {
605                 if ($url == "") {
606                         throw new BadRequestException("User not found.");
607                 }
608
609                 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
610
611                 if (DBA::isResult($contact)) {
612                         $ret = [
613                                 'id' => $contact["id"],
614                                 'id_str' => (string) $contact["id"],
615                                 'name' => $contact["name"],
616                                 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
617                                 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
618                                 'description' => BBCode::toPlaintext($contact["about"]),
619                                 'profile_image_url' => $contact["micro"],
620                                 'profile_image_url_https' => $contact["micro"],
621                                 'profile_image_url_profile_size' => $contact["thumb"],
622                                 'profile_image_url_large' => $contact["photo"],
623                                 'url' => $contact["url"],
624                                 'protected' => false,
625                                 'followers_count' => 0,
626                                 'friends_count' => 0,
627                                 'listed_count' => 0,
628                                 'created_at' => api_date($contact["created"]),
629                                 'favourites_count' => 0,
630                                 'utc_offset' => 0,
631                                 'time_zone' => 'UTC',
632                                 'geo_enabled' => false,
633                                 'verified' => false,
634                                 'statuses_count' => 0,
635                                 'lang' => '',
636                                 'contributors_enabled' => false,
637                                 'is_translator' => false,
638                                 'is_translation_enabled' => false,
639                                 'following' => false,
640                                 'follow_request_sent' => false,
641                                 'statusnet_blocking' => false,
642                                 'notifications' => false,
643                                 'statusnet_profile_url' => $contact["url"],
644                                 'uid' => 0,
645                                 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
646                                 'pid' => Contact::getIdForURL($contact["url"], 0, true),
647                                 'self' => 0,
648                                 'network' => $contact["network"],
649                         ];
650
651                         return $ret;
652                 } else {
653                         throw new BadRequestException("User ".$url." not found.");
654                 }
655         }
656
657         if ($uinfo[0]['self']) {
658                 if ($uinfo[0]['network'] == "") {
659                         $uinfo[0]['network'] = Protocol::DFRN;
660                 }
661
662                 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
663                 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
664         }
665         $countitems = 0;
666         $countfriends = 0;
667         $countfollowers = 0;
668         $starred = 0;
669
670         $pcontact_id  = Contact::getIdForURL($uinfo[0]['url'], 0, true);
671
672         if (!empty($profile['about'])) {
673                 $description = $profile['about'];
674         } else {
675                 $description = $uinfo[0]["about"];
676         }
677
678         if (!empty($usr['default-location'])) {
679                 $location = $usr['default-location'];
680         } elseif (!empty($uinfo[0]["location"])) {
681                 $location = $uinfo[0]["location"];
682         } else {
683                 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
684         }
685
686         $ret = [
687                 'id' => intval($pcontact_id),
688                 'id_str' => (string) intval($pcontact_id),
689                 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
690                 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
691                 'location' => $location,
692                 'description' => BBCode::toPlaintext($description),
693                 'profile_image_url' => $uinfo[0]['micro'],
694                 'profile_image_url_https' => $uinfo[0]['micro'],
695                 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
696                 'profile_image_url_large' => $uinfo[0]["photo"],
697                 'url' => $uinfo[0]['url'],
698                 'protected' => false,
699                 'followers_count' => intval($countfollowers),
700                 'friends_count' => intval($countfriends),
701                 'listed_count' => 0,
702                 'created_at' => api_date($uinfo[0]['created']),
703                 'favourites_count' => intval($starred),
704                 'utc_offset' => "0",
705                 'time_zone' => 'UTC',
706                 'geo_enabled' => false,
707                 'verified' => true,
708                 'statuses_count' => intval($countitems),
709                 'lang' => '',
710                 'contributors_enabled' => false,
711                 'is_translator' => false,
712                 'is_translation_enabled' => false,
713                 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
714                 'follow_request_sent' => false,
715                 'statusnet_blocking' => false,
716                 'notifications' => false,
717                 /// @TODO old way?
718                 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
719                 'statusnet_profile_url' => $uinfo[0]['url'],
720                 'uid' => intval($uinfo[0]['uid']),
721                 'cid' => intval($uinfo[0]['cid']),
722                 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
723                 'self' => $uinfo[0]['self'],
724                 'network' => $uinfo[0]['network'],
725         ];
726
727         // If this is a local user and it uses Frio, we can get its color preferences.
728         if ($ret['self']) {
729                 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
730                 if ($theme_info['theme'] === 'frio') {
731                         $schema = PConfig::get($ret['uid'], 'frio', 'schema');
732
733                         if ($schema && ($schema != '---')) {
734                                 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
735                                         $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
736                                         require_once $schemefile;
737                                 }
738                         } else {
739                                 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
740                                 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
741                                 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
742                         }
743                         if (empty($nav_bg)) {
744                                 $nav_bg = "#708fa0";
745                         }
746                         if (empty($link_color)) {
747                                 $link_color = "#6fdbe8";
748                         }
749                         if (empty($bgcolor)) {
750                                 $bgcolor = "#ededed";
751                         }
752
753                         $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
754                         $ret['profile_link_color'] = str_replace('#', '', $link_color);
755                         $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
756                 }
757         }
758
759         return $ret;
760 }
761
762 /**
763  * @brief return api-formatted array for item's author and owner
764  *
765  * @param App   $a    App
766  * @param array $item item from db
767  * @return array(array:author, array:owner)
768  * @throws BadRequestException
769  * @throws ImagickException
770  * @throws InternalServerErrorException
771  * @throws UnauthorizedException
772  */
773 function api_item_get_user(App $a, $item)
774 {
775         $status_user = api_get_user($a, $item['author-id'] ?? null);
776
777         $author_user = $status_user;
778
779         $status_user["protected"] = $item['private'] ?? 0;
780
781         if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
782                 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
783         } else {
784                 $owner_user = $author_user;
785         }
786
787         return ([$status_user, $author_user, $owner_user]);
788 }
789
790 /**
791  * @brief walks recursively through an array with the possibility to change value and key
792  *
793  * @param array    $array    The array to walk through
794  * @param callable $callback The callback function
795  *
796  * @return array the transformed array
797  */
798 function api_walk_recursive(array &$array, callable $callback)
799 {
800         $new_array = [];
801
802         foreach ($array as $k => $v) {
803                 if (is_array($v)) {
804                         if ($callback($v, $k)) {
805                                 $new_array[$k] = api_walk_recursive($v, $callback);
806                         }
807                 } else {
808                         if ($callback($v, $k)) {
809                                 $new_array[$k] = $v;
810                         }
811                 }
812         }
813         $array = $new_array;
814
815         return $array;
816 }
817
818 /**
819  * @brief Callback function to transform the array in an array that can be transformed in a XML file
820  *
821  * @param mixed  $item Array item value
822  * @param string $key  Array key
823  *
824  * @return boolean Should the array item be deleted?
825  */
826 function api_reformat_xml(&$item, &$key)
827 {
828         if (is_bool($item)) {
829                 $item = ($item ? "true" : "false");
830         }
831
832         if (substr($key, 0, 10) == "statusnet_") {
833                 $key = "statusnet:".substr($key, 10);
834         } elseif (substr($key, 0, 10) == "friendica_") {
835                 $key = "friendica:".substr($key, 10);
836         }
837         /// @TODO old-lost code?
838         //else
839         //      $key = "default:".$key;
840
841         return true;
842 }
843
844 /**
845  * @brief Creates the XML from a JSON style array
846  *
847  * @param array  $data         JSON style array
848  * @param string $root_element Name of the root element
849  *
850  * @return string The XML data
851  */
852 function api_create_xml(array $data, $root_element)
853 {
854         $childname = key($data);
855         $data2 = array_pop($data);
856
857         $namespaces = ["" => "http://api.twitter.com",
858                                 "statusnet" => "http://status.net/schema/api/1/",
859                                 "friendica" => "http://friendi.ca/schema/api/1/",
860                                 "georss" => "http://www.georss.org/georss"];
861
862         /// @todo Auto detection of needed namespaces
863         if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
864                 $namespaces = [];
865         }
866
867         if (is_array($data2)) {
868                 $key = key($data2);
869                 api_walk_recursive($data2, "api_reformat_xml");
870
871                 if ($key == "0") {
872                         $data4 = [];
873                         $i = 1;
874
875                         foreach ($data2 as $item) {
876                                 $data4[$i++ . ":" . $childname] = $item;
877                         }
878
879                         $data2 = $data4;
880                 }
881         }
882
883         $data3 = [$root_element => $data2];
884
885         $ret = XML::fromArray($data3, $xml, false, $namespaces);
886         return $ret;
887 }
888
889 /**
890  * @brief Formats the data according to the data type
891  *
892  * @param string $root_element Name of the root element
893  * @param string $type         Return type (atom, rss, xml, json)
894  * @param array  $data         JSON style array
895  *
896  * @return array|string (string|array) XML data or JSON data
897  */
898 function api_format_data($root_element, $type, $data)
899 {
900         switch ($type) {
901                 case "atom":
902                 case "rss":
903                 case "xml":
904                         $ret = api_create_xml($data, $root_element);
905                         break;
906                 case "json":
907                 default:
908                         $ret = $data;
909                         break;
910         }
911         return $ret;
912 }
913
914 /**
915  * TWITTER API
916  */
917
918 /**
919  * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
920  * returns a 401 status code and an error message if not.
921  *
922  * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
923  *
924  * @param string $type Return type (atom, rss, xml, json)
925  * @return array|string
926  * @throws BadRequestException
927  * @throws ForbiddenException
928  * @throws ImagickException
929  * @throws InternalServerErrorException
930  * @throws UnauthorizedException
931  */
932 function api_account_verify_credentials($type)
933 {
934         $a = DI::app();
935
936         if (api_user() === false) {
937                 throw new ForbiddenException();
938         }
939
940         unset($_REQUEST["user_id"]);
941         unset($_GET["user_id"]);
942
943         unset($_REQUEST["screen_name"]);
944         unset($_GET["screen_name"]);
945
946         $skip_status = $_REQUEST['skip_status'] ?? false;
947
948         $user_info = api_get_user($a);
949
950         // "verified" isn't used here in the standard
951         unset($user_info["verified"]);
952
953         // - Adding last status
954         if (!$skip_status) {
955                 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
956                 if (!empty($item)) {
957                         $user_info['status'] = api_format_item($item, $type);
958                 }
959         }
960
961         // "uid" and "self" are only needed for some internal stuff, so remove it from here
962         unset($user_info["uid"]);
963         unset($user_info["self"]);
964
965         return api_format_data("user", $type, ['user' => $user_info]);
966 }
967
968 /// @TODO move to top of file or somewhere better
969 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
970
971 /**
972  * Get data from $_POST or $_GET
973  *
974  * @param string $k
975  * @return null
976  */
977 function requestdata($k)
978 {
979         if (!empty($_POST[$k])) {
980                 return $_POST[$k];
981         }
982         if (!empty($_GET[$k])) {
983                 return $_GET[$k];
984         }
985         return null;
986 }
987
988 /**
989  * Deprecated function to upload media.
990  *
991  * @param string $type Return type (atom, rss, xml, json)
992  *
993  * @return array|string
994  * @throws BadRequestException
995  * @throws ForbiddenException
996  * @throws ImagickException
997  * @throws InternalServerErrorException
998  * @throws UnauthorizedException
999  */
1000 function api_statuses_mediap($type)
1001 {
1002         $a = DI::app();
1003
1004         if (api_user() === false) {
1005                 Logger::log('api_statuses_update: no user');
1006                 throw new ForbiddenException();
1007         }
1008         $user_info = api_get_user($a);
1009
1010         $_REQUEST['profile_uid'] = api_user();
1011         $_REQUEST['api_source'] = true;
1012         $txt = requestdata('status');
1013         /// @TODO old-lost code?
1014         //$txt = urldecode(requestdata('status'));
1015
1016         if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1017                 $txt = HTML::toBBCodeVideo($txt);
1018                 $config = HTMLPurifier_Config::createDefault();
1019                 $config->set('Cache.DefinitionImpl', null);
1020                 $purifier = new HTMLPurifier($config);
1021                 $txt = $purifier->purify($txt);
1022         }
1023         $txt = HTML::toBBCode($txt);
1024
1025         $a->argv[1] = $user_info['screen_name']; //should be set to username?
1026
1027         $picture = wall_upload_post($a, false);
1028
1029         // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1030         $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1031         $item_id = item_post($a);
1032
1033         // output the post that we just posted.
1034         return api_status_show($type, $item_id);
1035 }
1036
1037 /// @TODO move this to top of file or somewhere better!
1038 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1039
1040 /**
1041  * Updates the user’s current status.
1042  *
1043  * @param string $type Return type (atom, rss, xml, json)
1044  *
1045  * @return array|string
1046  * @throws BadRequestException
1047  * @throws ForbiddenException
1048  * @throws ImagickException
1049  * @throws InternalServerErrorException
1050  * @throws TooManyRequestsException
1051  * @throws UnauthorizedException
1052  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1053  */
1054 function api_statuses_update($type)
1055 {
1056         $a = DI::app();
1057
1058         if (api_user() === false) {
1059                 Logger::log('api_statuses_update: no user');
1060                 throw new ForbiddenException();
1061         }
1062
1063         api_get_user($a);
1064
1065         // convert $_POST array items to the form we use for web posts.
1066         if (requestdata('htmlstatus')) {
1067                 $txt = requestdata('htmlstatus');
1068                 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1069                         $txt = HTML::toBBCodeVideo($txt);
1070
1071                         $config = HTMLPurifier_Config::createDefault();
1072                         $config->set('Cache.DefinitionImpl', null);
1073
1074                         $purifier = new HTMLPurifier($config);
1075                         $txt = $purifier->purify($txt);
1076
1077                         $_REQUEST['body'] = HTML::toBBCode($txt);
1078                 }
1079         } else {
1080                 $_REQUEST['body'] = requestdata('status');
1081         }
1082
1083         $_REQUEST['title'] = requestdata('title');
1084
1085         $parent = requestdata('in_reply_to_status_id');
1086
1087         // Twidere sends "-1" if it is no reply ...
1088         if ($parent == -1) {
1089                 $parent = "";
1090         }
1091
1092         if (ctype_digit($parent)) {
1093                 $_REQUEST['parent'] = $parent;
1094         } else {
1095                 $_REQUEST['parent_uri'] = $parent;
1096         }
1097
1098         if (requestdata('lat') && requestdata('long')) {
1099                 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1100         }
1101         $_REQUEST['profile_uid'] = api_user();
1102
1103         if (!$parent) {
1104                 // Check for throttling (maximum posts per day, week and month)
1105                 $throttle_day = Config::get('system', 'throttle_limit_day');
1106                 if ($throttle_day > 0) {
1107                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1108
1109                         $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1110                         $posts_day = DBA::count('thread', $condition);
1111
1112                         if ($posts_day > $throttle_day) {
1113                                 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1114                                 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1115                                 throw new TooManyRequestsException(L10n::tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1116                         }
1117                 }
1118
1119                 $throttle_week = Config::get('system', 'throttle_limit_week');
1120                 if ($throttle_week > 0) {
1121                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1122
1123                         $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1124                         $posts_week = DBA::count('thread', $condition);
1125
1126                         if ($posts_week > $throttle_week) {
1127                                 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1128                                 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1129                                 throw new TooManyRequestsException(L10n::tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week));
1130                         }
1131                 }
1132
1133                 $throttle_month = Config::get('system', 'throttle_limit_month');
1134                 if ($throttle_month > 0) {
1135                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1136
1137                         $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1138                         $posts_month = DBA::count('thread', $condition);
1139
1140                         if ($posts_month > $throttle_month) {
1141                                 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1142                                 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1143                                 throw new TooManyRequestsException(L10n::t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1144                         }
1145                 }
1146         }
1147
1148         if (!empty($_FILES['media'])) {
1149                 // upload the image if we have one
1150                 $picture = wall_upload_post($a, false);
1151                 if (is_array($picture)) {
1152                         $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1153                 }
1154         }
1155
1156         if (requestdata('media_ids')) {
1157                 $ids = explode(',', requestdata('media_ids'));
1158                 foreach ($ids as $id) {
1159                         $r = q(
1160                                 "SELECT `resource-id`, `scale`, `nickname`, `type`, `desc` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
1161                                 intval($id),
1162                                 api_user()
1163                         );
1164                         if (DBA::isResult($r)) {
1165                                 $phototypes = Images::supportedTypes();
1166                                 $ext = $phototypes[$r[0]['type']];
1167                                 $description = $r[0]['desc'] ?? '';
1168                                 $_REQUEST['body'] .= "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1169                                 $_REQUEST['body'] .= '[img=' . DI::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1170                         }
1171                 }
1172         }
1173
1174         // set this so that the item_post() function is quiet and doesn't redirect or emit json
1175
1176         $_REQUEST['api_source'] = true;
1177
1178         if (empty($_REQUEST['source'])) {
1179                 $_REQUEST["source"] = api_source();
1180         }
1181
1182         // call out normal post function
1183         $item_id = item_post($a);
1184
1185         // output the post that we just posted.
1186         return api_status_show($type, $item_id);
1187 }
1188
1189 /// @TODO move to top of file or somewhere better
1190 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1191 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1192
1193 /**
1194  * Uploads an image to Friendica.
1195  *
1196  * @return array
1197  * @throws BadRequestException
1198  * @throws ForbiddenException
1199  * @throws ImagickException
1200  * @throws InternalServerErrorException
1201  * @throws UnauthorizedException
1202  * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1203  */
1204 function api_media_upload()
1205 {
1206         $a = DI::app();
1207
1208         if (api_user() === false) {
1209                 Logger::log('no user');
1210                 throw new ForbiddenException();
1211         }
1212
1213         api_get_user($a);
1214
1215         if (empty($_FILES['media'])) {
1216                 // Output error
1217                 throw new BadRequestException("No media.");
1218         }
1219
1220         $media = wall_upload_post($a, false);
1221         if (!$media) {
1222                 // Output error
1223                 throw new InternalServerErrorException();
1224         }
1225
1226         $returndata = [];
1227         $returndata["media_id"] = $media["id"];
1228         $returndata["media_id_string"] = (string)$media["id"];
1229         $returndata["size"] = $media["size"];
1230         $returndata["image"] = ["w" => $media["width"],
1231                                 "h" => $media["height"],
1232                                 "image_type" => $media["type"],
1233                                 "friendica_preview_url" => $media["preview"]];
1234
1235         Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1236
1237         return ["media" => $returndata];
1238 }
1239
1240 /// @TODO move to top of file or somewhere better
1241 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1242
1243 /**
1244  * Updates media meta data (picture descriptions)
1245  *
1246  * @param string $type Return type (atom, rss, xml, json)
1247  *
1248  * @return array|string
1249  * @throws BadRequestException
1250  * @throws ForbiddenException
1251  * @throws ImagickException
1252  * @throws InternalServerErrorException
1253  * @throws TooManyRequestsException
1254  * @throws UnauthorizedException
1255  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1256  *
1257  * @todo Compare the corresponding Twitter function for correct return values
1258  */
1259 function api_media_metadata_create($type)
1260 {
1261         $a = DI::app();
1262
1263         if (api_user() === false) {
1264                 Logger::info('no user');
1265                 throw new ForbiddenException();
1266         }
1267
1268         api_get_user($a);
1269
1270         $postdata = Network::postdata();
1271
1272         if (empty($postdata)) {
1273                 throw new BadRequestException("No post data");
1274         }
1275
1276         $data = json_decode($postdata, true);
1277         if (empty($data)) {
1278                 throw new BadRequestException("Invalid post data");
1279         }
1280
1281         if (empty($data['media_id']) || empty($data['alt_text'])) {
1282                 throw new BadRequestException("Missing post data values");
1283         }
1284
1285         if (empty($data['alt_text']['text'])) {
1286                 throw new BadRequestException("No alt text.");
1287         }
1288
1289         Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1290
1291         $condition =  ['id' => $data['media_id'], 'uid' => api_user()];
1292         $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1293         if (!DBA::isResult($photo)) {
1294                 throw new BadRequestException("Metadata not found.");
1295         }
1296
1297         DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1298 }
1299
1300 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1301
1302 /**
1303  * @param string $type    Return format (atom, rss, xml, json)
1304  * @param int    $item_id
1305  * @return string
1306  * @throws Exception
1307  */
1308 function api_status_show($type, $item_id)
1309 {
1310         Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1311
1312         $status_info = [];
1313
1314         $item = api_get_item(['id' => $item_id]);
1315         if (!empty($item)) {
1316                 $status_info = api_format_item($item, $type);
1317         }
1318
1319         Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1320
1321         return api_format_data('statuses', $type, ['status' => $status_info]);
1322 }
1323
1324 /**
1325  * Retrieves the last public status of the provided user info
1326  *
1327  * @param int    $ownerId Public contact Id
1328  * @param int    $uid     User Id
1329  * @return array
1330  * @throws Exception
1331  */
1332 function api_get_last_status($ownerId, $uid)
1333 {
1334         $condition = [
1335                 'author-id'=> $ownerId,
1336                 'uid'      => $uid,
1337                 'gravity'  => [GRAVITY_PARENT, GRAVITY_COMMENT],
1338                 'private'  => false
1339         ];
1340
1341         $item = api_get_item($condition);
1342
1343         return $item;
1344 }
1345
1346 /**
1347  * Retrieves a single item record based on the provided condition and converts it for API use.
1348  *
1349  * @param array $condition Item table condition array
1350  * @return array
1351  * @throws Exception
1352  */
1353 function api_get_item(array $condition)
1354 {
1355         $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1356
1357         return $item;
1358 }
1359
1360 /**
1361  * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1362  * The author's most recent status will be returned inline.
1363  *
1364  * @param string $type Return type (atom, rss, xml, json)
1365  * @return array|string
1366  * @throws BadRequestException
1367  * @throws ImagickException
1368  * @throws InternalServerErrorException
1369  * @throws UnauthorizedException
1370  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1371  */
1372 function api_users_show($type)
1373 {
1374         $a = Friendica\DI::app();
1375
1376         $user_info = api_get_user($a);
1377
1378         $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1379         if (!empty($item)) {
1380                 $user_info['status'] = api_format_item($item, $type);
1381         }
1382
1383         // "uid" and "self" are only needed for some internal stuff, so remove it from here
1384         unset($user_info['uid']);
1385         unset($user_info['self']);
1386
1387         return api_format_data('user', $type, ['user' => $user_info]);
1388 }
1389
1390 /// @TODO move to top of file or somewhere better
1391 api_register_func('api/users/show', 'api_users_show');
1392 api_register_func('api/externalprofile/show', 'api_users_show');
1393
1394 /**
1395  * Search a public user account.
1396  *
1397  * @param string $type Return type (atom, rss, xml, json)
1398  *
1399  * @return array|string
1400  * @throws BadRequestException
1401  * @throws ImagickException
1402  * @throws InternalServerErrorException
1403  * @throws UnauthorizedException
1404  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1405  */
1406 function api_users_search($type)
1407 {
1408         $a = DI::app();
1409
1410         $userlist = [];
1411
1412         if (!empty($_GET['q'])) {
1413                 $contacts = Contact::selectToArray(
1414                         ['id'],
1415                         [
1416                                 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1417                                 $_GET['q'],
1418                                 $_GET['q'],
1419                                 $_GET['q'],
1420                                 $_GET['q'],
1421                         ]
1422                 );
1423
1424                 if (DBA::isResult($contacts)) {
1425                         $k = 0;
1426                         foreach ($contacts as $contact) {
1427                                 $user_info = api_get_user($a, $contact['id']);
1428
1429                                 if ($type == 'xml') {
1430                                         $userlist[$k++ . ':user'] = $user_info;
1431                                 } else {
1432                                         $userlist[] = $user_info;
1433                                 }
1434                         }
1435                         $userlist = ['users' => $userlist];
1436                 } else {
1437                         throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1438                 }
1439         } else {
1440                 throw new BadRequestException('No search term specified.');
1441         }
1442
1443         return api_format_data('users', $type, $userlist);
1444 }
1445
1446 /// @TODO move to top of file or somewhere better
1447 api_register_func('api/users/search', 'api_users_search');
1448
1449 /**
1450  * Return user objects
1451  *
1452  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1453  *
1454  * @param string $type Return format: json or xml
1455  *
1456  * @return array|string
1457  * @throws BadRequestException
1458  * @throws ImagickException
1459  * @throws InternalServerErrorException
1460  * @throws NotFoundException if the results are empty.
1461  * @throws UnauthorizedException
1462  */
1463 function api_users_lookup($type)
1464 {
1465         $users = [];
1466
1467         if (!empty($_REQUEST['user_id'])) {
1468                 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1469                         if (!empty($id)) {
1470                                 $users[] = api_get_user(DI::app(), $id);
1471                         }
1472                 }
1473         }
1474
1475         if (empty($users)) {
1476                 throw new NotFoundException;
1477         }
1478
1479         return api_format_data("users", $type, ['users' => $users]);
1480 }
1481
1482 /// @TODO move to top of file or somewhere better
1483 api_register_func('api/users/lookup', 'api_users_lookup', true);
1484
1485 /**
1486  * Returns statuses that match a specified query.
1487  *
1488  * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1489  *
1490  * @param string $type Return format: json, xml, atom, rss
1491  *
1492  * @return array|string
1493  * @throws BadRequestException if the "q" parameter is missing.
1494  * @throws ForbiddenException
1495  * @throws ImagickException
1496  * @throws InternalServerErrorException
1497  * @throws UnauthorizedException
1498  */
1499 function api_search($type)
1500 {
1501         $a = DI::app();
1502         $user_info = api_get_user($a);
1503
1504         if (api_user() === false || $user_info === false) {
1505                 throw new ForbiddenException();
1506         }
1507
1508         if (empty($_REQUEST['q'])) {
1509                 throw new BadRequestException('q parameter is required.');
1510         }
1511
1512         $searchTerm = trim(rawurldecode($_REQUEST['q']));
1513
1514         $data = [];
1515         $data['status'] = [];
1516         $count = 15;
1517         $exclude_replies = !empty($_REQUEST['exclude_replies']);
1518         if (!empty($_REQUEST['rpp'])) {
1519                 $count = $_REQUEST['rpp'];
1520         } elseif (!empty($_REQUEST['count'])) {
1521                 $count = $_REQUEST['count'];
1522         }
1523
1524         $since_id = $_REQUEST['since_id'] ?? 0;
1525         $max_id = $_REQUEST['max_id'] ?? 0;
1526         $page = $_REQUEST['page'] ?? 1;
1527
1528         $start = max(0, ($page - 1) * $count);
1529
1530         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1531         if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1532                 $searchTerm = $matches[1];
1533                 $condition = ["`oid` > ?
1534                         AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) 
1535                         AND `otype` = ? AND `type` = ? AND `term` = ?",
1536                         $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1537                 if ($max_id > 0) {
1538                         $condition[0] .= ' AND `oid` <= ?';
1539                         $condition[] = $max_id;
1540                 }
1541                 $terms = DBA::select('term', ['oid'], $condition, []);
1542                 $itemIds = [];
1543                 while ($term = DBA::fetch($terms)) {
1544                         $itemIds[] = $term['oid'];
1545                 }
1546                 DBA::close($terms);
1547
1548                 if (empty($itemIds)) {
1549                         return api_format_data('statuses', $type, $data);
1550                 }
1551
1552                 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1553                 if ($exclude_replies) {
1554                         $preCondition[] = '`id` = `parent`';
1555                 }
1556
1557                 $condition = [implode(' AND ', $preCondition)];
1558         } else {
1559                 $condition = ["`id` > ?
1560                         " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1561                         AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1562                         AND `body` LIKE CONCAT('%',?,'%')",
1563                         $since_id, api_user(), $_REQUEST['q']];
1564                 if ($max_id > 0) {
1565                         $condition[0] .= ' AND `id` <= ?';
1566                         $condition[] = $max_id;
1567                 }
1568         }
1569
1570         $statuses = [];
1571
1572         if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1573                 $id = Item::fetchByLink($searchTerm, api_user());
1574                 if (!$id) {
1575                         // Public post
1576                         $id = Item::fetchByLink($searchTerm);
1577                 }
1578
1579                 if (!empty($id)) {
1580                         $statuses = Item::select([], ['id' => $id]);
1581                 }
1582         }
1583
1584         $statuses = $statuses ?: Item::selectForUser(api_user(), [], $condition, $params);
1585
1586         $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1587
1588         bindComments($data['status']);
1589
1590         return api_format_data('statuses', $type, $data);
1591 }
1592
1593 /// @TODO move to top of file or somewhere better
1594 api_register_func('api/search/tweets', 'api_search', true);
1595 api_register_func('api/search', 'api_search', true);
1596
1597 /**
1598  * Returns the most recent statuses posted by the user and the users they follow.
1599  *
1600  * @see  https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1601  *
1602  * @param string $type Return type (atom, rss, xml, json)
1603  *
1604  * @return array|string
1605  * @throws BadRequestException
1606  * @throws ForbiddenException
1607  * @throws ImagickException
1608  * @throws InternalServerErrorException
1609  * @throws UnauthorizedException
1610  * @todo Optional parameters
1611  * @todo Add reply info
1612  */
1613 function api_statuses_home_timeline($type)
1614 {
1615         $a = DI::app();
1616         $user_info = api_get_user($a);
1617
1618         if (api_user() === false || $user_info === false) {
1619                 throw new ForbiddenException();
1620         }
1621
1622         unset($_REQUEST["user_id"]);
1623         unset($_GET["user_id"]);
1624
1625         unset($_REQUEST["screen_name"]);
1626         unset($_GET["screen_name"]);
1627
1628         // get last network messages
1629
1630         // params
1631         $count = $_REQUEST['count'] ?? 20;
1632         $page = $_REQUEST['page']?? 0;
1633         $since_id = $_REQUEST['since_id'] ?? 0;
1634         $max_id = $_REQUEST['max_id'] ?? 0;
1635         $exclude_replies = !empty($_REQUEST['exclude_replies']);
1636         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1637
1638         $start = max(0, ($page - 1) * $count);
1639
1640         $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1641                 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1642
1643         if ($max_id > 0) {
1644                 $condition[0] .= " AND `item`.`id` <= ?";
1645                 $condition[] = $max_id;
1646         }
1647         if ($exclude_replies) {
1648                 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1649         }
1650         if ($conversation_id > 0) {
1651                 $condition[0] .= " AND `item`.`parent` = ?";
1652                 $condition[] = $conversation_id;
1653         }
1654
1655         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1656         $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1657
1658         $items = Item::inArray($statuses);
1659
1660         $ret = api_format_items($items, $user_info, false, $type);
1661
1662         // Set all posts from the query above to seen
1663         $idarray = [];
1664         foreach ($items as $item) {
1665                 $idarray[] = intval($item["id"]);
1666         }
1667
1668         if (!empty($idarray)) {
1669                 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1670                 if ($unseen) {
1671                         Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1672                 }
1673         }
1674
1675         bindComments($ret);
1676
1677         $data = ['status' => $ret];
1678         switch ($type) {
1679                 case "atom":
1680                         break;
1681                 case "rss":
1682                         $data = api_rss_extra($a, $data, $user_info);
1683                         break;
1684         }
1685
1686         return api_format_data("statuses", $type, $data);
1687 }
1688
1689
1690 /// @TODO move to top of file or somewhere better
1691 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1692 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1693
1694 /**
1695  * Returns the most recent statuses from public users.
1696  *
1697  * @param string $type Return type (atom, rss, xml, json)
1698  *
1699  * @return array|string
1700  * @throws BadRequestException
1701  * @throws ForbiddenException
1702  * @throws ImagickException
1703  * @throws InternalServerErrorException
1704  * @throws UnauthorizedException
1705  */
1706 function api_statuses_public_timeline($type)
1707 {
1708         $a = DI::app();
1709         $user_info = api_get_user($a);
1710
1711         if (api_user() === false || $user_info === false) {
1712                 throw new ForbiddenException();
1713         }
1714
1715         // get last network messages
1716
1717         // params
1718         $count = $_REQUEST['count'] ?? 20;
1719         $page = $_REQUEST['page'] ?? 1;
1720         $since_id = $_REQUEST['since_id'] ?? 0;
1721         $max_id = $_REQUEST['max_id'] ?? 0;
1722         $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1723         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1724
1725         $start = max(0, ($page - 1) * $count);
1726
1727         if ($exclude_replies && !$conversation_id) {
1728                 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1729                         GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1730
1731                 if ($max_id > 0) {
1732                         $condition[0] .= " AND `thread`.`iid` <= ?";
1733                         $condition[] = $max_id;
1734                 }
1735
1736                 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1737                 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1738
1739                 $r = Item::inArray($statuses);
1740         } else {
1741                 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1742                         GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1743
1744                 if ($max_id > 0) {
1745                         $condition[0] .= " AND `item`.`id` <= ?";
1746                         $condition[] = $max_id;
1747                 }
1748                 if ($conversation_id > 0) {
1749                         $condition[0] .= " AND `item`.`parent` = ?";
1750                         $condition[] = $conversation_id;
1751                 }
1752
1753                 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1754                 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1755
1756                 $r = Item::inArray($statuses);
1757         }
1758
1759         $ret = api_format_items($r, $user_info, false, $type);
1760
1761         bindComments($ret);
1762
1763         $data = ['status' => $ret];
1764         switch ($type) {
1765                 case "atom":
1766                         break;
1767                 case "rss":
1768                         $data = api_rss_extra($a, $data, $user_info);
1769                         break;
1770         }
1771
1772         return api_format_data("statuses", $type, $data);
1773 }
1774
1775 /// @TODO move to top of file or somewhere better
1776 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1777
1778 /**
1779  * Returns the most recent statuses posted by users this node knows about.
1780  *
1781  * @brief Returns the list of public federated posts this node knows about
1782  *
1783  * @param string $type Return format: json, xml, atom, rss
1784  * @return array|string
1785  * @throws BadRequestException
1786  * @throws ForbiddenException
1787  * @throws ImagickException
1788  * @throws InternalServerErrorException
1789  * @throws UnauthorizedException
1790  */
1791 function api_statuses_networkpublic_timeline($type)
1792 {
1793         $a = DI::app();
1794         $user_info = api_get_user($a);
1795
1796         if (api_user() === false || $user_info === false) {
1797                 throw new ForbiddenException();
1798         }
1799
1800         $since_id        = $_REQUEST['since_id'] ?? 0;
1801         $max_id          = $_REQUEST['max_id'] ?? 0;
1802
1803         // pagination
1804         $count = $_REQUEST['count'] ?? 20;
1805         $page  = $_REQUEST['page'] ?? 1;
1806
1807         $start = max(0, ($page - 1) * $count);
1808
1809         $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1810                 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1811
1812         if ($max_id > 0) {
1813                 $condition[0] .= " AND `thread`.`iid` <= ?";
1814                 $condition[] = $max_id;
1815         }
1816
1817         $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1818         $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1819
1820         $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1821
1822         bindComments($ret);
1823
1824         $data = ['status' => $ret];
1825         switch ($type) {
1826                 case "atom":
1827                         break;
1828                 case "rss":
1829                         $data = api_rss_extra($a, $data, $user_info);
1830                         break;
1831         }
1832
1833         return api_format_data("statuses", $type, $data);
1834 }
1835
1836 /// @TODO move to top of file or somewhere better
1837 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1838
1839 /**
1840  * Returns a single status.
1841  *
1842  * @param string $type Return type (atom, rss, xml, json)
1843  *
1844  * @return array|string
1845  * @throws BadRequestException
1846  * @throws ForbiddenException
1847  * @throws ImagickException
1848  * @throws InternalServerErrorException
1849  * @throws UnauthorizedException
1850  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1851  */
1852 function api_statuses_show($type)
1853 {
1854         $a = DI::app();
1855         $user_info = api_get_user($a);
1856
1857         if (api_user() === false || $user_info === false) {
1858                 throw new ForbiddenException();
1859         }
1860
1861         // params
1862         $id = intval($a->argv[3] ?? 0);
1863
1864         if ($id == 0) {
1865                 $id = intval($_REQUEST['id'] ?? 0);
1866         }
1867
1868         // Hotot workaround
1869         if ($id == 0) {
1870                 $id = intval($a->argv[4] ?? 0);
1871         }
1872
1873         Logger::log('API: api_statuses_show: ' . $id);
1874
1875         $conversation = !empty($_REQUEST['conversation']);
1876
1877         // try to fetch the item for the local user - or the public item, if there is no local one
1878         $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1879         if (!DBA::isResult($uri_item)) {
1880                 throw new BadRequestException("There is no status with this id.");
1881         }
1882
1883         $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1884         if (!DBA::isResult($item)) {
1885                 throw new BadRequestException("There is no status with this id.");
1886         }
1887
1888         $id = $item['id'];
1889
1890         if ($conversation) {
1891                 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1892                 $params = ['order' => ['id' => true]];
1893         } else {
1894                 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1895                 $params = [];
1896         }
1897
1898         $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1899
1900         /// @TODO How about copying this to above methods which don't check $r ?
1901         if (!DBA::isResult($statuses)) {
1902                 throw new BadRequestException("There is no status with this id.");
1903         }
1904
1905         $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1906
1907         if ($conversation) {
1908                 $data = ['status' => $ret];
1909                 return api_format_data("statuses", $type, $data);
1910         } else {
1911                 $data = ['status' => $ret[0]];
1912                 return api_format_data("status", $type, $data);
1913         }
1914 }
1915
1916 /// @TODO move to top of file or somewhere better
1917 api_register_func('api/statuses/show', 'api_statuses_show', true);
1918
1919 /**
1920  *
1921  * @param string $type Return type (atom, rss, xml, json)
1922  *
1923  * @return array|string
1924  * @throws BadRequestException
1925  * @throws ForbiddenException
1926  * @throws ImagickException
1927  * @throws InternalServerErrorException
1928  * @throws UnauthorizedException
1929  * @todo nothing to say?
1930  */
1931 function api_conversation_show($type)
1932 {
1933         $a = DI::app();
1934         $user_info = api_get_user($a);
1935
1936         if (api_user() === false || $user_info === false) {
1937                 throw new ForbiddenException();
1938         }
1939
1940         // params
1941         $id       = intval($a->argv[3]           ?? 0);
1942         $since_id = intval($_REQUEST['since_id'] ?? 0);
1943         $max_id   = intval($_REQUEST['max_id']   ?? 0);
1944         $count    = intval($_REQUEST['count']    ?? 20);
1945         $page     = intval($_REQUEST['page']     ?? 1);
1946
1947         $start = max(0, ($page - 1) * $count);
1948
1949         if ($id == 0) {
1950                 $id = intval($_REQUEST['id'] ?? 0);
1951         }
1952
1953         // Hotot workaround
1954         if ($id == 0) {
1955                 $id = intval($a->argv[4] ?? 0);
1956         }
1957
1958         Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1959
1960         // try to fetch the item for the local user - or the public item, if there is no local one
1961         $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1962         if (!DBA::isResult($item)) {
1963                 throw new BadRequestException("There is no status with this id.");
1964         }
1965
1966         $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1967         if (!DBA::isResult($parent)) {
1968                 throw new BadRequestException("There is no status with this id.");
1969         }
1970
1971         $id = $parent['id'];
1972
1973         $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1974                 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1975
1976         if ($max_id > 0) {
1977                 $condition[0] .= " AND `item`.`id` <= ?";
1978                 $condition[] = $max_id;
1979         }
1980
1981         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1982         $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1983
1984         if (!DBA::isResult($statuses)) {
1985                 throw new BadRequestException("There is no status with id $id.");
1986         }
1987
1988         $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1989
1990         $data = ['status' => $ret];
1991         return api_format_data("statuses", $type, $data);
1992 }
1993
1994 /// @TODO move to top of file or somewhere better
1995 api_register_func('api/conversation/show', 'api_conversation_show', true);
1996 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1997
1998 /**
1999  * Repeats a status.
2000  *
2001  * @param string $type Return type (atom, rss, xml, json)
2002  *
2003  * @return array|string
2004  * @throws BadRequestException
2005  * @throws ForbiddenException
2006  * @throws ImagickException
2007  * @throws InternalServerErrorException
2008  * @throws UnauthorizedException
2009  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2010  */
2011 function api_statuses_repeat($type)
2012 {
2013         global $called_api;
2014
2015         $a = DI::app();
2016
2017         if (api_user() === false) {
2018                 throw new ForbiddenException();
2019         }
2020
2021         api_get_user($a);
2022
2023         // params
2024         $id = intval($a->argv[3] ?? 0);
2025
2026         if ($id == 0) {
2027                 $id = intval($_REQUEST['id'] ?? 0);
2028         }
2029
2030         // Hotot workaround
2031         if ($id == 0) {
2032                 $id = intval($a->argv[4] ?? 0);
2033         }
2034
2035         Logger::log('API: api_statuses_repeat: '.$id);
2036
2037         $fields = ['body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2038         $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2039
2040         if (DBA::isResult($item) && $item['body'] != "") {
2041                 if (strpos($item['body'], "[/share]") !== false) {
2042                         $pos = strpos($item['body'], "[share");
2043                         $post = substr($item['body'], $pos);
2044                 } else {
2045                         $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2046
2047                         if (!empty($item['title'])) {
2048                                 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2049                         }
2050
2051                         $post .= $item['body'];
2052                         $post .= "[/share]";
2053                 }
2054                 $_REQUEST['body'] = $post;
2055                 $_REQUEST['tag'] = $item['tag'];
2056                 $_REQUEST['attach'] = $item['attach'];
2057                 $_REQUEST['profile_uid'] = api_user();
2058                 $_REQUEST['api_source'] = true;
2059
2060                 if (empty($_REQUEST['source'])) {
2061                         $_REQUEST["source"] = api_source();
2062                 }
2063
2064                 $item_id = item_post($a);
2065         } else {
2066                 throw new ForbiddenException();
2067         }
2068
2069         // output the post that we just posted.
2070         $called_api = [];
2071         return api_status_show($type, $item_id);
2072 }
2073
2074 /// @TODO move to top of file or somewhere better
2075 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2076
2077 /**
2078  * Destroys a specific status.
2079  *
2080  * @param string $type Return type (atom, rss, xml, json)
2081  *
2082  * @return array|string
2083  * @throws BadRequestException
2084  * @throws ForbiddenException
2085  * @throws ImagickException
2086  * @throws InternalServerErrorException
2087  * @throws UnauthorizedException
2088  * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2089  */
2090 function api_statuses_destroy($type)
2091 {
2092         $a = DI::app();
2093
2094         if (api_user() === false) {
2095                 throw new ForbiddenException();
2096         }
2097
2098         api_get_user($a);
2099
2100         // params
2101         $id = intval($a->argv[3] ?? 0);
2102
2103         if ($id == 0) {
2104                 $id = intval($_REQUEST['id'] ?? 0);
2105         }
2106
2107         // Hotot workaround
2108         if ($id == 0) {
2109                 $id = intval($a->argv[4] ?? 0);
2110         }
2111
2112         Logger::log('API: api_statuses_destroy: '.$id);
2113
2114         $ret = api_statuses_show($type);
2115
2116         Item::deleteForUser(['id' => $id], api_user());
2117
2118         return $ret;
2119 }
2120
2121 /// @TODO move to top of file or somewhere better
2122 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2123
2124 /**
2125  * Returns the most recent mentions.
2126  *
2127  * @param string $type Return type (atom, rss, xml, json)
2128  *
2129  * @return array|string
2130  * @throws BadRequestException
2131  * @throws ForbiddenException
2132  * @throws ImagickException
2133  * @throws InternalServerErrorException
2134  * @throws UnauthorizedException
2135  * @see http://developer.twitter.com/doc/get/statuses/mentions
2136  */
2137 function api_statuses_mentions($type)
2138 {
2139         $a = DI::app();
2140         $user_info = api_get_user($a);
2141
2142         if (api_user() === false || $user_info === false) {
2143                 throw new ForbiddenException();
2144         }
2145
2146         unset($_REQUEST["user_id"]);
2147         unset($_GET["user_id"]);
2148
2149         unset($_REQUEST["screen_name"]);
2150         unset($_GET["screen_name"]);
2151
2152         // get last network messages
2153
2154         // params
2155         $since_id = $_REQUEST['since_id'] ?? 0;
2156         $max_id   = $_REQUEST['max_id']   ?? 0;
2157         $count    = $_REQUEST['count']    ?? 20;
2158         $page     = $_REQUEST['page']     ?? 1;
2159
2160         $start = max(0, ($page - 1) * $count);
2161
2162         $query = "SELECT `item`.`id` FROM `user-item`
2163                 INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` AND `item`.`gravity` IN (?, ?)
2164                 WHERE (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND
2165                         `user-item`.`uid` = ? AND `user-item`.`notification-type` & ? != 0
2166                         AND `user-item`.`iid` > ?";
2167         $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2168                 UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED |
2169                 UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT,
2170                 $since_id];
2171
2172         if ($max_id > 0) {
2173                 $condition[0] .= " AND `item`.`id` <= ?";
2174                 $condition[] = $max_id;
2175         }
2176
2177         $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?";
2178         $condition[] = $start;
2179         $condition[] = $count;
2180
2181         $useritems = DBA::p($query, $condition);
2182         $itemids = [];
2183         while ($useritem = DBA::fetch($useritems)) {
2184                 $itemids[] = $useritem['id'];
2185         }
2186         DBA::close($useritems);
2187
2188         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2189         $statuses = Item::selectForUser(api_user(), [], ['id' => $itemids], $params);
2190
2191         $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2192
2193         $data = ['status' => $ret];
2194         switch ($type) {
2195                 case "atom":
2196                         break;
2197                 case "rss":
2198                         $data = api_rss_extra($a, $data, $user_info);
2199                         break;
2200         }
2201
2202         return api_format_data("statuses", $type, $data);
2203 }
2204
2205 /// @TODO move to top of file or somewhere better
2206 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2207 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2208
2209 /**
2210  * Returns the most recent statuses posted by the user.
2211  *
2212  * @brief Returns a user's public timeline
2213  *
2214  * @param string $type Either "json" or "xml"
2215  * @return string|array
2216  * @throws BadRequestException
2217  * @throws ForbiddenException
2218  * @throws ImagickException
2219  * @throws InternalServerErrorException
2220  * @throws UnauthorizedException
2221  * @see   https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2222  */
2223 function api_statuses_user_timeline($type)
2224 {
2225         $a = DI::app();
2226         $user_info = api_get_user($a);
2227
2228         if (api_user() === false || $user_info === false) {
2229                 throw new ForbiddenException();
2230         }
2231
2232         Logger::log(
2233                 "api_statuses_user_timeline: api_user: ". api_user() .
2234                         "\nuser_info: ".print_r($user_info, true) .
2235                         "\n_REQUEST:  ".print_r($_REQUEST, true),
2236                 Logger::DEBUG
2237         );
2238
2239         $since_id        = $_REQUEST['since_id'] ?? 0;
2240         $max_id          = $_REQUEST['max_id'] ?? 0;
2241         $exclude_replies = !empty($_REQUEST['exclude_replies']);
2242         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2243
2244         // pagination
2245         $count = $_REQUEST['count'] ?? 20;
2246         $page  = $_REQUEST['page'] ?? 1;
2247
2248         $start = max(0, ($page - 1) * $count);
2249
2250         $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2251                 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2252
2253         if ($user_info['self'] == 1) {
2254                 $condition[0] .= ' AND `item`.`wall` ';
2255         }
2256
2257         if ($exclude_replies) {
2258                 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2259         }
2260
2261         if ($conversation_id > 0) {
2262                 $condition[0] .= " AND `item`.`parent` = ?";
2263                 $condition[] = $conversation_id;
2264         }
2265
2266         if ($max_id > 0) {
2267                 $condition[0] .= " AND `item`.`id` <= ?";
2268                 $condition[] = $max_id;
2269         }
2270
2271         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2272         $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2273
2274         $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2275
2276         bindComments($ret);
2277
2278         $data = ['status' => $ret];
2279         switch ($type) {
2280                 case "atom":
2281                         break;
2282                 case "rss":
2283                         $data = api_rss_extra($a, $data, $user_info);
2284                         break;
2285         }
2286
2287         return api_format_data("statuses", $type, $data);
2288 }
2289
2290 /// @TODO move to top of file or somewhere better
2291 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2292
2293 /**
2294  * Star/unstar an item.
2295  * param: id : id of the item
2296  *
2297  * @param string $type Return type (atom, rss, xml, json)
2298  *
2299  * @return array|string
2300  * @throws BadRequestException
2301  * @throws ForbiddenException
2302  * @throws ImagickException
2303  * @throws InternalServerErrorException
2304  * @throws UnauthorizedException
2305  * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2306  */
2307 function api_favorites_create_destroy($type)
2308 {
2309         $a = DI::app();
2310
2311         if (api_user() === false) {
2312                 throw new ForbiddenException();
2313         }
2314
2315         // for versioned api.
2316         /// @TODO We need a better global soluton
2317         $action_argv_id = 2;
2318         if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2319                 $action_argv_id = 3;
2320         }
2321
2322         if ($a->argc <= $action_argv_id) {
2323                 throw new BadRequestException("Invalid request.");
2324         }
2325         $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2326         if ($a->argc == $action_argv_id + 2) {
2327                 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2328         } else {
2329                 $itemid = intval($_REQUEST['id'] ?? 0);
2330         }
2331
2332         $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2333
2334         if (!DBA::isResult($item)) {
2335                 throw new BadRequestException("Invalid item.");
2336         }
2337
2338         switch ($action) {
2339                 case "create":
2340                         $item['starred'] = 1;
2341                         break;
2342                 case "destroy":
2343                         $item['starred'] = 0;
2344                         break;
2345                 default:
2346                         throw new BadRequestException("Invalid action ".$action);
2347         }
2348
2349         $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2350
2351         if ($r === false) {
2352                 throw new InternalServerErrorException("DB error");
2353         }
2354
2355
2356         $user_info = api_get_user($a);
2357         $rets = api_format_items([$item], $user_info, false, $type);
2358         $ret = $rets[0];
2359
2360         $data = ['status' => $ret];
2361         switch ($type) {
2362                 case "atom":
2363                         break;
2364                 case "rss":
2365                         $data = api_rss_extra($a, $data, $user_info);
2366                         break;
2367         }
2368
2369         return api_format_data("status", $type, $data);
2370 }
2371
2372 /// @TODO move to top of file or somewhere better
2373 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2374 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2375
2376 /**
2377  * Returns the most recent favorite statuses.
2378  *
2379  * @param string $type Return type (atom, rss, xml, json)
2380  *
2381  * @return string|array
2382  * @throws BadRequestException
2383  * @throws ForbiddenException
2384  * @throws ImagickException
2385  * @throws InternalServerErrorException
2386  * @throws UnauthorizedException
2387  */
2388 function api_favorites($type)
2389 {
2390         global $called_api;
2391
2392         $a = DI::app();
2393         $user_info = api_get_user($a);
2394
2395         if (api_user() === false || $user_info === false) {
2396                 throw new ForbiddenException();
2397         }
2398
2399         $called_api = [];
2400
2401         // in friendica starred item are private
2402         // return favorites only for self
2403         Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2404
2405         if ($user_info['self'] == 0) {
2406                 $ret = [];
2407         } else {
2408                 // params
2409                 $since_id = $_REQUEST['since_id'] ?? 0;
2410                 $max_id = $_REQUEST['max_id'] ?? 0;
2411                 $count = $_GET['count'] ?? 20;
2412                 $page = $_REQUEST['page'] ?? 1;
2413
2414                 $start = max(0, ($page - 1) * $count);
2415
2416                 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2417                         api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2418
2419                 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2420
2421                 if ($max_id > 0) {
2422                         $condition[0] .= " AND `item`.`id` <= ?";
2423                         $condition[] = $max_id;
2424                 }
2425
2426                 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2427
2428                 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2429         }
2430
2431         bindComments($ret);
2432
2433         $data = ['status' => $ret];
2434         switch ($type) {
2435                 case "atom":
2436                         break;
2437                 case "rss":
2438                         $data = api_rss_extra($a, $data, $user_info);
2439                         break;
2440         }
2441
2442         return api_format_data("statuses", $type, $data);
2443 }
2444
2445 /// @TODO move to top of file or somewhere better
2446 api_register_func('api/favorites', 'api_favorites', true);
2447
2448 /**
2449  *
2450  * @param array $item
2451  * @param array $recipient
2452  * @param array $sender
2453  *
2454  * @return array
2455  * @throws InternalServerErrorException
2456  */
2457 function api_format_messages($item, $recipient, $sender)
2458 {
2459         // standard meta information
2460         $ret = [
2461                 'id'                    => $item['id'],
2462                 'sender_id'             => $sender['id'],
2463                 'text'                  => "",
2464                 'recipient_id'          => $recipient['id'],
2465                 'created_at'            => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2466                 'sender_screen_name'    => $sender['screen_name'],
2467                 'recipient_screen_name' => $recipient['screen_name'],
2468                 'sender'                => $sender,
2469                 'recipient'             => $recipient,
2470                 'title'                 => "",
2471                 'friendica_seen'        => $item['seen'] ?? 0,
2472                 'friendica_parent_uri'  => $item['parent-uri'] ?? '',
2473         ];
2474
2475         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2476         if (isset($ret['sender']['uid'])) {
2477                 unset($ret['sender']['uid']);
2478         }
2479         if (isset($ret['sender']['self'])) {
2480                 unset($ret['sender']['self']);
2481         }
2482         if (isset($ret['recipient']['uid'])) {
2483                 unset($ret['recipient']['uid']);
2484         }
2485         if (isset($ret['recipient']['self'])) {
2486                 unset($ret['recipient']['self']);
2487         }
2488
2489         //don't send title to regular StatusNET requests to avoid confusing these apps
2490         if (!empty($_GET['getText'])) {
2491                 $ret['title'] = $item['title'];
2492                 if ($_GET['getText'] == 'html') {
2493                         $ret['text'] = BBCode::convert($item['body'], false);
2494                 } elseif ($_GET['getText'] == 'plain') {
2495                         $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2496                 }
2497         } else {
2498                 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2499         }
2500         if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2501                 unset($ret['sender']);
2502                 unset($ret['recipient']);
2503         }
2504
2505         return $ret;
2506 }
2507
2508 /**
2509  *
2510  * @param array $item
2511  *
2512  * @return array
2513  * @throws InternalServerErrorException
2514  */
2515 function api_convert_item($item)
2516 {
2517         $body = $item['body'];
2518         $entities = api_get_entitities($statustext, $body);
2519
2520         // Add pictures to the attachment array and remove them from the body
2521         $attachments = api_get_attachments($body);
2522
2523         // Workaround for ostatus messages where the title is identically to the body
2524         $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2525         $statusbody = trim(HTML::toPlaintext($html, 0));
2526
2527         // handle data: images
2528         $statusbody = api_format_items_embeded_images($item, $statusbody);
2529
2530         $statustitle = trim($item['title']);
2531
2532         if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2533                 $statustext = trim($statusbody);
2534         } else {
2535                 $statustext = trim($statustitle."\n\n".$statusbody);
2536         }
2537
2538         if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2539                 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2540         }
2541
2542         $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2543
2544         // Workaround for clients with limited HTML parser functionality
2545         $search = ["<br>", "<blockquote>", "</blockquote>",
2546                         "<h1>", "</h1>", "<h2>", "</h2>",
2547                         "<h3>", "</h3>", "<h4>", "</h4>",
2548                         "<h5>", "</h5>", "<h6>", "</h6>"];
2549         $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2550                         "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2551                         "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2552                         "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2553         $statushtml = str_replace($search, $replace, $statushtml);
2554
2555         if ($item['title'] != "") {
2556                 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2557         }
2558
2559         do {
2560                 $oldtext = $statushtml;
2561                 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2562         } while ($oldtext != $statushtml);
2563
2564         if (substr($statushtml, 0, 4) == '<br>') {
2565                 $statushtml = substr($statushtml, 4);
2566         }
2567
2568         if (substr($statushtml, 0, -4) == '<br>') {
2569                 $statushtml = substr($statushtml, -4);
2570         }
2571
2572         // feeds without body should contain the link
2573         if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2574                 $statushtml .= BBCode::convert($item['plink']);
2575         }
2576
2577         return [
2578                 "text" => $statustext,
2579                 "html" => $statushtml,
2580                 "attachments" => $attachments,
2581                 "entities" => $entities
2582         ];
2583 }
2584
2585 /**
2586  *
2587  * @param string $body
2588  *
2589  * @return array
2590  * @throws InternalServerErrorException
2591  */
2592 function api_get_attachments(&$body)
2593 {
2594         $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2595         $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2596
2597         $URLSearchString = "^\[\]";
2598         if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2599                 return [];
2600         }
2601
2602         // Remove all embedded pictures, since they are added as attachments
2603         foreach ($images[0] as $orig) {
2604                 $body = str_replace($orig, '', $body);
2605         }
2606
2607         $attachments = [];
2608
2609         foreach ($images[1] as $image) {
2610                 $imagedata = Images::getInfoFromURLCached($image);
2611
2612                 if ($imagedata) {
2613                         $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2614                 }
2615         }
2616
2617         return $attachments;
2618 }
2619
2620 /**
2621  *
2622  * @param string $text
2623  * @param string $bbcode
2624  *
2625  * @return array
2626  * @throws InternalServerErrorException
2627  * @todo Links at the first character of the post
2628  */
2629 function api_get_entitities(&$text, $bbcode)
2630 {
2631         $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2632
2633         if ($include_entities != "true") {
2634                 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2635
2636                 foreach ($images[1] as $image) {
2637                         $replace = ProxyUtils::proxifyUrl($image);
2638                         $text = str_replace($image, $replace, $text);
2639                 }
2640                 return [];
2641         }
2642
2643         $bbcode = BBCode::cleanPictureLinks($bbcode);
2644
2645         // Change pure links in text to bbcode uris
2646         $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2647
2648         $entities = [];
2649         $entities["hashtags"] = [];
2650         $entities["symbols"] = [];
2651         $entities["urls"] = [];
2652         $entities["user_mentions"] = [];
2653
2654         $URLSearchString = "^\[\]";
2655
2656         $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2657
2658         $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2659         $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2660
2661         $bbcode = preg_replace(
2662                 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2663                 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2664                 $bbcode
2665         );
2666         $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2667
2668         $bbcode = preg_replace(
2669                 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2670                 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2671                 $bbcode
2672         );
2673         $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2674
2675         $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2676
2677         preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2678
2679         $ordered_urls = [];
2680         foreach ($urls[1] as $id => $url) {
2681                 $start = iconv_strpos($text, $url, 0, "UTF-8");
2682                 if (!($start === false)) {
2683                         $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2684                 }
2685         }
2686
2687         ksort($ordered_urls);
2688
2689         $offset = 0;
2690
2691         foreach ($ordered_urls as $url) {
2692                 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2693                         && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2694                 ) {
2695                         $display_url = $url["title"];
2696                 } else {
2697                         $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2698                         $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2699
2700                         if (strlen($display_url) > 26) {
2701                                 $display_url = substr($display_url, 0, 25)."…";
2702                         }
2703                 }
2704
2705                 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2706                 if (!($start === false)) {
2707                         $entities["urls"][] = ["url" => $url["url"],
2708                                                         "expanded_url" => $url["url"],
2709                                                         "display_url" => $display_url,
2710                                                         "indices" => [$start, $start+strlen($url["url"])]];
2711                         $offset = $start + 1;
2712                 }
2713         }
2714
2715         preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2716         $ordered_images = [];
2717         foreach ($images as $image) {
2718                 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2719                 if (!($start === false)) {
2720                         $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2721                 }
2722         }
2723
2724         preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2725         foreach ($images[1] as $image) {
2726                 $start = iconv_strpos($text, $image, 0, "UTF-8");
2727                 if (!($start === false)) {
2728                         $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2729                 }
2730         }
2731
2732         $offset = 0;
2733
2734         foreach ($ordered_images as $image) {
2735                 $url = $image['url'];
2736                 $ext_alt_text = $image['alt'];
2737
2738                 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2739                 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2740
2741                 if (strlen($display_url) > 26) {
2742                         $display_url = substr($display_url, 0, 25)."…";
2743                 }
2744
2745                 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2746                 if (!($start === false)) {
2747                         $image = Images::getInfoFromURLCached($url);
2748                         if ($image) {
2749                                 // If image cache is activated, then use the following sizes:
2750                                 // thumb  (150), small (340), medium (600) and large (1024)
2751                                 if (!Config::get("system", "proxy_disabled")) {
2752                                         $media_url = ProxyUtils::proxifyUrl($url);
2753
2754                                         $sizes = [];
2755                                         $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2756                                         $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2757
2758                                         if (($image[0] > 150) || ($image[1] > 150)) {
2759                                                 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2760                                                 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2761                                         }
2762
2763                                         $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2764                                         $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2765
2766                                         if (($image[0] > 600) || ($image[1] > 600)) {
2767                                                 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2768                                                 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2769                                         }
2770                                 } else {
2771                                         $media_url = $url;
2772                                         $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2773                                 }
2774
2775                                 $entities["media"][] = [
2776                                                         "id" => $start+1,
2777                                                         "id_str" => (string) ($start + 1),
2778                                                         "indices" => [$start, $start+strlen($url)],
2779                                                         "media_url" => Strings::normaliseLink($media_url),
2780                                                         "media_url_https" => $media_url,
2781                                                         "url" => $url,
2782                                                         "display_url" => $display_url,
2783                                                         "expanded_url" => $url,
2784                                                         "ext_alt_text" => $ext_alt_text,
2785                                                         "type" => "photo",
2786                                                         "sizes" => $sizes];
2787                         }
2788                         $offset = $start + 1;
2789                 }
2790         }
2791
2792         return $entities;
2793 }
2794
2795 /**
2796  *
2797  * @param array $item
2798  * @param string $text
2799  *
2800  * @return string
2801  */
2802 function api_format_items_embeded_images($item, $text)
2803 {
2804         $text = preg_replace_callback(
2805                 '|data:image/([^;]+)[^=]+=*|m',
2806                 function () use ($item) {
2807                         return DI::baseUrl() . '/display/' . $item['guid'];
2808                 },
2809                 $text
2810         );
2811         return $text;
2812 }
2813
2814 /**
2815  * @brief return <a href='url'>name</a> as array
2816  *
2817  * @param string $txt text
2818  * @return array
2819  *                      'name' => 'name',
2820  *                      'url => 'url'
2821  */
2822 function api_contactlink_to_array($txt)
2823 {
2824         $match = [];
2825         $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2826         if ($r && count($match)==3) {
2827                 $res = [
2828                         'name' => $match[2],
2829                         'url' => $match[1]
2830                 ];
2831         } else {
2832                 $res = [
2833                         'name' => $txt,
2834                         'url' => ""
2835                 ];
2836         }
2837         return $res;
2838 }
2839
2840
2841 /**
2842  * @brief return likes, dislikes and attend status for item
2843  *
2844  * @param array  $item array
2845  * @param string $type Return type (atom, rss, xml, json)
2846  *
2847  * @return array
2848  *            likes => int count,
2849  *            dislikes => int count
2850  * @throws BadRequestException
2851  * @throws ImagickException
2852  * @throws InternalServerErrorException
2853  * @throws UnauthorizedException
2854  */
2855 function api_format_items_activities($item, $type = "json")
2856 {
2857         $a = DI::app();
2858
2859         $activities = [
2860                 'like' => [],
2861                 'dislike' => [],
2862                 'attendyes' => [],
2863                 'attendno' => [],
2864                 'attendmaybe' => [],
2865                 'announce' => [],
2866         ];
2867
2868         $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2869         $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2870
2871         while ($parent_item = Item::fetch($ret)) {
2872                 // not used as result should be structured like other user data
2873                 //builtin_activity_puller($i, $activities);
2874
2875                 // get user data and add it to the array of the activity
2876                 $user = api_get_user($a, $parent_item['author-id']);
2877                 switch ($parent_item['verb']) {
2878                         case Activity::LIKE:
2879                                 $activities['like'][] = $user;
2880                                 break;
2881                         case Activity::DISLIKE:
2882                                 $activities['dislike'][] = $user;
2883                                 break;
2884                         case Activity::ATTEND:
2885                                 $activities['attendyes'][] = $user;
2886                                 break;
2887                         case Activity::ATTENDNO:
2888                                 $activities['attendno'][] = $user;
2889                                 break;
2890                         case Activity::ATTENDMAYBE:
2891                                 $activities['attendmaybe'][] = $user;
2892                                 break;
2893                         case Activity::ANNOUNCE:
2894                                 $activities['announce'][] = $user;
2895                                 break;
2896                         default:
2897                                 break;
2898                 }
2899         }
2900
2901         DBA::close($ret);
2902
2903         if ($type == "xml") {
2904                 $xml_activities = [];
2905                 foreach ($activities as $k => $v) {
2906                         // change xml element from "like" to "friendica:like"
2907                         $xml_activities["friendica:".$k] = $v;
2908                         // add user data into xml output
2909                         $k_user = 0;
2910                         foreach ($v as $user) {
2911                                 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2912                         }
2913                 }
2914                 $activities = $xml_activities;
2915         }
2916
2917         return $activities;
2918 }
2919
2920
2921 /**
2922  * @brief return data from profiles
2923  *
2924  * @param array $profile_row array containing data from db table 'profile'
2925  * @return array
2926  * @throws InternalServerErrorException
2927  */
2928 function api_format_items_profiles($profile_row)
2929 {
2930         $profile = [
2931                 'profile_id'       => $profile_row['id'],
2932                 'profile_name'     => $profile_row['profile-name'],
2933                 'is_default'       => $profile_row['is-default'] ? true : false,
2934                 'hide_friends'     => $profile_row['hide-friends'] ? true : false,
2935                 'profile_photo'    => $profile_row['photo'],
2936                 'profile_thumb'    => $profile_row['thumb'],
2937                 'publish'          => $profile_row['publish'] ? true : false,
2938                 'net_publish'      => $profile_row['net-publish'] ? true : false,
2939                 'description'      => $profile_row['pdesc'],
2940                 'date_of_birth'    => $profile_row['dob'],
2941                 'address'          => $profile_row['address'],
2942                 'city'             => $profile_row['locality'],
2943                 'region'           => $profile_row['region'],
2944                 'postal_code'      => $profile_row['postal-code'],
2945                 'country'          => $profile_row['country-name'],
2946                 'hometown'         => $profile_row['hometown'],
2947                 'gender'           => $profile_row['gender'],
2948                 'marital'          => $profile_row['marital'],
2949                 'marital_with'     => $profile_row['with'],
2950                 'marital_since'    => $profile_row['howlong'],
2951                 'sexual'           => $profile_row['sexual'],
2952                 'politic'          => $profile_row['politic'],
2953                 'religion'         => $profile_row['religion'],
2954                 'public_keywords'  => $profile_row['pub_keywords'],
2955                 'private_keywords' => $profile_row['prv_keywords'],
2956                 'likes'            => BBCode::convert(api_clean_plain_items($profile_row['likes'])    , false, 2),
2957                 'dislikes'         => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2958                 'about'            => BBCode::convert(api_clean_plain_items($profile_row['about'])    , false, 2),
2959                 'music'            => BBCode::convert(api_clean_plain_items($profile_row['music'])    , false, 2),
2960                 'book'             => BBCode::convert(api_clean_plain_items($profile_row['book'])     , false, 2),
2961                 'tv'               => BBCode::convert(api_clean_plain_items($profile_row['tv'])       , false, 2),
2962                 'film'             => BBCode::convert(api_clean_plain_items($profile_row['film'])     , false, 2),
2963                 'interest'         => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2964                 'romance'          => BBCode::convert(api_clean_plain_items($profile_row['romance'])  , false, 2),
2965                 'work'             => BBCode::convert(api_clean_plain_items($profile_row['work'])     , false, 2),
2966                 'education'        => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2967                 'social_networks'  => BBCode::convert(api_clean_plain_items($profile_row['contact'])  , false, 2),
2968                 'homepage'         => $profile_row['homepage'],
2969                 'users'            => null
2970         ];
2971         return $profile;
2972 }
2973
2974 /**
2975  * @brief format items to be returned by api
2976  *
2977  * @param array  $items       array of items
2978  * @param array  $user_info
2979  * @param bool   $filter_user filter items by $user_info
2980  * @param string $type        Return type (atom, rss, xml, json)
2981  * @return array
2982  * @throws BadRequestException
2983  * @throws ImagickException
2984  * @throws InternalServerErrorException
2985  * @throws UnauthorizedException
2986  */
2987 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2988 {
2989         $a = Friendica\DI::app();
2990
2991         $ret = [];
2992
2993         foreach ((array)$items as $item) {
2994                 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2995
2996                 // Look if the posts are matching if they should be filtered by user id
2997                 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2998                         continue;
2999                 }
3000
3001                 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
3002
3003                 $ret[] = $status;
3004         }
3005
3006         return $ret;
3007 }
3008
3009 /**
3010  * @param array  $item       Item record
3011  * @param string $type       Return format (atom, rss, xml, json)
3012  * @param array $status_user User record of the item author, can be provided by api_item_get_user()
3013  * @param array $author_user User record of the item author, can be provided by api_item_get_user()
3014  * @param array $owner_user  User record of the item owner, can be provided by api_item_get_user()
3015  * @return array API-formatted status
3016  * @throws BadRequestException
3017  * @throws ImagickException
3018  * @throws InternalServerErrorException
3019  * @throws UnauthorizedException
3020  */
3021 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3022 {
3023         $a = Friendica\DI::app();
3024
3025         if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3026                 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3027         }
3028
3029         localize_item($item);
3030
3031         $in_reply_to = api_in_reply_to($item);
3032
3033         $converted = api_convert_item($item);
3034
3035         if ($type == "xml") {
3036                 $geo = "georss:point";
3037         } else {
3038                 $geo = "geo";
3039         }
3040
3041         $status = [
3042                 'text'          => $converted["text"],
3043                 'truncated' => false,
3044                 'created_at'=> api_date($item['created']),
3045                 'in_reply_to_status_id' => $in_reply_to['status_id'],
3046                 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3047                 'source'    => (($item['app']) ? $item['app'] : 'web'),
3048                 'id'            => intval($item['id']),
3049                 'id_str'        => (string) intval($item['id']),
3050                 'in_reply_to_user_id' => $in_reply_to['user_id'],
3051                 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3052                 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3053                 $geo => null,
3054                 'favorited' => $item['starred'] ? true : false,
3055                 'user' =>  $status_user,
3056                 'friendica_author' => $author_user,
3057                 'friendica_owner' => $owner_user,
3058                 'friendica_private' => $item['private'] == 1,
3059                 //'entities' => NULL,
3060                 'statusnet_html' => $converted["html"],
3061                 'statusnet_conversation_id' => $item['parent'],
3062                 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3063                 'friendica_activities' => api_format_items_activities($item, $type),
3064                 'friendica_title' => $item['title'],
3065                 'friendica_html' => BBCode::convert($item['body'], false)
3066         ];
3067
3068         if (count($converted["attachments"]) > 0) {
3069                 $status["attachments"] = $converted["attachments"];
3070         }
3071
3072         if (count($converted["entities"]) > 0) {
3073                 $status["entities"] = $converted["entities"];
3074         }
3075
3076         if ($status["source"] == 'web') {
3077                 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3078         } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3079                 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3080         }
3081
3082         $retweeted_item = [];
3083         $quoted_item = [];
3084
3085         if ($item["id"] == $item["parent"]) {
3086                 $body = $item['body'];
3087                 $retweeted_item = api_share_as_retweet($item);
3088                 if ($body != $item['body']) {
3089                         $quoted_item = $retweeted_item;
3090                         $retweeted_item = [];
3091                 }
3092         }
3093
3094         if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3095                 $announce = api_get_announce($item);
3096                 if (!empty($announce)) {
3097                         $retweeted_item = $item;
3098                         $item = $announce;
3099                         $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3100                 }
3101         }
3102
3103         if (!empty($quoted_item)) {
3104                 if ($quoted_item['id'] != $item['id']) {
3105                         $quoted_status = api_format_item($quoted_item);
3106                         /// @todo Only remove the attachments that are also contained in the quotes status
3107                         unset($status['attachments']);
3108                         unset($status['entities']);
3109                 } else {
3110                         $conv_quoted = api_convert_item($quoted_item);
3111                         $quoted_status = $status;
3112                         unset($quoted_status['attachments']);
3113                         unset($quoted_status['entities']);
3114                         unset($quoted_status['statusnet_conversation_id']);
3115                         $quoted_status['text'] = $conv_quoted['text'];
3116                         $quoted_status['statusnet_html'] = $conv_quoted['html'];
3117                         try {
3118                                 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3119                         } catch (BadRequestException $e) {
3120                                 // user not found. should be found?
3121                                 /// @todo check if the user should be always found
3122                                 $quoted_status["user"] = [];
3123                         }
3124                 }
3125                 unset($quoted_status['friendica_author']);
3126                 unset($quoted_status['friendica_owner']);
3127                 unset($quoted_status['friendica_activities']);
3128                 unset($quoted_status['friendica_private']);
3129         }
3130
3131         if (!empty($retweeted_item)) {
3132                 $retweeted_status = $status;
3133                 unset($retweeted_status['friendica_author']);
3134                 unset($retweeted_status['friendica_owner']);
3135                 unset($retweeted_status['friendica_activities']);
3136                 unset($retweeted_status['friendica_private']);
3137                 unset($retweeted_status['statusnet_conversation_id']);
3138                 $status['user'] = $status['friendica_owner'];
3139                 try {
3140                         $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3141                 } catch (BadRequestException $e) {
3142                         // user not found. should be found?
3143                         /// @todo check if the user should be always found
3144                         $retweeted_status["user"] = [];
3145                 }
3146
3147                 $rt_converted = api_convert_item($retweeted_item);
3148
3149                 $retweeted_status['text'] = $rt_converted["text"];
3150                 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3151                 $retweeted_status['created_at'] =  api_date($retweeted_item['created']);
3152
3153                 if (!empty($quoted_status)) {
3154                         $retweeted_status['quoted_status'] = $quoted_status;
3155                 }
3156
3157                 $status['friendica_author'] = $retweeted_status['user'];
3158                 $status['retweeted_status'] = $retweeted_status;
3159         } elseif (!empty($quoted_status)) {
3160                 $root_status = api_convert_item($item);
3161
3162                 $status['text'] = $root_status["text"];
3163                 $status['statusnet_html'] = $root_status["html"];
3164                 $status['quoted_status'] = $quoted_status;
3165         }
3166
3167         // "uid" and "self" are only needed for some internal stuff, so remove it from here
3168         unset($status["user"]["uid"]);
3169         unset($status["user"]["self"]);
3170
3171         if ($item["coord"] != "") {
3172                 $coords = explode(' ', $item["coord"]);
3173                 if (count($coords) == 2) {
3174                         if ($type == "json") {
3175                                 $status["geo"] = ['type' => 'Point',
3176                                         'coordinates' => [(float) $coords[0],
3177                                                 (float) $coords[1]]];
3178                         } else {// Not sure if this is the official format - if someone founds a documentation we can check
3179                                 $status["georss:point"] = $item["coord"];
3180                         }
3181                 }
3182         }
3183
3184         return $status;
3185 }
3186
3187 /**
3188  * Returns the remaining number of API requests available to the user before the API limit is reached.
3189  *
3190  * @param string $type Return type (atom, rss, xml, json)
3191  *
3192  * @return array|string
3193  * @throws Exception
3194  */
3195 function api_account_rate_limit_status($type)
3196 {
3197         if ($type == "xml") {
3198                 $hash = [
3199                                 'remaining-hits' => '150',
3200                                 '@attributes' => ["type" => "integer"],
3201                                 'hourly-limit' => '150',
3202                                 '@attributes2' => ["type" => "integer"],
3203                                 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3204                                 '@attributes3' => ["type" => "datetime"],
3205                                 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3206                                 '@attributes4' => ["type" => "integer"],
3207                         ];
3208         } else {
3209                 $hash = [
3210                                 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3211                                 'remaining_hits' => '150',
3212                                 'hourly_limit' => '150',
3213                                 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3214                         ];
3215         }
3216
3217         return api_format_data('hash', $type, ['hash' => $hash]);
3218 }
3219
3220 /// @TODO move to top of file or somewhere better
3221 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3222
3223 /**
3224  * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3225  *
3226  * @param string $type Return type (atom, rss, xml, json)
3227  *
3228  * @return array|string
3229  */
3230 function api_help_test($type)
3231 {
3232         if ($type == 'xml') {
3233                 $ok = "true";
3234         } else {
3235                 $ok = "ok";
3236         }
3237
3238         return api_format_data('ok', $type, ["ok" => $ok]);
3239 }
3240
3241 /// @TODO move to top of file or somewhere better
3242 api_register_func('api/help/test', 'api_help_test', false);
3243
3244 /**
3245  * Returns all lists the user subscribes to.
3246  *
3247  * @param string $type Return type (atom, rss, xml, json)
3248  *
3249  * @return array|string
3250  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3251  */
3252 function api_lists_list($type)
3253 {
3254         $ret = [];
3255         /// @TODO $ret is not filled here?
3256         return api_format_data('lists', $type, ["lists_list" => $ret]);
3257 }
3258
3259 /// @TODO move to top of file or somewhere better
3260 api_register_func('api/lists/list', 'api_lists_list', true);
3261 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3262
3263 /**
3264  * Returns all groups the user owns.
3265  *
3266  * @param string $type Return type (atom, rss, xml, json)
3267  *
3268  * @return array|string
3269  * @throws BadRequestException
3270  * @throws ForbiddenException
3271  * @throws ImagickException
3272  * @throws InternalServerErrorException
3273  * @throws UnauthorizedException
3274  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3275  */
3276 function api_lists_ownerships($type)
3277 {
3278         $a = DI::app();
3279
3280         if (api_user() === false) {
3281                 throw new ForbiddenException();
3282         }
3283
3284         // params
3285         $user_info = api_get_user($a);
3286         $uid = $user_info['uid'];
3287
3288         $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3289
3290         // loop through all groups
3291         $lists = [];
3292         foreach ($groups as $group) {
3293                 if ($group['visible']) {
3294                         $mode = 'public';
3295                 } else {
3296                         $mode = 'private';
3297                 }
3298                 $lists[] = [
3299                         'name' => $group['name'],
3300                         'id' => intval($group['id']),
3301                         'id_str' => (string) $group['id'],
3302                         'user' => $user_info,
3303                         'mode' => $mode
3304                 ];
3305         }
3306         return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3307 }
3308
3309 /// @TODO move to top of file or somewhere better
3310 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3311
3312 /**
3313  * Returns recent statuses from users in the specified group.
3314  *
3315  * @param string $type Return type (atom, rss, xml, json)
3316  *
3317  * @return array|string
3318  * @throws BadRequestException
3319  * @throws ForbiddenException
3320  * @throws ImagickException
3321  * @throws InternalServerErrorException
3322  * @throws UnauthorizedException
3323  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3324  */
3325 function api_lists_statuses($type)
3326 {
3327         $a = DI::app();
3328
3329         $user_info = api_get_user($a);
3330         if (api_user() === false || $user_info === false) {
3331                 throw new ForbiddenException();
3332         }
3333
3334         unset($_REQUEST["user_id"]);
3335         unset($_GET["user_id"]);
3336
3337         unset($_REQUEST["screen_name"]);
3338         unset($_GET["screen_name"]);
3339
3340         if (empty($_REQUEST['list_id'])) {
3341                 throw new BadRequestException('list_id not specified');
3342         }
3343
3344         // params
3345         $count = $_REQUEST['count'] ?? 20;
3346         $page = $_REQUEST['page'] ?? 1;
3347         $since_id = $_REQUEST['since_id'] ?? 0;
3348         $max_id = $_REQUEST['max_id'] ?? 0;
3349         $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3350         $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3351
3352         $start = max(0, ($page - 1) * $count);
3353
3354         $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3355                 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3356
3357         if ($max_id > 0) {
3358                 $condition[0] .= " AND `item`.`id` <= ?";
3359                 $condition[] = $max_id;
3360         }
3361         if ($exclude_replies > 0) {
3362                 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3363         }
3364         if ($conversation_id > 0) {
3365                 $condition[0] .= " AND `item`.`parent` = ?";
3366                 $condition[] = $conversation_id;
3367         }
3368
3369         $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3370         $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3371
3372         $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3373
3374         $data = ['status' => $items];
3375         switch ($type) {
3376                 case "atom":
3377                         break;
3378                 case "rss":
3379                         $data = api_rss_extra($a, $data, $user_info);
3380                         break;
3381         }
3382
3383         return api_format_data("statuses", $type, $data);
3384 }
3385
3386 /// @TODO move to top of file or somewhere better
3387 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3388
3389 /**
3390  * Considers friends and followers lists to be private and won't return
3391  * anything if any user_id parameter is passed.
3392  *
3393  * @brief Returns either the friends of the follower list
3394  *
3395  * @param string $qtype Either "friends" or "followers"
3396  * @return boolean|array
3397  * @throws BadRequestException
3398  * @throws ForbiddenException
3399  * @throws ImagickException
3400  * @throws InternalServerErrorException
3401  * @throws UnauthorizedException
3402  */
3403 function api_statuses_f($qtype)
3404 {
3405         $a = DI::app();
3406
3407         if (api_user() === false) {
3408                 throw new ForbiddenException();
3409         }
3410
3411         // pagination
3412         $count = $_GET['count'] ?? 20;
3413         $page = $_GET['page'] ?? 1;
3414
3415         $start = max(0, ($page - 1) * $count);
3416
3417         $user_info = api_get_user($a);
3418
3419         if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3420                 /* this is to stop Hotot to load friends multiple times
3421                 *  I'm not sure if I'm missing return something or
3422                 *  is a bug in hotot. Workaround, meantime
3423                 */
3424
3425                 /*$ret=Array();
3426                 return array('$users' => $ret);*/
3427                 return false;
3428         }
3429
3430         $sql_extra = '';
3431         if ($qtype == 'friends') {
3432                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3433         } elseif ($qtype == 'followers') {
3434                 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3435         }
3436
3437         // friends and followers only for self
3438         if ($user_info['self'] == 0) {
3439                 $sql_extra = " AND false ";
3440         }
3441
3442         if ($qtype == 'blocks') {
3443                 $sql_filter = 'AND `blocked` AND NOT `pending`';
3444         } elseif ($qtype == 'incoming') {
3445                 $sql_filter = 'AND `pending`';
3446         } else {
3447                 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3448         }
3449
3450         $r = q(
3451                 "SELECT `nurl`
3452                 FROM `contact`
3453                 WHERE `uid` = %d
3454                 AND NOT `self`
3455                 $sql_filter
3456                 $sql_extra
3457                 ORDER BY `nick`
3458                 LIMIT %d, %d",
3459                 intval(api_user()),
3460                 intval($start),
3461                 intval($count)
3462         );
3463
3464         $ret = [];
3465         foreach ($r as $cid) {
3466                 $user = api_get_user($a, $cid['nurl']);
3467                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3468                 unset($user["uid"]);
3469                 unset($user["self"]);
3470
3471                 if ($user) {
3472                         $ret[] = $user;
3473                 }
3474         }
3475
3476         return ['user' => $ret];
3477 }
3478
3479
3480 /**
3481  * Returns the user's friends.
3482  *
3483  * @brief      Returns the list of friends of the provided user
3484  *
3485  * @deprecated By Twitter API in favor of friends/list
3486  *
3487  * @param string $type Either "json" or "xml"
3488  * @return boolean|string|array
3489  * @throws BadRequestException
3490  * @throws ForbiddenException
3491  */
3492 function api_statuses_friends($type)
3493 {
3494         $data =  api_statuses_f("friends");
3495         if ($data === false) {
3496                 return false;
3497         }
3498         return api_format_data("users", $type, $data);
3499 }
3500
3501 /**
3502  * Returns the user's followers.
3503  *
3504  * @brief      Returns the list of followers of the provided user
3505  *
3506  * @deprecated By Twitter API in favor of friends/list
3507  *
3508  * @param string $type Either "json" or "xml"
3509  * @return boolean|string|array
3510  * @throws BadRequestException
3511  * @throws ForbiddenException
3512  */
3513 function api_statuses_followers($type)
3514 {
3515         $data = api_statuses_f("followers");
3516         if ($data === false) {
3517                 return false;
3518         }
3519         return api_format_data("users", $type, $data);
3520 }
3521
3522 /// @TODO move to top of file or somewhere better
3523 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3524 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3525
3526 /**
3527  * Returns the list of blocked users
3528  *
3529  * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3530  *
3531  * @param string $type Either "json" or "xml"
3532  *
3533  * @return boolean|string|array
3534  * @throws BadRequestException
3535  * @throws ForbiddenException
3536  */
3537 function api_blocks_list($type)
3538 {
3539         $data =  api_statuses_f('blocks');
3540         if ($data === false) {
3541                 return false;
3542         }
3543         return api_format_data("users", $type, $data);
3544 }
3545
3546 /// @TODO move to top of file or somewhere better
3547 api_register_func('api/blocks/list', 'api_blocks_list', true);
3548
3549 /**
3550  * Returns the list of pending users IDs
3551  *
3552  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3553  *
3554  * @param string $type Either "json" or "xml"
3555  *
3556  * @return boolean|string|array
3557  * @throws BadRequestException
3558  * @throws ForbiddenException
3559  */
3560 function api_friendships_incoming($type)
3561 {
3562         $data =  api_statuses_f('incoming');
3563         if ($data === false) {
3564                 return false;
3565         }
3566
3567         $ids = [];
3568         foreach ($data['user'] as $user) {
3569                 $ids[] = $user['id'];
3570         }
3571
3572         return api_format_data("ids", $type, ['id' => $ids]);
3573 }
3574
3575 /// @TODO move to top of file or somewhere better
3576 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3577
3578 /**
3579  * Returns the instance's configuration information.
3580  *
3581  * @param string $type Return type (atom, rss, xml, json)
3582  *
3583  * @return array|string
3584  * @throws InternalServerErrorException
3585  */
3586 function api_statusnet_config($type)
3587 {
3588         $name      = Config::get('config', 'sitename');
3589         $server    = DI::baseUrl()->getHostname();
3590         $logo      = DI::baseUrl() . '/images/friendica-64.png';
3591         $email     = Config::get('config', 'admin_email');
3592         $closed    = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3593         $private   = Config::get('system', 'block_public') ? 'true' : 'false';
3594         $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3595         $ssl       = Config::get('system', 'have_ssl') ? 'true' : 'false';
3596         $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3597
3598         $config = [
3599                 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3600                         'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3601                         'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3602                         'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3603                         'shorturllength' => '30',
3604                         'friendica' => [
3605                                         'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3606                                         'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3607                                         'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3608                                         'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3609                                         ]
3610                 ],
3611         ];
3612
3613         return api_format_data('config', $type, ['config' => $config]);
3614 }
3615
3616 /// @TODO move to top of file or somewhere better
3617 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3618 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3619
3620 /**
3621  *
3622  * @param string $type Return type (atom, rss, xml, json)
3623  *
3624  * @return array|string
3625  */
3626 function api_statusnet_version($type)
3627 {
3628         // liar
3629         $fake_statusnet_version = "0.9.7";
3630
3631         return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3632 }
3633
3634 /// @TODO move to top of file or somewhere better
3635 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3636 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3637
3638 /**
3639  *
3640  * @param string $type Return type (atom, rss, xml, json)
3641  *
3642  * @param int $rel A contact relationship constant
3643  * @return array|string|void
3644  * @throws BadRequestException
3645  * @throws ForbiddenException
3646  * @throws ImagickException
3647  * @throws InternalServerErrorException
3648  * @throws UnauthorizedException
3649  * @todo use api_format_data() to return data
3650  */
3651 function api_ff_ids($type, int $rel)
3652 {
3653         if (!api_user()) {
3654                 throw new ForbiddenException();
3655         }
3656
3657         $a = DI::app();
3658
3659         api_get_user($a);
3660
3661         $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3662
3663         $contacts = DBA::p("SELECT `pcontact`.`id`
3664                 FROM `contact`
3665                 INNER JOIN `contact` AS `pcontact`
3666                     ON `contact`.`nurl` = `pcontact`.`nurl`
3667                     AND `pcontact`.`uid` = 0
3668                 WHERE `contact`.`uid` = ?
3669                 AND NOT `contact`.`self`
3670                 AND `contact`.`rel` IN (?, ?)",
3671                 api_user(),
3672                 $rel,
3673                 Contact::FRIEND
3674         );
3675
3676         $ids = [];
3677         foreach (DBA::toArray($contacts) as $contact) {
3678                 if ($stringify_ids) {
3679                         $ids[] = $contact['id'];
3680                 } else {
3681                         $ids[] = intval($contact['id']);
3682                 }
3683         }
3684
3685         return api_format_data('ids', $type, ['id' => $ids]);
3686 }
3687
3688 /**
3689  * Returns the ID of every user the user is following.
3690  *
3691  * @param string $type Return type (atom, rss, xml, json)
3692  *
3693  * @return array|string
3694  * @throws BadRequestException
3695  * @throws ForbiddenException
3696  * @throws ImagickException
3697  * @throws InternalServerErrorException
3698  * @throws UnauthorizedException
3699  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3700  */
3701 function api_friends_ids($type)
3702 {
3703         return api_ff_ids($type, Contact::SHARING);
3704 }
3705
3706 /**
3707  * Returns the ID of every user following the user.
3708  *
3709  * @param string $type Return type (atom, rss, xml, json)
3710  *
3711  * @return array|string
3712  * @throws BadRequestException
3713  * @throws ForbiddenException
3714  * @throws ImagickException
3715  * @throws InternalServerErrorException
3716  * @throws UnauthorizedException
3717  * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3718  */
3719 function api_followers_ids($type)
3720 {
3721         return api_ff_ids($type, Contact::FOLLOWER);
3722 }
3723
3724 /// @TODO move to top of file or somewhere better
3725 api_register_func('api/friends/ids', 'api_friends_ids', true);
3726 api_register_func('api/followers/ids', 'api_followers_ids', true);
3727
3728 /**
3729  * Sends a new direct message.
3730  *
3731  * @param string $type Return type (atom, rss, xml, json)
3732  *
3733  * @return array|string
3734  * @throws BadRequestException
3735  * @throws ForbiddenException
3736  * @throws ImagickException
3737  * @throws InternalServerErrorException
3738  * @throws NotFoundException
3739  * @throws UnauthorizedException
3740  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3741  */
3742 function api_direct_messages_new($type)
3743 {
3744         $a = DI::app();
3745
3746         if (api_user() === false) {
3747                 throw new ForbiddenException();
3748         }
3749
3750         if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3751                 return;
3752         }
3753
3754         $sender = api_get_user($a);
3755
3756         $recipient = null;
3757         if (!empty($_POST['screen_name'])) {
3758                 $r = q(
3759                         "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3760                         intval(api_user()),
3761                         DBA::escape($_POST['screen_name'])
3762                 );
3763
3764                 if (DBA::isResult($r)) {
3765                         // Selecting the id by priority, friendica first
3766                         api_best_nickname($r);
3767
3768                         $recipient = api_get_user($a, $r[0]['nurl']);
3769                 }
3770         } else {
3771                 $recipient = api_get_user($a, $_POST['user_id']);
3772         }
3773
3774         if (empty($recipient)) {
3775                 throw new NotFoundException('Recipient not found');
3776         }
3777
3778         $replyto = '';
3779         if (!empty($_REQUEST['replyto'])) {
3780                 $r = q(
3781                         'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3782                         intval(api_user()),
3783                         intval($_REQUEST['replyto'])
3784                 );
3785                 $replyto = $r[0]['parent-uri'];
3786                 $sub     = $r[0]['title'];
3787         } else {
3788                 if (!empty($_REQUEST['title'])) {
3789                         $sub = $_REQUEST['title'];
3790                 } else {
3791                         $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3792                 }
3793         }
3794
3795         $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3796
3797         if ($id > -1) {
3798                 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3799                 $ret = api_format_messages($r[0], $recipient, $sender);
3800         } else {
3801                 $ret = ["error"=>$id];
3802         }
3803
3804         $data = ['direct_message'=>$ret];
3805
3806         switch ($type) {
3807                 case "atom":
3808                         break;
3809                 case "rss":
3810                         $data = api_rss_extra($a, $data, $sender);
3811                         break;
3812         }
3813
3814         return api_format_data("direct-messages", $type, $data);
3815 }
3816
3817 /// @TODO move to top of file or somewhere better
3818 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3819
3820 /**
3821  * Destroys a direct message.
3822  *
3823  * @brief delete a direct_message from mail table through api
3824  *
3825  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3826  * @return string|array
3827  * @throws BadRequestException
3828  * @throws ForbiddenException
3829  * @throws ImagickException
3830  * @throws InternalServerErrorException
3831  * @throws UnauthorizedException
3832  * @see   https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3833  */
3834 function api_direct_messages_destroy($type)
3835 {
3836         $a = DI::app();
3837
3838         if (api_user() === false) {
3839                 throw new ForbiddenException();
3840         }
3841
3842         // params
3843         $user_info = api_get_user($a);
3844         //required
3845         $id = $_REQUEST['id'] ?? 0;
3846         // optional
3847         $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3848         $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3849         /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3850
3851         $uid = $user_info['uid'];
3852         // error if no id or parenturi specified (for clients posting parent-uri as well)
3853         if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3854                 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3855                 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3856         }
3857
3858         // BadRequestException if no id specified (for clients using Twitter API)
3859         if ($id == 0) {
3860                 throw new BadRequestException('Message id not specified');
3861         }
3862
3863         // add parent-uri to sql command if specified by calling app
3864         $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3865
3866         // get data of the specified message id
3867         $r = q(
3868                 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3869                 intval($uid),
3870                 intval($id)
3871         );
3872
3873         // error message if specified id is not in database
3874         if (!DBA::isResult($r)) {
3875                 if ($verbose == "true") {
3876                         $answer = ['result' => 'error', 'message' => 'message id not in database'];
3877                         return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3878                 }
3879                 /// @todo BadRequestException ok for Twitter API clients?
3880                 throw new BadRequestException('message id not in database');
3881         }
3882
3883         // delete message
3884         $result = q(
3885                 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3886                 intval($uid),
3887                 intval($id)
3888         );
3889
3890         if ($verbose == "true") {
3891                 if ($result) {
3892                         // return success
3893                         $answer = ['result' => 'ok', 'message' => 'message deleted'];
3894                         return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3895                 } else {
3896                         $answer = ['result' => 'error', 'message' => 'unknown error'];
3897                         return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3898                 }
3899         }
3900         /// @todo return JSON data like Twitter API not yet implemented
3901 }
3902
3903 /// @TODO move to top of file or somewhere better
3904 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3905
3906 /**
3907  * Unfollow Contact
3908  *
3909  * @brief unfollow contact
3910  *
3911  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3912  * @return string|array
3913  * @throws BadRequestException
3914  * @throws ForbiddenException
3915  * @throws ImagickException
3916  * @throws InternalServerErrorException
3917  * @throws NotFoundException
3918  * @see   https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3919  */
3920 function api_friendships_destroy($type)
3921 {
3922         $uid = api_user();
3923
3924         if ($uid === false) {
3925                 throw new ForbiddenException();
3926         }
3927
3928         $contact_id = $_REQUEST['user_id'] ?? 0;
3929
3930         if (empty($contact_id)) {
3931                 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3932                 throw new BadRequestException("no user_id specified");
3933         }
3934
3935         // Get Contact by given id
3936         $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3937
3938         if(!DBA::isResult($contact)) {
3939                 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3940                 throw new NotFoundException("no contact found to given ID");
3941         }
3942
3943         $url = $contact["url"];
3944
3945         $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3946                         $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3947                         Strings::normaliseLink($url), $url];
3948         $contact = DBA::selectFirst('contact', [], $condition);
3949
3950         if (!DBA::isResult($contact)) {
3951                 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3952                 throw new NotFoundException("Not following Contact");
3953         }
3954
3955         if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3956                 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3957                 throw new ExpectationFailedException("Not supported");
3958         }
3959
3960         $dissolve = ($contact['rel'] == Contact::SHARING);
3961
3962         $owner = User::getOwnerDataById($uid);
3963         if ($owner) {
3964                 Contact::terminateFriendship($owner, $contact, $dissolve);
3965         }
3966         else {
3967                 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3968                 throw new NotFoundException("Error Processing Request");
3969         }
3970
3971         // Sharing-only contacts get deleted as there no relationship any more
3972         if ($dissolve) {
3973                 Contact::remove($contact['id']);
3974         } else {
3975                 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3976         }
3977
3978         // "uid" and "self" are only needed for some internal stuff, so remove it from here
3979         unset($contact["uid"]);
3980         unset($contact["self"]);
3981
3982         // Set screen_name since Twidere requests it
3983         $contact["screen_name"] = $contact["nick"];
3984
3985         return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3986 }
3987 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3988
3989 /**
3990  *
3991  * @param string $type Return type (atom, rss, xml, json)
3992  * @param string $box
3993  * @param string $verbose
3994  *
3995  * @return array|string
3996  * @throws BadRequestException
3997  * @throws ForbiddenException
3998  * @throws ImagickException
3999  * @throws InternalServerErrorException
4000  * @throws UnauthorizedException
4001  */
4002 function api_direct_messages_box($type, $box, $verbose)
4003 {
4004         $a = DI::app();
4005         if (api_user() === false) {
4006                 throw new ForbiddenException();
4007         }
4008         // params
4009         $count = $_GET['count'] ?? 20;
4010         $page = $_REQUEST['page'] ?? 1;
4011
4012         $since_id = $_REQUEST['since_id'] ?? 0;
4013         $max_id = $_REQUEST['max_id'] ?? 0;
4014
4015         $user_id = $_REQUEST['user_id'] ?? '';
4016         $screen_name = $_REQUEST['screen_name'] ?? '';
4017
4018         //  caller user info
4019         unset($_REQUEST["user_id"]);
4020         unset($_GET["user_id"]);
4021
4022         unset($_REQUEST["screen_name"]);
4023         unset($_GET["screen_name"]);
4024
4025         $user_info = api_get_user($a);
4026         if ($user_info === false) {
4027                 throw new ForbiddenException();
4028         }
4029         $profile_url = $user_info["url"];
4030
4031         // pagination
4032         $start = max(0, ($page - 1) * $count);
4033
4034         $sql_extra = "";
4035
4036         // filters
4037         if ($box=="sentbox") {
4038                 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
4039         } elseif ($box == "conversation") {
4040                 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '')  . "'";
4041         } elseif ($box == "all") {
4042                 $sql_extra = "true";
4043         } elseif ($box == "inbox") {
4044                 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
4045         }
4046
4047         if ($max_id > 0) {
4048                 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
4049         }
4050
4051         if ($user_id != "") {
4052                 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4053         } elseif ($screen_name !="") {
4054                 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4055         }
4056
4057         $r = q(
4058                 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`id` DESC LIMIT %d,%d",
4059                 intval(api_user()),
4060                 intval($since_id),
4061                 intval($start),
4062                 intval($count)
4063         );
4064         if ($verbose == "true" && !DBA::isResult($r)) {
4065                 $answer = ['result' => 'error', 'message' => 'no mails available'];
4066                 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4067         }
4068
4069         $ret = [];
4070         foreach ($r as $item) {
4071                 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4072                         $recipient = $user_info;
4073                         $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4074                 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4075                         $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4076                         $sender = $user_info;
4077                 }
4078
4079                 if (isset($recipient) && isset($sender)) {
4080                         $ret[] = api_format_messages($item, $recipient, $sender);
4081                 }
4082         }
4083
4084
4085         $data = ['direct_message' => $ret];
4086         switch ($type) {
4087                 case "atom":
4088                         break;
4089                 case "rss":
4090                         $data = api_rss_extra($a, $data, $user_info);
4091                         break;
4092         }
4093
4094         return api_format_data("direct-messages", $type, $data);
4095 }
4096
4097 /**
4098  * Returns the most recent direct messages sent by the user.
4099  *
4100  * @param string $type Return type (atom, rss, xml, json)
4101  *
4102  * @return array|string
4103  * @throws BadRequestException
4104  * @throws ForbiddenException
4105  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4106  */
4107 function api_direct_messages_sentbox($type)
4108 {
4109         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4110         return api_direct_messages_box($type, "sentbox", $verbose);
4111 }
4112
4113 /**
4114  * Returns the most recent direct messages sent to the user.
4115  *
4116  * @param string $type Return type (atom, rss, xml, json)
4117  *
4118  * @return array|string
4119  * @throws BadRequestException
4120  * @throws ForbiddenException
4121  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4122  */
4123 function api_direct_messages_inbox($type)
4124 {
4125         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4126         return api_direct_messages_box($type, "inbox", $verbose);
4127 }
4128
4129 /**
4130  *
4131  * @param string $type Return type (atom, rss, xml, json)
4132  *
4133  * @return array|string
4134  * @throws BadRequestException
4135  * @throws ForbiddenException
4136  */
4137 function api_direct_messages_all($type)
4138 {
4139         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4140         return api_direct_messages_box($type, "all", $verbose);
4141 }
4142
4143 /**
4144  *
4145  * @param string $type Return type (atom, rss, xml, json)
4146  *
4147  * @return array|string
4148  * @throws BadRequestException
4149  * @throws ForbiddenException
4150  */
4151 function api_direct_messages_conversation($type)
4152 {
4153         $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4154         return api_direct_messages_box($type, "conversation", $verbose);
4155 }
4156
4157 /// @TODO move to top of file or somewhere better
4158 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4159 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4160 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4161 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4162
4163 /**
4164  * Returns an OAuth Request Token.
4165  *
4166  * @see https://oauth.net/core/1.0/#auth_step1
4167  */
4168 function api_oauth_request_token()
4169 {
4170         $oauth1 = new FKOAuth1();
4171         try {
4172                 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4173         } catch (Exception $e) {
4174                 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4175                 exit();
4176         }
4177         echo $r;
4178         exit();
4179 }
4180
4181 /**
4182  * Returns an OAuth Access Token.
4183  *
4184  * @return array|string
4185  * @see https://oauth.net/core/1.0/#auth_step3
4186  */
4187 function api_oauth_access_token()
4188 {
4189         $oauth1 = new FKOAuth1();
4190         try {
4191                 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4192         } catch (Exception $e) {
4193                 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4194                 exit();
4195         }
4196         echo $r;
4197         exit();
4198 }
4199
4200 /// @TODO move to top of file or somewhere better
4201 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4202 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4203
4204
4205 /**
4206  * @brief delete a complete photoalbum with all containing photos from database through api
4207  *
4208  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4209  * @return string|array
4210  * @throws BadRequestException
4211  * @throws ForbiddenException
4212  * @throws InternalServerErrorException
4213  */
4214 function api_fr_photoalbum_delete($type)
4215 {
4216         if (api_user() === false) {
4217                 throw new ForbiddenException();
4218         }
4219         // input params
4220         $album = $_REQUEST['album'] ?? '';
4221
4222         // we do not allow calls without album string
4223         if ($album == "") {
4224                 throw new BadRequestException("no albumname specified");
4225         }
4226         // check if album is existing
4227         $r = q(
4228                 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4229                 intval(api_user()),
4230                 DBA::escape($album)
4231         );
4232         if (!DBA::isResult($r)) {
4233                 throw new BadRequestException("album not available");
4234         }
4235
4236         // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4237         // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4238         foreach ($r as $rr) {
4239                 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4240                 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4241
4242                 if (!DBA::isResult($photo_item)) {
4243                         throw new InternalServerErrorException("problem with deleting items occured");
4244                 }
4245                 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4246         }
4247
4248         // now let's delete all photos from the album
4249         $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4250
4251         // return success of deletion or error message
4252         if ($result) {
4253                 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4254                 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4255         } else {
4256                 throw new InternalServerErrorException("unknown error - deleting from database failed");
4257         }
4258 }
4259
4260 /**
4261  * @brief update the name of the album for all photos of an album
4262  *
4263  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4264  * @return string|array
4265  * @throws BadRequestException
4266  * @throws ForbiddenException
4267  * @throws InternalServerErrorException
4268  */
4269 function api_fr_photoalbum_update($type)
4270 {
4271         if (api_user() === false) {
4272                 throw new ForbiddenException();
4273         }
4274         // input params
4275         $album = $_REQUEST['album'] ?? '';
4276         $album_new = $_REQUEST['album_new'] ?? '';
4277
4278         // we do not allow calls without album string
4279         if ($album == "") {
4280                 throw new BadRequestException("no albumname specified");
4281         }
4282         if ($album_new == "") {
4283                 throw new BadRequestException("no new albumname specified");
4284         }
4285         // check if album is existing
4286         if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4287                 throw new BadRequestException("album not available");
4288         }
4289         // now let's update all photos to the albumname
4290         $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4291
4292         // return success of updating or error message
4293         if ($result) {
4294                 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4295                 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4296         } else {
4297                 throw new InternalServerErrorException("unknown error - updating in database failed");
4298         }
4299 }
4300
4301
4302 /**
4303  * @brief list all photos of the authenticated user
4304  *
4305  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4306  * @return string|array
4307  * @throws ForbiddenException
4308  * @throws InternalServerErrorException
4309  */
4310 function api_fr_photos_list($type)
4311 {
4312         if (api_user() === false) {
4313                 throw new ForbiddenException();
4314         }
4315         $r = q(
4316                 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4317                 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4318                 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4319                 intval(local_user())
4320         );
4321         $typetoext = [
4322                 'image/jpeg' => 'jpg',
4323                 'image/png' => 'png',
4324                 'image/gif' => 'gif'
4325         ];
4326         $data = ['photo'=>[]];
4327         if (DBA::isResult($r)) {
4328                 foreach ($r as $rr) {
4329                         $photo = [];
4330                         $photo['id'] = $rr['resource-id'];
4331                         $photo['album'] = $rr['album'];
4332                         $photo['filename'] = $rr['filename'];
4333                         $photo['type'] = $rr['type'];
4334                         $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4335                         $photo['created'] = $rr['created'];
4336                         $photo['edited'] = $rr['edited'];
4337                         $photo['desc'] = $rr['desc'];
4338
4339                         if ($type == "xml") {
4340                                 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4341                         } else {
4342                                 $photo['thumb'] = $thumb;
4343                                 $data['photo'][] = $photo;
4344                         }
4345                 }
4346         }
4347         return api_format_data("photos", $type, $data);
4348 }
4349
4350 /**
4351  * @brief upload a new photo or change an existing photo
4352  *
4353  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4354  * @return string|array
4355  * @throws BadRequestException
4356  * @throws ForbiddenException
4357  * @throws ImagickException
4358  * @throws InternalServerErrorException
4359  * @throws NotFoundException
4360  */
4361 function api_fr_photo_create_update($type)
4362 {
4363         if (api_user() === false) {
4364                 throw new ForbiddenException();
4365         }
4366         // input params
4367         $photo_id  = $_REQUEST['photo_id']  ?? null;
4368         $desc      = $_REQUEST['desc']      ?? null;
4369         $album     = $_REQUEST['album']     ?? null;
4370         $album_new = $_REQUEST['album_new'] ?? null;
4371         $allow_cid = $_REQUEST['allow_cid'] ?? null;
4372         $deny_cid  = $_REQUEST['deny_cid' ] ?? null;
4373         $allow_gid = $_REQUEST['allow_gid'] ?? null;
4374         $deny_gid  = $_REQUEST['deny_gid' ] ?? null;
4375         $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4376
4377         // do several checks on input parameters
4378         // we do not allow calls without album string
4379         if ($album == null) {
4380                 throw new BadRequestException("no albumname specified");
4381         }
4382         // if photo_id == null --> we are uploading a new photo
4383         if ($photo_id == null) {
4384                 $mode = "create";
4385
4386                 // error if no media posted in create-mode
4387                 if (empty($_FILES['media'])) {
4388                         // Output error
4389                         throw new BadRequestException("no media data submitted");
4390                 }
4391
4392                 // album_new will be ignored in create-mode
4393                 $album_new = "";
4394         } else {
4395                 $mode = "update";
4396
4397                 // check if photo is existing in databasei
4398                 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4399                         throw new BadRequestException("photo not available");
4400                 }
4401         }
4402
4403         // checks on acl strings provided by clients
4404         $acl_input_error = false;
4405         $acl_input_error |= check_acl_input($allow_cid);
4406         $acl_input_error |= check_acl_input($deny_cid);
4407         $acl_input_error |= check_acl_input($allow_gid);
4408         $acl_input_error |= check_acl_input($deny_gid);
4409         if ($acl_input_error) {
4410                 throw new BadRequestException("acl data invalid");
4411         }
4412         // now let's upload the new media in create-mode
4413         if ($mode == "create") {
4414                 $media = $_FILES['media'];
4415                 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4416
4417                 // return success of updating or error message
4418                 if (!is_null($data)) {
4419                         return api_format_data("photo_create", $type, $data);
4420                 } else {
4421                         throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4422                 }
4423         }
4424
4425         // now let's do the changes in update-mode
4426         if ($mode == "update") {
4427                 $updated_fields = [];
4428
4429                 if (!is_null($desc)) {
4430                         $updated_fields['desc'] = $desc;
4431                 }
4432
4433                 if (!is_null($album_new)) {
4434                         $updated_fields['album'] = $album_new;
4435                 }
4436
4437                 if (!is_null($allow_cid)) {
4438                         $allow_cid = trim($allow_cid);
4439                         $updated_fields['allow_cid'] = $allow_cid;
4440                 }
4441
4442                 if (!is_null($deny_cid)) {
4443                         $deny_cid = trim($deny_cid);
4444                         $updated_fields['deny_cid'] = $deny_cid;
4445                 }
4446
4447                 if (!is_null($allow_gid)) {
4448                         $allow_gid = trim($allow_gid);
4449                         $updated_fields['allow_gid'] = $allow_gid;
4450                 }
4451
4452                 if (!is_null($deny_gid)) {
4453                         $deny_gid = trim($deny_gid);
4454                         $updated_fields['deny_gid'] = $deny_gid;
4455                 }
4456
4457                 $result = false;
4458                 if (count($updated_fields) > 0) {
4459                         $nothingtodo = false;
4460                         $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4461                 } else {
4462                         $nothingtodo = true;
4463                 }
4464
4465                 if (!empty($_FILES['media'])) {
4466                         $nothingtodo = false;
4467                         $media = $_FILES['media'];
4468                         $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4469                         if (!is_null($data)) {
4470                                 return api_format_data("photo_update", $type, $data);
4471                         }
4472                 }
4473
4474                 // return success of updating or error message
4475                 if ($result) {
4476                         $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4477                         return api_format_data("photo_update", $type, ['$result' => $answer]);
4478                 } else {
4479                         if ($nothingtodo) {
4480                                 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4481                                 return api_format_data("photo_update", $type, ['$result' => $answer]);
4482                         }
4483                         throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4484                 }
4485         }
4486         throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4487 }
4488
4489 /**
4490  * @brief delete a single photo from the database through api
4491  *
4492  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4493  * @return string|array
4494  * @throws BadRequestException
4495  * @throws ForbiddenException
4496  * @throws InternalServerErrorException
4497  */
4498 function api_fr_photo_delete($type)
4499 {
4500         if (api_user() === false) {
4501                 throw new ForbiddenException();
4502         }
4503
4504         // input params
4505         $photo_id = $_REQUEST['photo_id'] ?? null;
4506
4507         // do several checks on input parameters
4508         // we do not allow calls without photo id
4509         if ($photo_id == null) {
4510                 throw new BadRequestException("no photo_id specified");
4511         }
4512
4513         // check if photo is existing in database
4514         if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4515                 throw new BadRequestException("photo not available");
4516         }
4517
4518         // now we can perform on the deletion of the photo
4519         $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4520
4521         // return success of deletion or error message
4522         if ($result) {
4523                 // retrieve the id of the parent element (the photo element)
4524                 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4525                 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4526
4527                 if (!DBA::isResult($photo_item)) {
4528                         throw new InternalServerErrorException("problem with deleting items occured");
4529                 }
4530                 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4531                 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4532                 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4533
4534                 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4535                 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4536         } else {
4537                 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4538         }
4539 }
4540
4541
4542 /**
4543  * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4544  *
4545  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4546  * @return string|array
4547  * @throws BadRequestException
4548  * @throws ForbiddenException
4549  * @throws InternalServerErrorException
4550  * @throws NotFoundException
4551  */
4552 function api_fr_photo_detail($type)
4553 {
4554         if (api_user() === false) {
4555                 throw new ForbiddenException();
4556         }
4557         if (empty($_REQUEST['photo_id'])) {
4558                 throw new BadRequestException("No photo id.");
4559         }
4560
4561         $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4562         $photo_id = $_REQUEST['photo_id'];
4563
4564         // prepare json/xml output with data from database for the requested photo
4565         $data = prepare_photo_data($type, $scale, $photo_id);
4566
4567         return api_format_data("photo_detail", $type, $data);
4568 }
4569
4570
4571 /**
4572  * Updates the user’s profile image.
4573  *
4574  * @brief updates the profile image for the user (either a specified profile or the default profile)
4575  *
4576  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4577  *
4578  * @return string|array
4579  * @throws BadRequestException
4580  * @throws ForbiddenException
4581  * @throws ImagickException
4582  * @throws InternalServerErrorException
4583  * @throws NotFoundException
4584  * @see   https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4585  */
4586 function api_account_update_profile_image($type)
4587 {
4588         if (api_user() === false) {
4589                 throw new ForbiddenException();
4590         }
4591         // input params
4592         $profile_id = $_REQUEST['profile_id'] ?? 0;
4593
4594         // error if image data is missing
4595         if (empty($_FILES['image'])) {
4596                 throw new BadRequestException("no media data submitted");
4597         }
4598
4599         // check if specified profile id is valid
4600         if ($profile_id != 0) {
4601                 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4602                 // error message if specified profile id is not in database
4603                 if (!DBA::isResult($profile)) {
4604                         throw new BadRequestException("profile_id not available");
4605                 }
4606                 $is_default_profile = $profile['is-default'];
4607         } else {
4608                 $is_default_profile = 1;
4609         }
4610
4611         // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4612         $media = null;
4613         if (!empty($_FILES['image'])) {
4614                 $media = $_FILES['image'];
4615         } elseif (!empty($_FILES['media'])) {
4616                 $media = $_FILES['media'];
4617         }
4618         // save new profile image
4619         $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4620
4621         // get filetype
4622         if (is_array($media['type'])) {
4623                 $filetype = $media['type'][0];
4624         } else {
4625                 $filetype = $media['type'];
4626         }
4627         if ($filetype == "image/jpeg") {
4628                 $fileext = "jpg";
4629         } elseif ($filetype == "image/png") {
4630                 $fileext = "png";
4631         } else {
4632                 throw new InternalServerErrorException('Unsupported filetype');
4633         }
4634
4635         // change specified profile or all profiles to the new resource-id
4636         if ($is_default_profile) {
4637                 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4638                 Photo::update(['profile' => false], $condition);
4639         } else {
4640                 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4641                         'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4642                 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4643         }
4644
4645         Contact::updateSelfFromUserID(api_user(), true);
4646
4647         // Update global directory in background
4648         $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4649         if ($url && strlen(Config::get('system', 'directory'))) {
4650                 Worker::add(PRIORITY_LOW, "Directory", $url);
4651         }
4652
4653         Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4654
4655         // output for client
4656         if ($data) {
4657                 return api_account_verify_credentials($type);
4658         } else {
4659                 // SaveMediaToDatabase failed for some reason
4660                 throw new InternalServerErrorException("image upload failed");
4661         }
4662 }
4663
4664 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4665 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4666 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4667 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4668 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4669 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4670 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4671 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4672 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4673
4674 /**
4675  * Update user profile
4676  *
4677  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4678  *
4679  * @return array|string
4680  * @throws BadRequestException
4681  * @throws ForbiddenException
4682  * @throws ImagickException
4683  * @throws InternalServerErrorException
4684  * @throws UnauthorizedException
4685  */
4686 function api_account_update_profile($type)
4687 {
4688         $local_user = api_user();
4689         $api_user = api_get_user(DI::app());
4690
4691         if (!empty($_POST['name'])) {
4692                 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4693                 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4694                 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4695                 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4696         }
4697
4698         if (isset($_POST['description'])) {
4699                 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4700                 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4701                 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4702         }
4703
4704         Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4705         // Update global directory in background
4706         if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4707                 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4708         }
4709
4710         return api_account_verify_credentials($type);
4711 }
4712
4713 /// @TODO move to top of file or somewhere better
4714 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4715
4716 /**
4717  *
4718  * @param string $acl_string
4719  * @return bool
4720  * @throws Exception
4721  */
4722 function check_acl_input($acl_string)
4723 {
4724         if (empty($acl_string)) {
4725                 return false;
4726         }
4727
4728         $contact_not_found = false;
4729
4730         // split <x><y><z> into array of cid's
4731         preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4732
4733         // check for each cid if it is available on server
4734         $cid_array = $array[0];
4735         foreach ($cid_array as $cid) {
4736                 $cid = str_replace("<", "", $cid);
4737                 $cid = str_replace(">", "", $cid);
4738                 $condition = ['id' => $cid, 'uid' => api_user()];
4739                 $contact_not_found |= !DBA::exists('contact', $condition);
4740         }
4741         return $contact_not_found;
4742 }
4743
4744 /**
4745  * @param string  $mediatype
4746  * @param array   $media
4747  * @param string  $type
4748  * @param string  $album
4749  * @param string  $allow_cid
4750  * @param string  $deny_cid
4751  * @param string  $allow_gid
4752  * @param string  $deny_gid
4753  * @param string  $desc
4754  * @param integer $profile
4755  * @param boolean $visibility
4756  * @param string  $photo_id
4757  * @return array
4758  * @throws BadRequestException
4759  * @throws ForbiddenException
4760  * @throws ImagickException
4761  * @throws InternalServerErrorException
4762  * @throws NotFoundException
4763  * @throws UnauthorizedException
4764  */
4765 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $profile = 0, $visibility = false, $photo_id = null)
4766 {
4767         $visitor   = 0;
4768         $src = "";
4769         $filetype = "";
4770         $filename = "";
4771         $filesize = 0;
4772
4773         if (is_array($media)) {
4774                 if (is_array($media['tmp_name'])) {
4775                         $src = $media['tmp_name'][0];
4776                 } else {
4777                         $src = $media['tmp_name'];
4778                 }
4779                 if (is_array($media['name'])) {
4780                         $filename = basename($media['name'][0]);
4781                 } else {
4782                         $filename = basename($media['name']);
4783                 }
4784                 if (is_array($media['size'])) {
4785                         $filesize = intval($media['size'][0]);
4786                 } else {
4787                         $filesize = intval($media['size']);
4788                 }
4789                 if (is_array($media['type'])) {
4790                         $filetype = $media['type'][0];
4791                 } else {
4792                         $filetype = $media['type'];
4793                 }
4794         }
4795
4796         if ($filetype == "") {
4797                 $filetype = Images::guessType($filename);
4798         }
4799         $imagedata = @getimagesize($src);
4800         if ($imagedata) {
4801                 $filetype = $imagedata['mime'];
4802         }
4803         Logger::log(
4804                 "File upload src: " . $src . " - filename: " . $filename .
4805                 " - size: " . $filesize . " - type: " . $filetype,
4806                 Logger::DEBUG
4807         );
4808
4809         // check if there was a php upload error
4810         if ($filesize == 0 && $media['error'] == 1) {
4811                 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4812         }
4813         // check against max upload size within Friendica instance
4814         $maximagesize = Config::get('system', 'maximagesize');
4815         if ($maximagesize && ($filesize > $maximagesize)) {
4816                 $formattedBytes = Strings::formatBytes($maximagesize);
4817                 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4818         }
4819
4820         // create Photo instance with the data of the image
4821         $imagedata = @file_get_contents($src);
4822         $Image = new Image($imagedata, $filetype);
4823         if (!$Image->isValid()) {
4824                 throw new InternalServerErrorException("unable to process image data");
4825         }
4826
4827         // check orientation of image
4828         $Image->orient($src);
4829         @unlink($src);
4830
4831         // check max length of images on server
4832         $max_length = Config::get('system', 'max_image_length');
4833         if (!$max_length) {
4834                 $max_length = MAX_IMAGE_LENGTH;
4835         }
4836         if ($max_length > 0) {
4837                 $Image->scaleDown($max_length);
4838                 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4839         }
4840         $width = $Image->getWidth();
4841         $height = $Image->getHeight();
4842
4843         // create a new resource-id if not already provided
4844         $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4845
4846         if ($mediatype == "photo") {
4847                 // upload normal image (scales 0, 1, 2)
4848                 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4849
4850                 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4851                 if (!$r) {
4852                         Logger::log("photo upload: image upload with scale 0 (original size) failed");
4853                 }
4854                 if ($width > 640 || $height > 640) {
4855                         $Image->scaleDown(640);
4856                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4857                         if (!$r) {
4858                                 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4859                         }
4860                 }
4861
4862                 if ($width > 320 || $height > 320) {
4863                         $Image->scaleDown(320);
4864                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4865                         if (!$r) {
4866                                 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4867                         }
4868                 }
4869                 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4870         } elseif ($mediatype == "profileimage") {
4871                 // upload profile image (scales 4, 5, 6)
4872                 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4873
4874                 if ($width > 300 || $height > 300) {
4875                         $Image->scaleDown(300);
4876                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4877                         if (!$r) {
4878                                 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4879                         }
4880                 }
4881
4882                 if ($width > 80 || $height > 80) {
4883                         $Image->scaleDown(80);
4884                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4885                         if (!$r) {
4886                                 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4887                         }
4888                 }
4889
4890                 if ($width > 48 || $height > 48) {
4891                         $Image->scaleDown(48);
4892                         $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4893                         if (!$r) {
4894                                 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4895                         }
4896                 }
4897                 $Image->__destruct();
4898                 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4899         }
4900
4901         if (isset($r) && $r) {
4902                 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4903                 if ($photo_id == null && $mediatype == "photo") {
4904                         post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4905                 }
4906                 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4907                 return prepare_photo_data($type, false, $resource_id);
4908         } else {
4909                 throw new InternalServerErrorException("image upload failed");
4910         }
4911 }
4912
4913 /**
4914  *
4915  * @param string  $hash
4916  * @param string  $allow_cid
4917  * @param string  $deny_cid
4918  * @param string  $allow_gid
4919  * @param string  $deny_gid
4920  * @param string  $filetype
4921  * @param boolean $visibility
4922  * @throws InternalServerErrorException
4923  */
4924 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4925 {
4926         // get data about the api authenticated user
4927         $uri = Item::newURI(intval(api_user()));
4928         $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4929
4930         $arr = [];
4931         $arr['guid']          = System::createUUID();
4932         $arr['uid']           = intval(api_user());
4933         $arr['uri']           = $uri;
4934         $arr['parent-uri']    = $uri;
4935         $arr['type']          = 'photo';
4936         $arr['wall']          = 1;
4937         $arr['resource-id']   = $hash;
4938         $arr['contact-id']    = $owner_record['id'];
4939         $arr['owner-name']    = $owner_record['name'];
4940         $arr['owner-link']    = $owner_record['url'];
4941         $arr['owner-avatar']  = $owner_record['thumb'];
4942         $arr['author-name']   = $owner_record['name'];
4943         $arr['author-link']   = $owner_record['url'];
4944         $arr['author-avatar'] = $owner_record['thumb'];
4945         $arr['title']         = "";
4946         $arr['allow_cid']     = $allow_cid;
4947         $arr['allow_gid']     = $allow_gid;
4948         $arr['deny_cid']      = $deny_cid;
4949         $arr['deny_gid']      = $deny_gid;
4950         $arr['visible']       = $visibility;
4951         $arr['origin']        = 1;
4952
4953         $typetoext = [
4954                         'image/jpeg' => 'jpg',
4955                         'image/png' => 'png',
4956                         'image/gif' => 'gif'
4957                         ];
4958
4959         // adds link to the thumbnail scale photo
4960         $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4961                                 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4962                                 . '[/url]';
4963
4964         // do the magic for storing the item in the database and trigger the federation to other contacts
4965         Item::insert($arr);
4966 }
4967
4968 /**
4969  *
4970  * @param string $type
4971  * @param int    $scale
4972  * @param string $photo_id
4973  *
4974  * @return array
4975  * @throws BadRequestException
4976  * @throws ForbiddenException
4977  * @throws ImagickException
4978  * @throws InternalServerErrorException
4979  * @throws NotFoundException
4980  * @throws UnauthorizedException
4981  */
4982 function prepare_photo_data($type, $scale, $photo_id)
4983 {
4984         $a = DI::app();
4985         $user_info = api_get_user($a);
4986
4987         if ($user_info === false) {
4988                 throw new ForbiddenException();
4989         }
4990
4991         $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4992         $data_sql = ($scale === false ? "" : "data, ");
4993
4994         // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4995         // clients needs to convert this in their way for further processing
4996         $r = q(
4997                 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4998                                         `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4999                                         MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
5000                         FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY 
5001                                `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
5002                                `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
5003                 $data_sql,
5004                 intval(local_user()),
5005                 DBA::escape($photo_id),
5006                 $scale_sql
5007         );
5008
5009         $typetoext = [
5010                 'image/jpeg' => 'jpg',
5011                 'image/png' => 'png',
5012                 'image/gif' => 'gif'
5013         ];
5014
5015         // prepare output data for photo
5016         if (DBA::isResult($r)) {
5017                 $data = ['photo' => $r[0]];
5018                 $data['photo']['id'] = $data['photo']['resource-id'];
5019                 if ($scale !== false) {
5020                         $data['photo']['data'] = base64_encode($data['photo']['data']);
5021                 } else {
5022                         unset($data['photo']['datasize']); //needed only with scale param
5023                 }
5024                 if ($type == "xml") {
5025                         $data['photo']['links'] = [];
5026                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5027                                 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
5028                                                                                 "scale" => $k,
5029                                                                                 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
5030                         }
5031                 } else {
5032                         $data['photo']['link'] = [];
5033                         // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
5034                         $i = 0;
5035                         for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5036                                 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
5037                                 $i++;
5038                         }
5039                 }
5040                 unset($data['photo']['resource-id']);
5041                 unset($data['photo']['minscale']);
5042                 unset($data['photo']['maxscale']);
5043         } else {
5044                 throw new NotFoundException();
5045         }
5046
5047         // retrieve item element for getting activities (like, dislike etc.) related to photo
5048         $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
5049         $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
5050
5051         $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5052
5053         // retrieve comments on photo
5054         $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5055                 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5056
5057         $statuses = Item::selectForUser(api_user(), [], $condition);
5058
5059         // prepare output of comments
5060         $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5061         $comments = [];
5062         if ($type == "xml") {
5063                 $k = 0;
5064                 foreach ($commentData as $comment) {
5065                         $comments[$k++ . ":comment"] = $comment;
5066                 }
5067         } else {
5068                 foreach ($commentData as $comment) {
5069                         $comments[] = $comment;
5070                 }
5071         }
5072         $data['photo']['friendica_comments'] = $comments;
5073
5074         // include info if rights on photo and rights on item are mismatching
5075         $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5076                 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5077                 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5078                 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5079         $data['photo']['rights_mismatch'] = $rights_mismatch;
5080
5081         return $data;
5082 }
5083
5084
5085 /**
5086  * Similar as /mod/redir.php
5087  * redirect to 'url' after dfrn auth
5088  *
5089  * Why this when there is mod/redir.php already?
5090  * This use api_user() and api_login()
5091  *
5092  * params
5093  *              c_url: url of remote contact to auth to
5094  *              url: string, url to redirect after auth
5095  */
5096 function api_friendica_remoteauth()
5097 {
5098         $url = $_GET['url'] ?? '';
5099         $c_url = $_GET['c_url'] ?? '';
5100
5101         if ($url === '' || $c_url === '') {
5102                 throw new BadRequestException("Wrong parameters.");
5103         }
5104
5105         $c_url = Strings::normaliseLink($c_url);
5106
5107         // traditional DFRN
5108
5109         $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5110         if (!DBA::isResult($contact)) {
5111                 throw new BadRequestException("Unknown contact");
5112         }
5113
5114         $cid = $contact['id'];
5115
5116         $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5117
5118         if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5119                 System::externalRedirect($url ?: $c_url);
5120         }
5121
5122         if ($contact['duplex'] && $contact['issued-id']) {
5123                 $orig_id = $contact['issued-id'];
5124                 $dfrn_id = '1:' . $orig_id;
5125         }
5126         if ($contact['duplex'] && $contact['dfrn-id']) {
5127                 $orig_id = $contact['dfrn-id'];
5128                 $dfrn_id = '0:' . $orig_id;
5129         }
5130
5131         $sec = Strings::getRandomHex();
5132
5133         $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5134                 'sec' => $sec, 'expire' => time() + 45];
5135         DBA::insert('profile_check', $fields);
5136
5137         Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5138         $dest = ($url ? '&destination_url=' . $url : '');
5139
5140         System::externalRedirect(
5141                 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5142                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5143                 . '&type=profile&sec=' . $sec . $dest
5144         );
5145 }
5146 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5147
5148 /**
5149  * Return an item with announcer data if it had been announced
5150  *
5151  * @param array $item Item array
5152  * @return array Item array with announce data
5153  */
5154 function api_get_announce($item)
5155 {
5156         // Quit if the item already has got a different owner and author
5157         if ($item['owner-id'] != $item['author-id']) {
5158                 return [];
5159         }
5160
5161         // Don't change original or Diaspora posts
5162         if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5163                 return [];
5164         }
5165
5166         // Quit if we do now the original author and it had been a post from a native network
5167         if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5168                 return [];
5169         }
5170
5171         $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5172         $activity = Item::activityToIndex(Activity::ANNOUNCE);
5173         $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5174         $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5175         if (!DBA::isResult($announce)) {
5176                 return [];
5177         }
5178
5179         return array_merge($item, $announce);
5180 }
5181
5182 /**
5183  * @brief Return the item shared, if the item contains only the [share] tag
5184  *
5185  * @param array $item Sharer item
5186  * @return array|false Shared item or false if not a reshare
5187  * @throws ImagickException
5188  * @throws InternalServerErrorException
5189  */
5190 function api_share_as_retweet(&$item)
5191 {
5192         $body = trim($item["body"]);
5193
5194         if (Diaspora::isReshare($body, false) === false) {
5195                 if ($item['author-id'] == $item['owner-id']) {
5196                         return false;
5197                 } else {
5198                         // Reshares from OStatus, ActivityPub and Twitter
5199                         $reshared_item = $item;
5200                         $reshared_item['owner-id'] = $reshared_item['author-id'];
5201                         $reshared_item['owner-link'] = $reshared_item['author-link'];
5202                         $reshared_item['owner-name'] = $reshared_item['author-name'];
5203                         $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5204                         return $reshared_item;
5205                 }
5206         }
5207
5208         $reshared = Item::getShareArray($item);
5209         if (empty($reshared)) {
5210                 return false;
5211         }
5212
5213         $reshared_item = $item;
5214
5215         if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5216                 return false;
5217         }
5218
5219         if (!empty($reshared['comment'])) {
5220                 $item['body'] = $reshared['comment'];
5221         }
5222
5223         $reshared_item["share-pre-body"] = $reshared['comment'];
5224         $reshared_item["body"] = $reshared['shared'];
5225         $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5226         $reshared_item["author-name"] = $reshared['author'];
5227         $reshared_item["author-link"] = $reshared['profile'];
5228         $reshared_item["author-avatar"] = $reshared['avatar'];
5229         $reshared_item["plink"] = $reshared['link'] ?? '';
5230         $reshared_item["created"] = $reshared['posted'];
5231         $reshared_item["edited"] = $reshared['posted'];
5232
5233         // Try to fetch the original item
5234         if (!empty($reshared['guid'])) {
5235                 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5236         } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5237                 $condition = ['id' => $original_id];
5238         } else {
5239                 $condition = [];
5240         }
5241
5242         if (!empty($condition)) {
5243                 $original_item = Item::selectFirst([], $condition);
5244                 if (DBA::isResult($original_item)) {
5245                         $reshared_item = array_merge($reshared_item, $original_item);
5246                 }
5247         }
5248
5249         return $reshared_item;
5250 }
5251
5252 /**
5253  *
5254  * @param array $item
5255  *
5256  * @return array
5257  * @throws Exception
5258  */
5259 function api_in_reply_to($item)
5260 {
5261         $in_reply_to = [];
5262
5263         $in_reply_to['status_id'] = null;
5264         $in_reply_to['user_id'] = null;
5265         $in_reply_to['status_id_str'] = null;
5266         $in_reply_to['user_id_str'] = null;
5267         $in_reply_to['screen_name'] = null;
5268
5269         if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5270                 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5271                 if (DBA::isResult($parent)) {
5272                         $in_reply_to['status_id'] = intval($parent['id']);
5273                 } else {
5274                         $in_reply_to['status_id'] = intval($item['parent']);
5275                 }
5276
5277                 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5278
5279                 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5280                 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5281
5282                 if (DBA::isResult($parent)) {
5283                         $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5284                         $in_reply_to['user_id'] = intval($parent['author-id']);
5285                         $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5286                 }
5287
5288                 // There seems to be situation, where both fields are identical:
5289                 // https://github.com/friendica/friendica/issues/1010
5290                 // This is a bugfix for that.
5291                 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5292                         Logger::warning(API_LOG_PREFIX . 'ID {id} is similar to reply-to {reply-to}', ['module' => 'api', 'action' => 'in_reply_to', 'id' => $item['id'], 'reply-to' => $in_reply_to['status_id']]);
5293                         $in_reply_to['status_id'] = null;
5294                         $in_reply_to['user_id'] = null;
5295                         $in_reply_to['status_id_str'] = null;
5296                         $in_reply_to['user_id_str'] = null;
5297                         $in_reply_to['screen_name'] = null;
5298                 }
5299         }
5300
5301         return $in_reply_to;
5302 }
5303
5304 /**
5305  *
5306  * @param string $text
5307  *
5308  * @return string
5309  * @throws InternalServerErrorException
5310  */
5311 function api_clean_plain_items($text)
5312 {
5313         $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5314
5315         $text = BBCode::cleanPictureLinks($text);
5316         $URLSearchString = "^\[\]";
5317
5318         $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5319
5320         if ($include_entities == "true") {
5321                 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5322         }
5323
5324         // Simplify "attachment" element
5325         $text = BBCode::removeAttachment($text);
5326
5327         return $text;
5328 }
5329
5330 /**
5331  *
5332  * @param array $contacts
5333  *
5334  * @return void
5335  */
5336 function api_best_nickname(&$contacts)
5337 {
5338         $best_contact = [];
5339
5340         if (count($contacts) == 0) {
5341                 return;
5342         }
5343
5344         foreach ($contacts as $contact) {
5345                 if ($contact["network"] == "") {
5346                         $contact["network"] = "dfrn";
5347                         $best_contact = [$contact];
5348                 }
5349         }
5350
5351         if (sizeof($best_contact) == 0) {
5352                 foreach ($contacts as $contact) {
5353                         if ($contact["network"] == "dfrn") {
5354                                 $best_contact = [$contact];
5355                         }
5356                 }
5357         }
5358
5359         if (sizeof($best_contact) == 0) {
5360                 foreach ($contacts as $contact) {
5361                         if ($contact["network"] == "dspr") {
5362                                 $best_contact = [$contact];
5363                         }
5364                 }
5365         }
5366
5367         if (sizeof($best_contact) == 0) {
5368                 foreach ($contacts as $contact) {
5369                         if ($contact["network"] == "stat") {
5370                                 $best_contact = [$contact];
5371                         }
5372                 }
5373         }
5374
5375         if (sizeof($best_contact) == 0) {
5376                 foreach ($contacts as $contact) {
5377                         if ($contact["network"] == "pump") {
5378                                 $best_contact = [$contact];
5379                         }
5380                 }
5381         }
5382
5383         if (sizeof($best_contact) == 0) {
5384                 foreach ($contacts as $contact) {
5385                         if ($contact["network"] == "twit") {
5386                                 $best_contact = [$contact];
5387                         }
5388                 }
5389         }
5390
5391         if (sizeof($best_contact) == 1) {
5392                 $contacts = $best_contact;
5393         } else {
5394                 $contacts = [$contacts[0]];
5395         }
5396 }
5397
5398 /**
5399  * Return all or a specified group of the user with the containing contacts.
5400  *
5401  * @param string $type Return type (atom, rss, xml, json)
5402  *
5403  * @return array|string
5404  * @throws BadRequestException
5405  * @throws ForbiddenException
5406  * @throws ImagickException
5407  * @throws InternalServerErrorException
5408  * @throws UnauthorizedException
5409  */
5410 function api_friendica_group_show($type)
5411 {
5412         $a = DI::app();
5413
5414         if (api_user() === false) {
5415                 throw new ForbiddenException();
5416         }
5417
5418         // params
5419         $user_info = api_get_user($a);
5420         $gid = $_REQUEST['gid'] ?? 0;
5421         $uid = $user_info['uid'];
5422
5423         // get data of the specified group id or all groups if not specified
5424         if ($gid != 0) {
5425                 $r = q(
5426                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5427                         intval($uid),
5428                         intval($gid)
5429                 );
5430                 // error message if specified gid is not in database
5431                 if (!DBA::isResult($r)) {
5432                         throw new BadRequestException("gid not available");
5433                 }
5434         } else {
5435                 $r = q(
5436                         "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5437                         intval($uid)
5438                 );
5439         }
5440
5441         // loop through all groups and retrieve all members for adding data in the user array
5442         $grps = [];
5443         foreach ($r as $rr) {
5444                 $members = Contact::getByGroupId($rr['id']);
5445                 $users = [];
5446
5447                 if ($type == "xml") {
5448                         $user_element = "users";
5449                         $k = 0;
5450                         foreach ($members as $member) {
5451                                 $user = api_get_user($a, $member['nurl']);
5452                                 $users[$k++.":user"] = $user;
5453                         }
5454                 } else {
5455                         $user_element = "user";
5456                         foreach ($members as $member) {
5457                                 $user = api_get_user($a, $member['nurl']);
5458                                 $users[] = $user;
5459                         }
5460                 }
5461                 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5462         }
5463         return api_format_data("groups", $type, ['group' => $grps]);
5464 }
5465 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5466
5467
5468 /**
5469  * Delete the specified group of the user.
5470  *
5471  * @param string $type Return type (atom, rss, xml, json)
5472  *
5473  * @return array|string
5474  * @throws BadRequestException
5475  * @throws ForbiddenException
5476  * @throws ImagickException
5477  * @throws InternalServerErrorException
5478  * @throws UnauthorizedException
5479  */
5480 function api_friendica_group_delete($type)
5481 {
5482         $a = DI::app();
5483
5484         if (api_user() === false) {
5485                 throw new ForbiddenException();
5486         }
5487
5488         // params
5489         $user_info = api_get_user($a);
5490         $gid = $_REQUEST['gid'] ?? 0;
5491         $name = $_REQUEST['name'] ?? '';
5492         $uid = $user_info['uid'];
5493
5494         // error if no gid specified
5495         if ($gid == 0 || $name == "") {
5496                 throw new BadRequestException('gid or name not specified');
5497         }
5498
5499         // get data of the specified group id
5500         $r = q(
5501                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5502                 intval($uid),
5503                 intval($gid)
5504         );
5505         // error message if specified gid is not in database
5506         if (!DBA::isResult($r)) {
5507                 throw new BadRequestException('gid not available');
5508         }
5509
5510         // get data of the specified group id and group name
5511         $rname = q(
5512                 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5513                 intval($uid),
5514                 intval($gid),
5515                 DBA::escape($name)
5516         );
5517         // error message if specified gid is not in database
5518         if (!DBA::isResult($rname)) {
5519                 throw new BadRequestException('wrong group name');
5520         }
5521
5522         // delete group
5523         $ret = Group::removeByName($uid, $name);
5524         if ($ret) {
5525                 // return success
5526                 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5527                 return api_format_data("group_delete", $type, ['result' => $success]);
5528         } else {
5529                 throw new BadRequestException('other API error');
5530         }
5531 }
5532 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5533
5534 /**
5535  * Delete a group.
5536  *
5537  * @param string $type Return type (atom, rss, xml, json)
5538  *
5539  * @return array|string
5540  * @throws BadRequestException
5541  * @throws ForbiddenException
5542  * @throws ImagickException
5543  * @throws InternalServerErrorException
5544  * @throws UnauthorizedException
5545  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5546  */
5547 function api_lists_destroy($type)
5548 {
5549         $a = DI::app();
5550
5551         if (api_user() === false) {
5552                 throw new ForbiddenException();
5553         }
5554
5555         // params
5556         $user_info = api_get_user($a);
5557         $gid = $_REQUEST['list_id'] ?? 0;
5558         $uid = $user_info['uid'];
5559
5560         // error if no gid specified
5561         if ($gid == 0) {
5562                 throw new BadRequestException('gid not specified');
5563         }
5564
5565         // get data of the specified group id
5566         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5567         // error message if specified gid is not in database
5568         if (!$group) {
5569                 throw new BadRequestException('gid not available');
5570         }
5571
5572         if (Group::remove($gid)) {
5573                 $list = [
5574                         'name' => $group['name'],
5575                         'id' => intval($gid),
5576                         'id_str' => (string) $gid,
5577                         'user' => $user_info
5578                 ];
5579
5580                 return api_format_data("lists", $type, ['lists' => $list]);
5581         }
5582 }
5583 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5584
5585 /**
5586  * Add a new group to the database.
5587  *
5588  * @param  string $name  Group name
5589  * @param  int    $uid   User ID
5590  * @param  array  $users List of users to add to the group
5591  *
5592  * @return array
5593  * @throws BadRequestException
5594  */
5595 function group_create($name, $uid, $users = [])
5596 {
5597         // error if no name specified
5598         if ($name == "") {
5599                 throw new BadRequestException('group name not specified');
5600         }
5601
5602         // get data of the specified group name
5603         $rname = q(
5604                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5605                 intval($uid),
5606                 DBA::escape($name)
5607         );
5608         // error message if specified group name already exists
5609         if (DBA::isResult($rname)) {
5610                 throw new BadRequestException('group name already exists');
5611         }
5612
5613         // check if specified group name is a deleted group
5614         $rname = q(
5615                 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5616                 intval($uid),
5617                 DBA::escape($name)
5618         );
5619         // error message if specified group name already exists
5620         if (DBA::isResult($rname)) {
5621                 $reactivate_group = true;
5622         }
5623
5624         // create group
5625         $ret = Group::create($uid, $name);
5626         if ($ret) {
5627                 $gid = Group::getIdByName($uid, $name);
5628         } else {
5629                 throw new BadRequestException('other API error');
5630         }
5631
5632         // add members
5633         $erroraddinguser = false;
5634         $errorusers = [];
5635         foreach ($users as $user) {
5636                 $cid = $user['cid'];
5637                 // check if user really exists as contact
5638                 $contact = q(
5639                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5640                         intval($cid),
5641                         intval($uid)
5642                 );
5643                 if (count($contact)) {
5644                         Group::addMember($gid, $cid);
5645                 } else {
5646                         $erroraddinguser = true;
5647                         $errorusers[] = $cid;
5648                 }
5649         }
5650
5651         // return success message incl. missing users in array
5652         $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5653
5654         return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5655 }
5656
5657 /**
5658  * Create the specified group with the posted array of contacts.
5659  *
5660  * @param string $type Return type (atom, rss, xml, json)
5661  *
5662  * @return array|string
5663  * @throws BadRequestException
5664  * @throws ForbiddenException
5665  * @throws ImagickException
5666  * @throws InternalServerErrorException
5667  * @throws UnauthorizedException
5668  */
5669 function api_friendica_group_create($type)
5670 {
5671         $a = DI::app();
5672
5673         if (api_user() === false) {
5674                 throw new ForbiddenException();
5675         }
5676
5677         // params
5678         $user_info = api_get_user($a);
5679         $name = $_REQUEST['name'] ?? '';
5680         $uid = $user_info['uid'];
5681         $json = json_decode($_POST['json'], true);
5682         $users = $json['user'];
5683
5684         $success = group_create($name, $uid, $users);
5685
5686         return api_format_data("group_create", $type, ['result' => $success]);
5687 }
5688 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5689
5690 /**
5691  * Create a new group.
5692  *
5693  * @param string $type Return type (atom, rss, xml, json)
5694  *
5695  * @return array|string
5696  * @throws BadRequestException
5697  * @throws ForbiddenException
5698  * @throws ImagickException
5699  * @throws InternalServerErrorException
5700  * @throws UnauthorizedException
5701  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5702  */
5703 function api_lists_create($type)
5704 {
5705         $a = DI::app();
5706
5707         if (api_user() === false) {
5708                 throw new ForbiddenException();
5709         }
5710
5711         // params
5712         $user_info = api_get_user($a);
5713         $name = $_REQUEST['name'] ?? '';
5714         $uid = $user_info['uid'];
5715
5716         $success = group_create($name, $uid);
5717         if ($success['success']) {
5718                 $grp = [
5719                         'name' => $success['name'],
5720                         'id' => intval($success['gid']),
5721                         'id_str' => (string) $success['gid'],
5722                         'user' => $user_info
5723                 ];
5724
5725                 return api_format_data("lists", $type, ['lists'=>$grp]);
5726         }
5727 }
5728 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5729
5730 /**
5731  * Update the specified group with the posted array of contacts.
5732  *
5733  * @param string $type Return type (atom, rss, xml, json)
5734  *
5735  * @return array|string
5736  * @throws BadRequestException
5737  * @throws ForbiddenException
5738  * @throws ImagickException
5739  * @throws InternalServerErrorException
5740  * @throws UnauthorizedException
5741  */
5742 function api_friendica_group_update($type)
5743 {
5744         $a = DI::app();
5745
5746         if (api_user() === false) {
5747                 throw new ForbiddenException();
5748         }
5749
5750         // params
5751         $user_info = api_get_user($a);
5752         $uid = $user_info['uid'];
5753         $gid = $_REQUEST['gid'] ?? 0;
5754         $name = $_REQUEST['name'] ?? '';
5755         $json = json_decode($_POST['json'], true);
5756         $users = $json['user'];
5757
5758         // error if no name specified
5759         if ($name == "") {
5760                 throw new BadRequestException('group name not specified');
5761         }
5762
5763         // error if no gid specified
5764         if ($gid == "") {
5765                 throw new BadRequestException('gid not specified');
5766         }
5767
5768         // remove members
5769         $members = Contact::getByGroupId($gid);
5770         foreach ($members as $member) {
5771                 $cid = $member['id'];
5772                 foreach ($users as $user) {
5773                         $found = ($user['cid'] == $cid ? true : false);
5774                 }
5775                 if (!isset($found) || !$found) {
5776                         Group::removeMemberByName($uid, $name, $cid);
5777                 }
5778         }
5779
5780         // add members
5781         $erroraddinguser = false;
5782         $errorusers = [];
5783         foreach ($users as $user) {
5784                 $cid = $user['cid'];
5785                 // check if user really exists as contact
5786                 $contact = q(
5787                         "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5788                         intval($cid),
5789                         intval($uid)
5790                 );
5791
5792                 if (count($contact)) {
5793                         Group::addMember($gid, $cid);
5794                 } else {
5795                         $erroraddinguser = true;
5796                         $errorusers[] = $cid;
5797                 }
5798         }
5799
5800         // return success message incl. missing users in array
5801         $status = ($erroraddinguser ? "missing user" : "ok");
5802         $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5803         return api_format_data("group_update", $type, ['result' => $success]);
5804 }
5805
5806 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5807
5808 /**
5809  * Update information about a group.
5810  *
5811  * @param string $type Return type (atom, rss, xml, json)
5812  *
5813  * @return array|string
5814  * @throws BadRequestException
5815  * @throws ForbiddenException
5816  * @throws ImagickException
5817  * @throws InternalServerErrorException
5818  * @throws UnauthorizedException
5819  * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5820  */
5821 function api_lists_update($type)
5822 {
5823         $a = DI::app();
5824
5825         if (api_user() === false) {
5826                 throw new ForbiddenException();
5827         }
5828
5829         // params
5830         $user_info = api_get_user($a);
5831         $gid = $_REQUEST['list_id'] ?? 0;
5832         $name = $_REQUEST['name'] ?? '';
5833         $uid = $user_info['uid'];
5834
5835         // error if no gid specified
5836         if ($gid == 0) {
5837                 throw new BadRequestException('gid not specified');
5838         }
5839
5840         // get data of the specified group id
5841         $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5842         // error message if specified gid is not in database
5843         if (!$group) {
5844                 throw new BadRequestException('gid not available');
5845         }
5846
5847         if (Group::update($gid, $name)) {
5848                 $list = [
5849                         'name' => $name,
5850                         'id' => intval($gid),
5851                         'id_str' => (string) $gid,
5852                         'user' => $user_info
5853                 ];
5854
5855                 return api_format_data("lists", $type, ['lists' => $list]);
5856         }
5857 }
5858
5859 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5860
5861 /**
5862  *
5863  * @param string $type Return type (atom, rss, xml, json)
5864  *
5865  * @return array|string
5866  * @throws BadRequestException
5867  * @throws ForbiddenException
5868  * @throws ImagickException
5869  * @throws InternalServerErrorException
5870  */
5871 function api_friendica_activity($type)
5872 {
5873         $a = DI::app();
5874
5875         if (api_user() === false) {
5876                 throw new ForbiddenException();
5877         }
5878         $verb = strtolower($a->argv[3]);
5879         $verb = preg_replace("|\..*$|", "", $verb);
5880
5881         $id = $_REQUEST['id'] ?? 0;
5882
5883         $res = Item::performLike($id, $verb);
5884
5885         if ($res) {
5886                 if ($type == "xml") {
5887                         $ok = "true";
5888                 } else {
5889                         $ok = "ok";
5890                 }
5891                 return api_format_data('ok', $type, ['ok' => $ok]);
5892         } else {
5893                 throw new BadRequestException('Error adding activity');
5894         }
5895 }
5896
5897 /// @TODO move to top of file or somewhere better
5898 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5899 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5900 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5901 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5902 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5903 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5904 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5905 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5906 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5907 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5908
5909 /**
5910  * @brief Returns notifications
5911  *
5912  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5913  * @return string|array
5914  * @throws BadRequestException
5915  * @throws ForbiddenException
5916  * @throws InternalServerErrorException
5917  */
5918 function api_friendica_notification($type)
5919 {
5920         $a = DI::app();
5921
5922         if (api_user() === false) {
5923                 throw new ForbiddenException();
5924         }
5925         if ($a->argc!==3) {
5926                 throw new BadRequestException("Invalid argument count");
5927         }
5928         $notes = DI::notify()->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
5929
5930         if ($type == "xml") {
5931                 $xmlnotes = [];
5932                 if (!empty($notes)) {
5933                         foreach ($notes as $note) {
5934                                 $xmlnotes[] = ["@attributes" => $note];
5935                         }
5936                 }
5937
5938                 $notes = $xmlnotes;
5939         }
5940         return api_format_data("notes", $type, ['note' => $notes]);
5941 }
5942
5943 /**
5944  * POST request with 'id' param as notification id
5945  *
5946  * @brief Set notification as seen and returns associated item (if possible)
5947  *
5948  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5949  * @return string|array
5950  * @throws BadRequestException
5951  * @throws ForbiddenException
5952  * @throws ImagickException
5953  * @throws InternalServerErrorException
5954  * @throws UnauthorizedException
5955  */
5956 function api_friendica_notification_seen($type)
5957 {
5958         $a = DI::app();
5959         $user_info = api_get_user($a);
5960
5961         if (api_user() === false || $user_info === false) {
5962                 throw new ForbiddenException();
5963         }
5964         if ($a->argc!==4) {
5965                 throw new BadRequestException("Invalid argument count");
5966         }
5967
5968         $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5969
5970         $nm = DI::notify();
5971         $note = $nm->getByID($id);
5972         if (is_null($note)) {
5973                 throw new BadRequestException("Invalid argument");
5974         }
5975
5976         $nm->setSeen($note);
5977         if ($note['otype']=='item') {
5978                 // would be really better with an ItemsManager and $im->getByID() :-P
5979                 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5980                 if (DBA::isResult($item)) {
5981                         // we found the item, return it to the user
5982                         $ret = api_format_items([$item], $user_info, false, $type);
5983                         $data = ['status' => $ret];
5984                         return api_format_data("status", $type, $data);
5985                 }
5986                 // the item can't be found, but we set the note as seen, so we count this as a success
5987         }
5988         return api_format_data('result', $type, ['result' => "success"]);
5989 }
5990
5991 /// @TODO move to top of file or somewhere better
5992 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5993 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5994
5995 /**
5996  * @brief update a direct_message to seen state
5997  *
5998  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5999  * @return string|array (success result=ok, error result=error with error message)
6000  * @throws BadRequestException
6001  * @throws ForbiddenException
6002  * @throws ImagickException
6003  * @throws InternalServerErrorException
6004  * @throws UnauthorizedException
6005  */
6006 function api_friendica_direct_messages_setseen($type)
6007 {
6008         $a = DI::app();
6009         if (api_user() === false) {
6010                 throw new ForbiddenException();
6011         }
6012
6013         // params
6014         $user_info = api_get_user($a);
6015         $uid = $user_info['uid'];
6016         $id = $_REQUEST['id'] ?? 0;
6017
6018         // return error if id is zero
6019         if ($id == "") {
6020                 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6021                 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6022         }
6023
6024         // error message if specified id is not in database
6025         if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6026                 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6027                 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6028         }
6029
6030         // update seen indicator
6031         $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6032
6033         if ($result) {
6034                 // return success
6035                 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6036                 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6037         } else {
6038                 $answer = ['result' => 'error', 'message' => 'unknown error'];
6039                 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6040         }
6041 }
6042
6043 /// @TODO move to top of file or somewhere better
6044 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6045
6046 /**
6047  * @brief search for direct_messages containing a searchstring through api
6048  *
6049  * @param string $type      Known types are 'atom', 'rss', 'xml' and 'json'
6050  * @param string $box
6051  * @return string|array (success: success=true if found and search_result contains found messages,
6052  *                          success=false if nothing was found, search_result='nothing found',
6053  *                          error: result=error with error message)
6054  * @throws BadRequestException
6055  * @throws ForbiddenException
6056  * @throws ImagickException
6057  * @throws InternalServerErrorException
6058  * @throws UnauthorizedException
6059  */
6060 function api_friendica_direct_messages_search($type, $box = "")
6061 {
6062         $a = DI::app();
6063
6064         if (api_user() === false) {
6065                 throw new ForbiddenException();
6066         }
6067
6068         // params
6069         $user_info = api_get_user($a);
6070         $searchstring = $_REQUEST['searchstring'] ?? '';
6071         $uid = $user_info['uid'];
6072
6073         // error if no searchstring specified
6074         if ($searchstring == "") {
6075                 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6076                 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6077         }
6078
6079         // get data for the specified searchstring
6080         $r = q(
6081                 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND `body` LIKE '%s' ORDER BY `mail`.`id` DESC",
6082                 intval($uid),
6083                 DBA::escape('%'.$searchstring.'%')
6084         );
6085
6086         $profile_url = $user_info["url"];
6087
6088         // message if nothing was found
6089         if (!DBA::isResult($r)) {
6090                 $success = ['success' => false, 'search_results' => 'problem with query'];
6091         } elseif (count($r) == 0) {
6092                 $success = ['success' => false, 'search_results' => 'nothing found'];
6093         } else {
6094                 $ret = [];
6095                 foreach ($r as $item) {
6096                         if ($box == "inbox" || $item['from-url'] != $profile_url) {
6097                                 $recipient = $user_info;
6098                                 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6099                         } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6100                                 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6101                                 $sender = $user_info;
6102                         }
6103
6104                         if (isset($recipient) && isset($sender)) {
6105                                 $ret[] = api_format_messages($item, $recipient, $sender);
6106                         }
6107                 }
6108                 $success = ['success' => true, 'search_results' => $ret];
6109         }
6110
6111         return api_format_data("direct_message_search", $type, ['$result' => $success]);
6112 }
6113
6114 /// @TODO move to top of file or somewhere better
6115 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6116
6117 /**
6118  * @brief return data of all the profiles a user has to the client
6119  *
6120  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6121  * @return string|array
6122  * @throws BadRequestException
6123  * @throws ForbiddenException
6124  * @throws ImagickException
6125  * @throws InternalServerErrorException
6126  * @throws UnauthorizedException
6127  */
6128 function api_friendica_profile_show($type)
6129 {
6130         $a = DI::app();
6131
6132         if (api_user() === false) {
6133                 throw new ForbiddenException();
6134         }
6135
6136         // input params
6137         $profile_id = $_REQUEST['profile_id'] ?? 0;
6138
6139         // retrieve general information about profiles for user
6140         $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6141         $directory = Config::get('system', 'directory');
6142
6143         // get data of the specified profile id or all profiles of the user if not specified
6144         if ($profile_id != 0) {
6145                 $r = Profile::getById(api_user(), $profile_id);
6146                 // error message if specified gid is not in database
6147                 if (!DBA::isResult($r)) {
6148                         throw new BadRequestException("profile_id not available");
6149                 }
6150         } else {
6151                 $r = Profile::getListByUser(api_user());
6152         }
6153         // loop through all returned profiles and retrieve data and users
6154         $k = 0;
6155         $profiles = [];
6156         if (DBA::isResult($r)) {
6157                 foreach ($r as $rr) {
6158                         $profile = api_format_items_profiles($rr);
6159
6160                         // select all users from contact table, loop and prepare standard return for user data
6161                         $users = [];
6162                         $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6163                         foreach ($nurls as $nurl) {
6164                                 $user = api_get_user($a, $nurl['nurl']);
6165                                 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6166                         }
6167                         $profile['users'] = $users;
6168
6169                         // add prepared profile data to array for final return
6170                         if ($type == "xml") {
6171                                 $profiles[$k++ . ":profile"] = $profile;
6172                         } else {
6173                                 $profiles[] = $profile;
6174                         }
6175                 }
6176         }
6177
6178         // return settings, authenticated user and profiles data
6179         $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6180
6181         $result = ['multi_profiles' => $multi_profiles ? true : false,
6182                                         'global_dir' => $directory,
6183                                         'friendica_owner' => api_get_user($a, $self['nurl']),
6184                                         'profiles' => $profiles];
6185         return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6186 }
6187 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6188
6189 /**
6190  * Returns a list of saved searches.
6191  *
6192  * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6193  *
6194  * @param  string $type Return format: json or xml
6195  *
6196  * @return string|array
6197  * @throws Exception
6198  */
6199 function api_saved_searches_list($type)
6200 {
6201         $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6202
6203         $result = [];
6204         while ($term = DBA::fetch($terms)) {
6205                 $result[] = [
6206                         'created_at' => api_date(time()),
6207                         'id' => intval($term['id']),
6208                         'id_str' => $term['id'],
6209                         'name' => $term['term'],
6210                         'position' => null,
6211                         'query' => $term['term']
6212                 ];
6213         }
6214
6215         DBA::close($terms);
6216
6217         return api_format_data("terms", $type, ['terms' => $result]);
6218 }
6219
6220 /// @TODO move to top of file or somewhere better
6221 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6222
6223 /*
6224  * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6225  *
6226  * @brief Number of comments
6227  *
6228  * @param object $data [Status, Status]
6229  *
6230  * @return void
6231  */
6232 function bindComments(&$data) 
6233 {
6234         if (count($data) == 0) {
6235                 return;
6236         }
6237         
6238         $ids = [];
6239         $comments = [];
6240         foreach ($data as $item) {
6241                 $ids[] = $item['id'];
6242         }
6243
6244         $idStr = DBA::escape(implode(', ', $ids));
6245         $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6246         $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6247         $itemsData = DBA::toArray($items);
6248
6249         foreach ($itemsData as $item) {
6250                 $comments[$item['parent']] = $item['comments'];
6251         }
6252
6253         foreach ($data as $idx => $item) {
6254                 $id = $item['id'];
6255                 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6256         }
6257 }
6258
6259 /*
6260 @TODO Maybe open to implement?
6261 To.Do:
6262         [pagename] => api/1.1/statuses/lookup.json
6263         [id] => 605138389168451584
6264         [include_cards] => true
6265         [cards_platform] => Android-12
6266         [include_entities] => true
6267         [include_my_retweet] => 1
6268         [include_rts] => 1
6269         [include_reply_count] => true
6270         [include_descendent_reply_count] => true
6271 (?)
6272
6273
6274 Not implemented by now:
6275 statuses/retweets_of_me
6276 friendships/create
6277 friendships/destroy
6278 friendships/exists
6279 friendships/show
6280 account/update_location
6281 account/update_profile_background_image
6282 blocks/create
6283 blocks/destroy
6284 friendica/profile/update
6285 friendica/profile/create
6286 friendica/profile/delete
6287
6288 Not implemented in status.net:
6289 statuses/retweeted_to_me
6290 statuses/retweeted_by_me
6291 direct_messages/destroy
6292 account/end_session
6293 account/update_delivery_device
6294 notifications/follow
6295 notifications/leave
6296 blocks/exists
6297 blocks/blocking
6298 lists
6299 */