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