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