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