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