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