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