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